答:
The use of toggle () is not enabled for Jquery 1.9 or higher, you can solve it by use Jquery migrate.

```<code><script src="https://code.jquery.com/jquery-1.11.1.min.js"></script>
<script src="https://code.jquery.com/jquery-migrate-1.2.1.min.js"></script>
</code>```

It is advisable to use classes to hide or show elements
Change css through jquery after a click on a div

Title: Toggle() function is not working in accordion

Body:
The use of toggle () is not enabled for Jquery 1.9 or higher, you can solve it by use Jquery migrate.

<script src="https://code.jquery.com/jquery-1.11.1.min.js"></script>
<script src="https://code.jquery.com/jquery-migrate-1.2.1.min.js"></script>

It is advisable to use classes to hide or show elements
Change css through jquery after a click on a div


来源: stackexchange

问:
New pull request without unmerged commits
I have a pull request on a repository. The commits are still unmerged. Now, I want to make another pull request, totally independent from the previous one. When I create a new branch and make the new commits, all of the unmerged commits are also alongside with the new ones!

I want to create a new pull request without the unmerged commits. Please help me on how should I do that as I'm new to git :)

答:
When I create a new branch and make the new commits

This is the source of your problem.  Instead of adding commits to the same feature branch, you should create a new branch from the current feature's parent and commit from there.  Let's say the parent branch is master and the feature branch has 3 commits in it.  The diagram would look like this:

```<code>master:  ... A -- B -- C
                   \
feature:            M -- N -- O
</code>```

When you created a new branch from feature and started adding new commits you ended up with this:

```<code>master:  ... A -- B -- C
                   \
feature:            M -- N -- O
                               \
new_ft:                         S -- T ...
</code>```

In other words, the history of feature is part of the new branch.  Instead, you can create a new branch from the B commit in master using:

```<code>git checkout -b new_feature <SHA-1 for commit B>
</code>```

Now make your other set of commits, and then this second pull request will be essentially independent from the first one.

ContentLicense: CC BY-SA 3.0

Body:
When I create a new branch and make the new commits

This is the source of your problem.  Instead of adding commits to the same feature branch, you should create a new branch from the current feature's parent and commit from there.  Let's say the parent branch is master and the feature branch has 3 commits in it.  The diagram would look like this:

master:  ... A -- B -- C
                   \
feature:            M -- N -- O

When you created a new branch from feature and started adding new commits you ended up with this:

master:  ... A -- B -- C
                   \
feature:            M -- N -- O
                               \
new_ft:                         S -- T ...

In other words, the history of feature is part of the new branch.  Instead, you can create a new branch from the B commit in master using:

git checkout -b new_feature <SHA-1 for commit B>

Now make your other set of commits, and then this second pull request will be essentially independent from the first one.


问:
Elastic Beanstalk can't enable nginx gzip
I'm facing an issue with AWS Elastic Beanstalk and gzip.

I'm trying to enable Gzip compression and especially gzip compression for application/javascript. So, I tried to write two separately files.

The first one named 00_elastic_beanstalk_proxy.conf and I copy paste the content from the existing file which was in /etc/nginx/conf.d folder.

In the end of the file, I added the following lines of code:

gzip on;
gzip_comp_level 4;
gzip_types text/html text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript;

then i created an another file named gzip.conf and i put this code:
and the other one gzip.conf :

container_commands:
  enable_javascript_compress:
    command: sudo cp .ebextensions/00_elastic_beanstalk_proxy.conf /etc/nginx/conf.d/00_elastic_beanstalk_proxy.conf

If I'm trying to upload and deploy those files which I saved them into .ebextensions folder the gzip is not working.

If I'm trying to edit this file from the server with ssh and vim everything works great.

Is there any way to fix it and not needs to connect every time with ssh?

答:
Try creating the gzip file using the files object. Here's what the start of one of my nginx confs look:

```<code>files:
  /tmp/install-nginx-conf.sh:
    mode: "000755"
    owner: root
    group: root
    content: |
      #!/bin/sh
      cp /tmp/nginx_proxy.conf
/tmp/deployment/config/#etc#nginx#conf.d#00_elastic_beanstalk_proxy.conf
</code>```

Body:
Try creating the gzip file using the files object. Here's what the start of one of my nginx confs look:

files:
  /tmp/install-nginx-conf.sh:
    mode: "000755"
    owner: root
    group: root
    content: |
      #!/bin/sh
      cp /tmp/nginx_proxy.conf
/tmp/deployment/config/#etc#nginx#conf.d#00_elastic_beanstalk_proxy.conf


问:
How do you copy an animated gif to clipboard from a keyboard?(iOS 8)
I'm making a custom keyboard in which you can copy an gif to clipboard when pressing a button.

I'm not getting to work so far. Even though I've tried the following

```<code>-(void)doWhenButtonPressed {

[UIPasteboard generalPasteboard].image = [UIImage imageNamed:@"my.gif"];

}
</code>```

Now it does not copy anything, which I think is kind of strange, because it does copy the image when i it with this line in a normal application. So what am i doing wrong?

PS: I have even checked that I can actually acces 'my.gif' by adding it programmatically to a button...
PPS: And the method -(void)doWhenButtonPressed is called as well.

答:
Here is the demo code in Swift 3.0.</p>

```<code>let pb = UIPasteboard.general
let data = NSData(contentsOfURL: url)
if data != nil
{
 self.pb.setData(data!, forPasteboardType: kUTTypeGIF as String)
}
</code>```

Body:
I'm making a custom keyboard in which you can copy an gif to clipboard when pressing a button.

I'm not getting to work so far. Even though I've tried the following

-(void)doWhenButtonPressed {

[UIPasteboard generalPasteboard].image = [UIImage imageNamed:@"my.gif"];

}

Now it does not copy anything, which I think is kind of strange, because it does copy the image when i it with this line in a normal application. So what am i doing wrong?

PS: I have even checked that I can actually acces 'my.gif' by adding it programmatically to a button...
PPS: And the method -(void)doWhenButtonPressed is called as well.

Body:
Here is the demo code in Swift 3.0.

let pb = UIPasteboard.general
let data = NSData(contentsOfURL: url)
if data != nil
{
 self.pb.setData(data!, forPasteboardType: kUTTypeGIF as String)
}


问:
JNA undefined symbol
I'm trying to bind the dhcpctl library to Java using JNA. This is mi code (I didn't declare all the functions yet):

```<code>package com.abiquo.abicloud.omapi;

import com.abiquo.abicloud.omapi.DHCPControlStructure.DHCPCtrlDataString;
import com.abiquo.abicloud.omapi.DHCPControlStructure.DHCPHandle;
import com.abiquo.abicloud.omapi.OmapiControlStructure.OmapiObjectTypeT;
import com.sun.jna.Library;
import com.sun.jna.Native;
import com.sun.jna.Pointer;

/**
 * Binding of the dhcpctl header.
 * @author jdevesa@abiquo.com
 */
public interface DHCPControlLibrary extends Library
{
    /**
     * Create the loaded instance of the native library
     */
    DHCPControlLibrary INSTANCE =
        (DHCPControlLibrary) Native.loadLibrary("dhcpctl", DHCPControlLibrary.class);

    /**
     * Define as synchronized
     */
    DHCPControlLibrary SYNC_INSTANCE=(DHCPControlLibrary)                              Native.synchronizedLibrary(INSTANCE);

    int dhcpctl_initialize ();
    int dhcpctl_connect (DHCPHandle handle1, String address, int port, DHCPHandle.ByValue handle2);
    int dhcpctl_wait_for_completion (DHCPHandle handle, Pointer int1);
    int dhcpctl_get_value (DHCPCtrlDataString dataString , DHCPHandle.ByValue handleValue, String str1);
    int dhcpctl_get_boolean (Pointer int1, DHCPHandle.ByValue handleValue, String str1);
    int dhcpctl_set_value (DHCPHandle.ByValue handleValue, DHCPCtrlDataString dataString, String str1);
    ... etc ...

}
</code>```

dhcpctl uses omapi library to call the remote DHCP server. So, when I try to load the library with:

```<code>DHCPControlLibrary dhcpExecutor = DHCPControlLibrary.INSTANCE;
</code>```

it throws the following error:

```<code>Exception in thread "main" java.lang.UnsatisfiedLinkError: Unable to load library 'dhcpctl': /usr/lib/libdhcpctl.so: undefined symbol: omapi_type_generic
    at com.sun.jna.NativeLibrary.loadLibrary(NativeLibrary.java:160)
    at com.sun.jna.NativeLibrary.getInstance(NativeLibrary.java:228)
    at com.sun.jna.Library$Handler.<init>(Library.java:140)
    at com.sun.jna.Native.loadLibrary(Native.java:372)
    at com.sun.jna.Native.loadLibrary(Native.java:357)
    at com.abiquo.abicloud.omapi.DHCPControlLibrary.<clinit>(DHCPControlLibrary.java:40)
    at com.abiquo.abicloud.omapi.DHCPexecution.main(DHCPexecution.java:11)
</code>```

omapi__type__generic is an external variable stored in omapi.h. I think I have to do a sort of linking when i load the library, but I don't know how to do it.

Many thanks.

答:
I think u forget extern "C" while writing c++ code.
In my case
c++ code:

```<code>    #include <stdlib.h>
    #include <iostream>
    using namespace std;
    extern "C"
    {
        void test() {
             cout << "TEST" << endl;
        }

        int addTest(int a,int b)
        {
          int c = a + b ;
          return c ;
        }
    }
</code>```

and java code

```<code>    import com.sun.jna.Library;
    import com.sun.jna.Native;

    public class jnatest1 {

        public interface Clibrary extends Library {
            Clibrary INSTANTCE = (Clibrary) Native.loadLibrary("hello",
                    Clibrary.class);

            void test();
            int addTest(int a,int b);
        }

        public static void main(String[] args) {
            Clibrary.INSTANTCE.test();
            int c = Clibrary.INSTANTCE.addTest(10,20);
            System.out.println(c);
        }
    }
</code>```

it works for me

ContentLicense: CC BY-SA 2.5

Title: JNA undefined symbol

Body:
I'm trying to bind the dhcpctl library to Java using JNA. This is mi code (I didn't declare all the functions yet):

package com.abiquo.abicloud.omapi;

import com.abiquo.abicloud.omapi.DHCPControlStructure.DHCPCtrlDataString;
import com.abiquo.abicloud.omapi.DHCPControlStructure.DHCPHandle;
import com.abiquo.abicloud.omapi.OmapiControlStructure.OmapiObjectTypeT;
import com.sun.jna.Library;
import com.sun.jna.Native;
import com.sun.jna.Pointer;

/**
 * Binding of the dhcpctl header.
 * @author jdevesa@abiquo.com
 */
public interface DHCPControlLibrary extends Library
{
    /**
     * Create the loaded instance of the native library
     */
    DHCPControlLibrary INSTANCE =
        (DHCPControlLibrary) Native.loadLibrary("dhcpctl", DHCPControlLibrary.class);

    /**
     * Define as synchronized
     */
    DHCPControlLibrary SYNC_INSTANCE=(DHCPControlLibrary)                              Native.synchronizedLibrary(INSTANCE);

    int dhcpctl_initialize ();
    int dhcpctl_connect (DHCPHandle handle1, String address, int port, DHCPHandle.ByValue handle2);
    int dhcpctl_wait_for_completion (DHCPHandle handle, Pointer int1);
    int dhcpctl_get_value (DHCPCtrlDataString dataString , DHCPHandle.ByValue handleValue, String str1);
    int dhcpctl_get_boolean (Pointer int1, DHCPHandle.ByValue handleValue, String str1);
    int dhcpctl_set_value (DHCPHandle.ByValue handleValue, DHCPCtrlDataString dataString, String str1);
    ... etc ...

}

dhcpctl uses omapi library to call the remote DHCP server. So, when I try to load the library with:

DHCPControlLibrary dhcpExecutor = DHCPControlLibrary.INSTANCE;

it throws the following error:

Exception in thread "main" java.lang.UnsatisfiedLinkError: Unable to load library 'dhcpctl': /usr/lib/libdhcpctl.so: undefined symbol: omapi_type_generic
    at com.sun.jna.NativeLibrary.loadLibrary(NativeLibrary.java:160)
    at com.sun.jna.NativeLibrary.getInstance(NativeLibrary.java:228)
    at com.sun.jna.Library$Handler.<init>(Library.java:140)
    at com.sun.jna.Native.loadLibrary(Native.java:372)
    at com.sun.jna.Native.loadLibrary(Native.java:357)
    at com.abiquo.abicloud.omapi.DHCPControlLibrary.<clinit>(DHCPControlLibrary.java:40)
    at com.abiquo.abicloud.omapi.DHCPexecution.main(DHCPexecution.java:11)

omapi__type__generic is an external variable stored in omapi.h. I think I have to do a sort of linking when i load the library, but I don't know how to do it.

Many thanks.

Body:
I think u forget extern "C" while writing c++ code.
In my case
c++ code:

    #include <stdlib.h>
    #include <iostream>
    using namespace std;
    extern "C"
    {
        void test() {
             cout << "TEST" << endl;
        }

        int addTest(int a,int b)
        {
          int c = a + b ;
          return c ;
        }
    }

and java code

    import com.sun.jna.Library;
    import com.sun.jna.Native;

    public class jnatest1 {

        public interface Clibrary extends Library {
            Clibrary INSTANTCE = (Clibrary) Native.loadLibrary("hello",
                    Clibrary.class);

            void test();
            int addTest(int a,int b);
        }

        public static void main(String[] args) {
            Clibrary.INSTANTCE.test();
            int c = Clibrary.INSTANTCE.addTest(10,20);
            System.out.println(c);
        }
    }

it works for me


问:
how to append a array to a np.array?
```<code>coordinates =  np.empty([0,5])
np.vstack(  (coordinates,  np.array([1, 2, 3, 4, 5]) ))
print coordinates  # []
np.append(coordinates, np.array([1, 2, 3, 4, 5]), axis=0)
print coordinates
</code>```

In the code shown above, I tried to append the array, but both approaches failed. In the first approach, the output is still empty, in the second approach, the output is an error saying

ValueError: all the input arrays must have same number of dimensions

What is wrong with my method?

答:
You need to capture the results of numpy.vstack()

From the (Docs)

numpy.vstack(arrays, axis=0)

Returns:

stacked : ndarray

Test Code:

```<code>coordinates = np.empty([0, 5])
x = np.vstack((coordinates, np.array([1, 2, 3, 4, 5])))
print x
</code>```

Results:

```<code>[[ 1.  2.  3.  4.  5.]]
</code>```

Title: how to append a array to a np.array?

Body:
coordinates =  np.empty([0,5])
np.vstack(  (coordinates,  np.array([1, 2, 3, 4, 5]) ))
print coordinates  # []
np.append(coordinates, np.array([1, 2, 3, 4, 5]), axis=0)
print coordinates

In the code shown above, I tried to append the array, but both approaches failed. In the first approach, the output is still empty, in the second approach, the output is an error saying

ValueError: all the input arrays must have same number of dimensions

What is wrong with my method?

Body:
You need to capture the results of numpy.vstack()

From the (Docs)

numpy.vstack(arrays, axis=0)

Returns:

stacked : ndarray

Test Code:

coordinates = np.empty([0, 5])
x = np.vstack((coordinates, np.array([1, 2, 3, 4, 5])))
print x

Results:

[[ 1.  2.  3.  4.  5.]]


问:
How to pass json from java to javascript function
I make from my database a json string and i want to pass it to my javascript function, and print it into a html table. I use angular to make it easy to print the table, but i don't know how can i sent the data from java to javascript.
These is what i tried in java.

```<code>public void jsonRetr (String numeRepo) throws SQLException {
    String sql = "SELECT * FROM " + numeRepo;
    PreparedStatement prStm = (PreparedStatement) conn.prepareStatement(sql);
    ResultSet rs = prStm.executeQuery(sql);
    ArrayList<PersoaneJSON> persoane = new ArrayList<PersoaneJSON>();

    while (rs.next()) {
        String id = rs.getString("id");
        String login_name = rs.getString("login_name");
        String email = rs.getString("email");
        String public_gits = rs.getString("public_gits");
        String Html_profile = rs.getString("Html_profile");
        String Avatar_URL = rs.getString("Avatar_URL");

        PersoaneJSON persoana = new PersoaneJSON(id, login_name, email, public_gits, Html_profile, Avatar_URL);
        persoane.add(persoana);
    }
    Gson gson = new Gson();
    String json = gson.toJson(persoane);
    }
</code>```

These is what i tried in javascript.

```<code>    var employeeApp = angular.module("EmployeeApp",[]);
    employeeApp.controller("empCtrl",function($scope){
    $scope.query = {}
    $scope.queryBy = '$'
    $scope.employees = [];
    $scope.orderProp="name";
  });
</code>```

答:
I do some changes in your code (you can apply whatever you like)

```<code>public ArrayList<PersoaneJSON> jsonRetr (String numeRepo) throws SQLException {
    String sql = "SELECT * FROM " + numeRepo;
    PreparedStatement prStm = (PreparedStatement) conn.prepareStatement(sql);
    ResultSet rs = prStm.executeQuery(sql);
    ArrayList<PersoaneJSON> persoane = new ArrayList<PersoaneJSON>();

    while (rs.next()) {
        String id = rs.getString("id");
        String login_name = rs.getString("login_name");
        String email = rs.getString("email");
        String public_gits = rs.getString("public_gits");
        String Html_profile = rs.getString("Html_profile");
        String Avatar_URL = rs.getString("Avatar_URL");

        PersoaneJSON persoana = new PersoaneJSON(id, login_name, email, public_gits, Html_profile, Avatar_URL);
        persoane.add(persoana);
    }
   return persoane;
}
</code>```

And here is Servlet doGet Method.

```<code>  protected void doGet(HttpServletRequest request, HttpServletResponse response)
                throws ServletException, IOException {

            PrintWriter out = response.getWriter();

                response.setContentType("application/json;charset=utf-8");

                Gson gson = new Gson();
        String json = gson.toJson(jsonRetr("xyz"));

                out.write(json);
                out.close();

    }
</code>```

Use jquery and read your json object as follows

```<code>$.getJSON( "Action/Servlet", function( data ) {
    console.log(JSON.parse(data));
});
</code>```

Body:
I make from my database a json string and i want to pass it to my javascript function, and print it into a html table. I use angular to make it easy to print the table, but i don't know how can i sent the data from java to javascript.
These is what i tried in java.

public void jsonRetr (String numeRepo) throws SQLException {
    String sql = "SELECT * FROM " + numeRepo;
    PreparedStatement prStm = (PreparedStatement) conn.prepareStatement(sql);
    ResultSet rs = prStm.executeQuery(sql);
    ArrayList<PersoaneJSON> persoane = new ArrayList<PersoaneJSON>();

    while (rs.next()) {
        String id = rs.getString("id");
        String login_name = rs.getString("login_name");
        String email = rs.getString("email");
        String public_gits = rs.getString("public_gits");
        String Html_profile = rs.getString("Html_profile");
        String Avatar_URL = rs.getString("Avatar_URL");

        PersoaneJSON persoana = new PersoaneJSON(id, login_name, email, public_gits, Html_profile, Avatar_URL);
        persoane.add(persoana);
    }
    Gson gson = new Gson();
    String json = gson.toJson(persoane);
    }

These is what i tried in javascript.

    var employeeApp = angular.module("EmployeeApp",[]);
    employeeApp.controller("empCtrl",function($scope){
    $scope.query = {}
    $scope.queryBy = '$'
    $scope.employees = [];
    $scope.orderProp="name";
  });

Body:
I do some changes in your code (you can apply whatever you like)

public ArrayList<PersoaneJSON> jsonRetr (String numeRepo) throws SQLException {
    String sql = "SELECT * FROM " + numeRepo;
    PreparedStatement prStm = (PreparedStatement) conn.prepareStatement(sql);
    ResultSet rs = prStm.executeQuery(sql);
    ArrayList<PersoaneJSON> persoane = new ArrayList<PersoaneJSON>();

    while (rs.next()) {
        String id = rs.getString("id");
        String login_name = rs.getString("login_name");
        String email = rs.getString("email");
        String public_gits = rs.getString("public_gits");
        String Html_profile = rs.getString("Html_profile");
        String Avatar_URL = rs.getString("Avatar_URL");

        PersoaneJSON persoana = new PersoaneJSON(id, login_name, email, public_gits, Html_profile, Avatar_URL);
        persoane.add(persoana);
    }
   return persoane;
}

And here is Servlet doGet Method.

  protected void doGet(HttpServletRequest request, HttpServletResponse response)
                throws ServletException, IOException {

            PrintWriter out = response.getWriter();

                response.setContentType("application/json;charset=utf-8");

                Gson gson = new Gson();
        String json = gson.toJson(jsonRetr("xyz"));

                out.write(json);
                out.close();

    }

Use jquery and read your json object as follows

$.getJSON( "Action/Servlet", function( data ) {
    console.log(JSON.parse(data));
});


问:
Do any CPUs have hardware support for bounds checking?
It doesn't seem like it would be difficult to associate ranges with segments of memory. Then have an assembly instruction which treats 2 integers as "location" & "offset" (another for "data" if setting), and returns the data and error code. This would mean no longer having to make a choice between speed and security/safety when working with arrays.

Another example might be a function which verifies that instructions originating in a particular memory range cannot physically access memory outside that range. If all hardware connected to the motherboard had this capability (and were made to be compatible with each other), it would be trivial to make perfect virtual machines that run at nearly the same speed as the physical machine.

Dustin Soodak

答:
Yes.

Decades ago, Lisp machines performed simultaneous validation checks (e.g. type checks and bounds checks) as the program ran with the assumption the program and state were valid, jumping "back in time" if the check failed - unfortunately this ability to get "free" runtime validation was lost when conventional (i.e. x86) machines became dominant.

https://en.wikipedia.org/wiki/Lisp_machine

Lisp Machines ran the tests in parallel with the more conventional single instruction additions. If the simultaneous tests failed, then the result was discarded and recomputed; this meant in many cases a speed increase by several factors. This simultaneous checking approach was used as well in testing the bounds of arrays when referenced, and other memory management necessities (not merely garbage collection or arrays).

Fortunately we're finally learning from the past and slowly, and by piecemeal, reintroducing those innovations - Intel's "MPX" (Memory Protection eXtensions) for x86 were introduced in Skylake-generation processors for hardware bounds-checking - though it isn't perfect.

(x86 is a regression in other ways too: IBM's mainframes had true hardware-accelerated system virtualization in the 1980s - we didn't get it on x86 until 2005 with Intel's "VT-x" and AMD's "AMD-V" extensions).

x86 BOUND

Technically, x86 does have hardware bounds-checking: the the BOUND instruction was introduced in 1982 in the Intel 80188 (as well as the Intel 286 and above, but not the Intel 8086, 8088 or 80186 processors).

While the BOUND instruction does provide hardware bounds-checking, I understand it indirectly caused performance issues because it breaks the hardware branch predictor (according to a Reddit thread, but I'm unsure why), but also because it requires the bounds to be specified in a tuple in memory - that's terrible for performance - I understand at runtime it's no faster than manually having the instructions to do an "if index not in range [x,y] then signal the BR exception to the program or OS" (so you might imagine the BOUND instruction was added for the convenience of people who coded assembly by-hand, which was quite common in the 1980s).

The BOUND instruction is still present in today's processors, but it was not included in AMD64 (x64) - likely for the performance reasons I explained above, and also because likely very few people were using it (and compilers could trivially replace it with a manual bounds check, that might have better performance anyway, as that could use registers).

Another disadvantage to storing the array bounds in memory is that code elsewhere (that wasn't subject to BOUNDS checking) could overwrite the previously written bounds for another pointer and circumvent the check that way - this is mostly a problem with code that intentionally tries to disable safety features (i.e. malware), but if the bounds were stored in the stack - and given how easy it is to corrupt the stack, it has even less utility.

Intel MPX

Intel MPX was introduced in Skylake architecture in 2015 and should be present in all Skylake and subsequent processor models in the mainstream Intel Core family (including Xeon, and non-SoC versions of Celeron and Pentium). Intel also implemented MPX in the Goldmont architecture (Atom, and SoC versions of Celeron and Pentium) from 2016 onwards.

MPX is superior to BOUND in that it provides dedicated registers to store the bounds range so the bounds-check should be almost zero-cost compared to BOUND which required a memory access. On the Intel 486 the BOUND instruction takes 7 cycles (compare to CMP which takes only 2 cycles even if the operand was a memory address). In Skylake the MPX equivalent (BNDMK, BNDCL and BNDCU) are all 1-cycle instructions and BNDMK can be amortized as it only needs to be called once for each new pointer).

I cannot find any information on wherever or not AMD has implemented their own version of MPX yet (as of June 2017).

Critical thoughts on MPX

Unfortunately the current state of MPX is not all that rosy - a recent paper by Oleksenko, Kuvaiskii, et al. in February 2017 "Intel MPX Explained" (PDF link: caution: not yet peer-reviewed) is a tad critical:

Our main conclusion is that Intel MPX is a promising technique that is not yet practical for widespread adoption. Intel MPX’s performance overheads are still high (~50% on average), and the supporting infrastructure has bugs which may cause compilation or runtime errors. Moreover, we showcase the design limitations of Intel MPX: it cannot detect temporal errors, may have false positives and false negatives in multithreaded code, and its restrictions
on memory layout require substantial code changes for some programs.

Also note that compared to the Lisp Machines of yore, Intel MPX is still executed inline - whereas in Lisp Machines (if my understanding is correct) bounds checks happened concurrently in hardware with a retroactive jump backwards if the check failed; thus, so-long as a running program's pointers do not point to out-of-bounds locations then there would be an absolutely zero runtime performance cost, so if you have this C code:

```<code>char arr[10];
arr[9] = 'a';
arr[8] = 'b';
</code>```

Then under MPX then this would be executed:

```<code>Time    Instruction              Notes
1       BNDMK arr, arr+9         Set bounds 0 to 9.
2       BNDCL arr                Check `arr` meets lower-bound.
3       BNDCU arr                Check `arr` meets upper-bound.
4       MOV 'a' arr+9            Assign 'a' to arr+9.
5       MOV 'a' arr+8            Assign 'a' to arr+8.
</code>```

But on a Lisp machine (if it were magically possible to compile C to Lisp...), then the program-reader-hardware in the computer has the ability to execute additional "side" instructions concurrently with the "actual" instructions, allowing the "side" instructions to instruct the computer to disregard the results from the "actual" instructions in the event of an error:

```<code>Time    Actual instruction    Side instruction
1       MOV 'A' arr+9         ENSURE arr+9 BETWEEN arr, arr+9
2       MOV 'A' arr+8         ENSURE arr+8 BETWEEN arr, arr+9
</code>```

I understand the instructions-per-cycle for the "side" instructions are not the same as the "Actual" instructions - so the side-check for the instruction at Time=1 might only complete after the "Actual" instructions have already progressed on to Time=3 - but if the check failed then it would pass the instruction pointer of the failed instruction to the exception handler that would direct the program to disregard the results of the instructions executed after Time=1. I don't know how they could achieve that without massive amounts of memory or some mandatory execution pauses, possibly memory-fencing too -
that's outside the scope of my answer, but it is at least theoretically possible.

(Note in this contrived example I'm using constexpr index values that a compiler can prove will never be out-of-bounds so would omit the MPX checks entirely - so pretend they're user-supplied variables instead :) ).

I'm not an expert in x86 (or have any experience in microprocessor design, spare a CS500-level course I took at UW and didn't do the homework for...) but I don't believe concurrent execution of bounds-checks nor "time travel" is possible with x86's current design, despite the extant implementation of out-of-order execution - I might be wrong, however. I speculate that if all pointer-types were promoted to 3-tuples ( struct BoundedPointer<T> { T* ptr, T* min, T* max } - which technically already happens with MPX and other software-based bounds-checks as every guarded pointer has its bounds defined when BNDMK is called) then the protection could be provided for free by the MMU - but now pointers will consume 24 bytes of memory, each, instead of the current 8 bytes - or compare to the measly 4 bytes under 32-bit x86 - RAM is plentiful, but still a finite resource that shouldn't be wasted.

MPX in GCC

GCC supported for MPX from version 5.0 to 9.1 ( https://gcc.gnu.org/wiki/Intel%20MPX%20support%20in%20the%20GCC%20compiler ) when it was removed due to its maintenance burden.

MPX in Visual Studio / Visual C++

Visual Studio 2015 Update 1 (2015.1) added "experimental" support for MPX with the /d2MPX switch ( https://blogs.msdn.microsoft.com/vcblog/2016/01/20/visual-studio-2015-update-1-new-experimental-feature-mpx/ ). Support is still present in Visual Studio 2017 but Microsoft has not announced if it's considered a mainstream (i.e. non-experimental) feature yet.

MPX in Clang / LLVM

Clang has partially supported manual use of MPX in the past, but that support was fully removed in version 10.0

As of July 2021, LLVM still seems capable of outputting MPX instructions, but I can't see any evidence of an MPX "pass".

MPX in Intel C/C++ Compiler

The Intel C/C++ Compiler has supported MPX since version 15.0.

Body:
Yes.

Decades ago, Lisp machines performed simultaneous validation checks (e.g. type checks and bounds checks) as the program ran with the assumption the program and state were valid, jumping "back in time" if the check failed - unfortunately this ability to get "free" runtime validation was lost when conventional (i.e. x86) machines became dominant.

https://en.wikipedia.org/wiki/Lisp_machine

Lisp Machines ran the tests in parallel with the more conventional single instruction additions. If the simultaneous tests failed, then the result was discarded and recomputed; this meant in many cases a speed increase by several factors. This simultaneous checking approach was used as well in testing the bounds of arrays when referenced, and other memory management necessities (not merely garbage collection or arrays).

Fortunately we're finally learning from the past and slowly, and by piecemeal, reintroducing those innovations - Intel's "MPX" (Memory Protection eXtensions) for x86 were introduced in Skylake-generation processors for hardware bounds-checking - though it isn't perfect.

(x86 is a regression in other ways too: IBM's mainframes had true hardware-accelerated system virtualization in the 1980s - we didn't get it on x86 until 2005 with Intel's "VT-x" and AMD's "AMD-V" extensions).

x86 BOUND

Technically, x86 does have hardware bounds-checking: the the BOUND instruction was introduced in 1982 in the Intel 80188 (as well as the Intel 286 and above, but not the Intel 8086, 8088 or 80186 processors).

While the BOUND instruction does provide hardware bounds-checking, I understand it indirectly caused performance issues because it breaks the hardware branch predictor (according to a Reddit thread, but I'm unsure why), but also because it requires the bounds to be specified in a tuple in memory - that's terrible for performance - I understand at runtime it's no faster than manually having the instructions to do an "if index not in range [x,y] then signal the BR exception to the program or OS" (so you might imagine the BOUND instruction was added for the convenience of people who coded assembly by-hand, which was quite common in the 1980s).

The BOUND instruction is still present in today's processors, but it was not included in AMD64 (x64) - likely for the performance reasons I explained above, and also because likely very few people were using it (and compilers could trivially replace it with a manual bounds check, that might have better performance anyway, as that could use registers).

Another disadvantage to storing the array bounds in memory is that code elsewhere (that wasn't subject to BOUNDS checking) could overwrite the previously written bounds for another pointer and circumvent the check that way - this is mostly a problem with code that intentionally tries to disable safety features (i.e. malware), but if the bounds were stored in the stack - and given how easy it is to corrupt the stack, it has even less utility.

Intel MPX

Intel MPX was introduced in Skylake architecture in 2015 and should be present in all Skylake and subsequent processor models in the mainstream Intel Core family (including Xeon, and non-SoC versions of Celeron and Pentium). Intel also implemented MPX in the Goldmont architecture (Atom, and SoC versions of Celeron and Pentium) from 2016 onwards.

MPX is superior to BOUND in that it provides dedicated registers to store the bounds range so the bounds-check should be almost zero-cost compared to BOUND which required a memory access. On the Intel 486 the BOUND instruction takes 7 cycles (compare to CMP which takes only 2 cycles even if the operand was a memory address). In Skylake the MPX equivalent (BNDMK, BNDCL and BNDCU) are all 1-cycle instructions and BNDMK can be amortized as it only needs to be called once for each new pointer).

I cannot find any information on wherever or not AMD has implemented their own version of MPX yet (as of June 2017).

Critical thoughts on MPX

Unfortunately the current state of MPX is not all that rosy - a recent paper by Oleksenko, Kuvaiskii, et al. in February 2017 "Intel MPX Explained" (PDF link: caution: not yet peer-reviewed) is a tad critical:

Our main conclusion is that Intel MPX is a promising technique that is not yet practical for widespread adoption. Intel MPX’s performance overheads are still high (~50% on average), and the supporting infrastructure has bugs which may cause compilation or runtime errors. Moreover, we showcase the design limitations of Intel MPX: it cannot detect temporal errors, may have false positives and false negatives in multithreaded code, and its restrictions
on memory layout require substantial code changes for some programs.

Also note that compared to the Lisp Machines of yore, Intel MPX is still executed inline - whereas in Lisp Machines (if my understanding is correct) bounds checks happened concurrently in hardware with a retroactive jump backwards if the check failed; thus, so-long as a running program's pointers do not point to out-of-bounds locations then there would be an absolutely zero runtime performance cost, so if you have this C code:

char arr[10];
arr[9] = 'a';
arr[8] = 'b';

Then under MPX then this would be executed:

Time    Instruction              Notes
1       BNDMK arr, arr+9         Set bounds 0 to 9.
2       BNDCL arr                Check `arr` meets lower-bound.
3       BNDCU arr                Check `arr` meets upper-bound.
4       MOV 'a' arr+9            Assign 'a' to arr+9.
5       MOV 'a' arr+8            Assign 'a' to arr+8.

But on a Lisp machine (if it were magically possible to compile C to Lisp...), then the program-reader-hardware in the computer has the ability to execute additional "side" instructions concurrently with the "actual" instructions, allowing the "side" instructions to instruct the computer to disregard the results from the "actual" instructions in the event of an error:

Time    Actual instruction    Side instruction
1       MOV 'A' arr+9         ENSURE arr+9 BETWEEN arr, arr+9
2       MOV 'A' arr+8         ENSURE arr+8 BETWEEN arr, arr+9

I understand the instructions-per-cycle for the "side" instructions are not the same as the "Actual" instructions - so the side-check for the instruction at Time=1 might only complete after the "Actual" instructions have already progressed on to Time=3 - but if the check failed then it would pass the instruction pointer of the failed instruction to the exception handler that would direct the program to disregard the results of the instructions executed after Time=1. I don't know how they could achieve that without massive amounts of memory or some mandatory execution pauses, possibly memory-fencing too -
that's outside the scope of my answer, but it is at least theoretically possible.

(Note in this contrived example I'm using constexpr index values that a compiler can prove will never be out-of-bounds so would omit the MPX checks entirely - so pretend they're user-supplied variables instead :) ).

I'm not an expert in x86 (or have any experience in microprocessor design, spare a CS500-level course I took at UW and didn't do the homework for...) but I don't believe concurrent execution of bounds-checks nor "time travel" is possible with x86's current design, despite the extant implementation of out-of-order execution - I might be wrong, however. I speculate that if all pointer-types were promoted to 3-tuples ( struct BoundedPointer<T> { T* ptr, T* min, T* max } - which technically already happens with MPX and other software-based bounds-checks as every guarded pointer has its bounds defined when BNDMK is called) then the protection could be provided for free by the MMU - but now pointers will consume 24 bytes of memory, each, instead of the current 8 bytes - or compare to the measly 4 bytes under 32-bit x86 - RAM is plentiful, but still a finite resource that shouldn't be wasted.

MPX in GCC

GCC supported for MPX from version 5.0 to 9.1 ( https://gcc.gnu.org/wiki/Intel%20MPX%20support%20in%20the%20GCC%20compiler ) when it was removed due to its maintenance burden.

MPX in Visual Studio / Visual C++

Visual Studio 2015 Update 1 (2015.1) added "experimental" support for MPX with the /d2MPX switch ( https://blogs.msdn.microsoft.com/vcblog/2016/01/20/visual-studio-2015-update-1-new-experimental-feature-mpx/ ). Support is still present in Visual Studio 2017 but Microsoft has not announced if it's considered a mainstream (i.e. non-experimental) feature yet.

MPX in Clang / LLVM

Clang has partially supported manual use of MPX in the past, but that support was fully removed in version 10.0

As of July 2021, LLVM still seems capable of outputting MPX instructions, but I can't see any evidence of an MPX "pass".

MPX in Intel C/C++ Compiler

The Intel C/C++ Compiler has supported MPX since version 15.0.

ContentLicense: CC BY-SA 4.0


问:
Iterate a Linq Expression and convert it into DB parameter
How i can iterate a Linq Expression and convert it into DB parameter so that i can avoid passing multiple parameter as input to the DAL method

Business Layer:
 In BL i have code like this

```<code>  database.GetProduct(a => a.ProductType == "tea" || a.Price <= 5);
</code>```

In DAL i use plain ADO.Net and want to convert the expression whatever i returned from BL to ADO.Net parameters

Data Access Layer:

```<code> public DataSet GetProduct(Expression<Func<Product, bool>> pred)
 {

    step 1:
          Iterate the predicate and create new sqlparameter.
    step 2:
      return database.ExecuteDataset(parameters)
 }
</code>```

How i  can iterate "pred" & convert it to SQLParameter

答: You need to look into using the visitor pattern on your expression so you can walk through the expression tree you generate to determine which members to project as parameters.  The IQToolkit  project has a nice ExpressionVisitor base class that you could find useful as a base implemenation of the visitor pattern. You could subclass that to handle the VisitMemberAccess specifically to deal with your properties.

Body:
How i can iterate a Linq Expression and convert it into DB parameter so that i can avoid passing multiple parameter as input to the DAL method

Business Layer:
 In BL i have code like this

  database.GetProduct(a => a.ProductType == "tea" || a.Price <= 5);

In DAL i use plain ADO.Net and want to convert the expression whatever i returned from BL to ADO.Net parameters

Data Access Layer:

 public DataSet GetProduct(Expression<Func<Product, bool>> pred)
 {

    step 1:
          Iterate the predicate and create new sqlparameter.
    step 2:
      return database.ExecuteDataset(parameters)
 }

How i  can iterate "pred" & convert it to SQLParameter


问:
How to pass Multiple Class Object in $http Request
My requirement is to pass multiple class object(which is going to map with request param or request body in rest controller) in angular $http service.

I can't pass class object in request body since one http call has only one request body.

When i'm trying to pass class object in $http param I'm getting class cast exception.

is there any way to pass multiple object in single $http call ??

```<code>@RequestMapping(value = "CommitObject", method = RequestMethod.POST)
public void Commit(@RequestParam(value = "clazz") final String clazz,
        @RequestParam(value = "Id") final String modelId,@RequestBody LinkedHashMap<String, Object> obj) {
    mService.Commit(Id,clazz workingmodelObj);
}
</code>```

答:
If you're trying to make a $http.post request you can make an array of the objects you are trying to send and then attach it in the request.

$http.put('ROUTE HERE', Array Of Objects);

Body:
My requirement is to pass multiple class object(which is going to map with request param or request body in rest controller) in angular $http service.

I can't pass class object in request body since one http call has only one request body.

When i'm trying to pass class object in $http param I'm getting class cast exception.

is there any way to pass multiple object in single $http call ??

@RequestMapping(value = "CommitObject", method = RequestMethod.POST)
public void Commit(@RequestParam(value = "clazz") final String clazz,
        @RequestParam(value = "Id") final String modelId,@RequestBody LinkedHashMap<String, Object> obj) {
    mService.Commit(Id,clazz workingmodelObj);
}


问:
Adding Fragaria framework to Xcode
I am trying to install the latest version of mugginsoft's Fragaria framework. My project already has some CocoaPods and static C libraries, the project targets macOS 10.12 and is written in Objective-C.

I cloned the repo from github, but it turned out there was no install guide. I did exactly what the other question on SO suggested:

Build the framework from source. I did so by opening the .xcodeproj file, changing target to Fragaria framework, choosing Product->Build For->Running and copying the resulting .framework file to a known location from the DerivedData location Xcode put it in.

Project->Targets->My Target->General->Linked Frameworks & Libraries->Other->Choose Fragaria.framework

Add it to copy files build phase, copying to Frameworks directory

It did not work. Although the .framework file could be seen inside the Frameworks folder with all its headers and the views from the framework are recognised in IB, building the project yields a disappointing Fragaria/Fragaria.h not found.

What do I do wrong?

答: I eventually resorted to using a custom Fragaria podspec, which can be found on CocoaPods' macOS app github repository.</p>

Title: Adding Fragaria framework to Xcode


问:
Inheritance and Threads to modify super values
```<code>public class Vehicle extends Thread implements Serializable{

   private int gas;

   public Vehicle(int gas){
       this.gas = gas;
   }
}//Vehicle

public class Car extends Vehicle{

   private int brakes;

   public Car(int fuel, int brakes){
       super(fuel)
       this.brakes = brakes;
   }

   @Override
   public void run(){
       //code here
   }
}//Car
</code>```

My question is, since this is a Thread and I need to modify some values from the super class(the gas), is there any way to do it in the run method? As far as I know, the only way is making an instance but I can't do it there

The idea is to reduce the fuel level while the car is moving

As well, the serializable implement will work if I try to write a Car object into a file, or the car is the one that needs to extends from serializable?

This is just an example, I also have another class called Bus and both of them have different run methods, Just saving some code

答:
You can modify the code like, really sorry for the bad formatting.

Introduce a setter method for fuel in the vehicle class and invoke it from the sub class run method.

Can think about making the vehicle class Runnable, if you do not want to persist all the thread related information while serializing the objects.

In order to serialize the super class instance variables you have to mark the Vehicle class implements serializable.

public class Vehicle implements Serializable
{
private int fuel;

```<code>   public Vehicle(int fuel){
       this.fuel = fuel;
   }

protected void setFuel (int fuel){
    this.fuel = fuel;
}
</code>```

}//Vehicle

Now car extends vehicle and implements Runnable

public class Car extends Vehicle implements Runnable{

private int brakes;

```<code>   public Car(int fuel, int brakes){
       super(fuel)
       this.brakes = brakes;
   }

   @Override
   public void run(){
       //code here
       setFuel(fuel-1); // update the fuel value
   }
}//Car
</code>```

There is a nice and crisp explanation about serialization in this question.

Are static variables serialized in Serialization process

Body:
public class Vehicle extends Thread implements Serializable{

   private int gas;

   public Vehicle(int gas){
       this.gas = gas;
   }
}//Vehicle

public class Car extends Vehicle{

   private int brakes;

   public Car(int fuel, int brakes){
       super(fuel)
       this.brakes = brakes;
   }

   @Override
   public void run(){
       //code here
   }
}//Car

My question is, since this is a Thread and I need to modify some values from the super class(the gas), is there any way to do it in the run method? As far as I know, the only way is making an instance but I can't do it there

The idea is to reduce the fuel level while the car is moving

As well, the serializable implement will work if I try to write a Car object into a file, or the car is the one that needs to extends from serializable?

This is just an example, I also have another class called Bus and both of them have different run methods, Just saving some code

Body:
You can modify the code like, really sorry for the bad formatting.

Introduce a setter method for fuel in the vehicle class and invoke it from the sub class run method.

Can think about making the vehicle class Runnable, if you do not want to persist all the thread related information while serializing the objects.

In order to serialize the super class instance variables you have to mark the Vehicle class implements serializable.

public class Vehicle implements Serializable
{
private int fuel;

   public Vehicle(int fuel){
       this.fuel = fuel;
   }

protected void setFuel (int fuel){
    this.fuel = fuel;
}

}//Vehicle

Now car extends vehicle and implements Runnable

public class Car extends Vehicle implements Runnable{

private int brakes;

   public Car(int fuel, int brakes){
       super(fuel)
       this.brakes = brakes;
   }

   @Override
   public void run(){
       //code here
       setFuel(fuel-1); // update the fuel value
   }
}//Car

There is a nice and crisp explanation about serialization in this question.

Are static variables serialized in Serialization process


问:
Using 24.01 Android gradle error
I got this error because of lower version in SDK.

```<code> Manifest merger failed : Attribute
 meta-data#android.support.VERSION@value value=(25.3.1) from
 [com.android.support:recyclerview-v7:25.3.1]
 AndroidManifest.xml:24:9-31 is also present at
 [com.android.support:appcompat-v7:26.0.0-alpha1]
 AndroidManifest.xml:27:9-38 value=(26.0.0-alpha1). Suggestion: add
 'tools:replace="android:value"' to element at
 AndroidManifest.xml:22:5-24:34 to override.
</code>```

答: add a supported library version whatever available in your SDK. its give a suggestion in build.gradle file of your app.</p>

Title: Using 24.01 Android gradle error

Body:
I got this error because of lower version in SDK.

 Manifest merger failed : Attribute
 meta-data#android.support.VERSION@value value=(25.3.1) from
 [com.android.support:recyclerview-v7:25.3.1]
 AndroidManifest.xml:24:9-31 is also present at
 [com.android.support:appcompat-v7:26.0.0-alpha1]
 AndroidManifest.xml:27:9-38 value=(26.0.0-alpha1). Suggestion: add
 'tools:replace="android:value"' to element at
 AndroidManifest.xml:22:5-24:34 to override.


答:
You probably created your branch not from master but from your recent feature branch.
To branch from your master you must first checkout the master.

This is what I would do.

0. Example Project setup and workflow

(1) fork on github (2) Clone origin to your computer (2) Add your fork as a remote. (3) Push new branches to your fork. (4) Make pull requests from your fork to the origin master

Look up github workflow as an example of a well tested approach.

1. Keep your local master in sync to origin

Go back to your master

```<code>git checkout master
</code>```

Often it is a good idea to sync it to the origin

```<code>git pull origin master
</code>```

Make sure that everything is like expected

```<code>git log
git status
</code>```

2. branch from master

Now create your branch

```<code>git checkout -b new_branch
</code>```

3. Add commits to your branch

Now look up the commits in your original branch

```<code>git log old_branch_with_to_many_commits
</code>```

All commits have a hash. You can use those numbers to cherry-pick single commits into your new_branch. So copy the hash of first commit you want to keep into your clipboard.

Now use git cherry-pick to get single commits into your new_branch one by one

```<code>git cherry-pick a_commit_hash
...
git cherry-pick next_commit_hash
</code>```

4. Clean up your old branch

Now you might want to clean the commits from your old branch.

```<code>git checkout old_branch_with_to_many_commits
</code>```

Lookup the hash of the last commit you want to keep

```<code>git log
</code>```

Copy the hash to reset the branch

```<code>git reset --hard hash_of_the_last_commit_you_want_to_keep
</code>```

Title: New pull request without unmerged commits

Body:
I have a pull request on a repository. The commits are still unmerged. Now, I want to make another pull request, totally independent from the previous one. When I create a new branch and make the new commits, all of the unmerged commits are also alongside with the new ones!

I want to create a new pull request without the unmerged commits. Please help me on how should I do that as I'm new to git :)

Body:
You probably created your branch not from master but from your recent feature branch.
To branch from your master you must first checkout the master.

This is what I would do.

0. Example Project setup and workflow

(1) fork on github (2) Clone origin to your computer (2) Add your fork as a remote. (3) Push new branches to your fork. (4) Make pull requests from your fork to the origin master

Look up github workflow as an example of a well tested approach.

1. Keep your local master in sync to origin

Go back to your master

git checkout master

Often it is a good idea to sync it to the origin

git pull origin master

Make sure that everything is like expected

git log
git status

2. branch from master

Now create your branch

git checkout -b new_branch

3. Add commits to your branch

Now look up the commits in your original branch

git log old_branch_with_to_many_commits

All commits have a hash. You can use those numbers to cherry-pick single commits into your new_branch. So copy the hash of first commit you want to keep into your clipboard.

Now use git cherry-pick to get single commits into your new_branch one by one

git cherry-pick a_commit_hash
...
git cherry-pick next_commit_hash

4. Clean up your old branch

Now you might want to clean the commits from your old branch.

git checkout old_branch_with_to_many_commits

Lookup the hash of the last commit you want to keep

git log

Copy the hash to reset the branch

git reset --hard hash_of_the_last_commit_you_want_to_keep


问:
Targeting Xamarin Mobile Mac using VS2017-style csproj
I like the new 'msbuild pack' nuget package generation in VS2017. I would like to use it to generate a library that uses Xamarin.Mac to be consumed by Xamarin Mobile Mac projects. I tried

```<code><Project Sdk="Microsoft.NET.Sdk">

  <PropertyGroup>
    <TargetFrameworks>Xamarin.Mac</TargetFrameworks>
  </PropertyGroup>

</Project>
</code>```

but I get

```<code>Severity    Code    Description Project File    Line    Suppression State
Error       Cannot infer TargetFrameworkIdentifier and/or TargetFrameworkVersion from TargetFramework='Xamarin.Mac'. They must be specified explicitly. Kumquat.Common.Mac  C:\Program Files (x86)\Microsoft Visual Studio\2017\Professional\MSBuild\Sdks\Microsoft.NET.Sdk\build\Microsoft.NET.TargetFrameworkInference.targets    84
</code>```

This example (https://github.com/Azure/azure-mobile-apps-net-client/blob/master/src/Microsoft.Azure.Mobile.Client/Microsoft.Azure.Mobile.Client.csproj) has

```<code><TargetFrameworks>netstandard1.4;net45;MonoAndroid71;Xamarin.iOS10;uap10.0</TargetFrameworks>
</code>```

However, when I try Xamarin.iOS10 on my end, I get a similar error. Is there something special I need to install on my machine to get Xamarin.* as Target Frameworks? I do have Xamarin installed. I have VS2017 (version 15.2).

答:
The Microsoft.NET.Sdk doesn't support automatic inference for this target framework yet. As you can see in the example you linked, they add the required definitions later in the same project:

```<code><PropertyGroup Condition=" '$(TargetFramework)' == 'Xamarin.iOS10' ">
  <TargetFrameworkIdentifier>Xamarin.iOS</TargetFrameworkIdentifier>
  <TargetFrameworkVersion>v1.0</TargetFrameworkVersion>
  <LanguageTargets>$(MSBuildExtensionsPath)\Xamarin\iOS\Xamarin.iOS.CSharp.targets</LanguageTargets>
  <DefineConstants>$(DefineConstants);PLATFORM_IOS;XAMARIN_AUTH_INTERNAL</DefineConstants>
</PropertyGroup>
</code>```

The .NET Sdk has logic to infer TargetFrameworkIdentifier and TargetFrameworkVersion only for netstandard, netcoreapp and net at the moment (see the source)

Body:
I like the new 'msbuild pack' nuget package generation in VS2017. I would like to use it to generate a library that uses Xamarin.Mac to be consumed by Xamarin Mobile Mac projects. I tried

<Project Sdk="Microsoft.NET.Sdk">

  <PropertyGroup>
    <TargetFrameworks>Xamarin.Mac</TargetFrameworks>
  </PropertyGroup>

</Project>

but I get

Severity    Code    Description Project File    Line    Suppression State
Error       Cannot infer TargetFrameworkIdentifier and/or TargetFrameworkVersion from TargetFramework='Xamarin.Mac'. They must be specified explicitly. Kumquat.Common.Mac  C:\Program Files (x86)\Microsoft Visual Studio\2017\Professional\MSBuild\Sdks\Microsoft.NET.Sdk\build\Microsoft.NET.TargetFrameworkInference.targets    84

This example (https://github.com/Azure/azure-mobile-apps-net-client/blob/master/src/Microsoft.Azure.Mobile.Client/Microsoft.Azure.Mobile.Client.csproj) has

<TargetFrameworks>netstandard1.4;net45;MonoAndroid71;Xamarin.iOS10;uap10.0</TargetFrameworks>

However, when I try Xamarin.iOS10 on my end, I get a similar error. Is there something special I need to install on my machine to get Xamarin.* as Target Frameworks? I do have Xamarin installed. I have VS2017 (version 15.2).

Body:
The Microsoft.NET.Sdk doesn't support automatic inference for this target framework yet. As you can see in the example you linked, they add the required definitions later in the same project:

<PropertyGroup Condition=" '$(TargetFramework)' == 'Xamarin.iOS10' ">
  <TargetFrameworkIdentifier>Xamarin.iOS</TargetFrameworkIdentifier>
  <TargetFrameworkVersion>v1.0</TargetFrameworkVersion>
  <LanguageTargets>$(MSBuildExtensionsPath)\Xamarin\iOS\Xamarin.iOS.CSharp.targets</LanguageTargets>
  <DefineConstants>$(DefineConstants);PLATFORM_IOS;XAMARIN_AUTH_INTERNAL</DefineConstants>
</PropertyGroup>

The .NET Sdk has logic to infer TargetFrameworkIdentifier and TargetFrameworkVersion only for netstandard, netcoreapp and net at the moment (see the source)


问:
Get fields from a third model based on the foreign key of a second model
I have three models, one of which has an ID from each of the others to join them. The issue I am trying to solve is how I can get the values From table one into table three  using table two to join them in the serializer, or if that is even the approach I should be taking to begin with.

model

```<code>class ModelOne(models.Model):
    color = models.CharField()
    size = models.CharField()

class ModelTwo(models.Model):
    One_id = models.ForeignKey(ModelOne)
    Three_id = models.CharField()

class ModelThree(models.Model):
</code>```

example serializer

```<code>class ModelThree Serializer
    model = ModelThree
    fields = ('color', 'size')

def get_color(self, obj):
    ???

def get_size(self, obj):
    ???
</code>```

my db structure

```<code>        ModelOne
-------------------------------------
id  color   size

    ModelTwo
-------------------------------------
id  ModelOneID  ModelThreeID

    ModelThree
-------------------------------------
id
</code>```

答:
If I understand your question correctly, you have two models ModelOne and ModelThree which are joined by another model ModelTwo

```<code>class ModelOne(models.Model):
    color = models.CharField(max_length=200)
    size = models.CharField(max_length=200)

class ModelTwo(models.Model):
    one = models.ForeignKey(ModelOne)
    three = models.ForeignKey('ModelThree')

class ModelThree(models.Model):
    some_field = models.CharField(max_length=200)

# this looks like a ManyToMany relationship between ModelThree and ModelOne
# where ModelTwo is the intermediate model
# you may want to check the docs https://docs.djangoproject.com/en/1.11/topics/db/models/#many-to-many-relationships
</code>```

and you want to be able to query values from ModelOne into ModelThree.

If you have an instance of ModelThree m3, then you can get all related ModelOne instances by querying the other side of the foreignkey relation like so:

```<code># ex:  m3 = ModelThree.objects.first()
model_twos = m3.modeltwo_set.all()
for two in model_twos:
   print two.one.color, two.one.size
</code>```

Body:
I have three models, one of which has an ID from each of the others to join them. The issue I am trying to solve is how I can get the values From table one into table three  using table two to join them in the serializer, or if that is even the approach I should be taking to begin with.

model

class ModelOne(models.Model):
    color = models.CharField()
    size = models.CharField()

class ModelTwo(models.Model):
    One_id = models.ForeignKey(ModelOne)
    Three_id = models.CharField()

class ModelThree(models.Model):

example serializer

class ModelThree Serializer
    model = ModelThree
    fields = ('color', 'size')

def get_color(self, obj):
    ???

def get_size(self, obj):
    ???

my db structure

        ModelOne
-------------------------------------
id  color   size

    ModelTwo
-------------------------------------
id  ModelOneID  ModelThreeID

    ModelThree
-------------------------------------
id

Body:
If I understand your question correctly, you have two models ModelOne and ModelThree which are joined by another model ModelTwo

class ModelOne(models.Model):
    color = models.CharField(max_length=200)
    size = models.CharField(max_length=200)

class ModelTwo(models.Model):
    one = models.ForeignKey(ModelOne)
    three = models.ForeignKey('ModelThree')

class ModelThree(models.Model):
    some_field = models.CharField(max_length=200)

# this looks like a ManyToMany relationship between ModelThree and ModelOne
# where ModelTwo is the intermediate model
# you may want to check the docs https://docs.djangoproject.com/en/1.11/topics/db/models/#many-to-many-relationships

and you want to be able to query values from ModelOne into ModelThree.

If you have an instance of ModelThree m3, then you can get all related ModelOne instances by querying the other side of the foreignkey relation like so:

# ex:  m3 = ModelThree.objects.first()
model_twos = m3.modeltwo_set.all()
for two in model_twos:
   print two.one.color, two.one.size


问:
Updating SQL table values dependent on a value from an alternative table
I'll try and make this as clear as I possibly can. My structure is something like this:

Tables:

```<code>Fish
Pond
Plant
order_details
order_item
etc...
</code>```

Now what I'm trying to do is this. If an order is started but not completed within half an hour the items from that order are returned to the relevant tables. I have the ordering process set up (I have not used transaction, I just insert the order items into the order_item table).

So basically I'm saying that if order_id 1 had an order_date (date-time field) more than 3 minutes ago. Then for each item on the table update the relevant stock item based on its stock_id (i.e. fish0 will be on the fish table and plant1 will be on the plant table). I guess in pseudo code it would read something like this:

```<code>select all order_id's
from order_details
where the datetime is more than 30 minutes ago
</code>```

for each of the items with that order_id in the Order_item table

If stockid contains fish then update fish_in_stock with current qty + order qty where the stock id matches, but if the stock id is like pond then do the same on the pond table

Does this make sense? It may be something impossible. The only reason I ask is so that I can try and automate this as a stored procedure.

答:
I'm not able to add comment to your post, but here is what I see </p>

```<code>--update your order_details first
Update Order_Details set Order_Status = 'CANCELLED' where Order_Date < DATEADD(MINUTE, -15, SYSDATETIMEOFFSET()) AND Order_Status = 'OPEN'

--update the quantities second add select and () for each

Update Fish set Fish_In_Stock = (Select a.Fish_In_Stock + b.Order_Item_Qty from Fish as a, Order_Item as b, Order_Details as c where c.Order_Date < DATEADD(MINUTE, -15, SYSDATETIMEOFFSET()) and b.Stock_ID = a.Stock_ID AND b.Order_Status = 'OPEN' AND c.Order_Status = 'OPEN');

Update Plant set Plant_In_Stock = (select a.Plant_In_Stock + b.Order_Item_Qty from Plant as a, Order_Item as b, Order_Details as c where c.Order_Date < DATEADD(MINUTE, -15, SYSDATETIMEOFFSET()) and b.Stock_ID = a.Stock_ID AND b.Order_Status = 'OPEN' AND c.Order_Status = 'OPEN');

Update Pond set Pond_In_Stock = (select a.Pond_In_Stock + b.Order_Item_Qty from Pond as a, Order_Item as b, Order_Details as c where c.Order_Date < DATEADD(MINUTE, -15, SYSDATETIMEOFFSET()) and b.Stock_ID = a.Stock_ID AND b.Order_Status = 'OPEN' AND c.Order_Status = 'OPEN');

Update Food set Food_In_Stock = (select a.Food_In_Stock + b.Order_Item_Qty from Food as a, Order_Item as b, Order_Details as c where c.Order_Date < DATEADD(MINUTE, -15, SYSDATETIMEOFFSET()) and b.Stock_ID = a.Stock_ID AND b.Order_Status = 'OPEN' AND c.Order_Status = 'OPEN');

Update Pump set Pump_In_Stock = (select a.Pump_In_Stock + b.Order_Item_Qty from Pump as a, Order_Item as b, Order_Details as c where c.Order_Date < DATEADD(MINUTE, -15, SYSDATETIMEOFFSET()) and b.Stock_ID = a.Stock_ID AND b.Order_Status = 'OPEN' AND c.Order_Status = 'OPEN');

--not sure what this is for or what you are trying to do here, you should have a way to join the tables or use and outer join to select those that aren't equal to anything

Update Order_Item set Order_Status = b.Order_Status FROM Order_Item as a, Order_Details as b where b.Order_Date < DATEADD(MINUTE, -15, SYSDATETIMEOFFSET()) AND a.Order_Status <> b.Order_Status
</code>```

Body:
I'll try and make this as clear as I possibly can. My structure is something like this:

Tables:

Fish
Pond
Plant
order_details
order_item
etc...

Now what I'm trying to do is this. If an order is started but not completed within half an hour the items from that order are returned to the relevant tables. I have the ordering process set up (I have not used transaction, I just insert the order items into the order_item table).

So basically I'm saying that if order_id 1 had an order_date (date-time field) more than 3 minutes ago. Then for each item on the table update the relevant stock item based on its stock_id (i.e. fish0 will be on the fish table and plant1 will be on the plant table). I guess in pseudo code it would read something like this:

select all order_id's
from order_details
where the datetime is more than 30 minutes ago

for each of the items with that order_id in the Order_item table

If stockid contains fish then update fish_in_stock with current qty + order qty where the stock id matches, but if the stock id is like pond then do the same on the pond table

Does this make sense? It may be something impossible. The only reason I ask is so that I can try and automate this as a stored procedure.

Body:
I'm not able to add comment to your post, but here is what I see

--update your order_details first
Update Order_Details set Order_Status = 'CANCELLED' where Order_Date < DATEADD(MINUTE, -15, SYSDATETIMEOFFSET()) AND Order_Status = 'OPEN'

--update the quantities second add select and () for each

Update Fish set Fish_In_Stock = (Select a.Fish_In_Stock + b.Order_Item_Qty from Fish as a, Order_Item as b, Order_Details as c where c.Order_Date < DATEADD(MINUTE, -15, SYSDATETIMEOFFSET()) and b.Stock_ID = a.Stock_ID AND b.Order_Status = 'OPEN' AND c.Order_Status = 'OPEN');

Update Plant set Plant_In_Stock = (select a.Plant_In_Stock + b.Order_Item_Qty from Plant as a, Order_Item as b, Order_Details as c where c.Order_Date < DATEADD(MINUTE, -15, SYSDATETIMEOFFSET()) and b.Stock_ID = a.Stock_ID AND b.Order_Status = 'OPEN' AND c.Order_Status = 'OPEN');

Update Pond set Pond_In_Stock = (select a.Pond_In_Stock + b.Order_Item_Qty from Pond as a, Order_Item as b, Order_Details as c where c.Order_Date < DATEADD(MINUTE, -15, SYSDATETIMEOFFSET()) and b.Stock_ID = a.Stock_ID AND b.Order_Status = 'OPEN' AND c.Order_Status = 'OPEN');

Update Food set Food_In_Stock = (select a.Food_In_Stock + b.Order_Item_Qty from Food as a, Order_Item as b, Order_Details as c where c.Order_Date < DATEADD(MINUTE, -15, SYSDATETIMEOFFSET()) and b.Stock_ID = a.Stock_ID AND b.Order_Status = 'OPEN' AND c.Order_Status = 'OPEN');

Update Pump set Pump_In_Stock = (select a.Pump_In_Stock + b.Order_Item_Qty from Pump as a, Order_Item as b, Order_Details as c where c.Order_Date < DATEADD(MINUTE, -15, SYSDATETIMEOFFSET()) and b.Stock_ID = a.Stock_ID AND b.Order_Status = 'OPEN' AND c.Order_Status = 'OPEN');

--not sure what this is for or what you are trying to do here, you should have a way to join the tables or use and outer join to select those that aren't equal to anything

Update Order_Item set Order_Status = b.Order_Status FROM Order_Item as a, Order_Details as b where b.Order_Date < DATEADD(MINUTE, -15, SYSDATETIMEOFFSET()) AND a.Order_Status <> b.Order_Status


问:
jquery.ui tooltip: Show tooltip only after hover for a duration of time
I would like to show the tooltip over an element only if I have kept the mouse there for 1 second. If I hover for less than 1 second, the tooltip should not show. How do I accomplish this?</p>

答:
You can simply set the delay parameter which I found in the docs

The code could look like this

$(document).ready(function() {
  $('.selector').tooltip({
    show: { effect: 'slideDown', delay: 1000, duration: 250 }
  });
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/themes/smoothness/jquery-ui.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>

TEST</code>```

Body:
You can simply set the delay parameter which I found in the docs

The code could look like this

$(document).ready(function() {
  $('.selector').tooltip({
    show: { effect: 'slideDown', delay: 1000, duration: 250 }
  });
});

<link href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/themes/smoothness/jquery-ui.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>

<a href="#" class="selector" title="Tooltip with delay and duration">TEST</a>


问:
Android .Decrypt Existing Sqlite runntime in android
I need a local database for my application.I created one and i encrypted it.(I know the password).Now i want to load this db to my original application.I want to decrypte it before copy. I had a copy code like this this is working for unencrpyted db. How can I translate this for my encrypted db.Thanks</p>

```<code>private void copyDataBase() throws IOException {

//Open your local db as the input stream
InputStream myInput = myContext.getAssets().open(DB_NAME);

// Path to the just created empty db
String outFileName = DB_PATH + DB_NAME;

//Open the empty db as the output stream
OutputStream myOutput = new FileOutputStream(outFileName);

//transfer bytes from the inputfile to the outputfile
byte[] buffer = new byte[1024];
int length;
while ((length = myInput.read(buffer)) > 0) {
    myOutput.write(buffer, 0, length);
}

//Close the streams
myOutput.flush();
myOutput.close();
myInput.close();

}
</code>```

答:
Looking on the wiki on DB Browser for SQLite repo, DB Browser uses SQLCipher as a default encryption extension, so I assume that you have used the default SQLCipher extension. This means that to use that encrypted DB file on Android, you need to use SQLCipher's Android Port.

More examples and documentation can be found in their Android Repo and here.

Update:

This update explains a sample setup for using SQLiteCipher.

Add SQLCipher dependency in your application's build.gradle file:

compile net.zetetic:android-database-sqlcipher:3.5.7@aar

Initialize SQLCipher's native library before performing any db ops by calling:
net.sqlcipher.database.SQLiteDatabase.loadLibs(context)

(optional, recommended) Create an implementation of:
net.sqlcipher.database.SQLiteOpenHelper or, better yet, make your existing SQLiteOpenHelper extend from this class

Then whenever you request a database (getReadableDatabase() or getWriteableDatabase()), supply your encryption password with it, e.g.,

SQLiteDatabase db = helper.getReadableDatabase(_PASSWORD_)

See more details on this gist.

Also, in your case you need to copy the encrypted database from the raw assets folder to the path returned by calling Context.getDatabasePath() for the first time your app is run.

Hope this explains the things to you,

Regards

Body:
I need a local database for my application.I created one and i encrypted it.(I know the password).Now i want to load this db to my original application.I want to decrypte it before copy. I had a copy code like this this is working for unencrpyted db. How can I translate this for my encrypted db.Thanks

private void copyDataBase() throws IOException {

//Open your local db as the input stream
InputStream myInput = myContext.getAssets().open(DB_NAME);

// Path to the just created empty db
String outFileName = DB_PATH + DB_NAME;

//Open the empty db as the output stream
OutputStream myOutput = new FileOutputStream(outFileName);

//transfer bytes from the inputfile to the outputfile
byte[] buffer = new byte[1024];
int length;
while ((length = myInput.read(buffer)) > 0) {
    myOutput.write(buffer, 0, length);
}

//Close the streams
myOutput.flush();
myOutput.close();
myInput.close();

}


问:
What could be the reason? Azure SAS token request going as http instead of https
I am testing whether my Azure SAS token is working or not in the production environment. I have created C# code to test the same.

```<code>class Program
{
    static void Main(string[] args)
    {

        var storageAccount = new StorageAccount();

        //Configure Storage Account and get the reference of a newly created table
        try
        {
            var cloudTableReference = storageAccount.CloudTableInstance;

            if (cloudTableReference != null)
            {
                Console.WriteLine("Table {0} created successfully using SAS token", cloudTableReference.Name);
            }
            else
            {
                Console.WriteLine("There is an error in new table creation");
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine("Error is:  - {0}", ex.Message);
        }
    }
}
</code>```

And below is the StorageAccount.cs

```<code>class StorageAccount
{
    private CloudStorageAccount CloudStorageAccount { get; set; }
    private CloudTableClient CloudTableClient { get; set; }
    private CloudTable CloudTable { get; set; }

    /// <summary>
    /// Fetches Storage Account connection string from App.Config and returns a CloudTableClient object.
    /// </summary>
    /// <returns>CloudTableClient</returns>
    public CloudTableClient ConfigureStorageAccount()
    {
        // Retrieve the storage account from the connection string.
        if (ConfigurationManager.AppSettings["StorageConnectionString"] != string.Empty)
        {
            CloudStorageAccount = CloudStorageAccount.Parse(
                ConfigurationManager.AppSettings["StorageConnectionString"]);

            try
            {
                CloudTableClient = CloudStorageAccount.CreateCloudTableClient();
                return CloudTableClient;
            }
            catch (Exception exception)
            {
                Console.WriteLine(exception.Message);
                return null;
            }
        }

        var storageCred = new StorageCredentials(ConfigurationManager.AppSettings["SASToken"]);
        try
        {
            CloudTableClient = new CloudTableClient(
                new StorageUri(new Uri(ConfigurationManager.AppSettings["StorageAccountUri"])), storageCred);
            return CloudTableClient;
        }
        catch (Exception exception)
        {
            Console.WriteLine(exception.Message);
            return null;
        }
    }
    /// <summary>
    /// Returns a CloudTable instance for a Table
    /// </summary>
    public CloudTable CloudTableInstance
    {
        get
        {
            try
            {
                ConfigureStorageAccount();
                CloudTable = CloudTableClient.GetTableReference("ProdTestTable");
                CloudTable.Create();
                return CloudTable;
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                return null;
            }
        }
    }
}
</code>```

App.config

```<code><?xml version="1.0" encoding="utf-8" ?>
<configuration>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6.1" />
</startup>
<appSettings>
<add key="SASToken" value="SAS_TOKEN_VALUE" />
<add key="StorageAccountUri" value="URI"/>
</appSettings>
<system.net>
<defaultProxy useDefaultCredentials="true">
  <proxy proxyaddress="http://XXX.XX.X.XXX"/>
</defaultProxy>
</system.net>
</configuration>
</code>```

I run this code on an App server which doesn't have internet access so I have specified the proxy in the app.config file. It runs smoothly till this point, but the request generated from App server reaches proxy as an HTTP one instead of HTTPS. My SAS token spr parameter is https. Can anyone point out to the possible error?

答:
but the request generated from App server reaches proxy as an HTTP one instead of HTTPS.

I can't reproduce the issue on my side. I used Fiddler as my proxy.

```<code><system.net>
  <defaultProxy useDefaultCredentials="true">
    <proxy proxyaddress="http://127.0.0.1:8888"/>
  </defaultProxy>
</system.net>
</code>```

After run your code, I can see that the request URL in fiddler is start with https.

if (ConfigurationManager.AppSettings["StorageConnectionString"] != string.Empty)

I am confused by this code. It will be null and throw an exception later if I don't set StorageConnectionString value in app setting.  I need to configure it as empty string in app setting.

```<code><add key="StorageConnectionString" value=""/>
</code>```

Please check this configuration in your app.config, if you set a connection string with HTTP protocol instead of SASToken.

In addition, you also could disable the HTTP request temporarily from your Storage server by changing secure transfer required property on Azure portal. If the creating table operation also works fine. It will prove that the transfer protocol is HTTPS.

Body:
I am testing whether my Azure SAS token is working or not in the production environment. I have created C# code to test the same.

class Program
{
    static void Main(string[] args)
    {

        var storageAccount = new StorageAccount();

        //Configure Storage Account and get the reference of a newly created table
        try
        {
            var cloudTableReference = storageAccount.CloudTableInstance;

            if (cloudTableReference != null)
            {
                Console.WriteLine("Table {0} created successfully using SAS token", cloudTableReference.Name);
            }
            else
            {
                Console.WriteLine("There is an error in new table creation");
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine("Error is:  - {0}", ex.Message);
        }
    }
}

And below is the StorageAccount.cs

class StorageAccount
{
    private CloudStorageAccount CloudStorageAccount { get; set; }
    private CloudTableClient CloudTableClient { get; set; }
    private CloudTable CloudTable { get; set; }

    ///
    /// Fetches Storage Account connection string from App.Config and returns a CloudTableClient object.
    ///
    /// <returns>CloudTableClient</returns>
    public CloudTableClient ConfigureStorageAccount()
    {
        // Retrieve the storage account from the connection string.
        if (ConfigurationManager.AppSettings["StorageConnectionString"] != string.Empty)
        {
            CloudStorageAccount = CloudStorageAccount.Parse(
                ConfigurationManager.AppSettings["StorageConnectionString"]);

            try
            {
                CloudTableClient = CloudStorageAccount.CreateCloudTableClient();
                return CloudTableClient;
            }
            catch (Exception exception)
            {
                Console.WriteLine(exception.Message);
                return null;
            }
        }

        var storageCred = new StorageCredentials(ConfigurationManager.AppSettings["SASToken"]);
        try
        {
            CloudTableClient = new CloudTableClient(
                new StorageUri(new Uri(ConfigurationManager.AppSettings["StorageAccountUri"])), storageCred);
            return CloudTableClient;
        }
        catch (Exception exception)
        {
            Console.WriteLine(exception.Message);
            return null;
        }
    }
    ///
    /// Returns a CloudTable instance for a Table
    ///
    public CloudTable CloudTableInstance
    {
        get
        {
            try
            {
                ConfigureStorageAccount();
                CloudTable = CloudTableClient.GetTableReference("ProdTestTable");
                CloudTable.Create();
                return CloudTable;
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                return null;
            }
        }
    }
}

App.config

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6.1" />
</startup>
<appSettings>
<add key="SASToken" value="SAS_TOKEN_VALUE" />
<add key="StorageAccountUri" value="URI"/>
</appSettings>
<system.net>
<defaultProxy useDefaultCredentials="true">
  <proxy proxyaddress="http://XXX.XX.X.XXX"/>
</defaultProxy>
</system.net>
</configuration>

I run this code on an App server which doesn't have internet access so I have specified the proxy in the app.config file. It runs smoothly till this point, but the request generated from App server reaches proxy as an HTTP one instead of HTTPS. My SAS token spr parameter is https. Can anyone point out to the possible error?

Body:
but the request generated from App server reaches proxy as an HTTP one instead of HTTPS.

I can't reproduce the issue on my side. I used Fiddler as my proxy.

<system.net>
  <defaultProxy useDefaultCredentials="true">
    <proxy proxyaddress="http://127.0.0.1:8888"/>
  </defaultProxy>
</system.net>

After run your code, I can see that the request URL in fiddler is start with https.

if (ConfigurationManager.AppSettings["StorageConnectionString"] != string.Empty)

I am confused by this code. It will be null and throw an exception later if I don't set StorageConnectionString value in app setting.  I need to configure it as empty string in app setting.

<add key="StorageConnectionString" value=""/>

Please check this configuration in your app.config, if you set a connection string with HTTP protocol instead of SASToken.

In addition, you also could disable the HTTP request temporarily from your Storage server by changing secure transfer required property on Azure portal. If the creating table operation also works fine. It will prove that the transfer protocol is HTTPS.


答:
You can pass Objects by appending it in formData

Angular side

```<code>var formData=new FormData();
formData.append("obj1",new Blob([JSON.stringify(obj1)],{type: "application/json"}));
formData.append("obj2",new Blob([JSON.stringify(obj2)],{type: "application/json"}));
http({
     method: 'POST',
     url: '/MyProject/requestUrl',
     headers: { 'Content-Type': undefined},//to set boundary value by default
     data: formData,
    })
</code>```

Spring side

```<code>@RequestMapping(value = { "/requestUrl" }, consumes = { "multipart/form-data" }, method = RequestMethod.POST)
@ResponseBody
public String getRequest(@RequestPart("obj1") Object1 object1,
        @RequestPart("obj2") Object2 Object2,HttpSession session)
        throws IOException {

        //implementation
}
</code>```

Title: How to pass Multiple Class Object in $http Request

Body:
You can pass Objects by appending it in formData

Angular side

var formData=new FormData();
formData.append("obj1",new Blob([JSON.stringify(obj1)],{type: "application/json"}));
formData.append("obj2",new Blob([JSON.stringify(obj2)],{type: "application/json"}));
http({
     method: 'POST',
     url: '/MyProject/requestUrl',
     headers: { 'Content-Type': undefined},//to set boundary value by default
     data: formData,
    })

Spring side

@RequestMapping(value = { "/requestUrl" }, consumes = { "multipart/form-data" }, method = RequestMethod.POST)
@ResponseBody
public String getRequest(@RequestPart("obj1") Object1 object1,
        @RequestPart("obj2") Object2 Object2,HttpSession session)
        throws IOException {

        //implementation
}


问:
Is it possible for Eclipse to only open one JFrame?
When run the project second time, can the previous JFrame closed before open the new one ?

So I no need to close the JFrame when trying to run the project second time.

Is it possible to open only one JFrame?

答:
Select the Terminate and Relaunch command [ Terminate and Relaunch ] to first terminate the selected debug target and secondly, relaunch it.

Once a launch is terminated it can be automatically removed from the Debug View. To change this setting use the  Opens the Launching preference page Run/Debug > Launching preference page.


问:
how to open .pdf file form android file path appended to Google Docs View
i am using InAppBrower to open pdf file it is not supporting the .pdf file so i choose to use gview for supporting it

My file path file:///data/user/0/com.schneider.and/files/Attendance_Policy_Ver_1.0.pdf

here is my code for inappbrower

```<code>//the below code works file
// var url = https://docs.google.com/gview?embedded=true&url=http://unec.edu.az/application/uploads/2014/12/pdf-sample.pdf

//the below code is not working showing blank screen
    var url = https://docs.google.com/gview?embedded=true&url=file:///data/user/0/com.schneider.and/files/Attendance_Policy_Ver_1.0.pdf ;

//my inappbrowser code
    const browser = this.iab.create(url, '_blank', 'location=yes
,EnableViewPortScale=yes');
</code>```

i am getting blank screen in my inappbrowser window.

答:
First of all refer this answer on launching pdf files in Inappbrowser in Android.

I think you cannot give your local file path in that way.

InAppBrowser is supported for web content mostly. its in a way similar to Androids WebView.

Quoting from Inappbrowser - Apache Cordova,

You can show helpful articles, videos, and web resources inside of your app. Users can view web pages without leaving your app.

The InAppBrowser window behaves like a standard web browser, and can't access Cordova APIs. For this reason, the InAppBrowser is recommended if you need to load third-party (untrusted) content

Do check this format for opening Local URIs (HTML pages).

You can use ngCordova-FileOpener2 for opening files (including pdf) from the device storage. This uses default application for opening particular type of file.

Working code snippet -

```<code><body >
    <ion-pane>
      <ion-header-bar class="bar-stable">
        <h1 class="title">Ionic Blank Starter</h1>
      </ion-header-bar>
      <ion-content ng-controller="FileOpenerController">
        <button class="button button-full button-positive" ng-click="openPDF()">
          Open PDF File
        </button>
      </ion-content>
    </ion-pane>
</body>
</code>```

Then in JavaScript file use this -

```<code>app.controller('FileOpenerController', function($scope, $cordovaFileOpener2, $ionicPlatform) {

    $scope.openPDF= function() {
        $cordovaFileOpener2.open(
            '/sdcard/Download/109.pdf',
            'application/pdf'
        ).then(function() {
            console.log('Success');
        }, function(err) {
        console.log('An error occurred: ' + JSON.stringify(err));
        });
    };
});
</code>```

Full tutorial along with the code can be found here.

Body:
i am using InAppBrower to open pdf file it is not supporting the .pdf file so i choose to use gview for supporting it

My file path file:///data/user/0/com.schneider.and/files/Attendance_Policy_Ver_1.0.pdf

here is my code for inappbrower

//the below code works file
// var url = https://docs.google.com/gview?embedded=true&url=http://unec.edu.az/application/uploads/2014/12/pdf-sample.pdf

//the below code is not working showing blank screen
    var url = https://docs.google.com/gview?embedded=true&url=file:///data/user/0/com.schneider.and/files/Attendance_Policy_Ver_1.0.pdf ;

//my inappbrowser code
    const browser = this.iab.create(url, '_blank', 'location=yes
,EnableViewPortScale=yes');

i am getting blank screen in my inappbrowser window.

Body:
First of all refer this answer on launching pdf files in Inappbrowser in Android.

I think you cannot give your local file path in that way.

InAppBrowser is supported for web content mostly. its in a way similar to Androids WebView.

Quoting from Inappbrowser - Apache Cordova,

You can show helpful articles, videos, and web resources inside of your app. Users can view web pages without leaving your app.

The InAppBrowser window behaves like a standard web browser, and can't access Cordova APIs. For this reason, the InAppBrowser is recommended if you need to load third-party (untrusted) content

Do check this format for opening Local URIs (HTML pages).

You can use ngCordova-FileOpener2 for opening files (including pdf) from the device storage. This uses default application for opening particular type of file.

Working code snippet -

<body >
    <ion-pane>
      <ion-header-bar class="bar-stable">
        <h1 class="title">Ionic Blank Starter</h1>
      </ion-header-bar>
      <ion-content ng-controller="FileOpenerController">
        <button class="button button-full button-positive" ng-click="openPDF()">
          Open PDF File
        </button>
      </ion-content>
    </ion-pane>
</body>

Then in JavaScript file use this -

app.controller('FileOpenerController', function($scope, $cordovaFileOpener2, $ionicPlatform) {

    $scope.openPDF= function() {
        $cordovaFileOpener2.open(
            '/sdcard/Download/109.pdf',
            'application/pdf'
        ).then(function() {
            console.log('Success');
        }, function(err) {
        console.log('An error occurred: ' + JSON.stringify(err));
        });
    };
});

Full tutorial along with the code can be found here.


问:
Retrieving Data in MongoDB
```<code>{
    "ID" : 7,
    "vendor" : "Gold's Gym",
    "savings" : 50,
    "value" : 300,
    "description" : "Get a 3 month membership for $250 ($300 value)",
    "terms" : "Non transferrable",
    "product" : "Membership",
    "expires" : {
            "year" : 2017,
            "month" : 7,
            "date" : 31
    },
    "code" : "GYM-1",
    "tags" : [
            "fitness"
    ]
},
{
    "ID" : 8,
    "vendor" : "Golds Gym",
    "discount" : 15,
    "description" : "Get 15% discount on fitness classes",
    "terms" : "Non transferrable",
    "exceptions" : "Not applicable to swimming classes",
    "product" : "Classes",
    "purchaseValidity" : {
            "year" : 2017,
            "month" : 7,
            "date" : 31
    },
    "expires": {
            "year" : 2017,
            "month" : 12,
            "date" : 31
    },
    "code" : "GYM-2",
    "tags" : [
            "fitness"
    ]
}
</code>```

This is part of a lager code. However,  I want to retrieve the data items with tag: fitness  that offer discounts:  $gte 10 or savings above 10

This is what I started working with, however I cant find the syntax to work with both discounts and fitness

```<code>items.find({tags: "fitness"}, {discount: {$gte: 10}}).pretty()
</code>```

答:
You Can Do it like this :-

1.$elemMatch used for match in arrays.

2.$and in by Default in query.

```<code>items.find({ tags:{  $elemMatch:{$eq: "fitness"}} ,
             $or:[  {discount: {$gte: 10}},
                    {savings: {$gte: 10}}
                 ] })
</code>```

Thanks.

Title: Retrieving Data in MongoDB

Body:
{
    "ID" : 7,
    "vendor" : "Gold's Gym",
    "savings" : 50,
    "value" : 300,
    "description" : "Get a 3 month membership for $250 ($300 value)",
    "terms" : "Non transferrable",
    "product" : "Membership",
    "expires" : {
            "year" : 2017,
            "month" : 7,
            "date" : 31
    },
    "code" : "GYM-1",
    "tags" : [
            "fitness"
    ]
},
{
    "ID" : 8,
    "vendor" : "Golds Gym",
    "discount" : 15,
    "description" : "Get 15% discount on fitness classes",
    "terms" : "Non transferrable",
    "exceptions" : "Not applicable to swimming classes",
    "product" : "Classes",
    "purchaseValidity" : {
            "year" : 2017,
            "month" : 7,
            "date" : 31
    },
    "expires": {
            "year" : 2017,
            "month" : 12,
            "date" : 31
    },
    "code" : "GYM-2",
    "tags" : [
            "fitness"
    ]
}

This is part of a lager code. However,  I want to retrieve the data items with tag: fitness  that offer discounts:  $gte 10 or savings above 10

This is what I started working with, however I cant find the syntax to work with both discounts and fitness

items.find({tags: "fitness"}, {discount: {$gte: 10}}).pretty()

Body:
You Can Do it like this :-

1.$elemMatch used for match in arrays.

2.$and in by Default in query.

items.find({ tags:{  $elemMatch:{$eq: "fitness"}} ,
             $or:[  {discount: {$gte: 10}},
                    {savings: {$gte: 10}}
                 ] })

Thanks.


问:
Efficient SQL query for selecting records where a related record DOES NOT exist
I am trying to select a User where that User DOES NOT have an associated record with a certain value.

I have a User model, a User has_one Feed, a Feed has_many FeedTracks, a FeedTrack belongs_to a Track. I want to select Users only where they DO NOT have a FeedTrack with a certain TrackId.

I'm using rails but I would be open to strict SQL for this.

The best I've got is:

```<code> SELECT TOP 1000 *
 FROM Users u
 LEFT JOIN Feeds f ON f.user_id = u.id
 LEFT JOIN FeedTracks ft ON ft.feed_id = f.id
 ONLY IF ALL OF THOSE feedTracks' track_id !== <<track_id>>
</code>```

Obviously that last part statement is not real SQL and that's what my question is. How would I say, hey, get me the Users where this related record doesn't exist. But if that record does exist, don't return that User.

In other words, if that user has a feed, with a feed track with that track id, don't return that User. But if it doesn't, do return that User.

答:
You should use not existst operation  like this

```<code> SELECT TOP 1000 *
 FROM Users u
    LEFT JOIN Feeds f ON f.id = u.feed_id
    LEFT JOIN FeedTracks ft ON ft.feed_id = f.id
 where not exists
(select 1
from FeedTracks  ft1
where ft1.feed_id = f.id
  and ft1.track_id = <<track_id>>)
</code>```

Body:
I am trying to select a User where that User DOES NOT have an associated record with a certain value.

I have a User model, a User has_one Feed, a Feed has_many FeedTracks, a FeedTrack belongs_to a Track. I want to select Users only where they DO NOT have a FeedTrack with a certain TrackId.

I'm using rails but I would be open to strict SQL for this.

The best I've got is:

 SELECT TOP 1000 *
 FROM Users u
 LEFT JOIN Feeds f ON f.user_id = u.id
 LEFT JOIN FeedTracks ft ON ft.feed_id = f.id
 ONLY IF ALL OF THOSE feedTracks' track_id !== <<track_id>>

Obviously that last part statement is not real SQL and that's what my question is. How would I say, hey, get me the Users where this related record doesn't exist. But if that record does exist, don't return that User.

In other words, if that user has a feed, with a feed track with that track id, don't return that User. But if it doesn't, do return that User.

Body:
You should use not existst operation  like this

 SELECT TOP 1000 *
 FROM Users u
    LEFT JOIN Feeds f ON f.id = u.feed_id
    LEFT JOIN FeedTracks ft ON ft.feed_id = f.id
 where not exists
(select 1
from FeedTracks  ft1
where ft1.feed_id = f.id
  and ft1.track_id = <<track_id>>)


问:
document.getElementById giving Null by JS not by HTML
When I am defining my input tag in html and accessing in JS by id then I am getting my tag.

HTML Code:

```<code><input class="easyui-combobox" name="language" style="width:30%;" id= "XX">
</code>```

JS Code:

```<code>var cc = document.getElementById("XX");
</code>```

Here things are fine.

But When I am creating from javascript and trying to access I am getting. I want dynamic So I need to create from JS.

JS Code:

```<code>var input = document.createElement("input");
input.className = 'easyui-combobox';
input.style = 'width:30%';
input.id = "XX";
</code>```

Here I am getting null after applying this:

```<code>var cc = document.getElementById("XX");
</code>```

答:
The element has been created, but needs to be appended to the DOM.  Use the
appendChild() or insertBefore() method.

```<code>var input = document.createElement("input");
input.className = 'easyui-combobox';
input.style = 'width:30%';
input.id = "XX";
document.body.appendChild(input);
</code>```

Body:
When I am defining my input tag in html and accessing in JS by id then I am getting my tag.

HTML Code:

<input class="easyui-combobox" name="language" style="width:30%;" id= "XX">

JS Code:

var cc = document.getElementById("XX");

Here things are fine.

But When I am creating from javascript and trying to access I am getting. I want dynamic So I need to create from JS.

JS Code:

var input = document.createElement("input");
input.className = 'easyui-combobox';
input.style = 'width:30%';
input.id = "XX";

Here I am getting null after applying this:

var cc = document.getElementById("XX");

Body:
The element has been created, but needs to be appended to the DOM.  Use the
appendChild() or insertBefore() method.

var input = document.createElement("input");
input.className = 'easyui-combobox';
input.style = 'width:30%';
input.id = "XX";
document.body.appendChild(input);