答:
Just use an additional decedent selector only changing the background property:

```<code>.leftpart .nav-links .nav-links ul li a {
  background: red;
 }
</code>```

.leftpart {
  width: 100%;
  display: block;
  margin: 20px;
}

.leftpart .nav-links ul {
  list-style: none;
  margin: 0;
  padding: 0;
  display: block;
}

.leftpart .nav-links ul li {
  margin-bottom: 20px;
}

.leftpart .nav-links ul li a {
  background: green;
  color: #fff;
  padding: 20px;
  display: inline-block;
}

.leftpart .nav-links .nav-links ul li a {
  background: red;
 }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="leftpart">
  <div class="nav-links">
    <h1> Primary Links </h1>
    <ul>
      <li>
        Profile
      </li>

      <li>
        Friends
      </li>

      <li>
        Milestones
      </li>

      <li>
        Groups
      </li>
    </ul>

    <div class="sub-seciton">
      <div class="nav-links">
        <ul>
          <li>
            Edit
          </li>

          <li>
            Save
          </li>
        </ul>
      </div>
    </div>

  </div>

  <div class="nav-links">
    <h1> Secondary Links </h1>
    <ul>
      <li>
        Privacy
      </li>

      <li>
        Settings
      </li>
    </ul>
  </div>
</div></code>```

Title: Same class on parent and child element for navigation ".nav-links" - Looking for best CSS solution

Body:
Just use an additional decedent selector only changing the background property:

.leftpart .nav-links .nav-links ul li a {
  background: red;
 }

.leftpart {
  width: 100%;
  display: block;
  margin: 20px;
}

.leftpart .nav-links ul {
  list-style: none;
  margin: 0;
  padding: 0;
  display: block;
}

.leftpart .nav-links ul li {
  margin-bottom: 20px;
}

.leftpart .nav-links ul li a {
  background: green;
  color: #fff;
  padding: 20px;
  display: inline-block;
}

.leftpart .nav-links .nav-links ul li a {
  background: red;
 }

<div class="leftpart">
  <div class="nav-links">
    <h1> Primary Links </h1>
    <ul>
      <li>
        <a href="/profile.html">Profile</a>
      </li>

      <li>
        <a href="/friends.html">Friends</a>
      </li>

      <li>
        <a href="/milestone.html">Milestones</a>
      </li>

      <li>
        <a href="/groups.html">Groups</a>
      </li>
    </ul>

    <div class="sub-seciton">
      <div class="nav-links">
        <ul>
          <li>
            <a href="#">Edit</a>
          </li>

          <li>
            <a href="#">Save</a>
          </li>
        </ul>
      </div>
    </div>

  </div>

  <div class="nav-links">
    <h1> Secondary Links </h1>
    <ul>
      <li>
        <a href="/privacy.html">Privacy</a>
      </li>

      <li>
        <a href="/settings.html">Settings</a>
      </li>
    </ul>
  </div>
</div>


来源: stackexchange

问:
Compare two files(file1 & file2) and add one column from from file2 to file1 if first column of two files matches
I have two files (file1 and file2)

file1

```<code>ABC=14.2.0.7.SAMPLE=git.xyz/plugins/gitiles/+/refs/heads/clientpatch/abc/patch142007
DEF=14.3.0.5.SAMPLE=git.xyz/plugins/gitiles/+/refs/heads/clientpatch/def/patch143005
DEF=14.3.0.5.SAMPLE2=git.calypso/plugins/gitiles/+/refs/heads/clientpatch/def/patch14300-calib
HIJ=12.0.0.0.Sp3.SAMPLE3=git.xyz/plugins/gitiles/+/refs/heads/clientpatch/hij/patch120000sp3
MNO=16.1.0.28.SAMPLE=git.xyz/plugins/gitiles/+/refs/heads/clientpatch/mno/patch161028
</code>```

.......(150 lines)

file2

```<code>IJK = open
ABC = closed
PQR = closed
DEF = open
HIJ = open
LMN = closed
MNO = closed
PQR = open
</code>```

......(> 150 lines)

output file

```<code>ABC=14.2.0.7.SAMPLE=git.xyz/plugins/gitiles/+/refs/heads/client/abc/patch142007=closed
DEF=14.3.0.5.SAMPLE=git.xyz/plugins/gitiles/+/refs/heads/client/def/patch143005=open
DEF=14.3.0.5.SAMPLE2=git.xyz/plugins/gitiles/+/refs/heads/client/def/patch14300-calib=open
HIJ=12.0.0.0.Sp3.SAMPLE3=git.xyz/plugins/gitiles/+/refs/heads/client/hij/patch120000sp3=open
MNO=16.1.0.28.SAMPLE=git.xyz/plugins/gitiles/+/refs/heads/client/mno/patch161028=closed
</code>```

I have tried the following script. But it is not giving me any output. Not even printing anything. No errors

```<code>while IFS= read -r line
do
key1=`echo $line | awk -F "=" '{print $1}'` < file1
key2=`echo $line | awk -F "=" '{print $2}'` < file1
key3=`echo $line | awk -F "=" '{print $3}'` < file1
key4=`echo $line | awk -F "=" '{print $1}'` < file2
value3=`echo $line | awk -F "=" '{print $2}'` < file2
if [ "$key1" == "$key4" ]; then
echo "$key1=$key2=$key3=$value3"
fi
done
</code>```

Giving a brief description for how the code should work.

The code should compare first columns of two files(file1 and file2). If each name matches it should give me output file as listed above. Else go to the next line. I should get output if my two files are either in sorted or unsorted format.
Helps will be appreciated. Thank you

答:
Or another approach with awk that stores the file2 values in an array and then appends the correct state to the appropriate line in file1:

```<code>awk -F' = ' 'NR==FNR {a[$1]=$2; next} {print $0"="a[$1]}' file2 FS="=" file1
</code>```

Example Use/Output

```<code>$ awk -F' = ' 'NR==FNR {a[$1]=$2; next} {print $0"="a[$1]}' file2 FS="=" file1
ABC=14.2.0.7.SAMPLE=git.xyz/plugins/gitiles/+/refs/heads/clientpatch/abc/patch142007=closed
DEF=14.3.0.5.SAMPLE=git.xyz/plugins/gitiles/+/refs/heads/clientpatch/def/patch143005=open
DEF=14.3.0.5.SAMPLE2=git.calypso/plugins/gitiles/+/refs/heads/clientpatch/def/patch14300-calib=open
HIJ=12.0.0.0.Sp3.SAMPLE3=git.xyz/plugins/gitiles/+/refs/heads/clientpatch/hij/patch120000sp3=open
MNO=16.1.0.28.SAMPLE=git.xyz/plugins/gitiles/+/refs/heads/clientpatch/mno/patch161028=closed
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have two files (file1 and file2)

file1

ABC=14.2.0.7.SAMPLE=git.xyz/plugins/gitiles/+/refs/heads/clientpatch/abc/patch142007
DEF=14.3.0.5.SAMPLE=git.xyz/plugins/gitiles/+/refs/heads/clientpatch/def/patch143005
DEF=14.3.0.5.SAMPLE2=git.calypso/plugins/gitiles/+/refs/heads/clientpatch/def/patch14300-calib
HIJ=12.0.0.0.Sp3.SAMPLE3=git.xyz/plugins/gitiles/+/refs/heads/clientpatch/hij/patch120000sp3
MNO=16.1.0.28.SAMPLE=git.xyz/plugins/gitiles/+/refs/heads/clientpatch/mno/patch161028

.......(150 lines)

file2

IJK = open
ABC = closed
PQR = closed
DEF = open
HIJ = open
LMN = closed
MNO = closed
PQR = open

......(> 150 lines)

output file

ABC=14.2.0.7.SAMPLE=git.xyz/plugins/gitiles/+/refs/heads/client/abc/patch142007=closed
DEF=14.3.0.5.SAMPLE=git.xyz/plugins/gitiles/+/refs/heads/client/def/patch143005=open
DEF=14.3.0.5.SAMPLE2=git.xyz/plugins/gitiles/+/refs/heads/client/def/patch14300-calib=open
HIJ=12.0.0.0.Sp3.SAMPLE3=git.xyz/plugins/gitiles/+/refs/heads/client/hij/patch120000sp3=open
MNO=16.1.0.28.SAMPLE=git.xyz/plugins/gitiles/+/refs/heads/client/mno/patch161028=closed

I have tried the following script. But it is not giving me any output. Not even printing anything. No errors

while IFS= read -r line
do
key1=`echo $line | awk -F "=" '{print $1}'` < file1
key2=`echo $line | awk -F "=" '{print $2}'` < file1
key3=`echo $line | awk -F "=" '{print $3}'` < file1
key4=`echo $line | awk -F "=" '{print $1}'` < file2
value3=`echo $line | awk -F "=" '{print $2}'` < file2
if [ "$key1" == "$key4" ]; then
echo "$key1=$key2=$key3=$value3"
fi
done

Giving a brief description for how the code should work.

The code should compare first columns of two files(file1 and file2). If each name matches it should give me output file as listed above. Else go to the next line. I should get output if my two files are either in sorted or unsorted format.
Helps will be appreciated. Thank you

Body:
Or another approach with awk that stores the file2 values in an array and then appends the correct state to the appropriate line in file1:

awk -F' = ' 'NR==FNR {a[$1]=$2; next} {print $0"="a[$1]}' file2 FS="=" file1

Example Use/Output

$ awk -F' = ' 'NR==FNR {a[$1]=$2; next} {print $0"="a[$1]}' file2 FS="=" file1
ABC=14.2.0.7.SAMPLE=git.xyz/plugins/gitiles/+/refs/heads/clientpatch/abc/patch142007=closed
DEF=14.3.0.5.SAMPLE=git.xyz/plugins/gitiles/+/refs/heads/clientpatch/def/patch143005=open
DEF=14.3.0.5.SAMPLE2=git.calypso/plugins/gitiles/+/refs/heads/clientpatch/def/patch14300-calib=open
HIJ=12.0.0.0.Sp3.SAMPLE3=git.xyz/plugins/gitiles/+/refs/heads/clientpatch/hij/patch120000sp3=open
MNO=16.1.0.28.SAMPLE=git.xyz/plugins/gitiles/+/refs/heads/clientpatch/mno/patch161028=closed


问:
Error creating bean with name 'dataSource' [org/springframework/boot/autoconfigure/jdbc/DataSourceConfiguration$Hikari.class]
i'm getting the following error when i try to debug a Spring boot with Gradle project in Eclipse

```<code>Error creating bean with name 'org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaConfiguration':
Unsatisfied dependency expressed through constructor parameter 0; nested exception
is org.springframework.beans.factory.BeanCreationException:
Error creating bean with name 'dataSource' defined in class path resource
[org/springframework/boot/autoconfigure/jdbc/DataSourceConfiguration$Hikari.class]

Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [com.zaxxer.hikari.HikariDataSource]: Factory method 'dataSource' threw exception; nested exception is java.lang.IllegalStateException: Cannot load driver class: com.mysql.jdbc.Driver

</code>```

i've searched a lot, and most of the solutions came from something that is wrong in the application.properties file, but i can not figure what is wrong in mine

```<code>server.port=8080
spring.datasource.driverClassName=com.mysql.jdbc.Driver
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL5InnoDBDialect
spring.jpa.show-sql=true
spring.jpa.hibernate.ddl-auto=update
spring.datasource.url=jdbc:mysql://localhost:3306/dices?useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC
spring.datasource.username=root
spring.datasource.password=root
</code>```

Any suggestion?

thanks

答: Can you try adding compile("mysql:mysql-connector-java") to your build.gradle and check again?

Body:
i'm getting the following error when i try to debug a Spring boot with Gradle project in Eclipse

Error creating bean with name 'org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaConfiguration':
Unsatisfied dependency expressed through constructor parameter 0; nested exception
is org.springframework.beans.factory.BeanCreationException:
Error creating bean with name 'dataSource' defined in class path resource
[org/springframework/boot/autoconfigure/jdbc/DataSourceConfiguration$Hikari.class]

Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [com.zaxxer.hikari.HikariDataSource]: Factory method 'dataSource' threw exception; nested exception is java.lang.IllegalStateException: Cannot load driver class: com.mysql.jdbc.Driver

i've searched a lot, and most of the solutions came from something that is wrong in the application.properties file, but i can not figure what is wrong in mine

server.port=8080
spring.datasource.driverClassName=com.mysql.jdbc.Driver
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL5InnoDBDialect
spring.jpa.show-sql=true
spring.jpa.hibernate.ddl-auto=update
spring.datasource.url=jdbc:mysql://localhost:3306/dices?useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC
spring.datasource.username=root
spring.datasource.password=root

Any suggestion?

thanks


问:
C# File/Directory Permissions for local share
I need a file to be editable by all local users. The application saves common information to all users in its own folder under ProgramData. I need to guarantee reading and writing to all users, it is so little information that it does not merit the use of a database.

I get the path to the folder from:Path.Combine(Application.CommonAppDataPath, "InfoConfig");

All users can read, write and create in this folder. Except the files that are created by the other users.

I already tried to remove Creator Owner without success. So my last attempt was not to inherit from the container folder and create the permissions from scratch for SYSTEM, Administrators and Users. But it didn't work either, here is my code.

```<code>            string sharedFolder = Path.Combine(Application.CommonAppDataPath, "InfoConfig");
        if (!Directory.Exists(sharedFolder))
        {
            DirectoryInfo directoryInfo = Directory.CreateDirectory(sharedFolder);
            DirectorySecurity directorySecurity = directoryInfo.GetAccessControl();
            directorySecurity.SetAccessRuleProtection(true, false);
            FileSystemRights fileSystemRights =
                      FileSystemRights.FullControl |
                      FileSystemRights.Modify |
                      FileSystemRights.Read |
                      FileSystemRights.Delete;
            SecurityIdentifier usersSid =
                      new SecurityIdentifier(WellKnownSidType.BuiltinUsersSid, null);
            SecurityIdentifier systemSid =
                      new SecurityIdentifier(WellKnownSidType.LocalSystemSid, null);
            SecurityIdentifier adminsSid =
                      new SecurityIdentifier(WellKnownSidType.BuiltinAdministratorsSid, null);

            FileSystemAccessRule rule =
                      new FileSystemAccessRule(systemSid, fileSystemRights, AccessControlType.Allow);

            directorySecurity.AddAccessRule(rule);

            rule = new FileSystemAccessRule(adminsSid, fileSystemRights, AccessControlType.Allow);
            directorySecurity.AddAccessRule(rule);

            rule = new FileSystemAccessRule(usersSid, FileSystemRights.Read
                     | FileSystemRights.Write
                     | FileSystemRights.Modify,
                     AccessControlType.Allow);
            directorySecurity.AddAccessRule(rule);

            directoryInfo.SetAccessControl(directorySecurity);
        }
</code>```

It still doesn't work. What am I doing wrong?

答:
I have only considered the below snippet for usersSid, you can tweak it for the other userTypes as well

Have added ObjectSecurity.ModifyAccessRule(AccessControlModification, AccessRule, Boolean) which applies the specified modification to the Discretionary Access Control List (DACL) associated with this ObjectSecurity object (directorySecurity in our instance).

```<code>
string sharedFolder = Path.Combine(Application.CommonAppDataPath, "InfoConfig");

 if (!Directory.Exists(sharedFolder))
 {
    DirectoryInfo directoryInfo = Directory.CreateDirectory(sharedFolder);
    DirectorySecurity directorySecurity = directoryInfo.GetAccessControl();

    directorySecurity.SetAccessRuleProtection(true, false);

    FileSystemRights fileSystemRights =
            FileSystemRights.FullControl |
            FileSystemRights.Modify |
            FileSystemRights.Read |
            FileSystemRights.Delete;

    SecurityIdentifier usersSid =
            new SecurityIdentifier(WellKnownSidType.BuiltinUsersSid, null);

    FileSystemAccessRule rule =  new FileSystemAccessRule(usersSid, fileSystemRights,InheritanceFlags.None, PropagationFlags.NoPropagateInherit, AccessControlType.Allow);
    directorySecurity.AddAccessRule(rule);

    bool result;
    directorySecurity.ModifyAccessRule(AccessControlModification.Set, rule, out result);

    if (!result)
        {
            throw new InvalidOperationException("Failed to give full-control permission to all users for path " + path);
        }

    FileSystemAccessRule inheritedRule = new FileSystemAccessRule(
    usersSid,
    fileSystemRights,
    InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit,
    PropagationFlags.InheritOnly,
    AccessControlType.Allow);

    bool inheritedResult;
    directorySecurity.ModifyAccessRule(AccessControlModification.Add, inheritedRule, out inheritedResult);

    if (!inheritedResult)
    {
        throw new InvalidOperationException("Failed to give full-control permission inheritance to all users for " + path);
    }

    directoryInfo.SetAccessControl(directorySecurity);
}

</code>```

Body:
I need a file to be editable by all local users. The application saves common information to all users in its own folder under ProgramData. I need to guarantee reading and writing to all users, it is so little information that it does not merit the use of a database.

I get the path to the folder from:Path.Combine(Application.CommonAppDataPath, "InfoConfig");

All users can read, write and create in this folder. Except the files that are created by the other users.

I already tried to remove Creator Owner without success. So my last attempt was not to inherit from the container folder and create the permissions from scratch for SYSTEM, Administrators and Users. But it didn't work either, here is my code.

            string sharedFolder = Path.Combine(Application.CommonAppDataPath, "InfoConfig");
        if (!Directory.Exists(sharedFolder))
        {
            DirectoryInfo directoryInfo = Directory.CreateDirectory(sharedFolder);
            DirectorySecurity directorySecurity = directoryInfo.GetAccessControl();
            directorySecurity.SetAccessRuleProtection(true, false);
            FileSystemRights fileSystemRights =
                      FileSystemRights.FullControl |
                      FileSystemRights.Modify |
                      FileSystemRights.Read |
                      FileSystemRights.Delete;
            SecurityIdentifier usersSid =
                      new SecurityIdentifier(WellKnownSidType.BuiltinUsersSid, null);
            SecurityIdentifier systemSid =
                      new SecurityIdentifier(WellKnownSidType.LocalSystemSid, null);
            SecurityIdentifier adminsSid =
                      new SecurityIdentifier(WellKnownSidType.BuiltinAdministratorsSid, null);

            FileSystemAccessRule rule =
                      new FileSystemAccessRule(systemSid, fileSystemRights, AccessControlType.Allow);

            directorySecurity.AddAccessRule(rule);

            rule = new FileSystemAccessRule(adminsSid, fileSystemRights, AccessControlType.Allow);
            directorySecurity.AddAccessRule(rule);

            rule = new FileSystemAccessRule(usersSid, FileSystemRights.Read
                     | FileSystemRights.Write
                     | FileSystemRights.Modify,
                     AccessControlType.Allow);
            directorySecurity.AddAccessRule(rule);

            directoryInfo.SetAccessControl(directorySecurity);
        }

It still doesn't work. What am I doing wrong?

Body:
I have only considered the below snippet for usersSid, you can tweak it for the other userTypes as well

Have added ObjectSecurity.ModifyAccessRule(AccessControlModification, AccessRule, Boolean) which applies the specified modification to the Discretionary Access Control List (DACL) associated with this ObjectSecurity object (directorySecurity in our instance).

string sharedFolder = Path.Combine(Application.CommonAppDataPath, "InfoConfig");

 if (!Directory.Exists(sharedFolder))
 {
    DirectoryInfo directoryInfo = Directory.CreateDirectory(sharedFolder);
    DirectorySecurity directorySecurity = directoryInfo.GetAccessControl();

    directorySecurity.SetAccessRuleProtection(true, false);

    FileSystemRights fileSystemRights =
            FileSystemRights.FullControl |
            FileSystemRights.Modify |
            FileSystemRights.Read |
            FileSystemRights.Delete;

    SecurityIdentifier usersSid =
            new SecurityIdentifier(WellKnownSidType.BuiltinUsersSid, null);

    FileSystemAccessRule rule =  new FileSystemAccessRule(usersSid, fileSystemRights,InheritanceFlags.None, PropagationFlags.NoPropagateInherit, AccessControlType.Allow);
    directorySecurity.AddAccessRule(rule);

    bool result;
    directorySecurity.ModifyAccessRule(AccessControlModification.Set, rule, out result);

    if (!result)
        {
            throw new InvalidOperationException("Failed to give full-control permission to all users for path " + path);
        }

    FileSystemAccessRule inheritedRule = new FileSystemAccessRule(
    usersSid,
    fileSystemRights,
    InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit,
    PropagationFlags.InheritOnly,
    AccessControlType.Allow);

    bool inheritedResult;
    directorySecurity.ModifyAccessRule(AccessControlModification.Add, inheritedRule, out inheritedResult);

    if (!inheritedResult)
    {
        throw new InvalidOperationException("Failed to give full-control permission inheritance to all users for " + path);
    }

    directoryInfo.SetAccessControl(directorySecurity);
}


问:
Functions / App Services memory in shared environments secure from probing documentation - Cross Tenant Hacking
Query from client re Cross Tenant Hacking.  Can’t seem to find the exact verbiage to address their concerns re consumption plan.  Probably be something re functions and app service managed runtimes and not being able to “poke” out into other areas memory.  Anyone got anything?

I’m also going to talk to them about ASE for functions, premium plans, and such.

“We've been asked how you protect access to memory in Azure PaaS, specifically Functions. I assume that if I run a function, the memory for that function is not available for someone else's function (so they can't snoop).  Can you supply documentation on this?”

Thanks...

答:
All Azure Web Apps (as well as Mobile App/Services, WebJobs and Functions) run in a secure environment called Azure Web App Sandbox. This is the case of Windows Plans.

In case of Linux Plans, apps run inside of a (docker) container as mentioned in this comment which inherently provides isolation.


问:
Populating a WP7 List from a webservice causes 'Invalid cross-thread access.'
Sorry if this is a easy question but I am totally new to WP7.
I have a rest service that I am trying to consume however I get an error 'Invalid cross-thread access.'

This is my code

```<code>   public ObservableCollection<TransactionViewModel> Transactions { get;private set; }
   public MainViewModel()
    {
        this.Transactions = new ObservableCollection<TransactionViewModel>();
    }
    public void LoadTransactions(string id)
    {
        var req = (HttpWebRequest)WebRequest.Create(string.Format("http://domain.com/Transactions?Id={0}", id));
            req.Method = "POST";
            req.ContentType = "application/json; charset=utf-8";

           // call async
            req.BeginGetResponse(new AsyncCallback(jsonGetRequestStreamCallback), req);

        this.IsDataLoaded = true;

    }

    void jsonGetRequestStreamCallback(IAsyncResult asynchronousResult)
    {

        WebResponse response = ((HttpWebRequest)asynchronousResult.AsyncState).EndGetResponse(asynchronousResult);
        using (StreamReader reader = new StreamReader(response.GetResponseStream()))
        {
            string responseString = reader.ReadToEnd();
            reader.Close();

            var s = JsonConvert.DeserializeObject<List<TransactionViewModel>>(responseString);

            foreach (var t in s)
            {
                Transactions.Add(new TransactionViewModel()
                                     {
                                      .........
                                     }
            }
</code>```

Have I done something really stupid here?

答:
When you come back from the request you are no longer on the UI thread. So you need to switch control back to the UI thread before performing any actions that will affect the UI.

You are updating an ObservableCollection, which will be bound on the UI and therefore the update is going to affect the UI.

There are a number of approaches, the simplest for you purposes will be

```<code>Deployment.Current.Dispatcher.BeginInvoke(()=> {
 foreach (var t in s) {
  Transactions.Add(new TransactionViewModel());
 }
});
```

Edit: Also if you want to read a little more about this, I have a blog post about it here http://csainty.blogspot.com/2010/10/windows-phone-7asynchronous-programming.html it starts from code like yours that looks reasonable and should work, explains a few of the gotchas and how to get it working.

ContentLicense: CC BY-SA 3.0

Body:
Sorry if this is a easy question but I am totally new to WP7.
I have a rest service that I am trying to consume however I get an error 'Invalid cross-thread access.'

This is my code

   public ObservableCollection<TransactionViewModel> Transactions { get;private set; }
   public MainViewModel()
    {
        this.Transactions = new ObservableCollection<TransactionViewModel>();
    }
    public void LoadTransactions(string id)
    {
        var req = (HttpWebRequest)WebRequest.Create(string.Format("http://domain.com/Transactions?Id={0}", id));
            req.Method = "POST";
            req.ContentType = "application/json; charset=utf-8";

           // call async
            req.BeginGetResponse(new AsyncCallback(jsonGetRequestStreamCallback), req);

        this.IsDataLoaded = true;

    }

    void jsonGetRequestStreamCallback(IAsyncResult asynchronousResult)
    {

        WebResponse response = ((HttpWebRequest)asynchronousResult.AsyncState).EndGetResponse(asynchronousResult);
        using (StreamReader reader = new StreamReader(response.GetResponseStream()))
        {
            string responseString = reader.ReadToEnd();
            reader.Close();

            var s = JsonConvert.DeserializeObject<List<TransactionViewModel>>(responseString);

            foreach (var t in s)
            {
                Transactions.Add(new TransactionViewModel()
                                     {
                                      .........
                                     }
            }

Have I done something really stupid here?

Body:
When you come back from the request you are no longer on the UI thread. So you need to switch control back to the UI thread before performing any actions that will affect the UI.

You are updating an ObservableCollection, which will be bound on the UI and therefore the update is going to affect the UI.

There are a number of approaches, the simplest for you purposes will be

Deployment.Current.Dispatcher.BeginInvoke(()=> {
 foreach (var t in s) {
  Transactions.Add(new TransactionViewModel());
 }
});

Edit: Also if you want to read a little more about this, I have a blog post about it here http://csainty.blogspot.com/2010/10/windows-phone-7asynchronous-programming.html it starts from code like yours that looks reasonable and should work, explains a few of the gotchas and how to get it working.


问:
is there any dependency manager for Racket?
Like npm for node, we use package.json to solve dependencies.

I tried raco pkg, it seems to be just a way to dev/pub packages instead of solving external dependencies.

答:
As I described above, info.rkt in Racket acts like package.json in JavaScript, and raco pkg install will read the dependencies specified in info.rkt and recursively install these dependencies.

For instance, here's the Pollen project's info.rkt. You can see that it specifies txexpr which is another package as a dependency. Therefore, when you raco pkg install pollen, it will ask you if you want to install txexpr too. You can also invoke raco pkg install --auto pollen which will install dependencies automatically without asking any question.

Note that these packages are registered with https://pkg.racket-lang.org/ which is an equivalent of https://www.npmjs.com/ in JS.

You can read the documentation of info.rkt regarding package dependencies here.


问:
swagger-ui-express Multiple Routes for Different API Documentation
I have 2 separate swagger API documentations which I want to run via swagger-ui-express NPM package, and my express server is starting fine on port 5000, but when I am trying to access any of the URL always getting the 404 error, Here is my app.js file and URL's for your reference:

Route 1: http://localhost:5000/edi
Route 2: http://localhost:5000/ecom

```<code>const express    = require('express');
const router     = require('express').Router();
const swaggerUi  = require('swagger-ui-express');

const ediSwaggerDocument  = require('./edi-openapi.json');
const ecomSwaggerDocument = require('./ecom-openapi.json');

const SWAGGER_APP_PORT = process.env.SWAGGER_APP_PORT || 5000;

const app = express();

// Route Middleware to be called before serving Any Route
router.use('/', swaggerUi.serve);

// Route - EDI RESTful API Documentaion
router.get('/edi', swaggerUi.setup(ediSwaggerDocument));

// Route - eCommerce RESTful API Documentaion
router.get('/ecom', swaggerUi.setup(ecomSwaggerDocument));

app.listen(SWAGGER_APP_PORT, () => console.log(`RESTful API Up and Running on Port ${SWAGGER_APP_PORT}`));
</code>```

答:
Try the following configurations to hook swaggerUi with express-app

app.use("/edi", swaggerUi.serve, (...args) => swaggerUi.setup(ediSwaggerDocument)(...args));
app.use("/ecom", swaggerUi.serve, (...args) => swaggerUi.setup(ecomSwaggerDocument)(...args));

```

Body:
I have 2 separate swagger API documentations which I want to run via swagger-ui-express NPM package, and my express server is starting fine on port 5000, but when I am trying to access any of the URL always getting the 404 error, Here is my app.js file and URL's for your reference:

Route 1: http://localhost:5000/edi
Route 2: http://localhost:5000/ecom

const express    = require('express');
const router     = require('express').Router();
const swaggerUi  = require('swagger-ui-express');

const ediSwaggerDocument  = require('./edi-openapi.json');
const ecomSwaggerDocument = require('./ecom-openapi.json');

const SWAGGER_APP_PORT = process.env.SWAGGER_APP_PORT || 5000;

const app = express();

// Route Middleware to be called before serving Any Route
router.use('/', swaggerUi.serve);

// Route - EDI RESTful API Documentaion
router.get('/edi', swaggerUi.setup(ediSwaggerDocument));

// Route - eCommerce RESTful API Documentaion
router.get('/ecom', swaggerUi.setup(ecomSwaggerDocument));

app.listen(SWAGGER_APP_PORT, () => console.log(`RESTful API Up and Running on Port ${SWAGGER_APP_PORT}`));


问:
Why is BytesPerFrame in buffer unexpectedly huge when tapping mic in AVAudioEngine
I'm trying to get the buffer data from the microphone.

I was trying to access the BytesPerFrame from the buffer value inside the tap block. I tried running the same code on xcode with swift and it gives a normal value. It only gets weird when I ran it in C# with Xamarin.iOS.

I even tried initializing the format with AudioStreamBasicDescription with a specific BytesPerFrame = 2 but the problem is the same.

Here's what it looks like in C#:

```<code>    var engine = new AVAudioEngine();

    var format = new AVAudioFormat(
        format: AVAudioCommonFormat.PCMInt16,
        sampleRate: 44100,
        channels: 1,
        interleaved: false);

    engine.InputNode.InstallTapOnBus(
        bus: 0,
        bufferSize: 4096,
        format,
        tapBlock: (buffer, when) =>
            {
                Console.WriteLine(buffer.FrameCapacity);
                Console.WriteLine(buffer.Format.StreamDescription.BytesPerFrame);

                // other processing
            });

    engine.StartAndReturnError(out var err);
</code>```

This is the swift version:

    let format = AVAudioFormat(commonFormat: AVAudioCommonFormat.pcmFormatInt16, sampleRate: Double(44100), channels: 1, interleaved: false)
    engine.inputNode.installTap(onBus: 0, bufferSize: 4096, format: format) { (buffer, time) -> Void in
        let bytesPerFrame = buffer.format.streamDescription.pointee.mBytesPerFrame;
        let frameCapacity = buffer.frameCapacity;
    }

    status = .Recording
    try! engine.start()
```

In C#, I expected the BytesPerFrame value to be just 2 but what I get is something weirdly huge like 1871587600

This doesn't happen in swift.

答:
To me it looks like a bug in Xamarin.iOS.
I created an issue on their GitHub there: https://github.com/xamarin/xamarin-macios/issues/7890.

For future readers that may arrive here in the future, it is likely that the important question is the following one:

I'm trying to get the buffer data from the microphone.

This is actually possible even though the description data is garbage.

```<code>private void OnBusTap(AVAudioPcmBuffer buffer, AVAudioTime when)
{
    AudioBuffer audioBuffer = buffer.AudioBufferList[0];
    byte[] data = new byte[audioBuffer.DataByteSize];
    Marshal.Copy(audioBuffer.Data, data, 0, audioBuffer.DataByteSize);
    // do something with data. However, note that you are not on the main thread.
}
</code>```

In my case OnBusTap is called 10 times per seconds and DataByteSize is 8820, which perfectly matches the sampleRate of 44100.

Body:
I'm trying to get the buffer data from the microphone.

I was trying to access the BytesPerFrame from the buffer value inside the tap block. I tried running the same code on xcode with swift and it gives a normal value. It only gets weird when I ran it in C# with Xamarin.iOS.

I even tried initializing the format with AudioStreamBasicDescription with a specific BytesPerFrame = 2 but the problem is the same.

Here's what it looks like in C#:

    var engine = new AVAudioEngine();

    var format = new AVAudioFormat(
        format: AVAudioCommonFormat.PCMInt16,
        sampleRate: 44100,
        channels: 1,
        interleaved: false);

    engine.InputNode.InstallTapOnBus(
        bus: 0,
        bufferSize: 4096,
        format,
        tapBlock: (buffer, when) =>
            {
                Console.WriteLine(buffer.FrameCapacity);
                Console.WriteLine(buffer.Format.StreamDescription.BytesPerFrame);

                // other processing
            });

    engine.StartAndReturnError(out var err);

This is the swift version:

    let format = AVAudioFormat(commonFormat: AVAudioCommonFormat.pcmFormatInt16, sampleRate: Double(44100), channels: 1, interleaved: false)
    engine.inputNode.installTap(onBus: 0, bufferSize: 4096, format: format) { (buffer, time) -> Void in
        let bytesPerFrame = buffer.format.streamDescription.pointee.mBytesPerFrame;
        let frameCapacity = buffer.frameCapacity;
    }

    status = .Recording
    try! engine.start()

In C#, I expected the BytesPerFrame value to be just 2 but what I get is something weirdly huge like 1871587600

This doesn't happen in swift.

Body:
To me it looks like a bug in Xamarin.iOS.
I created an issue on their GitHub there: https://github.com/xamarin/xamarin-macios/issues/7890.

For future readers that may arrive here in the future, it is likely that the important question is the following one:

I'm trying to get the buffer data from the microphone.

This is actually possible even though the description data is garbage.

private void OnBusTap(AVAudioPcmBuffer buffer, AVAudioTime when)
{
    AudioBuffer audioBuffer = buffer.AudioBufferList[0];
    byte[] data = new byte[audioBuffer.DataByteSize];
    Marshal.Copy(audioBuffer.Data, data, 0, audioBuffer.DataByteSize);
    // do something with data. However, note that you are not on the main thread.
}

In my case OnBusTap is called 10 times per seconds and DataByteSize is 8820, which perfectly matches the sampleRate of 44100.


问:
How to parse function in Object at JSON in node js
Hi I'm trying to parse data, i used JSON.parse(), data.items.reqHandler is a function, but JSON.parse recognize reqHandler to string. In this case, how can i get data change to js not to use JSON.parse(JSON.parse(....)) ?</p>

```<code>data.json = {
    items: [
        {
            ID: "11",
            reqHandler: function requestHandler(ex) {
                return {
                ...
                };
            };
            },
            ...
        }
    ],
    count: 0,
    action: "batchprocess",
    headers: {
    ...
    },
    stage: "dev"
};
</code>```

答:
If your function is defined somewhere, You can try

```<code>let fn = window['requestHandler'];
if(typeof fn === 'function') {
    fn(ex);
}
</code>```

In this particular case, function requestHandler is defined. const fn = window["requestHandler"] would obtain a reference to function requestHandler (ex) {}. Once we have a reference to a function inside a variable, we can call this function by "calling the variable", i.e. fn(ex), which equals requestHandler(ex), which is what the OP wants.

Body:
Hi I'm trying to parse data, i used JSON.parse(), data.items.reqHandler is a function, but JSON.parse recognize reqHandler to string. In this case, how can i get data change to js not to use JSON.parse(JSON.parse(....)) ?

data.json = {
    items: [
        {
            ID: "11",
            reqHandler: function requestHandler(ex) {
                return {
                ...
                };
            };
            },
            ...
        }
    ],
    count: 0,
    action: "batchprocess",
    headers: {
    ...
    },
    stage: "dev"
};

Body:
If your function is defined somewhere, You can try

let fn = window['requestHandler'];
if(typeof fn === 'function') {
    fn(ex);
}

In this particular case, function requestHandler is defined. const fn = window["requestHandler"] would obtain a reference to function requestHandler (ex) {}. Once we have a reference to a function inside a variable, we can call this function by "calling the variable", i.e. fn(ex), which equals requestHandler(ex), which is what the OP wants.


问:
Why state variable inside redux Reducer not not increment by 1
I have a simple two button on the web page one for increment and one for decrements an integer.

Once i click on + button it will add 1 to the current value.

Below is my Reducer and i have wrapped "INCREMENT" with a setTimeout and when i click on + button i'am expecting to see 1 on the page after 2 secs, but it gives me 77 as soon as click happens without waiting for 2 secs, Why this happens, why 77 every time?

p.s. I might need a middleware to handle this async action, but i m trying to understand whats going on

Thank you

```<code>const mathReducer = (state = 0, action) => {
  switch (action.type) {
    case 'INCREMENT':
      return setTimeout(() => {
        state = state + 1
      }, 2000)
    case 'DECREMENT':
      return state - 1
    default:
      return state
  }
}

export default mathReducer
</code>```

答:
Because a reducer function works by deterministically returning the new value of the state, given the old state, and whatever action.

In your code you are just reassigning the state variable, with this line:

```<code>    state = state + 1
</code>```

If what you want to do is update the state after 1 second, what I would do is use the setTimeout to defer triggering the 'update state' action.

Body:
I have a simple two button on the web page one for increment and one for decrements an integer.

Once i click on + button it will add 1 to the current value.

Below is my Reducer and i have wrapped "INCREMENT" with a setTimeout and when i click on + button i'am expecting to see 1 on the page after 2 secs, but it gives me 77 as soon as click happens without waiting for 2 secs, Why this happens, why 77 every time?

p.s. I might need a middleware to handle this async action, but i m trying to understand whats going on

Thank you

const mathReducer = (state = 0, action) => {
  switch (action.type) {
    case 'INCREMENT':
      return setTimeout(() => {
        state = state + 1
      }, 2000)
    case 'DECREMENT':
      return state - 1
    default:
      return state
  }
}

export default mathReducer

Body:
Because a reducer function works by deterministically returning the new value of the state, given the old state, and whatever action.

In your code you are just reassigning the state variable, with this line:

    state = state + 1

If what you want to do is update the state after 1 second, what I would do is use the setTimeout to defer triggering the 'update state' action.


问:
Can't insert values to my table inside anonymous block..but it is working if i run the query without begin end
```<code>INSERT INTO  mtl_strmnth_grid_tmp
( guid,
  rigmove_mnth_no,
  rigmove_month,
  AVERAGE,
  actual
)
SELECT
    '1234',
    A.rigmove_mnth_no,
    A.rigmove_month,
    B.AVG as "AVERAGE",
    b.actual AS "ACTUAL"
FROM
    (
        SELECT DISTINCT
            to_char(quarter_date,'MM') AS rigmove_mnth_no,
            to_char(quarter_date,'MONTH') AS rigmove_month
        FROM
            t_adm_calendar
        WHERE
            quarter_date BETWEEN TO_DATE('01/01/2018','DD/MM/YYYY') AND TO_DATE('31/01/2018','DD/MM/YYYY')
    ) A
    LEFT OUTER JOIN (
        SELECT
            rigmove_mnth_no,
            rigmove_month,
            SUM(AVG) AS AVG,
            actual
        FROM
            (SELECT
                    EXTRACT(MONTH FROM sm1.rigmove_date) rigmove_mnth_no,
                    to_char(sm1.rigmove_date,'MONTH') rigmove_month,
                    SUM(DISTINCT sm2.AVG) AS AVG,
                    sm1.main_activity_code_pk,
                    SUM(sm1.actual) AS actual
                FROM
                    v_report_smdelivery sm1
                    LEFT JOIN v_report_smdelivery_budget sm2 ON sm1.main_activity_code_pk = sm2.main_activity_code_pk
                WHERE
                    sm1.rigmove_date BETWEEN TO_DATE('01/01/2018','DD/MM/YYYY') AND TO_DATE('31/01/2018','DD/MM/YYYY')
                GROUP BY
                    EXTRACT(MONTH FROM sm1.rigmove_date),
                    to_char(sm1.rigmove_date,'MONTH'),
                    sm1.main_activity_code_pk
                ORDER BY
                    EXTRACT(MONTH FROM sm1.rigmove_date),
                    to_char(sm1.rigmove_date,'MONTH')
            )
        GROUP BY
            rigmove_mnth_no,
            rigmove_month,
            actual

        ORDER BY
            rigmove_mnth_no,
            rigmove_month
    ) b ON A.rigmove_mnth_no = b.rigmove_mnth_no
ORDER BY rigmove_mnth_no
;
</code>```

If i use this query inside begin end/..it is showing error
ORA-00979: not a GROUP BY expression
ORA-06512: at line 3
00979. 00000 -  "not a GROUP BY expression"
*Cause:

*Action:

But if I run this query outside plsql block it is working...help me to solve this....

答:
Actually I removed the extract in group by clause and it is working fine...

But another system it is working fine even though extract in group by clause...

Body:
INSERT INTO  mtl_strmnth_grid_tmp
( guid,
  rigmove_mnth_no,
  rigmove_month,
  AVERAGE,
  actual
)
SELECT
    '1234',
    A.rigmove_mnth_no,
    A.rigmove_month,
    B.AVG as "AVERAGE",
    b.actual AS "ACTUAL"
FROM
    (
        SELECT DISTINCT
            to_char(quarter_date,'MM') AS rigmove_mnth_no,
            to_char(quarter_date,'MONTH') AS rigmove_month
        FROM
            t_adm_calendar
        WHERE
            quarter_date BETWEEN TO_DATE('01/01/2018','DD/MM/YYYY') AND TO_DATE('31/01/2018','DD/MM/YYYY')
    ) A
    LEFT OUTER JOIN (
        SELECT
            rigmove_mnth_no,
            rigmove_month,
            SUM(AVG) AS AVG,
            actual
        FROM
            (SELECT
                    EXTRACT(MONTH FROM sm1.rigmove_date) rigmove_mnth_no,
                    to_char(sm1.rigmove_date,'MONTH') rigmove_month,
                    SUM(DISTINCT sm2.AVG) AS AVG,
                    sm1.main_activity_code_pk,
                    SUM(sm1.actual) AS actual
                FROM
                    v_report_smdelivery sm1
                    LEFT JOIN v_report_smdelivery_budget sm2 ON sm1.main_activity_code_pk = sm2.main_activity_code_pk
                WHERE
                    sm1.rigmove_date BETWEEN TO_DATE('01/01/2018','DD/MM/YYYY') AND TO_DATE('31/01/2018','DD/MM/YYYY')
                GROUP BY
                    EXTRACT(MONTH FROM sm1.rigmove_date),
                    to_char(sm1.rigmove_date,'MONTH'),
                    sm1.main_activity_code_pk
                ORDER BY
                    EXTRACT(MONTH FROM sm1.rigmove_date),
                    to_char(sm1.rigmove_date,'MONTH')
            )
        GROUP BY
            rigmove_mnth_no,
            rigmove_month,
            actual

        ORDER BY
            rigmove_mnth_no,
            rigmove_month
    ) b ON A.rigmove_mnth_no = b.rigmove_mnth_no
ORDER BY rigmove_mnth_no
;

If i use this query inside begin end/..it is showing error
ORA-00979: not a GROUP BY expression
ORA-06512: at line 3
00979. 00000 -  "not a GROUP BY expression"
*Cause:

*Action:

But if I run this query outside plsql block it is working...help me to solve this....


问:
How to pass params with history.push/Link/Redirect in react-router v4?
How can we pass parameter with this.props.history.push('/page') in React-Router v4?

```<code>.then(response => {
       var r = this;
        if (response.status >= 200 && response.status < 300) {
             r.props.history.push('/template');
          });
</code>```

答:
Extending the solution (suggested by Shubham Khatri) for use with React hooks (16.8 onwards):

```<code>package.json (always worth updating to latest packages)

{
     ...

     "react": "^16.12.0",
     "react-router-dom": "^5.1.2",

     ...
}

</code>```

Passing parameters with history push:

```<code>import { useHistory } from "react-router-dom";

const FirstPage = props => {
    let history = useHistory();

    const someEventHandler = event => {
       history.push({
           pathname: '/secondpage',
           search: '?query=abc',
           state: { detail: 'some_value' }
       });
    };

};

export default FirstPage;

</code>```

Accessing the passed parameter using useLocation from 'react-router-dom':

```<code>import { useEffect } from "react";
import { useLocation } from "react-router-dom";

const SecondPage = props => {
    const location = useLocation();

    useEffect(() => {
       console.log(location.pathname); // result: '/secondpage'
       console.log(location.search); // result: '?query=abc'
       console.log(location.state.detail); // result: 'some_value'
    }, [location]);

};

</code>```

Body:
How can we pass parameter with this.props.history.push('/page') in React-Router v4?

.then(response => {
       var r = this;
        if (response.status >= 200 && response.status < 300) {
             r.props.history.push('/template');
          });

Body:
Extending the solution (suggested by Shubham Khatri) for use with React hooks (16.8 onwards):

package.json (always worth updating to latest packages)

{
     ...

     "react": "^16.12.0",
     "react-router-dom": "^5.1.2",

     ...
}

Passing parameters with history push:

import { useHistory } from "react-router-dom";

const FirstPage = props => {
    let history = useHistory();

    const someEventHandler = event => {
       history.push({
           pathname: '/secondpage',
           search: '?query=abc',
           state: { detail: 'some_value' }
       });
    };

};

export default FirstPage;

Accessing the passed parameter using useLocation from 'react-router-dom':

import { useEffect } from "react";
import { useLocation } from "react-router-dom";

const SecondPage = props => {
    const location = useLocation();

    useEffect(() => {
       console.log(location.pathname); // result: '/secondpage'
       console.log(location.search); // result: '?query=abc'
       console.log(location.state.detail); // result: 'some_value'
    }, [location]);

};


问:
Same class on parent and child element for navigation ".nav-links" - Looking for best CSS solution
I have to create left section for a website ".leftpart" in which I have parent navigation class ".nav-links" with CSS properties. I have also have same class ".nav-links" as a sub section under parent ".nav-links". I want to give a different background color "red" to child ".nav-links" [Edit and Save]. Can you anyone suggest best way to do this ?

My code is below, thanks in advance :

.leftpart {
          width: 100%;
          display: block;
          margin: 20px;
        }

        .leftpart .nav-links ul {
          list-style: none;
          margin: 0;
          padding: 0;
          display: block;
        }

        .leftpart .nav-links ul li {
          margin-bottom:20px;
        }

        .leftpart .nav-links ul li a {
           background:green;
           color:#fff;
           padding: 20px;
           display: inline-block;
        }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="leftpart">
        <div class="nav-links">
          <h1> Primary Links </h1>
          <ul>
            <li>
              Profile
            </li>

            <li>
              Friends
            </li>

            <li>
              Milestones
            </li>

            <li>
              Groups
            </li>
          </ul>

          <div class="sub-seciton">
              <div class="nav-links">
                <ul>
                  <li>
                    Edit
                  </li>

                  <li>
                    Save
                  </li>
                </ul>
              </div>
          </div>

        </div>

        <div class="nav-links">
          <h1> Secondary Links </h1>
          <ul>
            <li>
              Privacy
            </li>

            <li>
              Settings
            </li>
          </ul>
        </div>
    </div></code>```

答:
Just set your CSS code more specific for it:

        .leftpart {
          width: 100%;
          display: block;
          margin: 20px;
        }

        .leftpart .nav-links ul {
          list-style: none;
          margin: 0;
          padding: 0;
          display: block;
        }

        .leftpart .nav-links ul li {
          margin-bottom:20px;
        }

        .leftpart .nav-links ul li a {
           background:green;
           color:#fff;
           padding: 20px;
           display: inline-block;
        }

        .leftpart .nav-links .sub-seciton .nav-links ul li a {
           background:red;
           color:#fff;
           padding: 20px;
           display: inline-block;
        }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="leftpart">
        <div class="nav-links">
          <h1> Primary Links </h1>
          <ul>
            <li>
              Profile
            </li>

            <li>
              Friends
            </li>

            <li>
              Milestones
            </li>

            <li>
              Groups
            </li>
          </ul>

          <div class="sub-seciton">
              <div class="nav-links">
                <ul>
                  <li>
                    Edit
                  </li>

                  <li>
                    Save
                  </li>
                </ul>
              </div>
          </div>

        </div>

        <div class="nav-links">
          <h1> Secondary Links </h1>
          <ul>
            <li>
              Privacy
            </li>

            <li>
              Settings
            </li>
          </ul>
        </div>
    </div></code>```

Body:
I have to create left section for a website ".leftpart" in which I have parent navigation class ".nav-links" with CSS properties. I have also have same class ".nav-links" as a sub section under parent ".nav-links". I want to give a different background color "red" to child ".nav-links" [Edit and Save]. Can you anyone suggest best way to do this ?

My code is below, thanks in advance :

.leftpart {
          width: 100%;
          display: block;
          margin: 20px;
        }

        .leftpart .nav-links ul {
          list-style: none;
          margin: 0;
          padding: 0;
          display: block;
        }

        .leftpart .nav-links ul li {
          margin-bottom:20px;
        }

        .leftpart .nav-links ul li a {
           background:green;
           color:#fff;
           padding: 20px;
           display: inline-block;
        }

 Primary Links

              Profile

              Friends

              Milestones

              Groups

                    Edit

                    Save

 Secondary Links

              Privacy

              Settings

Body:
Just set your CSS code more specific for it:

        .leftpart {
          width: 100%;
          display: block;
          margin: 20px;
        }

        .leftpart .nav-links ul {
          list-style: none;
          margin: 0;
          padding: 0;
          display: block;
        }

        .leftpart .nav-links ul li {
          margin-bottom:20px;
        }

        .leftpart .nav-links ul li a {
           background:green;
           color:#fff;
           padding: 20px;
           display: inline-block;
        }

        .leftpart .nav-links .sub-seciton .nav-links ul li a {
           background:red;
           color:#fff;
           padding: 20px;
           display: inline-block;
        }

<div class="leftpart">
        <div class="nav-links">
          <h1> Primary Links </h1>
          <ul>
            <li>
              <a href="/profile.html">Profile</a>
            </li>

            <li>
              <a href="/friends.html">Friends</a>
            </li>

            <li>
              <a href="/milestone.html">Milestones</a>
            </li>

            <li>
              <a href="/groups.html">Groups</a>
            </li>
          </ul>

          <div class="sub-seciton">
              <div class="nav-links">
                <ul>
                  <li>
                    <a href="#">Edit</a>
                  </li>

                  <li>
                    <a href="#">Save</a>
                  </li>
                </ul>
              </div>
          </div>

        </div>

        <div class="nav-links">
          <h1> Secondary Links </h1>
          <ul>
            <li>
              <a href="/privacy.html">Privacy</a>
            </li>

            <li>
              <a href="/settings.html">Settings</a>
            </li>
          </ul>
        </div>
    </div>


问:
Rest Framework deserialize one field and serialize model object
Hi I want to deserialize only using 1 field. However, I want to serialize it as an object depending on the model.

Suppose I have:

```<code>#models.py
class Product(models.Model):
    name = models.CharField()
    amount = models.IntegerField()
    description = models.TextField()

class Query(models.Model):
    name = models.CharField()
    product = models.ForeignKey(Product)
    ...

#serializers.py
class ProductSerializer(serializers.ModelSerializer):
    class Meta:
        model = Product
        fields = '__all__'

class QuerySerializer(serializers.ModelSerializer):
    product = ProductSerializer()

    class Meta:
        model = Query
        fields = '__all__'
</code>```

I want to POST/deserialize something like this on the QuerySerializer:

```<code>{
    "name": "Query 1",
    "product": "Banana",
    ...
}
</code>```

and I want something like this in return for serializer:

```<code>{
    "name": "Query 1",
    "product": {
                   "name": "Banana",
                   "amount": 1,
                   "description": "Banana description"
               }
    ...
}
</code>```

I know a way is overriding to_internal_value but I do not like it since it messes up with ValidationErrrors.

I also get this as a result:

```<code>{'product': {'non_field_errors':
['Invalid data. Expected a dictionary, but got str.']}}
</code>```

答:
First of all, make the name field of Product as unique to avoid unnecessary complications.

```<code>class Product(models.Model):
    name = models.CharField(<b>unique=True</b>)
    amount = models.IntegerField()
    description = models.TextField()</code>```

and change your serializer as,

```<code>class QuerySerializer(serializers.ModelSerializer):
    <b>product = serializers.CharField(write_only=True)</b>

    class Meta:
        model = Query
        fields = '__all__'

    <b>def create(self, validated_data):
        product_name = validated_data.pop('product')
        product_instance = Product.objects.get(name=product_name)
        return Query.objects.create(product=product_instance, **validated_data)

    def to_representation(self, instance):
        rep = super().to_representation(instance)
        rep['product'] = ProductSerializer(instance.product).data
        return rep</b></code>```

Reference: DRF: Simple foreign key assignment with nested serializers?

Body:
Hi I want to deserialize only using 1 field. However, I want to serialize it as an object depending on the model.

Suppose I have:

#models.py
class Product(models.Model):
    name = models.CharField()
    amount = models.IntegerField()
    description = models.TextField()

class Query(models.Model):
    name = models.CharField()
    product = models.ForeignKey(Product)
    ...

#serializers.py
class ProductSerializer(serializers.ModelSerializer):
    class Meta:
        model = Product
        fields = '__all__'

class QuerySerializer(serializers.ModelSerializer):
    product = ProductSerializer()

    class Meta:
        model = Query
        fields = '__all__'

I want to POST/deserialize something like this on the QuerySerializer:

{
    "name": "Query 1",
    "product": "Banana",
    ...
}

and I want something like this in return for serializer:

{
    "name": "Query 1",
    "product": {
                   "name": "Banana",
                   "amount": 1,
                   "description": "Banana description"
               }
    ...
}

I know a way is overriding to_internal_value but I do not like it since it messes up with ValidationErrrors.

I also get this as a result:

{'product': {'non_field_errors':
['Invalid data. Expected a dictionary, but got str.']}}

Body:
First of all, make the name field of Product as unique to avoid unnecessary complications.

class Product(models.Model):
    name = models.CharField(unique=True)
    amount = models.IntegerField()
    description = models.TextField()

and change your serializer as,

class QuerySerializer(serializers.ModelSerializer):
    product = serializers.CharField(write_only=True)

    class Meta:
        model = Query
        fields = '__all__'

    def create(self, validated_data):
        product_name = validated_data.pop('product')
        product_instance = Product.objects.get(name=product_name)
        return Query.objects.create(product=product_instance, **validated_data)

    def to_representation(self, instance):
        rep = super().to_representation(instance)
        rep['product'] = ProductSerializer(instance.product).data
        return rep

Reference: DRF: Simple foreign key assignment with nested serializers?


问:
Playing m3u8 video with video tag
```<code><video width="352" height="198" controls>
    <source src="video.m3u8" type="application/x-mpegURL">
</video>
</code>```

This code works fine with all browsers on my android device but doesn't works on Firefox / Chrome / Safari on my computer.
I need to play the video on all devices. What can I do?

答:
this should easily work</p>

```<code><script src="https://cdn.jsdelivr.net/npm/hls.js@latest"></script>
<video id="video"></video>
<script>
  if(Hls.isSupported()) {
    var video = document.getElementById('video');
    var hls = new Hls();
    hls.loadSource('https://video-dev.github.io/streams/x36xhzz/x36xhzz.m3u8');
    hls.attachMedia(video);
    hls.on(Hls.Events.MANIFEST_PARSED,function() {
      video.play();
  });
 }
</script>
</code>```

Title: Playing m3u8 video with video tag

Body:
<video width="352" height="198" controls>
    <source src="video.m3u8" type="application/x-mpegURL">
</video>

This code works fine with all browsers on my android device but doesn't works on Firefox / Chrome / Safari on my computer.
I need to play the video on all devices. What can I do?

Body:
this should easily work

<script src="https://cdn.jsdelivr.net/npm/hls.js@latest"></script>
<video id="video"></video>
<script>
  if(Hls.isSupported()) {
    var video = document.getElementById('video');
    var hls = new Hls();
    hls.loadSource('https://video-dev.github.io/streams/x36xhzz/x36xhzz.m3u8');
    hls.attachMedia(video);
    hls.on(Hls.Events.MANIFEST_PARSED,function() {
      video.play();
  });
 }
</script>


问:
Why do i need to left shift before summing the result?
Here is a code snippet that works as intended, it correctly reverses the bits of an integer and returns the new int. My question is why does the line result <<= 1 have to occur before I sum result with the operation n&1?

In the first iteration, it does not affect results because the result is instantiated as 0. If I put the result <<= 1 line at the END of the for loop, I would still be left shifting result before I sum result with n&1.
My code, with the left shifting result at the end, isn't working and I can't seem to understand this final step.

```<code>public int reverseBits(int n) {
    int result = 0;
    for(int i=0; i<32; i++){
        result <<= 1;
        result += n&1;
        n >>= 1;
    }
    return result;
}
</code>```

答:
Because otherwise you operate on the wrong bit of your operation. Note you could replace your current bitshifts with simple arithmetic and division if that helps. Like,

```<code>public static int reverseBits(int n) {
    int result = 0;
    for (int i = 0; i < 32; i++) {
        result += result + (n & 1);
        n /= 2;
    }
    return result;
}
</code>```

Explanation1:

```<code>result <<= 1;
</code>```

This is equivalent to result = result * 2, which is the same as result = result + result thus we can combine with the next instruction;

```<code>result += n&1
</code>```

and get

```<code>result += result + (n & 1);
</code>```

As for >>= 1, that is the same as / 2.

1Math.

Body:
Here is a code snippet that works as intended, it correctly reverses the bits of an integer and returns the new int. My question is why does the line result <<= 1 have to occur before I sum result with the operation n&1?

In the first iteration, it does not affect results because the result is instantiated as 0. If I put the result <<= 1 line at the END of the for loop, I would still be left shifting result before I sum result with n&1.
My code, with the left shifting result at the end, isn't working and I can't seem to understand this final step.

public int reverseBits(int n) {
    int result = 0;
    for(int i=0; i<32; i++){
        result <<= 1;
        result += n&1;
        n >>= 1;
    }
    return result;
}

Body:
Because otherwise you operate on the wrong bit of your operation. Note you could replace your current bitshifts with simple arithmetic and division if that helps. Like,

public static int reverseBits(int n) {
    int result = 0;
    for (int i = 0; i < 32; i++) {
        result += result + (n & 1);
        n /= 2;
    }
    return result;
}

Explanation1:

result <<= 1;

This is equivalent to result = result * 2, which is the same as result = result + result thus we can combine with the next instruction;

result += n&1

and get

result += result + (n & 1);

As for >>= 1, that is the same as / 2.

1Math.


问:
How to realize a 3d web Applet
i've been request from a customer to realize a 3d applet (maybe flex or silverlight ?) that gives me the possibility to apply clothes textures (such as pants or shoes) to human 3d models.

I also need to modify the height of the models...

can you give me any suggestion about where to start ? i'm pretty new in this world and i need a way to start from scratch.

Thanks in adavance.

答:
Does he need "True" 3D or Faux 3D?

For true 3D in the Flash Player, you'll need to use Stage3D which is only available in prerelease form from Adobe Labs.  I expect it in the next major version of the Flash Player.  If I had to guess that will be Version 11 and it will be released at Adobe Max in October.  If you Google around, the code name was called Molehill.  You may find some videos and other information on it using that name.

If "Faux" 3D is okay, then there are a handful of frameworks for Flash you canlook at, such as Away3D or PaperVision.

I can't help w/ regards to Silverlight specifics.

Update:

PaperVision is an abandoned product, as pointed out in the comments, so I would only use that with caution.

Alternativa is another alternative.

Title: How to realize a 3d web Applet


问:
How do get the text from specific line in listbox delphi
I want to get the text from a specific line.

Ex.

ListBox Contents:

Line 0    String 1

Line 1    String 2

Line 3    String 3

How do get the text from line 1 per example?

i try with this:

(listbox1.Items.Objects[1] as TText).Text

But generates a random access violation...

There is a another way?

答:
```<code>Items.Lines[0] - Access element 0 (first string) of Lines array -- for Kylix

Items.Strings[0] - Access element 0 (first string) of Strings array -- for VCL/FMX
</code>```

AV generates when you're trying to Access memory, that is not available, so, in other words, delphi have no type-checking for accessing program memory (binary data), and it results in a wide range of unhandled errors, such as wrong type error and NullPointer exception, which is, however can be handled without modifying memory routines (writing other typedefinitions to provide checking), pointer can be checked by comparing with nil in Pascal implementation or by CMP func in Assembler.

More about this:

Every variable, constant and, of course, method is stored in computer memory (RAM) during execution process, in its own field, which is supplied by the processor (CPU) to program, and limited by integrated on the motherboard logic, so it's cannot write to the other programs memory.

Most data types has its own byte-alignment (specific of the storing 0 and 1, but, when type is more than just a one byte, it's widened to contain type information) to know, that it is have correct binary data in it, such as Strings, Objects and Records.

String stores it's own length and encoding in byte representation of its content, when the class stores the actual type name, which is used to control functions and procedures calling.

But, the delphi Pascal seems to access memory right after specification of the data adress, without any checking of its content, so it will result in returning random values in case of accessing unspecified types -- types, that have no widened type info (such as different integer types) and AV in case of acessing specified types.

Just remember to check all of the Pointer types (as usual they starts from P letter, such as PAnsiChar) for containing something in it:

Ways:

```<code>// Assigned function
if Assigned(pvar) then
DoSomething();
// = nil comparision / equation
if pvar <> nil then
DoSomething()
Else
Exit;
</code>```

Body:
Items.Lines[0] - Access element 0 (first string) of Lines array -- for Kylix

Items.Strings[0] - Access element 0 (first string) of Strings array -- for VCL/FMX

AV generates when you're trying to Access memory, that is not available, so, in other words, delphi have no type-checking for accessing program memory (binary data), and it results in a wide range of unhandled errors, such as wrong type error and NullPointer exception, which is, however can be handled without modifying memory routines (writing other typedefinitions to provide checking), pointer can be checked by comparing with nil in Pascal implementation or by CMP func in Assembler.

More about this:

Every variable, constant and, of course, method is stored in computer memory (RAM) during execution process, in its own field, which is supplied by the processor (CPU) to program, and limited by integrated on the motherboard logic, so it's cannot write to the other programs memory.

Most data types has its own byte-alignment (specific of the storing 0 and 1, but, when type is more than just a one byte, it's widened to contain type information) to know, that it is have correct binary data in it, such as Strings, Objects and Records.

String stores it's own length and encoding in byte representation of its content, when the class stores the actual type name, which is used to control functions and procedures calling.

But, the delphi Pascal seems to access memory right after specification of the data adress, without any checking of its content, so it will result in returning random values in case of accessing unspecified types -- types, that have no widened type info (such as different integer types) and AV in case of acessing specified types.

Just remember to check all of the Pointer types (as usual they starts from P letter, such as PAnsiChar) for containing something in it:

Ways:

// Assigned function
if Assigned(pvar) then
DoSomething();
// = nil comparision / equation
if pvar <> nil then
DoSomething()
Else
Exit;


问:
How do calculate coordinates
I have a list coordinates same latitude, longitude. I want to divide them into a circle around the original coordinate.

For example I have a list of 6 items the same coordinates, how do i get list vertex point's coordinates of hexagon by use JavaScript with google map

答:
It sounds like Ken Y-N's comment is exactly what you are looking for.

```<code>fucntion printPoints(latitude, longitude, radius, vertices){

    for (var i = 0; i < vertices; i ++){
        console.log([latitude + (radius*Math.cos(Math.PI*2/vertices * i)), longitude + (radius*Math.sin(Math.PI*2/vertices * i))]);
    }

}

printPoints(0, 0, 10, 6); //prints [10, 0] [5, 8.7] [-5, 8.7] [-10, 0] [-5, -8.7] [5, -8.7]
</code>```

This function simply prints the coordinates, but you can modify it as you would like to.

Title: How do calculate coordinates

Body:
It sounds like Ken Y-N's comment is exactly what you are looking for.

fucntion printPoints(latitude, longitude, radius, vertices){

    for (var i = 0; i < vertices; i ++){
        console.log([latitude + (radius*Math.cos(Math.PI*2/vertices * i)), longitude + (radius*Math.sin(Math.PI*2/vertices * i))]);
    }

}

printPoints(0, 0, 10, 6); //prints [10, 0] [5, 8.7] [-5, 8.7] [-10, 0] [-5, -8.7] [5, -8.7]

This function simply prints the coordinates, but you can modify it as you would like to.


问:
how to generate a php image for src
I would like to use:

```<code>src="my_generated_image_from_php.jpg"
</code>```

instead of

src="my_php_image.php"

How do I do it?

my_php_image.php like:

```<code><?php
     ......
     Header('Content-type: image/png');
     imagepng($im2);
     imagedestroy($im2);
     ......
?>
</code>```

答:
You are probably thinking about URL rewriting (mod_rewrite), which is used to serve something with different URL.

my_generated_image_from_php.jpeg (hiding real extension of the file called - 'php') may then get you the same thing as my_php_image.php?image=my_generated_image_from_php.jpeg.

When it comes to MIME-type and header of the script's response, it would be good if you could include it, but this is not required to achieve what you expect.

Title: how to generate a php image for src

Body:
I would like to use:

src="my_generated_image_from_php.jpg"

instead of

src="my_php_image.php"

How do I do it?

my_php_image.php like:

<?php
     ......
     Header('Content-type: image/png');
     imagepng($im2);
     imagedestroy($im2);
     ......
?>


问:
APK and Expo Client android app are different
I am building a cross-platform app with expo SDK36. I am testing with the expo client on android and ios.

It seems that the built expo apk downloaded on expo is different than the android version tested from my android expo client.

I can't scroll on my views with the app APK, hopefully, I saw it.

Is this an expo bug and is this expected? I was expecting to have the same app on both expo and real app.

I must rebuild until I find the bug, the APK and expo pipelines are quite busy, how can I troubleshoot efficiently without ejecting?

答:
it is running cache. run this command. It will clear the cache.</p>

```<code>npm start --cache-clear

</code>```

Body:
it is running cache. run this command. It will clear the cache.

npm start --cache-clear


问:
Create new product by calliing shopify api
I am trying to create a new product by calling the shopify product api (/admin/api/2020-01/products.json). I am trying to achieve this using the "https" module. Below is the sample code

```<code>const url1 = 'https://{api_token}@tuscstore.myshopify.com/admin/api/2020-01/products.json';
    var obj = {
      "product":[
          {
              "title": "Saturn",
              "body_html": "<p>The epitome of elegance</p>",
              "vendor": "Soltions inc",
              "product_type": "Planets",
              "handle": "saturn",
              "tags": "",
              "images": [
                  {
                      "src": "https://solarsystem.nasa.gov/system/stellar_items/image_files/38_saturn_1600x900.jpg"
                  }
              ]
          }
      ]
    };

const https = require('https');

var data = JSON.stringify(obj)

const options = new URL(url1);

var req = https.request(options, (res) => {
  console.log('statusCode:', res.statusCode);
  console.log('headers:', res.headers);

/*   res.on('data', (d) => {
     process.stdout.write(d);
  }); */
});

req.on('error', (e) => {
  console.error(e);
});

req.write(data);
req.end();

const Index = () => (
    <div>
      <p>Sample app using React and Next.js</p>
    </div>
  );

export default Index;
</code>```

I am facing 2 problems,

when I do "process.stdout.write(d)", I receive cannot readproperty "write" undefined.

If I comment it out as I have done in
the code above, I don't get the error.

In either case I get the statuscode as 200, and not 201 which is what I shoudl receive according to shopify's docs.

Can someone please help me with what is going wrong?

Edit: Using Post,I get a type error

```<code>const https = require('https');

var data = JSON.stringify(obj)

var options = {
  hostname: 'https://{apikey:password}@tuscstore.myshopify.com/admin/api/2020-01',
  path: '/products.json',
  method: 'POST',
  headers: {
       'Content-Type': 'application/json',
       /*'Content-Length': data.length*/
       'Authorization' : 'API_TOKEN'
     }
};

var req = https.request(options, (res) => {
  console.log('statusCode:', res.statusCode);
  console.log('headers:', res.headers);
});

req.on('error', (e) => {
  console.error(e);
});

req.write(data);
req.end();
</code>```

TypeError: Failed to execute 'fetch' on 'Window': Failed to parse URL from https://[https://{APIKEY:PWD}@tuscstore.myshopify.com/admin/api/2020-01]/products.json

答:
you creating a new product you have to make http POST request , and now your making http GET request you should update your options like so :

```<code>const options = {
  hostname: 'https://apikey:password@<@store_url>/admin/api/2020-01', // your host name
  path: '/shop.json', // your end point
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
    'Authorization' : 'YOUR_API_TOKEN'
  }
}
</code>```

OR you can use this package to solve all your problems https://www.npmjs.com/package/shopify-api-node

Body:
I am trying to create a new product by calling the shopify product api (/admin/api/2020-01/products.json). I am trying to achieve this using the "https" module. Below is the sample code

const url1 = 'https://{api_token}@tuscstore.myshopify.com/admin/api/2020-01/products.json';
    var obj = {
      "product":[
          {
              "title": "Saturn",
              "body_html": "
The epitome of elegance
",
              "vendor": "Soltions inc",
              "product_type": "Planets",
              "handle": "saturn",
              "tags": "",
              "images": [
                  {
                      "src": "https://solarsystem.nasa.gov/system/stellar_items/image_files/38_saturn_1600x900.jpg"
                  }
              ]
          }
      ]
    };

const https = require('https');

var data = JSON.stringify(obj)

const options = new URL(url1);

var req = https.request(options, (res) => {
  console.log('statusCode:', res.statusCode);
  console.log('headers:', res.headers);

/*   res.on('data', (d) => {
     process.stdout.write(d);
  }); */
});

req.on('error', (e) => {
  console.error(e);
});

req.write(data);
req.end();

const Index = () => (

Sample app using React and Next.js

  );

export default Index;

I am facing 2 problems,

when I do "process.stdout.write(d)", I receive cannot readproperty "write" undefined.

If I comment it out as I have done in
the code above, I don't get the error.

In either case I get the statuscode as 200, and not 201 which is what I shoudl receive according to shopify's docs.

Can someone please help me with what is going wrong?

Edit: Using Post,I get a type error

const https = require('https');

var data = JSON.stringify(obj)

var options = {
  hostname: 'https://{apikey:password}@tuscstore.myshopify.com/admin/api/2020-01',
  path: '/products.json',
  method: 'POST',
  headers: {
       'Content-Type': 'application/json',
       /*'Content-Length': data.length*/
       'Authorization' : 'API_TOKEN'
     }
};

var req = https.request(options, (res) => {
  console.log('statusCode:', res.statusCode);
  console.log('headers:', res.headers);
});

req.on('error', (e) => {
  console.error(e);
});

req.write(data);
req.end();

TypeError: Failed to execute 'fetch' on 'Window': Failed to parse URL from https://[https://{APIKEY:PWD}@tuscstore.myshopify.com/admin/api/2020-01]/products.json

Body:
you creating a new product you have to make http POST request , and now your making http GET request you should update your options like so :

const options = {
  hostname: 'https://apikey:password@<@store_url>/admin/api/2020-01', // your host name
  path: '/shop.json', // your end point
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
    'Authorization' : 'YOUR_API_TOKEN'
  }
}

OR you can use this package to solve all your problems https://www.npmjs.com/package/shopify-api-node


问:
Using Azure API Management service, how do I setup authentication for browser to API FrontEnd requests?
I realize that AZURE APIMS has a lot out of the box. Including subscription based server-side authentication.

However, I would like to know:
What options are available for client apps which are browsers?
For example,
Assume I have a single backend API with a single endpoint. I want to expose this endpoint to external business partners who use browser based applications which make requests to the backend from client side (browser)

How can I achieve this using AZURE API management service?

答:
APIM supports protecting your API with OAuth 2.0 which you can setup on your APIM instance and leverage in your browser-based applications.

Your application would first have to get the JWT token from your identity provider and then provide the same in requests to the APIM endpoint which are pre-validated using a policy.

Here are samples of applications using AzureAD (and its MSAL library) for authentication/authorization.


问:
Bypass "Entity not found" error with JPA
Sometimes it's quite difficult (or a performance problem) to clean delete all references to an entity.

For example, I've got a Person object which has relationships to another Person objects.

When I delete a Person, I don't want to delete this Person in all relations she can have simply because sometimes this Person object does not know where it is referenced. So, if I would like to clean delete all references, I must do extra sql work that can result in performance problem.

In an ideal world, I would like to delete the Person object and when another Person do a reference to this Person (because it has its id in its relations), simply return null.

The fact is JPA complains that

```<code>javax.persistence.EntityNotFoundException: No row with the given identifier exists
</code>```

Is there a way to force JPA to return a null reference and not an exception in this case ?

答:
```<code>ERROR 1452: Cannot add or update a child row: a foreign key constraint fails....
   if this type of error occur :
   then
  First of all
  goto this table and check in setting > if Engine is: InnoDB then change its to MyISAM

 (and delete references foreign constraint)
</code>```

Its 100% working...

Body:
Sometimes it's quite difficult (or a performance problem) to clean delete all references to an entity.

For example, I've got a Person object which has relationships to another Person objects.

When I delete a Person, I don't want to delete this Person in all relations she can have simply because sometimes this Person object does not know where it is referenced. So, if I would like to clean delete all references, I must do extra sql work that can result in performance problem.

In an ideal world, I would like to delete the Person object and when another Person do a reference to this Person (because it has its id in its relations), simply return null.

The fact is JPA complains that

javax.persistence.EntityNotFoundException: No row with the given identifier exists

Is there a way to force JPA to return a null reference and not an exception in this case ?

Body:
ERROR 1452: Cannot add or update a child row: a foreign key constraint fails....
   if this type of error occur :
   then
  First of all
  goto this table and check in setting > if Engine is: InnoDB then change its to MyISAM

 (and delete references foreign constraint)

Its 100% working...


问:
how to open next modal directly after one is saved?
```<code><?php
        //session_start();

        $con= mysqli_connect('localhost','root','');
        mysqli_select_db($con,'cementation');

        if(!$con)
        {

        echo "Not Connected to the server";
        }

        if(!mysqli_select_db($con,'cementation'))
        {
        echo "DB Not Selected";
        }
        $date= date("Y/m/d"); //1
        ?>
<!--6th table starts-->
<form method="post" action="/cementation/configuration/dooconfig.php">
    <div class="modal fade" id="modalForm11" tabindex="-1" role="dialog" aria-labelledby="myModalLabel"
         aria-hidden="true">
        <div class="modal-dialog modal-lg" role="document">
            <div class="modal-content">
                <div class="modal-header text-center">
                    <h4 class="modal-title w-100 font-weight-bold">Detail of Operations</h4>
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">×</span>
                    </button>
                </div>
                <div class="modal-body mx-3">
                    <div class="row">

                        <div class="col-sm-12">  <!-- Imp Div 1 -->

                            <div class="row"> <!-- Main Row Div -->
                                <div class="col-sm-12"> <!-- First Main Col -->

                                    <div class="row">
                                        <div class="col-sm-3" style="width: 100%">
                                            <div class="md-form mb-4">
                                                <input type="text" id="Entry_no" name="Entry_no" placeholder="Row #"
                                                       class="form-control validate">
                                            </div>
                                        </div>

                                        <div class="col-sm-3">
                                            <div class="md-form mb-4">
                                                <input type="text" id="from_time" name="From_time" placeholder="from"
                                                       class="form-control validate">
                                            </div>

                                        </div>
                                        <div class="col-sm-3">
                                            <div class="md-form mb-4">
                                                <input type="text" id="to_time" name="To_time" placeholder="to"
                                                       class="form-control validate">
                                            </div>
                                        </div>

                                        <div class="col-sm-3">
                                            <div class="md-form mb-4">
                                                <input type="text" id="hrs" name="HRS" placeholder="hrs"
                                                       class="form-control validate">
                                            </div>
                                        </div>

                                        <div class="col-sm-4">
                                            <div class="md-form mb-4">
                                                <input type="text" id="code" name="code" placeholder="code"
                                                       class="form-control validate">
                                            </div>
                                        </div>

                                        <div class="col-sm-8">
                                            <div class="md-form mb-4">
                                                <input type="text" id="operations" name="detail_of_operations"
                                                       placeholder="operations" class="form-control validate">
                                            </div>
                                        </div>

                                        <div class="col-sm-8">
                                            <div class="md-form mb-4">
                                                <button type="Save" class="btn btn-primary" name="add-row"
                                                        onclick="$('#modalForm11').modal('show');">Save and Add Row
                                                </button>
                                            </div>
                                        </div>

                                    </div>

                                    <!-- Reload
                                   </div>
                               </div> -->

                                </div> <!-- 1st Main Col Ends -->
                                <div class="col-sm-12"> <!-- second col for main row starts -->
                                    <table width="100%" border-collapse: collapse class="datafill" border="1px solid">
                                        <tr>
                                            <th>Row #</th>
                                            <th>From</th>
                                            <th>To</th>
                                            <th>Hrs</th>
                                            <th>Code</th>
                                            <th>Operations</th>
                                        </tr>

                                        <?php
                                                $date= date("Y/m/d");
                                                $s= "SELECT Entry_no,From_time,To_time,HRS,code,detail_of_operations FROM detail_of_operations WHERE date='$date'";
                                                $result= $con->query($s);

                                                if ($result -> num_rows >0) {
                                                while ($row = $result -> fetch_assoc()){
                                                echo "<tr><td>".$row["Entry_no"]."</td><td>".$row["From_time"]."</td><td>".$row["To_time"]."</td><td>".$row["HRS"]."</td><td>".$row["code"]."</td><td>".$row["detail_of_operations"]."</td></tr>";

                                                }
                                                }
                                                else {
                                                echo "0 result";
                                                }

                                                ?>
                                    </table>

                                </div> <!-- Second Col for main row ends -->
                            </div> <!-- Main row div ends -->
                        </div> <!-- IMP Div 1 ends -->
                        <div class="modal-footer d-flex justify-content-center">

                            <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
                            <a href="form.php">
                                <button type="button" class="btn btn-primary">Save</button>
                            </a>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
    <div class="button">

        <button type="button" class="btn btn-primary" data-toggle="modal" data-target="#modalForm11">Detail of
            Operations
        </button>
    </div>
</form>
</code>```

I have a form which consists of a lot of modals. i want to open the next model to popup as soon as the user saves data in the 1st modal. i also have a  few modals that needs multiple entries for one record.

Modal1,Modal2,modal3,modal4,Details_of_Operations,Formations.

These are all my Modals that needs data to be entered and they all store data for current date. I want the user to be able to go to next modal directly after saving one.

答:
You can implement javascript promises to achieve your goal.
Here is a quick example in which you can base on.

function saveSomeData() {
  return new Promise((resolve, reject) => {
    // setTimeOut to simulate the call waiting for the API
    setTimeout(() => {
      resolve({ succeeded: true, message: 'data saved' })
    }, 900)

    // Use reject if the API returns any error to catch it
    // on the promise call
    // ---> reject(err)
  });
}

function onClickSaveModal(previousModalId, nextModalId) {
  // Uses promises to wait until the data of the current modal
  // is saved to open the other one
  saveSomeData()
    .then(res => {
      if (res.succeeded) {
        alert('Data saved successfully');

        hideModal(previousModalId);

        // checks if it is the last modal
        if (nextModalId) {
          showModal(nextModalId);
        }
      }
    })
    .catch(err => {
      // it enters here when you reject the promise
      alert('Some error trying to save data');
      console.log(err);
    });
}

function showModal(id) {
  const modal = document.querySelector(`#${id}`);
  modal.style.display = 'inline-block';
}
function hideModal(id) {
  const modal = document.querySelector(`#${id}`);
  modal.style.display = 'none';
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#modal1, #modal2, #modal3 {
  height: 100px;
  width: 100px;
  margin: 0 15px;
  display: inline-block;
}
#modal1 {
  background-color: lightblue;
}

#modal2 {
  background-color: lightcoral;
  display: none;
}

#modal3 {
  background-color: lightcyan;
  display: none;
}

.open {
  display: inline-block;
}</code>```

modal 1

  <button onclick="onClickSaveModal('modal1','modal2')">Save</button>

modal 2

  <button onclick="onClickSaveModal('modal2','modal3')">Save</button>

modal 3

  <button onclick="onClickSaveModal('modal3')">Save</button>

```

Let me know if you have any questions about this implementation.

Body:
<?php
        //session_start();

        $con= mysqli_connect('localhost','root','');
        mysqli_select_db($con,'cementation');

        if(!$con)
        {

        echo "Not Connected to the server";
        }

        if(!mysqli_select_db($con,'cementation'))
        {
        echo "DB Not Selected";
        }
        $date= date("Y/m/d"); //1
        ?>

<form method="post" action="/cementation/configuration/dooconfig.php">

Detail of Operations

                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                        ×
                    </button>

                                                <input type="text" id="Entry_no" name="Entry_no" placeholder="Row #"
                                                       class="form-control validate">

                                                <input type="text" id="from_time" name="From_time" placeholder="from"
                                                       class="form-control validate">

                                                <input type="text" id="to_time" name="To_time" placeholder="to"
                                                       class="form-control validate">

                                                <input type="text" id="hrs" name="HRS" placeholder="hrs"
                                                       class="form-control validate">

                                                <input type="text" id="code" name="code" placeholder="code"
                                                       class="form-control validate">

                                                <input type="text" id="operations" name="detail_of_operations"
                                                       placeholder="operations" class="form-control validate">

                                                <button type="Save" class="btn btn-primary" name="add-row"
                                                        onclick="$('#modalForm11').modal('show');">Save and Add Row
                                                </button>

                                            Row #
                                            From
                                            To
                                            Hrs
                                            Code
                                            Operations

                                        <?php
                                                $date= date("Y/m/d");
                                                $s= "SELECT Entry_no,From_time,To_time,HRS,code,detail_of_operations FROM detail_of_operations WHERE date='$date'";
                                                $result= $con->query($s);

                                                if ($result -> num_rows >0) {
                                                while ($row = $result -> fetch_assoc()){
                                                echo "
".$row["Entry_no"]."	".$row["From_time"]."	".$row["To_time"]."	".$row["HRS"]."	".$row["code"]."	".$row["detail_of_operations"]."
";

                                                }
                                                }
                                                else {
                                                echo "0 result";
                                                }

                                                ?>

                            <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>

                                <button type="button" class="btn btn-primary">Save</button>

        <button type="button" class="btn btn-primary" data-toggle="modal" data-target="#modalForm11">Detail of
            Operations
        </button>

</form>

I have a form which consists of a lot of modals. i want to open the next model to popup as soon as the user saves data in the 1st modal. i also have a  few modals that needs multiple entries for one record.

Modal1,Modal2,modal3,modal4,Details_of_Operations,Formations.

These are all my Modals that needs data to be entered and they all store data for current date. I want the user to be able to go to next modal directly after saving one.

Body:
You can implement javascript promises to achieve your goal.
Here is a quick example in which you can base on.

function saveSomeData() {
  return new Promise((resolve, reject) => {
    // setTimeOut to simulate the call waiting for the API
    setTimeout(() => {
      resolve({ succeeded: true, message: 'data saved' })
    }, 900)

    // Use reject if the API returns any error to catch it
    // on the promise call
    // ---> reject(err)
  });
}

function onClickSaveModal(previousModalId, nextModalId) {
  // Uses promises to wait until the data of the current modal
  // is saved to open the other one
  saveSomeData()
    .then(res => {
      if (res.succeeded) {
        alert('Data saved successfully');

        hideModal(previousModalId);

        // checks if it is the last modal
        if (nextModalId) {
          showModal(nextModalId);
        }
      }
    })
    .catch(err => {
      // it enters here when you reject the promise
      alert('Some error trying to save data');
      console.log(err);
    });
}

function showModal(id) {
  const modal = document.querySelector(`#${id}`);
  modal.style.display = 'inline-block';
}
function hideModal(id) {
  const modal = document.querySelector(`#${id}`);
  modal.style.display = 'none';
}

#modal1, #modal2, #modal3 {
  height: 100px;
  width: 100px;
  margin: 0 15px;
  display: inline-block;
}
#modal1 {
  background-color: lightblue;
}

#modal2 {
  background-color: lightcoral;
  display: none;
}

#modal3 {
  background-color: lightcyan;
  display: none;
}

.open {
  display: inline-block;
}

<div id="modal1">
  <p>modal 1</p>
  <button onclick="onClickSaveModal('modal1','modal2')">Save</button>
</div>

<div id="modal2">
  <p>modal 2</p>
  <button onclick="onClickSaveModal('modal2','modal3')">Save</button>
</div>

<div id="modal3">
  <p>modal 3</p>
  <button onclick="onClickSaveModal('modal3')">Save</button>
</div>

Let me know if you have any questions about this implementation.