问:
Using std::map to find duplicates in data and its performance issue. Can I pre-allocate it?
My goal is to check for duplicate IDs in my custom data structure. I'm coding it with Visual Studio 2008 Sp1. So I wrote the following debugger-only function that does "sanity checks" on the data as I work with the code.

I'm using the following approach:

I enumerate through all elements in my data structure (which by itself is relatively fast.)

I then use std::map to collect IDs of all elements as keys, while I make the value part point to the data structure element itself (which will help me quickly identify the duplicate.)

For each element in my data structure I see if its ID is in my std::map, and if so, the function asserts. Otherwise it adds it to the map.

Here's a pseudo-code for that:

```<code>std::map<ULONGLONG, BIN_XML_TAG*> dicTagIDs;

for(std::vector<MY_ELEMENT>::const_iterator iTag = arrNode.begin(); iTag != arrNode.end(); ++iTag)
{
    std::map<ULONGLONG, MY_ELEMENT*>::const_iterator itrT = dicTagIDs.find(iTag->uiTagID);
    if(itrT != dicTagIDs.end())
    {
        //Duplicate tag ID!
        MY_ELEMENT* pDuplicateToTag = itrT->second;
        ASSERT(NULL);
    }

    //If not, then add it
    dicTagIDs[iTag->uiTagID] = iTag._Myptr;

    //... may later call itself recursively
}
</code>```

This works, except that the function above gets exponentially slower as the size of my data structure grows. And since I use it everywhere throughout my "debugger-build" code, it'd be nice to speed it up.

So I was thinking to pre-allocate std::map. I don't know the exact number of elements in my data structure (it is structured kinda like an XML file) but I can make an approximate guess that I could use for preallocation.

But std::map doesn't seem to provide a reserve() method.

So any suggestions how to speed this up?

答:
std::unordered_maps are faster for key lookups (much faster in my experience) in most implementations (algorithmically, they are O(1) as opposed to the O(log(n)) for std::map).

And they have a reserve() method

Body:
My goal is to check for duplicate IDs in my custom data structure. I'm coding it with Visual Studio 2008 Sp1. So I wrote the following debugger-only function that does "sanity checks" on the data as I work with the code.

I'm using the following approach:

I enumerate through all elements in my data structure (which by itself is relatively fast.)

I then use std::map to collect IDs of all elements as keys, while I make the value part point to the data structure element itself (which will help me quickly identify the duplicate.)

For each element in my data structure I see if its ID is in my std::map, and if so, the function asserts. Otherwise it adds it to the map.

Here's a pseudo-code for that:

std::map<ULONGLONG, BIN_XML_TAG*> dicTagIDs;

for(std::vector<MY_ELEMENT>::const_iterator iTag = arrNode.begin(); iTag != arrNode.end(); ++iTag)
{
    std::map<ULONGLONG, MY_ELEMENT*>::const_iterator itrT = dicTagIDs.find(iTag->uiTagID);
    if(itrT != dicTagIDs.end())
    {
        //Duplicate tag ID!
        MY_ELEMENT* pDuplicateToTag = itrT->second;
        ASSERT(NULL);
    }

    //If not, then add it
    dicTagIDs[iTag->uiTagID] = iTag._Myptr;

    //... may later call itself recursively
}

This works, except that the function above gets exponentially slower as the size of my data structure grows. And since I use it everywhere throughout my "debugger-build" code, it'd be nice to speed it up.

So I was thinking to pre-allocate std::map. I don't know the exact number of elements in my data structure (it is structured kinda like an XML file) but I can make an approximate guess that I could use for preallocation.

But std::map doesn't seem to provide a reserve() method.

So any suggestions how to speed this up?


来源: stackexchange

问:
Django Forms and Bootstrap - CSS classes and <divs>
I'm using Twitter Bootstrap with Django to render forms.

Bootstrap can format your forms quite nicely - as long as you have the CSS classes it expects included.

However, my issue is that the forms generated by Django's {{ form.as_p }} don't render well with Bootstrap, as they don't have these classes.

For example, the output from Django:

```<code>    <form class="horizontal-form" action="/contact/" method="post">
        <div style='display:none'>
            <input type='hidden' name='csrfmiddlewaretoken'
                   value='26c39ab41e38cf6061367750ea8c2ea8'/>
        </div>
        <p><label for="id_name">Name:</label> <input id="id_name" type="text" name="name" value="FOOBAR" maxlength="20" /></p>
        <p><label for="id_directory">Directory:</label> <input id="id_directory" type="text" name="directory" value="FOOBAR" maxlength="60" /></p>
       <p><label for="id_comment">Comment:</label> <textarea id="id_comment" rows="10" cols="40" name="comment">Lorem ipsum dolor sic amet.</textarea></p>
       <p>
           <label for="id_server">Server:</label>
           <select name="server" id="id_server">
               <option value="">---------</option>
               <option value="1"
                   selected="selected">sydeqexcd01.au.db.com</option>
               <option value="2">server1</option>
               <option value="3">server2</option>
               <option value="4">server3</option>
           </select>
       </p>
       <input type="submit" value="Submit" />
    </form>
</code>```

From what I can tell, Bootstrap requires that your forms has a <fieldset class="control-group">, each  has class="control-label", and each <input> is wrapped in a
:

```<code><fieldset class="control-group">
    <label class="control-label" for="input01">Text input</label>
    <div class="controls">
        <input type="text" class="xlarge" name="input01">
        <p class="help-text">Help text here. Be sure to fill this out like so, or else!</p>
    </div>
</fieldset>
</code>```

However, adding custom CSS labels to every form field in Django is rather painful:

Add class to Django label_tag() output

Is there a smarter way of either using {{ form.as_p }}, or iterating through the fields, without having to manually specify things, or do a whole bunch of hackery?

Cheers,
Victor

答:
Here is my version using django_tweaks with a better looking result. I find render_field lighter to use than adding filters. I have also added bootstrap formatted alert messages and turned off navigator validation (with novalidate). I am relatively new to Django so don't hesitate to comment if you find any non-sense</p>

```<code><form class="large" method="post" action="/suscript/" novalidate>
    {% csrf_token %}
    <fieldset>
        <legend>{{ title }}</legend>
        {% for field in form %}
            <div class="control-group {%if field.errors %}error{%endif%}">
                <div class="input-group controls">
                    <label class="input-group-addon control-label" id="{{field.label|safe}}">{{ field.label }}</label>
                    {% render_field field type="text" class="form-control" placeholder="" aria-describedby="field.label|safe" %}
                </div>
                    {% for error in field.errors %}
                         <div class="alert alert-danger">
                            <strong>{{ error|escape }}</strong>
                         </div>
                    {% endfor %}

                    {% if field.help_text %}
                        <p class="help-inline">{{ field.help_text|safe }}</p>
                    {% endif %}
            </div>

        {% endfor %}
    </fieldset>
    <div class="form-actions">
        <button type="submit" class="btn btn-primary" >Submit</button>
    </div>
</form>
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I'm using Twitter Bootstrap with Django to render forms.

Bootstrap can format your forms quite nicely - as long as you have the CSS classes it expects included.

However, my issue is that the forms generated by Django's {{ form.as_p }} don't render well with Bootstrap, as they don't have these classes.

For example, the output from Django:

    <form class="horizontal-form" action="/contact/" method="post">

            <input type='hidden' name='csrfmiddlewaretoken'
                   value='26c39ab41e38cf6061367750ea8c2ea8'/>

Name: <input id="id_name" type="text" name="name" value="FOOBAR" maxlength="20" />

Directory: <input id="id_directory" type="text" name="directory" value="FOOBAR" maxlength="60" />

Comment: <textarea id="id_comment" rows="10" cols="40" name="comment">Lorem ipsum dolor sic amet.</textarea>

           Server:
           <select name="server" id="id_server">
               <option value="">---------</option>
               <option value="1"
                   selected="selected">sydeqexcd01.au.db.com</option>
               <option value="2">server1</option>
               <option value="3">server2</option>
               <option value="4">server3</option>
           </select>

       <input type="submit" value="Submit" />
    </form>

From what I can tell, Bootstrap requires that your forms has a <fieldset class="control-group">, each  has class="control-label", and each <input> is wrapped in a
:

<fieldset class="control-group">
    Text input

        <input type="text" class="xlarge" name="input01">

Help text here. Be sure to fill this out like so, or else!

</fieldset>

However, adding custom CSS labels to every form field in Django is rather painful:

Add class to Django label_tag() output

Is there a smarter way of either using {{ form.as_p }}, or iterating through the fields, without having to manually specify things, or do a whole bunch of hackery?

Cheers,
Victor

Body:
Here is my version using django_tweaks with a better looking result. I find render_field lighter to use than adding filters. I have also added bootstrap formatted alert messages and turned off navigator validation (with novalidate). I am relatively new to Django so don't hesitate to comment if you find any non-sense

<form class="large" method="post" action="/suscript/" novalidate>
    {% csrf_token %}
    <fieldset>
        <legend>{{ title }}</legend>
        {% for field in form %}
            <div class="control-group {%if field.errors %}error{%endif%}">
                <div class="input-group controls">
                    <label class="input-group-addon control-label" id="{{field.label|safe}}">{{ field.label }}</label>
                    {% render_field field type="text" class="form-control" placeholder="" aria-describedby="field.label|safe" %}
                </div>
                    {% for error in field.errors %}
                         <div class="alert alert-danger">
                            <strong>{{ error|escape }}</strong>
                         </div>
                    {% endfor %}

                    {% if field.help_text %}
                        <p class="help-inline">{{ field.help_text|safe }}</p>
                    {% endif %}
            </div>

        {% endfor %}
    </fieldset>
    <div class="form-actions">
        <button type="submit" class="btn btn-primary" >Submit</button>
    </div>
</form>


问:
How do I change the color of all the elements (onHover) in a  even though some are wrapped in ?
The implementation is here: http://jsfiddle.net/chp8y/1/

If you hover over the first box, #1, you will see the 'Add Client' change color but the #1 won't. How do I achieve that without using JS ?

If you do a .sit-in-the-corner:hover it will only work when you hover over the 1. But that's not what I want.

Thoughts?

答:
Wrap the #s with anchor tags. Drop the color attribute from the .sit-in-the-corner and add that attribute to the anchors. Like this:

HTML:

```<code><span class="sit-in-the-corner"><a class="tile-number">1</a></span>
</code>```

CSS:

```<code>.sit-in-the-corner {
    float: left;
    margin-left: 5px;
    margin-top: -85px;
}

.tile-number {
    color: #556655;
}
</code>```

ContentLicense: CC BY-SA 2.5

Title: How do I change the color of all the elements (onHover) in a <td> even though some are wrapped in <span>?

Body:
Wrap the #s with anchor tags. Drop the color attribute from the .sit-in-the-corner and add that attribute to the anchors. Like this:

HTML:

<span class="sit-in-the-corner"><a class="tile-number">1</a></span>

CSS:

.sit-in-the-corner {
    float: left;
    margin-left: 5px;
    margin-top: -85px;
}

.tile-number {
    color: #556655;
}


问:
Laravel validation for individual input fields
I am using ajax calls in my jquery to send user input from my blade to my controller.

I have an input field

```<code><div class="col-md-3">
    <input type="text" class="form-control inputProfilePage" id="fname" name="fname" placeholder="First Name"
           value="{{ Auth::user()->fname }}">
  </div>
  <div class="col-md-3">
    <input type="text" class="form-control inputProfilePage" id="lname" name="lname" placeholder="Last Name"
           value="{{ Auth::user()->lname }}">
  </div>
</code>```

fname is for firstname, lname is for lastname

In my jquery I have a call

```<code>$('.selectProfilePage').change(function(){
          var val = $(this).val();
          var field = $(this).attr('id');
          updateProfilePage(val, field);
      });
</code>```

field is the name of the field, val is the value the user entered into the input.

updateProfilePage is an ajax call

```<code>function updateProfilePage(val, field) {
          $.ajaxSetup({
              headers: {
                  'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
              }
          });
          $.ajax({
              type: 'POST',
              url: '/userprofilepage',
              data: {
                  val: val,
                  field: field
              },
              success: function (msg) {
                  console.log("Profile page has been updated:" + val);
              },
              error: function (msg) {
                  console.log("Profile page has not been updated:" + msg);
              }
          });
      }
</code>```

In my routes file this calls my store function.  What I am struggling with is how to validate the value the user has entered.  Here is my store method in my controller

```<code> public function store(Request $request)
    {
            $this->validate($request, [
                'val' => 'alpha'
            ]);
    }
</code>```

If the user enters anything that is not alphabetic I want to print out an error message on my blade.

I added the following code to my blade but the error still does not appear

```<code><div class="alert alert-error">
   <ul>
       @foreach($errors->all() as $error)
           <li>{{$error}}</li>
       @endforeach
   </ul>
</div>
</code>```

So what am I doing wrong?  I want to get the error to show up in my blade if the user inputs anything that is not alphabetic in the input for firstname of lastname.

答:
The blade syntax is generated by the server every time the page is loaded, as you send the form in ajax the page is not reloaded, to add the error in your alert box I would do something like this: (Not tested)</p>

```<code>function updateProfilePage(val, field) {
          $.ajaxSetup({
              headers: {
                  'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
              }
          });
          $.ajax({
              type: 'POST',
              url: '/userprofilepage',
              data: {
                  val: val,
                  field: field
              }
          }).done(function () {
                $('.alert').find('ul').append('<li>Profile page has been updated:' + data + '</li>');
          }).fail(function () {
                $('.alert').find('ul').append('<li>Profile page has not been updated:' + data + '</li>');
          }).always(function (e) {
                console.log(e);
          });
      }
</code>```

Body:
I am using ajax calls in my jquery to send user input from my blade to my controller.

I have an input field

    <input type="text" class="form-control inputProfilePage" id="fname" name="fname" placeholder="First Name"
           value="{{ Auth::user()->fname }}">

    <input type="text" class="form-control inputProfilePage" id="lname" name="lname" placeholder="Last Name"
           value="{{ Auth::user()->lname }}">

fname is for firstname, lname is for lastname

In my jquery I have a call

$('.selectProfilePage').change(function(){
          var val = $(this).val();
          var field = $(this).attr('id');
          updateProfilePage(val, field);
      });

field is the name of the field, val is the value the user entered into the input.

updateProfilePage is an ajax call

function updateProfilePage(val, field) {
          $.ajaxSetup({
              headers: {
                  'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
              }
          });
          $.ajax({
              type: 'POST',
              url: '/userprofilepage',
              data: {
                  val: val,
                  field: field
              },
              success: function (msg) {
                  console.log("Profile page has been updated:" + val);
              },
              error: function (msg) {
                  console.log("Profile page has not been updated:" + msg);
              }
          });
      }

In my routes file this calls my store function.  What I am struggling with is how to validate the value the user has entered.  Here is my store method in my controller

 public function store(Request $request)
    {
            $this->validate($request, [
                'val' => 'alpha'
            ]);
    }

If the user enters anything that is not alphabetic I want to print out an error message on my blade.

I added the following code to my blade but the error still does not appear

       @foreach($errors->all() as $error)

{{$error}}

       @endforeach

So what am I doing wrong?  I want to get the error to show up in my blade if the user inputs anything that is not alphabetic in the input for firstname of lastname.

Body:
The blade syntax is generated by the server every time the page is loaded, as you send the form in ajax the page is not reloaded, to add the error in your alert box I would do something like this: (Not tested)

function updateProfilePage(val, field) {
          $.ajaxSetup({
              headers: {
                  'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
              }
          });
          $.ajax({
              type: 'POST',
              url: '/userprofilepage',
              data: {
                  val: val,
                  field: field
              }
          }).done(function () {
                $('.alert').find('ul').append('<li>Profile page has been updated:' + data + '</li>');
          }).fail(function () {
                $('.alert').find('ul').append('<li>Profile page has not been updated:' + data + '</li>');
          }).always(function (e) {
                console.log(e);
          });
      }


问:
How to achieve this effect while listview is loading with items in android?
Lately, this kind of effect is gaining lot of popularity.
While items are being populated, listview shows this kind of affect.
What exactly is this and how can one implement it.
Thanks!

答:
Create a dummy layout exactly similar to what you want o show on pre-loading and then set it to listView on Empaty method,like this.</p>

```<code>View emptyView = findViewById(R.id.empty_view);
 listView.setEmptyView(emptyView);
</code>```

Body:
Create a dummy layout exactly similar to what you want o show on pre-loading and then set it to listView on Empaty method,like this.

View emptyView = findViewById(R.id.empty_view);
 listView.setEmptyView(emptyView);


问:
What file access woke the sleeping disk in Windows?
Every now and then, my sleeping disk wakes up, does what sounds like a single read, and then sits idle until it falls asleep again. Sometimes a program that I am using completely freezes for about 10 seconds while the disk spins up, even though that program doesn't seem to need to read from that drive.

Is there an api for listening to file accesses as they happen, or similar, so I can figure out what is read from that drive, so I can move it? If not on Windows, can I do this on Linux?

This is also applicable for figuring out what files/folders a program is accessing in general, so I wouldn't say it only applies to my very narrow problem.

答:
There's a simple tool called What's My Computer Doing? that you can use to get a quick idea of what's causing activity on your computer.

Install and run it, and leave it running in the background.  Once you use this tool to narrow down which process is causing the disk activity, you'll want a more comprehensive tool.  I use Process Monitor from Sysinternals/Microsoft.

It can be a bit daunting at first, but that's mainly because it is so powerful.  It can also alter the behavior of the computer.  When it's running, it backs up the huge quantity of data it collects to the disk.  So that's why I suggest using the 'What's My Computer Doing?' tool first.  Once you know which process is generating the disk access you can add a new filter rule (keep all the defaults, as they mask out a bunch of normal system processes) and select "Process Name" "is" "process_name", or select "PID" "is" "actual_PID".

There are plenty of tutorials like this one that can help you get started with Process Monitor.


问:
What is the best way to write a contract for CSS usage in Web Development?
Our Dev team had been developing enterprise web page more than 2 years ago.  We are curious to know what is the best way to write a contract for CSS usage.  For example, if we have a COMP, how we agree on a contract so our developers and our designers agree and we don't have to go back.

Is there a tool that is available for this type of technical writing?

What is the threadhold of information put in the CSS versus on the HTML page?  Some of our designers thing that some things should go directly into the HTML page.  The general opinion is that everything that is style should go in a CSS and all else in the html.

Thanks for your input.

答:
Well, if a webpage has very specific CSS just for itself, I guess there is an argument for defining the CSS in the page, otherwise I would always have the CSS in an external file.

Try to avoid or at least minimise in-lining the CSS as a style attribute on HTML elements though, that would be a PITA to manage.

Most pages will be template driven with standard content styles, and thus the CSS styles will be defined in external files.

One thing you might want to think about are the number of CSS files - some people suggest that you should minimise this to just one file site-wide or per-template (or area of the site) to minimise HTTP requests to the server and avoid delayed CSS loading and funny looking styling up until that point.

So this "contract for CSS usage" is actually just a coding standard for HTML pages?

OwnerDisplayName: Geo

OwnerDisplayName: JeeBee


问:
angular2, how to return object who have the max value of an attribute in an array of objects
i'am working on an angular2 app , i have an array of objects and i want to return the object how has max value of an attribute (in my case the object how have more likes) how to do that in typescript

import {Player} from './player';
export const PlayersData : Player[] = [
{id:1,name:"Marc-andré Ter stegen",number:"1",post:"Goalkeeper",goals:0,assist:0,likes:10,dislike:0,img:"http://s.weltsport.net/bilder/spieler/gross/150720.jpg"},
{id:2,name:"Gerrad Piqué",number:"3",post:"Defender",goals:0,assist:0,likes:10,dislike:0,img:"http://s.weltsport.net/bilder/spieler/gross/27798.jpg"},
{id:3,name:"Ivan Rakitić",number:"4",post:"Midfielder",goals:0,assist:0,likes:7,dislike:0,img:"http://s.weltsport.net/bilder/spieler/gross/35308.jpg"},
{id:4,name:"Sergie Buskquets",number:"5",post:"Midfielder",goals:0,assist:0,likes:10,dislike:0,img:"http://s.weltsport.net/bilder/spieler/gross/124973.jpg"},
{id:5,name:"Denis Suarez",number:"6",post:"Midfielder",goals:20,assist:20,likes:10,dislike:0,img:"http://s.weltsport.net/bilder/spieler/gross/200516.jpg"},
{id:6,name:"Arda Turan",number:"7",post:"Midfielder",goals:0,assist:10,likes:10,dislike:0,img:"http://s.weltsport.net/bilder/spieler/gross/30203.jpg"},
{id:7,name:"Andres Iniesta",number:"8",post:"Midfielder",goals:10,assist:20,likes:0,dislike:0,img:"http://s.weltsport.net/bilder/spieler/gross/5057.jpg"},
{id:8,name:"Luis Suarez",number:"9",post:"Forward",goals:0,assist:0,likes:30,dislike:0,img:"http://s.weltsport.net/bilder/spieler/gross/43635.jpg"},
{id:9,name:"Lionel Messi",number:"10",post:"Forward",goals:0,assist:0,likes:40,dislike:0,img:"http://s.weltsport.net/bilder/spieler/gross/26622.jpg"},
{id:10,name:"Neymar Jr",number:"11",post:"Forward",goals:30,assist:10,likes:30,dislike:0,img:"http://s.weltsport.net/bilder/spieler/gross/142105.jpg"},
{id:11,name:"Javier Mascherano",number:"14",post:"Defender",goals:0,assist:0,likes:10,dislike:0,img:"http://s.weltsport.net/bilder/spieler/gross/22185.jpg"},
{id:12,name:"Jordi Alba",number:"18",post:"Defender",goals:0,assist:0,likes:10,dislike:0,img:"http://s.weltsport.net/bilder/spieler/gross/125417.jpg"},
{id:13,name:"Sergio Roberto",number:"20",post:"Midfielder",goals:0,assist:0,likes:20,dislike:0,img:"http://s.weltsport.net/bilder/spieler/gross/171905.jpg"},
{id:14,name:"Samuel Umtiti",number:"23",post:"Defender",goals:0,assist:0,likes:9,dislike:0,img:"http://s.weltsport.net/bilder/spieler/gross/170711.jpg"}

];```
</div>
</div>
</p>

<p>this is what i tried in typescript </p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>export class DashboardComponent implements OnInit {
  players : Player[] = [];
 bestPlayer:Player;
  constructor(private playerService : PlayerService) { }
 max =0;
 bestPlayer = this.players[0];
  ngOnInit() {
   this.playerService.getPlayers()
   .then(players=> this.players = players);
   for (player of players)
      if (player.likes>max) {
        max => player.likes;
        bestPlayer => player;
      }
  }

}</code>```

答:
i found the solution :

bestPlayer:Player;
data:Player[];
max:number =0;
  constructor(private playerService : PlayerService) { }
  ngOnInit() {
    this.data=this.playerService.getDatas();
    for (var i = 0; i <= this.data.length; i++) {
    if (this.data[i].likes>this.max) {
      this.max=this.data[i].likes;
      this.bestPlayer=this.data[i];

     }
  }```

Body:
i'am working on an angular2 app , i have an array of objects and i want to return the object how has max value of an attribute (in my case the object how have more likes) how to do that in typescript

import {Player} from './player';
export const PlayersData : Player[] = [
{id:1,name:"Marc-andré Ter stegen",number:"1",post:"Goalkeeper",goals:0,assist:0,likes:10,dislike:0,img:"http://s.weltsport.net/bilder/spieler/gross/150720.jpg"},
{id:2,name:"Gerrad Piqué",number:"3",post:"Defender",goals:0,assist:0,likes:10,dislike:0,img:"http://s.weltsport.net/bilder/spieler/gross/27798.jpg"},
{id:3,name:"Ivan Rakitić",number:"4",post:"Midfielder",goals:0,assist:0,likes:7,dislike:0,img:"http://s.weltsport.net/bilder/spieler/gross/35308.jpg"},
{id:4,name:"Sergie Buskquets",number:"5",post:"Midfielder",goals:0,assist:0,likes:10,dislike:0,img:"http://s.weltsport.net/bilder/spieler/gross/124973.jpg"},
{id:5,name:"Denis Suarez",number:"6",post:"Midfielder",goals:20,assist:20,likes:10,dislike:0,img:"http://s.weltsport.net/bilder/spieler/gross/200516.jpg"},
{id:6,name:"Arda Turan",number:"7",post:"Midfielder",goals:0,assist:10,likes:10,dislike:0,img:"http://s.weltsport.net/bilder/spieler/gross/30203.jpg"},
{id:7,name:"Andres Iniesta",number:"8",post:"Midfielder",goals:10,assist:20,likes:0,dislike:0,img:"http://s.weltsport.net/bilder/spieler/gross/5057.jpg"},
{id:8,name:"Luis Suarez",number:"9",post:"Forward",goals:0,assist:0,likes:30,dislike:0,img:"http://s.weltsport.net/bilder/spieler/gross/43635.jpg"},
{id:9,name:"Lionel Messi",number:"10",post:"Forward",goals:0,assist:0,likes:40,dislike:0,img:"http://s.weltsport.net/bilder/spieler/gross/26622.jpg"},
{id:10,name:"Neymar Jr",number:"11",post:"Forward",goals:30,assist:10,likes:30,dislike:0,img:"http://s.weltsport.net/bilder/spieler/gross/142105.jpg"},
{id:11,name:"Javier Mascherano",number:"14",post:"Defender",goals:0,assist:0,likes:10,dislike:0,img:"http://s.weltsport.net/bilder/spieler/gross/22185.jpg"},
{id:12,name:"Jordi Alba",number:"18",post:"Defender",goals:0,assist:0,likes:10,dislike:0,img:"http://s.weltsport.net/bilder/spieler/gross/125417.jpg"},
{id:13,name:"Sergio Roberto",number:"20",post:"Midfielder",goals:0,assist:0,likes:20,dislike:0,img:"http://s.weltsport.net/bilder/spieler/gross/171905.jpg"},
{id:14,name:"Samuel Umtiti",number:"23",post:"Defender",goals:0,assist:0,likes:9,dislike:0,img:"http://s.weltsport.net/bilder/spieler/gross/170711.jpg"}

];

this is what i tried in typescript

export class DashboardComponent implements OnInit {
  players : Player[] = [];
 bestPlayer:Player;
  constructor(private playerService : PlayerService) { }
 max =0;
 bestPlayer = this.players[0];
  ngOnInit() {
   this.playerService.getPlayers()
   .then(players=> this.players = players);
   for (player of players)
      if (player.likes>max) {
        max => player.likes;
        bestPlayer => player;
      }
  }

}


问:
Is it possible to pass the elements of a list as arguments of one function call in C#?
I am writing a bot designed to interact with an online game. I am using a function called "Send" which is defined like so:

```<code>public void Send(string type, params object[] parameters);
</code>```

"Send" is a function which can have a variable number of arguments, thanks to the params keyword. If I am storing these arguments in a List<object>, can I pass this list of arguments to the function without having to write different code for each possible number of arguments?

I know that if that params keyword wasn't there I could just pass the whole list as one argument using List<T>.ToArray(), but the Send function is defined in a preprepared library which I can't alter.

答:
Small explanation:

```<code>var myList = new List<object>() { 1, "foo", "bar"};

Send(type, myList.ToArray());         //this will invoke: void Send(string, object, object, object);
Send(type, (object)myList.ToArray()); //this will invoke: void Send(string, object);
Send(type, myList);                   //this will invoke: void Send(string, object);
</code>```

So if you want your list to be considered as params - you can invoke ToArray(), if you want it to be considered as single parameter - just cast it to object.

Body:
I am writing a bot designed to interact with an online game. I am using a function called "Send" which is defined like so:

public void Send(string type, params object[] parameters);

"Send" is a function which can have a variable number of arguments, thanks to the params keyword. If I am storing these arguments in a List<object>, can I pass this list of arguments to the function without having to write different code for each possible number of arguments?

I know that if that params keyword wasn't there I could just pass the whole list as one argument using List<T>.ToArray(), but the Send function is defined in a preprepared library which I can't alter.

Body:
Small explanation:

var myList = new List<object>() { 1, "foo", "bar"};

Send(type, myList.ToArray());         //this will invoke: void Send(string, object, object, object);
Send(type, (object)myList.ToArray()); //this will invoke: void Send(string, object);
Send(type, myList);                   //this will invoke: void Send(string, object);

So if you want your list to be considered as params - you can invoke ToArray(), if you want it to be considered as single parameter - just cast it to object.


问:
Where does Linux kernel do process and TCP connections cleanup after process dies?
I am trying to find place in the linux kernel where it does cleanup after process dies. Specifically, I want to see if/how it handles open TCP connections after process is killed with -9 signal. I am pretty sure it closes all connections, but I want to see details, and if there is any chance that connections are not closed properly.

Pointers to linux kernel sources are welcome.

答:
I'm pretty sure the socket cleanup is more of a side effect of releasing all the file descriptors after the process dies, and not directly done by the process cleanup.

I'm going to go out on a limb though, and assume you're hitting a common pitfall with network programming. If I am correct in guessing that your problem is that you get an "Address in use" error (EADDRINUSE) when trying to bind to an address after a process is killed, then you are running into the socket's TIME_WAIT.

If this is the case, you can either wait for the timeout, usually 60 seconds, or you can modify the socket to allow immediate reuse like so.

```<code>int sock, ret, on;
struct sockaddr_in servaddr;

sock = socket( AF_INET, SOCK_STREAM, 0 ):

/* Enable address reuse */
on = 1;
ret = setsockopt( sock, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on) );
</code>```

[EDIT]

From your comments, It sounds like you are having issues with half-open connections, and don't fully understand how TCP works. TCP has no way of knowing if a client is dead, or just idle. If you kill -9 a client process, the four-way closing handshake never completes. This shouldn't be leaving open connections on your server though, so you still may need to get a network dump to be sure of what's going on.

I can't say for sure how you should handle this without knowing exactly what you are doing, but you can read about TCP Keepalive here. A couple other options are sending empty or null messages periodically to the client (may require modifying your protocol), or setting hard timers on idle connections (may result in dropped valid connections).

Body:
I'm pretty sure the socket cleanup is more of a side effect of releasing all the file descriptors after the process dies, and not directly done by the process cleanup.

I'm going to go out on a limb though, and assume you're hitting a common pitfall with network programming. If I am correct in guessing that your problem is that you get an "Address in use" error (EADDRINUSE) when trying to bind to an address after a process is killed, then you are running into the socket's TIME_WAIT.

If this is the case, you can either wait for the timeout, usually 60 seconds, or you can modify the socket to allow immediate reuse like so.

int sock, ret, on;
struct sockaddr_in servaddr;

sock = socket( AF_INET, SOCK_STREAM, 0 ):

/* Enable address reuse */
on = 1;
ret = setsockopt( sock, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on) );

[EDIT]

From your comments, It sounds like you are having issues with half-open connections, and don't fully understand how TCP works. TCP has no way of knowing if a client is dead, or just idle. If you kill -9 a client process, the four-way closing handshake never completes. This shouldn't be leaving open connections on your server though, so you still may need to get a network dump to be sure of what's going on.

I can't say for sure how you should handle this without knowing exactly what you are doing, but you can read about TCP Keepalive here. A couple other options are sending empty or null messages periodically to the client (may require modifying your protocol), or setting hard timers on idle connections (may result in dropped valid connections).


问:
How to Denormalize object with java.util.stream
I have the following objects:

```<code>public class Customer {

    private int id;
    private String name;
    private Collection<Order> orders;

    public int getId() {return id;}
    public void setId(int id) {this.id = id;}
    public String getName() {return name;}
    public void setName(String name) {this.name = name;}
    public Collection<Order> getOrders() {return orders;}
    public void setOrders(Collection<Order> orders) {this.orders = orders;}
}

public class Order {
    private int id;
    private String item;

    public int getId() {return id;}
    public void setId(int id) {this.id = id;}
    public String getItem() {return item;}
    public void setItem(String item) {this.item = item;}
}

public class CustomerOrderDto {
    private int customerId;
    private String customerName;
    private String orderId;
    private String orderItem;

    public int getCustomerId() {return customerId;}
    public void setCustomerId(int customerId) {this.customerId = customerId;}
    public String getName() {return name;}
    public void setName(String name) {this.name = name;}
    public String getOrderId() {return orderId;}
    public void setOrderId(String orderId) {this.orderId = orderId;}
    public String getOrderItem() {return orderItem;}
    public void setOrderItem(String orderItem) {this.orderItem = orderItem;}
}
</code>```

So if I have a Customer object with two Orders the result would be a list of two CustomerOrderDto objects.

I can obviously do this with for loops, but I am looking for a more elegant solution using Java streams.

My background is .NET where I can easily do this with LINQ, but this my first java project and I wanted to see if I can do something similar here.

答:
```<code>private List<Customer.CustomerOrderDto> customerOrderDtoList(Customer customer){
    Collection<Customer.Order> orders = customer.getOrders();
    return orders.stream()
                 .map(order -> createCustomerOrderDto(customer, order))
                 .collect(Collectors.toList());
}

private Customer.CustomerOrderDto createCustomerOrderDto(Customer customer, Customer.Order order){
    Customer.CustomerOrderDto dto = new Customer.CustomerOrderDto();

    return dto;
}
</code>```

Body:
I have the following objects:

public class Customer {

    private int id;
    private String name;
    private Collection<Order> orders;

    public int getId() {return id;}
    public void setId(int id) {this.id = id;}
    public String getName() {return name;}
    public void setName(String name) {this.name = name;}
    public Collection<Order> getOrders() {return orders;}
    public void setOrders(Collection<Order> orders) {this.orders = orders;}
}

public class Order {
    private int id;
    private String item;

    public int getId() {return id;}
    public void setId(int id) {this.id = id;}
    public String getItem() {return item;}
    public void setItem(String item) {this.item = item;}
}

public class CustomerOrderDto {
    private int customerId;
    private String customerName;
    private String orderId;
    private String orderItem;

    public int getCustomerId() {return customerId;}
    public void setCustomerId(int customerId) {this.customerId = customerId;}
    public String getName() {return name;}
    public void setName(String name) {this.name = name;}
    public String getOrderId() {return orderId;}
    public void setOrderId(String orderId) {this.orderId = orderId;}
    public String getOrderItem() {return orderItem;}
    public void setOrderItem(String orderItem) {this.orderItem = orderItem;}
}

So if I have a Customer object with two Orders the result would be a list of two CustomerOrderDto objects.

I can obviously do this with for loops, but I am looking for a more elegant solution using Java streams.

My background is .NET where I can easily do this with LINQ, but this my first java project and I wanted to see if I can do something similar here.


问:
How to fit all pixel sized images in a div?
I'm building a web application where I want to display product like in e-commerce website. The images of random dimension have to be fit in a particular box.
I have tried following code but it distorts the image if height is more than width, but looks perfectly if it is vice versa.</p>

```<code><div class="panel panel-default text-center">
                <div class="panel-heading" style="padding:2px;">
                    <a href="#" style=" text-decoration: none;"><img  src="images/abc.jpg" style="width:100%;height:220px;" /></a></a>
                </div>

                <div class="panel-body w3-card" style="padding-top:0px;background-color:#ebebeb;">
                    <a href="#" class="pull-left" style=" text-decoration: none;"><h5 style="margin-bottom:0px;" ><b>Product One</b></h5>
                    <p class="pull-left" style="margin-top:0px;color:#6e6e6e;margin-bottom:0px;"><i class="fa fa-inr"></i> 10,000/-</p></a>
                </div>

            </div>
</code>```

答:
add another attributes in your style :

```<code>    <div class="panel-heading" style="padding:2px;">
                <a href="#" style=" text-decoration: none;"><img  src="images/abc.jpg" style="width:100%;height:auto;max-width:100px;" /></a></a>
    </div>
</code>```

Does it work now?

Body:
I'm building a web application where I want to display product like in e-commerce website. The images of random dimension have to be fit in a particular box.
I have tried following code but it distorts the image if height is more than width, but looks perfectly if it is vice versa.

Product One

 10,000/-

Body:
add another attributes in your style :

    <div class="panel-heading" style="padding:2px;">
                <a href="#" style=" text-decoration: none;"><img  src="images/abc.jpg" style="width:100%;height:auto;max-width:100px;" /></a></a>
    </div>

Does it work now?


问:
Knitr generating very large html files
I am trying to use Knitr to write simple text-only html pages, but the file sizes are extremely large - 700KB for a 1 line RMarkdown.  I am on R 3.4.0, and R Studio 1.0.143

For example, the following RMarkdown file generates a 695 kb file.  When I look at the source, that is because there is a huge amount of base 64 code under the script tag.  Is there anything that can be done to make the file size more compact, say a couple of KBs that I would expect it to be

(eg script src="data:application/x-javascript;base64,LyohIGpRdW...and this goes on and on forever)

```<code>---
title: "This is  a test"
author: "Mukul Pareek"
date: "June 7, 2017"
output: html_document
---

## This is a test file which when knit to html is 695KB
</code>```

答:
My ad-hoc solution is to use the BiocStyle style from Bioconductor. This reduces the html file size to 50 kb.

```<code>---
title: "This is  a test"
author: "Mukul Pareek"
date: "June 7, 2017"
output:
  BiocStyle::html_document
---
</code>```

A more extreme solution is found here: How to render HTML from RMarkdown without javascript in output

It produces an html file smaller than 1 kb.

```<code>---
title: "This is  a test"
author: "Mukul Pareek"
date: "June 7, 2017"
output:
  html_document:
    theme: null
    highlight: null
    mathjax: null
---
</code>```

Title: Knitr generating very large html files

Body:
I am trying to use Knitr to write simple text-only html pages, but the file sizes are extremely large - 700KB for a 1 line RMarkdown.  I am on R 3.4.0, and R Studio 1.0.143

For example, the following RMarkdown file generates a 695 kb file.  When I look at the source, that is because there is a huge amount of base 64 code under the script tag.  Is there anything that can be done to make the file size more compact, say a couple of KBs that I would expect it to be

(eg script src="data:application/x-javascript;base64,LyohIGpRdW...and this goes on and on forever)

---
title: "This is  a test"
author: "Mukul Pareek"
date: "June 7, 2017"
output: html_document
---

## This is a test file which when knit to html is 695KB

Body:
My ad-hoc solution is to use the BiocStyle style from Bioconductor. This reduces the html file size to 50 kb.

---
title: "This is  a test"
author: "Mukul Pareek"
date: "June 7, 2017"
output:
  BiocStyle::html_document
---

A more extreme solution is found here: How to render HTML from RMarkdown without javascript in output

It produces an html file smaller than 1 kb.

---
title: "This is  a test"
author: "Mukul Pareek"
date: "June 7, 2017"
output:
  html_document:
    theme: null
    highlight: null
    mathjax: null
---


问:
How to debug a Cordova's hook?
I was wondering if is it possible to debug a javascript hook in Cordova?

My hook is triggered before prepare. My command is

```<code>cordova prepare ios
</code>```

I currently use Visual Studio Code and there is a plugin "Cordova tools" to debug an app at runtime. But my need is to debug at build time.

Any recommandation?

PS : what I mean with debug is real debug, that is to say with breakpoints and display of variables, etc..

答:
Updated answer 25 Nov 2019

Since node-inspector is deprecated, here is how I would now do this:

Open chrome://inspect in Chrome browser

Run node --inspect --inspect-brk /path/to/node_modules/cordova/bin/cordova prepare from the root of my Cordova app project which contains the hook scripts I wish to debug

In the Chrome tab, press inspect on the target to open Chrome Dev Tools

Under Filesystem tab, select Add folder to workspace and select the directory inside my Cordova project containing the hook scripts

Add a breakpoint to my hook script

Press Play in Chrome Dev Tools to proceed and hit my breakpoint

Original answer 7 Jun 2017
Here's how I debug my hook scripts:

Install node inspector: npm install -g node-inspector

From the Cordova project root directory, run the Cordova command via node inspector with appropriate options to trigger my hook script, for example:

node-debug /path/to/node_modules/cordova/bin/cordova prepare

When node inspector opens in a Chrome tab, browse Sources to find your hook script

Add a breakpoint

Press Resume to continue execution to your breakpoint

Then you can interactively debug your hook script:

Title: How to debug a Cordova's hook?

Body:
I was wondering if is it possible to debug a javascript hook in Cordova?

My hook is triggered before prepare. My command is

cordova prepare ios

I currently use Visual Studio Code and there is a plugin "Cordova tools" to debug an app at runtime. But my need is to debug at build time.

Any recommandation?

PS : what I mean with debug is real debug, that is to say with breakpoints and display of variables, etc..

ContentLicense: CC BY-SA 4.0


问:
postgres count with like condition
I am new to Postgres and trying to figure out how can i improve performance of count query with 'Like' in where clause.

```<code>    select    count(*)
    from master_data
    where name ilike '%<userInput>%';
</code>```

I am even fine with estimated value.I googled few links and found out we can quickly get a count of entire table by using below query.

```<code> SELECT reltuples AS approximate_row_count FROM pg_class WHERE relname = '<TableName>';
</code>```

However for count with  like condition i am still not able to figure out.
Please suggest.Below are the links which i referred already.

https://wiki.postgresql.org/wiki/Count_estimate

https://www.citusdata.com/blog/2016/10/12/count-performance/#dup_counts_estimated_filtered

Postgres Version - 9.5.4

答:
Do you must use LIKE?
Maybe it's possible to make something with IN?
http://www.postgresqltutorial.com/postgresql-in/</p>

Title: postgres count with like condition

Body:
I am new to Postgres and trying to figure out how can i improve performance of count query with 'Like' in where clause.

    select    count(*)
    from master_data
    where name ilike '%<userInput>%';

I am even fine with estimated value.I googled few links and found out we can quickly get a count of entire table by using below query.

 SELECT reltuples AS approximate_row_count FROM pg_class WHERE relname = '<TableName>';

However for count with  like condition i am still not able to figure out.
Please suggest.Below are the links which i referred already.

https://wiki.postgresql.org/wiki/Count_estimate

https://www.citusdata.com/blog/2016/10/12/count-performance/#dup_counts_estimated_filtered

Postgres Version - 9.5.4


问:
XSLT: Rename attribute if not exists
I have a lot of XML files that contain attributes with a misspelled value:

```<code><Part id="1">
  <Attribute Name="Colo" Value="Red" />
</Part>
</code>```

Colo should be Color. Now in some files this has been corrected manually and then both attributes exist:

```<code><Attribute Name="Colo" Value="Red" />
<Attribute Name="Color" Value="Blue" />
</code>```

I have a XSL transformation that renames the Colo attribute to Color but I have no idea how to avoid that when the corrected attribute already exists.

```<code><xsl:template match="node()|@*">
    <xsl:copy>
        <xsl:apply-templates select="node()|@*"/>
    </xsl:copy>
</xsl:template>

<xsl:template match="Attribute/@Name[. = 'Colo']">
    <xsl:attribute name="Name">
        <xsl:value-of select="'Color'"/>
    </xsl:attribute>
</xsl:template>
</code>```

How to not rename if there already is the correct attribute?

答:
I think you want to do:

XSLT 1.0

```<code><xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>
<xsl:strip-space elements="*"/>

<!-- identity transform -->
<xsl:template match="@*|node()">
    <xsl:copy>
        <xsl:apply-templates select="@*|node()"/>
    </xsl:copy>
</xsl:template>

<xsl:template match="Attribute[@Name = 'Colo']">
    <xsl:if test="not(../Attribute[@Name = 'Color'])">
        <Attribute Name="Color" Value="{@Value}" />
    </xsl:if>
</xsl:template>

</xsl:stylesheet>
</code>```

This will modify the Attribute element with the misspelled name if it does not have a sibling with the correct name; otherwise it will just remove it.

Title: XSLT: Rename attribute if not exists

Body:
I have a lot of XML files that contain attributes with a misspelled value:

<Part id="1">
  <Attribute Name="Colo" Value="Red" />
</Part>

Colo should be Color. Now in some files this has been corrected manually and then both attributes exist:

<Attribute Name="Colo" Value="Red" />
<Attribute Name="Color" Value="Blue" />

I have a XSL transformation that renames the Colo attribute to Color but I have no idea how to avoid that when the corrected attribute already exists.

<xsl:template match="node()|@*">
    <xsl:copy>
        <xsl:apply-templates select="node()|@*"/>
    </xsl:copy>
</xsl:template>

<xsl:template match="Attribute/@Name[. = 'Colo']">
    <xsl:attribute name="Name">
        <xsl:value-of select="'Color'"/>
    </xsl:attribute>
</xsl:template>

How to not rename if there already is the correct attribute?

Body:
I think you want to do:

XSLT 1.0

<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>
<xsl:strip-space elements="*"/>

<!-- identity transform -->
<xsl:template match="@*|node()">
    <xsl:copy>
        <xsl:apply-templates select="@*|node()"/>
    </xsl:copy>
</xsl:template>

<xsl:template match="Attribute[@Name = 'Colo']">
    <xsl:if test="not(../Attribute[@Name = 'Color'])">
        <Attribute Name="Color" Value="{@Value}" />
    </xsl:if>
</xsl:template>

</xsl:stylesheet>

This will modify the Attribute element with the misspelled name if it does not have a sibling with the correct name; otherwise it will just remove it.


问:
Intramolecular protein residue contact map using biopython, KeyError: 'CA'
I am trying to identify amino acid residues in contact in the 3D protein structure. I am new to BioPython but found this helpful website http://www2.warwick.ac.uk/fac/sci/moac/people/students/peter_cock/python/protein_contact_map/

Following their lead (which I will reproduce here for completion; Note, however, that I am using a different protein):

```<code>import Bio.PDB
import numpy as np

pdb_code = "1QHW"
pdb_filename = "1qhw.pdb"

def calc_residue_dist(residue_one, residue_two) :
    """Returns the C-alpha distance between two residues"""
    diff_vector  = residue_one["CA"].coord - residue_two["CA"].coord
    return np.sqrt(np.sum(diff_vector * diff_vector))

def calc_dist_matrix(chain_one, chain_two) :
    """Returns a matrix of C-alpha distances between two chains"""
    answer = np.zeros((len(chain_one), len(chain_two)), np.float)
    for row, residue_one in enumerate(chain_one) :
        for col, residue_two in enumerate(chain_two) :
            answer[row, col] = calc_residue_dist(residue_one, residue_two)
    return answer

structure = Bio.PDB.PDBParser().get_structure(pdb_code, pdb_filename)
model = structure[0]

dist_matrix = calc_dist_matrix(model["A"], model["A"])
</code>```

But when I run the above code, I get the following error message:

```<code>Traceback (most recent call last):

  File "<ipython-input-26-7239fb7ebe14>", line 4, in <module>
    dist_matrix = calc_dist_matrix(model["A"], model["A"])

  File "<ipython-input-3-730a11883f27>", line 15, in calc_dist_matrix
    answer[row, col] = calc_residue_dist(residue_one, residue_two)

  File "<ipython-input-3-730a11883f27>", line 6, in calc_residue_dist
    diff_vector  = residue_one["CA"].coord - residue_two["CA"].coord

  File "/Users/anaconda/lib/python3.6/site-packages/Bio/PDB/Entity.py", line 39, in __getitem__
    return self.child_dict[id]

KeyError: 'CA'
</code>```

Any suggestions on how to fix this issue?

答:
I believe the problem is that some of the elements in model["A"] are not amino acids and therefore do not contain "CA".

To get around this, I wrote a new function which returns only the amino acid residues:

```<code>from Bio.PDB import *
chain = model["A"]

def aa_residues(chain):
        aa_only = []
        for i in chain:
            if i.get_resname() in standard_aa_names:
                aa_only.append(i)
        return aa_only

    AA_1 = aa_residues(model["A"])
    dist_matrix = calc_dist_matrix(AA_1, AA_1)
</code>```

Body:
I am trying to identify amino acid residues in contact in the 3D protein structure. I am new to BioPython but found this helpful website http://www2.warwick.ac.uk/fac/sci/moac/people/students/peter_cock/python/protein_contact_map/

Following their lead (which I will reproduce here for completion; Note, however, that I am using a different protein):

import Bio.PDB
import numpy as np

pdb_code = "1QHW"
pdb_filename = "1qhw.pdb"

def calc_residue_dist(residue_one, residue_two) :
    """Returns the C-alpha distance between two residues"""
    diff_vector  = residue_one["CA"].coord - residue_two["CA"].coord
    return np.sqrt(np.sum(diff_vector * diff_vector))

def calc_dist_matrix(chain_one, chain_two) :
    """Returns a matrix of C-alpha distances between two chains"""
    answer = np.zeros((len(chain_one), len(chain_two)), np.float)
    for row, residue_one in enumerate(chain_one) :
        for col, residue_two in enumerate(chain_two) :
            answer[row, col] = calc_residue_dist(residue_one, residue_two)
    return answer

structure = Bio.PDB.PDBParser().get_structure(pdb_code, pdb_filename)
model = structure[0]

dist_matrix = calc_dist_matrix(model["A"], model["A"])

But when I run the above code, I get the following error message:

Traceback (most recent call last):

  File "<ipython-input-26-7239fb7ebe14>", line 4, in <module>
    dist_matrix = calc_dist_matrix(model["A"], model["A"])

  File "<ipython-input-3-730a11883f27>", line 15, in calc_dist_matrix
    answer[row, col] = calc_residue_dist(residue_one, residue_two)

  File "<ipython-input-3-730a11883f27>", line 6, in calc_residue_dist
    diff_vector  = residue_one["CA"].coord - residue_two["CA"].coord

  File "/Users/anaconda/lib/python3.6/site-packages/Bio/PDB/Entity.py", line 39, in __getitem__
    return self.child_dict[id]

KeyError: 'CA'

Any suggestions on how to fix this issue?

Body:
I believe the problem is that some of the elements in model["A"] are not amino acids and therefore do not contain "CA".

To get around this, I wrote a new function which returns only the amino acid residues:

from Bio.PDB import *
chain = model["A"]

def aa_residues(chain):
        aa_only = []
        for i in chain:
            if i.get_resname() in standard_aa_names:
                aa_only.append(i)
        return aa_only

    AA_1 = aa_residues(model["A"])
    dist_matrix = calc_dist_matrix(AA_1, AA_1)


问:
Rails where condition with nested associations
Let's say I have Delivery model which has one Postman and that Postmanhas many Teams.

I would like to get all deliveries with specific team ID = 1 for example.

I have try:

```<code>Delivery.joins(:postman).where(:postmans => {team_ids: 1})
</code>```

But I couldn't manage to get them. How can I achieve this?

答:
You should do like below</p>

```<code>Delivery.joins(:postman => :teams).where(:postman => {teams: {id: 1}})
</code>```

Body:
Let's say I have Delivery model which has one Postman and that Postmanhas many Teams.

I would like to get all deliveries with specific team ID = 1 for example.

I have try:

Delivery.joins(:postman).where(:postmans => {team_ids: 1})

But I couldn't manage to get them. How can I achieve this?

Body:
You should do like below

Delivery.joins(:postman => :teams).where(:postman => {teams: {id: 1}})


问:
why not quotation mark around period
I am beginner in Java. As I was going through the book, I got stuck on this problem. My question is why there are single quotes instead of double quotes around this period. When we want to print a string, we use double quotes.

答:
'.' would indicate a type of char

"." would indicate a type of string

Both will work to print

Title: why not quotation mark around period


问:
JavaFX: ImageView is being displayed only when I use an absolute path... why?
I'm using JavaFX with SceneBuilder on Intellij IDEA. I'm trying to display a simple png image in the login screen of my application. If I try to take the relative path (as showed below) the picture won't be showed (even if I don't get any error nor warning).

```<code><ImageView
    fitHeight="87.0"
    fitWidth="91.0"
    pickOnBounds="true"
    preserveRatio="true">
    <image>
        <Image
            url="@../../res/logo.png" />
    </image>
</ImageView>
</code>```

However, if I try with an absolute path instead it works.

```<code><Image
    url="file:/home/username/Workspaces/IdeaProjects/MyProject/res/logo.png" />
</code>```

Since I'm working on this project with a group and I'm sharing it with git, I absolutely need the path to be relative. How to solve this issue?

Notice that If I insert a relative path that brings to a non-existent resource I get an error! So the IDE correctly recognizes the path, but somehow can't display properly the picture when it's a relative path.

答:
I've tested this with IntelliJ and got it working. I suggest you to do the following:

In IntelliJ go to File -> Project Structure...

Under Modules select your res folder and add it as "Resources" folder.

Click Ok, and change the path of your image to "/logo.png" in the fxml.

Image as follows for better explanation ;)

Body:
I'm using JavaFX with SceneBuilder on Intellij IDEA. I'm trying to display a simple png image in the login screen of my application. If I try to take the relative path (as showed below) the picture won't be showed (even if I don't get any error nor warning).

<ImageView
    fitHeight="87.0"
    fitWidth="91.0"
    pickOnBounds="true"
    preserveRatio="true">
    <image>
        <Image
            url="@../../res/logo.png" />
    </image>
</ImageView>

However, if I try with an absolute path instead it works.

<Image
    url="file:/home/username/Workspaces/IdeaProjects/MyProject/res/logo.png" />

Since I'm working on this project with a group and I'm sharing it with git, I absolutely need the path to be relative. How to solve this issue?

Notice that If I insert a relative path that brings to a non-existent resource I get an error! So the IDE correctly recognizes the path, but somehow can't display properly the picture when it's a relative path.


问:
Xcode 8 Constraints in TableViewController
I have an issue with constraints in my TableViewController. I have put all necessary constraints (I think so), but when I run my app - it looks like a mess. It's really strange for me, because I have one ViewController where I put two table views in one time, used similar constraints and they work pretty fine on different devices. But here is a mess when I run it anywhere.

Here is screenshot of my constraints:

And here is how it looks like when app is running:

What am I doing wrong? I've checked several questions on stackoverflow, but didn't get it.

答:
Add a distance constraint between the text and Name of the item. Then add a constraint from Name of item to the top of the cell.

EDIT
Try to put the text and Name of the item inside a vertically UIStackView and set the certain constraints for it. I think this will solve your problem


问:
Simple Nested For Loop
I'm trying to paste "Area1" 50 times, and "Area2" 50 time right below "Area1" in the same column. My codes run the first 50 times, and replace the first 50 rows when running Area=2. How do I make "Area2" start on a new row, under "Area1"? Thank you :))</p>

```<code>For Area = 1 To 2
    For Row = 1 To 50
        Sheets("A").Cells(Row, 2) = Sheets("A").Cells(2, 31)
        Next Row
Next Area
</code>```

答:
One way to do this is creating another variable and increment it, in second loop, each time +1. Like this:</p>

```<code>For Area = 1 To 2
    For Row = 1 To 50
        myRow = myRow + 1
        Sheets("A").Cells(myRow, 2) = Sheets("A").Cells(2, 31)
        Next Row
Next Area
</code>```

Title: Simple Nested For Loop

Body:
I'm trying to paste "Area1" 50 times, and "Area2" 50 time right below "Area1" in the same column. My codes run the first 50 times, and replace the first 50 rows when running Area=2. How do I make "Area2" start on a new row, under "Area1"? Thank you :))

For Area = 1 To 2
    For Row = 1 To 50
        Sheets("A").Cells(Row, 2) = Sheets("A").Cells(2, 31)
        Next Row
Next Area

Body:
One way to do this is creating another variable and increment it, in second loop, each time +1. Like this:

For Area = 1 To 2
    For Row = 1 To 50
        myRow = myRow + 1
        Sheets("A").Cells(myRow, 2) = Sheets("A").Cells(2, 31)
        Next Row
Next Area


问:
Using std::map to find duplicates in data and its performance issue. Can I pre-allocate it?
My goal is to check for duplicate IDs in my custom data structure. I'm coding it with Visual Studio 2008 Sp1. So I wrote the following debugger-only function that does "sanity checks" on the data as I work with the code.

I'm using the following approach:

I enumerate through all elements in my data structure (which by itself is relatively fast.)

I then use std::map to collect IDs of all elements as keys, while I make the value part point to the data structure element itself (which will help me quickly identify the duplicate.)

For each element in my data structure I see if its ID is in my std::map, and if so, the function asserts. Otherwise it adds it to the map.

Here's a pseudo-code for that:

```<code>std::map<ULONGLONG, BIN_XML_TAG*> dicTagIDs;

for(std::vector<MY_ELEMENT>::const_iterator iTag = arrNode.begin(); iTag != arrNode.end(); ++iTag)
{
    std::map<ULONGLONG, MY_ELEMENT*>::const_iterator itrT = dicTagIDs.find(iTag->uiTagID);
    if(itrT != dicTagIDs.end())
    {
        //Duplicate tag ID!
        MY_ELEMENT* pDuplicateToTag = itrT->second;
        ASSERT(NULL);
    }

    //If not, then add it
    dicTagIDs[iTag->uiTagID] = iTag._Myptr;

    //... may later call itself recursively
}
</code>```

This works, except that the function above gets exponentially slower as the size of my data structure grows. And since I use it everywhere throughout my "debugger-build" code, it'd be nice to speed it up.

So I was thinking to pre-allocate std::map. I don't know the exact number of elements in my data structure (it is structured kinda like an XML file) but I can make an approximate guess that I could use for preallocation.

But std::map doesn't seem to provide a reserve() method.

So any suggestions how to speed this up?

答:
For each element in my data structure I see if its ID is in my
  std::map, and if so, the function asserts. Otherwise it adds it to the
  map.

You probably don't want to do do that, simply use the map's insert() member function, which will fail if the key is already in the map.

And you can't reserve space in tree-based containers like std::map.

Body:
My goal is to check for duplicate IDs in my custom data structure. I'm coding it with Visual Studio 2008 Sp1. So I wrote the following debugger-only function that does "sanity checks" on the data as I work with the code.

I'm using the following approach:

I enumerate through all elements in my data structure (which by itself is relatively fast.)

I then use std::map to collect IDs of all elements as keys, while I make the value part point to the data structure element itself (which will help me quickly identify the duplicate.)

For each element in my data structure I see if its ID is in my std::map, and if so, the function asserts. Otherwise it adds it to the map.

Here's a pseudo-code for that:

std::map<ULONGLONG, BIN_XML_TAG*> dicTagIDs;

for(std::vector<MY_ELEMENT>::const_iterator iTag = arrNode.begin(); iTag != arrNode.end(); ++iTag)
{
    std::map<ULONGLONG, MY_ELEMENT*>::const_iterator itrT = dicTagIDs.find(iTag->uiTagID);
    if(itrT != dicTagIDs.end())
    {
        //Duplicate tag ID!
        MY_ELEMENT* pDuplicateToTag = itrT->second;
        ASSERT(NULL);
    }

    //If not, then add it
    dicTagIDs[iTag->uiTagID] = iTag._Myptr;

    //... may later call itself recursively
}

This works, except that the function above gets exponentially slower as the size of my data structure grows. And since I use it everywhere throughout my "debugger-build" code, it'd be nice to speed it up.

So I was thinking to pre-allocate std::map. I don't know the exact number of elements in my data structure (it is structured kinda like an XML file) but I can make an approximate guess that I could use for preallocation.

But std::map doesn't seem to provide a reserve() method.

So any suggestions how to speed this up?


问:
Run brew restart command using Homebrew module for Ansible
I have been trying to run the command

brew services restart nrpe

with the help of Ansible's homebrew module.

I have gone through the documentation (homebrew ansible doc) but I couldn't find an example which does a similar thing. I have tried the following:

```<code>    - homebrew:
        name: nrpe
        state: present
        install_options: services,restart
</code>```

but it didn't work. Please let me know the correct way to run the command
brew services restart nrpe.

P.S. - Installation of nrpe or other services though homebrew is working great.

Edit 1 - Also including the Nagios tag because this might also be faced by the nagios community.

答:
According to the documentation of the homebrew ansible module, the command :

```<code>brew services restart nrpe
</code>```

seems not implemented. The solution could be to use the command module:

```<code>- name: restart the nrpe service
  command: brew services restart nrpe
</code>```

Body:
I have been trying to run the command

brew services restart nrpe

with the help of Ansible's homebrew module.

I have gone through the documentation (homebrew ansible doc) but I couldn't find an example which does a similar thing. I have tried the following:

    - homebrew:
        name: nrpe
        state: present
        install_options: services,restart

but it didn't work. Please let me know the correct way to run the command
brew services restart nrpe.

P.S. - Installation of nrpe or other services though homebrew is working great.

Edit 1 - Also including the Nagios tag because this might also be faced by the nagios community.

Body:
According to the documentation of the homebrew ansible module, the command :

brew services restart nrpe

seems not implemented. The solution could be to use the command module:

- name: restart the nrpe service
  command: brew services restart nrpe


问:
Select Data from Table and Insert into a different DB
I'm using python and psycopg2 to remotely query some psql databases, and I'm trying to figure out the best way to select the data I need from the remote table, and insert it into a table on a separate DB (local application server).

Most of the stuff I've read has directed me to avoid executemany and look toward COPY operations, but I'm unsure how to implement this on a specific select statement as opposed to the entire table. Should I be headed this way or am I completely off?

答:
Take a look at http://ryrobes.com/featured-articles/using-a-simple-python-script-for-end-to-end-data-transformation-and-etl-part-1/

Granted, this is pulling from Oracle and inserting into SQL Server, but the concepts should be the same.


问:
Set UILabel Text at Completion of CloudKit Asyncronous Operation in Swift
I'm new to Swift, and asynchronous code in general, so tell me if this is way off. Basically I want to:

Open the App

That triggers a read of CloudKit records

Once the read is complete a UILabel will display the number of records retrieved

This clearly isn't useful in itself, but as a principle it will help me to understand the asynchronous code operation, and how to trigger actions on their completion.

```<code>// In ViewController Swift file:

class ViewController: UIViewController{

    override func viewDidLoad() {
        super.viewDidLoad()
        readDatabase()
    }
    @IBOutlet weak var myLabel: UILabel!
}

let VC=ViewController()

//In Another Swift file:

func readDatabase() {
    let predicate = NSPredicate(value: true)
    let query = CKQuery(recordType: "myRecord", predicate: predicate)
    let container = CKContainer.default()
    let privateDB = container.privateCloudDatabase

    privateDB.perform(query, inZoneWith:nil) { (allRecs, err) in
        VC.myLabel.text = ("\(allRecs?.count) records retreived")

    /*
    ERROR OCCURS IN LINE ABOVE:
       CONSOLE: fatal error: unexpectedly found nil while unwrapping an Optional value
       BY CODE LINE: Thread 8:EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0)
    */

    }
}
</code>```

I'm able to set the text field from within the viewDidLoad function, so why not from a function called within that function?

A few other things I've tried:

Use async dispatch to put it on thread 1

Implement a var with within the ViewController class, with a didSet that sets the text, set the var to the desired value in the privateDB.perform code to trigger the change

These both create the same problem as above.

Yes, I know there isn't any error handling in .perform, and yes there are records. If I trigger the setting of the UILabel text to the record count manually a few seconds after the view has loaded, it works fine.

So the question is...
How do I use the completion of the database read as a trigger to load attributes of the records to the view?

Thanks

Edit

What actually happened here was that VC was created globally, but never presented - since loadView was never called for it, myLabel didn't exist and, being a force unwrapped property, caused a crash when it was referenced

答:
Got it, the solution looks like this:

```<code>// In ViewController Swift file:

typealias CompletionHandler = (_ recCount:Int,_ err:Error?) -> Void

class ViewController: UIViewController{

    override func viewDidLoad() {
        super.viewDidLoad()
        readDatabase(completionHandler: { (recCount,success) -> Void in
            if err == nil {
                 self.myLabel.text = "\(recCount) records loaded"
            } else {
                 self.myLabel.text = "load failed: \(err)"
            }
        })
    }
    @IBOutlet weak var myLabel: UILabel!
}

//In Another Swift file:

func readDatabase() {
    let predicate = NSPredicate(value: true)
    let query = CKQuery(recordType: "myRecord", predicate: predicate)
    let container = CKContainer.default()
    let privateDB = container.privateCloudDatabase

    privateDB.perform(query, inZoneWith:nil) { (allRecs, err) in
        if let recCount = allRecs?.count {
            completionHandler(recCount,err)
        } else {
            completionHandler(0,err)
        }
    }
}
</code>```

The difference between this and the original is that this uses the CompletionHandler typealias in the function call for loading the database records, which returns the count of records and an optional error.

The completion operation can now live in the ViewController class and access the UILabel using self.myLabel, which solves the error that was occurring earlier, while keeping the database loading code separate to the ViewController class.

This version of the code also has basic error handling.

Body:
I'm new to Swift, and asynchronous code in general, so tell me if this is way off. Basically I want to:

Open the App

That triggers a read of CloudKit records

Once the read is complete a UILabel will display the number of records retrieved

This clearly isn't useful in itself, but as a principle it will help me to understand the asynchronous code operation, and how to trigger actions on their completion.

// In ViewController Swift file:

class ViewController: UIViewController{

    override func viewDidLoad() {
        super.viewDidLoad()
        readDatabase()
    }
    @IBOutlet weak var myLabel: UILabel!
}

let VC=ViewController()

//In Another Swift file:

func readDatabase() {
    let predicate = NSPredicate(value: true)
    let query = CKQuery(recordType: "myRecord", predicate: predicate)
    let container = CKContainer.default()
    let privateDB = container.privateCloudDatabase

    privateDB.perform(query, inZoneWith:nil) { (allRecs, err) in
        VC.myLabel.text = ("\(allRecs?.count) records retreived")

    /*
    ERROR OCCURS IN LINE ABOVE:
       CONSOLE: fatal error: unexpectedly found nil while unwrapping an Optional value
       BY CODE LINE: Thread 8:EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0)
    */

    }
}

I'm able to set the text field from within the viewDidLoad function, so why not from a function called within that function?

A few other things I've tried:

Use async dispatch to put it on thread 1

Implement a var with within the ViewController class, with a didSet that sets the text, set the var to the desired value in the privateDB.perform code to trigger the change

These both create the same problem as above.

Yes, I know there isn't any error handling in .perform, and yes there are records. If I trigger the setting of the UILabel text to the record count manually a few seconds after the view has loaded, it works fine.

So the question is...
How do I use the completion of the database read as a trigger to load attributes of the records to the view?

Thanks

Edit

What actually happened here was that VC was created globally, but never presented - since loadView was never called for it, myLabel didn't exist and, being a force unwrapped property, caused a crash when it was referenced

Body:
Got it, the solution looks like this:

// In ViewController Swift file:

typealias CompletionHandler = (_ recCount:Int,_ err:Error?) -> Void

class ViewController: UIViewController{

    override func viewDidLoad() {
        super.viewDidLoad()
        readDatabase(completionHandler: { (recCount,success) -> Void in
            if err == nil {
                 self.myLabel.text = "\(recCount) records loaded"
            } else {
                 self.myLabel.text = "load failed: \(err)"
            }
        })
    }
    @IBOutlet weak var myLabel: UILabel!
}

//In Another Swift file:

func readDatabase() {
    let predicate = NSPredicate(value: true)
    let query = CKQuery(recordType: "myRecord", predicate: predicate)
    let container = CKContainer.default()
    let privateDB = container.privateCloudDatabase

    privateDB.perform(query, inZoneWith:nil) { (allRecs, err) in
        if let recCount = allRecs?.count {
            completionHandler(recCount,err)
        } else {
            completionHandler(0,err)
        }
    }
}

The difference between this and the original is that this uses the CompletionHandler typealias in the function call for loading the database records, which returns the count of records and an optional error.

The completion operation can now live in the ViewController class and access the UILabel using self.myLabel, which solves the error that was occurring earlier, while keeping the database loading code separate to the ViewController class.

This version of the code also has basic error handling.


问:
Printing the 3 highest integers from an array without sorting
I am trying to create a program that prints the highest integers from a collection of student's grades array, but the code keeps returning me the same values each time it returns me a value.

So far this is the code:

```<code>class BestGrades {
public static void main(String args[]){
            Scanner sc = new Scanner(System.in);

            int grade[] = new int[6];
            int best[] = new int[3];

            System.out.println("Enter the student's grade...");

            for(int i = 0; i < grade.length; i++){

                    grade[i] = sc.nextInt();

                    for(int a = 0; a < best.length; a++){
                            if(grade[i] > best[a]){
                                    best[a] = grade[i];
                            }
                    }
            }

            for(int i = 0; i < best.length; i++){
                    System.out.println("Best degrees are: "+best[i]);
            }
    }
</code>```

}

As I said, the code will always return me the same highest value 3x.
Pardon me for any mistakes, first time asking here.

答:
You could try to solve this problem in a functional style. Using the previously described strategy:

iterate through array and find if current element is superior to one of the items in the best note array.

if so then find the smallest best note in the array and capture its position

copy the current item to the best note array using the position found in 2.

This is the functional alternative which can capture N best notes:

```<code>public static int[] findNHighest2(int[] array, int limit) {
    return IntStream.range(0, array.length).boxed().collect(() -> new int[limit], (a, i) -> { // collect in array with specified size.
        IntStream.range(0, limit).boxed().filter(j -> array[i] > a[j]).findFirst().ifPresent(k -> { // finding if there is an item larger than the best ones
            int minPos = findMinPos(a, limit); // find the minimum of the best ones
            a[minPos] = array[i]; // copy the new best item to our best item array
        });
    }, (a, i) -> {});
}

private static int findMinPos(int[] array, int limit) {
    return IntStream.range(0, limit)
            .reduce((i,j) -> array[i] > array[j] ? j : i)
            .getAsInt();
}
</code>```

Usage:

```<code>public static void main(String[] args) throws IOException {
    int[] arr = {9, 3,1, 9, 2, 7, 11, 2, 1, -1, 100, 8, 9, 199, 2};
    System.out.println(Arrays.toString(findNHighest(arr.clone(), 6)));
}
</code>```

The result on the console:

```<code>[9, 199, 11, 9, 100, 9]
</code>```

Body:
I am trying to create a program that prints the highest integers from a collection of student's grades array, but the code keeps returning me the same values each time it returns me a value.

So far this is the code:

class BestGrades {
public static void main(String args[]){
            Scanner sc = new Scanner(System.in);

            int grade[] = new int[6];
            int best[] = new int[3];

            System.out.println("Enter the student's grade...");

            for(int i = 0; i < grade.length; i++){

                    grade[i] = sc.nextInt();

                    for(int a = 0; a < best.length; a++){
                            if(grade[i] > best[a]){
                                    best[a] = grade[i];
                            }
                    }
            }

            for(int i = 0; i < best.length; i++){
                    System.out.println("Best degrees are: "+best[i]);
            }
    }

}

As I said, the code will always return me the same highest value 3x.
Pardon me for any mistakes, first time asking here.

Body:
You could try to solve this problem in a functional style. Using the previously described strategy:

iterate through array and find if current element is superior to one of the items in the best note array.

if so then find the smallest best note in the array and capture its position

copy the current item to the best note array using the position found in 2.

This is the functional alternative which can capture N best notes:

public static int[] findNHighest2(int[] array, int limit) {
    return IntStream.range(0, array.length).boxed().collect(() -> new int[limit], (a, i) -> { // collect in array with specified size.
        IntStream.range(0, limit).boxed().filter(j -> array[i] > a[j]).findFirst().ifPresent(k -> { // finding if there is an item larger than the best ones
            int minPos = findMinPos(a, limit); // find the minimum of the best ones
            a[minPos] = array[i]; // copy the new best item to our best item array
        });
    }, (a, i) -> {});
}

private static int findMinPos(int[] array, int limit) {
    return IntStream.range(0, limit)
            .reduce((i,j) -> array[i] > array[j] ? j : i)
            .getAsInt();
}

Usage:

public static void main(String[] args) throws IOException {
    int[] arr = {9, 3,1, 9, 2, 7, 11, 2, 1, -1, 100, 8, 9, 199, 2};
    System.out.println(Arrays.toString(findNHighest(arr.clone(), 6)));
}

The result on the console:

[9, 199, 11, 9, 100, 9]


问:
Scala: fastest `remove(i: Int)` in mutable sequence
Which implementation from scala.collection.mutable package should I take if I intend to do lots of by-index-deletions, like remove(i: Int), in a single-threaded environment? The most obvious choice, ListBuffer, says that it may take linear time depending on buffer size. Is there some collection with log(n) or even constant time for this operation?

答:
Removal operators, including buf remove i, are not part of Seq, but it's actually part of Buffer trait under scala.mutable. (See Buffers)

See the first table on Performance Characteristics. I am guessing buf remove i has the same characteristic as insert, which are linear for both ArrayBuffer and ListBuffer.
As documented in Array Buffers, they use arrays internally, and Link Buffers use linked lists (that's still O(n) for remove).

As an alternative, immutable Vector may give you an effective constant time.

Vectors are represented as trees with a high branching factor. Every tree node contains up to 32 elements of the vector or contains up to 32 other tree nodes. [...] So for all vectors of reasonable size, an element selection involves up to 5 primitive array selections. This is what we meant when we wrote that element access is "effectively constant time".

```<code>scala> import scala.collection.immutable._
import scala.collection.immutable._

scala> def remove[A](xs: Vector[A], i: Int) = (xs take i) ++ (xs drop (i + 1))
remove: [A](xs: scala.collection.immutable.Vector[A],i: Int)scala.collection.immutable.Vector[A]

scala> val foo = Vector(1, 2, 3, 4, 5)
foo: scala.collection.immutable.Vector[Int] = Vector(1, 2, 3, 4, 5)

scala> remove(foo, 2)
res0: scala.collection.immutable.Vector[Int] = Vector(1, 2, 4, 5)
</code>```

Note, however, a high constant time with lots of overhead may not win a quick linear access until the data size is significantly large.

Body:
Removal operators, including buf remove i, are not part of Seq, but it's actually part of Buffer trait under scala.mutable. (See Buffers)

See the first table on Performance Characteristics. I am guessing buf remove i has the same characteristic as insert, which are linear for both ArrayBuffer and ListBuffer.
As documented in Array Buffers, they use arrays internally, and Link Buffers use linked lists (that's still O(n) for remove).

As an alternative, immutable Vector may give you an effective constant time.

Vectors are represented as trees with a high branching factor. Every tree node contains up to 32 elements of the vector or contains up to 32 other tree nodes. [...] So for all vectors of reasonable size, an element selection involves up to 5 primitive array selections. This is what we meant when we wrote that element access is "effectively constant time".

scala> import scala.collection.immutable._
import scala.collection.immutable._

scala> def remove[A](xs: Vector[A], i: Int) = (xs take i) ++ (xs drop (i + 1))
remove: [A](xs: scala.collection.immutable.Vector[A],i: Int)scala.collection.immutable.Vector[A]

scala> val foo = Vector(1, 2, 3, 4, 5)
foo: scala.collection.immutable.Vector[Int] = Vector(1, 2, 3, 4, 5)

scala> remove(foo, 2)
res0: scala.collection.immutable.Vector[Int] = Vector(1, 2, 4, 5)

Note, however, a high constant time with lots of overhead may not win a quick linear access until the data size is significantly large.


问:
How to implements a null-safe Restrictions builder?
I'm screwing up with the implementation of a method that should take two parameters:

a Criteria

and a list of Criterion

My code actually is:

```<code>public static void addNullSafeOrCondition(final Criteria criteria, final Criterion... conditions) {

    final List<Criterion> validCriterion = new ArrayList<Criterion>(conditions.length);

    for (final Criterion condition : conditions) {
        if (condition != null) {
            validCriterion.add(condition);
        }
    }

    if (validCriterion.size() == 0) {
        return;
    } else {
        if (validCriterion.size() == 1) {
            criteria.add(validCriterion.get(0));
        } else {
            //Can't convert list to ... varargs
            criteria.add(Restrictions.or( *** validCriterion *** ));
        }
    }

}
</code>```

I can't find any way to convert an ArrayList to  varargs but specially I'm looking for a better solution, like any existing HibernateUtils library or any Restriction's method, I didn't know, that create a null-safe Restrictions.

Thanks.

答:
```<code>public static void addNullSafeOrCondition(final Criteria criteria, final Criterion... conditions) {
    if (conditions == null || conditions.length==0){
        return;
    }

    final List<Criterion> validCriterion = new ArrayList<Criterion>();

    for (final Criterion condition : conditions) {
        if (condition != null) {
            validCriterion.add(condition);
        }
    }
    if (validCriterion.isEmpty()) {
        return;
    }
    //Can't convert list to ... varargs
    criteria.add(Restrictions.or(validCriterion.toArray(new Criterion[ validCriterion.size() ]))); //public static Disjunction or(Criterion... predicates)--work's for one element also
  }
</code>```

criteria.add(Restrictions.or(validCriterion.toArray(new Criterion[ validCriterion.size() ])));

create your own HibernateUtils  and move your method into your onw HibernateUtils

Body:
I'm screwing up with the implementation of a method that should take two parameters:

a Criteria

and a list of Criterion

My code actually is:

public static void addNullSafeOrCondition(final Criteria criteria, final Criterion... conditions) {

    final List<Criterion> validCriterion = new ArrayList<Criterion>(conditions.length);

    for (final Criterion condition : conditions) {
        if (condition != null) {
            validCriterion.add(condition);
        }
    }

    if (validCriterion.size() == 0) {
        return;
    } else {
        if (validCriterion.size() == 1) {
            criteria.add(validCriterion.get(0));
        } else {
            //Can't convert list to ... varargs
            criteria.add(Restrictions.or( *** validCriterion *** ));
        }
    }

}

I can't find any way to convert an ArrayList to  varargs but specially I'm looking for a better solution, like any existing HibernateUtils library or any Restriction's method, I didn't know, that create a null-safe Restrictions.

Thanks.

Body:
public static void addNullSafeOrCondition(final Criteria criteria, final Criterion... conditions) {
    if (conditions == null || conditions.length==0){
        return;
    }

    final List<Criterion> validCriterion = new ArrayList<Criterion>();

    for (final Criterion condition : conditions) {
        if (condition != null) {
            validCriterion.add(condition);
        }
    }
    if (validCriterion.isEmpty()) {
        return;
    }
    //Can't convert list to ... varargs
    criteria.add(Restrictions.or(validCriterion.toArray(new Criterion[ validCriterion.size() ]))); //public static Disjunction or(Criterion... predicates)--work's for one element also
  }

criteria.add(Restrictions.or(validCriterion.toArray(new Criterion[ validCriterion.size() ])));

create your own HibernateUtils  and move your method into your onw HibernateUtils


问:
Ajax doesn't return json if there is text in php file
I'm pretty new to Jquery Ajax and sorry if that's a simple thing.

So my problem here is that I want to retrieve a json object from my php file, but it only works when I echo only one Json object like this :

```<code><?php
header('Content-type: application/json; charset=utf-8');
$arr = array ('Lastname'=>'Doe','Firstname'=>'John','Age'=>109);
echo json_encode($arr);
</code>```

When I want to echo another json or some text returned as json in my javascript file, I don't get anything back from the ajax call.

```<code>  <?php
// This code doesn't work
    header('Content-type: application/json; charset=utf-8');
    $arr = array ('Lastname'=>'Doe','Firstname'=>'John','Age'=>109);
    echo 'hi there';
    $json = 'Hello people';
    echo json_encode($json);
    echo json_encode($arr);
</code>```

My ajax call is this :

```<code>$.ajax({
        url: 'test.php',
        type: 'GET',
        success: function (response) {
            console.log(response);
        }
    });
</code>```

So my final question is : what's wrong in my code, and what's not allowed in ajax call

答:
You can only put one JSON object in a response. If you have more than one thing you want to send, just make an array:

```<code>echo json_encode([
    'user' => ['Lastname'=>'Doe', 'Firstname'=>'John', 'Age'=>109],
    'other' => 'some other stuff',
    'more' => ['even', 'more', 'suff'],
]);
</code>```

You also don't want any extraneous output before or after the JSON, so remove this:

```<code>echo 'hi there';
</code>```

Body:
I'm pretty new to Jquery Ajax and sorry if that's a simple thing.

So my problem here is that I want to retrieve a json object from my php file, but it only works when I echo only one Json object like this :

<?php
header('Content-type: application/json; charset=utf-8');
$arr = array ('Lastname'=>'Doe','Firstname'=>'John','Age'=>109);
echo json_encode($arr);

When I want to echo another json or some text returned as json in my javascript file, I don't get anything back from the ajax call.

  <?php
// This code doesn't work
    header('Content-type: application/json; charset=utf-8');
    $arr = array ('Lastname'=>'Doe','Firstname'=>'John','Age'=>109);
    echo 'hi there';
    $json = 'Hello people';
    echo json_encode($json);
    echo json_encode($arr);

My ajax call is this :

$.ajax({
        url: 'test.php',
        type: 'GET',
        success: function (response) {
            console.log(response);
        }
    });

So my final question is : what's wrong in my code, and what's not allowed in ajax call

Body:
You can only put one JSON object in a response. If you have more than one thing you want to send, just make an array:

echo json_encode([
    'user' => ['Lastname'=>'Doe', 'Firstname'=>'John', 'Age'=>109],
    'other' => 'some other stuff',
    'more' => ['even', 'more', 'suff'],
]);

You also don't want any extraneous output before or after the JSON, so remove this:

echo 'hi there';


问:
Does anyone know where a parquet table stores the files?
I'm inserting some records into a Hive Parquet table and everything is flawlessly working, however I would like to check the files using the hue file browser, does anyone know where are those files located ? and is there a property I could use while creating the table to change the location ?

Here's my table definition:

```<code>CREATE EXTERNAL TABLE parquet_test_2 (
column1 int,
column2 int
)
STORED AS PARQUET
TBLPROPERTIES ('PARQUET.COMPRESS'='SNAPPY');
</code>```

答:
You should have control over the directory where you are writing files. I am writing data from once hive to another but I change the format from text to parquet and I am using below command:

```<code>val hiveDF = hsc.sql(iSql)
hiveDF.coalesce(noExecutors).write.mode("append").parquet(parquetLoc)`
</code>```

It would be similar if you are writing from a plain text file. As @Samson Scharfrichter mentioned you can use the LOCATION option while creating the table to have specific directory as your source but you need to make sure you are writing data to that directory only.

```<code>CREATE EXTERNAL TABLE parquet_test_2 (
column1 int,
column2 int
)
STORED AS PARQUET
LOCATION '{HDFS_DIR}'
TBLPROPERTIES ('PARQUET.COMPRESS'='SNAPPY');
</code>```

Body:
I'm inserting some records into a Hive Parquet table and everything is flawlessly working, however I would like to check the files using the hue file browser, does anyone know where are those files located ? and is there a property I could use while creating the table to change the location ?

Here's my table definition:

CREATE EXTERNAL TABLE parquet_test_2 (
column1 int,
column2 int
)
STORED AS PARQUET
TBLPROPERTIES ('PARQUET.COMPRESS'='SNAPPY');

Body:
You should have control over the directory where you are writing files. I am writing data from once hive to another but I change the format from text to parquet and I am using below command:

val hiveDF = hsc.sql(iSql)
hiveDF.coalesce(noExecutors).write.mode("append").parquet(parquetLoc)`

It would be similar if you are writing from a plain text file. As @Samson Scharfrichter mentioned you can use the LOCATION option while creating the table to have specific directory as your source but you need to make sure you are writing data to that directory only.

CREATE EXTERNAL TABLE parquet_test_2 (
column1 int,
column2 int
)
STORED AS PARQUET
LOCATION '{HDFS_DIR}'
TBLPROPERTIES ('PARQUET.COMPRESS'='SNAPPY');