问:
Conditional Spinner
I've one problem. I've created spinner, and everything app runs without crashing, but it won't change value of int price, neither setText doesn't work

```<code>public class MainActivity extends AppCompatActivity implements View.OnClickListener {

Button calculateBtn;
EditText userEcts;
TextView ectsPrice;
TextView summary;
Spinner courses;
String cors;
int price = 200;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    userEcts = (EditText) findViewById(R.id.ects_input);
    summary = (TextView) findViewById(R.id.text_summary);
    courses = (Spinner) findViewById(R.id.course_spinner);

    calculateBtn = (Button) findViewById(R.id.calculate);
    calculateBtn.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            //When the button is clicked, call the calculate method.
            calculate();
        }
    });

    final String[] courseArray = new String[4];
    {
        courseArray[0] = "Preddiplomski studij Menadžment";
        courseArray[1] = "Preddiplomski studij Promet";
        courseArray[2] = "Preddiplomski Upravni studij";
        courseArray[3] = "Specijalistički studij Menadžment";
    }

    ArrayAdapter courseAdapter = new ArrayAdapter(this,
            android.R.layout.simple_spinner_item, courseArray);
    courseAdapter.setDropDownViewResource(android.R.layout.select_dialog_singlechoice);
    courses.setAdapter(courseAdapter);

    courses.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener(){

        public void onItemSelected(AdapterView<?> parent,
                                   View view, int pos, long id) {

            //Get item from Spinner and store in string conductorSize........
            cors = parent.getItemAtPosition(pos).toString();
            if (cors.equals(0)) {
                ectsPrice.setText("200");
                price = 200;
            } else if (cors.equals(1)) {
                ectsPrice.setText("250");
                price = 250;
            } else if (cors.equals(2)) {
                ectsPrice.setText("300");
                price = 300;
            } else if (cors.equals(3)) {
                ectsPrice.setText("350");
                price = 350;
            } else {
                //Do nothing
            }
        }

        public void onNothingSelected(AdapterView parent) {
            // Do nothing.
        }
    });
}

public void calculate() {
    //gets entered text from the EditText,and convert to integers.
    if (!TextUtils.isEmpty(userEcts.getText().toString())) {
        Double ects = Double.parseDouble(userEcts.getText().toString());
        //do the calculation
        Double calculatedPrice = ects * price;
        //set the value to the TextView, to display on screen.
        summary.setText("Ukupno za platit: " + Double.toString(calculatedPrice) + "kn");
    } else {
        Toast.makeText(this, "Niste unijeli broj bodova", Toast.LENGTH_SHORT).show();
    }
}

@Override
public void onClick(View v) {
    calculate();
}
</code>```

}

So, on selecting item on position 0, I want to setText to specific text, and change price. Can anyone help?

答:
Use a switch statment : </p>

```<code>public void onItemSelected(AdapterView<?> parent,
                               View view, int pos, long id) {

        switch(pos){
            case 0:
              ectsPrice.setText("200");
              price = 200;
              break;
            case 1:
              ectsPrice.setText("250");
              price = 250;
              break;
            case 2:
              ectsPrice.setText("300");
              price = 300;
              break;
            case 3:
              ectsPrice.setText("350");
              price = 350;
              break;
        }
  }
</code>```

Title: Conditional Spinner

Body:
I've one problem. I've created spinner, and everything app runs without crashing, but it won't change value of int price, neither setText doesn't work

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

Button calculateBtn;
EditText userEcts;
TextView ectsPrice;
TextView summary;
Spinner courses;
String cors;
int price = 200;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    userEcts = (EditText) findViewById(R.id.ects_input);
    summary = (TextView) findViewById(R.id.text_summary);
    courses = (Spinner) findViewById(R.id.course_spinner);

    calculateBtn = (Button) findViewById(R.id.calculate);
    calculateBtn.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            //When the button is clicked, call the calculate method.
            calculate();
        }
    });

    final String[] courseArray = new String[4];
    {
        courseArray[0] = "Preddiplomski studij Menadžment";
        courseArray[1] = "Preddiplomski studij Promet";
        courseArray[2] = "Preddiplomski Upravni studij";
        courseArray[3] = "Specijalistički studij Menadžment";
    }

    ArrayAdapter courseAdapter = new ArrayAdapter(this,
            android.R.layout.simple_spinner_item, courseArray);
    courseAdapter.setDropDownViewResource(android.R.layout.select_dialog_singlechoice);
    courses.setAdapter(courseAdapter);

    courses.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener(){

        public void onItemSelected(AdapterView<?> parent,
                                   View view, int pos, long id) {

            //Get item from Spinner and store in string conductorSize........
            cors = parent.getItemAtPosition(pos).toString();
            if (cors.equals(0)) {
                ectsPrice.setText("200");
                price = 200;
            } else if (cors.equals(1)) {
                ectsPrice.setText("250");
                price = 250;
            } else if (cors.equals(2)) {
                ectsPrice.setText("300");
                price = 300;
            } else if (cors.equals(3)) {
                ectsPrice.setText("350");
                price = 350;
            } else {
                //Do nothing
            }
        }

        public void onNothingSelected(AdapterView parent) {
            // Do nothing.
        }
    });
}

public void calculate() {
    //gets entered text from the EditText,and convert to integers.
    if (!TextUtils.isEmpty(userEcts.getText().toString())) {
        Double ects = Double.parseDouble(userEcts.getText().toString());
        //do the calculation
        Double calculatedPrice = ects * price;
        //set the value to the TextView, to display on screen.
        summary.setText("Ukupno za platit: " + Double.toString(calculatedPrice) + "kn");
    } else {
        Toast.makeText(this, "Niste unijeli broj bodova", Toast.LENGTH_SHORT).show();
    }
}

@Override
public void onClick(View v) {
    calculate();
}

}

So, on selecting item on position 0, I want to setText to specific text, and change price. Can anyone help?

Body:
Use a switch statment :

public void onItemSelected(AdapterView<?> parent,
                               View view, int pos, long id) {

        switch(pos){
            case 0:
              ectsPrice.setText("200");
              price = 200;
              break;
            case 1:
              ectsPrice.setText("250");
              price = 250;
              break;
            case 2:
              ectsPrice.setText("300");
              price = 300;
              break;
            case 3:
              ectsPrice.setText("350");
              price = 350;
              break;
        }
  }


来源: stackexchange

问:
Property Has a Previous Declaration
I tried adding XMPP framework into my ios project and I couldn't get it working. Turns out I added it incorrectly, So I tried removing it and now without XMPP I am getting these errors:
Thanks in Advance!

答: the error is your interface Duplicate interface definition for class. this is work for me duplicate interface declaration for class. somehow you have managed to import the .h file twice. Check to make sure you always use #import and not #include.

ContentLicense: CC BY-SA 3.0

Title: Property Has a Previous Declaration


问:
Replace all td's tags by th in a java String
I want to replace replace all "td" by "th" in this String

```<code>String head = "<tr>\n<td> </td>\n<td> </td>\n<td>Libelle</td>\n"
                      + "<td>Nom Table</td>\n<td>Groupe</td>\n<td> </td>\n</tr>\n"
</code>```

I tried to use :

```<code>head.replace("<td>", "<th>");
head.replace("</td>", "</th>");
</code>```

but it doesn't working.

Can you help me ?

答:
You can have one line as this.</p>

```<code> head = head.replaceAll("td>", "th>");
</code>```

Body:
I want to replace replace all "td" by "th" in this String

String head = "
\n 	\n 	\nLibelle	\n"
                      + "Nom Table	\nGroupe	\n 	\n
\n"

I tried to use :

head.replace("", "");
head.replace("	", "	");

but it doesn't working.

Can you help me ?

Body:
You can have one line as this.

 head = head.replaceAll("td>", "th>");


问:
Excel: Data validation source
I have a list and I want to display certain data based on another cell value. Let's call it "cell A1".

In my logic, every value of "cell A1" means different list items.

The problem is when I added other values to the possible data that "cell A1" could contain, the formula becomes very long and couldn't fit in the source field!

For example, if "cell A1" possible values are Tigre, Dog, Cat, Lion, Horse, Sheep and Turkey, the condition is:

```<code>=IF(D4="Tigre";'Sheet1'!$B$2:$B$1000;IF(D4="Dog";'Sheet2'!$B$2:$B$1000;IF(D4="Cat";'Sheet3'!$B$2:$B$1000;IF(D4="Lion";'Sheet4'!$B$2:$B$1000; IF(D4=" Horse";'Sheet5'!$B$2:$B$1000;IF(D4="Sheep";'Sheet6'!$B$2:$B$1000;IF(D4=" Turkey";'Sheet7'!$B$2:$B$1000;IF(D4="Val8";'Sheet8'!$B$2:$B$1000;""))))))))))
</code>```

Check this image, the source field is already full! (before the end of the condition)

have you an idea how work around this issue or how to optimise the conditional formula?

PS: I'm a french user, so I apologize of my bad english! And, I know that I need to use "SI" instead of "IF" :)

Thanks.

答:
As I see from your example, Val1 Val2 etc. are keys to redirect to specific worksheets. You can write the "mapping" data betweens these "Vals" and sheet names somewhere (possibly in a hidden worksheet or any available/hidden columns) and use it in the validation formula using a combination of INDIRECT and VLOOKUP. Say in this example I use Columns G:H in worksheet "mapping":

```<code>' Worksheet mapping
 G             H
Val 1       Sheet number 1
Value 2       Sheet2
Val3       My worksheet number 3
</code>```

Now your data validation formula can be like this:

```<code>=INDIRECT("'"&VLOOKUP($D$4,mapping!$G$1:$H$3,2,0) &"'!$B2:$B1000")
</code>```

p.s. you can then make the column mapping!G1:G3 your data validation list for the cell $D$4 that holds the keys.

I also notice here that if the ranges are not always the same (unlike in your example where they all are B2:B1000), you can also make the mapping "complete" by including the ranges in the redirection column (column H in my example).

Title: Excel: Data validation source

Body:
I have a list and I want to display certain data based on another cell value. Let's call it "cell A1".

In my logic, every value of "cell A1" means different list items.

The problem is when I added other values to the possible data that "cell A1" could contain, the formula becomes very long and couldn't fit in the source field!

For example, if "cell A1" possible values are Tigre, Dog, Cat, Lion, Horse, Sheep and Turkey, the condition is:

=IF(D4="Tigre";'Sheet1'!$B$2:$B$1000;IF(D4="Dog";'Sheet2'!$B$2:$B$1000;IF(D4="Cat";'Sheet3'!$B$2:$B$1000;IF(D4="Lion";'Sheet4'!$B$2:$B$1000; IF(D4=" Horse";'Sheet5'!$B$2:$B$1000;IF(D4="Sheep";'Sheet6'!$B$2:$B$1000;IF(D4=" Turkey";'Sheet7'!$B$2:$B$1000;IF(D4="Val8";'Sheet8'!$B$2:$B$1000;""))))))))))

Check this image, the source field is already full! (before the end of the condition)

have you an idea how work around this issue or how to optimise the conditional formula?

PS: I'm a french user, so I apologize of my bad english! And, I know that I need to use "SI" instead of "IF" :)

Thanks.

Body:
As I see from your example, Val1 Val2 etc. are keys to redirect to specific worksheets. You can write the "mapping" data betweens these "Vals" and sheet names somewhere (possibly in a hidden worksheet or any available/hidden columns) and use it in the validation formula using a combination of INDIRECT and VLOOKUP. Say in this example I use Columns G:H in worksheet "mapping":

' Worksheet mapping
 G             H
Val 1       Sheet number 1
Value 2       Sheet2
Val3       My worksheet number 3

Now your data validation formula can be like this:

=INDIRECT("'"&VLOOKUP($D$4,mapping!$G$1:$H$3,2,0) &"'!$B2:$B1000")

p.s. you can then make the column mapping!G1:G3 your data validation list for the cell $D$4 that holds the keys.

I also notice here that if the ranges are not always the same (unlike in your example where they all are B2:B1000), you can also make the mapping "complete" by including the ranges in the redirection column (column H in my example).


问:
CSS3 :Iframe not taking 100% height
I have 2 bootstrap columns.

in the first column there is a fixed position div. and in the 2nd column I have an iframe div.
I have given iframe height="100%" but it is not taking 100% of the browser.

.left_side_div{
  width:25%;
  min-height:100%;
  background : #FFFFFF;
  position:fixed;
  top:0;
  left:0;
  bottom:0;
  border:thin black solid;
}

.iframe_div{
  width:100%;
  height:100%;
  border:thin black solid;

}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

<div class="row">
<div class="col-lg-3 col-md-3 col-sm-3 col-xs-3">
  <div class="left_side_div"></div>
</div>
<div class="col-lg-9 col-md-9 col-sm-9 col-xs-9">
  <div class="iframe_div">
    <iframe src="http://google.co.in/" width="100%" height="100%"></iframe>
  </div>
</div>
</div></code>```

Here is JSFiddle

Any help would be great.

Thank You.

答:
use margin 0 for row</p>

```<code>.row{
   margin: 0;
}
</code>```

Title: CSS3 :Iframe not taking 100% height

Body:
I have 2 bootstrap columns.

in the first column there is a fixed position div. and in the 2nd column I have an iframe div.
I have given iframe height="100%" but it is not taking 100% of the browser.

.left_side_div{
  width:25%;
  min-height:100%;
  background : #FFFFFF;
  position:fixed;
  top:0;
  left:0;
  bottom:0;
  border:thin black solid;
}

.iframe_div{
  width:100%;
  height:100%;
  border:thin black solid;

}

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

Here is JSFiddle

Any help would be great.

Thank You.

Body:
use margin 0 for row

.row{
   margin: 0;
}


问:
How to use Character subscript in Swift 3.1?
I'm new to Swift. I found out some weird behavior of subscript matching:

```<code>struct SubscriptTest {
    subscript(character: Character) -> String {
        return "Character: \(character)"
    }

    subscript(string: String) -> String {
        return "String: \(string)"
    }

    subscript(int: Int) -> String {
        return "Int: \(int)"
    }
}

let test = SubscriptTest()
test["abc"] // String: abc
test[13] // Int: 13
test[""] // String:  (surprisingly)
</code>```

I thought the last test would match my Character subscript, not the String one. I tried to swap the order of subscripts declarations, thinking that maybe the last matching one is being used. It didn't change anything, String subscript is still used for single Character.

I know I could just use String subscript and check for characters count, but the root of my question is curiosity.

Why is Character subscript never matched here?

答:
"" can be both a String literal and a Character literal,
and defaults to String (if both are valid in the context). With

```<code>test["" as Character] // Character:
</code>```

or

```<code>let c: Character = ""
test[c] // Character:
</code>```

you get the expected result.

Body:
I'm new to Swift. I found out some weird behavior of subscript matching:

struct SubscriptTest {
    subscript(character: Character) -> String {
        return "Character: \(character)"
    }

    subscript(string: String) -> String {
        return "String: \(string)"
    }

    subscript(int: Int) -> String {
        return "Int: \(int)"
    }
}

let test = SubscriptTest()
test["abc"] // String: abc
test[13] // Int: 13
test[""] // String:  (surprisingly)

I thought the last test would match my Character subscript, not the String one. I tried to swap the order of subscripts declarations, thinking that maybe the last matching one is being used. It didn't change anything, String subscript is still used for single Character.

I know I could just use String subscript and check for characters count, but the root of my question is curiosity.

Why is Character subscript never matched here?

Body:
"" can be both a String literal and a Character literal,
and defaults to String (if both are valid in the context). With

test["" as Character] // Character:

or

let c: Character = ""
test[c] // Character:

you get the expected result.


问:
c# Comparing two List<T> Show Additions, Deletions and Property Changes
I have two Lists of type myObj defined as so:

```<code>public class myObj
{
    public int Id {get;set;}
    public string Name {get;set}
    public Address Address {get;set;}
}
</code>```

This uses another class called Address

```<code>public class Address
{
    public int Id {get;set;}
    public string Line1 {get;set}
    public string ZipCode {get;set;}
}
</code>```

And I have a main sub as below.

```<code>sub Main()
{
    var myTestObj1 = new List<myObj>(
        new myObj(){ Id = 1, Name = "Bob", new Address(){ Id = 1, Line 1= "", ZipCode = "90120"}},
        new myObj(){ Id = 2, Name = "Kaz", new Address(){ Id = 2, Line 1= "", ZipCode = "90121"}}
    );
    var myTestObj2 = new List<myObj>(
        new myObj(){ Id = 2, Name = "Kaz", new Address(){ Id = 2, Line 1= "", ZipCode = "00121"}}
        new myObj(){ Id = 3, Name = "Suz", new Address(){ Id = 3, Line 1= "", ZipCode = "99999"}}
    );
}
</code>```

What I need to do is check the lists for differences. From the above, I am looking for the following.

Looking for the difference between myTestObj1 and myTestObj2

I would expect to see:

```<code>myObj id = 1 = New Record
myObj id = 2 = ZipCode has Changed
myObj id = 3 = Record to be deleted
</code>```

So far I have looked at using reflection, but examples only show one to one comparisons.

C# Compare Two Lists of Different Objects

Difference between two lists

Compare two List objects for equality, ignoring order

If this is a duplicate, can someone point out where to find the solution as I have looked for hours.

Thanks

答:
Well thanks for the advice, but in the end I have chosen a simpler way of doing this.

I have added a new property to the viewmodel that holds an enum value for either add, delete, update, or no change. The view has this field added as a hidden input. Then it is updated as and when by some java script.

Body:
I have two Lists of type myObj defined as so:

public class myObj
{
    public int Id {get;set;}
    public string Name {get;set}
    public Address Address {get;set;}
}

This uses another class called Address

public class Address
{
    public int Id {get;set;}
    public string Line1 {get;set}
    public string ZipCode {get;set;}
}

And I have a main sub as below.

sub Main()
{
    var myTestObj1 = new List<myObj>(
        new myObj(){ Id = 1, Name = "Bob", new Address(){ Id = 1, Line 1= "", ZipCode = "90120"}},
        new myObj(){ Id = 2, Name = "Kaz", new Address(){ Id = 2, Line 1= "", ZipCode = "90121"}}
    );
    var myTestObj2 = new List<myObj>(
        new myObj(){ Id = 2, Name = "Kaz", new Address(){ Id = 2, Line 1= "", ZipCode = "00121"}}
        new myObj(){ Id = 3, Name = "Suz", new Address(){ Id = 3, Line 1= "", ZipCode = "99999"}}
    );
}

What I need to do is check the lists for differences. From the above, I am looking for the following.

Looking for the difference between myTestObj1 and myTestObj2

I would expect to see:

myObj id = 1 = New Record
myObj id = 2 = ZipCode has Changed
myObj id = 3 = Record to be deleted

So far I have looked at using reflection, but examples only show one to one comparisons.

C# Compare Two Lists of Different Objects

Difference between two lists

Compare two List objects for equality, ignoring order

If this is a duplicate, can someone point out where to find the solution as I have looked for hours.

Thanks


问:
XPath 1.0 to find if an element's value is in a list of values
Is there a way to construct an XPath that evaluates whether an element's value is in a predefined list of values? Something akin to this:

```<code>/Location/Addr[State='TX or AL or MA']
</code>```

Which would match nodes whith State elements for Texas, Alabama, or Massachusetts? I know that I can unpack the expression:

```<code>/Location/Addr[State='TX] or  /Location/Addr[State='AL'], etc...
</code>```

But this is a bit cumbersome since the xpaths are quite long, as is the list of values. My google-fu isn't turning up much on the issue...

答:
Just necromancing, since XPath 2.0 has come along.

With XPath 2.0, you can do:

```<code>/Location/Addr[State=('TX', 'AL', 'MA')]
</code>```

Alternatively, with XPath 1.0, you can use contains in combination with string-length:

```<code>DECLARE @tXML xml = '<svg>
<g>
<path></path>
<path data-objid="0000X1">tt</path>
<path data-objid="0000X2"></path>
<path data-objid="0000X3"></path>
</g>
</svg>';

-- SELECT @tXML;

SELECT
    c.p.value('(@data-objid)[1]', 'varchar(50)') AS objID
FROM @tXML.nodes('//node()[contains("0000X1,0000X2", @data-objid) and string-length(@data-objid) != 0]') AS c(p)

SET @tXML.modify('delete //node()[contains("0000X1,0000X2", @data-objid) and string-length(@data-objid) != 0]');

SELECT @tXML AS del;

DECLARE @newRecord xml = '<path data-objid="0000X4"></path>';

-- SET @tXML.modify('insert sql:variable("@newRecord") as first into (/svg/g)[1]')
SET @tXML.modify('insert sql:variable("@newRecord") as last into (/svg/g)[1]')

SELECT @tXML AS ins;
</code>```

See also: add block into specific position

And to update (with xml, you can only update one value at a time, and the text()selector finds nothing for an empty element, so you first need to empty the element, then insert the value, and that for each match):

```<code>SET @tXML.modify('replace value of (//path[contains("0000X1,0000X2", @data-objid) and string-length(@data-objid) != 0]/text())[1] with "40"')
SET @tXML.modify('replace value of (//path[contains("0000X1,0000X2", @data-objid) and string-length(@data-objid) != 0]/text())[2] with "40"')

SET @tXML.modify('replace value of (//path[contains("0000X1,0000X2", @data-objid) and string-length(@data-objid) != 0]/text())[1] with ""')
SET @tXML.modify('insert text{"This Works"} into (//path[contains("0000X1,0000X2", @data-objid) and string-length(@data-objid) != 0])[1]')

SET @tXML.modify('replace value of (//path[contains("0000X1,0000X2", @data-objid) and string-length(@data-objid) != 0]/text())[2] with ""')
SET @tXML.modify('insert text{"This Works"} into (//path[contains("0000X1,0000X2", @data-objid) and string-length(@data-objid) != 0])[2]')
</code>```

And to insert and delete an attribute

```<code>-- insert attribute
-- SET @tXML.modify('insert attribute data-objid1 {"1"} into (//path[contains("0000X1,0000X2", @data-objid) and string-length(@data-objid) != 0])[1]')
-- delete attribute
-- and then, delete suddenly can remove several nodes - unlike insert or modify ...
-- SET @tXML.modify('delete (//path[contains("0000X1,0000X2", @data-objid) and string-length(@data-objid) != 0])/@data-objid[1]')

-- only insert if there is no attribute "data-objid", therefore check with [not(@data-objid)]
-- (on replace, it doesn't create an attribute if it doesn't exist)
SET @tXML.modify('insert attribute data-objid {"1"} into (//path[not(@data-objid) and contains("0000X1,0000X2", @data-objid) and string-length(@data-objid) != 0])[1]')
SET @tXML.modify('replace value of (//path[contains("0000X1,0000X2", @data-objid) and string-length(@data-objid) != 0]/@data-objid)[1] with "Test"')
</code>```

And with variables:

```<code>DECLARE @testvar varchar(30);
SET @testvar = 'abc';
SET @tXML.modify('insert attribute data-objid {sql:variable("@testvar")} into (//path[not(@data-objid)] and contains("0000X1,0000X2", @data-objid) and string-length(@data-objid) != 0)[1]')
SET @tXML.modify('replace value of (//path[contains("0000X1,0000X2", @data-objid) and string-length(@data-objid) != 0]/@data-objid)[1] with sql:variable("@testvar")')
SET @testvar = '0000X1,0000X2';
SET @tXML.modify('delete (//path[contains(sql:variable("@testvar"), @data-objid) and string-length(@data-objid) != 0])/@data-objid[1]')
</code>```

Note that you should concat the attribute data-objid to ("," + objid + ","), so that modify doesn't accidentally find it if the testvar is ',0000X1a,0000X2b,' instead of ',0000X1,0000X2,' (for example)

```<code>DECLARE @testvar varchar(30);
SET @testvar = ',0000X1a,0000X2b,';
SET @tXML.modify('delete (//path[contains(sql:variable("@testvar"), concat(",", @data-objid, ",")) and string-length(@data-objid) != 0])/@data-objid[1]')

SELECT @tXML
</code>```

ContentLicense: CC BY-SA 2.5

Body:
Is there a way to construct an XPath that evaluates whether an element's value is in a predefined list of values? Something akin to this:

/Location/Addr[State='TX or AL or MA']

Which would match nodes whith State elements for Texas, Alabama, or Massachusetts? I know that I can unpack the expression:

/Location/Addr[State='TX] or  /Location/Addr[State='AL'], etc...

But this is a bit cumbersome since the xpaths are quite long, as is the list of values. My google-fu isn't turning up much on the issue...

Body:
Just necromancing, since XPath 2.0 has come along.

With XPath 2.0, you can do:

/Location/Addr[State=('TX', 'AL', 'MA')]

Alternatively, with XPath 1.0, you can use contains in combination with string-length:

DECLARE @tXML xml = '<svg>
<g>
<path></path>
<path data-objid="0000X1">tt</path>
<path data-objid="0000X2"></path>
<path data-objid="0000X3"></path>
</g>
</svg>';

-- SELECT @tXML;

SELECT
    c.p.value('(@data-objid)[1]', 'varchar(50)') AS objID
FROM @tXML.nodes('//node()[contains("0000X1,0000X2", @data-objid) and string-length(@data-objid) != 0]') AS c(p)

SET @tXML.modify('delete //node()[contains("0000X1,0000X2", @data-objid) and string-length(@data-objid) != 0]');

SELECT @tXML AS del;

DECLARE @newRecord xml = '<path data-objid="0000X4"></path>';

-- SET @tXML.modify('insert sql:variable("@newRecord") as first into (/svg/g)[1]')
SET @tXML.modify('insert sql:variable("@newRecord") as last into (/svg/g)[1]')

SELECT @tXML AS ins;

See also: add block into specific position

And to update (with xml, you can only update one value at a time, and the text()selector finds nothing for an empty element, so you first need to empty the element, then insert the value, and that for each match):

SET @tXML.modify('replace value of (//path[contains("0000X1,0000X2", @data-objid) and string-length(@data-objid) != 0]/text())[1] with "40"')
SET @tXML.modify('replace value of (//path[contains("0000X1,0000X2", @data-objid) and string-length(@data-objid) != 0]/text())[2] with "40"')

SET @tXML.modify('replace value of (//path[contains("0000X1,0000X2", @data-objid) and string-length(@data-objid) != 0]/text())[1] with ""')
SET @tXML.modify('insert text{"This Works"} into (//path[contains("0000X1,0000X2", @data-objid) and string-length(@data-objid) != 0])[1]')

SET @tXML.modify('replace value of (//path[contains("0000X1,0000X2", @data-objid) and string-length(@data-objid) != 0]/text())[2] with ""')
SET @tXML.modify('insert text{"This Works"} into (//path[contains("0000X1,0000X2", @data-objid) and string-length(@data-objid) != 0])[2]')

And to insert and delete an attribute

-- insert attribute
-- SET @tXML.modify('insert attribute data-objid1 {"1"} into (//path[contains("0000X1,0000X2", @data-objid) and string-length(@data-objid) != 0])[1]')
-- delete attribute
-- and then, delete suddenly can remove several nodes - unlike insert or modify ...
-- SET @tXML.modify('delete (//path[contains("0000X1,0000X2", @data-objid) and string-length(@data-objid) != 0])/@data-objid[1]')

-- only insert if there is no attribute "data-objid", therefore check with [not(@data-objid)]
-- (on replace, it doesn't create an attribute if it doesn't exist)
SET @tXML.modify('insert attribute data-objid {"1"} into (//path[not(@data-objid) and contains("0000X1,0000X2", @data-objid) and string-length(@data-objid) != 0])[1]')
SET @tXML.modify('replace value of (//path[contains("0000X1,0000X2", @data-objid) and string-length(@data-objid) != 0]/@data-objid)[1] with "Test"')

And with variables:

DECLARE @testvar varchar(30);
SET @testvar = 'abc';
SET @tXML.modify('insert attribute data-objid {sql:variable("@testvar")} into (//path[not(@data-objid)] and contains("0000X1,0000X2", @data-objid) and string-length(@data-objid) != 0)[1]')
SET @tXML.modify('replace value of (//path[contains("0000X1,0000X2", @data-objid) and string-length(@data-objid) != 0]/@data-objid)[1] with sql:variable("@testvar")')
SET @testvar = '0000X1,0000X2';
SET @tXML.modify('delete (//path[contains(sql:variable("@testvar"), @data-objid) and string-length(@data-objid) != 0])/@data-objid[1]')

Note that you should concat the attribute data-objid to ("," + objid + ","), so that modify doesn't accidentally find it if the testvar is ',0000X1a,0000X2b,' instead of ',0000X1,0000X2,' (for example)

DECLARE @testvar varchar(30);
SET @testvar = ',0000X1a,0000X2b,';
SET @tXML.modify('delete (//path[contains(sql:variable("@testvar"), concat(",", @data-objid, ",")) and string-length(@data-objid) != 0])/@data-objid[1]')

SELECT @tXML

ContentLicense: CC BY-SA 4.0


问:
Python Calling windows api VkKeyScan returns random value
I wrote a tiny dll in C++ ,which called the windows api VkKeyScan.
But every time I call it ,it returns a random value to me .

```<code>#include "Windows.h"
extern "C" __declspec(dllexport) auto func()//return random values, unless change auto to int
{
    return VkKeyScan('a');
};
</code>```

If I simply change the return type of the function from auto to int ,it always returns the right value (which is 65).

Or if I use VkKeyScanA('a') instead of VkKeyScan('a'), it also returns the right value all the time .(both VkKeyScanA and VkKeyScan return short integers)

I wonder what causes this bug ?

Calling VkKeyScanW using ctypes returns random values too.

```<code>from ctypes import *

print(windll.user32.VkKeyScanW(c_wchar('a')))//return random values
</code>```

答:
VkKeyScan actually returns a SHORT (16-bit int type) and the remaining upper bits in the return register are undefined.

I'm guessing that auto keeps the type as a short and the code that calls func is the problem, it treats it as a 32-bit value even though there is only 16-bits of defined data there. Forcing the return type to int will sign extend from 16 to 32 bits.

ctypes probably has the same issue and is either not declared as returning a c_int16 or not properly sign-extending when used as a parameter for print.

Body:
I wrote a tiny dll in C++ ,which called the windows api VkKeyScan.
But every time I call it ,it returns a random value to me .

#include "Windows.h"
extern "C" __declspec(dllexport) auto func()//return random values, unless change auto to int
{
    return VkKeyScan('a');
};

If I simply change the return type of the function from auto to int ,it always returns the right value (which is 65).

Or if I use VkKeyScanA('a') instead of VkKeyScan('a'), it also returns the right value all the time .(both VkKeyScanA and VkKeyScan return short integers)

I wonder what causes this bug ?

Calling VkKeyScanW using ctypes returns random values too.

from ctypes import *

print(windll.user32.VkKeyScanW(c_wchar('a')))//return random values


问:
regex extract list of strings from file
I have an input file (input.txt) which contains some data that follows a standard format similar to the following lines:

```<code><descriptor/nnn> <http://www.nnn.org/2004/02/skos/core#prefLabel> "Politische Inklusion"@de .
<descriptor/nnn> <http://www.nnn.org/2004/02/skos/core#prefLabel> "Political inclusion"@en .
<descriptor/nnn> <http://www.nnn.org/2004/02/skos/core#prefLabel> "Radiologische Kampfmittel"@de .
</code>```

I want to extract a list of English strings which lies between the " "@en in outputfile-en.txt, and German strings which lies between the " "@de in outputfile-de.txt

In this example outputfile-en.txt should contain:

```<code>Political inclusion
</code>```

and outputfile-de.txt should contain:

```<code>Politische Inklusion
Radiologische Kampfmittel
</code>```

Which regex is suitable here?

答:
With such a simple pattern there's no need for regex at all, especially not to re-iterate over the same data to pick up different languages - you can stream parse and write your results on the fly:

```<code>with open("input.txt", "r") as f:  # open the input file
    file_handles = {}  # a map of our individual output file handles
    for line in f:  # read it line by line
        rindex = line.rfind("@")  # find the last `@` character
        language = line[rindex+1:rindex+3]  # grab the following two characters as language
        if rindex != -1:  # char found, consider the line...
            lindex = line.rfind("\"", 0, rindex-1)  # find the preceding quotation
            if lindex != -1:  # found, we have a match
                if language not in file_handles:  # add a file handle for this language:
                    file_handles[language] = open("outputfile-{}.txt".format(language), "w")
                # write the found slice between `lindex` and `rindex` + a new line
                file_handles[language].write(line[lindex+1:rindex-1] + "\n")
    for handle in file_handles.values():  # lets close our output file handles
        handle.close()
</code>```

Should be significantly faster than regex + as a bonus is that it will work with any language so if you have ...@it lines it will save outputfile-it.txt as well.

Title: regex extract list of strings from file

Body:
I have an input file (input.txt) which contains some data that follows a standard format similar to the following lines:

<descriptor/nnn> <http://www.nnn.org/2004/02/skos/core#prefLabel> "Politische Inklusion"@de .
<descriptor/nnn> <http://www.nnn.org/2004/02/skos/core#prefLabel> "Political inclusion"@en .
<descriptor/nnn> <http://www.nnn.org/2004/02/skos/core#prefLabel> "Radiologische Kampfmittel"@de .

I want to extract a list of English strings which lies between the " "@en in outputfile-en.txt, and German strings which lies between the " "@de in outputfile-de.txt

In this example outputfile-en.txt should contain:

Political inclusion

and outputfile-de.txt should contain:

Politische Inklusion
Radiologische Kampfmittel

Which regex is suitable here?

Body:
With such a simple pattern there's no need for regex at all, especially not to re-iterate over the same data to pick up different languages - you can stream parse and write your results on the fly:

with open("input.txt", "r") as f:  # open the input file
    file_handles = {}  # a map of our individual output file handles
    for line in f:  # read it line by line
        rindex = line.rfind("@")  # find the last `@` character
        language = line[rindex+1:rindex+3]  # grab the following two characters as language
        if rindex != -1:  # char found, consider the line...
            lindex = line.rfind("\"", 0, rindex-1)  # find the preceding quotation
            if lindex != -1:  # found, we have a match
                if language not in file_handles:  # add a file handle for this language:
                    file_handles[language] = open("outputfile-{}.txt".format(language), "w")
                # write the found slice between `lindex` and `rindex` + a new line
                file_handles[language].write(line[lindex+1:rindex-1] + "\n")
    for handle in file_handles.values():  # lets close our output file handles
        handle.close()

Should be significantly faster than regex + as a bonus is that it will work with any language so if you have ...@it lines it will save outputfile-it.txt as well.


问:
How to add a project to bitbucket correctly?
I've been trying for the last day to add a local project to a repository in bitbucket.

Created an ssh key, added it to the repository.
The repository is mine. I created. Yet i can't push the project. I tried tthe guide in bitbucket. the last command git push -u origin master bring up an error

I tried git push --all. It brings up a window asking for git credentials then a smaller window openssh asks for the password of the repo. I created the repo so i can share my work with my academic and professional supervisors

thanks

Edit : i tried this question question link but it didn't solve my problem

答:
First download git:
https://git-scm.com/downloads

when you are installing it, make sure you install the gitGUI with it.
After that open the Git GUI and follow the instruction below:

Click the Generate Key button:

copy the key to the clipboard and add it to bitbucket as follows:
Go to your account settings. And add the key there.

Now go to your project folder(local). Open that directory with gitGUI.

Then add the bitbucket SSH link to it.

After that, the GUI is pretty much intuitive. I think you have the knowledge to continue.


问:
cascading combobox is not updating itemsource of dependent combobox
I have two comboboxes

```<code><ComboBox x:Name="cmbInstanceList" Margin="15,0,5,0" Grid.Row="1" Grid.Column="1" ItemsSource="{Binding InstanceList}" SelectionChanged="cmbInstanceList_SelectionChanged"

                              Height="25"
                              Style="{StaticResource InputControlErrorsCombo}" Validation.ErrorTemplate="{StaticResource validationTemplate}"  />
<ComboBox x:Name="cmbDatabaseList" Margin="15,0,5,0" Grid.Row="2" Grid.Column="1" ItemsSource="{Binding DatabaseList}"

                              Height="25" Style="{StaticResource InputControlErrorsCombo}" Validation.ErrorTemplate="{StaticResource validationTemplate}" />
</code>```

Here, based on cmbInstanceList, I fill cmbDatabaseList through Itemsource property. InstanceList and DatabaseList are model properties of type List.

In code back-end I am using selectionchanged event to fill the second combobox.

```<code>private void cmbInstanceList_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (cmbInstanceList.SelectedValue != null)
            {
                this.data.InstanceName = cmbInstanceList.SelectedValue.ToString();
                this.data.DatabaseList.Clear(); // this is not working
                FillData(this.data.InstanceName);
            }
        }
</code>```

where this.data represents the model class which contains all the properties.

FillData method contains a call to service and if data is not available the return data values will be just an empty list.

```<code>response = service.RequestDatabasesByInstance(request);
                if (response != null)
                {
                    if (response.DatabaseList != null && response.DatabaseList.Any())
                        this.data.DatabaseList = response.DatabaseList.ToList<string>();
                    else
                    {
                        this.data.DatabaseList.Clear();
                        throw new Exception("No data available");
                    }
                }
</code>```

Problem: when I select the value from cmbInstance and service returns the response with the list with values, all good and working fine.
When I select the value, where service is not able to retrieve the data and returns the empty list there is a problem. even though, I set the model property to clear the items, on UI I can still see combobox contains the values and items are not getting cleared.

答:
I have forgotten the basic concepts of MVVM

You don't seem to know what the MVVM pattern is all about...

Handling the SelectionChanged event in the view to implement cascading ComboBoxes is not MVVM.

Instead you should populate the source collection of the second ComboBox when the source property that is bound to the SelectedItem property of the first ComboBox is set. There is a full example and more information available in the following blog post: https://blog.magnusmontin.net/2013/06/17/cascading-comboboxes-in-wpf-using-mvvm/.

There should be zero code in the code-behind related to the cascading ComboBoxes if you follow the MVVM pattern. The solution you have presented here doesn't follow the MVVM design pattern.

Body:
I have two comboboxes

<ComboBox x:Name="cmbInstanceList" Margin="15,0,5,0" Grid.Row="1" Grid.Column="1" ItemsSource="{Binding InstanceList}" SelectionChanged="cmbInstanceList_SelectionChanged"

                              Height="25"
                              Style="{StaticResource InputControlErrorsCombo}" Validation.ErrorTemplate="{StaticResource validationTemplate}"  />
<ComboBox x:Name="cmbDatabaseList" Margin="15,0,5,0" Grid.Row="2" Grid.Column="1" ItemsSource="{Binding DatabaseList}"

                              Height="25" Style="{StaticResource InputControlErrorsCombo}" Validation.ErrorTemplate="{StaticResource validationTemplate}" />

Here, based on cmbInstanceList, I fill cmbDatabaseList through Itemsource property. InstanceList and DatabaseList are model properties of type List.

In code back-end I am using selectionchanged event to fill the second combobox.

private void cmbInstanceList_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (cmbInstanceList.SelectedValue != null)
            {
                this.data.InstanceName = cmbInstanceList.SelectedValue.ToString();
                this.data.DatabaseList.Clear(); // this is not working
                FillData(this.data.InstanceName);
            }
        }

where this.data represents the model class which contains all the properties.

FillData method contains a call to service and if data is not available the return data values will be just an empty list.

response = service.RequestDatabasesByInstance(request);
                if (response != null)
                {
                    if (response.DatabaseList != null && response.DatabaseList.Any())
                        this.data.DatabaseList = response.DatabaseList.ToList<string>();
                    else
                    {
                        this.data.DatabaseList.Clear();
                        throw new Exception("No data available");
                    }
                }

Problem: when I select the value from cmbInstance and service returns the response with the list with values, all good and working fine.
When I select the value, where service is not able to retrieve the data and returns the empty list there is a problem. even though, I set the model property to clear the items, on UI I can still see combobox contains the values and items are not getting cleared.


问:
Error:Conflict with dependency 'com.google.code.findbugs:jsr305'
I created a new project in Android Studio 2.2 Preview 1 with Android App and Backend module with Google Messaging. This is the app file:

```<code>apply plugin: 'com.android.application'

android {
    compileSdkVersion 23
    buildToolsVersion "23.0.3"
    defaultConfig {
        applicationId "com.xxx.xxx"
        minSdkVersion 15
        targetSdkVersion 23
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    compile 'com.android.support:appcompat-v7:23.4.0'
    compile 'com.android.support.constraint:constraint-layout:1.0.0-alpha1'
    compile 'com.google.android.gms:play-services-gcm:9.0.0'
    testCompile 'junit:junit:4.12'
    androidTestCompile 'com.android.support.test.espresso:espresso-core:2.2.2'
    androidTestCompile 'com.android.support.test:runner:0.5'
    androidTestCompile 'com.android.support:support-annotations:23.4.0'
    compile project(path: ':backend', configuration: 'android-endpoints')
}
</code>```

But it's giving:

Error:Conflict with dependency 'com.google.code.findbugs:jsr305'. Resolved versions for app (1.3.9) and test app (2.0.1) differ. See http://g.co/androidstudio/app-test-app-conflict for details.

I am new to Android and not able to find what is this error. How do I fix it?

答:
The reason why this happen is that diff dependency use same lib of diff version.

So, there are 3 steps or (1 step) to solve this problem.

1st

Add

```<code>configurations.all {
    resolutionStrategy.force 'com.google.code.findbugs:jsr305:2.0.1'
}
</code>```

to your build.gradle file in android {...}

2nd

Open terminal in android studio

run ./gradlew -q app:dependencies command.

3rd

Click Clean Project from menu bar of android studio in Build list.

It will rebuild the project, and then
remove code in 1st step.

Maybe you need just exec 2nd step.  I can't rollback when error occurs.
Have a try.

Body:
I created a new project in Android Studio 2.2 Preview 1 with Android App and Backend module with Google Messaging. This is the app file:

apply plugin: 'com.android.application'

android {
    compileSdkVersion 23
    buildToolsVersion "23.0.3"
    defaultConfig {
        applicationId "com.xxx.xxx"
        minSdkVersion 15
        targetSdkVersion 23
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    compile 'com.android.support:appcompat-v7:23.4.0'
    compile 'com.android.support.constraint:constraint-layout:1.0.0-alpha1'
    compile 'com.google.android.gms:play-services-gcm:9.0.0'
    testCompile 'junit:junit:4.12'
    androidTestCompile 'com.android.support.test.espresso:espresso-core:2.2.2'
    androidTestCompile 'com.android.support.test:runner:0.5'
    androidTestCompile 'com.android.support:support-annotations:23.4.0'
    compile project(path: ':backend', configuration: 'android-endpoints')
}

But it's giving:

Error:Conflict with dependency 'com.google.code.findbugs:jsr305'. Resolved versions for app (1.3.9) and test app (2.0.1) differ. See http://g.co/androidstudio/app-test-app-conflict for details.

I am new to Android and not able to find what is this error. How do I fix it?

Body:
The reason why this happen is that diff dependency use same lib of diff version.

So, there are 3 steps or (1 step) to solve this problem.

1st

Add

configurations.all {
    resolutionStrategy.force 'com.google.code.findbugs:jsr305:2.0.1'
}

to your build.gradle file in android {...}

2nd

Open terminal in android studio

run ./gradlew -q app:dependencies command.

3rd

Click Clean Project from menu bar of android studio in Build list.

It will rebuild the project, and then
remove code in 1st step.

Maybe you need just exec 2nd step.  I can't rollback when error occurs.
Have a try.


问:
VALIDATE statement is causing a value not to be stored in the database
I have been dealing with an issue recently and am stuck. A particular program(a compiled .p) has codes written where its trying to save values to a particular field in the db.

Below this there is a VAILDATE statement on that table. This is causing the value to revert while doing an update operation. I messaged before and after VALIDATE and can see the value updated before VALIDATE and reverted just after VALIDATE. Please can someone help me on this. Many thanks in advance.

答:
Thanks for all your helps. I am thankful to be part of such a great community.

I have now found what was causing this. The document "https://documentation.progress.com/output/ua/OpenEdge_latest/index.html#page/dvref/validate-statement.html"  has the answer in the last point. I was unaware of this behaviour of VALIDATE Statement.

Thanks a lot all again.


问:
Case Insensitive filtering with lambdaj
I'm attempting to familiarize myself with lambdaj, and am unsure how the best way to solve this problem.  Given the following test:

```<code>@Test
public void test() {
  final List<String> l1 = new ArrayList<>();
  final List<String> l2 = new ArrayList<>();

  l1.add("same");
  l1.add("Upper");
  l1.add("lower");

  l2.add("same");
  l2.add("upper");
  l2.add("lower");
  l2.add("extra");

  final List<String> l3 = Lambda.filter(Matchers.not(Matchers.isIn(l1)), l2);
  Assert.assertThat("There should be one item in l3", l3.size(), Matchers.equalTo(1));
}
</code>```

How can I make the Matcher not care about case? i.e. I want a list of the items in l2 which are not in l1 irrespective of case?  I'd prefer to not have to run another Lambda to convert each list of strings to the same case, but instead a way to modify the Matcher to do as I wish.  Is this possible or do I have to convert the items to the same case first?

答:
Hope this answer could help you:</p>

```<code>    List<String> convert = convert(list1, new Converter<String, String>() {
        @Override
        public String convert(String from) {
            return from.toLowerCase();
        }
    });
    List<String> filter2 = filter(isIn(list2), convert);

    System.out.println("filter2 -> " + filter2);
    // filter2 -> [same, upper, lower]
</code>```

Title: Case Insensitive filtering with lambdaj

Body:
I'm attempting to familiarize myself with lambdaj, and am unsure how the best way to solve this problem.  Given the following test:

@Test
public void test() {
  final List<String> l1 = new ArrayList<>();
  final List<String> l2 = new ArrayList<>();

  l1.add("same");
  l1.add("Upper");
  l1.add("lower");

  l2.add("same");
  l2.add("upper");
  l2.add("lower");
  l2.add("extra");

  final List<String> l3 = Lambda.filter(Matchers.not(Matchers.isIn(l1)), l2);
  Assert.assertThat("There should be one item in l3", l3.size(), Matchers.equalTo(1));
}

How can I make the Matcher not care about case? i.e. I want a list of the items in l2 which are not in l1 irrespective of case?  I'd prefer to not have to run another Lambda to convert each list of strings to the same case, but instead a way to modify the Matcher to do as I wish.  Is this possible or do I have to convert the items to the same case first?

Body:
Hope this answer could help you:

    List<String> convert = convert(list1, new Converter<String, String>() {
        @Override
        public String convert(String from) {
            return from.toLowerCase();
        }
    });
    List<String> filter2 = filter(isIn(list2), convert);

    System.out.println("filter2 -> " + filter2);
    // filter2 -> [same, upper, lower]


问:
What method is the best to copy files from one server to another using PHP
I need to copy a couple of files over from one server to another using PHP. Now I currently use PHP FTP functionality which is ok but causes issues. Are there better ways to accomplish this?</p>

答:
Your best bet is usually rsync, especially if you need to copy a directory structure. It's not strictly a PHP method, but you can call using shell_exec() or backtick syntax:

```<code>`rsync -acz /files/to/copy/ user@remotehost:/target/dir/`
</code>```

You'll need to use public key authentication, but there are plenty of tutorials around on that. If you know the location of a public key file that will get you into the remote server, you can use the -e switch:

```<code>`rsync -acze 'ssh -i /path/to/your.key' /files...`
</code>```

Check out the rsync website for more info.

PHP's backtick syntax works with variable interpolation, so you can use variables like $source, $target etc in your syntax.

Body:
Your best bet is usually rsync, especially if you need to copy a directory structure. It's not strictly a PHP method, but you can call using shell_exec() or backtick syntax:

`rsync -acz /files/to/copy/ user@remotehost:/target/dir/`

You'll need to use public key authentication, but there are plenty of tutorials around on that. If you know the location of a public key file that will get you into the remote server, you can use the -e switch:

`rsync -acze 'ssh -i /path/to/your.key' /files...`

Check out the rsync website for more info.

PHP's backtick syntax works with variable interpolation, so you can use variables like $source, $target etc in your syntax.


问:
CakePHP: Queries in Controller or Models?
If I really go through the MVC approach, then the queries should be in the Model, in CakePHP case the Table Classes, but when I go through the tutorials and documentation that Cake Provides they simply state that queries should be in the Controller.

As you can see in the example over here on Cake's websites: https://book.cakephp.org/3.0/en/tutorials-and-examples/blog/part-two.html

But if I go through this link or many other I have come across, the query part should be in the Models: https://www.toptal.com/cakephp/most-common-cakephp-mistakes#common-mistake-3-keeping-business-logic-in-controllers-instead-of-models

It is not just about what Cake displays in the examples or some developers opinion, but what should really be the genuine way to code in Cake when dealing with database queries. I have found almost 90% people doing query related tasks in Controllers only for Cake, as they quote "Cake mentions the same in their examples". But what about the MVC way, we create Table Classes just to mention the associations then? If Cake's own website does that, then somehow it means they have done it intentionally.

答:
It's a good programming practice that to use your database queries in your Model because you can reuse these queries(In another controller) later by calling the method using the object of the model. However, you can also write your queries in your Controller.

For example:-

```<code>//Consider this code block is in Products Model
function totalActiveProduct(){
   $totalProduct=$this->find('all', ['conditions'=>['is_active'=>'Y']]);
return $totalProduct;
}
</code>```

If you want to get the total active product in any controller you can  do this,

```<code>$this->Categories->Products->totalActiveProduct();  //Total procuct in category controller
$this->Products->totalActiveProduct();   //Total products in Product controller.
</code>```

Actually, when you are writing the query in you controller, you have to use the object of your model(That means indirectly you are using your controller). You are thinking that you are writing this in your controller but actually, you are writing it in the model(Object of Model).

```<code>$this->Products->find('all');
</code>```

Simply this means you are writing this in your model object(Where Products is the model object). Directly or indirectly you are doing your each and every database operation through the Model.

Body:
It's a good programming practice that to use your database queries in your Model because you can reuse these queries(In another controller) later by calling the method using the object of the model. However, you can also write your queries in your Controller.

For example:-

//Consider this code block is in Products Model
function totalActiveProduct(){
   $totalProduct=$this->find('all', ['conditions'=>['is_active'=>'Y']]);
return $totalProduct;
}

If you want to get the total active product in any controller you can  do this,

$this->Categories->Products->totalActiveProduct();  //Total procuct in category controller
$this->Products->totalActiveProduct();   //Total products in Product controller.

Actually, when you are writing the query in you controller, you have to use the object of your model(That means indirectly you are using your controller). You are thinking that you are writing this in your controller but actually, you are writing it in the model(Object of Model).

$this->Products->find('all');

Simply this means you are writing this in your model object(Where Products is the model object). Directly or indirectly you are doing your each and every database operation through the Model.


答:
I think you may be after something called dependent data validation.

Look here for a step by step tutorial http://www.contextures.com/xlDataVal02.html

Title: Excel: Data validation source

Body:
I have a list and I want to display certain data based on another cell value. Let's call it "cell A1".

In my logic, every value of "cell A1" means different list items.

The problem is when I added other values to the possible data that "cell A1" could contain, the formula becomes very long and couldn't fit in the source field!

For example, if "cell A1" possible values are Tigre, Dog, Cat, Lion, Horse, Sheep and Turkey, the condition is:

=IF(D4="Tigre";'Sheet1'!$B$2:$B$1000;IF(D4="Dog";'Sheet2'!$B$2:$B$1000;IF(D4="Cat";'Sheet3'!$B$2:$B$1000;IF(D4="Lion";'Sheet4'!$B$2:$B$1000; IF(D4=" Horse";'Sheet5'!$B$2:$B$1000;IF(D4="Sheep";'Sheet6'!$B$2:$B$1000;IF(D4=" Turkey";'Sheet7'!$B$2:$B$1000;IF(D4="Val8";'Sheet8'!$B$2:$B$1000;""))))))))))

Check this image, the source field is already full! (before the end of the condition)

have you an idea how work around this issue or how to optimise the conditional formula?

PS: I'm a french user, so I apologize of my bad english! And, I know that I need to use "SI" instead of "IF" :)

Thanks.


问:
No such a module 'Firebase' in Tests.swift file after Converting to swift 3
After I converted the project to swift 3 I'm getting this error in Test.swift file:

```<code>No such module 'Firebase'
Command/usr/bin/ditto failed with code 1
</code>```

is that mean I have to update the firebase framework? Why that happened?

*The application still runs though!

*Here's the pod file:

```<code># Uncomment this line to define a global platform for your project
# platform :ios, '9.0'

use_frameworks!

target 'TheTestingApp' do
pod 'Firebase'
pod 'Firebase/Auth'
pod 'Firebase/Database'
pod 'Firebase/Storage'
end
</code>```

答: you check your podfile its already in declare at that time your project has been clean (ctrl+shift+k) Otherwise podfile data erase and again podfile install its should better work..</p>

Body:
After I converted the project to swift 3 I'm getting this error in Test.swift file:

No such module 'Firebase'
Command/usr/bin/ditto failed with code 1

is that mean I have to update the firebase framework? Why that happened?

*The application still runs though!

*Here's the pod file:

# Uncomment this line to define a global platform for your project
# platform :ios, '9.0'

use_frameworks!

target 'TheTestingApp' do
pod 'Firebase'
pod 'Firebase/Auth'
pod 'Firebase/Database'
pod 'Firebase/Storage'
end


问:
How to pass Json collection object to mvc controller action method
I am creating one Json array object and trying to pass it in MVC controller action method but i am getting null paramerter; as per my knowledge json only maps .net primitive datatypes.... so it assign null value.

Note: when i have look at request object i found that there are three parameter of created array. But how to get that value as parameter of function?

答:
You need to create a custom model binder which will take the json value and construct a model object which can be passed into your action.

Another option is to use a different value binder. See Phil Haack's site for an example.


问:
How to set label height for auto adjust in Read More/Less with Swift 3?
I would like to create the paragraph with Read More/Read Less at the end.
 Here are my codes;

```<code>func getLabelHeight(text: String, width: CGFloat, font: UIFont) -> CGFloat {

    let lbl = UILabel(frame: .zero)
    lbl.frame.size.width = width
    lbl.font = font
    lbl.numberOfLines = 0
    lbl.text = text
    lbl.sizeToFit()
    lbl.adjustsFontSizeToFitWidth = true
    return lbl.frame.size.height

}
</code>```

```<code> @IBAction func btnReadMore(_ sender: Any) {
    if isLabelAtMaxHeight {

        btnReadmore.setTitle(NSLocalizedString("Read more", comment: ""), for: .normal)
        btnReadmore.titleLabel!.font = UIFont (name: "Tharlon", size: 13)
        isLabelAtMaxHeight = false
        lblReviewHeight.constant = 29
        lblReview.font = UIFont (name: "Tharlon", size: 13)

    }
    else {

        btnReadmore.setTitle(NSLocalizedString("Read less", comment: ""), for: .normal)
        btnReadmore.titleLabel!.font = UIFont (name: "Tharlon", size: 13)
        isLabelAtMaxHeight = true
        lblReviewHeight.constant = getLabelHeight(text: lblReview.text!, width: view.bounds.width, font: lblReview.font)
        lblReview.font = UIFont (name: "Tharlon", size: 13)
        lblReview.lineBreakMode = NSLineBreakMode.byTruncatingHead

    }

}
</code>```

I also set the label "Word wrap" in Attributes Inspector.

The problem is that when I add "NSLineBreakMode.byTruncatingHead" in Read Less part, all the texts show completely. But, some words in those places inside text disappear.

So, I remove that code and run the app. At that time, texts are not shown completely and only show half. I've been trying to solve this problem the whole day.

I don't want to use any other library.

Could anyone help me please?

答:
to calculate text height by font and width you can use this extension

```<code>extension UIFont {
func sizeOfString (_ string: String, constrainedToWidth width: CGFloat) -> CGSize {
    return NSString(string: string).boundingRect(with: CGSize(width: width, height: CGFloat.greatestFiniteMagnitude),
                                                         options: NSStringDrawingOptions.usesLineFragmentOrigin,
                                                         attributes: [NSFontAttributeName: self],
                                                         context: nil).size
}
}
</code>```

then call it

```<code>let width = 290.0
let textSize = UIFont.systemFont(ofSize: 15).sizeOfString("text", constrainedToWidth: width)
</code>```

Body:
I would like to create the paragraph with Read More/Read Less at the end.
 Here are my codes;

func getLabelHeight(text: String, width: CGFloat, font: UIFont) -> CGFloat {

    let lbl = UILabel(frame: .zero)
    lbl.frame.size.width = width
    lbl.font = font
    lbl.numberOfLines = 0
    lbl.text = text
    lbl.sizeToFit()
    lbl.adjustsFontSizeToFitWidth = true
    return lbl.frame.size.height

}

 @IBAction func btnReadMore(_ sender: Any) {
    if isLabelAtMaxHeight {

        btnReadmore.setTitle(NSLocalizedString("Read more", comment: ""), for: .normal)
        btnReadmore.titleLabel!.font = UIFont (name: "Tharlon", size: 13)
        isLabelAtMaxHeight = false
        lblReviewHeight.constant = 29
        lblReview.font = UIFont (name: "Tharlon", size: 13)

    }
    else {

        btnReadmore.setTitle(NSLocalizedString("Read less", comment: ""), for: .normal)
        btnReadmore.titleLabel!.font = UIFont (name: "Tharlon", size: 13)
        isLabelAtMaxHeight = true
        lblReviewHeight.constant = getLabelHeight(text: lblReview.text!, width: view.bounds.width, font: lblReview.font)
        lblReview.font = UIFont (name: "Tharlon", size: 13)
        lblReview.lineBreakMode = NSLineBreakMode.byTruncatingHead

    }

}

I also set the label "Word wrap" in Attributes Inspector.

The problem is that when I add "NSLineBreakMode.byTruncatingHead" in Read Less part, all the texts show completely. But, some words in those places inside text disappear.

So, I remove that code and run the app. At that time, texts are not shown completely and only show half. I've been trying to solve this problem the whole day.

I don't want to use any other library.

Could anyone help me please?

Body:
to calculate text height by font and width you can use this extension

extension UIFont {
func sizeOfString (_ string: String, constrainedToWidth width: CGFloat) -> CGSize {
    return NSString(string: string).boundingRect(with: CGSize(width: width, height: CGFloat.greatestFiniteMagnitude),
                                                         options: NSStringDrawingOptions.usesLineFragmentOrigin,
                                                         attributes: [NSFontAttributeName: self],
                                                         context: nil).size
}
}

then call it

let width = 290.0
let textSize = UIFont.systemFont(ofSize: 15).sizeOfString("text", constrainedToWidth: width)


问:
SonarQube Rule: Every Rule with an sample example are present?
Agenda and reason to ask this question : I was going through profile created by someone and want to remove false positive rules.

Question :

For example :

I want to understand below rule,

"Correctness - Class defines methods which confuse Character with int parameters"

Where should i see details and examples?

Thanks,
Roshankumar

答:
Since you appear to be in a SonarQube rule list context, the rule detail will give you this. To see it, click on the rule or right-arrow.

The descriptions for FindBugs rules can be terse at best, but this is an FB-contrib rule with a slightly longer description. However, it does not contain examples.


问:
How to add line-break in the google groups description field?
I tried several ways to add line-breaks in the google groups description field while creating the group using the Google directory api. https://developers.google.com/admin-sdk/directory/v1/reference/groups/insert
Ex: \n, \r\n,
&#10 etc.

But none of the worked.

Please let me know if you have any other option.

Thanks

答: The last thing you can try is to URI encode the '\n' using %0A. This seems to have been successfully used in this SO post.


问:
Possible to use messages in enum?
I am wondering if it's possible to have a enum with messages.

What I am trying to accomplish is to have nested messages, based on which enum is selected. The problem is easily solved by doing business logic checks using the optional identifier.

I am just looking for a more elegant business logic controll implementation than if-statement the hell out of the message to determine which code path to execute.

Something like this is what I have in mind. Is this possible to achieve?

```<code>message T {
    enum A {
        message T2 = 1;
    }
}
</code>```

答:
No - enumerations are simply named 32-bit integers; but there is oneof - I wonder if that is what you are looking for:

```<code>message T {
    oneof A {
        T2 t2 = 1;
        //...other options here
    }
}
message T2 {}
</code>```

Title: Possible to use messages in enum?

Body:
I am wondering if it's possible to have a enum with messages.

What I am trying to accomplish is to have nested messages, based on which enum is selected. The problem is easily solved by doing business logic checks using the optional identifier.

I am just looking for a more elegant business logic controll implementation than if-statement the hell out of the message to determine which code path to execute.

Something like this is what I have in mind. Is this possible to achieve?

message T {
    enum A {
        message T2 = 1;
    }
}

Body:
No - enumerations are simply named 32-bit integers; but there is oneof - I wonder if that is what you are looking for:

message T {
    oneof A {
        T2 t2 = 1;
        //...other options here
    }
}
message T2 {}


问:
airflow webserver -p 8080 result in OSError: [Errno 13] Permission denied
After installing airflow package in AWS EC2 instance , i am trying to start the airflow webserver Its showing permission denied issue , i am not getting which file or folder its trying to create/modify to get this error.

```<code>[root@ip-172-31-62-1 airflow]# /usr/local/bin/airflow webserver -p 8080
[2017-06-13 04:24:35,692] {__init__.py:57} INFO - Using executor SequentialExecutor

/usr/local/lib/python2.7/site-packages/flask/exthook.py:71: ExtDeprecationWarning: Importing flask.ext.cache is deprecated, use flask_cache instead.
  .format(x=modname), ExtDeprecationWarning
[2017-06-13 04:24:36,093] [4053] {models.py:167} INFO - Filling up the DagBag from /home/ec2-user/airflow/dags
Running the Gunicorn Server with:
Workers: 4 sync
Host: 0.0.0.0:8080
Timeout: 120
Logfiles: - -
=================================================================

Traceback (most recent call last):
  File "/usr/local/bin/airflow", line 28, in <module>
    args.func(args)
  File "/usr/local/lib/python2.7/site-packages/airflow/bin/cli.py", line 791, in webserver
    gunicorn_master_proc = subprocess.Popen(run_args)
  File "/usr/lib64/python2.7/subprocess.py", line 711, in __init__
    errread, errwrite)
  File "/usr/lib64/python2.7/subprocess.py", line 1343, in _execute_child
    raise child_exception
OSError: [Errno 13] Permission denied

------------------------------------
The Value of run_args in above error message is
['gunicorn', '-w', '4', '-k', 'sync', '-t', '120', '-b', '0.0.0.0:8080', '-n', 'airflow-webserver', '-p', '/home/ec2-user/airflow/airflow-webserver.pid', '-c', 'airflow.www.gunicorn_config', '--access-logfile', '-', '--error-logfile', '-', 'airflow.www.app:cached_app()']
</code>```

答:
I had this same issue. It got resolved when I installed the whole setup in sudo mode. Please find the commands I used:</p>

```<code>sudo apt-get update && sudo apt-get -y upgrade

sudo apt-get install python-pip

sudo -H pip install airflow

sudo airflow initdb

sudo airflow webserver -p 8080
</code>```

Body:
After installing airflow package in AWS EC2 instance , i am trying to start the airflow webserver Its showing permission denied issue , i am not getting which file or folder its trying to create/modify to get this error.

[root@ip-172-31-62-1 airflow]# /usr/local/bin/airflow webserver -p 8080
[2017-06-13 04:24:35,692] {__init__.py:57} INFO - Using executor SequentialExecutor

/usr/local/lib/python2.7/site-packages/flask/exthook.py:71: ExtDeprecationWarning: Importing flask.ext.cache is deprecated, use flask_cache instead.
  .format(x=modname), ExtDeprecationWarning
[2017-06-13 04:24:36,093] [4053] {models.py:167} INFO - Filling up the DagBag from /home/ec2-user/airflow/dags
Running the Gunicorn Server with:
Workers: 4 sync
Host: 0.0.0.0:8080
Timeout: 120
Logfiles: - -
=================================================================

Traceback (most recent call last):
  File "/usr/local/bin/airflow", line 28, in <module>
    args.func(args)
  File "/usr/local/lib/python2.7/site-packages/airflow/bin/cli.py", line 791, in webserver
    gunicorn_master_proc = subprocess.Popen(run_args)
  File "/usr/lib64/python2.7/subprocess.py", line 711, in __init__
    errread, errwrite)
  File "/usr/lib64/python2.7/subprocess.py", line 1343, in _execute_child
    raise child_exception
OSError: [Errno 13] Permission denied

------------------------------------
The Value of run_args in above error message is
['gunicorn', '-w', '4', '-k', 'sync', '-t', '120', '-b', '0.0.0.0:8080', '-n', 'airflow-webserver', '-p', '/home/ec2-user/airflow/airflow-webserver.pid', '-c', 'airflow.www.gunicorn_config', '--access-logfile', '-', '--error-logfile', '-', 'airflow.www.app:cached_app()']

Body:
I had this same issue. It got resolved when I installed the whole setup in sudo mode. Please find the commands I used:

sudo apt-get update && sudo apt-get -y upgrade

sudo apt-get install python-pip

sudo -H pip install airflow

sudo airflow initdb

sudo airflow webserver -p 8080


问:
Replace all td's tags by th in a java String
I want to replace replace all "td" by "th" in this String

```<code>String head = "<tr>\n<td> </td>\n<td> </td>\n<td>Libelle</td>\n"
                      + "<td>Nom Table</td>\n<td>Groupe</td>\n<td> </td>\n</tr>\n"
</code>```

I tried to use :

```<code>head.replace("<td>", "<th>");
head.replace("</td>", "</th>");
</code>```

but it doesn't working.

Can you help me ?

答:
This is something that takes care of scenarios like empty  tags and when your td tags have attributes like class=\"abc\" :

```<code>String head  = ""<td class=\"abc\">outdoor</td><td />"";
head = head.replace("<td", "<th");
head = head.replace("</td", "</th");
System.out.println(head);
</code>```

Body:
I want to replace replace all "td" by "th" in this String

String head = "
\n 	\n 	\nLibelle	\n"
                      + "Nom Table	\nGroupe	\n 	\n
\n"

I tried to use :

head.replace("", "");
head.replace("	", "	");

but it doesn't working.

Can you help me ?

Body:
This is something that takes care of scenarios like empty <td /><td/> tags and when your td tags have attributes like class=\"abc\" :

String head  = ""<td class=\"abc\">outdoor</td><td />"";
head = head.replace("<td", "<th");
head = head.replace("</td", "</th");
System.out.println(head);


问:
Standalone kubelet persistent disk mount on Google Cloud instance
I have a process that needs to run daily in a Docker container, syncing some data from a storage bucket to an external volume (Google Cloud persistent disk). So far, I managed to launch the process by creating a single-node container cluster.

Since the process completes in a couple of hours, I want to delete VM resources (except the persistent disk of course) once complete. Launching/deleting a single compute-VM (without the kubernetes cluster setup) seems simpler, so I was trying to get a single kubelet running on a container-optimized cloud instance. Persistent disk mounting is where this fails.

My launch command:

```<code>gcloud compute instances create cvm-name-0 \
    --image-family=cos-stable \
    --image-project=cos-cloud \
    --boot-disk-type pd-ssd \
    --boot-disk-size 10GB \
    --metadata-from-file \
    "google-container-manifest=containers.yaml,user-data=cloudinit.yaml" \
    --zone "$gzone" \
    --scopes default,storage-rw \
    --machine-type n1-highcpu-4
</code>```

Contents of container.yaml:

```<code>apiVersion: v1
kind: Pod
metadata:
  name: container-name
spec:
  containers:
    - name: container-name
      image: gcr.io/project-name/container-name
      imagePullPolicy: Always
      volumeMounts:
        - name: persistent-disk-name
          mountPath: /home/someuser/somedir
  volumes:
    - name: persistent-disk-name
      gcePersistentDisk:
        pdName: persistent-disk-name
        fsType: ext4
</code>```

Contents of cloudinit.yaml:

```<code>#cloud-config
bootcmd:
- echo "KUBELET_OPTS=\"--cloud-provider=gce\"" > /etc/default/kubelet
runcmd:
- systemctl start kubelet.service
</code>```

While the --cloud-provider=gce option fixes the "Failed to get GCE Cloud Provider" error per this question, there is still some problem mounting the disk.

A potentially relevant line from the container OS log says:

EXT4-fs (dm-0): couldn't mount as ext3 due to feature incompatibilities

Any way to make this work on a single compute instance (without the kubernetes cluster)? Where else should I be looking for more informative error logs?

答:
I'm not using kubernetes at the moment, but I am backing up to a cloud storage bucket.

I have something like this in my cloud-config:

```<code>users:
- name: dockerrunner
  uid: 2000
  groups: docker
write_files:
- path: /home/dockerrunner/backup-hourly.sh
  permissions: 0755
  owner: dockerrunner
  content: |
    #!/bin/sh
    export HOME=/home/dockerrunner
    export USER=root
    toolbox --bind /mnt/disks/nfs:/mnt/disks/nfs \
      /google-cloud-sdk/bin/gsutil -m \
      rsync -r /mnt/disks/nfs gs://<bucket-name>/hourly
- path: /etc/systemd/system/files-backup-hourly.service
  permissions: 0644
  owner: root
  content: |
    [Unit]
    Description=Shared Files Backup upload script - hourly

    [Service]
    Type=oneshot
    ExecStart=/bin/sh /home/dockerrunner/backup-hourly.sh

- path: /etc/systemd/system/files-backup-hourly.timer
  permissions: 0644
  owner: root
  content: |
    [Unit]
    Description=Run Shared Files Backup create script every hour

    [Timer]
    OnCalendar=*-*-* *:00:00

    [Install]
    WantedBy=timers.target
runcmd:
- systemctl daemon-reload
- systemctl start files-backup-hourly.service
- systemctl start files-backup-hourly.timer
</code>```

Body:
I have a process that needs to run daily in a Docker container, syncing some data from a storage bucket to an external volume (Google Cloud persistent disk). So far, I managed to launch the process by creating a single-node container cluster.

Since the process completes in a couple of hours, I want to delete VM resources (except the persistent disk of course) once complete. Launching/deleting a single compute-VM (without the kubernetes cluster setup) seems simpler, so I was trying to get a single kubelet running on a container-optimized cloud instance. Persistent disk mounting is where this fails.

My launch command:

gcloud compute instances create cvm-name-0 \
    --image-family=cos-stable \
    --image-project=cos-cloud \
    --boot-disk-type pd-ssd \
    --boot-disk-size 10GB \
    --metadata-from-file \
    "google-container-manifest=containers.yaml,user-data=cloudinit.yaml" \
    --zone "$gzone" \
    --scopes default,storage-rw \
    --machine-type n1-highcpu-4

Contents of container.yaml:

apiVersion: v1
kind: Pod
metadata:
  name: container-name
spec:
  containers:
    - name: container-name
      image: gcr.io/project-name/container-name
      imagePullPolicy: Always
      volumeMounts:
        - name: persistent-disk-name
          mountPath: /home/someuser/somedir
  volumes:
    - name: persistent-disk-name
      gcePersistentDisk:
        pdName: persistent-disk-name
        fsType: ext4

Contents of cloudinit.yaml:

#cloud-config
bootcmd:
- echo "KUBELET_OPTS=\"--cloud-provider=gce\"" > /etc/default/kubelet
runcmd:
- systemctl start kubelet.service

While the --cloud-provider=gce option fixes the "Failed to get GCE Cloud Provider" error per this question, there is still some problem mounting the disk.

A potentially relevant line from the container OS log says:

EXT4-fs (dm-0): couldn't mount as ext3 due to feature incompatibilities

Any way to make this work on a single compute instance (without the kubernetes cluster)? Where else should I be looking for more informative error logs?

Body:
I'm not using kubernetes at the moment, but I am backing up to a cloud storage bucket.

I have something like this in my cloud-config:

users:
- name: dockerrunner
  uid: 2000
  groups: docker
write_files:
- path: /home/dockerrunner/backup-hourly.sh
  permissions: 0755
  owner: dockerrunner
  content: |
    #!/bin/sh
    export HOME=/home/dockerrunner
    export USER=root
    toolbox --bind /mnt/disks/nfs:/mnt/disks/nfs \
      /google-cloud-sdk/bin/gsutil -m \
      rsync -r /mnt/disks/nfs gs://<bucket-name>/hourly
- path: /etc/systemd/system/files-backup-hourly.service
  permissions: 0644
  owner: root
  content: |
    [Unit]
    Description=Shared Files Backup upload script - hourly

    [Service]
    Type=oneshot
    ExecStart=/bin/sh /home/dockerrunner/backup-hourly.sh

- path: /etc/systemd/system/files-backup-hourly.timer
  permissions: 0644
  owner: root
  content: |
    [Unit]
    Description=Run Shared Files Backup create script every hour

    [Timer]
    OnCalendar=*-*-* *:00:00

    [Install]
    WantedBy=timers.target
runcmd:
- systemctl daemon-reload
- systemctl start files-backup-hourly.service
- systemctl start files-backup-hourly.timer


问:
Git: How to get the full name of object's hash?
I got short object hash from somewhere, for example, git diff:

```<code>diff --git a/Note1.md b/Note1.md
index 2b95b9f..b9596f0 100644
--- a/Note1.md
+++ b/Note1.md
@@ -1328,6 +1328,12 @@ variables.(starting with (@)
</code>```

How can I get 40 byte length names of those short ID (2b95b9f and b9596f0)?

答:
Use the following command:

git show --pretty=%H <short-hash>

Body:
I got short object hash from somewhere, for example, git diff:

diff --git a/Note1.md b/Note1.md
index 2b95b9f..b9596f0 100644
--- a/Note1.md
+++ b/Note1.md
@@ -1328,6 +1328,12 @@ variables.(starting with (@)

How can I get 40 byte length names of those short ID (2b95b9f and b9596f0)?


问:
Does the put method increases the "modCount" in case of replacing the old value for a given key?
In the below code (actual implementation of put method inside HashMap), I see the modCount is incremented only in case of new entry getting added but not sure whether it is getting incremented in normal case of replacement of old value and inserting new value for a given key. But I have an understanding that mod count increases in case of the hashmap structure changes, i.e in case of add, remove or update the value inside a map. Can someone explain this, as I do not see here in the code the modCount getting incremented inside the if part rather outside the for loop (so is it only for adding anew value, this modCount changes)?</p>

```<code>public V put(K key, V value) {
 if (key == null)
     return putForNullKey(value);
  int hash = hash(key.hashCode());
  int i = indexFor(hash, table.length);
  for (Entry<K,V> e = table[i]; e != null; e = e.next) {
       Object k;
       if (e.hash == hash && ((k = e.key) == key || key.equals(k))) {
           V oldValue = e.value;
           e.value = value;
           e.recordAccess(this);
           return oldValue;
       }
  }
  modCount++;
  addEntry(hash, key, value, i);
  return null;
}
</code>```

答:
Copied below directly from the javadoc of modcount of hashmap.java class :-

/**
       * The number of times this HashMap has been structurally modified
       * Structural modifications are those that change the number of mappings in
       * the HashMap or otherwise modify its internal structure (e.g.,
       * rehash).  This field is used to make iterators on Collection-views of
       * the HashMap fail-fast.  (See ConcurrentModificationException).
       */

So Modcount will not be changed if you replace the old value for a key and i am using java-8 and below is the piece of code which replace the value for a existing key :-

```<code>if (e != null) { // existing mapping for key
                V oldValue = e.value;
                if (!onlyIfAbsent || oldValue == null)
                    e.value = value;
                afterNodeAccess(e);
                return oldValue;
            }
</code>```

And modcount++ is increase after above line but note here we are returning and see the comment // existing mapping for key.
So to answer your question modcount is not increase in case of value is replace for existing key as it will neither change the structure of hashmap nor it will cause the rehashing of map.

Note:- Even the code sample which you have provided there also you can notice that if its for existing key its replacing the value and returning the old value, which is the return for a put method. so line modCount++; will not be executed.

Hope i am clear and let me know if you have some doubts.

Body:
In the below code (actual implementation of put method inside HashMap), I see the modCount is incremented only in case of new entry getting added but not sure whether it is getting incremented in normal case of replacement of old value and inserting new value for a given key. But I have an understanding that mod count increases in case of the hashmap structure changes, i.e in case of add, remove or update the value inside a map. Can someone explain this, as I do not see here in the code the modCount getting incremented inside the if part rather outside the for loop (so is it only for adding anew value, this modCount changes)?

public V put(K key, V value) {
 if (key == null)
     return putForNullKey(value);
  int hash = hash(key.hashCode());
  int i = indexFor(hash, table.length);
  for (Entry<K,V> e = table[i]; e != null; e = e.next) {
       Object k;
       if (e.hash == hash && ((k = e.key) == key || key.equals(k))) {
           V oldValue = e.value;
           e.value = value;
           e.recordAccess(this);
           return oldValue;
       }
  }
  modCount++;
  addEntry(hash, key, value, i);
  return null;
}

Body:
Copied below directly from the javadoc of modcount of hashmap.java class :-

/**
       * The number of times this HashMap has been structurally modified
       * Structural modifications are those that change the number of mappings in
       * the HashMap or otherwise modify its internal structure (e.g.,
       * rehash).  This field is used to make iterators on Collection-views of
       * the HashMap fail-fast.  (See ConcurrentModificationException).
       */

So Modcount will not be changed if you replace the old value for a key and i am using java-8 and below is the piece of code which replace the value for a existing key :-

if (e != null) { // existing mapping for key
                V oldValue = e.value;
                if (!onlyIfAbsent || oldValue == null)
                    e.value = value;
                afterNodeAccess(e);
                return oldValue;
            }

And modcount++ is increase after above line but note here we are returning and see the comment // existing mapping for key.
So to answer your question modcount is not increase in case of value is replace for existing key as it will neither change the structure of hashmap nor it will cause the rehashing of map.

Note:- Even the code sample which you have provided there also you can notice that if its for existing key its replacing the value and returning the old value, which is the return for a put method. so line modCount++; will not be executed.

Hope i am clear and let me know if you have some doubts.


问:
How to create a copy of a file having length more than 260 characters
How to create a copy of a file having length more than 260 characters including file name using vb.net

When we are trying to create a copy using File.Copy method it throws exception as follows:

"The specified path, file name, or both are too long. The fully qualified file name must be less than 260 characters, and the directory name must be less than 248 characters."

Is it possible, then please help...

答:
You're running into the MAX_PATH limitation.  As a work around you should be able to P/Invoke directly to kernel32.dll's CopyFile function and use the "\\?\" Prefix in front of the destination path to prevent hitting the MAX_PATH issue.

Note that while you're able to copy the file in the way most apps won't be able to open it since they are also limited by MAX_PATH.

A good overview of the problem can be found here: http://blogs.msdn.com/bclteam/archive/2007/02/13/long-paths-in-net-part-1-of-3-kim-hamilton.aspx

Some example code of P/Invoking into these methods using C# can be found in Part 2, here: http://blogs.msdn.com/bclteam/archive/2007/03/26/long-paths-in-net-part-2-of-3-long-path-workarounds-kim-hamilton.aspx

The library that schnaader linked to looks like it will save you the problem of P/Invoking into kernel32.dll, not sure if you want to take a dependency on an external dll or not.

OwnerDisplayName: Sugam

LastEditorDisplayName: CodeSlave

OwnerDisplayName: Matt Ellis

LastEditorDisplayName: Matt Ellis


问:
Add three Buttons in an UIAlertView
I created uialertview, and add two buttons, Now I need to add one more button in alert view. How to edit my code to add one more button?</p>

```<code>UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Refresh" message:@"Are you want to Refresh Data" delegate:self cancelButtonTitle:@"Cancel" otherButtonTitles:@"OK", nil];
[alert show];
[alert release];
</code>```

答:
Try to add your buttons in otherButtonTitles </p>

```<code>UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Refresh" message:@"Are you want to Refresh Data" delegate:self cancelButtonTitle:@"Cancel" otherButtonTitles:@"Button1",@"Button2"@"Button2",nil];
</code>```

Title: Add three Buttons in an UIAlertView

Body:
I created uialertview, and add two buttons, Now I need to add one more button in alert view. How to edit my code to add one more button?

UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Refresh" message:@"Are you want to Refresh Data" delegate:self cancelButtonTitle:@"Cancel" otherButtonTitles:@"OK", nil];
[alert show];
[alert release];

Body:
Try to add your buttons in otherButtonTitles

UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Refresh" message:@"Are you want to Refresh Data" delegate:self cancelButtonTitle:@"Cancel" otherButtonTitles:@"Button1",@"Button2"@"Button2",nil];


问:
What is the difference between an attribute and a column?
The two terms "attribute" and "column" seems to be used interchangeably...but my guess is that a column is the box and an attribute is what goes into the box.</p>

答:
A "Column" is a column in a database table whereas "attribute(s)" are externally visible facets of an object.

An "attribute" is for a model and a "column" is for a table in a database.

Here's a schema for a model:

```<code>create_table "retreats", force: :cascade do |t|
  t.string "title"
  t.string "tagline"
  t.datetime "created_at", null: false
  t.datetime "updated_at", null: false
end
</code>```

Here "retreats" is a table in a database with the following columns "title", "tagline", "created_at", "updated_at".

This table has a model Retreat which has attributes "title", "tagline", "created_at" and "updated_at". You can get some more information on attributes on this page.

They are similar but they are different because of their context.

edit 1:

A row in a database table is mapped by an object in Rails. The value of the attribute of that object is the value of the column in that row.

As vojic points out, a column contains the attribute values for all the objects.

Body:
A "Column" is a column in a database table whereas "attribute(s)" are externally visible facets of an object.

An "attribute" is for a model and a "column" is for a table in a database.

Here's a schema for a model:

create_table "retreats", force: :cascade do |t|
  t.string "title"
  t.string "tagline"
  t.datetime "created_at", null: false
  t.datetime "updated_at", null: false
end

Here "retreats" is a table in a database with the following columns "title", "tagline", "created_at", "updated_at".

This table has a model Retreat which has attributes "title", "tagline", "created_at" and "updated_at". You can get some more information on attributes on this page.

They are similar but they are different because of their context.

edit 1:

A row in a database table is mapped by an object in Rails. The value of the attribute of that object is the value of the column in that row.

As vojic points out, a column contains the attribute values for all the objects.


问:
Swift 3 CoreBluetooth Background data receive
I am trying to receive some data from an Arduino which is emitting some data when I push a button.

Now I've noticed that it does not receive after a while. I did not kill the
app yet. How come? I've already added

```<code><key>UIBackgroundModes</key>
<array>
    <string>bluetooth-central</string>
    <string>bluetooth-peripheral</string>
    <string>external-accessory</string>
</array>
</code>```

My devices are both paired.

EDIT:

I am trying to do the same as the Tile App, it works really well there.

EDIT 2:

I instantiate my manager like this:

centralManager = CBCentralManager(delegate:self, queue:nil)

答:
you need to initialize your CBCentralManager by passing in the option parameter your restore key identifier.

```<code>let central = CBCentralManager(delegate: self, queue: nil, options: [CBCentralManagerOptionRestoreIdentifierKey: "yourkey"])
</code>```

Where "your key" can be anything you want and it is useful for you just to understand that your app was awaken to handle a BLE message. If the app was killed by the system when a new BLE message will cause it to be resurrect in your app delegate didFinish launching this key will be passed in the options parameter.

To make it work properly you'll have to implement the delegate method

```<code>optional public func centralManager(_ central: CBCentralManager, willRestoreState dict: [String : Any])
</code>```

this will be called in case of app killed by the system (or by a crash.. not by the user by the way) in order to notify you that a new BLE event happened. In the will restore state dict you will have all the info you need to restore your BLE session.

Here you will find all apple's recommendations to work with the BLE in background.

Remember that the connection with your peripheral will always be severed if the user performs any actions that voluntarily causes the connection to go off, such as app killed, Blueetooth disabled. iOS will continue to awake/resurrect your app in case of crash, app in background and then killed by the system.

The events that will cause the app to be awaken are notifications from registered notifying characteristics, new peripherals discovery, read of a characteristic. (basically any callback of the CoreBluetooth delegate)

Keep in mind that a scan operation while in background has limitations.

From apple's documentation linked before:

Although you can perform many Bluetooth-related tasks while your app is in the background, keep in mind that scanning for peripherals while
  your app is in the background operates differently than when your app
  is in the foreground. In particular, when your app is scanning for
  device while in the background:

The CBCentralManagerScanOptionAllowDuplicatesKey scan option key is
  ignored, and multiple discoveries of an advertising peripheral are
  coalesced into a single discovery event.

If all apps that are scanning
  for peripherals are in the background, the interval at which your
  central device scans for advertising packets increases. As a result,
  it may take longer to discover an advertising peripheral.

Happy coding.

Body:
I am trying to receive some data from an Arduino which is emitting some data when I push a button.

Now I've noticed that it does not receive after a while. I did not kill the
app yet. How come? I've already added

<key>UIBackgroundModes</key>
<array>
    <string>bluetooth-central</string>
    <string>bluetooth-peripheral</string>
    <string>external-accessory</string>
</array>

My devices are both paired.

EDIT:

I am trying to do the same as the Tile App, it works really well there.

EDIT 2:

I instantiate my manager like this:

centralManager = CBCentralManager(delegate:self, queue:nil)

Body:
you need to initialize your CBCentralManager by passing in the option parameter your restore key identifier.

let central = CBCentralManager(delegate: self, queue: nil, options: [CBCentralManagerOptionRestoreIdentifierKey: "yourkey"])

Where "your key" can be anything you want and it is useful for you just to understand that your app was awaken to handle a BLE message. If the app was killed by the system when a new BLE message will cause it to be resurrect in your app delegate didFinish launching this key will be passed in the options parameter.

To make it work properly you'll have to implement the delegate method

optional public func centralManager(_ central: CBCentralManager, willRestoreState dict: [String : Any])

this will be called in case of app killed by the system (or by a crash.. not by the user by the way) in order to notify you that a new BLE event happened. In the will restore state dict you will have all the info you need to restore your BLE session.

Here you will find all apple's recommendations to work with the BLE in background.

Remember that the connection with your peripheral will always be severed if the user performs any actions that voluntarily causes the connection to go off, such as app killed, Blueetooth disabled. iOS will continue to awake/resurrect your app in case of crash, app in background and then killed by the system.

The events that will cause the app to be awaken are notifications from registered notifying characteristics, new peripherals discovery, read of a characteristic. (basically any callback of the CoreBluetooth delegate)

Keep in mind that a scan operation while in background has limitations.

From apple's documentation linked before:

Although you can perform many Bluetooth-related tasks while your app is in the background, keep in mind that scanning for peripherals while
  your app is in the background operates differently than when your app
  is in the foreground. In particular, when your app is scanning for
  device while in the background:

The CBCentralManagerScanOptionAllowDuplicatesKey scan option key is
  ignored, and multiple discoveries of an advertising peripheral are
  coalesced into a single discovery event.

If all apps that are scanning
  for peripherals are in the background, the interval at which your
  central device scans for advertising packets increases. As a result,
  it may take longer to discover an advertising peripheral.

Happy coding.