问:
How to add multiple textfields programatically in swift ios
I am trying to show multiple textFields by running a loop, that whether the number of textfields noTextField is greater than zero (which is an input value), it should display the multiple textFields on ViewController.

Here is what I have one textfield and prints multiple hello but could not display multiple textfields.

What I have

enter image description here

What I want

enter image description here

```<code>            if self.noTextFields! > 0 {
            for _ in 0..<self.noTextFields! {
               // self.createForm()
                print ("hello")

                let sampleTextField =  UITextField(frame: CGRect(x: 20, y: 100, width: 300, height: 40))
                sampleTextField.placeholder = "Enter text here"
                sampleTextField.font = UIFont.systemFont(ofSize: 15)
                sampleTextField.borderStyle = UITextBorderStyle.roundedRect
                sampleTextField.autocorrectionType = UITextAutocorrectionType.no
                sampleTextField.keyboardType = UIKeyboardType.default
                sampleTextField.returnKeyType = UIReturnKeyType.done
                sampleTextField.clearButtonMode = UITextFieldViewMode.whileEditing;
                sampleTextField.contentVerticalAlignment = UIControlContentVerticalAlignment.center
                sampleTextField.delegate = self as? UITextFieldDelegate
                self.view.addSubview(sampleTextField)

            }
        }
</code>```

答:
Mistakes and Corrections:

Check the SubView items contents for the self.view by self.view.items values printing in logs.

You have not assigned the X / Y position for the +1 counter text fields you are allocating to any incremental position so even if the new object will get created it will be overlapped on the same previous item.

I would always recommend to put the textfield object in array at same time when you do addSubview call, immediately after this                self.view.addSubview(sampleTextField) call. This will help me to save the reference for each text field item when required to modify / access / deallocate.

You also set the tag for each textfield object so its better to get the object with that tag from the subviews with [self.view viewWithTag:tagNo] call if you dont want an array to be used.

Your snippet will look like

```<code>     var xValue = 0,yValue =0
     var tagNo = 0
     var textObjects = allocate new array.

     if self.noTextFields! > 0 {
                for _ in 0..<self.noTextFields! {
                   // self.createForm()
                    print ("hello")

                    let sampleTextField =  UITextField(frame: CGRect(x: xValue, y: yValue, width: 300, height: 40)) //Note that I have set xValue and yValue
                    sampleTextField.placeholder = "Enter text here"
                    sampleTextField.font = UIFont.systemFont(ofSize: 15)
                    sampleTextField.borderStyle = UITextBorderStyle.roundedRect
                    sampleTextField.autocorrectionType = UITextAutocorrectionType.no
                    sampleTextField.keyboardType = UIKeyboardType.default
                    sampleTextField.returnKeyType = UIReturnKeyType.done
                    sampleTextField.clearButtonMode = UITextFieldViewMode.whileEditing;
                    sampleTextField.contentVerticalAlignment = UIControlContentVerticalAlignment.center
                    sampleTextField.delegate = self as? UITextFieldDelegate
                    sampleTextField.tag = tagNo  //Note this line for tagNo
                    self.view.addSubview(sampleTextField)
                    textObjects.addObject:sampleTextField //Note this line for adding textfield to array for reference to get total items added

yValue = yValue + sampleTextField.frame.size.height + 20; //Added yValue to place another text view at bottom of initial one and 20px buffer for gap.
                }
            }
</code>```

print "Total Textobjects in array:textObjects.count

If required to get object from view its self.view.viewwithTag(tagNo) will return exact text field.

Body:
I am trying to show multiple textFields by running a loop, that whether the number of textfields noTextField is greater than zero (which is an input value), it should display the multiple textFields on ViewController.

Here is what I have one textfield and prints multiple hello but could not display multiple textfields.

What I have

enter image description here

What I want

enter image description here

            if self.noTextFields! > 0 {
            for _ in 0..<self.noTextFields! {
               // self.createForm()
                print ("hello")

                let sampleTextField =  UITextField(frame: CGRect(x: 20, y: 100, width: 300, height: 40))
                sampleTextField.placeholder = "Enter text here"
                sampleTextField.font = UIFont.systemFont(ofSize: 15)
                sampleTextField.borderStyle = UITextBorderStyle.roundedRect
                sampleTextField.autocorrectionType = UITextAutocorrectionType.no
                sampleTextField.keyboardType = UIKeyboardType.default
                sampleTextField.returnKeyType = UIReturnKeyType.done
                sampleTextField.clearButtonMode = UITextFieldViewMode.whileEditing;
                sampleTextField.contentVerticalAlignment = UIControlContentVerticalAlignment.center
                sampleTextField.delegate = self as? UITextFieldDelegate
                self.view.addSubview(sampleTextField)

            }
        }

Body:
Mistakes and Corrections:

Check the SubView items contents for the self.view by self.view.items values printing in logs.

You have not assigned the X / Y position for the +1 counter text fields you are allocating to any incremental position so even if the new object will get created it will be overlapped on the same previous item.

I would always recommend to put the textfield object in array at same time when you do addSubview call, immediately after this                self.view.addSubview(sampleTextField) call. This will help me to save the reference for each text field item when required to modify / access / deallocate.

You also set the tag for each textfield object so its better to get the object with that tag from the subviews with [self.view viewWithTag:tagNo] call if you dont want an array to be used.

Your snippet will look like

     var xValue = 0,yValue =0
     var tagNo = 0
     var textObjects = allocate new array.

     if self.noTextFields! > 0 {
                for _ in 0..<self.noTextFields! {
                   // self.createForm()
                    print ("hello")

                    let sampleTextField =  UITextField(frame: CGRect(x: xValue, y: yValue, width: 300, height: 40)) //Note that I have set xValue and yValue
                    sampleTextField.placeholder = "Enter text here"
                    sampleTextField.font = UIFont.systemFont(ofSize: 15)
                    sampleTextField.borderStyle = UITextBorderStyle.roundedRect
                    sampleTextField.autocorrectionType = UITextAutocorrectionType.no
                    sampleTextField.keyboardType = UIKeyboardType.default
                    sampleTextField.returnKeyType = UIReturnKeyType.done
                    sampleTextField.clearButtonMode = UITextFieldViewMode.whileEditing;
                    sampleTextField.contentVerticalAlignment = UIControlContentVerticalAlignment.center
                    sampleTextField.delegate = self as? UITextFieldDelegate
                    sampleTextField.tag = tagNo  //Note this line for tagNo
                    self.view.addSubview(sampleTextField)
                    textObjects.addObject:sampleTextField //Note this line for adding textfield to array for reference to get total items added

yValue = yValue + sampleTextField.frame.size.height + 20; //Added yValue to place another text view at bottom of initial one and 20px buffer for gap.
                }
            }

print "Total Textobjects in array:textObjects.count

If required to get object from view its self.view.viewwithTag(tagNo) will return exact text field.


来源: stackexchange

问:
How do I create a link using JavaScript?
I have a string for a title and a string for a link.  I'm not sure how to put the two together to create a link on a page using JavaScript.  Any help is appreciated.

The reason I'm trying to figure this out is because I have an RSS feed and have a list of titles ands URLs.  I would like to link the titles to the URL to make the page useful.

I am using jQuery but am completely new to it and wasn't aware it could help in this situation.

答:
Create links using JavaScript:

```<code><script language="javascript">
<!--
document.write("<a href=\"www.example.com\">");
document.write("Your Title");
document.write("</a>");
//-->
</script>
</code>```

OR

```<code><script type="text/javascript">
document.write('Your Title'.link('http://www.example.com'));
</script>
</code>```

OR

```<code><script type="text/javascript">
newlink = document.createElement('a');
newlink.innerHTML = 'Google';
newlink.setAttribute('title', 'Google');
newlink.setAttribute('href', 'http://google.com');
document.body.appendChild(newlink);
</script>
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Create links using JavaScript:

<script language="javascript">
<!--
document.write("<a href=\"www.example.com\">");
document.write("Your Title");
document.write("</a>");
//-->
</script>

OR

<script type="text/javascript">
document.write('Your Title'.link('http://www.example.com'));
</script>

OR

<script type="text/javascript">
newlink = document.createElement('a');
newlink.innerHTML = 'Google';
newlink.setAttribute('title', 'Google');
newlink.setAttribute('href', 'http://google.com');
document.body.appendChild(newlink);
</script>

ContentLicense: CC BY-SA 2.5


问:
Index of a substring in a string with Swift
I'm used to do this in JavaScript:

```<code>var domains = "abcde".substring(0, "abcde".indexOf("cd")) // Returns "ab"
</code>```

Swift doesn't have this function, how to do something similar?

答:
In Swift 4 :

Getting Index of a character in a string :

```<code>let str = "abcdefghabcd"
if let index = str.index(of: "b") {
   print(index) // Index(_compoundOffset: 4, _cache: Swift.String.Index._Cache.character(1))
}
</code>```

Creating SubString (prefix and suffix) from String using Swift 4:

```<code>let str : String = "ilike"
for i in 0...str.count {
    let index = str.index(str.startIndex, offsetBy: i) // String.Index
    let prefix = str[..<index] // String.SubSequence
    let suffix = str[index...] // String.SubSequence
    print("prefix \(prefix), suffix : \(suffix)")
}
</code>```

Output

```<code>prefix , suffix : ilike
prefix i, suffix : like
prefix il, suffix : ike
prefix ili, suffix : ke
prefix ilik, suffix : e
prefix ilike, suffix :
</code>```

If you want to generate a substring between 2 indices , use :

```<code>let substring1 = string[startIndex...endIndex] // including endIndex
let subString2 = string[startIndex..<endIndex] // excluding endIndex
</code>```

Body:
I'm used to do this in JavaScript:

var domains = "abcde".substring(0, "abcde".indexOf("cd")) // Returns "ab"

Swift doesn't have this function, how to do something similar?

Body:
In Swift 4 :

Getting Index of a character in a string :

let str = "abcdefghabcd"
if let index = str.index(of: "b") {
   print(index) // Index(_compoundOffset: 4, _cache: Swift.String.Index._Cache.character(1))
}

Creating SubString (prefix and suffix) from String using Swift 4:

let str : String = "ilike"
for i in 0...str.count {
    let index = str.index(str.startIndex, offsetBy: i) // String.Index
    let prefix = str[..<index] // String.SubSequence
    let suffix = str[index...] // String.SubSequence
    print("prefix \(prefix), suffix : \(suffix)")
}

Output

prefix , suffix : ilike
prefix i, suffix : like
prefix il, suffix : ike
prefix ili, suffix : ke
prefix ilik, suffix : e
prefix ilike, suffix :

If you want to generate a substring between 2 indices , use :

let substring1 = string[startIndex...endIndex] // including endIndex
let subString2 = string[startIndex..<endIndex] // excluding endIndex

ContentLicense: CC BY-SA 3.0


问:
finding a path in a 2 dimensional plain with obstacles
I'm trying to solve a programming task I've been given and I don't have the slightest idea how to do it.

This is the problem:

Skinny Pete is invited to a garden birthday party. He doesn’t really
  like parties too much, but heard that the birthday cake is going to be
  really amazing and he wouldn’t like to miss the chance to try it.

There is only one little problem. There is a sprinkler system
  installed in the garden and by knowing his friends, there is a high
  chance of someone turning it on as a party prank. Pete likes cake, but
  really hates getting wet. Luckily he found a sketch of the garden that
  has the location of the sprinklers and how far each one can sprinkle
  water.

The garden looks like a rectangle that is open on one side and has the house in the opposite side.

The cake is going to be in the house.

The other two sides have fences so one can not enter through there, and the house does not have a back entrance. Pete is interested to
  know if it is possible to enter the garden and get to the house
  without any risk of getting wet.

For simplicity we can think that the map of the garden is in Cartesian
  coordinate system.

The garden is a rectangle that has sides parallel to the axes and having its bottom left corner at the origin (0, 0).

The entrance to the garden is the left side and the the house is at the right side.

Sprinklers are represented as circles with a center and a radius. Stepping anywhere inside such a circle might get you wet.

For the purpose of this problem, and since Pete is so skinny, we can think of him as just a point travelling in the space, with real
  numbers as coordinates.

Input Specifications First line of the standard input contains two
  space separated integers H and W, the height and the width of the
  garden.

Next line contains the number of sprinklers N. After that N lines
  follow having three space separated integers each - Xi, Yi and Ri.
  This a description of a sprinkler as a circle with center (Xi, Yi) and
  radius Ri.

1 ≤ N ≤ 128

1 ≤ H, W ≤ 1024

0 ≤ Xi ≤ W

0 ≤ Yi ≤ H

1 ≤ Ri ≤ 1024

Output Specifications

Output a single line containing “CAKE” (without quotes) if it is
  possible to get to the house without getting wet and “NO CAKE”(without
  quotes) otherwise.

thanks in advance to helpers

答:
Since you show no code and you only implicitly ask for help, I'll give a key idea and leave the mathematics and the implementation to  you.

Skinny Pete can get the cake without getting wet unless there is a chain of sprinkler circles between the bottom and the top of the garden. In other words, we can assume that Pete succeeds. But look through all the circles. We see if any circle intersects the bottom edge of the garden--that is easy mathematics. If there is none, Pete really succeeds. If there is, see if there is another circle that intersects that first one, then if there is another that intersects the second, etc. Finally, you see if the last circle in this chain intersects the top edge of the garden. If there is any such chain of intersecting circles that also intersects top and bottom of the garden, poor Pete goes hungry. (Note that just one circle that intersects both top and bottom would also frustrate Pete--consider that to be a chain of one.)

Here is a diagram of the second example in your contest PDF, where you can see there is no chain of spanning circles so Pete succeeds.

And here is a diagram of the third example, where Pete fails. Note that there is a chain of four circles on the left, colored blue, that spans the garden.

Given that idea, there is an obvious O(N^2) algorithm to find all pairs of intersecting circles and an O(N) algorithm to find the circles intersecting the top and bottom sides of the garden. You could use a path-finding algorithm from graph theory to solve your problem. Think of the top and bottom sides and your circles as nodes in the graph, with two nodes connected with an edge if they intersect. You then search for a path between the nodes representing the top and bottom sides.

Good luck on figuring the mathematics, algorithm, and code.


问:
Error with passing data over Intent
I'm trying to pass an ID from one class to another using intent after watching a youtube tutorial. However, it always passes over the default value of -1 rather than the value I want.

```<code>mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
            String homeTeam = adapterView.getItemAtPosition(i).toString();
            Log.d(TAG, "onItemClick: You Clicked on " + homeTeam);

            Cursor data = myDB.getMatch(homeTeam); //get the id associated with that name
            int itemID = -1;
            while(data.moveToNext()){
                itemID = data.getInt(0);
            }
            if(itemID > -1){
                //Log.d(TAG, "onItemClick: The ID is: " + itemID);
                Intent editScreenIntent = new Intent(ViewMatchesActivity.this, UpdateMatchActivity.class);
                editScreenIntent.putExtra("MatchId", itemID);
                editScreenIntent.putExtra("homeTeam",homeTeam);
                startActivity(editScreenIntent);
            }
            else{
                toastMessage("No ID associated with that name");
            }
        }
    });
}
</code>```

The class it goes to:

```<code> //get the intent extra from the ListDataActivity
    Intent receivedIntent = getIntent();

    //now get the itemID we passed as an extra
    selectedID = receivedIntent.getIntExtra("matchId", -1); //NOTE: -1 is just the default value

    //now get the name we passed as an extra
    selectedName = receivedIntent.getStringExtra("homeTeam");

    //set the text to show the current selected name
    editable_item.setText(selectedName);
</code>```

In his tutorial, it works fine but when I try it after I edit a match, in my log it comes up with MatchId = -1 when it shouldn't be.

I'll include the method in the database also:

```<code>public void updateName(String newName, int id, String oldName){
    SQLiteDatabase db = this.getWritableDatabase();
    String query = "UPDATE " + MATCH_TABLE + " SET " + MATCH_HOME_TEAM_COL +
            " = '" + newName + "' WHERE " + MATCH_ID_COL + " = '" + id + "'" +
            " AND " + MATCH_HOME_TEAM_COL + " = '" + oldName + "'";
    Log.d(TAG, "updateName: query: " + query);
    Log.d(TAG, "updateName: Setting name to " + newName);
    db.execSQL(query);
}
</code>```

答:
The key which you have passing is MatchId and you are fetching data from matchId, Which are not same.

Replace your code to

```<code> selectedID = receivedIntent.getIntExtra("MatchId", -1); //NOTE: -1 is just the default value
</code>```

Title: Error with passing data over Intent

Body:
I'm trying to pass an ID from one class to another using intent after watching a youtube tutorial. However, it always passes over the default value of -1 rather than the value I want.

mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
            String homeTeam = adapterView.getItemAtPosition(i).toString();
            Log.d(TAG, "onItemClick: You Clicked on " + homeTeam);

            Cursor data = myDB.getMatch(homeTeam); //get the id associated with that name
            int itemID = -1;
            while(data.moveToNext()){
                itemID = data.getInt(0);
            }
            if(itemID > -1){
                //Log.d(TAG, "onItemClick: The ID is: " + itemID);
                Intent editScreenIntent = new Intent(ViewMatchesActivity.this, UpdateMatchActivity.class);
                editScreenIntent.putExtra("MatchId", itemID);
                editScreenIntent.putExtra("homeTeam",homeTeam);
                startActivity(editScreenIntent);
            }
            else{
                toastMessage("No ID associated with that name");
            }
        }
    });
}

The class it goes to:

 //get the intent extra from the ListDataActivity
    Intent receivedIntent = getIntent();

    //now get the itemID we passed as an extra
    selectedID = receivedIntent.getIntExtra("matchId", -1); //NOTE: -1 is just the default value

    //now get the name we passed as an extra
    selectedName = receivedIntent.getStringExtra("homeTeam");

    //set the text to show the current selected name
    editable_item.setText(selectedName);

In his tutorial, it works fine but when I try it after I edit a match, in my log it comes up with MatchId = -1 when it shouldn't be.

I'll include the method in the database also:

public void updateName(String newName, int id, String oldName){
    SQLiteDatabase db = this.getWritableDatabase();
    String query = "UPDATE " + MATCH_TABLE + " SET " + MATCH_HOME_TEAM_COL +
            " = '" + newName + "' WHERE " + MATCH_ID_COL + " = '" + id + "'" +
            " AND " + MATCH_HOME_TEAM_COL + " = '" + oldName + "'";
    Log.d(TAG, "updateName: query: " + query);
    Log.d(TAG, "updateName: Setting name to " + newName);
    db.execSQL(query);
}

Body:
The key which you have passing is MatchId and you are fetching data from matchId, Which are not same.

Replace your code to

 selectedID = receivedIntent.getIntExtra("MatchId", -1); //NOTE: -1 is just the default value


问:
Why is there no transform_if in the C++ standard library?
A use case emerged when wanting to do a contitional copy (1. doable with copy_if) but from a container of values to a container of pointers to those values (2. doable with transform).

With the available tools I can't do it in less than two steps :

```<code>#include <vector>
#include <algorithm>

using namespace std;

struct ha {
    int i;
    explicit ha(int a) : i(a) {}
};

int main()
{
    vector<ha> v{ ha{1}, ha{7}, ha{1} }; // initial vector
    // GOAL : make a vector of pointers to elements with i < 2
    vector<ha*> ph; // target vector
    vector<ha*> pv; // temporary vector
    // 1.
    transform(v.begin(), v.end(), back_inserter(pv),
        [](ha &arg) { return &arg; });
    // 2.
    copy_if(pv.begin(), pv.end(), back_inserter(ph),
        [](ha *parg) { return parg->i < 2;  }); // 2.

    return 0;
}
</code>```

Ofcourse we could call remove_if on pv and eliminate the need for a temporary, better yet though, it's not difficult to implement (for unary operations) something like this :

```<code>template <
    class InputIterator, class OutputIterator,
    class UnaryOperator, class Pred
>
OutputIterator transform_if(InputIterator first1, InputIterator last1,
                            OutputIterator result, UnaryOperator op, Pred pred)
{
    while (first1 != last1)
    {
        if (pred(*first1)) {
            *result = op(*first1);
            ++result;
        }
        ++first1;
    }
    return result;
}

// example call
transform_if(v.begin(), v.end(), back_inserter(ph),
[](ha &arg) { return &arg;      }, // 1.
[](ha &arg) { return arg.i < 2; });// 2.
</code>```

Is there a more elegant workaround with the available C++ standard library tools ?

Is there a reason why transform_if does not exist in the library? Is the combination of the existing tools a sufficient workaround and/or considered performance wise well behaved ?

答:
After just finding this question again after some time, and devising a whole slew of potentially useful generic iterator adaptors I realized that the original question required NOTHING more than std::reference_wrapper.

Use it instead of a pointer, and you're good:

Live On Coliru

```<code>#include <algorithm>
#include <functional> // std::reference_wrapper
#include <iostream>
#include <vector>

struct ha {
    int i;
};

int main() {
    std::vector<ha> v { {1}, {7}, {1}, };

    std::vector<std::reference_wrapper<ha const> > ph; // target vector
    copy_if(v.begin(), v.end(), back_inserter(ph), [](const ha &parg) { return parg.i < 2; });

    for (ha const& el : ph)
        std::cout << el.i << " ";
}
</code>```

Prints

```<code>1 1
</code>```

Body:
A use case emerged when wanting to do a contitional copy (1. doable with copy_if) but from a container of values to a container of pointers to those values (2. doable with transform).

With the available tools I can't do it in less than two steps :

#include <vector>
#include <algorithm>

using namespace std;

struct ha {
    int i;
    explicit ha(int a) : i(a) {}
};

int main()
{
    vector<ha> v{ ha{1}, ha{7}, ha{1} }; // initial vector
    // GOAL : make a vector of pointers to elements with i < 2
    vector<ha*> ph; // target vector
    vector<ha*> pv; // temporary vector
    // 1.
    transform(v.begin(), v.end(), back_inserter(pv),
        [](ha &arg) { return &arg; });
    // 2.
    copy_if(pv.begin(), pv.end(), back_inserter(ph),
        [](ha *parg) { return parg->i < 2;  }); // 2.

    return 0;
}

Ofcourse we could call remove_if on pv and eliminate the need for a temporary, better yet though, it's not difficult to implement (for unary operations) something like this :

template <
    class InputIterator, class OutputIterator,
    class UnaryOperator, class Pred
>
OutputIterator transform_if(InputIterator first1, InputIterator last1,
                            OutputIterator result, UnaryOperator op, Pred pred)
{
    while (first1 != last1)
    {
        if (pred(*first1)) {
            *result = op(*first1);
            ++result;
        }
        ++first1;
    }
    return result;
}

// example call
transform_if(v.begin(), v.end(), back_inserter(ph),
[](ha &arg) { return &arg;      }, // 1.
[](ha &arg) { return arg.i < 2; });// 2.

Is there a more elegant workaround with the available C++ standard library tools ?

Is there a reason why transform_if does not exist in the library? Is the combination of the existing tools a sufficient workaround and/or considered performance wise well behaved ?

Body:
After just finding this question again after some time, and devising a whole slew of potentially useful generic iterator adaptors I realized that the original question required NOTHING more than std::reference_wrapper.

Use it instead of a pointer, and you're good:

Live On Coliru

#include <algorithm>
#include <functional> // std::reference_wrapper
#include <iostream>
#include <vector>

struct ha {
    int i;
};

int main() {
    std::vector<ha> v { {1}, {7}, {1}, };

    std::vector<std::reference_wrapper<ha const> > ph; // target vector
    copy_if(v.begin(), v.end(), back_inserter(ph), [](const ha &parg) { return parg.i < 2; });

    for (ha const& el : ph)
        std::cout << el.i << " ";
}

Prints

1 1


问:
What does exactly mean by the term repository in git?
I'm trying to learn git.

I read few tutorials. Everywhere I got confused with the actual meaning of this term called 'Repository'.

See the below definitions :

A repository contains a directory named .git, where git keeps all of
  its metadata for the repository. The content of the .git directory are
  private to git.

So, my question is whether the directory which contains entire project (i.e. all the files of my project) along with the .git directory (usually it's hidden by default) is called the Repository of only the .git folder present within my project folder is called the Repository?

答:
Think of this in this way: The folder containing your project files (all the code) is the code repository. The .git folder that contains the Git metadata is the Git repository. The Git repository corresponds to the contents of the code repository.

In general, when someone says "Repository", it usually means the code repository (including the .git folder, if the code base is version-controlled). When "Repository" is said in terms of Git, it technically means the .git folder and its contents.


问:
cast from sockaddr * to sockaddr_in * increases required alignment
The compiler produces this warning when I'm working with some code which looks like -

```<code>....

for(p = res; p != NULL; p = p->ai_next) {
    void *addr;
    std::string ipVer = "IPv0";

    if(p->ai_family == AF_INET) {
        ipVer                    = "IPv4";
        struct sockaddr_in *ipv4 = (struct sockaddr_in *)p->ai_addr;
        addr                     = &(ipv4->sin_addr);
    }

    else {
        ipVer                     = "IPv6";
        struct sockaddr_in6 *ipv6 = (struct sockaddr_in6 *)p->ai_addr;
        addr                      = &(ipv6->sin6_addr);
    }
....
}
</code>```

where p = res are of type struct addrinfo and the types producing warnings are sockaddr_in and sockaddr_in6. The warning comes from statements :

struct sockaddr_in *ipv4 = (struct sockaddr_in *)p->ai_addr;

struct sockaddr_in6 *ipv6 = (struct sockaddr_in6 *)p->ai_addr;

All I want to know is what is causing this warning and what can I do to correct it if this is not the proper way to do things. Could I use any of static_cast / dynamic_cast / reinterpret_cast here?

The exact warning is - cast from 'struct sockaddr *' to 'struct sockaddr_in *' increases required alignment from 2 to 4.

答:
To elaborate on the memcpy version. I thnk this is needed for ARM which cannot have misalligned data.

I created a struct that contains just the first two fields (I only needed port)

```<code>struct sockaddr_in_header {
    sa_family_t    sin_family; /* address family: AF_INET */
    in_port_t      sin_port;   /* port in network byte order */
};
</code>```

Then to get the port out, I used memcpy to move the data to the stack

```<code>struct sockaddr_in_header   sinh;
unsigned short              sin_port;

memcpy(&sinh, conn->local_sockaddr, sizeof(struct sockaddr_in_header));
</code>```

And return the port

```<code>sin_port = ntohs(sinh.sin_port);
</code>```

This answer is really related to getting the port on Arm

How do I cast sockaddr pointer to sockaddr_in on Arm

The powers that be think that to be the same question as this one, however I dont want to ignore warnings. Experience has taught me that is a bad idea.

Body:
The compiler produces this warning when I'm working with some code which looks like -

....

for(p = res; p != NULL; p = p->ai_next) {
    void *addr;
    std::string ipVer = "IPv0";

    if(p->ai_family == AF_INET) {
        ipVer                    = "IPv4";
        struct sockaddr_in *ipv4 = (struct sockaddr_in *)p->ai_addr;
        addr                     = &(ipv4->sin_addr);
    }

    else {
        ipVer                     = "IPv6";
        struct sockaddr_in6 *ipv6 = (struct sockaddr_in6 *)p->ai_addr;
        addr                      = &(ipv6->sin6_addr);
    }
....
}

where p = res are of type struct addrinfo and the types producing warnings are sockaddr_in and sockaddr_in6. The warning comes from statements :

struct sockaddr_in *ipv4 = (struct sockaddr_in *)p->ai_addr;

struct sockaddr_in6 *ipv6 = (struct sockaddr_in6 *)p->ai_addr;

All I want to know is what is causing this warning and what can I do to correct it if this is not the proper way to do things. Could I use any of static_cast / dynamic_cast / reinterpret_cast here?

The exact warning is - cast from 'struct sockaddr *' to 'struct sockaddr_in *' increases required alignment from 2 to 4.

Body:
To elaborate on the memcpy version. I thnk this is needed for ARM which cannot have misalligned data.

I created a struct that contains just the first two fields (I only needed port)

struct sockaddr_in_header {
    sa_family_t    sin_family; /* address family: AF_INET */
    in_port_t      sin_port;   /* port in network byte order */
};

Then to get the port out, I used memcpy to move the data to the stack

struct sockaddr_in_header   sinh;
unsigned short              sin_port;

memcpy(&sinh, conn->local_sockaddr, sizeof(struct sockaddr_in_header));

And return the port

sin_port = ntohs(sinh.sin_port);

This answer is really related to getting the port on Arm

How do I cast sockaddr pointer to sockaddr_in on Arm

The powers that be think that to be the same question as this one, however I dont want to ignore warnings. Experience has taught me that is a bad idea.


问:
In Java, will empty collections of the same type, but different type parameters always be equal?
Consider the following snippet:

```<code>    List<String> list1 = new ArrayList<>();
    List<Integer> list2 = new ArrayList<>();
    assertThat(list1.equals(list2), is(true));
</code>```

The assertion succeeds.

Indeed, as far as I understand, there is no way in Java, for the equals method to differentiate between the two, due to run-time type-erasure (i.e. the fact the type arguments String and Integer are only accessible at compile-time, but not at run-time).
And since there are no elements, which could be compared, equals has to return true. And by this line of thought, this must be true, for all collections.

So the question is the following: is my thought process correct, or am I missing something?

EDIT

@qqilihq gave an excellent answer, which prompts the next question:
Is this possible to achieve without passing the type explicitly (I'm fine if the type is stored explicitly somehow, just the user does should not have to pass it.)

I attempted the following, but it did not work (I guess due to type erasure):

```<code>    public TypedList(List<T> delegate) {
        this.delegate = Objects.requireNonNull(delegate);
        this.type = (Class<T>) delegate.getClass();
    }
</code>```

But maybe you can do something similar to this? this.type = T. (This does not compile, but maybe something similar would be possible.)

答:
As you state, the type information is lost at runtime in your given example. But concerning your question in the comments:

can you also show a counter-example, i.e. a collection where two empty instances of different generic types would not be treated as equal?

You can of course implement your own Collection which does take into account the type information in the equals method. Here's a very simple example creating a TypedList wrapper around an arbitrary List:

```<code>static final class TypedList<T> extends AbstractList<T> {
    private final List<T> delegate;
    private final Class<T> type;

    public TypedList(List<T> delegate, Class<T> type) {
        this.delegate = Objects.requireNonNull(delegate);
        this.type = Objects.requireNonNull(type);
    }

    @Override
    public T get(int index) {
        return delegate.get(index);
    }

    @Override
    public int size() {
        return delegate.size();
    }

    @Override
    public boolean equals(Object obj) {
        if (!super.equals(obj)) {
            return false;
        }
        // Lists are equal, now additionally, check the type
        TypedList<?> other = (TypedList<?>) obj;
        return this.type.equals(other.type);
    }

    // hashCode omitted for brevity
}
</code>```

Note, that you'll need to store the type explicitly due to the mentioned type erasure. Usage:

```<code>List<String> list1 = new ArrayList<>();
List<Integer> list2 = new ArrayList<>();
System.out.println(list1.equals(list2)); // true

list1 = new TypedList<>(list1, String.class);
list2 = new TypedList<>(list2, Integer.class);
System.out.println(list1.equals(list2)); // false
</code>```

Body:
Consider the following snippet:

    List<String> list1 = new ArrayList<>();
    List<Integer> list2 = new ArrayList<>();
    assertThat(list1.equals(list2), is(true));

The assertion succeeds.

Indeed, as far as I understand, there is no way in Java, for the equals method to differentiate between the two, due to run-time type-erasure (i.e. the fact the type arguments String and Integer are only accessible at compile-time, but not at run-time).
And since there are no elements, which could be compared, equals has to return true. And by this line of thought, this must be true, for all collections.

So the question is the following: is my thought process correct, or am I missing something?

EDIT

@qqilihq gave an excellent answer, which prompts the next question:
Is this possible to achieve without passing the type explicitly (I'm fine if the type is stored explicitly somehow, just the user does should not have to pass it.)

I attempted the following, but it did not work (I guess due to type erasure):

    public TypedList(List<T> delegate) {
        this.delegate = Objects.requireNonNull(delegate);
        this.type = (Class<T>) delegate.getClass();
    }

But maybe you can do something similar to this? this.type = T. (This does not compile, but maybe something similar would be possible.)

Body:
As you state, the type information is lost at runtime in your given example. But concerning your question in the comments:

can you also show a counter-example, i.e. a collection where two empty instances of different generic types would not be treated as equal?

You can of course implement your own Collection which does take into account the type information in the equals method. Here's a very simple example creating a TypedList wrapper around an arbitrary List:

static final class TypedList<T> extends AbstractList<T> {
    private final List<T> delegate;
    private final Class<T> type;

    public TypedList(List<T> delegate, Class<T> type) {
        this.delegate = Objects.requireNonNull(delegate);
        this.type = Objects.requireNonNull(type);
    }

    @Override
    public T get(int index) {
        return delegate.get(index);
    }

    @Override
    public int size() {
        return delegate.size();
    }

    @Override
    public boolean equals(Object obj) {
        if (!super.equals(obj)) {
            return false;
        }
        // Lists are equal, now additionally, check the type
        TypedList<?> other = (TypedList<?>) obj;
        return this.type.equals(other.type);
    }

    // hashCode omitted for brevity
}

Note, that you'll need to store the type explicitly due to the mentioned type erasure. Usage:

List<String> list1 = new ArrayList<>();
List<Integer> list2 = new ArrayList<>();
System.out.println(list1.equals(list2)); // true

list1 = new TypedList<>(list1, String.class);
list2 = new TypedList<>(list2, Integer.class);
System.out.println(list1.equals(list2)); // false


问:
island count two-dimensional array algorithm
```<code>let arr = [[1, 0, 1],
           [1, 0, 0],
           [1, 1, 1]
     ];
</code>```

i have array where 1-island and 0-water. I need to write a island counter. Here are 2 island 1 big and 1 small(singele). For example here are 5 single islands

```<code>let arr = [[1, 0, 1],
           [0, 1, 0],
           [1, 0, 1]
     ];
</code>```

i had write double cycle to appeal each item in array like this:

```<code>for(let i = 0; i < arr.length; i++){
    for(let x = 0; x < arr[i].length; x++){
         if(...){}
    }
 }
</code>```

and I need to write сondition for this. Help me please.

答:
You could use a counter and check all adjacent items and update the element with the actual counter.

function check(array) {

    function test(array, i, j, value) {
        if (array[i] && array[i][j] === -1) {
            array[i][j] = value;
            test(array, i -1, j, value);
            test(array, i + 1, j, value);
            test(array, i, j - 1, value);
            test(array, i, j + 1, value);
            return true;
        }
    }
    var value = 1;

    array.forEach(a=> a.forEach((b, i, bb) => bb[i] = -b));
    array.forEach((a, i, aa) => a.forEach((b, j) => test(aa, i, j, value) && value++));
    document.getElementById('out').innerHTML += array.map(a => a.join(' ')).join('\n') + '
';
    return value - 1;
}

console.log(check([[1, 0, 1], [1, 0, 0], [1, 1, 1]]));
console.log(check([[1, 0, 1], [0, 1, 0], [1, 0, 1]]));```
<pre class="snippet-code-html lang-html prettyprint-override"><code><pre id="out">``````

Body:
let arr = [[1, 0, 1],
           [1, 0, 0],
           [1, 1, 1]
     ];

i have array where 1-island and 0-water. I need to write a island counter. Here are 2 island 1 big and 1 small(singele). For example here are 5 single islands

let arr = [[1, 0, 1],
           [0, 1, 0],
           [1, 0, 1]
     ];

i had write double cycle to appeal each item in array like this:

for(let i = 0; i < arr.length; i++){
    for(let x = 0; x < arr[i].length; x++){
         if(...){}
    }
 }

and I need to write сondition for this. Help me please.

Body:
You could use a counter and check all adjacent items and update the element with the actual counter.

function check(array) {

    function test(array, i, j, value) {
        if (array[i] && array[i][j] === -1) {
            array[i][j] = value;
            test(array, i -1, j, value);
            test(array, i + 1, j, value);
            test(array, i, j - 1, value);
            test(array, i, j + 1, value);
            return true;
        }
    }
    var value = 1;

    array.forEach(a=> a.forEach((b, i, bb) => bb[i] = -b));
    array.forEach((a, i, aa) => a.forEach((b, j) => test(aa, i, j, value) && value++));
    document.getElementById('out').innerHTML += array.map(a => a.join(' ')).join('\n') + '<hr>';
    return value - 1;
}

console.log(check([[1, 0, 1], [1, 0, 0], [1, 1, 1]]));
console.log(check([[1, 0, 1], [0, 1, 0], [1, 0, 1]]));

<pre id="out"></pre>


问:
Explain this snippet which finds the maximum of two integers without using if-else or any other comparison operator?
Find the maximum of two numbers. You should not use if-else or any other comparison operator. I found this question on online bulletin board, so i thought i should ask in StackOverflow

EXAMPLE
Input: 5, 10
Output: 10

I found this solution, can someone help me understand these lines of code

```<code>int getMax(int a, int b) {
    int c = a - b;
    int k = (c >> 31) & 0x1;
    int max = a - k * c;
    return max;
}
</code>```

答:
Use bitwise hacks

```<code>r = x ^ ((x ^ y) & -(x < y)); // max(x, y)
</code>```

If you know that INT_MIN <= x - y <= INT_MAX, then you can use the following, which is faster because (x - y) only needs to be evaluated once.

```<code>r = x - ((x - y) & ((x - y) >> (sizeof(int) * CHAR_BIT - 1))); // max(x, y)
</code>```

Source : Bit Twiddling Hacks by Sean Eron Anderson

Body:
Find the maximum of two numbers. You should not use if-else or any other comparison operator. I found this question on online bulletin board, so i thought i should ask in StackOverflow

EXAMPLE
Input: 5, 10
Output: 10

I found this solution, can someone help me understand these lines of code

int getMax(int a, int b) {
    int c = a - b;
    int k = (c >> 31) & 0x1;
    int max = a - k * c;
    return max;
}

Body:
Use bitwise hacks

r = x ^ ((x ^ y) & -(x < y)); // max(x, y)

If you know that INT_MIN <= x - y <= INT_MAX, then you can use the following, which is faster because (x - y) only needs to be evaluated once.

r = x - ((x - y) & ((x - y) >> (sizeof(int) * CHAR_BIT - 1))); // max(x, y)

Source : Bit Twiddling Hacks by Sean Eron Anderson


问:
Populating dropdown menu with JSON Data
I'm tyring to use AJAX to populate a dropdown box based on the selection of another dropdown. I followed a tutorial using jQuery located here - http://remysharp.com/2007/01/20/auto-populating-select-boxes-using-jquery-ajax/ and have altered the select box ID names in the select box names in the script.

When there's a change to the value of the main checkbox the ajax is sent and returns as below:

{
  "1": "Kieran Hutchinson",
  "2": "Caleb Tan",
  "3": ""
}
```
<p>THis is slightly different to the JSON string that is returned in the tutorials code which looks like this</p>
<pre class="lang-json prettyprint-override"><code>[{
  optionValue: 10,
  optionDisplay: 'Remy'
}, {
  optionValue: 11,
  optionDisplay: 'Arif'
}, {
  optionValue: 12,
  optionDisplay: 'JC'
}]
</code>```

I'm thinking this is the issue but I have no idea how to get the correct values out of my JSON response.

The javascript is as below:

$(function() {
  $("select#ContactCompanyId").change(function() {
    $.getJSON("contactList", {
      id: $(this).val(),
      ajax: 'true'
    }, function(j) {
      var options = '';
      for (var i = 0; i < j.length; i++) {
        options += '<option value="' + j[i].optionValue + '">' + j[i].optionDisplay + '</option>';
      }
      $("select#QuoteContactId").html(options);
    })
  })
})
```

Thanks in advance

答:
If you could slightly change your response to return value and text keys in JSON:

```<code>[{
  value: 10,
  text: 'Remy'
}, {
  value: 11,
  text: 'Arif'
}, {
  value: 12,
  text: 'JC'
}]
</code>```

you could use JQuery view engine and just load the array into a dropdown:

```<code>$.getJSON("contactList", {
    id: $(this).val(),
    ajax: 'true'
  },
  function(j) {
    $("select#QuoteContactId").view(response);
  })
</code>```

See details here: https://jocapc.github.io/jquery-view-engine/docs/ajax-dropdown

Title: Populating dropdown menu with JSON Data

Body:
I'm tyring to use AJAX to populate a dropdown box based on the selection of another dropdown. I followed a tutorial using jQuery located here - http://remysharp.com/2007/01/20/auto-populating-select-boxes-using-jquery-ajax/ and have altered the select box ID names in the select box names in the script.

When there's a change to the value of the main checkbox the ajax is sent and returns as below:

{
  "1": "Kieran Hutchinson",
  "2": "Caleb Tan",
  "3": ""
}

THis is slightly different to the JSON string that is returned in the tutorials code which looks like this

[{
  optionValue: 10,
  optionDisplay: 'Remy'
}, {
  optionValue: 11,
  optionDisplay: 'Arif'
}, {
  optionValue: 12,
  optionDisplay: 'JC'
}]

I'm thinking this is the issue but I have no idea how to get the correct values out of my JSON response.

The javascript is as below:

$(function() {
  $("select#ContactCompanyId").change(function() {
    $.getJSON("contactList", {
      id: $(this).val(),
      ajax: 'true'
    }, function(j) {
      var options = '';
      for (var i = 0; i < j.length; i++) {
        options += '<option value="' + j[i].optionValue + '">' + j[i].optionDisplay + '</option>';
      }
      $("select#QuoteContactId").html(options);
    })
  })
})

Thanks in advance

Body:
If you could slightly change your response to return value and text keys in JSON:

[{
  value: 10,
  text: 'Remy'
}, {
  value: 11,
  text: 'Arif'
}, {
  value: 12,
  text: 'JC'
}]

you could use JQuery view engine and just load the array into a dropdown:

$.getJSON("contactList", {
    id: $(this).val(),
    ajax: 'true'
  },
  function(j) {
    $("select#QuoteContactId").view(response);
  })

See details here: https://jocapc.github.io/jquery-view-engine/docs/ajax-dropdown


问:
Is there a function which returns all possible combinations of completions for given set of tokens?
Is there a python function which returns all possible combinations of completions for given set of tokens:

```<code>tokens = ["Afoo","fooB","Abar","Bbar","barA","barBX","barBY"]

complete(tokens,"foo","barB")
</code>```

should return:

```<code>[["Afoo","barBX"],["Afoo","barBY"],["fooB","barBX"],["fooB","barBY"]]
</code>```

答:
I thought to this solution

I get all the foo and the barB
then I combine the two lists

```<code>tokens = ["Afoo", "fooB", "Abar", "Bbar", "barA", "barBX", "barBY"]

foo = [a for a in tokens if "foo" in a]

barB = [a for a in tokens if "barB" in a]

x = [(a, b) for a in foo for b in barB]

print(x)
</code>```

output:

```<code>[('Afoo', 'barBX'), ('Afoo', 'barBY'), ('fooB', 'barBX'), ('fooB', 'barBY')]
</code>```

Quicker

```<code>tokens = ["Afoo", "fooB", "Abar", "Bbar", "barA", "barBX", "barBY"]

x = [(a, b) for a in tokens if "foo" in a for b in tokens if "barB" in b]

print(x)
</code>```

output:

```<code>[('Afoo', 'barBX'), ('Afoo', 'barBY'), ('fooB', 'barBX'), ('fooB', 'barBY')]
</code>```

Body:
Is there a python function which returns all possible combinations of completions for given set of tokens:

tokens = ["Afoo","fooB","Abar","Bbar","barA","barBX","barBY"]

complete(tokens,"foo","barB")

should return:

[["Afoo","barBX"],["Afoo","barBY"],["fooB","barBX"],["fooB","barBY"]]

Body:
I thought to this solution

I get all the foo and the barB
then I combine the two lists

tokens = ["Afoo", "fooB", "Abar", "Bbar", "barA", "barBX", "barBY"]

foo = [a for a in tokens if "foo" in a]

barB = [a for a in tokens if "barB" in a]

x = [(a, b) for a in foo for b in barB]

print(x)

output:

[('Afoo', 'barBX'), ('Afoo', 'barBY'), ('fooB', 'barBX'), ('fooB', 'barBY')]

Quicker

tokens = ["Afoo", "fooB", "Abar", "Bbar", "barA", "barBX", "barBY"]

x = [(a, b) for a in tokens if "foo" in a for b in tokens if "barB" in b]

print(x)

output:

[('Afoo', 'barBX'), ('Afoo', 'barBY'), ('fooB', 'barBX'), ('fooB', 'barBY')]


问:
Can i add SVG image in ImageView?
I have an imageView : width=200 ,height=150 ,when i upload a big image (.jpg)  for example image :1200*500 pixels and i minus the width ad height of imageView ,the image lose his quality ,it will be not clear ,can i find a way to  add .svg or vector image in imageView ?

答:
I found an option by using Transcoder API of batik library project from apache and convert the resultant BufferedImage to a JavaFX Image.

Edit:

Transcoder API provide classes to convert SVG document to PNG,JPG,TIFF,we can use this sample of code to create a JPEG image from SVG path,

```<code>import java.io.*;

import org.apache.batik.transcoder.image.JPEGTranscoder;
import org.apache.batik.transcoder.TranscoderInput;
import org.apache.batik.transcoder.TranscoderOutput;

public class SaveAsJPEG {

    public static void main(String[] args) throws Exception {

        // Create a JPEG transcoder
        JPEGTranscoder t = new JPEGTranscoder();

        // Set the transcoding hints.
        t.addTranscodingHint(JPEGTranscoder.KEY_QUALITY,
                   new Float(.8));

        // Create the transcoder input.
        String svgURI = new File("C:\Users\Blue\Downloads\icon8_smile.svg").toURL().toString();
        TranscoderInput input = new TranscoderInput(svgURI);

        // Create the transcoder output.
        OutputStream ostream = new FileOutputStream("icon8_smile.jpg");
        TranscoderOutput output = new TranscoderOutput(ostream);

        // Save the image.
        t.transcode(input, output);

        // Flush and close the stream.
        ostream.flush();
        ostream.close();
        System.exit(0);
    }
}
</code>```

By this way we can transform an SVG vector image to other image based on pixels.
Other option we can add it to our code ,for help us to define the size of output image  :

```<code>t.addTranscodingHint(JPEGTranscoder.KEY_WIDTH, new Float(250));
</code>```

This line of code help us to define the size of image according to size of ImageView and we can make some changes like this :

```<code>t.addTranscodingHint(JPEGTranscoder.KEY_WIDTH, imageView.getFitWidth();
</code>```

Title: Can i add SVG image in ImageView?

Body:
I found an option by using Transcoder API of batik library project from apache and convert the resultant BufferedImage to a JavaFX Image.

Edit:

Transcoder API provide classes to convert SVG document to PNG,JPG,TIFF,we can use this sample of code to create a JPEG image from SVG path,

import java.io.*;

import org.apache.batik.transcoder.image.JPEGTranscoder;
import org.apache.batik.transcoder.TranscoderInput;
import org.apache.batik.transcoder.TranscoderOutput;

public class SaveAsJPEG {

    public static void main(String[] args) throws Exception {

        // Create a JPEG transcoder
        JPEGTranscoder t = new JPEGTranscoder();

        // Set the transcoding hints.
        t.addTranscodingHint(JPEGTranscoder.KEY_QUALITY,
                   new Float(.8));

        // Create the transcoder input.
        String svgURI = new File("C:\Users\Blue\Downloads\icon8_smile.svg").toURL().toString();
        TranscoderInput input = new TranscoderInput(svgURI);

        // Create the transcoder output.
        OutputStream ostream = new FileOutputStream("icon8_smile.jpg");
        TranscoderOutput output = new TranscoderOutput(ostream);

        // Save the image.
        t.transcode(input, output);

        // Flush and close the stream.
        ostream.flush();
        ostream.close();
        System.exit(0);
    }
}

By this way we can transform an SVG vector image to other image based on pixels.
Other option we can add it to our code ,for help us to define the size of output image  :

t.addTranscodingHint(JPEGTranscoder.KEY_WIDTH, new Float(250));

This line of code help us to define the size of image according to size of ImageView and we can make some changes like this :

t.addTranscodingHint(JPEGTranscoder.KEY_WIDTH, imageView.getFitWidth();


问:
importing pyspark in python shell
This is a copy of someone else's question on another forum that was never answered, so I thought I'd re-ask it here, as I have the same issue.  (See http://geekple.com/blogs/feeds/Xgzu7/posts/351703064084736)

I have Spark installed properly on my machine and am able to run python programs with the pyspark modules without error when using ./bin/pyspark as my python interpreter.

However, when I attempt to run the regular Python shell, when I try to import pyspark modules I get this error:

```<code>from pyspark import SparkContext
</code>```

and it says

```<code>"No module named pyspark".
</code>```

How can I fix this?  Is there an environment variable I need to set to point Python to the pyspark headers/libraries/etc.?  If my spark installation is /spark/, which pyspark paths do I need to include?  Or can pyspark programs only be run from the pyspark interpreter?

答:
I had the same problem.

Also make sure you are using right python version and you are installing it with right pip version. in my case: I had both python 2.7 and 3.x.
I have installed pyspark with

pip2.7 install pyspark

and it worked.

Title: importing pyspark in python shell

Body:
This is a copy of someone else's question on another forum that was never answered, so I thought I'd re-ask it here, as I have the same issue.  (See http://geekple.com/blogs/feeds/Xgzu7/posts/351703064084736)

I have Spark installed properly on my machine and am able to run python programs with the pyspark modules without error when using ./bin/pyspark as my python interpreter.

However, when I attempt to run the regular Python shell, when I try to import pyspark modules I get this error:

from pyspark import SparkContext

and it says

"No module named pyspark".

How can I fix this?  Is there an environment variable I need to set to point Python to the pyspark headers/libraries/etc.?  If my spark installation is /spark/, which pyspark paths do I need to include?  Or can pyspark programs only be run from the pyspark interpreter?


问:
ngx bootstrap datepicker remove arrows
I am pretty new on working with Angular and Bootstrap and i have a problem. I use a ngx bootstrap datepicker, but i want to remove the standard arrows on the buttons of the datepicker calendar. Here is my printscreen of the problem

Can somebody help me

Greetz,

Youri

答:
Try (I don't use ngx-bootstrap and I'm not sure)</p>

```<code>.bs-datepicker-head .next {
    display: none;
}
</code>```

Title: ngx bootstrap datepicker remove arrows

Body:
Try (I don't use ngx-bootstrap and I'm not sure)

.bs-datepicker-head .next {
    display: none;
}


问:
How was the first computer program created?

Possible Duplicate:

  How was the first compiler written?

This question has always been bothering me.
To compile a program, you need a compiler, which is also a type of program, so what compiled the compiler?
Somebody told me that the first compilers were written in assembly or machine code.
But thinking about that, that is still not the complete story. After all, how does the machine code go from the hard drive to RAM to the CPU without an operating system and drivers? The drivers had to have been programmed somehow.

I know that the very early computers had switches and allowed you to flip the switch to indicate bits. I am wondering how the leap was made from switches to a way to get the CPU to read machine code without needing a computer program to tell it to do so.

答:
Once upon a time to use a computer you entered machine code in binary. People got tired of doing that, so they made a program (with machine code) that would read assembly. After a while they realized that writing in assembly sucked, so they used assembly to make high level languages such as FORTRAN.

To get the full story, enroll in college and take some CS or COMPE classes.


问:
Why has the .bss segment not increased when variables are added?
Recently,I learned that the .bss segment store uninitialized data. However, when I try a small program as below and use size(1) command in terminal, the .bss segment didn't change, even if I add some global variables. Do I misunderstand something?

```<code>jameschu@aspire-e5-573g:~$ cat test.c
#include <stdio.h>

int main(void)
    {
  printf("hello world\n");
  return 0;
}
jameschu@aspire-e5-573g:~$ gcc -c test.c
jameschu@aspire-e5-573g:~$ size test.o
   text    data     bss     dec     hex filename
     89       0       0      89      59 test.o
jameschu@aspire-e5-573g:~$ cat test.c
#include <stdio.h>
int a1;
int a2;
int a3;

int main(void)
{
  printf("hello world\n");
  return 0;
}
jameschu@aspire-e5-573g:~$ gcc -c test.c
jameschu@aspire-e5-573g:~$ size test.o
   text    data     bss     dec     hex filename
     89       0       0      89      59 test.o
</code>```

答:
This is because the way global variables work.

The problem that is being solved is that it is possible to declare a global variable, without initializing it, in several .c files and not getting a duplicate symbol error. That is, every global uninitialized declaration works like a weak declaration, that can be considered external if no other declaration contains an initialization.

How it this implemented by the compiler? Easy:

when compiling, instead of adding that variable in the bss segment it will be added to the COMMON segment.

when linking, however, it will merge all the COMMON variables with the same name and discard anyone that is already in other section. The remaining ones will be moved to the bss of the executable.

And that is why you don't see your variables in the bss of the object file, but you do in the executable file.

You can check the contents of the object sections using a more modern alternative to size, such as  objdump -x. And note how the variables are placed in *COM*.

It is worth noting that if you declare your global variable as static you are saying that the variable belongs to that compilation unit, so the COMMON is not used and you get the behavior you expect:

```<code>int a;
int b;
static int c;

$ size test.o
text       data     bss     dec     hex filename
 91       0       4      95      5f test.o
</code>```

Initializing to 0 will get a similar result.

```<code>int a;
int b;
int c = 0;

$ size test.o
text      data    bss    dec     hex    filename
 91       0       4      95      5f test.o
</code>```

However initializing to anything other than 0 will move that variable to data:

```<code>int a;
int b = 1;
int c = 0;

$ size test.o
text      data    bss    dec     hex    filename
 91       4       4      99      5f test.o
</code>```

Body:
Recently,I learned that the .bss segment store uninitialized data. However, when I try a small program as below and use size(1) command in terminal, the .bss segment didn't change, even if I add some global variables. Do I misunderstand something?

jameschu@aspire-e5-573g:~$ cat test.c
#include <stdio.h>

int main(void)
    {
  printf("hello world\n");
  return 0;
}
jameschu@aspire-e5-573g:~$ gcc -c test.c
jameschu@aspire-e5-573g:~$ size test.o
   text    data     bss     dec     hex filename
     89       0       0      89      59 test.o
jameschu@aspire-e5-573g:~$ cat test.c
#include <stdio.h>
int a1;
int a2;
int a3;

int main(void)
{
  printf("hello world\n");
  return 0;
}
jameschu@aspire-e5-573g:~$ gcc -c test.c
jameschu@aspire-e5-573g:~$ size test.o
   text    data     bss     dec     hex filename
     89       0       0      89      59 test.o

Body:
This is because the way global variables work.

The problem that is being solved is that it is possible to declare a global variable, without initializing it, in several .c files and not getting a duplicate symbol error. That is, every global uninitialized declaration works like a weak declaration, that can be considered external if no other declaration contains an initialization.

How it this implemented by the compiler? Easy:

when compiling, instead of adding that variable in the bss segment it will be added to the COMMON segment.

when linking, however, it will merge all the COMMON variables with the same name and discard anyone that is already in other section. The remaining ones will be moved to the bss of the executable.

And that is why you don't see your variables in the bss of the object file, but you do in the executable file.

You can check the contents of the object sections using a more modern alternative to size, such as  objdump -x. And note how the variables are placed in *COM*.

It is worth noting that if you declare your global variable as static you are saying that the variable belongs to that compilation unit, so the COMMON is not used and you get the behavior you expect:

int a;
int b;
static int c;

$ size test.o
text       data     bss     dec     hex filename
 91       0       4      95      5f test.o

Initializing to 0 will get a similar result.

int a;
int b;
int c = 0;

$ size test.o
text      data    bss    dec     hex    filename
 91       0       4      95      5f test.o

However initializing to anything other than 0 will move that variable to data:

int a;
int b = 1;
int c = 0;

$ size test.o
text      data    bss    dec     hex    filename
 91       4       4      99      5f test.o


问:
laravel: how to pass a parameters to a function in model?
I'm using laravel 5.5 / php 7.2 /

for example, I have a function like this in a model:

```<code>public function featuredTopSight($count=8)
{
    return $this->hasMany(Sight::class)
        ->wherePublish(1)
        ->latest()
        ->take($count);
}
</code>```

and then, In view:

```<code>$sight->featuredTopSight(8);
</code>```

But I got this error:

```<code>"htmlspecialchars() expects parameter 1 to be string, object given
</code>```

but with $sight->featuredTopSight; I got right answer. but I can not pass the parameter.

答:
In that function you're defining a relationship.

You can't call a relationship with arguments.

First you need to declare the relation, and then the query or method to retrieve results.

Your method should be something similar to:

```<code>public function sights()
{
    return $this->hasMany(Sight::class);
}

public function getFeaturedTopSights($count = 8)
{
    return $this->sights()->wherePublish(1)->latest()->take($count)->get();
}
</code>```

Body:
I'm using laravel 5.5 / php 7.2 /

for example, I have a function like this in a model:

public function featuredTopSight($count=8)
{
    return $this->hasMany(Sight::class)
        ->wherePublish(1)
        ->latest()
        ->take($count);
}

and then, In view:

$sight->featuredTopSight(8);

But I got this error:

"htmlspecialchars() expects parameter 1 to be string, object given

but with $sight->featuredTopSight; I got right answer. but I can not pass the parameter.

Body:
In that function you're defining a relationship.

You can't call a relationship with arguments.

First you need to declare the relation, and then the query or method to retrieve results.

Your method should be something similar to:

public function sights()
{
    return $this->hasMany(Sight::class);
}

public function getFeaturedTopSights($count = 8)
{
    return $this->sights()->wherePublish(1)->latest()->take($count)->get();
}


问:
PostgreSQL SELECT, UPDATE and INSERT together
I'm currently trying to SELECT columns from a table, do some arithmetic with the selected values and then INSERT the updated values back into the same table. So far, I'm thinking of SELECT all columns, copy to another table, UPDATE that table and copy it back but this seems kinda redundant.

```<code>INSERT INTO tableB (x, y) SELECT x, y FROM tableA;

UPDATE tableB SET y = y + 1;

INSERT INTO tableA (x, y) SELECT x, y FROM tableB;
</code>```

where x and y are declared UNIQUE(x, y)

EDIT: Is there a way to avoid creating another table for this transaction?

答:
If I read your logic correctly, then you only need two inserts here, possibly inside a transaction:

```<code>BEGIN;
    INSERT INTO tableB (x, y) SELECT x, y+1 FROM tableA;
    INSERT INTO tableA (x, y) SELECT x, y FROM tableB
COMMIT;
</code>```

The update after the insert is unnecessary as you can simply insert the incremented values of y.

Body:
I'm currently trying to SELECT columns from a table, do some arithmetic with the selected values and then INSERT the updated values back into the same table. So far, I'm thinking of SELECT all columns, copy to another table, UPDATE that table and copy it back but this seems kinda redundant.

INSERT INTO tableB (x, y) SELECT x, y FROM tableA;

UPDATE tableB SET y = y + 1;

INSERT INTO tableA (x, y) SELECT x, y FROM tableB;

where x and y are declared UNIQUE(x, y)

EDIT: Is there a way to avoid creating another table for this transaction?

Body:
If I read your logic correctly, then you only need two inserts here, possibly inside a transaction:

BEGIN;
    INSERT INTO tableB (x, y) SELECT x, y+1 FROM tableA;
    INSERT INTO tableA (x, y) SELECT x, y FROM tableB
COMMIT;

The update after the insert is unnecessary as you can simply insert the incremented values of y.


问:
Monitoring CPU usage of IIS7 worker processes
What is the best way to monitor IIS7 worker processes and store informations about websites which are using CPU/memory too much?

Thanks

答: I recently started looking at accessing WMI with ASP.NET.  Assuming your ASP Service Account has enough permissions you can query and even monitor the various performance metrics using the standard WMI method calls.  You might want to start out by looking at O'Reilly Media's article A Quick Introduction to WMI from .NET and see if that satisfies your needs.</p>

OwnerDisplayName: GrZeCh

OwnerDisplayName: Dscoduc


答:
The short answer: the first programs were meticulously written in raw machine code, and everything was built up from there.

The idea is called bootstrapping.  Suppose that you have a bare machine with a processor, some flash memory, and a hard disk.  Typically, the processor is configured on power-up to load a simple operating system called the bootloader from a fixed location in non-volatile memory (for example, CMOS or flash).  This OS is extraordinarily simple and has just enough functionality to point the computer to the spot on disk where the real OS lives.  This OS can then turn on more and more devices and load more and more complicated programs, until eventually the whole OS is up and running.

But what is this bootloader written in?  Originally, these were written in raw machine code and hardcoded into the machine.  The programs it would run would be written in machine code as well, which would be unbelievably slow and tedious to work with.  Eventually, someone wrote the first simple assembler in machine code.  Once you have this assembler, you can start writing programs in assembly, including the assembler itself.  In fact, once you have a simple assembler, you never need to write machine code again.  You can just keep writing the assembler in assembly!

From this point you can build more complex programming languages by first writing the compiler using existing tools (the assembler, for example) to get just enough functionality available so that the compiler can do basic programming.  You then use that compiler to write a compiler for the programming language itself, and use the same trick to build off of your previous work to get something bigger and cooler.  This technique is still used today - most compilers are written in the language they compile to.

To summarize, everything had to be done by hand at some awful point in the past, but thanks to the hard work of the people who did this we can build off of what's already there.

Title: How was the first computer program created?

Body:
Possible Duplicate:

  How was the first compiler written?

This question has always been bothering me.
To compile a program, you need a compiler, which is also a type of program, so what compiled the compiler?
Somebody told me that the first compilers were written in assembly or machine code.
But thinking about that, that is still not the complete story. After all, how does the machine code go from the hard drive to RAM to the CPU without an operating system and drivers? The drivers had to have been programmed somehow.

I know that the very early computers had switches and allowed you to flip the switch to indicate bits. I am wondering how the leap was made from switches to a way to get the CPU to read machine code without needing a computer program to tell it to do so.


问:
getting error as list index out of range
I have the following program to calculate the percentage of CO2 every year.
I get an error, "list index out of range", once the entire program runs on the following line:

```<code>m= co2level[i+1][1]
</code>```

Code:

```<code># Program to calculate percentage of CO2 every year

co2level = [(2001,320.93),(2003,322.16),(2004,328.07),
             (2006,323.91),(2008,341.47),(2009,348.22)]
i = 0

while i!=len(co2level):

   m= co2level[i+1][1] # I am getting error here as list index out of range
   n= co2level[i][1]
   percentage=((m-n)/n)*100
   print " Change in percentage of CO2 in year %r is"%co2level[i][0],percentage

   i+=1
</code>```

答:
Python is 0 indexed; that means for a list with n elements, the first element of a list is at index 0 and the last element is at index n - 1

Consider the following snippent from your code:

```<code>while i!=len(co2level):
   m= co2level[i+1][1]
</code>```

The line m = co2level[i+1][1] implies that you start iterating from the element at index 1 (2003,322.16) and tries to get the item at index 6 at the end which causes the error. Morover you have an error in how you assigned m and n. To correct this you can do:

```<code>i = 0
while i!=len(co2level):
   m= co2level[i][0] # I am getting error here as list index out of range
   n= co2level[i][1]
   percentage=((m-n)/n)*100
   print" Change in percentage of CO2 in year %r is"%co2level[i][0],percentage
   i+=1
</code>```

The more pythonic way (using for loops) will be

```<code>for i in co2level:
    m = i[0]
    n = i[1]
    percentage=((m-n)/n)*100
    print" Change in percentage of CO2 in year %r is"%co2level[i][0],percentage
</code>```

better still:

```<code>for i in co2level:
    m, n = i
   percentage=((m-n)/n)*100
   print" Change in percentage of CO2 in year %r is"%co2level[i][0],percentage
</code>```

Body:
I have the following program to calculate the percentage of CO2 every year.
I get an error, "list index out of range", once the entire program runs on the following line:

m= co2level[i+1][1]

Code:

# Program to calculate percentage of CO2 every year

co2level = [(2001,320.93),(2003,322.16),(2004,328.07),
             (2006,323.91),(2008,341.47),(2009,348.22)]
i = 0

while i!=len(co2level):

   m= co2level[i+1][1] # I am getting error here as list index out of range
   n= co2level[i][1]
   percentage=((m-n)/n)*100
   print " Change in percentage of CO2 in year %r is"%co2level[i][0],percentage

   i+=1

Body:
Python is 0 indexed; that means for a list with n elements, the first element of a list is at index 0 and the last element is at index n - 1

Consider the following snippent from your code:

while i!=len(co2level):
   m= co2level[i+1][1]

The line m = co2level[i+1][1] implies that you start iterating from the element at index 1 (2003,322.16) and tries to get the item at index 6 at the end which causes the error. Morover you have an error in how you assigned m and n. To correct this you can do:

i = 0
while i!=len(co2level):
   m= co2level[i][0] # I am getting error here as list index out of range
   n= co2level[i][1]
   percentage=((m-n)/n)*100
   print" Change in percentage of CO2 in year %r is"%co2level[i][0],percentage
   i+=1

The more pythonic way (using for loops) will be

for i in co2level:
    m = i[0]
    n = i[1]
    percentage=((m-n)/n)*100
    print" Change in percentage of CO2 in year %r is"%co2level[i][0],percentage

better still:

for i in co2level:
    m, n = i
   percentage=((m-n)/n)*100
   print" Change in percentage of CO2 in year %r is"%co2level[i][0],percentage


问:
Two conditions function is not work in javascript
I've created two conditions function in javascript. The first function is when user fill opsi combobox "Internal" then field pengirim internal disabled = false. And then the second function is when user have filled combobox "Internal" and field pengirim internal still null or not filled. Then user get notification that field pengirim internal must required value. I don't know why, please advice me

// jika dipilih opsi internal maka field pengirim internal enabled. field pengirim eksternal disabled
$("#opsi").change(function() {
  if ($("#opsi").val() === "Internal") {
    document.getElementById('pengirim_internal').disabled = false;
    // disabled field pengirim internal dan clear pengirim eksternal
    document.getElementById('pengirim_eksternal').disabled = true;
    document.getElementById('pengirim_eksternal').value = '';
  }
  elseif
  $("#validation-form").validate({
    rules: {
      pengirim_internal: "required"
    },
    messages: {
      pengirim_internal: "Silahkan Pilih Pengirim Internal!",
    },
    submitHandler: function(form) {
      form.submit();
    }
  });
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><fieldset class="hr">
  <label class="span2">Opsi Surat Masuk</label>
  <select name="opsi" id="opsi">
     <option value="">Pilih Satu</option>
     <option value="Internal">Internal</option>
     <option value="Eksternal">Eksternal</option>
    </select><span class="mandatory">*</span>
</fieldset>
<fieldset class="hr">
  Pengirim Internal :
  <select id="pengirim_internal" name="pengirim_internal">
        <option name="pengirim_internal" value="Islam">Example1</option>
        <option nama="pengirim_internal" value="Kristen">Example2</option>
        </select>
  <span class="mandatory">*</span>
</fieldset></code>```

答:
With the code that you have given, I hope this will works for you,

```<code>//jika dipilih opsi internal maka field pengirim internal enabled. field pengirim eksternal disabled
$("#opsi").on('change',function() {
    if ( $("#opsi").val() === "Internal" ) {
           $('#pengirim_internal').prop('disabled',false);
           // disabled field pengirim internal dan clear pengirim eksternal
           $('#pengirim_eksternal').prop('disabled', 'disabled');
           $('#pengirim_eksternal').val('');
        }
    else
    {
        $("#validation-form").validate({
        rules: {
            pengirim_internal: "required"
        },
        messages: {
            pengirim_internal: "Silahkan Pilih Pengirim Internal!",
        },
        submitHandler: function(form) {
            form.submit();
        }
        });
    }
});
</code>```

Make sure to add jquery and jquery.validate.min.js references to your page.

Body:
I've created two conditions function in javascript. The first function is when user fill opsi combobox "Internal" then field pengirim internal disabled = false. And then the second function is when user have filled combobox "Internal" and field pengirim internal still null or not filled. Then user get notification that field pengirim internal must required value. I don't know why, please advice me

// jika dipilih opsi internal maka field pengirim internal enabled. field pengirim eksternal disabled
$("#opsi").change(function() {
  if ($("#opsi").val() === "Internal") {
    document.getElementById('pengirim_internal').disabled = false;
    // disabled field pengirim internal dan clear pengirim eksternal
    document.getElementById('pengirim_eksternal').disabled = true;
    document.getElementById('pengirim_eksternal').value = '';
  }
  elseif
  $("#validation-form").validate({
    rules: {
      pengirim_internal: "required"
    },
    messages: {
      pengirim_internal: "Silahkan Pilih Pengirim Internal!",
    },
    submitHandler: function(form) {
      form.submit();
    }
  });
});

<fieldset class="hr">
  Opsi Surat Masuk
  <select name="opsi" id="opsi">
     <option value="">Pilih Satu</option>
     <option value="Internal">Internal</option>
     <option value="Eksternal">Eksternal</option>
    </select>*
</fieldset>
<fieldset class="hr">
  Pengirim Internal :
  <select id="pengirim_internal" name="pengirim_internal">
        <option name="pengirim_internal" value="Islam">Example1</option>
        <option nama="pengirim_internal" value="Kristen">Example2</option>
        </select>
  *
</fieldset>

Body:
With the code that you have given, I hope this will works for you,

//jika dipilih opsi internal maka field pengirim internal enabled. field pengirim eksternal disabled
$("#opsi").on('change',function() {
    if ( $("#opsi").val() === "Internal" ) {
           $('#pengirim_internal').prop('disabled',false);
           // disabled field pengirim internal dan clear pengirim eksternal
           $('#pengirim_eksternal').prop('disabled', 'disabled');
           $('#pengirim_eksternal').val('');
        }
    else
    {
        $("#validation-form").validate({
        rules: {
            pengirim_internal: "required"
        },
        messages: {
            pengirim_internal: "Silahkan Pilih Pengirim Internal!",
        },
        submitHandler: function(form) {
            form.submit();
        }
        });
    }
});

Make sure to add jquery and jquery.validate.min.js references to your page.


问:
Stop and deallocate an Azure VM within the guest OS
The VM info:

Basic A1 Serie VM with Ubuntu 16 on it

How to shutdown (or Stop) and de-allocate the VM in Azure without having to go to the azure portal?

Bearing in mind in Azure if you execute shutdown -h 0; it will stop the VM but won't deallocate it.

I'm asking this because I don't have a direct connection to the Azure portal nor do I have logins to it. I want to deallocate the VM using the guest OS only.

答:
I understand what's your scenario. You can SSH to the VM only, but cannot access the Azure. For Example you don't know the credential of Azure account.

For this scenario, you cannot deallocate the Azure VM. Because that action must need been done with Azure Account and it is completed in Azure, not just VM. Deallocate the Azure VM also links to other resources, such as Public IP address, Disk, Network interface and etc.

If you still want to deallocate the Azure VM, I suggest you call your owner of this Azure VM who can access azure portal.

Another hack around this problem is to use Azure CLI to login within the guest VM then control the VM. You will still need to login to Azure, but this is required only once.

Download and install Azure CLI as guided here

Generate a an authentication code using the command:

az login

This will generate an authentication code that can be used to log you in via the Azure owner (only required once). Use that code to authenticate.

After login in you can issue this command to stop and deallocate your VM:

az vm deallocate --resource-group myResourceGroup --name myVM

list of available azure CLI commands can be found here


问:
Crash when referencing a vector of Com_Ptrs through a pointer in a struct, vector size unknown

The following function works when called from a pointer to the class containing it. However, when the class containing this function is initialized inside of a struct, and then called on the instance inside of that struct, from another class, it crashes.

In the latter case, when the thing is 2 layers deep inside a struct, while debugging, the array size is unknown.
in the working case, while debugging the array size is known
no idea why it behaves differently, everything else is the same.

(Declared in the header:)

```<code>vector<Microsoft::WRL::ComPtr <ID3D11ShaderResourceView>> _textureViews;

ID3D11ShaderResourceView** TextureClass::GetTextureArray()
{
    return _textureViews[0].GetAddressOf();
}
</code>```

Here is the full code. Any insight would be much appreciated, thanks.

https://github.com/mister51213/DirectX11Engine/blob/Restructure/DirectX11Engine/GfxUtil.h

答: Oops it was just sloppy coding. I was masking the local pointer inside the material struct initialize function with another in-scope pointer to texture array, so the member variable version wasnt even getting initialized. Nothing to do with structs or ComPointers. Thank you for all your help.</p>

Body:
The following function works when called from a pointer to the class containing it. However, when the class containing this function is initialized inside of a struct, and then called on the instance inside of that struct, from another class, it crashes.

In the latter case, when the thing is 2 layers deep inside a struct, while debugging, the array size is unknown.
in the working case, while debugging the array size is known
no idea why it behaves differently, everything else is the same.

(Declared in the header:)

vector<Microsoft::WRL::ComPtr <ID3D11ShaderResourceView>> _textureViews;

ID3D11ShaderResourceView** TextureClass::GetTextureArray()
{
    return _textureViews[0].GetAddressOf();
}

Here is the full code. Any insight would be much appreciated, thanks.

https://github.com/mister51213/DirectX11Engine/blob/Restructure/DirectX11Engine/GfxUtil.h