问:
How to get user infomation with uid in firebase?

What I want to make

A system in which users send messages to administrators.

Progress

get uid (success)

get user info (fail)

If the user leaves a message, the administrator wants to see a list of them.

In the database,

```<code>messages {
    uid1 {
        key1 {
            name : "user name"
            text : "text that user remained"
            created_at : "time that message created"
        }
        key2 {
            …
        }
        …
    }

    uid2 {
        …
    }
}
</code>```

I store the information as above. now be able to view this information as a list on the admin page..(and admin click on the list to see the message.)

However, I have succeeded in loading each uid, but I do not know how to use `uid 'to fetch the user's information.

Here is the output(now):

```<code><div>uid1</div>
<div>uid2</div>
</code>```

Here is the code:

```<code>function getListItem() {
  var messagesRef = database.ref('personalchats') //personalchats 에 있는 uid로 접근
  messagesRef.on('child_added', setListItem);
  messagesRef.on('child_changed', setListItem);

}

function setListItem(data) {
  var key = data.key;

  var html = '<div class="listitem"> ' + key + '</div>;

   $(".collection").append(html);
}
</code>```

I want this result to be:

```<code><div>userName1 : current message</div>
<div>userName2 : current message</div>
...
</code>```

What can I do for it?

Thank you.

答:
convert the data using data() and then extract it using the value names given in the database.</p>

```<code>   function getListItem() {
      var messagesRef = database.ref('personalchats') //personalchats
      messagesRef.on('child_added', setListItem);
      messagesRef.on('child_changed', setListItem);
    }

   function setListItem(data) {
      var key = data.key;
      // create a variable to store the data
      var dataVal=data.val();
      var msgtext=dataVal.text;

      var html = '<div class="listitem"> ' + key + ': '+ msgtext</div>;
       $(".collection").append(html);
    }
</code>```

Body:
What I want to make

A system in which users send messages to administrators.

Progress

get uid (success)

get user info (fail)

If the user leaves a message, the administrator wants to see a list of them.

In the database,

messages {
    uid1 {
        key1 {
            name : "user name"
            text : "text that user remained"
            created_at : "time that message created"
        }
        key2 {
            …
        }
        …
    }

    uid2 {
        …
    }
}

I store the information as above. now be able to view this information as a list on the admin page..(and admin click on the list to see the message.)

However, I have succeeded in loading each uid, but I do not know how to use `uid 'to fetch the user's information.

Here is the output(now):

uid1

uid2

Here is the code:

function getListItem() {
  var messagesRef = database.ref('personalchats') //personalchats 에 있는 uid로 접근
  messagesRef.on('child_added', setListItem);
  messagesRef.on('child_changed', setListItem);

}

function setListItem(data) {
  var key = data.key;

  var html = '
 ' + key + '
;

   $(".collection").append(html);
}

I want this result to be:

userName1 : current message

userName2 : current message

...

What can I do for it?

Thank you.

Body:
convert the data using data() and then extract it using the value names given in the database.

   function getListItem() {
      var messagesRef = database.ref('personalchats') //personalchats
      messagesRef.on('child_added', setListItem);
      messagesRef.on('child_changed', setListItem);
    }

   function setListItem(data) {
      var key = data.key;
      // create a variable to store the data
      var dataVal=data.val();
      var msgtext=dataVal.text;

      var html = '<div class="listitem"> ' + key + ': '+ msgtext</div>;
       $(".collection").append(html);
    }


来源: stackexchange

问:
Java servlets - navigate to page
I have the following project structure:

I am trying to navigate to concerts.jsp from index.jsp:

index.jsp

```<code><li class="active"><a href="/ConcertsController">Concerts</a></li>
</code>```

This is my ConcertsController:

```<code>@WebServlet("/ConcertsController")
public class ConcertsController extends HttpServlet {
    private static final long serialVersionUID = 1L;

    public ConcertsController() {
        super();
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.getWriter().append("Served at: ").append(request.getContextPath());
        request.getRequestDispatcher("/WEB-INF/pages/concerts.jsp").forward(request, response);
    }
        ...
    }
</code>```

When I run the app, and click on the link in index.jsp, localhost:8080/ConcertsController URL opens and I get the

The requested resource is not available

error.

Edit 1: I am using Tomcat v7.0, servlets v3.0 and Java 8.

Edit 2 (possible duplicate): Well, surely I need to be able to do this without using the jstl library.

Edit 3: When localhost:8080/ConcertsController opens, I get the "resource not found" error. But when I manually edit the url to localhost:8080/AppName/ConcertsController, it works.

答:
Use

```<code>           <a href="${pageContext.request.contextPath}/ConcertsController">
</code>```

Also when forwarding the request to cencerts.jsp use ServletContext.getRequestDispatcher(....)

ServletRequest.getRequestDispatcher() method will evaluate the path relative to the path of the request. But for the method of ServletContext, the path parameter cannot be relative and must start with /( / means at the root of web application not current relative path).

ContentLicense: CC BY-SA 3.0

Title: Java servlets - navigate to page

Body:
I have the following project structure:

I am trying to navigate to concerts.jsp from index.jsp:

index.jsp

Concerts

This is my ConcertsController:

@WebServlet("/ConcertsController")
public class ConcertsController extends HttpServlet {
    private static final long serialVersionUID = 1L;

    public ConcertsController() {
        super();
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.getWriter().append("Served at: ").append(request.getContextPath());
        request.getRequestDispatcher("/WEB-INF/pages/concerts.jsp").forward(request, response);
    }
        ...
    }

When I run the app, and click on the link in index.jsp, localhost:8080/ConcertsController URL opens and I get the

The requested resource is not available

error.

Edit 1: I am using Tomcat v7.0, servlets v3.0 and Java 8.

Edit 2 (possible duplicate): Well, surely I need to be able to do this without using the jstl library.

Edit 3: When localhost:8080/ConcertsController opens, I get the "resource not found" error. But when I manually edit the url to localhost:8080/AppName/ConcertsController, it works.

Body:
Use

           <a href="${pageContext.request.contextPath}/ConcertsController">

Also when forwarding the request to cencerts.jsp use ServletContext.getRequestDispatcher(....)

ServletRequest.getRequestDispatcher() method will evaluate the path relative to the path of the request. But for the method of ServletContext, the path parameter cannot be relative and must start with /( / means at the root of web application not current relative path).


问:
Filter a list in python get integers
I have a list:

```<code>['Jack', 18, 'IM-101', 99.9]
</code>```

How do I filter it to get only the integers from it??

I tried

```<code>map(int, x)
</code>```

but it gives error.

```<code>ValueError: invalid literal for int()
  with base 10: 'Jack'
</code>```

答:
Use filter:

```<code>filter(lambda e: isinstance(e, int), x)
</code>```

Title: Filter a list in python get integers

Body:
I have a list:

['Jack', 18, 'IM-101', 99.9]

How do I filter it to get only the integers from it??

I tried

map(int, x)

but it gives error.

ValueError: invalid literal for int()
  with base 10: 'Jack'

Body:
Use filter:

filter(lambda e: isinstance(e, int), x)


问:
Which construction is faster?
Which construction is faster:

```<code>$a = $b * $c ? $b * $c : 0;
</code>```

or

```<code>$i = $b * $c;
$a = $i ? $i : 0;
</code>```

All variables are local ones.

Does speed differs for mulitplication, addition, substraction and division?

Update:

Here's some clarification:

This is a theoretical question about writing speed-optimized code from scratch. Not about "searching bottlenecks".

I can measure code speed by myself. But it's was not a question about homework of using microtime(). It was a question about how PHP-interpreter works (what I tried to figure out by digging google myself but was unseccusfull).

Moreover - I did measuring with myself and was a little confused. Different starting values of $a, $b and $c (combinations of zeros, negative, positive, integer and floats) produce different results between constructions. So I was confused.

BoltClock provide me usefull info but user576875 made my day by posting a link to opcode decoder! His answer contains also direct answer to my question. Thanks!

答:
```<code><?php
function run(){
$b=10;
$c=10;
$start=gettimeofday(TRUE);
for($k=0;$k<10000000;$k++){
  $a = $b * $c ? $b * $c : 0;
}
printf("%f\n", gettimeofday(TRUE)-$start);
$start=gettimeofday(TRUE);
for($k=0;$k<10000000;$k++){
  $i = $b * $c;
  $a = $i ? $i : 0;
}
printf("%f\n", gettimeofday(TRUE)-$start);
}
run();
?>
</code>```

On my system (PHP 5.3.3, Linux, Core i7 2.8GHz), I get

```<code>1.593521
1.512892
</code>```

So the separate assignment is slightly faster. For addition, (+ instead of *), I get the reverse result:

```<code>1.386522
1.450358
</code>```

So you really need to measure these on your own system - with a different PHP version, the outcome may change again.

ContentLicense: CC BY-SA 2.5

Title: Which construction is faster?

Body:
Which construction is faster:

$a = $b * $c ? $b * $c : 0;

or

$i = $b * $c;
$a = $i ? $i : 0;

All variables are local ones.

Does speed differs for mulitplication, addition, substraction and division?

Update:

Here's some clarification:

This is a theoretical question about writing speed-optimized code from scratch. Not about "searching bottlenecks".

I can measure code speed by myself. But it's was not a question about homework of using microtime(). It was a question about how PHP-interpreter works (what I tried to figure out by digging google myself but was unseccusfull).

Moreover - I did measuring with myself and was a little confused. Different starting values of $a, $b and $c (combinations of zeros, negative, positive, integer and floats) produce different results between constructions. So I was confused.

BoltClock provide me usefull info but user576875 made my day by posting a link to opcode decoder! His answer contains also direct answer to my question. Thanks!

Body:
<?php
function run(){
$b=10;
$c=10;
$start=gettimeofday(TRUE);
for($k=0;$k<10000000;$k++){
  $a = $b * $c ? $b * $c : 0;
}
printf("%f\n", gettimeofday(TRUE)-$start);
$start=gettimeofday(TRUE);
for($k=0;$k<10000000;$k++){
  $i = $b * $c;
  $a = $i ? $i : 0;
}
printf("%f\n", gettimeofday(TRUE)-$start);
}
run();
?>

On my system (PHP 5.3.3, Linux, Core i7 2.8GHz), I get

1.593521
1.512892

So the separate assignment is slightly faster. For addition, (+ instead of *), I get the reverse result:

1.386522
1.450358

So you really need to measure these on your own system - with a different PHP version, the outcome may change again.


问:
How can I solve "java.lang.NoClassDefFoundError"?
I've tried both the examples in Oracle's Java Tutorials. They both compile fine, but at run time, both come up with this error:

Exception in thread "main" java.lang.NoClassDefFoundError: graphics/shapes/Square
    at Main.main(Main.java:7)
Caused by: java.lang.ClassNotFoundException: graphics.shapes.Square
    at java.net.URLClassLoader$1.run(URLClassLoader.java:366)
    at java.net.URLClassLoader$1.run(URLClassLoader.java:355)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.net.URLClassLoader.findClass(URLClassLoader.java:354)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:308)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
    ... 1 more
```
<p>I think I might have the <code>Main.java</code> file in the wrong folder.</p>
<p>Here is the directory hierarchy:</p>
<pre class="lang-none prettyprint-override"><code>graphics
├ Main.java
├ shapes
|   ├ Square.java
|   ├ Triangle.java
├ linepoint
|   ├ Line.java
|   ├ Point.java
├ spaceobjects
|   ├ Cube.java
|   ├ RectPrism.java
</code>```

And here is Main.java:

```<code>import graphics.shapes.*;
import graphics.linepoint.*
import graphics.spaceobjects.*;

public class Main {
    public static void main(String args[]) {
        Square s = new Square(2, 3, 15);
        Line l = new Line(1, 5, 2, 3);
        Cube c = new Cube(13, 32, 22);
    }
}
</code>```

What am I doing wrong here?

UPDATE

After I put put the Main class into the graphics package (I added package graphics; to it), set the classpath to "_test" (folder containing graphics), compiled it, and ran it using java graphics.Main (from the command line), it worked.

Really late UPDATE #2

I wasn't using Eclipse (just Notepad++ and the JDK), and the above update solved my problem. However, it seems that many of these answers are for Eclipse and IntelliJ IDEA, but they have similar concepts.

答:
I use the FileSync plugin for Eclipse, so I can live debug on Tomcat. I received NoClassFoundError, because I had added a sync entry for the bin directory in the Eclipse workspace => classes in the metadata for Tomcat, but I hadn't also added a folder sync for the extlib directory in Eclipse =>

C:\Users\Stuart\eclipse-workspace\.metadata\.plugins\org.eclipse.wst.server.core\tmp0\webapps\myApp\WEB-INF\lib

ContentLicense: CC BY-SA 4.0

Body:
I've tried both the examples in Oracle's Java Tutorials. They both compile fine, but at run time, both come up with this error:

Exception in thread "main" java.lang.NoClassDefFoundError: graphics/shapes/Square
    at Main.main(Main.java:7)
Caused by: java.lang.ClassNotFoundException: graphics.shapes.Square
    at java.net.URLClassLoader$1.run(URLClassLoader.java:366)
    at java.net.URLClassLoader$1.run(URLClassLoader.java:355)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.net.URLClassLoader.findClass(URLClassLoader.java:354)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:308)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
    ... 1 more

I think I might have the Main.java file in the wrong folder.

Here is the directory hierarchy:

graphics
├ Main.java
├ shapes
|   ├ Square.java
|   ├ Triangle.java
├ linepoint
|   ├ Line.java
|   ├ Point.java
├ spaceobjects
|   ├ Cube.java
|   ├ RectPrism.java

And here is Main.java:

import graphics.shapes.*;
import graphics.linepoint.*
import graphics.spaceobjects.*;

public class Main {
    public static void main(String args[]) {
        Square s = new Square(2, 3, 15);
        Line l = new Line(1, 5, 2, 3);
        Cube c = new Cube(13, 32, 22);
    }
}

What am I doing wrong here?

UPDATE

After I put put the Main class into the graphics package (I added package graphics; to it), set the classpath to "_test" (folder containing graphics), compiled it, and ran it using java graphics.Main (from the command line), it worked.

Really late UPDATE #2

I wasn't using Eclipse (just Notepad++ and the JDK), and the above update solved my problem. However, it seems that many of these answers are for Eclipse and IntelliJ IDEA, but they have similar concepts.


问:
How to send email while form submission with saving data in database

Currently, our form is saving data in database on form submission but now we want (for example: to send email to email@example.com) as well. Below is the code but we are not sure, which script and where exactly we need to add.

```<code>              <!-- Nav tabs -->
              <ul class="nav nav-tabs" role="tablist" id="myTabs">
                <li role="presentation" class="active"><a href="#home" aria-controls="home" role="tab" data-toggle="tab">Project Brief Form</a></li>
                <li role="presentation"><a href="#profile" aria-controls="profile" role="tab" data-toggle="tab">Contact Form</a></li>
              </ul>
              <!-- Tab panes -->
              <div class="tab-content">
                <div role="tabpanel" class="tab-pane active" id="home">
                    <form  action="#" method="post" enctype="multipart/form-data" id="project">
                        <div class="row">
                            <div class="col-sm-12">
                                <div class="form-group">
                                    <label>Tell us about your project in your own words? What is, for you, the main goal of the project? *</label>
                                    <textarea class="form-control" rows="4" name="project" required></textarea>
                                </div>
                            </div>
                            <div class="col-sm-6">
                              <div class="form-group">
                                <label>Full name</label>
                                <input type="text" class="form-control" placeholder="Full name" name="name" required>
                              </div>
                              <div class="form-group">
                                <label>Email / Skypename</label>
                                <input type="text" class="form-control" placeholder="Email / Skypename" name="email" required>
                              </div>
                              <div class="form-group">
                                <label>Phone</label>
                                <input type="number" class="form-control" placeholder="Phone" name="phone" required>
                              </div>
                            </div>
                            <div class="col-sm-6">
                              <div class="form-group">
                                <label>How much do you want to spend?</label>
                                <select class="form-control" name="spend" required>
                                  <option value="500 - 3000 $">500 - 3000 $</option>
                                  <option value="3000 - 10000 $">3000 - 10000 $</option>
                                  <option value="10000 - 50000 $">10000 - 50000 $</option>
                                  <option value="50000 - 250000 $">50000 - 250000 $</option>
                                  <option value="250000 $ +">250000 $ +</option>
                                </select>
                              </div>
                              <div class="form-group">
                                <label>Which services are you interested in?</label>
                                <input type="text" class="form-control" placeholder="Which services are you interested in?" name="service" required>
                              </div>
                              <div class="form-group">
                                <label>How did you find out about us?</label>
                                <input type="text" class="form-control" placeholder="Example: Google, Facebook, Behance..." name="about" required>
                              </div>
                            </div>
                            <div class="col-sm-12 text-center">
                                <button type="submit" id="btnSubmit" onclick="SubmitForm('project','dubai','add_project')" class="btn btn-default">Submit</button>
                          </div>
                          <div id="result"></div>
                        </div>
                    </form>
                </div>
                <div role="tabpanel" class="tab-pane" id="profile">
                    <form  action="#" method="post" enctype="multipart/form-data" id="contact">
                        <div class="row">
                            <div class="col-sm-12">
                              <div class="form-group">
                                <label>Full name</label>
                                <input type="text" class="form-control" placeholder="Full name" name="name" required>
                              </div>
                              <div class="form-group">
                                <label>Email</label>
                                <input type="email" class="form-control" placeholder="Email" name="email" required>
                              </div>
                              <div class="form-group">
                                <label>Phone number</label>
                                <input type="number" class="form-control" placeholder="Phone number" name="phone" required>
                              </div>
                            </div>
                            <div class="col-sm-12">
                                <div class="form-group">
                                    <label>Tell us about your project in your own words? What is, for you, the main goal of the project? *</label>
                                    <textarea class="form-control" onclick="SubmitForm('contact','skyhigh','add_contact')" rows="4" name="about"></textarea>
                                </div>
                            </div>
                            <div class="col-sm-12 text-center">
                                <button type="submit" class="btn btn-default">Submit</button>
                            </div>
                            <div id="massage"></div>
                        </div>
                    </form>
                </div>
              </div>
            </div>

            <script type="text/javascript">
                $('#myTabs a').click(function (e) {
                  e.preventDefault()
                  $(this).tab('show');
                });
            </script>
        </div>
    </div>
</div>
</code>```

```<code>              <script type="text/javascript">
function SubmitForm(FormID, Controller, FunctionName) {
           $("#"+FormID).unbind('submit').submit(function (event) {
               var formData = $( this ).serialize();
               $.ajax({
                        type: 'POST',
                        url: "<?php echo $this->config->base_url(); ?>" + Controller + "/"+ FunctionName,
                        data: formData
                    })
                    .done(function (data) {
                        if(FormID=="project")
                        {
                        // $("#"+ ResultDivId).html(data);
                          $('<center><div class="alert alert-success success-order"><h4>Your Data Send Successfully, We will Contact You Soon.</h4></div></center>').insertBefore('#result').delay(10000).fadeOut();
                        }
                        else
                        {
                          $('<center><div class="alert alert-success success-order"><h4>Your Data Send Successfully, We will Contact You Soon.</h4></div></center>').insertBefore('#massage').delay(10000).fadeOut();
                        }
                    });

                    event.preventDefault();
                    $("#"+FormID)[0].reset();
                });
        }
</script>
</code>```

We want to send emails while form submission as its saving data in database only.

答:
For this you will need a mailing system. On www.packagist.org you can find a lot of very good working composer installing projects.

For example:
https://packagist.org/packages/swiftmailer/swiftmailer

Please read the documentation on how to install and use them.

Composer can be found here incase you are not using it yet: https://getcomposer.org/

To send an email:

The mailing system is basically being called near the moment you save your data into the database.

Body:
Currently, our form is saving data in database on form submission but now we want (for example: to send email to email@example.com) as well. Below is the code but we are not sure, which script and where exactly we need to add.

Project Brief Form

Contact Form

                    <form  action="#" method="post" enctype="multipart/form-data" id="project">

                                    Tell us about your project in your own words? What is, for you, the main goal of the project? *
                                    <textarea class="form-control" rows="4" name="project" required></textarea>

                                Full name
                                <input type="text" class="form-control" placeholder="Full name" name="name" required>

                                Email / Skypename
                                <input type="text" class="form-control" placeholder="Email / Skypename" name="email" required>

                                Phone
                                <input type="number" class="form-control" placeholder="Phone" name="phone" required>

                                How much do you want to spend?
                                <select class="form-control" name="spend" required>
                                  <option value="500 - 3000 $">500 - 3000 $</option>
                                  <option value="3000 - 10000 $">3000 - 10000 $</option>
                                  <option value="10000 - 50000 $">10000 - 50000 $</option>
                                  <option value="50000 - 250000 $">50000 - 250000 $</option>
                                  <option value="250000 $ +">250000 $ +</option>
                                </select>

                                Which services are you interested in?
                                <input type="text" class="form-control" placeholder="Which services are you interested in?" name="service" required>

                                How did you find out about us?
                                <input type="text" class="form-control" placeholder="Example: Google, Facebook, Behance..." name="about" required>

                                <button type="submit" id="btnSubmit" onclick="SubmitForm('project','dubai','add_project')" class="btn btn-default">Submit</button>

                    </form>

                    <form  action="#" method="post" enctype="multipart/form-data" id="contact">

                                Full name
                                <input type="text" class="form-control" placeholder="Full name" name="name" required>

                                Email
                                <input type="email" class="form-control" placeholder="Email" name="email" required>

                                Phone number
                                <input type="number" class="form-control" placeholder="Phone number" name="phone" required>

                                    Tell us about your project in your own words? What is, for you, the main goal of the project? *
                                    <textarea class="form-control" onclick="SubmitForm('contact','skyhigh','add_contact')" rows="4" name="about"></textarea>

                                <button type="submit" class="btn btn-default">Submit</button>

                    </form>

We want to send emails while form submission as its saving data in database only.


问:
how to minimise a long && statement - Java
I would like to check if all of the items in array squareData[] is 5.

I could just do this:

if(squareData[0] == 5 && squareData[1] == 5 && ...){...}

But it seems rather inefficient.

Is there a way to minimise this into a for loop of some kind?

Note that the size of squareData[] is 9 items

Thanks!

答:
Assuming your input in an int[], you can use Streams:

```<code>if (Arrays.stream(squareData).allMatch(i -> i==5)) {

}
</code>```

This will return true if all the elements in your array satisfy the condition i==5.

Body:
Assuming your input in an int[], you can use Streams:

if (Arrays.stream(squareData).allMatch(i -> i==5)) {

}

This will return true if all the elements in your array satisfy the condition i==5.


问:
Generate a 10-digit random number
I want to generate a random number with exactly 10-digits.

The random number cannot begin with zero, i.e. it must be a 10 digit number, not 10 random digits.

答:
You need a random integer, between 1000000000 (the lowest integer with 10 digits) and 9999999999 (the highest number with 10 digits).

Note that 1000000000 = 1e9 and 9999999999 = 1e10 - 1

The random integer generation can easily achieved with randi (see the documentation here), giving it the correct minimum and maximum values...

```<code>n = randi([1e9, 1e10-1])
</code>```

Title: Generate a 10-digit random number

Body:
You need a random integer, between 1000000000 (the lowest integer with 10 digits) and 9999999999 (the highest number with 10 digits).

Note that 1000000000 = 1e9 and 9999999999 = 1e10 - 1

The random integer generation can easily achieved with randi (see the documentation here), giving it the correct minimum and maximum values...

n = randi([1e9, 1e10-1])


问:
Entity Framework Relationships - Preferred Customer Address
Assuming a Customer can have multiple addresses, but only one "Preferred" address. How can I make it so a property on the model class holds the preferred address only and work using lambda expression through another object, for example Order?

My model classes looks like this:

```<code>public class Cusotmer
{
   public virtual int Id {get; set;}
   public virtual HashSet<Address> Addresses {get; set;}
   public virtual Address PreferredAddress => Addresses.FirstOrDefault(x => x.Preferred)
}

public class Order
{
    public virtual int Id {get; set;}
    public virtual Customer Customer {get; set;}
}
</code>```

I would like this to work:

```<code>_context.Order.Where(x => x.Id == 20).Select(x => x.Person.PreferredAddress);
</code>```

However I get an error saying:

"The specified type member 'PreferredAddress' is not supported in LINQ
  to Entities. Only initializers, entity members, and entity navigation
  properties are supported."

答:
You can't. It is not possible. Because you are using Linq to entities and these Linq statements are being converting to SQL query.So, there is no SQL equivalent for PreferredAddress property. The statement can't be converted to SQL query for this reason.

So, why don't you just try like this;

```<code>_context.Order.Where(x => x.Id == 20).Select(x => x.Person.Addresses.FirstOrDefault(x => x.Preferred));
</code>```

Body:
Assuming a Customer can have multiple addresses, but only one "Preferred" address. How can I make it so a property on the model class holds the preferred address only and work using lambda expression through another object, for example Order?

My model classes looks like this:

public class Cusotmer
{
   public virtual int Id {get; set;}
   public virtual HashSet<Address> Addresses {get; set;}
   public virtual Address PreferredAddress => Addresses.FirstOrDefault(x => x.Preferred)
}

public class Order
{
    public virtual int Id {get; set;}
    public virtual Customer Customer {get; set;}
}

I would like this to work:

_context.Order.Where(x => x.Id == 20).Select(x => x.Person.PreferredAddress);

However I get an error saying:

"The specified type member 'PreferredAddress' is not supported in LINQ
  to Entities. Only initializers, entity members, and entity navigation
  properties are supported."

Body:
You can't. It is not possible. Because you are using Linq to entities and these Linq statements are being converting to SQL query.So, there is no SQL equivalent for PreferredAddress property. The statement can't be converted to SQL query for this reason.

So, why don't you just try like this;

_context.Order.Where(x => x.Id == 20).Select(x => x.Person.Addresses.FirstOrDefault(x => x.Preferred));


问:
Adding an image to UITableViewCell in edit mode isn't aligning properly
I am using the code below to try to get the this look:

but instead it looks like:

```<code>func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]? {
    let deleteRowAction = UITableViewRowAction(style: UITableViewRowActionStyle.default, title: "Delete") { action, indexPath in

    }
    deleteRowAction.backgroundColor = UIColor.red
    deleteRowAction.backgroundColor = UIColor(patternImage: UIImage(named: "DeleteIcon.png")!)
    return [deleteRowAction]
    }
</code>```

What am I doing wrong?

答:
Just change:

```<code>deleteRowAction.backgroundColor = UIColor(patternImage: UIImage(named: "DeleteIcon.png")!)
</code>```

to:

```<code>deleteRowAction.image = UIImage(named: "DeleteIcon.png")
</code>```

And it should work.

Body:
I am using the code below to try to get the this look:

but instead it looks like:

func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]? {
    let deleteRowAction = UITableViewRowAction(style: UITableViewRowActionStyle.default, title: "Delete") { action, indexPath in

    }
    deleteRowAction.backgroundColor = UIColor.red
    deleteRowAction.backgroundColor = UIColor(patternImage: UIImage(named: "DeleteIcon.png")!)
    return [deleteRowAction]
    }

What am I doing wrong?

Body:
Just change:

deleteRowAction.backgroundColor = UIColor(patternImage: UIImage(named: "DeleteIcon.png")!)

to:

deleteRowAction.image = UIImage(named: "DeleteIcon.png")

And it should work.


问:
To add a Serial Number as the First Column in a GridView
I have a Grid View . It has two bound columns. I need to have a Serial Number column as the first column.

How can i do that ?
Thanks in Advance

答:
Create a datatable with two columns use a first column as autoincrement as true and AutoIncrementStep=1 like</p>

```<code>DataTable _test = new DataTable();
DataColumn c = new DataColumn("sno", typeof(int));
c.AutoIncrement = true;
c.AutoIncrementSeed = 1;
c.AutoIncrementStep = 1;
_test.Columns.Add(c);
_test.Columns.Add("description");
gvlisting.DataSource = _test;
</code>```

Body:
Create a datatable with two columns use a first column as autoincrement as true and AutoIncrementStep=1 like

DataTable _test = new DataTable();
DataColumn c = new DataColumn("sno", typeof(int));
c.AutoIncrement = true;
c.AutoIncrementSeed = 1;
c.AutoIncrementStep = 1;
_test.Columns.Add(c);
_test.Columns.Add("description");
gvlisting.DataSource = _test;


问:
check previous and current element of array
Imagine: I have a an array: ["1", "2", "X", ".", "4", "3", "Z", "-", "12"];

I consider which function should I use to:

find first NaN element in array (let say index = 2) and check if the next (index = 3) is also NaN and if yes (delete from array element with index = 2).

So the result of the transformed array should be: ["1", "2",".", "4", "3", "-", "12"];

I do not want your code, just suggestion/help how to start it.

Thank you for your responses and help.

答:
You can use a for loop to iterate over the array and keep track of the current and previous element.

Then you can and use isNaN to check if both values ares NaN or not.

If both are NaN, you can then use splice to remove the item at index i-1 (the equivalent of previous):

arr = ["1", "2", "X", ".", "4", "3", "Z", "-", "12"];

var previous = null;
for (var i = 0; i < arr.length; i++) {
  var current = arr[i];
  if(isNaN(previous) && isNaN(current)) {
     arr.splice(i-1, 1);
  }
  previous = current;
}

console.log(arr); //[ '1', '2', '.', '4', '3', '-', '12' ]```


问:
CSS - jpg image repeating
I am re-writing a website and i have inserted a background.
The background image is repeating.
I've tried various ways on setting the repeat = n without any luck.

Here is the current html section:

```<code><html xmlns='http://www.w3.org/1999/xhtml'>
<head>
    <meta http-equiv='Content-Type' content='text/html; charset=UTF-8' />
    <title>Site down | Maintenance</title>
    <META NAME="ROBOTS" CONTENT="NOINDEX, NOFOLLOW">
    <style type='text/css'>
        html,
        body {
            padding: 0;
            border: 0
        }

        .Header_image {
            padding- left: 20px
        }

        h1 {
            font-family: "verdana";
            padding: 0px;
            margin: 0px;
            font- size: 16pt;
            color: #D5261e
        }

        h3 {
            font-family: "verdana";
            padding: 0px;
            margin: 1px;
            font-size: 11pt;
        }

        p {
            font-family: "verdana";
            font-size: 13;
        }

        div.wide_rhn {
            padding-bottom: 17px
        }

        div.pg_three_col_border {
            BORDER-right: #e8e8e8 1px solid;
            BORDER-left: #e8e8e8 1px solid;
            background-color: #FFFFFF;
            PADDING-TOP: 11px;
            PADDING- LEFT: 17px;
            padding-bottom: 11px;
            font-family: arial;
            font-size: 75%;
            width: 763px;
            ^width: 782px
        }

        table.HP_table_header {
            position: relative;
            z-index: 200;
            padding- bottom: 10px;
            padding-top: 10px;
            *padding-bottom: 12px
        }

        td.HP_mainmenu {
            border: #878787 1px solid
        }

        table.HP_Image_table {
            MARGIN-LEFT: 124px;
            MARGIN-TOP: 1000px
        }
    </style>
</head>

<body background="man-with-no-shoes.jpg">

    <table class='HP_table_header' width='960' align='center' border='0' cellpadding='0' cellspacing='0'>
        <tbody>
            <tr>
                <td class='Header_image' width='189' align='left' height='74'>
                    <img src='images/test_logo.jpg' border='0' />
                </td>
            </tr>
        </tbody>
    </table>
    <table class='bg_body' width='1006' align='center' border='0' cellpadding='0' cellspacing='0' style='height: 500px;'>
        <tbody>
            <tr>
                <td valign='top'>
                    <table width='960' align='center' border='0' cellpadding='0' cellspacing='0'>
                        <tbody>
                            <tr>
                                <td valign='top' width='782' align='left'>
                                    <div id='WiderhPagetitlemain'>
</code>```

答:
Here you go buddy:</p>

```<code>    <html xmlns='http://www.w3.org/1999/xhtml'>
    <head>
    <meta http-equiv='Content-Type' content='text/html; charset=UTF-8' />
    <title>Site down | Maintenance</title>
    <META NAME="ROBOTS" CONTENT="NOINDEX, NOFOLLOW">
    <style type='text/css'>html,body {padding:0;border:0}.Header_image {padding-
    left:20px}
    h1 {font-family:"verdana" ; padding:0px;margin:0px;font-
    size:16pt;color:#D5261e}
    h3 {font-family:"verdana" ; padding:0px;margin:1px;font-size:11pt;}
    p {font-family:"verdana" ; font-size:13;}
    div.wide_rhn {padding-bottom:17px}
    div.pg_three_col_border {BORDER-right: #e8e8e8 1px solid;BORDER-left:
    #e8e8e8 1px solid;background-color:#FFFFFF;PADDING-TOP:11px;PADDING-
    LEFT:17px;padding-bottom:11px;font-family:arial;font-size:75%;width:
    763px;^width: 782px}
    table.HP_table_header {position:relative;z-index:200;padding-
    bottom:10px;padding-top:10px;*padding-bottom:12px}
    td.HP_mainmenu {border:#878787 1px solid}
    table.HP_Image_table {MARGIN-LEFT:124px;MARGIN-TOP:1000px}

body {
    background-image: url(man-with-no-shoes.jpg);
    background-repeat: no-repeat;
    }
    </style>

    </head>
    <body>

    <table class='HP_table_header' width='960' align='center' border='0'
    cellpadding='0'cellspacing='0'>
    <tbody>
    <tr>
    <td class='Header_image' width='189' align='left' height='74'><img
    src='images/test_logo.jpg' border='0' /></td>
    </tr>
    </tbody>
    </table>
    <table class='bg_body' width='1006' align='center' border='0'
    cellpadding='0' cellspacing='0'style='height: 500px;'>
    <tbody>
    <tr>
    <td valign='top'>
    <table width='960' align='center' border='0' cellpadding='0'
    cellspacing='0'>
    <tbody>
    <tr>
    <td valign='top' width='782' align='left'>
    <div id='WiderhPagetitlemain'>
</code>```

Title: CSS - jpg image repeating

Body:
I am re-writing a website and i have inserted a background.
The background image is repeating.
I've tried various ways on setting the repeat = n without any luck.

Here is the current html section:

    <meta http-equiv='Content-Type' content='text/html; charset=UTF-8' />
    <title>Site down | Maintenance</title>
    <META NAME="ROBOTS" CONTENT="NOINDEX, NOFOLLOW">

Body:
Here you go buddy:

    <html xmlns='http://www.w3.org/1999/xhtml'>
    <head>
    <meta http-equiv='Content-Type' content='text/html; charset=UTF-8' />
    <title>Site down | Maintenance</title>
    <META NAME="ROBOTS" CONTENT="NOINDEX, NOFOLLOW">
    <style type='text/css'>html,body {padding:0;border:0}.Header_image {padding-
    left:20px}
    h1 {font-family:"verdana" ; padding:0px;margin:0px;font-
    size:16pt;color:#D5261e}
    h3 {font-family:"verdana" ; padding:0px;margin:1px;font-size:11pt;}
    p {font-family:"verdana" ; font-size:13;}
    div.wide_rhn {padding-bottom:17px}
    div.pg_three_col_border {BORDER-right: #e8e8e8 1px solid;BORDER-left:
    #e8e8e8 1px solid;background-color:#FFFFFF;PADDING-TOP:11px;PADDING-
    LEFT:17px;padding-bottom:11px;font-family:arial;font-size:75%;width:
    763px;^width: 782px}
    table.HP_table_header {position:relative;z-index:200;padding-
    bottom:10px;padding-top:10px;*padding-bottom:12px}
    td.HP_mainmenu {border:#878787 1px solid}
    table.HP_Image_table {MARGIN-LEFT:124px;MARGIN-TOP:1000px}

body {
    background-image: url(man-with-no-shoes.jpg);
    background-repeat: no-repeat;
    }
    </style>

    </head>
    <body>

    <table class='HP_table_header' width='960' align='center' border='0'
    cellpadding='0'cellspacing='0'>
    <tbody>
    <tr>
    <td class='Header_image' width='189' align='left' height='74'><img
    src='images/test_logo.jpg' border='0' /></td>
    </tr>
    </tbody>
    </table>
    <table class='bg_body' width='1006' align='center' border='0'
    cellpadding='0' cellspacing='0'style='height: 500px;'>
    <tbody>
    <tr>
    <td valign='top'>
    <table width='960' align='center' border='0' cellpadding='0'
    cellspacing='0'>
    <tbody>
    <tr>
    <td valign='top' width='782' align='left'>
    <div id='WiderhPagetitlemain'>


问:
GRPC server response latency
First off, has anyone done a performance comparison for throughput/latency between a GRPC client-server implementation v/s a websocket+protobuf client-server implementation? Or at least something similary.

In order to reach this goal, I am trying out the example JAVA helloworld grpc client-server and trying to compare the latency of the response with a similar websocket client-server. Currently i am trying this out with both client and server on my local machine.

The websocket client-server has a simple while loop on the server side. For the grpc server i notice that it uses an asynchronous execution model. I suspect it creates a new thread for each client request, resulting in additional processing overheads. For instance, the websocket response latency i am measuring is in the order of 6-7 ms and the grpc example is showing a latency of about 600-700ms, accounting for protobuf overhead.

In order to do a similar comparison for grpc, is there a way to run the grpc server synchronously? I want to be able to eliminate the overhead of the thread creation/dispatch and other such internal overhead introduced by the asynchronous handling.

I do understand that there is a protobuf overhead involved in grpc that is not there in my websocket client-server example. However i can account for that by measuring the overhead introduced by protobuf processing.

Also, if i cannot run the grpc server synchronously, can i at least measure the thread dispatch/asynchronous processing overhead?

I am relatively new to JAVA, so pardon my ignorance.

答:
In order to do a similar comparison for grpc, is there a way to run the grpc server synchronously? I want to be able to eliminate the overhead of the thread creation/dispatch and other such internal overhead introduced by the asynchronous handling.

You can create a synchronous client. Generally the asynchronous is way faster. (Tested in Scala) You can simply use all resources you got in an non-blocking way. I would create a test on how many request from how many clients the server can handle per second. You can than limit the incoming request per client to make sure that your service will not crash. Asynchronous is also better for HTTP 2. HTTP 2 provides Multiplexing.

For a Benchmark I can recommend Metrics. You can expose the metrics via log or http endpoint.

Title: GRPC server response latency


问:
Using whereRaw() and orWhereRaw() with Join in laravel 5.2
I am writing a code like this:-

```<code>$results = User::select('users.id','users.user_type','users.status','homechef_details.user_id','homechef_details.address1','homechef_details.name','homechef_details.updated_rating')
        ->join('homechef_details', function($query) use ($rating,$keyword) {
            $query->on('users.id', '=', 'homechef_details.user_id');
            $query->where('users.status','=',1);
            if(isset($rating) && !empty($rating))
            {
                if(count($rating)==1)
                    $query->whereRaw('FLOOR(homechef_details.updated_rating) = '.$rating[0]);
                else if(count($rating)>1)
                {
                    $query->where(function($q) use($rating)
                    {
                        $q->whereRaw('FLOOR(homechef_details.updated_rating) = '.$rating[0]);
                        for($r = 1; $r < count($rating); $r++)
                        {
                           $q->orWhereRaw('FLOOR(homechef_details.updated_rating) = '.$rating[$r]);
                        }
                    });
                }
            }
        })->get();
</code>```

I need to check the floor value of the column value in the where clause. I am getting this error:-

```<code>Call to undefined method Illuminate\Database\Query\JoinClause::whereRaw()
</code>```

How can I fix this error?

答:
It seems that the JoinClause class doesn't have a method for raw queries, i suggest you try soemthing like </p>

```<code>$results = User::select('users.id','users.user_type','users.status','homechef_details.user_id','homechef_details.address1','homechef_details.name','homechef_details.updated_rating')
        ->join('homechef_details','users.id', '=', 'homechef_details.user_id')->where('users.status','=',1);
            if(isset($rating) && !empty($rating))
            {
                if(count($rating)==1)
                   $results = $results->whereRaw('FLOOR(homechef_details.updated_rating) = '.$rating[0]);
                else if(count($rating)>1)
                {
                   $results = $results->where(function($q) use($rating)
                    {
                        $q->whereRaw('FLOOR(homechef_details.updated_rating) = '.$rating[0]);
                        for($r = 1; $r < count($rating); $r++)
                        {
                           $q->orWhereRaw('FLOOR(homechef_details.updated_rating) = '.$rating[$r]);
                        }
                    });
                }
            }
 $results = $results->get();
</code>```

Body:
I am writing a code like this:-

$results = User::select('users.id','users.user_type','users.status','homechef_details.user_id','homechef_details.address1','homechef_details.name','homechef_details.updated_rating')
        ->join('homechef_details', function($query) use ($rating,$keyword) {
            $query->on('users.id', '=', 'homechef_details.user_id');
            $query->where('users.status','=',1);
            if(isset($rating) && !empty($rating))
            {
                if(count($rating)==1)
                    $query->whereRaw('FLOOR(homechef_details.updated_rating) = '.$rating[0]);
                else if(count($rating)>1)
                {
                    $query->where(function($q) use($rating)
                    {
                        $q->whereRaw('FLOOR(homechef_details.updated_rating) = '.$rating[0]);
                        for($r = 1; $r < count($rating); $r++)
                        {
                           $q->orWhereRaw('FLOOR(homechef_details.updated_rating) = '.$rating[$r]);
                        }
                    });
                }
            }
        })->get();

I need to check the floor value of the column value in the where clause. I am getting this error:-

Call to undefined method Illuminate\Database\Query\JoinClause::whereRaw()

How can I fix this error?

Body:
It seems that the JoinClause class doesn't have a method for raw queries, i suggest you try soemthing like

$results = User::select('users.id','users.user_type','users.status','homechef_details.user_id','homechef_details.address1','homechef_details.name','homechef_details.updated_rating')
        ->join('homechef_details','users.id', '=', 'homechef_details.user_id')->where('users.status','=',1);
            if(isset($rating) && !empty($rating))
            {
                if(count($rating)==1)
                   $results = $results->whereRaw('FLOOR(homechef_details.updated_rating) = '.$rating[0]);
                else if(count($rating)>1)
                {
                   $results = $results->where(function($q) use($rating)
                    {
                        $q->whereRaw('FLOOR(homechef_details.updated_rating) = '.$rating[0]);
                        for($r = 1; $r < count($rating); $r++)
                        {
                           $q->orWhereRaw('FLOOR(homechef_details.updated_rating) = '.$rating[$r]);
                        }
                    });
                }
            }
 $results = $results->get();


问:
Copy/merge data from 2 workbooks to one master workbook
I have 2 spreadsheets that are identical being filled out by different people. I tried to then get their separate data to copy into a mater spreadsheet that is the same as the first but hopefully with the 2 sets of data combined.
I've managed to set up a command button "submit" into my sheet that will copy rows from one spreadsheet but when the other person presses "submit" it just overrides the others data...
I know I need to write a loop and if but I can't get it work.

```<code>Private Sub CommandButton3_Click()

Application.ScreenUpdating = False

Dim wkb1 As Workbook
Dim sht1 As Worksheet
Dim wkb2 As Workbook
Dim sht2 As Worksheet

Set wkb1 = ThisWorkbook
Set wkb2 = Workbooks.Open("X:\TA Info\MASTER.xlsx")
Set sht1 = wkb1.Sheets("Sheet1")
Set sht2 = wkb2.Sheets("Sheet1")

sht1.Cells.Copy
sht2.Range("A1").PasteSpecial xlPasteValues
Application.CutCopyMode = False
wkb2.Close True

Application.ScreenUpdating = True

End Sub
</code>```

I understand this is a very unique question but I will appreciate any guidance anyone has the time to offer.

Thank you.

答:
Your line

```<code> sht2.Range("A1").PasteSpecial xlPasteValues
</code>```

Always pastes into range A1, overwriting anything there. To append the data below existing data use

```<code>  sht2.Range("A" & sht2.rows.count).End(xlup).offset(1,0).PasteSpecial xlPasteValues
</code>```

Ahh - but you can't copy all the cells in a sheet except into A1 - so we need to only copy the used cells. Changing

```<code>  sht1.Cells.Copy
</code>```

into

```<code>  sht1.UsedRange.Cells.Copy
</code>```

Body:
I have 2 spreadsheets that are identical being filled out by different people. I tried to then get their separate data to copy into a mater spreadsheet that is the same as the first but hopefully with the 2 sets of data combined.
I've managed to set up a command button "submit" into my sheet that will copy rows from one spreadsheet but when the other person presses "submit" it just overrides the others data...
I know I need to write a loop and if but I can't get it work.

Private Sub CommandButton3_Click()

Application.ScreenUpdating = False

Dim wkb1 As Workbook
Dim sht1 As Worksheet
Dim wkb2 As Workbook
Dim sht2 As Worksheet

Set wkb1 = ThisWorkbook
Set wkb2 = Workbooks.Open("X:\TA Info\MASTER.xlsx")
Set sht1 = wkb1.Sheets("Sheet1")
Set sht2 = wkb2.Sheets("Sheet1")

sht1.Cells.Copy
sht2.Range("A1").PasteSpecial xlPasteValues
Application.CutCopyMode = False
wkb2.Close True

Application.ScreenUpdating = True

End Sub

I understand this is a very unique question but I will appreciate any guidance anyone has the time to offer.

Thank you.

Body:
Your line

 sht2.Range("A1").PasteSpecial xlPasteValues

Always pastes into range A1, overwriting anything there. To append the data below existing data use

  sht2.Range("A" & sht2.rows.count).End(xlup).offset(1,0).PasteSpecial xlPasteValues

Ahh - but you can't copy all the cells in a sheet except into A1 - so we need to only copy the used cells. Changing

  sht1.Cells.Copy

into

  sht1.UsedRange.Cells.Copy


问:
Expand and collapse with AngularJS
I am trying to figure out a way to do an expand and collapse using AngularJS. I haven't been able to find an elegant way to do this without manipulating DOM objects in the controller (which is not the Angular way).

Currently I have a nice way to do it for a one layer expand and collapse. However when I start nesting, things get complicated, and don't work the way I want it to (expanding and collapsing multiple areas when they shouldn't be).

The problem comes in by me not knowing how to send a unique identifier with an ng-click to only expand/collapse the right content. I should mention that these items are in an ng-repeat so I can necessarily customize parameters being sent.

I was able to use this jsfiddle to help me get a one layer expand and collapse to work. However this is a toggle way to do it and I want the user to be able to keep things expanded while expanding others. So what I did to fix this was use an array of and every time something is clicked the index of that clicked item would be added to the array and the class expanded. When the user clicked again the index was removed from the array and the area was collapsed.

Another way I found that you can do it is by using directives. But I can't really find any exampled to wrap my head around how directives work. I am not sure how to even start when it comes to writing directives.

My current set up is this:

```<code>function Dexspander($scope) {
    $scope.ExpandArray = [];

    //Push or pop necessary elements for tracking
    $scope.DespopulatArray = function (identifier, element) {
    if (_.indexOf($scope.ExpandArray, identifier + element) != -1) {
            $scope.ExpandArray.splice(_.indexOf($scope.ExpandArray, identifier + element), 1);
        } else {
            $scope.ExpandArray.push(identifier + element);
        }
    }

    //Change class of necessary elements
    $scope.Dexspand = function (identifier, element) {
        if (_.indexOf($scope.ExpandArray, identifier + element) != -1) {
            return "expand";
        } else {
            return "collapse";
        }
    }
}

<div class="user-header" ng-repeat="user in users">
    <h1 ng-click="DespopulatArray('user', $index)">Expand</h1>
</div>
<div class="user-content" ng:class="Dexspand('user', $index)">
    <div class="content">
        <div class="user-information">
            <div class="info-header">
                <h1 ng-click="DespopulatArray('info', $index)>Some Information</h1>
            </div>
            <div class="info-contents" ng:class="Dexspand('info', $index)">
                stuff stuff stuff stuff...
            </div>
        </div>
    </div>
</div>
</code>```

The issue with this setup is that if I have to parent divs expanded and those both have something under them to expand, clicking the expand text will expand them in both areas as they are not unique.

答:
In html

```<code>button ng-click="myMethod()">Videos</button>
</code>```

In angular

```<code> $scope.myMethod = function () {
         $(".collapse").collapse('hide');    //if you want to hide
         $(".collapse").collapse('toggle');  //if you want toggle
         $(".collapse").collapse('show');    //if you want to show
}
</code>```

Title: Expand and collapse with AngularJS

Body:
I am trying to figure out a way to do an expand and collapse using AngularJS. I haven't been able to find an elegant way to do this without manipulating DOM objects in the controller (which is not the Angular way).

Currently I have a nice way to do it for a one layer expand and collapse. However when I start nesting, things get complicated, and don't work the way I want it to (expanding and collapsing multiple areas when they shouldn't be).

The problem comes in by me not knowing how to send a unique identifier with an ng-click to only expand/collapse the right content. I should mention that these items are in an ng-repeat so I can necessarily customize parameters being sent.

I was able to use this jsfiddle to help me get a one layer expand and collapse to work. However this is a toggle way to do it and I want the user to be able to keep things expanded while expanding others. So what I did to fix this was use an array of and every time something is clicked the index of that clicked item would be added to the array and the class expanded. When the user clicked again the index was removed from the array and the area was collapsed.

Another way I found that you can do it is by using directives. But I can't really find any exampled to wrap my head around how directives work. I am not sure how to even start when it comes to writing directives.

My current set up is this:

function Dexspander($scope) {
    $scope.ExpandArray = [];

    //Push or pop necessary elements for tracking
    $scope.DespopulatArray = function (identifier, element) {
    if (_.indexOf($scope.ExpandArray, identifier + element) != -1) {
            $scope.ExpandArray.splice(_.indexOf($scope.ExpandArray, identifier + element), 1);
        } else {
            $scope.ExpandArray.push(identifier + element);
        }
    }

    //Change class of necessary elements
    $scope.Dexspand = function (identifier, element) {
        if (_.indexOf($scope.ExpandArray, identifier + element) != -1) {
            return "expand";
        } else {
            return "collapse";
        }
    }
}

Expand

Some Information

                stuff stuff stuff stuff...

The issue with this setup is that if I have to parent divs expanded and those both have something under them to expand, clicking the expand text will expand them in both areas as they are not unique.

Body:
In html

button ng-click="myMethod()">Videos</button>

In angular

 $scope.myMethod = function () {
         $(".collapse").collapse('hide');    //if you want to hide
         $(".collapse").collapse('toggle');  //if you want toggle
         $(".collapse").collapse('show');    //if you want to show
}


问:
Jprofiler Agent Install error Centos 7
I am trying to Install Jprofiler agent of Centos 7 64 bit with Java 8 and Tomcat 8

root@ads [/opt/jprofiler9]# jpenable
    Connecting to org.apache.catalina.startup.Bootstrap start [23360] ...
    Please select the profiling mode:
    GUI mode (attach with JProfiler GUI) [1, Enter]
    Offline mode (use config file to set profiling settings) [2]
    1
    Please enter a profiling port
    [59687]
    8849

ERROR: Attaching is not supported: Unable to open socket file: target process not responding or HotSpot VM not loaded
com.sun.tools.attach.AttachNotSupportedException: Unable to open socket file: target process not responding or HotSpot VM not loaded
 at sun.tools.attach.LinuxVirtualMachine.<init>(LinuxVirtualMachine.java:100)
 at sun.tools.attach.LinuxAttachProvider.attachVirtualMachine(LinuxAttachProvider.java:63)
 at com.sun.tools.attach.VirtualMachine.attach(VirtualMachine.java:195)
 at com.jprofiler.a.d.b(ejt:292)
 at com.jprofiler.a.d.a(ejt:279)
 at com.jprofiler.a.d.a(ejt:249)
 at com.jprofiler.cli.EnableApplication.a(ejt:132)
 at com.jprofiler.cli.EnableApplication.h(ejt:95)
 at com.jprofiler.cli.b.a(ejt:26)
 at com.jprofiler.cli.EnableApplication.main(ejt:272)
 at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
 at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
 at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
 at java.lang.reflect.Method.invoke(Method.java:498)
 at com.exe4j.runtime.LauncherEngine.launch(LauncherEngine.java:65)
 at com.install4j.runtime.launcher.UnixLauncher.main(UnixLauncher.java:57)```

答:
Are you using sudo to run jpenable ?
Dont use sudo to start jpenable as well as the java process.</p>

Title: Jprofiler Agent Install error Centos 7


问:
Swift How to fix errors with Target Membership?
I am beginner to Swift and I am not aware of all the little details, so please forgive if it's a stupid question

My app is in quite advanced stage of development, so I would like to not mess with the existing code as little as possible. My problem is that I want to implement Today Extension in my app, in it I want to display a tableView that will display data from a single array from my "Plum" class and I need one method from the class to handle the selection. Unfortunately when I change the Plum's target membership to TodayExtension a whole bunch of errors are shown because many APIs from that class aren't available to TodayExtension. The class inherits from AVAudioPlayer so most essential methods aren't available in Extension.
I tried to create a helper class that would get the array from Plum and return it in method to my TableView but that still doesn't work because of "Use of unresolved identifier 'Plum'"

How can I obtain the array and use the method?

答:
Adding the Plum class in the today extension is a bad idea. Extensions should be lightweight and you only need to transfer the data needed.

In your case you may need the array of title and description. So form a array of dictionary with needed details and store these details in App group user defaults like @Hitesh answer.

In your today extension class, read this array from the user defaults then display the details in the table view.


问:
SQL Splitting strings
I have the following two strings in a table:

```<code>CN=ABCDEFG,OU=7SOE,OU=TEMP,OU=Sydney,OU=Australia,DC=LDAP,DC=COM
CN=ABCDEFGHIJ,OU=7SOEFHU,OU=TEST,OU=TEMP,OU=London,OU=Europe,DC=LDAP,DC=COM
</code>```

I want to extract the following information from these two:

```<code>Sydney
London
</code>```

I started using RIGHT, SUBSTRING and CHARINDEX but couldn't get the pattern correct from the right splitting it up essentially via the 'OU=' from the right. Looks messy and can't see an elegant way of splitting strings as you could in C#. - SQL 2014.

答:
you can use Split String function in SQL to split your astring to array and then accessing row with 'OU=' substring. syntax for that is as followed

```<code>SELECT value FROM STRING_SPLIT('Lorem,ipsum,dolor,sit,amet.', ',');
</code>```

or can use method described here

Split data in sql with multiple delimiters ( , and - ) with owns rule

and

https://raresql.com/2013/01/10/sql-server-split-string-into-rows-based-on-multiple-delimiters/

Title: SQL Splitting strings

Body:
I have the following two strings in a table:

CN=ABCDEFG,OU=7SOE,OU=TEMP,OU=Sydney,OU=Australia,DC=LDAP,DC=COM
CN=ABCDEFGHIJ,OU=7SOEFHU,OU=TEST,OU=TEMP,OU=London,OU=Europe,DC=LDAP,DC=COM

I want to extract the following information from these two:

Sydney
London

I started using RIGHT, SUBSTRING and CHARINDEX but couldn't get the pattern correct from the right splitting it up essentially via the 'OU=' from the right. Looks messy and can't see an elegant way of splitting strings as you could in C#. - SQL 2014.

Body:
you can use Split String function in SQL to split your astring to array and then accessing row with 'OU=' substring. syntax for that is as followed

SELECT value FROM STRING_SPLIT('Lorem,ipsum,dolor,sit,amet.', ',');

or can use method described here

Split data in sql with multiple delimiters ( , and - ) with owns rule

and

https://raresql.com/2013/01/10/sql-server-split-string-into-rows-based-on-multiple-delimiters/


问:
OO like behaviour in CSS: inheritance possible?
I have a simple border style say:

```<code>.border
{
   /*content*/
}
</code>```

I want several other classes to inherit this border style. Can this be done in CSS only?
Or do I need to specify it in HTML also?

I want:

```<code>.actionArea : .border
{
     /*content */
}
</code>```

Or can this only be done in HTML like:

```<code><div class="actionArea border"/>
</code>```

It would be very annoying if the latter is only possible.

Update

This works good enough, but still is a bit ugly:

```<code>.actionArea, .otherArea, .anotherArea
{
    /*border specification */
}

.actionArea
{
    /*area specification/*
}

.otherArea
{
    /*area specification/*
}

(..)
</code>```

答: You will need to use a CSS framework such as LESS for such a thing.</p>

Body:
I have a simple border style say:

.border
{
   /*content*/
}

I want several other classes to inherit this border style. Can this be done in CSS only?
Or do I need to specify it in HTML also?

I want:

.actionArea : .border
{
     /*content */
}

Or can this only be done in HTML like:

It would be very annoying if the latter is only possible.

Update

This works good enough, but still is a bit ugly:

.actionArea, .otherArea, .anotherArea
{
    /*border specification */
}

.actionArea
{
    /*area specification/*
}

.otherArea
{
    /*area specification/*
}

(..)


问:
How to send model data from view to api controller using ajax
I am trying to send the value from my this view to given API controller.It is working when i hard-code the json data.I am unable to send the data of id and brandname when i press the button since it is in table. How do I make it work?Please help

```<code>  <table class="table">
    <tr>
        <th>
            @Html.DisplayNameFor(model => model.Brand.BrandName)
        </th>
                <th>
            @Html.DisplayNameFor(model => model.ProductName)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.Price)
        </th>

        <th></th>
    </tr>

@foreach (var item in Model) {
    <tr>
        <td>
            @Html.DisplayFor(modelItem => item.Brand.BrandName)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.ProductName)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.Price)
        </td>
      <td><input type="button" id="Save" /></td>

    </tr>
}

</table>
@section scripts {
<script>
    $(document).ready(function () {
        $("#Save").click(function () {

            var brand = { 'id':1, 'brandname': 'abc' }

            $.ajax({
                url: 'http://localhost:51429/api/brands',
                type: 'POST',
                dataType: 'json',
                data: brand,
                success: function (data, textStatus, xhr) {
                    console.log(data);
                },
                error: function (xhr, textStatus, errorThrown) {
                    console.log('Error in Operation');
                }
            });

        });
    });

   </script>
    }
</code>```

I have a brand API. And it post API controller is

```<code>    [HttpPost]
    public IHttpActionResult Post([FromBody]Brands brand)
    {
        if (!ModelState.IsValid)
        {
            return BadRequest(ModelState);
        }
        db.Brands.Add(brand);
        db.SaveChanges();

        return CreatedAtRoute("DefaultApi", new { id = brand.Id }, brand);

    }
</code>```

答:
There are different approaches to get controls values from views, one solution can be wrap the
...
 with a form tag like

```<code><form id="Form1">
<table class="table">
 <tr>
    <th>
        @Html.DisplayNameFor(model => model.Brand.BrandName)
    </th>
            <th>
        @Html.DisplayNameFor(model => model.ProductName)
    </th>
    <th>
        @Html.DisplayNameFor(model => model.Price)
    </th>

    <th></th>
</tr>

@foreach (var item in Model) {
<tr>
    <td>
        @Html.DisplayFor(modelItem => item.Brand.BrandName)
    </td>
    <td>
        @Html.DisplayFor(modelItem => item.ProductName)
    </td>
    <td>
        @Html.DisplayFor(modelItem => item.Price)
    </td>
  <td><input type="button" id="Save" /></td>

 </tr>
}

</table>
</form>
</code>```

Access control values like

```<code>var brand = $('#Form1').serialize();

$.ajax({
     url: 'http://localhost:51429/api/brands',
     type: 'POST',
     dataType: 'json',
     data: brand,
     success: function (data, textStatus, xhr) {
          console.log(data);
     },
     error: function (xhr, textStatus, errorThrown) {
            console.log('Error in Operation');
     }
});
</code>```

Body:
I am trying to send the value from my this view to given API controller.It is working when i hard-code the json data.I am unable to send the data of id and brandname when i press the button since it is in table. How do I make it work?Please help

            @Html.DisplayNameFor(model => model.Brand.BrandName)

            @Html.DisplayNameFor(model => model.ProductName)

            @Html.DisplayNameFor(model => model.Price)

@foreach (var item in Model) {

            @Html.DisplayFor(modelItem => item.Brand.BrandName)

            @Html.DisplayFor(modelItem => item.ProductName)

            @Html.DisplayFor(modelItem => item.Price)

      <input type="button" id="Save" />

}

@section scripts {

    }

I have a brand API. And it post API controller is

    [HttpPost]
    public IHttpActionResult Post([FromBody]Brands brand)
    {
        if (!ModelState.IsValid)
        {
            return BadRequest(ModelState);
        }
        db.Brands.Add(brand);
        db.SaveChanges();

        return CreatedAtRoute("DefaultApi", new { id = brand.Id }, brand);

    }

Body:
There are different approaches to get controls values from views, one solution can be wrap the <table>...</table> with a form tag like

<form id="Form1">
<table class="table">
 <tr>
    <th>
        @Html.DisplayNameFor(model => model.Brand.BrandName)
    </th>
            <th>
        @Html.DisplayNameFor(model => model.ProductName)
    </th>
    <th>
        @Html.DisplayNameFor(model => model.Price)
    </th>

    <th></th>
</tr>

@foreach (var item in Model) {
<tr>
    <td>
        @Html.DisplayFor(modelItem => item.Brand.BrandName)
    </td>
    <td>
        @Html.DisplayFor(modelItem => item.ProductName)
    </td>
    <td>
        @Html.DisplayFor(modelItem => item.Price)
    </td>
  <td><input type="button" id="Save" /></td>

 </tr>
}

</table>
</form>

Access control values like

var brand = $('#Form1').serialize();

$.ajax({
     url: 'http://localhost:51429/api/brands',
     type: 'POST',
     dataType: 'json',
     data: brand,
     success: function (data, textStatus, xhr) {
          console.log(data);
     },
     error: function (xhr, textStatus, errorThrown) {
            console.log('Error in Operation');
     }
});


问:
Gradle: How to display androidTest results in the console?
As explained in other threads Gradle can be configured to log test results into the console:

Gradle Android: How to Display test results without using --info

Gradle: How to Display Test Results in the Console in Real Time?

Output unit testing results on console using spock junit testing and gradle build system

Basically, this can be setup through the following task:

```<code>tasks.withType(Test) {
    testLogging {
       // Custom configuration
    }
}
</code>```

This works fine for unit tests and looks somewhat like this:

```<code>...
:app:assembleDebugUnitTest
:app:testDebugUnitTest
:app:processDebugResources

com.example.StringsTest > formatValue PASSED
com.example.StringsTest > formatValueWithDecimals FAILED

1 test completed, 1 failed
</code>```

Besides, unit tests I also run integration test using the following command:

```<code>$ ./gradlew connectedAndroidTest
</code>```

When I look at the output in the console I am missing the individual test results as being written for unit tests. How can I configure test logging for instrumentation tests?

答:
The easy version is just to use:

./gradlew connectedAndroidTest --info

it take a littlebit to log it in the terminal/console window, but it's showing everything nice, colored and formatted

like …

```<code>…ShowsIntroduction[SM-G950F - 7.0] SUCCESS
…BackButtonReturnsToOnboardingScreen[SM-G950F - 7.0] SKIPPED
</code>```

good luck && have fun

Body:
As explained in other threads Gradle can be configured to log test results into the console:

Gradle Android: How to Display test results without using --info

Gradle: How to Display Test Results in the Console in Real Time?

Output unit testing results on console using spock junit testing and gradle build system

Basically, this can be setup through the following task:

tasks.withType(Test) {
    testLogging {
       // Custom configuration
    }
}

This works fine for unit tests and looks somewhat like this:

...
:app:assembleDebugUnitTest
:app:testDebugUnitTest
:app:processDebugResources

com.example.StringsTest > formatValue PASSED
com.example.StringsTest > formatValueWithDecimals FAILED

1 test completed, 1 failed

Besides, unit tests I also run integration test using the following command:

$ ./gradlew connectedAndroidTest

When I look at the output in the console I am missing the individual test results as being written for unit tests. How can I configure test logging for instrumentation tests?

Body:
The easy version is just to use:

./gradlew connectedAndroidTest --info

it take a littlebit to log it in the terminal/console window, but it's showing everything nice, colored and formatted

like …

…ShowsIntroduction[SM-G950F - 7.0] SUCCESS
…BackButtonReturnsToOnboardingScreen[SM-G950F - 7.0] SKIPPED

good luck && have fun


问:
Android MapBox change style of MyLocation marker
I'm using the MapBox API for Android (v5.1). I managed to get it to work all fine and I'm using a custom style (the light style but slightly modified).

I've enabled MyLocation and it is also working just fine. But the dot (or marker) that displays my location on the map (in GoogleMaps it's blue) has is light grey so it's barely visible on the map.

Is there any way to change it's color? I already tried to get the belongong layer but I couldn't find it, neither in the MapBox Studio nor in Android. Where can I customize it?

I found one possible solution (althoug it's meant for Google Maps) that would also work but that is - in my opinion - not a good solution.

答:
Displaying of location is now deprecated in MapboxMap. Recommended solution is to use LocationLayerPlugin.

EDIT
Since 0.4.0 Mapbox now has the prefix mapbox_ before each attribute. The new style names can be found here https://github.com/mapbox/mapbox-plugins-android/blob/master/plugin-locationlayer/src/main/res/values/styles.xml.

To change my location marker, you can add custom style into styles.xml that is inherited from mapbox_LocationLayer and override mapbox_foregroundDrawable item.

```<code><style name="CustomLocationLayer" parent="mapbox_LocationLayer">
    <item name="mapbox_foregroundDrawable">@drawable/location</item>
</style>
</code>```

Then you can create the layer with this style:

```<code>LocationLayerPlugin(mapView, mapboxMap, locationEngine, R.style.CustomLocationLayer)
</code>```

Body:
Displaying of location is now deprecated in MapboxMap. Recommended solution is to use LocationLayerPlugin.

EDIT
Since 0.4.0 Mapbox now has the prefix mapbox_ before each attribute. The new style names can be found here https://github.com/mapbox/mapbox-plugins-android/blob/master/plugin-locationlayer/src/main/res/values/styles.xml.

To change my location marker, you can add custom style into styles.xml that is inherited from mapbox_LocationLayer and override mapbox_foregroundDrawable item.

<style name="CustomLocationLayer" parent="mapbox_LocationLayer">
    <item name="mapbox_foregroundDrawable">@drawable/location</item>
</style>

Then you can create the layer with this style:

LocationLayerPlugin(mapView, mapboxMap, locationEngine, R.style.CustomLocationLayer)


问:
TextView and EditText in single Row in Android?
I am writing XML in following way, list_item2 contains TextView and EditText, while list_item is another XML contains only TextView,

```<code><?xml version="1.0" encoding="utf-8"?>
</code>```

```<code><TextView android:id="@+id/textItem"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:padding="10dp"
    android:textSize="16sp" >
</TextView>

    <EditText
    android:id="@+id/editText1"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content" >
</EditText>
</code>```

I am using the xml in ListView, such as

```<code>public View getView(int position, View convertView, ViewGroup parent) {
        View row;

        if(position!=2) {
                LayoutInflater inflater = getLayoutInflater();
                row = inflater.inflate(R.layout.list_item, parent, false);
        }
        else {
            LayoutInflater inflater = getLayoutInflater();
            row = inflater.inflate(R.layout.list_item2, parent, false);
        }
        TextView tv = (TextView) row.findViewById(R.id.textItem);
        tv.setText(getItem(position));

        tv.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub

            }
        });
</code>```

but It is creating output like

```<code> TextView

 EditText
</code>```

I want both on same row, such as

```<code>   TextView        EditText
</code>```

Any one edit the XML and let me know the hierarchy for creating GUI in Android Apps

答:
Nice and fast solution adopted today by many applications,
add this tags to your TextView

```<code>android:ellipsize="end"
android:maxLines="1"
</code>```

Now your textview is one row with three dots to the end.

Body:
I am writing XML in following way, list_item2 contains TextView and EditText, while list_item is another XML contains only TextView,

<?xml version="1.0" encoding="utf-8"?>

<TextView android:id="@+id/textItem"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:padding="10dp"
    android:textSize="16sp" >
</TextView>

    <EditText
    android:id="@+id/editText1"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content" >
</EditText>

I am using the xml in ListView, such as

public View getView(int position, View convertView, ViewGroup parent) {
        View row;

        if(position!=2) {
                LayoutInflater inflater = getLayoutInflater();
                row = inflater.inflate(R.layout.list_item, parent, false);
        }
        else {
            LayoutInflater inflater = getLayoutInflater();
            row = inflater.inflate(R.layout.list_item2, parent, false);
        }
        TextView tv = (TextView) row.findViewById(R.id.textItem);
        tv.setText(getItem(position));

        tv.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub

            }
        });

but It is creating output like

 TextView

 EditText

I want both on same row, such as

   TextView        EditText

Any one edit the XML and let me know the hierarchy for creating GUI in Android Apps

Body:
Nice and fast solution adopted today by many applications,
add this tags to your TextView

android:ellipsize="end"
android:maxLines="1"

Now your textview is one row with three dots to the end.


问:
fbauth2 is missing from your Info.plist under LSApplicationQueriesSchemes and is required for iOS 9.0
I am getting the log while login with Facebook. Kindly tell me how can i remove this log. I am working on ios8</p>

答:
If you're using v4.6.0 or higher of the SDK, you only need to add into your Info.plist:</p>

```<code><key>LSApplicationQueriesSchemes</key>
<array>
  <string>fbapi</string>
  <string>fb-messenger-api</string>
  <string>fbauth2</string>
  <string>fbshareextension</string>
</array>
</code>```

Body:
If you're using v4.6.0 or higher of the SDK, you only need to add into your Info.plist:

<key>LSApplicationQueriesSchemes</key>
<array>
  <string>fbapi</string>
  <string>fb-messenger-api</string>
  <string>fbauth2</string>
  <string>fbshareextension</string>
</array>


问:
how to minimise a long && statement - Java
I would like to check if all of the items in array squareData[] is 5.

I could just do this:

if(squareData[0] == 5 && squareData[1] == 5 && ...){...}

But it seems rather inefficient.

Is there a way to minimise this into a for loop of some kind?

Note that the size of squareData[] is 9 items

Thanks!

答:
I guess you are looking for something like:</p>

```<code>boolean isOk = true;
for(int i=0; i<squareData.length; i++)
    if(squareData[i]!=5)
       isOk=false;
</code>```

Body:
I guess you are looking for something like:

boolean isOk = true;
for(int i=0; i<squareData.length; i++)
    if(squareData[i]!=5)
       isOk=false;


问:
Iterating through HashMap by values
I need to loop through a HashMap, but to give importance to the values' order.
For example, consider the following hash map of <String, Integer>:

```<code>{"dog" : 2, "bird": 3, "cat" : 1}
</code>```

Now, I need to loop through the hasp map in order of ascending values, so that

```<code>for () {
 System.out.println( currentKey );
}
</code>```

will always output

"cat", "dog", "bird"

答:
Well, you may be interested in instead using a TreeMap, which sorts your entries by key.

Otherwise, you may be interested looking into Map.keySet(), Map.entrySet(), or Map.values().

If you still want to keep your Map a HashMap, you could use one of Collections' numerous functions for getting sorted collections (e.g. you could get a sorted version of your map, sort a list, etc).

Since I see you specifically want to sort by values, I think Michał Minicki's answer ought to be what you want.

Title: Iterating through HashMap by values

Body:
I need to loop through a HashMap, but to give importance to the values' order.
For example, consider the following hash map of <String, Integer>:

{"dog" : 2, "bird": 3, "cat" : 1}

Now, I need to loop through the hasp map in order of ascending values, so that

for () {
 System.out.println( currentKey );
}

will always output

"cat", "dog", "bird"


问:
Javascript fromCharCode equivalent in C#
I have a function i Javascript which looks like the following

```<code>// Use this to convert "0123DEF01234" (hex string) to
// binary data based on 0x01 0x23 0xDE 0xF0 0x12 0x34

hex = "0123456789ABCDEFFEDCBA98765432100123456789ABCDEF";

hex = hex.replace(/\s/g,""); // eliminate spaces

var keyar = hex.match(/../g); // break into array of doublets

var s="";  // holder for our return value

for(var i=0;i<keyar.length;i++)
        s += String.fromCharCode( Number( "0x" + keyar[i] ) );

return s;
</code>```

but i am not able to find the equivalent  of this line

```<code>        s += String.fromCharCode( Number( "0x" + keyar[i] ) );
</code>```

what can be the equivalent of this line?

答:
You can try using Linq:

```<code>using System.Linq;

...

string hex = "0123456789ABCDEFFEDCBA98765432100123456789ABCDEF";

// Eliminating white spaces
hex = string.Concat(hex.Where(c => !char.IsWhiteSpace(c)));

// Let "binary data based on 0x01 0x23 0xDE..." be an array
byte[] result = Enumerable
  .Range(0, hex.Length / 2) // we have hex.Length / 2 pairs
  .Select(index => Convert.ToByte(hex.Substring(index * 2, 2), 16))
  .ToArray();

// Test (let's print out the result array with items in the hex format)
Console.WriteLine(string.Join(" ", result.Select(b => $"0x{b:X2}")));
</code>```

Outcome:

```<code>0x01 0x23 0x45 0x67 0x89 0xAB 0xCD 0xEF 0xFE 0xDC 0xBA 0x98 0x76 0x54 0x32 0x10 0x01 0x23 0x45 0x67 0x89 0xAB 0xCD 0xEF
</code>```

Body:
I have a function i Javascript which looks like the following

// Use this to convert "0123DEF01234" (hex string) to
// binary data based on 0x01 0x23 0xDE 0xF0 0x12 0x34

hex = "0123456789ABCDEFFEDCBA98765432100123456789ABCDEF";

hex = hex.replace(/\s/g,""); // eliminate spaces

var keyar = hex.match(/../g); // break into array of doublets

var s="";  // holder for our return value

for(var i=0;i<keyar.length;i++)
        s += String.fromCharCode( Number( "0x" + keyar[i] ) );

return s;

but i am not able to find the equivalent  of this line

        s += String.fromCharCode( Number( "0x" + keyar[i] ) );

what can be the equivalent of this line?

Body:
You can try using Linq:

using System.Linq;

...

string hex = "0123456789ABCDEFFEDCBA98765432100123456789ABCDEF";

// Eliminating white spaces
hex = string.Concat(hex.Where(c => !char.IsWhiteSpace(c)));

// Let "binary data based on 0x01 0x23 0xDE..." be an array
byte[] result = Enumerable
  .Range(0, hex.Length / 2) // we have hex.Length / 2 pairs
  .Select(index => Convert.ToByte(hex.Substring(index * 2, 2), 16))
  .ToArray();

// Test (let's print out the result array with items in the hex format)
Console.WriteLine(string.Join(" ", result.Select(b => $"0x{b:X2}")));

Outcome:

0x01 0x23 0x45 0x67 0x89 0xAB 0xCD 0xEF 0xFE 0xDC 0xBA 0x98 0x76 0x54 0x32 0x10 0x01 0x23 0x45 0x67 0x89 0xAB 0xCD 0xEF


问:
Python - get a size of a network path folder
I'm using Python 2.7 to monitor disk usage of some application running on Windows 2012 server. How can I get a size of some network storage folder located for example here:

```<code>\\storage\my_folder\
</code>```

I've tried to use (from this post: calculating-a-directory-size-using-python ):

```<code>import os

def getFolderSize(folder):
    total_size = os.path.getsize(folder)
    for item in os.listdir(folder):
        itempath = os.path.join(folder, item)
        if os.path.isfile(itempath):
            total_size += os.path.getsize(itempath)
        elif os.path.isdir(itempath):
            total_size += getFolderSize(itempath)
    return total_size
</code>```

but of course network path is not supported.

答:
If it's a 2012 (Windows) server you may be able to use SMB.

Here's a small test program I just used to get the size of a shared folder on a Windows server. I haven't tested it exhaustively, so it may need some work, but it should give you a basis to work from.

It uses pysmb

```<code>from smb import SMBConnection

sep = '\\'

def RecursiveInspector(conn, shareName, path):
    #print path.encode('utf8')
    localSize = 0
    response = conn.listPath(shareName, path, timeout=30)
    for i in range(len(response)):
        fname = response[i].filename
        if (fname == ".") or (fname == ".."):
            continue
        if (response[i].isDirectory):
            dname = path
            if not (path.endswith(sep)):
                dname += sep
            dname += fname
            localSize += RecursiveInspector(conn, shareName, dname)
        else:
            localSize += response[i].file_size
    return localSize

conn = SMBConnection.SMBConnection("my_username",
                                   "my_password",
                                   "laptop",
                                   "the_shared_folder_name",
                                   use_ntlm_v2 = True)
conn.connect("1.2.3.4", 139)

path      = sep # start at root
totalSize = RecursiveInspector(conn, "the_shared_folder_name", path)

print totalSize
</code>```

Hope this may be useful.

Body:
I'm using Python 2.7 to monitor disk usage of some application running on Windows 2012 server. How can I get a size of some network storage folder located for example here:

\\storage\my_folder\

I've tried to use (from this post: calculating-a-directory-size-using-python ):

import os

def getFolderSize(folder):
    total_size = os.path.getsize(folder)
    for item in os.listdir(folder):
        itempath = os.path.join(folder, item)
        if os.path.isfile(itempath):
            total_size += os.path.getsize(itempath)
        elif os.path.isdir(itempath):
            total_size += getFolderSize(itempath)
    return total_size

but of course network path is not supported.

Body:
If it's a 2012 (Windows) server you may be able to use SMB.

Here's a small test program I just used to get the size of a shared folder on a Windows server. I haven't tested it exhaustively, so it may need some work, but it should give you a basis to work from.

It uses pysmb

from smb import SMBConnection

sep = '\\'

def RecursiveInspector(conn, shareName, path):
    #print path.encode('utf8')
    localSize = 0
    response = conn.listPath(shareName, path, timeout=30)
    for i in range(len(response)):
        fname = response[i].filename
        if (fname == ".") or (fname == ".."):
            continue
        if (response[i].isDirectory):
            dname = path
            if not (path.endswith(sep)):
                dname += sep
            dname += fname
            localSize += RecursiveInspector(conn, shareName, dname)
        else:
            localSize += response[i].file_size
    return localSize

conn = SMBConnection.SMBConnection("my_username",
                                   "my_password",
                                   "laptop",
                                   "the_shared_folder_name",
                                   use_ntlm_v2 = True)
conn.connect("1.2.3.4", 139)

path      = sep # start at root
totalSize = RecursiveInspector(conn, "the_shared_folder_name", path)

print totalSize

Hope this may be useful.


答:
Convert to stream and use allMatch method:</p>

```<code>java.util.stream.Stream.of(squareData).allMatch(v -> v == 5)
</code>```

Title: how to minimise a long && statement - Java

Body:
I would like to check if all of the items in array squareData[] is 5.

I could just do this:

if(squareData[0] == 5 && squareData[1] == 5 && ...){...}

But it seems rather inefficient.

Is there a way to minimise this into a for loop of some kind?

Note that the size of squareData[] is 9 items

Thanks!

Body:
Convert to stream and use allMatch method:

java.util.stream.Stream.of(squareData).allMatch(v -> v == 5)


问:
Getting Error in Asmx Web Service Unit Testing
I am getting below error message while running unit test for ASMX web service

Failed MyFunction The ASP.NET Web application at 'D:\MyProjectFolder' is already configured for testing by another test run. Only one test run at a time can run tests in ASP.NET. If there are no other test runs using this Web application, ensure that the Web.config file does not contain an httpModule named HostAdapter.

I checked in web.config. Below line already added in web.config. i removed below line to run test again but getting same error message.

```<code><httpModules>
  <add name="HostAdapter" type="Microsoft.VisualStudio.TestTools.HostAdapter.Web.HttpModule, Microsoft.VisualStudio.QualityTools.HostAdapters.ASPNETAdapter, Version=10.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
</httpModules>
</code>```

i am not able to debug unit test project.

答:
Just comment these tags:

```<code>[HostType("ASP.NET")]
[AspNetDevelopmentServerHost(""]
[UrlToTest("http://localhost...")]
</code>```

It worked for me after this.

Body:
I am getting below error message while running unit test for ASMX web service

Failed MyFunction The ASP.NET Web application at 'D:\MyProjectFolder' is already configured for testing by another test run. Only one test run at a time can run tests in ASP.NET. If there are no other test runs using this Web application, ensure that the Web.config file does not contain an httpModule named HostAdapter.

I checked in web.config. Below line already added in web.config. i removed below line to run test again but getting same error message.

<httpModules>
  <add name="HostAdapter" type="Microsoft.VisualStudio.TestTools.HostAdapter.Web.HttpModule, Microsoft.VisualStudio.QualityTools.HostAdapters.ASPNETAdapter, Version=10.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
</httpModules>

i am not able to debug unit test project.

Body:
Just comment these tags:

[HostType("ASP.NET")]
[AspNetDevelopmentServerHost(""]
[UrlToTest("http://localhost...")]

It worked for me after this.


问:
boost time_facet causes an exception that cannot be caught
Here is a simple example of the application

```<code>#include <string>
#include <boost/date_time/posix_time/posix_time.hpp>

int main()
{
    try
    {
        auto date = boost::posix_time::microsec_clock::local_time();

        // boost::posix_time::time_facet* facet = new boost::posix_time::time_facet("%d-%b-%Y %H:%M:%S"); --> this format works
        boost::posix_time::time_facet* facet = new boost::posix_time::time_facet("%d-%b-%Y %k:%M:%s"); // --> this format causes an exception that can't be handled
        std::stringstream ss;

        ss.imbue(std::locale(ss.getloc(), facet));
        //ss.exceptions(std::ios::badbit | std::ios::failbit);
        ss << date; // --> exception occurs here - It can't be caught.
        std::cout << ss.str() << std::endl;
    }
    catch (const std::exception& ex)
    {
        std::cerr << "std::exception " << ex.what() << std::endl;
    }
    catch (const boost::exception&)
    {
        std::cerr << "boost::exception " << std::endl;
    }
    catch (...)
    {
        std::cerr << "unknown exception" << std::endl;
    }

    return 0;
}
</code>```

The problem is with a certain format passed to the facet - either %k or %l cause the issue.   When a date is formatted using this format there is an exception. The exception is not caught by the exception handler - the program exits!

I am creating a library function so I need to assume invalid format strings will happen.  I am ok with an exception - I just need to be able to handle it and report the error, or confirm that the facet is valid before using it.

This happens on Windows 10.  The error is in the wcsftime function.  Also wcsftime is a wide char function, and I am using 8 bit char.  The application is compiled in Visual Studio 2017 with MultiByte character set rather than Unicode.

The issue occurs in the debugger with the above assertion.  Running the release build from the command line causes the application to crash and pop up the 'Application has stopped working' windows dialog.

The boost version is 1.65.1

What am I doing wrong?

答:
One of the things you're doing wrong is using MBCS...  Definitely not recommended.  Windows' native string format is UNICODE, and all functions ending with A transform the input strings, then call their W counterparts.

Why the call to new?  There surely is enough space on the stack for the time format.

Anyway, the dialog you are seeing shows a assertion failed message.  It is a debug breakpoint (__asm int 3;), not an exception.  It also is only present in the debug version of the runtime library.

You should try compiling a release build, or hitting the 'ignore' button and watch your app catching the exception.

[edit] after investigation, strftime() causes the app to crash. An invalid format string is considered a fatal error by the C runtime library.  Go figure why, but that's the way it is.

Body:
Here is a simple example of the application

#include <string>
#include <boost/date_time/posix_time/posix_time.hpp>

int main()
{
    try
    {
        auto date = boost::posix_time::microsec_clock::local_time();

        // boost::posix_time::time_facet* facet = new boost::posix_time::time_facet("%d-%b-%Y %H:%M:%S"); --> this format works
        boost::posix_time::time_facet* facet = new boost::posix_time::time_facet("%d-%b-%Y %k:%M:%s"); // --> this format causes an exception that can't be handled
        std::stringstream ss;

        ss.imbue(std::locale(ss.getloc(), facet));
        //ss.exceptions(std::ios::badbit | std::ios::failbit);
        ss << date; // --> exception occurs here - It can't be caught.
        std::cout << ss.str() << std::endl;
    }
    catch (const std::exception& ex)
    {
        std::cerr << "std::exception " << ex.what() << std::endl;
    }
    catch (const boost::exception&)
    {
        std::cerr << "boost::exception " << std::endl;
    }
    catch (...)
    {
        std::cerr << "unknown exception" << std::endl;
    }

    return 0;
}

The problem is with a certain format passed to the facet - either %k or %l cause the issue.   When a date is formatted using this format there is an exception. The exception is not caught by the exception handler - the program exits!

I am creating a library function so I need to assume invalid format strings will happen.  I am ok with an exception - I just need to be able to handle it and report the error, or confirm that the facet is valid before using it.

This happens on Windows 10.  The error is in the wcsftime function.  Also wcsftime is a wide char function, and I am using 8 bit char.  The application is compiled in Visual Studio 2017 with MultiByte character set rather than Unicode.

The issue occurs in the debugger with the above assertion.  Running the release build from the command line causes the application to crash and pop up the 'Application has stopped working' windows dialog.

The boost version is 1.65.1

What am I doing wrong?