问:
Query to show which games which friends don't have
I have three tables set up in Access. I want to make a query that shows which games someone doesn't have in common with me.

I tried using an unmatched query, but that didn't work since each person has at least one game in common with me.

I guess I'm unsure how to handle this. The GameTimePlayed table basically has the opposite of the information I want to query, so is it possible to query that and add a "Not" conditional to "GameName" or something?

This is for a final project for class, and isn't due for about another month. I don't expect anyone to answer this for me, but even just a point in the right direction would be greatly appreciated. Everything I've tried to find so far is basically about unmatched queries, which did not work for me.

--EDIT TO PROVIDE MORE INFO--

I have all of the games in FavoriteGames. However, not all of my friends (PersonID) have all of my FavoriteGames. I'd like a query to show a record of FirstName, LastName, GameName, for each PersonID, for each GameName that he/she does not have.

Expected Behavior Example: PersonID 10 only has one GameName in common with me. The query should return five records for PersonID 10
  (every game except Rocket League).

Sample Data:

tbl_FavoriteGames

tbl_FriendsWithGame

tbl_GameTimePlayed

GameName is the Primary Key for tbl_FavoriteGames

PersonID is the Primary Key for tbl_FriendsWithGame

PersonID, GameName Foreign Keys form a Composite Primary Key for tbl_GameTimePlayed

This is the closest I have gotten so far (still way off though) in that it removes the specified GameName:

```<code>SELECT *
FROM tbl_GameTimePlayed
WHERE NOT EXISTS
(
  SELECT *
  FROM tbl_FriendsWithGame
  WHERE tbl_GameTimePlayed.PersonID = tbl_FriendsWithGame.PersonID
    AND tbl_GameTimePlayed.GameName = tbl_FavoriteGames.GameName
);
</code>```

It prompts me to enter a GameName (no idea why). When I enter a GameName, it returns all records that don't have that specific GameName.

This returns 6 games for each person, whether or not the person actually has that game. Could be useful since it contains the people/games that aren't in common.

```<code>SELECT PersonID, GameName
FROM tbl_FriendsWithGame, tbl_FavoriteGames
WHERE EXISTS (SELECT PersonID FROM tbl_GameTimePlayed WHERE GameName = tbl_GameTimePlayed.GameName);
</code>```

I tried "WHERE NOT EXISTS" and that returned 0 results.

--SECOND EDIT: SOLVED!!--

I took a fresh look at the problem today, and figured it out! I used the code mentioned above to query (qry_AllPeopleAllGames) a list of all of the games, for all of the people (so 6 entries per person):

```<code>SELECT PersonID, GameName
FROM tbl_FriendsWithGame, tbl_FavoriteGames
WHERE EXISTS (SELECT PersonID FROM tbl_GameTimePlayed WHERE GameName = tbl_GameTimePlayed.GameName);
</code>```

Then, I made another query that compared the qry_AllPeopleAllGames list to my tbl_GameTimePlayed (which is the list of people, games they actually own, and hours played) and spit out a list of FirstName & LastInitial and GameName that don't exist in the real list:

```<code>SELECT [tbl_FriendsWithGame]![FirstName] & " " & [tbl_FriendsWithGame]![LastInitial] AS FullName, GameName

FROM qry_AllPeopleAllGames INNER JOIN tbl_FriendsWithGame ON qry_AllPeopleAllGames.PersonID = tbl_FriendsWithGame.PersonID

WHERE ((NOT Exists (SELECT PersonID, GameName

FROM tbl_GameTimePlayed

WHERE qry_AllPeopleAllGames.PersonID = tbl_GameTimePlayed.PersonID AND qry_AllPeopleAllGames.GameName = tbl_GameTimePlayed.GameName
)));
</code>```

****NOTE:**** The first part of the SELECT is not needed, I just used it for easier viewing in my actual query results (showing first name/last initial in one field).

I'm really excited that I figured this out! I'm sure there are better/more efficient ways to do this, and if you want to share, please let me know!

答:
You need a dataset of all possible pairs of friends/games in order to determine which games each friend does not have. Do you have a tbl_Friends? Consider:

Query1:

SELECT tblFriends.ID, tbl_FavoriteGames.ID FROM tblFriends, tbl_FavoriteGames;

That is a Cartesian query - without JOIN clause every record of each table will associate with each record of other table.

Query2:

SELECT Query1.tblFriends.ID, Query1.tbl_FavoriteGames.ID
FROM tbl_FriendsWithGame RIGHT JOIN Query1 ON (tbl_FriendsWithGame.GameID = Query1.tbl_FavoriteGames.ID) AND (tbl_FriendsWithGame.FriendID = Query1.tblFriends.ID) WHERE tbl_FriendsWithGame.GameID IS NULL;

Or if you don't have tbl_Friends

SELECT DISTINCT tbl_FriendsWithGame.FriendID, tbl_FavoriteGames.ID
FROM tbl_FavoriteGames, tbl_FriendsWithGame;

Then adjust Query2.

Body:
I have three tables set up in Access. I want to make a query that shows which games someone doesn't have in common with me.

I tried using an unmatched query, but that didn't work since each person has at least one game in common with me.

I guess I'm unsure how to handle this. The GameTimePlayed table basically has the opposite of the information I want to query, so is it possible to query that and add a "Not" conditional to "GameName" or something?

This is for a final project for class, and isn't due for about another month. I don't expect anyone to answer this for me, but even just a point in the right direction would be greatly appreciated. Everything I've tried to find so far is basically about unmatched queries, which did not work for me.

--EDIT TO PROVIDE MORE INFO--

I have all of the games in FavoriteGames. However, not all of my friends (PersonID) have all of my FavoriteGames. I'd like a query to show a record of FirstName, LastName, GameName, for each PersonID, for each GameName that he/she does not have.

Expected Behavior Example: PersonID 10 only has one GameName in common with me. The query should return five records for PersonID 10
  (every game except Rocket League).

Sample Data:

tbl_FavoriteGames

tbl_FriendsWithGame

tbl_GameTimePlayed

GameName is the Primary Key for tbl_FavoriteGames

PersonID is the Primary Key for tbl_FriendsWithGame

PersonID, GameName Foreign Keys form a Composite Primary Key for tbl_GameTimePlayed

This is the closest I have gotten so far (still way off though) in that it removes the specified GameName:

SELECT *
FROM tbl_GameTimePlayed
WHERE NOT EXISTS
(
  SELECT *
  FROM tbl_FriendsWithGame
  WHERE tbl_GameTimePlayed.PersonID = tbl_FriendsWithGame.PersonID
    AND tbl_GameTimePlayed.GameName = tbl_FavoriteGames.GameName
);

It prompts me to enter a GameName (no idea why). When I enter a GameName, it returns all records that don't have that specific GameName.

This returns 6 games for each person, whether or not the person actually has that game. Could be useful since it contains the people/games that aren't in common.

SELECT PersonID, GameName
FROM tbl_FriendsWithGame, tbl_FavoriteGames
WHERE EXISTS (SELECT PersonID FROM tbl_GameTimePlayed WHERE GameName = tbl_GameTimePlayed.GameName);

I tried "WHERE NOT EXISTS" and that returned 0 results.

--SECOND EDIT: SOLVED!!--

I took a fresh look at the problem today, and figured it out! I used the code mentioned above to query (qry_AllPeopleAllGames) a list of all of the games, for all of the people (so 6 entries per person):

SELECT PersonID, GameName
FROM tbl_FriendsWithGame, tbl_FavoriteGames
WHERE EXISTS (SELECT PersonID FROM tbl_GameTimePlayed WHERE GameName = tbl_GameTimePlayed.GameName);

Then, I made another query that compared the qry_AllPeopleAllGames list to my tbl_GameTimePlayed (which is the list of people, games they actually own, and hours played) and spit out a list of FirstName & LastInitial and GameName that don't exist in the real list:

SELECT [tbl_FriendsWithGame]![FirstName] & " " & [tbl_FriendsWithGame]![LastInitial] AS FullName, GameName

FROM qry_AllPeopleAllGames INNER JOIN tbl_FriendsWithGame ON qry_AllPeopleAllGames.PersonID = tbl_FriendsWithGame.PersonID

WHERE ((NOT Exists (SELECT PersonID, GameName

FROM tbl_GameTimePlayed

WHERE qry_AllPeopleAllGames.PersonID = tbl_GameTimePlayed.PersonID AND qry_AllPeopleAllGames.GameName = tbl_GameTimePlayed.GameName
)));

****NOTE:**** The first part of the SELECT is not needed, I just used it for easier viewing in my actual query results (showing first name/last initial in one field).

I'm really excited that I figured this out! I'm sure there are better/more efficient ways to do this, and if you want to share, please let me know!


来源: stackexchange

问:
How to print parts of an 2d array
Im not asking for the answer per say im asking necessarily what would i need to change in order to print out sections of a 2d array for example if the array has 5 rows and 5 columns how would i print out the last 3 rows and last three columns.</p>

```<code>   import java.util.Scanner;

public class multiplication {
    static int a,b;
    public static void main(String[] args){
    Scanner input = new Scanner(System.in);
    a =input.nextInt();
    b = input.nextInt();

 int[][] matrix = new int[a][b];

matrix = timesTable(a,b);

for (int row = 0; row < matrix.length; row++) {
    for (int column = 0; column < matrix[row].length; column++) {
        System.out.print(" "+matrix[row][column] + "\t|");
        }
      System.out.println();
      }

}

public static int[][] timesTable(int r, int c)
{
    int [][] yes = new int[c][c];
    for ( r = 0; r < yes.length ; r++)
    {
        for (c = 0; c < yes[r].length; c++)
        {

                 yes[r][c] = (r+1)*(c+1);

        }
             }

    return yes;
}
}
</code>```

答:
Is the goal of this exercise to build the matrix and then print the matrix -or- do you simply need to display the desired output? I assume this is a class assignment.

Hint: Think about this .. if you enter 2 & 5, do you want a 2x5 matrix or a 4x4 matrix? It's important when you alloc your matrix size.

ContentLicense: CC BY-SA 3.0

Title: How to print parts of an 2d array

Body:
Im not asking for the answer per say im asking necessarily what would i need to change in order to print out sections of a 2d array for example if the array has 5 rows and 5 columns how would i print out the last 3 rows and last three columns.

   import java.util.Scanner;

public class multiplication {
    static int a,b;
    public static void main(String[] args){
    Scanner input = new Scanner(System.in);
    a =input.nextInt();
    b = input.nextInt();

 int[][] matrix = new int[a][b];

matrix = timesTable(a,b);

for (int row = 0; row < matrix.length; row++) {
    for (int column = 0; column < matrix[row].length; column++) {
        System.out.print(" "+matrix[row][column] + "\t|");
        }
      System.out.println();
      }

}

public static int[][] timesTable(int r, int c)
{
    int [][] yes = new int[c][c];
    for ( r = 0; r < yes.length ; r++)
    {
        for (c = 0; c < yes[r].length; c++)
        {

                 yes[r][c] = (r+1)*(c+1);

        }
             }

    return yes;
}
}


问:
Is there any replacement for HTTP tunneling with RMI in Java 9?
So I see that HTTP tunneling over RMI has been removed in Java 9.

We sell commercial Java software, which runs in Tomcat. Our customers install this on their Mac, Windows, and Linux servers. This software is then accessed by the public, with a Java Swing client interface. It uses RMI for communication with the server software.

Most of our customers have firewalls preventing access to the server on any port other than 80/443. This is not a problem for Java 8 and earlier, which can use RMI over dynamic ports or switch to HTTP when a firewall blocks access.

However, removing the HTTP proxy feature in Java 9 means that most of our customers will no longer be able to use our software, as currently architected. It is impractical and insecure for our customers to configure their firewalls and servers for SSH access from the public, especially for customers running Windows servers.

Does this mean that we need to rewrite our application architecture to use some network protocol other than RMI? Or is there a way to keep RMI in Java 9? Ditching RMI entirely will require a complete rewrite of our user-facing application code, and is not a cost effective option.

答:
Seems like JDK-8023862 already deprecated HTTP proxying from RMI as also mentioned in the release notes of Java8.

As suggested in #JDK8180642 which also inquires of an alternative to removal of HTTP proxy implementation from RMI. One of the alternatives could be to use ssh to tunnel through the proxy.

Use ssh to establish a local port that is tunneled through the proxy
  to the remote machine.
  The connection will be more functional than the HTTP proxy implementation.

In the chained links you can find an article over how can one make outgoing Java RMI calls through a local firewall? which suggests other implementations such as SOCKS and socket factories as well.


问:
UiPickerview values displayed as question mark ("?")in swift - But getting the correct value while assigning it to a textBox
//I am able to see the correct value in the text box upon scrolling down the picker view. But the picker view display is coming as "?" (question marks). I am confused with where I need to assign the pickerview as input view to the textbox . But still that won't make any sense to the error I am facing right .

I am using Xcode 9 and Swift 3.2.

```<code>class BillDetailsViewController: UIViewController ,UITextFieldDelegate,UIPickerViewDelegate,UIPickerViewDataSource{

  //Variables  Declaration

  //Picker view outlet
  @IBOutlet var datePickerView: UIPickerView!

  //Picker view datasource - integer array
  var integerArray = [Int](1899...2500)

  //Textbox where picked value to be shown
  @IBOutlet var txtPaidYear: UITextField!

  //ViewLoad
  override func viewDidLoad() {

    super.viewDidLoad()
    self.hideKeyboardWhenTappedAround()

    datePickerView.isHidden = true
    datePickerView.reloadAllComponents()
    datePickerView.dataSource = self
    datePickerView.delegate = self
    txtPaidYear.inputView = datePickerView
  }

  //picker view delegate functions

  public func numberOfComponents(in pickerView: UIPickerView) -> Int {
    return 1
  }

  public func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
    return integerArray.count
  }

  public func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String! {
    let pickerValue: String = String(integerArray[row])
    return pickerValue
  }

  public func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
    txtPaidYear.text = String(integerArray[row])
    self.datePickerView.reloadAllComponents()
  }
}
</code>```

答:
I just removed all the TextView delgates in the class and it worked . Still need to figure out what was the exact issue . One of the textView delegate method was causing the issue it seems . I need to figure it out.Anyway issue got fixed .I just created an independent project and implemented UIPIckerView for which it was working perfect. Hence I did the same in my project removing all the textview delegate methods .
Thanks much for all your support . </p>

Body:
//I am able to see the correct value in the text box upon scrolling down the picker view. But the picker view display is coming as "?" (question marks). I am confused with where I need to assign the pickerview as input view to the textbox . But still that won't make any sense to the error I am facing right .

I am using Xcode 9 and Swift 3.2.

class BillDetailsViewController: UIViewController ,UITextFieldDelegate,UIPickerViewDelegate,UIPickerViewDataSource{

  //Variables  Declaration

  //Picker view outlet
  @IBOutlet var datePickerView: UIPickerView!

  //Picker view datasource - integer array
  var integerArray = [Int](1899...2500)

  //Textbox where picked value to be shown
  @IBOutlet var txtPaidYear: UITextField!

  //ViewLoad
  override func viewDidLoad() {

    super.viewDidLoad()
    self.hideKeyboardWhenTappedAround()

    datePickerView.isHidden = true
    datePickerView.reloadAllComponents()
    datePickerView.dataSource = self
    datePickerView.delegate = self
    txtPaidYear.inputView = datePickerView
  }

  //picker view delegate functions

  public func numberOfComponents(in pickerView: UIPickerView) -> Int {
    return 1
  }

  public func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
    return integerArray.count
  }

  public func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String! {
    let pickerValue: String = String(integerArray[row])
    return pickerValue
  }

  public func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
    txtPaidYear.text = String(integerArray[row])
    self.datePickerView.reloadAllComponents()
  }
}


问:
ColdFusion session variable is GONE in IE11
My coldfusion session variable failed in IE. I have no problem with maintaining the session across pages in FireFox and Chrome. Similar question has been posted here and the solution was to check J2EE session variable in Administrator. The different in my case is that I have J2EE session checked in Admin page and also I have the following in my Application.cfc

```<code><cfset THIS.Name ="New_Site_Version1"/>
<cfset THIS.ApplicationTimeout = CreateTimeSpan(0,0,30,0) />
<cfset THIS.SessionManagement ="YES"/>
<cfset THIS.SessionTimeout = CreateTimeSpan( 0,0,30,0 ) />
<cfset THIS.SetClientCookies = "YES" />

 <cffunction name="OnSessionStart" access="public" returntype="void" output="false">
       <CFIF IsDefined("URL.user_ID")>
       <CFSET SessionObj = New cfcomponents.Main.ManageSessions()>
       <CFSET SessionObj.CreateUserSessions(URL.user_ID)>
    </CFIF>
 </cffunction>
</code>```

I also have session cookies checked in Admin

When I checked, the session was created in Application.cfc but soon after I clicked on a link, it's gone!
It only happen in IE.

Is there any work around?

答:
"This" application scope is not the "Session" application scope.  You may need to review your variable scope when instantiating variables that should be available to other modules in your application.  You can do that here:

https://help.adobe.com/en_US/ColdFusion/9.0/Developing/WSc3ff6d0ea77859461172e0811cbec09af4-7ff1.html

When you instantiate a ColdFusion application you use the CFAPPLICATION tag detailed here:

https://help.adobe.com/en_US/ColdFusion/9.0/CFMLRef/WSc3ff6d0ea77859461172e0811cbec22c24-7d69.html

Body:
My coldfusion session variable failed in IE. I have no problem with maintaining the session across pages in FireFox and Chrome. Similar question has been posted here and the solution was to check J2EE session variable in Administrator. The different in my case is that I have J2EE session checked in Admin page and also I have the following in my Application.cfc

<cfset THIS.Name ="New_Site_Version1"/>
<cfset THIS.ApplicationTimeout = CreateTimeSpan(0,0,30,0) />
<cfset THIS.SessionManagement ="YES"/>
<cfset THIS.SessionTimeout = CreateTimeSpan( 0,0,30,0 ) />
<cfset THIS.SetClientCookies = "YES" />

 <cffunction name="OnSessionStart" access="public" returntype="void" output="false">
       <CFIF IsDefined("URL.user_ID")>
       <CFSET SessionObj = New cfcomponents.Main.ManageSessions()>
       <CFSET SessionObj.CreateUserSessions(URL.user_ID)>
    </CFIF>
 </cffunction>

I also have session cookies checked in Admin

When I checked, the session was created in Application.cfc but soon after I clicked on a link, it's gone!
It only happen in IE.

Is there any work around?


问:
How to delete duplicates in a string using recursion?
I'm working on a function that uses recursion in order to delete duplicate characters in a string. Problem is, I'm not sure how to keep passing a string along in order to keep comparing adjacent characters without cutting the string somehow. Here's what I have so far:

```<code>string stringClean(const string& str)
{
   string s1 = str;

   if (/*first char == next char*/)
      s1.at(/*first char*/) = "";
      return stringClean(s1);
   else
      return s1;
}
</code>```

As an example, stringClean("yyzzza") should return "yza". Any tips on how I should proceed?

答:
C++

Here's what I just thought about

```<code>#include <iostream>
#include <string>

std::string rec(std::string &word, int index);
std::string rec(std::string word) {
    if(word.length() <= 1) {
         return word;
    }
    return word[0] + rec(word, 1);
}

std::string rec(std::string &word, int index) {
   if(index == word.length()) {
       return "";
   }
   return (word[index] != word[index-1] ? std::string(1, word[index]) : "") + rec(word, index+1);
}

int main() {
    std::cout << rec("aaabbbbcccddd") << std::endl;
}
</code>```

For one line recursion lovers:

```<code>std::string rec(std::string &word, int index) {
   return index == word.length() ? "" : (word[index] != word[index-1] ? std::string(1, word[index]) : "") + rec(word, index+1);
}
</code>```

Body:
I'm working on a function that uses recursion in order to delete duplicate characters in a string. Problem is, I'm not sure how to keep passing a string along in order to keep comparing adjacent characters without cutting the string somehow. Here's what I have so far:

string stringClean(const string& str)
{
   string s1 = str;

   if (/*first char == next char*/)
      s1.at(/*first char*/) = "";
      return stringClean(s1);
   else
      return s1;
}

As an example, stringClean("yyzzza") should return "yza". Any tips on how I should proceed?

Body:
C++

Here's what I just thought about

#include <iostream>
#include <string>

std::string rec(std::string &word, int index);
std::string rec(std::string word) {
    if(word.length() <= 1) {
         return word;
    }
    return word[0] + rec(word, 1);
}

std::string rec(std::string &word, int index) {
   if(index == word.length()) {
       return "";
   }
   return (word[index] != word[index-1] ? std::string(1, word[index]) : "") + rec(word, index+1);
}

int main() {
    std::cout << rec("aaabbbbcccddd") << std::endl;
}

For one line recursion lovers:

std::string rec(std::string &word, int index) {
   return index == word.length() ? "" : (word[index] != word[index-1] ? std::string(1, word[index]) : "") + rec(word, index+1);
}


问:
Bring activity front if it is running or create new one with backpress

Let me explain detailed; I have notification and this notification opens B activity with two cases.

Cases :

If app is closed. (not running on background)

If app is opened. (on background or front)

Case-1

I click to the notification and it opens the B activity with case-1. When i press back i want to go to the A activity and kill B activity. I dont need B activity anymore. Everything easy from here without using flags. When I'm on B activity and press back two times from here, it goes A activity and then closes the app. My trouble here is, if i open the app from navigation buttons of phone (can't remember the name of this button) app is opening from B activity. That's not what i expected. I want to open A activity. Don't want to see B activity anymore.

Case-2

I click to the notification and it opens the B activity with case-2.When i press back i want to bring A activity to the front, without creating anything new. If i press back on B activity, two times and close the app and then again re-open app from navigation button of phone, want to open app from A activity.

So how can i make this correctly, i tried to use flags (i already read docs) but couldn't get work.
What flags should i use when i open the B activity and onBackPress method of B activity to go A activity as i wanted

答:
Just put this in ActivityB onBackPressed:

```<code>Intent i = new Intent(ActivityB.this , ActivityA.calss);
i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP|Intent.FLAG_ACTIVITY_SINGLE_TOP);
startActivity(i);
finish();
</code>```

How solve case 1:

finish(); on ActivityB BackPressed method make ActivityB finish after open ActivityA. So after opens ActivtyA, ActivityB will shut down.

How solve case 2:

With this combination flag, It will do what you want. It will close all activities in stack and just keep destination activity. If instance of activity exist it will use it and calls OnNewInstance and if not it will creates new one.

Body:
Just put this in ActivityB onBackPressed:

Intent i = new Intent(ActivityB.this , ActivityA.calss);
i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP|Intent.FLAG_ACTIVITY_SINGLE_TOP);
startActivity(i);
finish();

How solve case 1:

finish(); on ActivityB BackPressed method make ActivityB finish after open ActivityA. So after opens ActivtyA, ActivityB will shut down.

How solve case 2:

With this combination flag, It will do what you want. It will close all activities in stack and just keep destination activity. If instance of activity exist it will use it and calls OnNewInstance and if not it will creates new one.


问:
Check if Type is a TypeBuilder
How can I check if a Type object is a TypeBuilderInstantiation?

Basically, I need a method off the Type.

If it's a TypeBuilderInstantiation, I need to call TypeBuilder.GetMethod(...), not just theType.GetMethod(...) (because it throws a not supported exception).

I can't simply check if theType is TypeBuilder because TypeBuilderInstantiation inherits directly from Type (not TypeBuilder). I can't check directly against TypeBuilderInstantiation, because it's internal.

答:
Why not compare Type.Fullname to what you're expecting for TypeBuilderInstantiation?

This smells bad. Can you elaborate on what you're doing that you're mucking around with an internal class?

Title: Check if Type is a TypeBuilder

ContentLicense: CC BY-SA 2.5


问:
How to show multiple divs with jquery?
I'm trying to use show() to show both an  and a

Currently it will only show one or the other, whichever is called last. In the code below it'll be the html(img).show() because it comes after. Doing $('.showimagediv').html(div,img).show(); has the same effect. Trying to combine the two statements into one variable:

```<code>var img = ($('<a />', {href    : this.getAttribute("data-permaLink"), 'class': 'permaLinkDiv'}),$('<img />', {src    : this.getAttribute("data-url"), 'class': 'fullScreenimg'}));
</code>```

will only result in  showing up. Does anyone know how to show both at the same time?

```<code>  var imgToggle=false;
  $('.box').on('click', function() {
      var img = $('<img />', {src    : this.getAttribute("data-url"), 'class': 'fullScreenimg'});
      var div = $('<a />', {href    : this.getAttribute("data-permaLink"), 'class': 'permaLinkDiv'});
      if(imgToggle==true){
          $('.showimagediv').html(img).hide();
          imgToggle=false;
      }
      if(imgToggle==false){
          $('.showimagediv').html(div).show();
          $('.showimagediv').html(img).show();

          imgToggle=true;
      }

  })
  $('.showimagediv').on('click', function() {
      var img = $('<img />', {src    : this.getAttribute("data-url"), 'class': 'fullScreenimg'});
      var div = $('<a />', {href    : this.getAttribute("data-permaLink"), 'class': 'permaLinkDiv'});
      if(imgToggle==true){
          $('.showimagediv').html(img).hide();
          divToggle=false;
      }

  })
</code>```

答:
You can add or remove css class with display:none to show your divs. It's very simply and a good way.

Example CSS: .hide{display:none;}

```<code>$('div').add('img').addClass('hide');  //or
$('div').add('img').removeClass('hide');
</code>```

ContentLicense: CC BY-SA 4.0

Title: How to show multiple divs with jquery?

Body:
I'm trying to use show() to show both an  and a

Currently it will only show one or the other, whichever is called last. In the code below it'll be the html(img).show() because it comes after. Doing $('.showimagediv').html(div,img).show(); has the same effect. Trying to combine the two statements into one variable:

var img = ($('', {href    : this.getAttribute("data-permaLink"), 'class': 'permaLinkDiv'}),$('', {src    : this.getAttribute("data-url"), 'class': 'fullScreenimg'}));

will only result in  showing up. Does anyone know how to show both at the same time?

  var imgToggle=false;
  $('.box').on('click', function() {
      var img = $('', {src    : this.getAttribute("data-url"), 'class': 'fullScreenimg'});
      var div = $('', {href    : this.getAttribute("data-permaLink"), 'class': 'permaLinkDiv'});
      if(imgToggle==true){
          $('.showimagediv').html(img).hide();
          imgToggle=false;
      }
      if(imgToggle==false){
          $('.showimagediv').html(div).show();
          $('.showimagediv').html(img).show();

          imgToggle=true;
      }

  })
  $('.showimagediv').on('click', function() {
      var img = $('', {src    : this.getAttribute("data-url"), 'class': 'fullScreenimg'});
      var div = $('', {href    : this.getAttribute("data-permaLink"), 'class': 'permaLinkDiv'});
      if(imgToggle==true){
          $('.showimagediv').html(img).hide();
          divToggle=false;
      }

  })

Body:
You can add or remove css class with display:none to show your divs. It's very simply and a good way.

Example CSS: .hide{display:none;}

$('div').add('img').addClass('hide');  //or
$('div').add('img').removeClass('hide');


问:
Getting 404 while accessing the api
I am setting up the node js project to access the api.

directory tree view

```<code>└── html
    └── perb
        ├── bin
        ├── models
        ├── node_modules
</code>```

project tree view

But end up getting the 404.
But when I am trying to access through localhost, it is working fine.

localhost address : localhost:3000/trainer/logintrainer

server address: ip_address/perb/trainer/logintrainer

in bin/www file listen port is 3000

```<code>var port = normalizePort(process.env.PORT || '3000');
app.set('port', port);
</code>```

but I have tried to change it to 80 and 8080 also but nothing helps.

I am using the apache2 server and setup as ( https://www.1and1.com/cloud-community/learn/application/misc/set-up-a-nodejs-app-for-a-website-with-apache-on-ubuntu-1604/ )

Any help will be highly appreciated.

答:
In the files you set up in your tutorial, can you set your proxy to point at the ip you're trying to hit instead of localhost</p>

```<code><Location /nodejs>
  ProxyPass http://127.0.0.1:8080
  ProxyPassReverse http://127.0.0.1:8080
</Location>
</code>```

Title: Getting 404 while accessing the api

Body:
I am setting up the node js project to access the api.

directory tree view

└── html
    └── perb
        ├── bin
        ├── models
        ├── node_modules

project tree view

But end up getting the 404.
But when I am trying to access through localhost, it is working fine.

localhost address : localhost:3000/trainer/logintrainer

server address: ip_address/perb/trainer/logintrainer

in bin/www file listen port is 3000

var port = normalizePort(process.env.PORT || '3000');
app.set('port', port);

but I have tried to change it to 80 and 8080 also but nothing helps.

I am using the apache2 server and setup as ( https://www.1and1.com/cloud-community/learn/application/misc/set-up-a-nodejs-app-for-a-website-with-apache-on-ubuntu-1604/ )

Any help will be highly appreciated.

Body:
In the files you set up in your tutorial, can you set your proxy to point at the ip you're trying to hit instead of localhost

<Location /nodejs>
  ProxyPass http://127.0.0.1:8080
  ProxyPassReverse http://127.0.0.1:8080
</Location>


问:
Sort primitive array with custom Comparator on Clojure
I would like to sort a primitive Java Array using a custom Comparator, but I am getting a type error.  I think the comparator function is creating a Comparator<java.lang.Object> rather than a Comparator<Long>, but I can't figure out how to get around this.

Here is a minimal example:

```<code>x.core=> (def x (double-array [4 3 5 6 7]))
#'x.core/x
x.core=> (java.util.Arrays/sort x (comparator #(> %1 %2)))

ClassCastException [D cannot be cast to [Ljava.lang.Object;  x.core/eval1524 (form-init5588058267991397340.clj:1)
</code>```

I have tried adding different type hints to the comparator function, but frankly I am relatively new to the language and was basically just throwing darts.

I have deliberately simplified the example above to focus on the key question, which is a type error.  In the sections below I try to give some more detail to motivate the question and demonstrate why I am using a custom Comparator.

Motivation

What I am trying to do is duplicate R's order function, which works like this:

```<code>> x = c(7, 2, 5, 3, 1, 4, 6)
> order(x)
[1] 5 2 4 6 3 7 1
> x[order(x)]
[1] 1 2 3 4 5 6 7
</code>```

As you can see it returns the permutation of indices that will sort its input vector.

Here is a working solution in Clojure:

```<code>(defn order
  "Permutation of indices sorted by x"
  [x]
  (let [v (vec x)]
    (sort-by #(v %) (range (count v)))))

x.core=> (order [7 2 5 3 1 4 6])
(4 1 3 5 2 6 0)
</code>```

(Note that R is 1-indexed while Clojure is 0-indexed.)  The trick is to sort one vector (namely the indices of x [0, 1, ..., (count x)] by the vector x itself.

R vs. Clojure Performance

Unfortunately, I am bothered by the performance of this solution.  The R solution is much faster:

```<code>> x = runif(1000000)
> system.time({ y = order(x) })
   user  system elapsed
  0.041   0.004   0.046
</code>```

Corresponding Clojure code:

```<code>x.core=> (def x (repeatedly 1000000 rand))
#'x.core/x
x.core=> (time (def y (order x)))
"Elapsed time: 2857.216452 msecs"
#'x.core/y
</code>```

Primitive Arrays the Solution?

I discovered that primitive arrays tend to sort in comparable time to R:

```<code>> x = runif(1000000)
> system.time({ y = sort(x) })
   user  system elapsed
  0.061   0.005   0.069
</code>```

vs.

```<code>x.core=> (def x (double-array (repeatedly 1000000 rand)))
#'x.core/x
x.core=> (time (java.util.Arrays/sort x))
"Elapsed time: 86.827277 msecs"
nil
</code>```

This is the motivation for my attempt to use a custom Comparator with the java.util.Arrays class.  My hope is that the speed will be comparable to R.

I should add that I can use a custom Comparator with an ArrayList as shown below, but the performance was no better than my starting function:

```<code>(defn order2
  [x]
  (let [v (vec x)
        compx (comparator (fn [i j] (< (v i) (v j))))
        ix (java.util.ArrayList. (range (count v)))]
    (java.util.Collections/sort ix compx)
    (vec ix)))
</code>```

Any help will be appreciated, even if you just want to give some general Clojure advice.  I'm still learning the language and having a lot of fun doing it.  :-)

Edit

Per Carcigenicate's answer below,

```<code>(defn order
  [x]
  (let [ix (int-array (range (count x)))]
    (vec (-> (java.util.Arrays/stream ix)
             (.boxed)
             (.sorted (fn [i j] (< (aget x i) (aget x j))))
             (.mapToInt
               (proxy [java.util.function.ToIntFunction] []
                 (applyAsInt [^long d] d)))
             (.toArray)))))
</code>```

will work:

```<code>x.core=> (def x (double-array [5 3 1 3.14 -10]))
#'x.core/x
x.core=> (order x)
[4 2 1 3 0]
x.core=> (map #(aget x %) (order x))
(-10.0 1.0 3.0 3.14 5.0)
</code>```

Unfortunately it's super slow.  I guess primitives might not be the answer after all.

答:
Here's a Clojure implementation of the order function using quicksort with randomized pivots. It gets reasonably close to R: using your benchmark with a million doubles, I'm getting timings mostly in the 520-530 ms range, while R generally hovers around 500 ms here.

Update: With a very basic two-threaded version (2x quicksort followed by a merge step that produces the output vector) I'm getting noticeably improved timings – the worst benchmark average was 415 ms, otherwise I tend to get results in the 325-365 ms range. See end of this message for the two-threaded version, or if you prefer either version in gist form, here they are – two-threaded,
single-threaded.

Note that it pours its input into an array of doubles as an intermediate step and ultimately returns a vector of longs. Pouring a million doubles into a vector seems to take just over 30 ms on my box, so you could leave off that step if you're happy with an array result.

The main complication is the invokePrim – as of Clojure 1.9.0-RC1, a regular function call in that position would result in boxing. Other approaches are possible, but this works and seems straightforward enough.

See end of this message for some benchmark results.; the lower quantile result from the first run is actually the best reported result

```<code>(defn order2 [xs]
  (let [rnd (java.util.Random.)
        a1 (double-array xs)
        a2 (long-array (alength a1))]
    (dotimes [i (alength a2)]
      (aset a2 i i))
    (letfn [(quicksort [^long l ^long h]
              (if (< l h)
                (let [p (.invokePrim ^clojure.lang.IFn$LLL partition l h)]
                  (quicksort l (dec p))
                  (quicksort (inc p) h))))
            (partition ^long [^long l ^long h]
              (let [pidx (+ l (.nextInt rnd (- h l)))
                    pivot (aget a1 pidx)]
                (swap1 a1 pidx h)
                (swap2 a2 pidx h)
                (loop [i (dec l)
                       j l]
                  (if (< j h)
                    (if (< (aget a1 j) pivot)
                      (let [i (inc i)]
                        (swap1 a1 i j)
                        (swap2 a2 i j)
                        (recur i (inc j)))
                      (recur i (inc j)))
                    (let [i (inc i)]
                      (when (< (aget a1 h) (aget a1 i))
                        (swap1 a1 i h)
                        (swap2 a2 i h))
                      i)))))
            (swap1 [^doubles a ^long i ^long j]
              (let [tmp (aget a i)]
                (aset a i (aget a j))
                (aset a j tmp)))
            (swap2 [^longs a ^long i ^long j]
              (let [tmp (aget a i)]
                (aset a i (aget a j))
                (aset a j tmp)))]
      (quicksort 0 (dec (alength a1)))
      (vec a2))))
</code>```

Benchmark results (NB. the first run uses x defined as in the question text – (def x (repeatedly 1000000 rand)); it also uses c/bench, whereas the following runs use c/quick-bench):

```<code>user> (c/bench (order2 x))
Evaluation count : 120 in 60 samples of 2 calls.
             Execution time mean : 522.485408 ms
    Execution time std-deviation : 33.490530 ms
   Execution time lower quantile : 470.089782 ms ( 2.5%)
   Execution time upper quantile : 575.687990 ms (97.5%)
                   Overhead used : 15.378363 ns
nil
user> (let [x (repeatedly 1000000 rand)]
        (c/quick-bench (order2 x)))
Evaluation count : 6 in 6 samples of 1 calls.
             Execution time mean : 527.020004 ms
    Execution time std-deviation : 14.846061 ms
   Execution time lower quantile : 507.175127 ms ( 2.5%)
   Execution time upper quantile : 543.675752 ms (97.5%)
                   Overhead used : 15.378363 ns
nil
user> (let [x (repeatedly 1000000 rand)]
        (c/quick-bench (order2 x)))
Evaluation count : 6 in 6 samples of 1 calls.
             Execution time mean : 513.476501 ms
    Execution time std-deviation : 12.828449 ms
   Execution time lower quantile : 497.164534 ms ( 2.5%)
   Execution time upper quantile : 525.094463 ms (97.5%)
                   Overhead used : 15.378363 ns
nil
user> (let [x (repeatedly 1000000 rand)]
        (c/quick-bench (order2 x)))
Evaluation count : 6 in 6 samples of 1 calls.
             Execution time mean : 529.826816 ms
    Execution time std-deviation : 21.454522 ms
   Execution time lower quantile : 508.547461 ms ( 2.5%)
   Execution time upper quantile : 552.592925 ms (97.5%)
                   Overhead used : 15.378363 ns
nil
</code>```

Some R timings from the same box for comparison:

```<code>> system.time({ y = order(x) })
   user  system elapsed
  0.512   0.004   0.514
> system.time({ y = order(x) })
   user  system elapsed
  0.496   0.000   0.496
> system.time({ y = order(x) })
   user  system elapsed
  0.508   0.000   0.510
> system.time({ y = order(x) })
   user  system elapsed
  0.508   0.000   0.513
> system.time({ y = order(x) })
   user  system elapsed
  0.496   0.000   0.499
> system.time({ y = order(x) })
   user  system elapsed
  0.500   0.000   0.502
</code>```

Update: The two-threaded Clojure version:

```<code>(defn order3 [xs]
  (let [rnd (java.util.Random.)
        a1 (double-array xs)
        a2 (long-array (alength a1))]
    (dotimes [i (alength a2)]
      (aset a2 i i))
    (letfn [(quicksort [^long l ^long h]
              (if (< l h)
                (let [p (.invokePrim ^clojure.lang.IFn$LLL partition l h)]
                  (quicksort l (dec p))
                  (quicksort (inc p) h))))
            (partition ^long [^long l ^long h]
              (let [pidx (+ l (.nextInt rnd (- h l)))
                    pivot (aget a1 pidx)]
                (swap1 a1 pidx h)
                (swap2 a2 pidx h)
                (loop [i (dec l)
                       j l]
                  (if (< j h)
                    (if (< (aget a1 j) pivot)
                      (let [i (inc i)]
                        (swap1 a1 i j)
                        (swap2 a2 i j)
                        (recur i (inc j)))
                      (recur i (inc j)))
                    (let [i (inc i)]
                      (when (< (aget a1 h) (aget a1 i))
                        (swap1 a1 i h)
                        (swap2 a2 i h))
                      i)))))
            (swap1 [^doubles a ^long i ^long j]
              (let [tmp (aget a i)]
                (aset a i (aget a j))
                (aset a j tmp)))
            (swap2 [^longs a ^long i ^long j]
              (let [tmp (aget a i)]
                (aset a i (aget a j))
                (aset a j tmp)))]
      (let [lim (alength a1)
            mid (quot lim 2)
            f1 (future (quicksort 0 (dec mid)))
            f2 (future (quicksort mid (dec lim)))]
        @f1
        @f2
        (loop [out (transient [])
               i 0
               j mid]
          (cond
            (== i mid)
            (persistent!
              (if (== j lim)
                out
                (reduce (fn [out j]
                          (conj! out (aget a2 j)))
                  out
                  (range j lim))))

            (== j lim)
            (persistent!
              (reduce (fn [out i]
                        (conj! out (aget a2 i)))
                out
                (range i mid)))

            :else
            (let [ie (aget a1 i)
                  je (aget a1 j)]
              (if (< ie je)
                (recur (conj! out (aget a2 i)) (inc i) j)
                (recur (conj! out (aget a2 j)) i (inc j))))))))))
</code>```

Some benchmark results for this one:

```<code>user> (let [x (repeatedly 1000000 rand)]
        (c/quick-bench (order3 x)))
Evaluation count : 6 in 6 samples of 1 calls.
             Execution time mean : 325.351056 ms
    Execution time std-deviation : 3.511578 ms
   Execution time lower quantile : 321.947510 ms ( 2.5%)
   Execution time upper quantile : 330.375038 ms (97.5%)
                   Overhead used : 15.378363 ns
nil
user> (let [x (repeatedly 1000000 rand)]
        (c/quick-bench (order3 x)))
Evaluation count : 6 in 6 samples of 1 calls.
             Execution time mean : 339.422989 ms
    Execution time std-deviation : 19.929177 ms
   Execution time lower quantile : 318.996436 ms ( 2.5%)
   Execution time upper quantile : 366.113347 ms (97.5%)
                   Overhead used : 15.378363 ns
nil
user> (let [x (repeatedly 1000000 rand)]
        (c/quick-bench (order3 x)))
Evaluation count : 6 in 6 samples of 1 calls.
             Execution time mean : 415.171336 ms
    Execution time std-deviation : 13.624262 ms
   Execution time lower quantile : 393.242455 ms ( 2.5%)
   Execution time upper quantile : 428.881001 ms (97.5%)
                   Overhead used : 15.378363 ns

Found 1 outliers in 6 samples (16.6667 %)
    low-severe   1 (16.6667 %)
 Variance from outliers : 13.8889 % Variance is moderately inflated by outliers
nil
user> (let [x (repeatedly 1000000 rand)]
        (c/quick-bench (order3 x)))
Evaluation count : 6 in 6 samples of 1 calls.
             Execution time mean : 324.547827 ms
    Execution time std-deviation : 5.196817 ms
   Execution time lower quantile : 318.541727 ms ( 2.5%)
   Execution time upper quantile : 331.878289 ms (97.5%)
                   Overhead used : 15.378363 ns
nil
user> (c/bench (order3 x))
Evaluation count : 180 in 60 samples of 3 calls.
             Execution time mean : 361.529793 ms
    Execution time std-deviation : 45.285047 ms
   Execution time lower quantile : 307.535934 ms ( 2.5%)
   Execution time upper quantile : 446.679687 ms (97.5%)
                   Overhead used : 15.378363 ns

Found 1 outliers in 60 samples (1.6667 %)
    low-severe   1 (1.6667 %)
 Variance from outliers : 78.9377 % Variance is severely inflated by outliers
nil
</code>```

Body:
I would like to sort a primitive Java Array using a custom Comparator, but I am getting a type error.  I think the comparator function is creating a Comparator<java.lang.Object> rather than a Comparator<Long>, but I can't figure out how to get around this.

Here is a minimal example:

x.core=> (def x (double-array [4 3 5 6 7]))
#'x.core/x
x.core=> (java.util.Arrays/sort x (comparator #(> %1 %2)))

ClassCastException [D cannot be cast to [Ljava.lang.Object;  x.core/eval1524 (form-init5588058267991397340.clj:1)

I have tried adding different type hints to the comparator function, but frankly I am relatively new to the language and was basically just throwing darts.

I have deliberately simplified the example above to focus on the key question, which is a type error.  In the sections below I try to give some more detail to motivate the question and demonstrate why I am using a custom Comparator.

Motivation

What I am trying to do is duplicate R's order function, which works like this:

> x = c(7, 2, 5, 3, 1, 4, 6)
> order(x)
[1] 5 2 4 6 3 7 1
> x[order(x)]
[1] 1 2 3 4 5 6 7

As you can see it returns the permutation of indices that will sort its input vector.

Here is a working solution in Clojure:

(defn order
  "Permutation of indices sorted by x"
  [x]
  (let [v (vec x)]
    (sort-by #(v %) (range (count v)))))

x.core=> (order [7 2 5 3 1 4 6])
(4 1 3 5 2 6 0)

(Note that R is 1-indexed while Clojure is 0-indexed.)  The trick is to sort one vector (namely the indices of x [0, 1, ..., (count x)] by the vector x itself.

R vs. Clojure Performance

Unfortunately, I am bothered by the performance of this solution.  The R solution is much faster:

> x = runif(1000000)
> system.time({ y = order(x) })
   user  system elapsed
  0.041   0.004   0.046

Corresponding Clojure code:

x.core=> (def x (repeatedly 1000000 rand))
#'x.core/x
x.core=> (time (def y (order x)))
"Elapsed time: 2857.216452 msecs"
#'x.core/y

Primitive Arrays the Solution?

I discovered that primitive arrays tend to sort in comparable time to R:

> x = runif(1000000)
> system.time({ y = sort(x) })
   user  system elapsed
  0.061   0.005   0.069

vs.

x.core=> (def x (double-array (repeatedly 1000000 rand)))
#'x.core/x
x.core=> (time (java.util.Arrays/sort x))
"Elapsed time: 86.827277 msecs"
nil

This is the motivation for my attempt to use a custom Comparator with the java.util.Arrays class.  My hope is that the speed will be comparable to R.

I should add that I can use a custom Comparator with an ArrayList as shown below, but the performance was no better than my starting function:

(defn order2
  [x]
  (let [v (vec x)
        compx (comparator (fn [i j] (< (v i) (v j))))
        ix (java.util.ArrayList. (range (count v)))]
    (java.util.Collections/sort ix compx)
    (vec ix)))

Any help will be appreciated, even if you just want to give some general Clojure advice.  I'm still learning the language and having a lot of fun doing it.  :-)

Edit

Per Carcigenicate's answer below,

(defn order
  [x]
  (let [ix (int-array (range (count x)))]
    (vec (-> (java.util.Arrays/stream ix)
             (.boxed)
             (.sorted (fn [i j] (< (aget x i) (aget x j))))
             (.mapToInt
               (proxy [java.util.function.ToIntFunction] []
                 (applyAsInt [^long d] d)))
             (.toArray)))))

will work:

x.core=> (def x (double-array [5 3 1 3.14 -10]))
#'x.core/x
x.core=> (order x)
[4 2 1 3 0]
x.core=> (map #(aget x %) (order x))
(-10.0 1.0 3.0 3.14 5.0)

Unfortunately it's super slow.  I guess primitives might not be the answer after all.

Body:
Here's a Clojure implementation of the order function using quicksort with randomized pivots. It gets reasonably close to R: using your benchmark with a million doubles, I'm getting timings mostly in the 520-530 ms range, while R generally hovers around 500 ms here.

Update: With a very basic two-threaded version (2x quicksort followed by a merge step that produces the output vector) I'm getting noticeably improved timings – the worst benchmark average was 415 ms, otherwise I tend to get results in the 325-365 ms range. See end of this message for the two-threaded version, or if you prefer either version in gist form, here they are – two-threaded,
single-threaded.

Note that it pours its input into an array of doubles as an intermediate step and ultimately returns a vector of longs. Pouring a million doubles into a vector seems to take just over 30 ms on my box, so you could leave off that step if you're happy with an array result.

The main complication is the invokePrim – as of Clojure 1.9.0-RC1, a regular function call in that position would result in boxing. Other approaches are possible, but this works and seems straightforward enough.

See end of this message for some benchmark results.; the lower quantile result from the first run is actually the best reported result

(defn order2 [xs]
  (let [rnd (java.util.Random.)
        a1 (double-array xs)
        a2 (long-array (alength a1))]
    (dotimes [i (alength a2)]
      (aset a2 i i))
    (letfn [(quicksort [^long l ^long h]
              (if (< l h)
                (let [p (.invokePrim ^clojure.lang.IFn$LLL partition l h)]
                  (quicksort l (dec p))
                  (quicksort (inc p) h))))
            (partition ^long [^long l ^long h]
              (let [pidx (+ l (.nextInt rnd (- h l)))
                    pivot (aget a1 pidx)]
                (swap1 a1 pidx h)
                (swap2 a2 pidx h)
                (loop [i (dec l)
                       j l]
                  (if (< j h)
                    (if (< (aget a1 j) pivot)
                      (let [i (inc i)]
                        (swap1 a1 i j)
                        (swap2 a2 i j)
                        (recur i (inc j)))
                      (recur i (inc j)))
                    (let [i (inc i)]
                      (when (< (aget a1 h) (aget a1 i))
                        (swap1 a1 i h)
                        (swap2 a2 i h))
                      i)))))
            (swap1 [^doubles a ^long i ^long j]
              (let [tmp (aget a i)]
                (aset a i (aget a j))
                (aset a j tmp)))
            (swap2 [^longs a ^long i ^long j]
              (let [tmp (aget a i)]
                (aset a i (aget a j))
                (aset a j tmp)))]
      (quicksort 0 (dec (alength a1)))
      (vec a2))))

Benchmark results (NB. the first run uses x defined as in the question text – (def x (repeatedly 1000000 rand)); it also uses c/bench, whereas the following runs use c/quick-bench):

user> (c/bench (order2 x))
Evaluation count : 120 in 60 samples of 2 calls.
             Execution time mean : 522.485408 ms
    Execution time std-deviation : 33.490530 ms
   Execution time lower quantile : 470.089782 ms ( 2.5%)
   Execution time upper quantile : 575.687990 ms (97.5%)
                   Overhead used : 15.378363 ns
nil
user> (let [x (repeatedly 1000000 rand)]
        (c/quick-bench (order2 x)))
Evaluation count : 6 in 6 samples of 1 calls.
             Execution time mean : 527.020004 ms
    Execution time std-deviation : 14.846061 ms
   Execution time lower quantile : 507.175127 ms ( 2.5%)
   Execution time upper quantile : 543.675752 ms (97.5%)
                   Overhead used : 15.378363 ns
nil
user> (let [x (repeatedly 1000000 rand)]
        (c/quick-bench (order2 x)))
Evaluation count : 6 in 6 samples of 1 calls.
             Execution time mean : 513.476501 ms
    Execution time std-deviation : 12.828449 ms
   Execution time lower quantile : 497.164534 ms ( 2.5%)
   Execution time upper quantile : 525.094463 ms (97.5%)
                   Overhead used : 15.378363 ns
nil
user> (let [x (repeatedly 1000000 rand)]
        (c/quick-bench (order2 x)))
Evaluation count : 6 in 6 samples of 1 calls.
             Execution time mean : 529.826816 ms
    Execution time std-deviation : 21.454522 ms
   Execution time lower quantile : 508.547461 ms ( 2.5%)
   Execution time upper quantile : 552.592925 ms (97.5%)
                   Overhead used : 15.378363 ns
nil

Some R timings from the same box for comparison:

> system.time({ y = order(x) })
   user  system elapsed
  0.512   0.004   0.514
> system.time({ y = order(x) })
   user  system elapsed
  0.496   0.000   0.496
> system.time({ y = order(x) })
   user  system elapsed
  0.508   0.000   0.510
> system.time({ y = order(x) })
   user  system elapsed
  0.508   0.000   0.513
> system.time({ y = order(x) })
   user  system elapsed
  0.496   0.000   0.499
> system.time({ y = order(x) })
   user  system elapsed
  0.500   0.000   0.502

Update: The two-threaded Clojure version:

(defn order3 [xs]
  (let [rnd (java.util.Random.)
        a1 (double-array xs)
        a2 (long-array (alength a1))]
    (dotimes [i (alength a2)]
      (aset a2 i i))
    (letfn [(quicksort [^long l ^long h]
              (if (< l h)
                (let [p (.invokePrim ^clojure.lang.IFn$LLL partition l h)]
                  (quicksort l (dec p))
                  (quicksort (inc p) h))))
            (partition ^long [^long l ^long h]
              (let [pidx (+ l (.nextInt rnd (- h l)))
                    pivot (aget a1 pidx)]
                (swap1 a1 pidx h)
                (swap2 a2 pidx h)
                (loop [i (dec l)
                       j l]
                  (if (< j h)
                    (if (< (aget a1 j) pivot)
                      (let [i (inc i)]
                        (swap1 a1 i j)
                        (swap2 a2 i j)
                        (recur i (inc j)))
                      (recur i (inc j)))
                    (let [i (inc i)]
                      (when (< (aget a1 h) (aget a1 i))
                        (swap1 a1 i h)
                        (swap2 a2 i h))
                      i)))))
            (swap1 [^doubles a ^long i ^long j]
              (let [tmp (aget a i)]
                (aset a i (aget a j))
                (aset a j tmp)))
            (swap2 [^longs a ^long i ^long j]
              (let [tmp (aget a i)]
                (aset a i (aget a j))
                (aset a j tmp)))]
      (let [lim (alength a1)
            mid (quot lim 2)
            f1 (future (quicksort 0 (dec mid)))
            f2 (future (quicksort mid (dec lim)))]
        @f1
        @f2
        (loop [out (transient [])
               i 0
               j mid]
          (cond
            (== i mid)
            (persistent!
              (if (== j lim)
                out
                (reduce (fn [out j]
                          (conj! out (aget a2 j)))
                  out
                  (range j lim))))

            (== j lim)
            (persistent!
              (reduce (fn [out i]
                        (conj! out (aget a2 i)))
                out
                (range i mid)))

            :else
            (let [ie (aget a1 i)
                  je (aget a1 j)]
              (if (< ie je)
                (recur (conj! out (aget a2 i)) (inc i) j)
                (recur (conj! out (aget a2 j)) i (inc j))))))))))

Some benchmark results for this one:

user> (let [x (repeatedly 1000000 rand)]
        (c/quick-bench (order3 x)))
Evaluation count : 6 in 6 samples of 1 calls.
             Execution time mean : 325.351056 ms
    Execution time std-deviation : 3.511578 ms
   Execution time lower quantile : 321.947510 ms ( 2.5%)
   Execution time upper quantile : 330.375038 ms (97.5%)
                   Overhead used : 15.378363 ns
nil
user> (let [x (repeatedly 1000000 rand)]
        (c/quick-bench (order3 x)))
Evaluation count : 6 in 6 samples of 1 calls.
             Execution time mean : 339.422989 ms
    Execution time std-deviation : 19.929177 ms
   Execution time lower quantile : 318.996436 ms ( 2.5%)
   Execution time upper quantile : 366.113347 ms (97.5%)
                   Overhead used : 15.378363 ns
nil
user> (let [x (repeatedly 1000000 rand)]
        (c/quick-bench (order3 x)))
Evaluation count : 6 in 6 samples of 1 calls.
             Execution time mean : 415.171336 ms
    Execution time std-deviation : 13.624262 ms
   Execution time lower quantile : 393.242455 ms ( 2.5%)
   Execution time upper quantile : 428.881001 ms (97.5%)
                   Overhead used : 15.378363 ns

Found 1 outliers in 6 samples (16.6667 %)
    low-severe   1 (16.6667 %)
 Variance from outliers : 13.8889 % Variance is moderately inflated by outliers
nil
user> (let [x (repeatedly 1000000 rand)]
        (c/quick-bench (order3 x)))
Evaluation count : 6 in 6 samples of 1 calls.
             Execution time mean : 324.547827 ms
    Execution time std-deviation : 5.196817 ms
   Execution time lower quantile : 318.541727 ms ( 2.5%)
   Execution time upper quantile : 331.878289 ms (97.5%)
                   Overhead used : 15.378363 ns
nil
user> (c/bench (order3 x))
Evaluation count : 180 in 60 samples of 3 calls.
             Execution time mean : 361.529793 ms
    Execution time std-deviation : 45.285047 ms
   Execution time lower quantile : 307.535934 ms ( 2.5%)
   Execution time upper quantile : 446.679687 ms (97.5%)
                   Overhead used : 15.378363 ns

Found 1 outliers in 60 samples (1.6667 %)
    low-severe   1 (1.6667 %)
 Variance from outliers : 78.9377 % Variance is severely inflated by outliers
nil


问:
How to prevent clang-format from adding a single semicolon to a new line?
I have this line of code in C++

```<code>while (fread(pixel_array++, sizeof(byte), 3, fp));
</code>```

but when I use clang-format, it splits the semicolon and add it into a new line

```<code>while (fread(pixel_array++, sizeof(byte), 3, fp))
    ;
</code>```

I don't like this kind of style, and I just prefer to keep the original one.

How should I modify my clang-format configuration? Thanks.

答:
clang-format 5.0 currently doesn't recognize that type of loop. Unfortunately as of clang-format version 5, you won't get a setting that does what you need.

Looking up the Clang Format Style Options, the closest that I've found is AllowShortLoopsOnASingleLine: true, but that setting doesn't recognize the loop condition as being the body of the loop.

As long as clang-format doesn't recognize those kinds of loops, what I'd do is to mark it your code with // clang-format off and then // clang-format on around your block of code.

Body:
I have this line of code in C++

while (fread(pixel_array++, sizeof(byte), 3, fp));

but when I use clang-format, it splits the semicolon and add it into a new line

while (fread(pixel_array++, sizeof(byte), 3, fp))
    ;

I don't like this kind of style, and I just prefer to keep the original one.

How should I modify my clang-format configuration? Thanks.


问:
unwraping div tags between two elements
I want to remove the div's between two specific elements

item1

item2

item3

item4

```
</div>
</div>
</p>

<p>i want to remove the div's between  id test1 and id ulid
how to use unwrap here
expected output</p>

```

item1

item2

item3

item4

```

答:
Try this and add this jQuery $('div[id^="test"][id!="test1"]').contents().unwrap();

$('div[id^="test"][id!="test1"]').contents().unwrap();```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="test1">
  <div id="test2">
    <div id="test3">
      <div id="test4">
        <div id="test5">
          <div id="test6">
            <ul id="ulid">
              <li>item1</li>
              <li>item2</li>
              <li>item3</li>
              <li>item4</li>
            </ul>
          </div>
        </div>
      </div>
    </div>
  </div>
</div></code>```

Title: unwraping div tags between two elements

Body:
I want to remove the div's between two specific elements

item1

item2

item3

item4

i want to remove the div's between  id test1 and id ulid
how to use unwrap here
expected output

item1

item2

item3

item4

Body:
Try this and add this jQuery $('div[id^="test"][id!="test1"]').contents().unwrap();

$('div[id^="test"][id!="test1"]').contents().unwrap();

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="test1">
  <div id="test2">
    <div id="test3">
      <div id="test4">
        <div id="test5">
          <div id="test6">
            <ul id="ulid">
              <li>item1</li>
              <li>item2</li>
              <li>item3</li>
              <li>item4</li>
            </ul>
          </div>
        </div>
      </div>
    </div>
  </div>
</div>


问:
C# Primitive types (double, int, etc) and Struct differences
I am confused with structs.

```<code>class A
{
  double a { get; set; }
  MyStruct b { get; set; }

  void Modify()
  {
     a = 1.0;    // This compiles.
     b.c = 2.0;  // Assuming c is a double. This gives the known error.
  }
}
</code>```

Now why I am able to set the value of the structure a, and not of the structure's field b ?
The answer I read is that I have a copy of b and not b's backing field. By the same logic I must have a copy of a, not a, so how it explains that the a property is changed after the permitted assignement

```<code>a = 1.0;
</code>```

? Thank you.

EDIT :

Also in order to still use b inside the A class, "filtered" by the set and get methods and not directly by using the backing field _b, something which could look like this:

```<code>MyStruct _b;
MyStruct b { get { return _b; } set { _b=value; } }
</code>```

and then use the field

```<code>_b
</code>```

, as correctly stated in the answers, I thinked of a silly method to "wrap" the property in an one dimensional array of size 1.

```<code>MyStruct[] b { get; set; }
</code>```

kind of wrapping the struct with a class. I dont know the computational cost of this, but I preferred it from using the field directly inside the A class.

ANSWERED : Ok, the confusion in this question comes, when you are used to interpret properties as fields in your mind. If you interpret properties the correct way -as the MsIL does-, all things settle down. All the answers and comments below, are relevant.
(Sorry for the bad English.)

答:
You're doing two different things. Here's an example of doing the same thing in both places:

```<code>a = 1.0;
b = new MyStruct(2.0);
</code>```

In both of these cases, the assignment operator is calling the "setter" of the property. You can think of it as:

```<code>this.SetA(1.0);
this.SetB(new MyStruct(2.0));
</code>```

As a more complicated example, if you wrote:

```<code>a = a + 1.0;
</code>```

that's equivalent to:

```<code>this.SetA(1.0 + this.GetA());
</code>```

Body:
I am confused with structs.

class A
{
  double a { get; set; }
  MyStruct b { get; set; }

  void Modify()
  {
     a = 1.0;    // This compiles.
     b.c = 2.0;  // Assuming c is a double. This gives the known error.
  }
}

Now why I am able to set the value of the structure a, and not of the structure's field b ?
The answer I read is that I have a copy of b and not b's backing field. By the same logic I must have a copy of a, not a, so how it explains that the a property is changed after the permitted assignement

a = 1.0;

? Thank you.

EDIT :

Also in order to still use b inside the A class, "filtered" by the set and get methods and not directly by using the backing field _b, something which could look like this:

MyStruct _b;
MyStruct b { get { return _b; } set { _b=value; } }

and then use the field

_b

, as correctly stated in the answers, I thinked of a silly method to "wrap" the property in an one dimensional array of size 1.

MyStruct[] b { get; set; }

kind of wrapping the struct with a class. I dont know the computational cost of this, but I preferred it from using the field directly inside the A class.

ANSWERED : Ok, the confusion in this question comes, when you are used to interpret properties as fields in your mind. If you interpret properties the correct way -as the MsIL does-, all things settle down. All the answers and comments below, are relevant.
(Sorry for the bad English.)

Body:
You're doing two different things. Here's an example of doing the same thing in both places:

a = 1.0;
b = new MyStruct(2.0);

In both of these cases, the assignment operator is calling the "setter" of the property. You can think of it as:

this.SetA(1.0);
this.SetB(new MyStruct(2.0));

As a more complicated example, if you wrote:

a = a + 1.0;

that's equivalent to:

this.SetA(1.0 + this.GetA());


问:
get() function in c++ not working for files
I wrote the following code in codeblocks and since I am new to programming I would like to know the problem in simple words. Does the open() constructor create a new file if it does not exists? </p>

```<code>#include<iostream>
#include<fstream>
#include<cstring>
using namespace std;
int main()
{
  char str[80];
  cout<<"Enter a string : ";cin>>str;
  int len=strlen(str);
  fstream file;
  file.open("TEXT",ios::in|ios::out);
  for(int i=0;i<len;i++)
  file.put(str[i]);
  file.seekg(0);
  char ch;
  cout<<"\nPrintitng Contents....\n";
  int k=0;
  while(file)
  {
    file.seekg(k);
    file.get(ch);
    cout<<ch;
    k++;
  }

  return 0;
}
</code>```

答:
Following code is more appropriate for C++, I think</p>

```<code>#include<iostream>
#include<fstream>
#include<string>
using namespace std;
int main()
{
    string str;
    string newStr;
    cout << "Enter a string : "; cin >> str;
    int len = str.length();
    fstream file;
    file.open("TEXT", ios::out| ios::in );
    if (!file.is_open())
        return 0;
    file << str;
    file.seekg(0,file.beg);
    char ch;
    cout << "\nPrintitng Contents....\n";

    file >> newStr;
    cout << newStr;
    file.close();

    return 0;
}
</code>```

Body:
I wrote the following code in codeblocks and since I am new to programming I would like to know the problem in simple words. Does the open() constructor create a new file if it does not exists?

#include<iostream>
#include<fstream>
#include<cstring>
using namespace std;
int main()
{
  char str[80];
  cout<<"Enter a string : ";cin>>str;
  int len=strlen(str);
  fstream file;
  file.open("TEXT",ios::in|ios::out);
  for(int i=0;i<len;i++)
  file.put(str[i]);
  file.seekg(0);
  char ch;
  cout<<"\nPrintitng Contents....\n";
  int k=0;
  while(file)
  {
    file.seekg(k);
    file.get(ch);
    cout<<ch;
    k++;
  }

  return 0;
}

Body:
Following code is more appropriate for C++, I think

#include<iostream>
#include<fstream>
#include<string>
using namespace std;
int main()
{
    string str;
    string newStr;
    cout << "Enter a string : "; cin >> str;
    int len = str.length();
    fstream file;
    file.open("TEXT", ios::out| ios::in );
    if (!file.is_open())
        return 0;
    file << str;
    file.seekg(0,file.beg);
    char ch;
    cout << "\nPrintitng Contents....\n";

    file >> newStr;
    cout << newStr;
    file.close();

    return 0;
}


问:
`ng-click="$mdMenu.open($event)"` not working in angular material
I am adding a material component in my angular app but is click is not functioning.

ref url: https://material.angularjs.org/latest/demo/menu

bug:

In "Position Mode Demos" section, ng-click="$mdMenu.open($event)" is not working. I don't see in documentation that I have to add something like $mdMenu as dependency. Similar components not working too.

```<code><div layout="column" flex-xs="100" flex-sm="100" flex="33" layout-align="center center">

        <p><code>md-position-mode="target-right target"</code></p>
        <md-menu md-position-mode="target-right target" >
          <md-button aria-label="Open demo menu" class="md-icon-button" ng-click="$mdMenu.open($event)">
            <md-icon md-menu-origin md-svg-icon="call:portable-wifi-off"></md-icon>
          </md-button>
          <md-menu-content width="4" >
            <md-menu-item ng-repeat="item in [1, 2, 3]">
              <md-button ng-click="ctrl.announceClick($index)">
                  <div layout="row" flex>
                    <p flex>Option {{item}}</p>
                    <md-icon md-menu-align-target md-svg-icon="call:portable-wifi-off" style="margin: auto 3px auto 0;"></md-icon>
                  </div>
              </md-button>
            </md-menu-item>
          </md-menu-content>
        </md-menu>

</div>
</code>```

答:
https://codepen.io/anon/pen/xPpGeW

Make sure you have the correct version of angular material library loaded for the documents you're reading things change in the material library pretty often.

  <meta name="viewport" content="width=device-width, initial-scale=1">

  <link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/angular_material/1.1.4/angular-material.css">

  <md-menu>

   <md-button ng-click="$mdMenu.open($event)" class="md-icon-button" aria-label="Open sample menu">
    Menu
     <md-icon md-font-icon="icon-settings"></md-icon>
   </md-button>
   <md-menu-content>
     <md-menu-item><md-button ng-click="doSomething()">Do Something</md-button></md-menu-item>
   </md-menu-content>
  </md-menu>

```

Body:
I am adding a material component in my angular app but is click is not functioning.

ref url: https://material.angularjs.org/latest/demo/menu

bug:

In "Position Mode Demos" section, ng-click="$mdMenu.open($event)" is not working. I don't see in documentation that I have to add something like $mdMenu as dependency. Similar components not working too.

md-position-mode="target-right target"

        <md-menu md-position-mode="target-right target" >
          <md-button aria-label="Open demo menu" class="md-icon-button" ng-click="$mdMenu.open($event)">
            <md-icon md-menu-origin md-svg-icon="call:portable-wifi-off"></md-icon>
          </md-button>
          <md-menu-content width="4" >
            <md-menu-item ng-repeat="item in [1, 2, 3]">
              <md-button ng-click="ctrl.announceClick($index)">

Option {{item}}

                    <md-icon md-menu-align-target md-svg-icon="call:portable-wifi-off" style="margin: auto 3px auto 0;"></md-icon>

              </md-button>
            </md-menu-item>
          </md-menu-content>
        </md-menu>

Body:
https://codepen.io/anon/pen/xPpGeW

Make sure you have the correct version of angular material library loaded for the documents you're reading things change in the material library pretty often.

<html lang="en" >
<head>
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <!-- Angular Material style sheet -->
  <link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/angular_material/1.1.4/angular-material.css">
</head>
<body ng-app="BlankApp" ng-cloak>
  <!--
    Your HTML content here
  -->

  <!-- Angular Material requires Angular.js Libraries -->
  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.5/angular.js"></script>
  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.5/angular-animate.min.js"></script>
  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.5/angular-aria.min.js"></script>
  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.5/angular-messages.min.js"></script>

  <!-- Angular Material Library -->
  <script src="https://ajax.googleapis.com/ajax/libs/angular_material/1.1.4/angular-material.min.js"></script>

  <!-- Your application bootstrap  -->
  <script type="text/javascript">
    /**
     * You must include the dependency on 'ngMaterial'
     */
    angular.module('BlankApp', ['ngMaterial']);
  </script>

  <md-menu>
   <!-- Trigger element is a md-button with an icon -->
   <md-button ng-click="$mdMenu.open($event)" class="md-icon-button" aria-label="Open sample menu">
    Menu
     <md-icon md-font-icon="icon-settings"></md-icon>
   </md-button>
   <md-menu-content>
     <md-menu-item><md-button ng-click="doSomething()">Do Something</md-button></md-menu-item>
   </md-menu-content>
  </md-menu>
</body>
</html>

<!--
Copyright 2016 Google Inc. All Rights Reserved.
Use of this source code is governed by an MIT-style license that can be in foundin the LICENSE file at https://material.angularjs.org/license.
-->


问:
How to interrupt Galen Framework layout checking?
I'm using Galen Framework for Web layout checking in my projects.
The problem is that I have a large amount of HTMl objects and layout rules defined in Galen specification, and somehow at runtime some of them are not discoverable.
It causes Galen run very slow to complete the test.

How can we cancel/interrupt the test while it's still running?

答:
If you are using Terminal / Command Prompt to run the test then

Ctrl + C (Cmd + C in mac) is the standard way to terminate a process
  on the fly.


问:
sp_xml_preparedocument go with error "Only one top level element is allowed in an XML document"
I'am trying to execute sp_xml_preparedocument and geting error "Only one top level element is allowed in an XML document"

my T-SQL commands:

```<code>DECLARE @aa XML
DECLARE @idoc int
SET @aa =(select * from db_name for xml auto, xmldata)
</code>```

@aa now is

```<code><Schema xmlns="urn:schemas-microsoft-com:xml-data" xmlns:dt="urn:schemas-microsoft-com:datatypes" name="Schema7">
<ElementType name="Person" content="empty" model="closed">
  <AttributeType name="preson_id" dt:type="i4" />
  <AttributeType name="Name" dt:type="string" />
  <AttributeType name="Surname" dt:type="string" />
  <AttributeType name="guid" dt:type="uuid" />
  <AttributeType name="version" dt:type="bin.base64" />
  <attribute type="preson_id" />
  <attribute type="Name" />
  <attribute type="Surname" />
  <attribute type="guid" />
  <attribute type="version" />
 </ElementType>
</Schema>
  <Person xmlns="x-schema:#Schema7" preson_id="1" Name="Иван" Surname="Иванов" guid="2E739E87-3CA4-4ED8-ADD0-8B59957668B8" version="AAAAAAAAB9E=" />
  <Person xmlns="x-schema:#Schema7" preson_id="2" Name="Николай" Surname="Николаев" guid="BDC41C59-D70F-4B70-954E-4918B9516AF8" version="AAAAAAAAB9I=" />
  <Person xmlns="x-schema:#Schema7" preson_id="3" Name="Максим" Surname="Максимов" guid="740E57F3-56BA-48B8-92AF-978D7B1D2712" version="AAAAAAAAB9M=" />
</code>```

```<code>EXEC sp_xml_preparedocument @idoc OUTPUT, @aa
</code>```

```<code>The XML parse error 0xc00ce555 occurred on line number 1, near the XML text ""
Msg 6602, Level 16, State 2, Procedure sp_xml_preparedocument, Line 1
The error description is 'Only one top level element is allowed in an XML document
</code>```

I'am new in this, and i need help)))
An one more question - How parse timestamp type?

if i use

```<code>SET @aa =(select * from db_name for xml elements, root('root'), type)
</code>```

sp_xml_preparedocument works fine, OPENXML returns all values of my db_table, but timestamp values looks not the same as were..

Sorry for my bad English

答:
An XML document must have one root element only - see W3C specification.

Thus in you case if Schema is the root element you cannot add the Person elements at the end

Body:
I'am trying to execute sp_xml_preparedocument and geting error "Only one top level element is allowed in an XML document"

my T-SQL commands:

DECLARE @aa XML
DECLARE @idoc int
SET @aa =(select * from db_name for xml auto, xmldata)

@aa now is

<Schema xmlns="urn:schemas-microsoft-com:xml-data" xmlns:dt="urn:schemas-microsoft-com:datatypes" name="Schema7">
<ElementType name="Person" content="empty" model="closed">
  <AttributeType name="preson_id" dt:type="i4" />
  <AttributeType name="Name" dt:type="string" />
  <AttributeType name="Surname" dt:type="string" />
  <AttributeType name="guid" dt:type="uuid" />
  <AttributeType name="version" dt:type="bin.base64" />
  <attribute type="preson_id" />
  <attribute type="Name" />
  <attribute type="Surname" />
  <attribute type="guid" />
  <attribute type="version" />
 </ElementType>
</Schema>
  <Person xmlns="x-schema:#Schema7" preson_id="1" Name="Иван" Surname="Иванов" guid="2E739E87-3CA4-4ED8-ADD0-8B59957668B8" version="AAAAAAAAB9E=" />
  <Person xmlns="x-schema:#Schema7" preson_id="2" Name="Николай" Surname="Николаев" guid="BDC41C59-D70F-4B70-954E-4918B9516AF8" version="AAAAAAAAB9I=" />
  <Person xmlns="x-schema:#Schema7" preson_id="3" Name="Максим" Surname="Максимов" guid="740E57F3-56BA-48B8-92AF-978D7B1D2712" version="AAAAAAAAB9M=" />

EXEC sp_xml_preparedocument @idoc OUTPUT, @aa

The XML parse error 0xc00ce555 occurred on line number 1, near the XML text ""
Msg 6602, Level 16, State 2, Procedure sp_xml_preparedocument, Line 1
The error description is 'Only one top level element is allowed in an XML document

I'am new in this, and i need help)))
An one more question - How parse timestamp type?

if i use

SET @aa =(select * from db_name for xml elements, root('root'), type)

sp_xml_preparedocument works fine, OPENXML returns all values of my db_table, but timestamp values looks not the same as were..

Sorry for my bad English


问:
Notification Badge On Action Item Android
I wana add a notification badge on the cart image placed in action bar and manipulate it programmatically. Any Help?</p>

答:
Simplest hack by giving style.

```<code>        <TextView
                android:id="@+id/fabCounter"
                style="@style/Widget.Design.FloatingActionButton"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_alignParentEnd="true"
                android:layout_centerVertical="true"
                android:layout_marginEnd="10dp"
                android:padding="5dp"
                android:text="10"
                android:textColor="@android:color/black"
                android:textSize="14sp" />
</code>```

Body:
Simplest hack by giving style.

        <TextView
                android:id="@+id/fabCounter"
                style="@style/Widget.Design.FloatingActionButton"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_alignParentEnd="true"
                android:layout_centerVertical="true"
                android:layout_marginEnd="10dp"
                android:padding="5dp"
                android:text="10"
                android:textColor="@android:color/black"
                android:textSize="14sp" />


问:
Codeigniter Cart cannot add items
So i'm trying to create an application with cart and when i tried adding the item, it's not working. By the way i already have a working cart application that's why i'm wondering why it's not working. I almost copied everything from the working one. here's the code

Cart Controller

```<code><?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Cart extends CI_Controller {

public function __construct()
{
    parent::__construct();
    $this->load->library('cart');
}

public function add_to_cart(){

    $id = $this->uri->segment(3);
    if($this->cart->contents()){
        foreach ($this->cart->contents() as $item){
            if ($item['id']==$id){
                $data = array('rowid'=>$item['rowid'],
                    'qty'=>++$item['qty']);
                $process = $this->cart->update($data);
            }
            else{
                $data = array(
                    'id'=>$id,
                    'qty'=>1,
                    'name' => $this->get_data->get_value('product_name','products','product_id', $id),
                    'price' => $this->get_data->get_value('product_price','products','product_id', $id)
                    );
                $process = $this->cart->insert($data);
            }
        }
    }
    else{
        $data = array('id'=>$id,
                    'qty' =>1,
                    'name' => $this->get_data->get_value('product_name','products','product_id', $id),
                    'price' => $this->get_data->get_value('product_price','products','product_id', $id),
                    );
                    $process = $this->cart->insert($data);
    }

    if($process){
        $this->session->set_flashdata('success', 'Successful');
        redirect('products');
    }
    else{
        $this->session->set_flashdata('failed', 'Failed');
        redirect('products');
        //var_dump($process);
    }
}
</code>```

Here's the button

```<code><div class="button pull-right" style="margin-top: 10px;"><a href="<?php echo base_url().'cart/add_to_cart/'.$row->product_id;?>"><span class="glyphicon glyphicon-shopping-cart"></span>Add to Cart</a></div>
</code>```

I really can't see the problem, i'm using session database, the sess_us_database is already TRUE. I tried using var_dump($process) and it's false, i tried var_dump($data) and the data seems to be fine but the insert part isn't working. Any idea guys? it would be a big help for me, thank you.

答:
A nice way to change this variable is putting a MY_Cart.php on your application\libraries\MY_Cart.php with this code:</p>

```<code><?php  if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class MY_Cart extends CI_Cart {

    var $product_name_rules = '[:print:]';

}
</code>```

Title: Codeigniter Cart cannot add items

Body:
So i'm trying to create an application with cart and when i tried adding the item, it's not working. By the way i already have a working cart application that's why i'm wondering why it's not working. I almost copied everything from the working one. here's the code

Cart Controller

<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Cart extends CI_Controller {

public function __construct()
{
    parent::__construct();
    $this->load->library('cart');
}

public function add_to_cart(){

    $id = $this->uri->segment(3);
    if($this->cart->contents()){
        foreach ($this->cart->contents() as $item){
            if ($item['id']==$id){
                $data = array('rowid'=>$item['rowid'],
                    'qty'=>++$item['qty']);
                $process = $this->cart->update($data);
            }
            else{
                $data = array(
                    'id'=>$id,
                    'qty'=>1,
                    'name' => $this->get_data->get_value('product_name','products','product_id', $id),
                    'price' => $this->get_data->get_value('product_price','products','product_id', $id)
                    );
                $process = $this->cart->insert($data);
            }
        }
    }
    else{
        $data = array('id'=>$id,
                    'qty' =>1,
                    'name' => $this->get_data->get_value('product_name','products','product_id', $id),
                    'price' => $this->get_data->get_value('product_price','products','product_id', $id),
                    );
                    $process = $this->cart->insert($data);
    }

    if($process){
        $this->session->set_flashdata('success', 'Successful');
        redirect('products');
    }
    else{
        $this->session->set_flashdata('failed', 'Failed');
        redirect('products');
        //var_dump($process);
    }
}

Here's the button

<a href="<?php echo base_url().'cart/add_to_cart/'.$row->product_id;?>">Add to Cart

I really can't see the problem, i'm using session database, the sess_us_database is already TRUE. I tried using var_dump($process) and it's false, i tried var_dump($data) and the data seems to be fine but the insert part isn't working. Any idea guys? it would be a big help for me, thank you.

Body:
A nice way to change this variable is putting a MY_Cart.php on your application\libraries\MY_Cart.php with this code:

<?php  if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class MY_Cart extends CI_Cart {

    var $product_name_rules = '[:print:]';

}


问:
How to print json console.log data in browser?
I'm trying to output Json data in browser using javascript but i was only able to output in console.log i don't know what to search of. I'm a beginner in javascript please help me out here.

script.js

```<code>$(document).ready(function() {
    var url = 'http://api.themoviedb.org/3/',
        mode = 'movie/',
        movie_id,
        key = '?api_key=e9dfeccf734a61b9a52d9d7660f0d0a1';

    $('button').click(function() {
        var input = $('#movie').val(),
            movie_id = encodeURI(input);
        $.ajax({
            type: 'GET',
            url: url + mode + movie_id + key,
            async: false,
            jsonpCallback: 'testing',
            contentType: 'application/json',
            dataType: 'jsonp',
            success: function(json) {
                console.dir(json);
            },
            error: function(e) {
                console.log(e.message);
            }
        });
    });
});
</code>```

index.php

```<code><input id="movie" type="text" /><button>Search</button>
</code>```

This code output all the data in console.log but i wanna do is it should display data in browser and i wanna output some specific objects like title of movie and overview and image.

答:
Retrieve the specific values using key and show it. The object have keys and values. Doing object.key will give the value

$(document).ready(function() {
  var url = 'https://api.themoviedb.org/3/',
    mode = 'movie/',
    movie_id,
    key = '?api_key=e9dfeccf734a61b9a52d9d7660f0d0a1';

  $('button').click(function() {
    var input = $('#movie').val(),
      movie_id = encodeURI(input);
    $.ajax({
      type: 'GET',
      url: url + mode + movie_id + key,
      async: false,
      jsonpCallback: 'testing',
      contentType: 'application/json',
      dataType: 'jsonp',
      success: function(json) {
        $("#title").text(json.title);
        //$("#movTitle").prop('src'); // add image path here
        $("#overview").text(json.overview) //overview is a key
      },
      error: function(e) {
        console.log(e.message);
      }
    });
  });
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="movie" type="text" /><button>Search</button>
<!-- Search This: 346364 -->
<div id="title">
</div>
<div>
  <img id="movTitle" src="" alt="">
</div>
<div id="overview">

</div></code>```

Body:
I'm trying to output Json data in browser using javascript but i was only able to output in console.log i don't know what to search of. I'm a beginner in javascript please help me out here.

script.js

$(document).ready(function() {
    var url = 'http://api.themoviedb.org/3/',
        mode = 'movie/',
        movie_id,
        key = '?api_key=e9dfeccf734a61b9a52d9d7660f0d0a1';

    $('button').click(function() {
        var input = $('#movie').val(),
            movie_id = encodeURI(input);
        $.ajax({
            type: 'GET',
            url: url + mode + movie_id + key,
            async: false,
            jsonpCallback: 'testing',
            contentType: 'application/json',
            dataType: 'jsonp',
            success: function(json) {
                console.dir(json);
            },
            error: function(e) {
                console.log(e.message);
            }
        });
    });
});

index.php

<input id="movie" type="text" /><button>Search</button>

This code output all the data in console.log but i wanna do is it should display data in browser and i wanna output some specific objects like title of movie and overview and image.

Body:
Retrieve the specific values using key and show it. The object have keys and values. Doing object.key will give the value

$(document).ready(function() {
  var url = 'https://api.themoviedb.org/3/',
    mode = 'movie/',
    movie_id,
    key = '?api_key=e9dfeccf734a61b9a52d9d7660f0d0a1';

  $('button').click(function() {
    var input = $('#movie').val(),
      movie_id = encodeURI(input);
    $.ajax({
      type: 'GET',
      url: url + mode + movie_id + key,
      async: false,
      jsonpCallback: 'testing',
      contentType: 'application/json',
      dataType: 'jsonp',
      success: function(json) {
        $("#title").text(json.title);
        //$("#movTitle").prop('src'); // add image path here
        $("#overview").text(json.overview) //overview is a key
      },
      error: function(e) {
        console.log(e.message);
      }
    });
  });
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="movie" type="text" /><button>Search</button>
<!-- Search This: 346364 -->
<div id="title">
</div>
<div>
  <img id="movTitle" src="" alt="">
</div>
<div id="overview">

</div>


答:
I think you don't have "TEXT". and fstream::open don't make file when if file that you want to read do not exist.

so you may try in different stream to read and write.

following code will help you.

```<code>#include<iostream>
#include<fstream>
#include<cstring>

using namespace std;

int main()
{
    char str[80];
    cout << "Enter a string : ";
    cin >> str;
    int len = strlen(str);

    ofstream fout;
    fout.open("TEXT.txt");

    for (int i = 0; i<len; i++)
        fout.put(str[i]);

    fout.close();

    ifstream fin;
    fin.open("TEXT.txt");

    char ch;
    cout << "\nPrintitng Contents....\n";

    while (!fin.eof())
    {
        fin.get(ch);
        cout << ch;
        ch = NULL;
    }

    fin.close();

    return 0;
}
</code>```

and you may improve your code like this

```<code>#include <iostream>
#include <fstream>
#include <string>

using namespace std;

int main()
{
    string str;

    cout << "Enter a string : ";
    cin >> str;

    ofstream fout;
    fout.open("TEXT.txt");

    fout << str;

    fout.close();

    str.clear();

    ifstream fin;
    fin.open("TEXT.txt");

    cout << "\nPrintitng Contents....\n";

    fin >> str;
    cout << str;

    fin.close();

    return 0;
}
</code>```

Title: get() function in c++ not working for files

Body:
I think you don't have "TEXT". and fstream::open don't make file when if file that you want to read do not exist.

so you may try in different stream to read and write.

following code will help you.

#include<iostream>
#include<fstream>
#include<cstring>

using namespace std;

int main()
{
    char str[80];
    cout << "Enter a string : ";
    cin >> str;
    int len = strlen(str);

    ofstream fout;
    fout.open("TEXT.txt");

    for (int i = 0; i<len; i++)
        fout.put(str[i]);

    fout.close();

    ifstream fin;
    fin.open("TEXT.txt");

    char ch;
    cout << "\nPrintitng Contents....\n";

    while (!fin.eof())
    {
        fin.get(ch);
        cout << ch;
        ch = NULL;
    }

    fin.close();

    return 0;
}

and you may improve your code like this

#include <iostream>
#include <fstream>
#include <string>

using namespace std;

int main()
{
    string str;

    cout << "Enter a string : ";
    cin >> str;

    ofstream fout;
    fout.open("TEXT.txt");

    fout << str;

    fout.close();

    str.clear();

    ifstream fin;
    fin.open("TEXT.txt");

    cout << "\nPrintitng Contents....\n";

    fin >> str;
    cout << str;

    fin.close();

    return 0;
}


问:
'CLLocationManagerDelegate' cannot be constructed because it has no accessible initializers
I am a newbie coder and I am using a tutorial to help me learn.

I am making a weather app, but I am receiving this error and was hoping someone could help.

'CLLocationManagerDelegate' cannot be constructed because it has no accessible initializers

Thank you.

答:
WeatherViewController is already the CLLocationManagerDelegate.

You should be instantiating CLLocationManager instead:

```<code>let locationManager = CLLocationManager()
</code>```

Body:
WeatherViewController is already the CLLocationManagerDelegate.

You should be instantiating CLLocationManager instead:

let locationManager = CLLocationManager()