问:
Google Maps markers from XML
I tried to use Google Tutorial (https://developers.google.com/maps/documentation/javascript/mysql-to-maps)
I did XML output rightly, so we have a file, and an initialized map, but for some reasons markers do not appear, and we have an errors:

ReferenceError: marker is not defined
 and

ReferenceError: doNothing is not defined.

I have read some similar questions around, but unfortunately have not enough skills in JS to understand what actually I am missing.
Any help will be appreciated.

XML

```<code><?xml version="1.0"?>

-<markers>
<marker year="2019" lng="137.553619" lat="36.106525" name="Norikura" id="1"/>
<marker year="2019" lng="139.767151" lat="33.140198" name="Hachijou-jima" id="2"/>
<marker year="2019" lng="138.896469" lat="35.678909" name="Ubako" id="3"/>
<marker year="2020" lng="140.416473" lat="38.170666" name="Zao" id="4"/>
<marker year="2020" lng="138.370071" lat="35.999195" name="Io" id="5"/>
<marker year="2020" lng="139.167664" lat="35.781200" name="Hinode" id="6"/>
</markers>
</code>```

HTML

```<code><div id="map">
   <script async defer src="https://maps.googleapis.com/maps/api/js?key=AIzaSyAVpvd7SOVCDWe3XiCps1r6428suI7BMq0&callback=initMap">
   </script>
</div>
<script src="markersMap.js"></script>
</code>```

markersMap.js

```<code>function initMap() {
  // The location of Fuji
  var fuji = {lat: 35.358056, lng: 138.731111};
  // The map, centered at Fuji
  var map = new google.maps.Map(
      document.getElementById('map'), {zoom: 9, center: fuji});
 loadMarkers();
 }

function downloadUrl(url,callback) {
 var request = window.ActiveXObject ?
     new ActiveXObject('Microsoft.XMLHTTP') :
     new XMLHttpRequestfunction initMap() {

 request.onreadystatechange = function() {
   if (request.readyState == 4) {
     request.onreadystatechange = doNothing;
     callback(request, request.status);
   }
 };

 request.open('GET', url, true);
 request.send(null);
}

downloadUrl('test1.xml', function(data) {
  var xml = data.responseXML;
  var markers = xml.documentElement.getElementsByTagName('marker');
  Array.prototype.forEach.call(markers, function(markerElem) {
    var id = markerElem.getAttribute('id');
    var name = markerElem.getAttribute('name');
    var year = markerElem.getAttribute('year');
    var point = new google.maps.LatLng(
        parseFloat(markerElem.getAttribute('lat')),
        parseFloat(markerElem.getAttribute('lng')));

    var infowincontent = document.createElement('div');
    var strong = document.createElement('strong');
    strong.textContent = name
    infowincontent.appendChild(strong);
    infowincontent.appendChild(document.createElement('br'));

    var text = document.createElement('text');
    text.textContent = year
    infowincontent.appendChild(text);
    var marker = new google.maps.Marker({
      map: map,
      position: point
   });
});
});

marker.addListener('click', function() {
  infoWindow.setContent(infowincontent);
  infoWindow.open(map, marker);
});
</code>```

答:
As for doNothing
Seems like you're missing (check the tutorial)

```<code>function doNothing() {}
</code>```

As for marker
In your code marker is defined inside downloadUrl function, while used outside
In tutorial it is used inside

```<code>  var marker = new google.maps.Marker({
    map: map,
    position: point,
    label: icon.label
  });
  marker.addListener('click', function() {
    infoWindow.setContent(infowincontent);
    infoWindow.open(map, marker);
  });
</code>```

Title: Google Maps markers from XML

Body:
I tried to use Google Tutorial (https://developers.google.com/maps/documentation/javascript/mysql-to-maps)
I did XML output rightly, so we have a file, and an initialized map, but for some reasons markers do not appear, and we have an errors:

ReferenceError: marker is not defined
 and

ReferenceError: doNothing is not defined.

I have read some similar questions around, but unfortunately have not enough skills in JS to understand what actually I am missing.
Any help will be appreciated.

XML

<?xml version="1.0"?>

-<markers>
<marker year="2019" lng="137.553619" lat="36.106525" name="Norikura" id="1"/>
<marker year="2019" lng="139.767151" lat="33.140198" name="Hachijou-jima" id="2"/>
<marker year="2019" lng="138.896469" lat="35.678909" name="Ubako" id="3"/>
<marker year="2020" lng="140.416473" lat="38.170666" name="Zao" id="4"/>
<marker year="2020" lng="138.370071" lat="35.999195" name="Io" id="5"/>
<marker year="2020" lng="139.167664" lat="35.781200" name="Hinode" id="6"/>
</markers>

HTML

markersMap.js

function initMap() {
  // The location of Fuji
  var fuji = {lat: 35.358056, lng: 138.731111};
  // The map, centered at Fuji
  var map = new google.maps.Map(
      document.getElementById('map'), {zoom: 9, center: fuji});
 loadMarkers();
 }

function downloadUrl(url,callback) {
 var request = window.ActiveXObject ?
     new ActiveXObject('Microsoft.XMLHTTP') :
     new XMLHttpRequestfunction initMap() {

 request.onreadystatechange = function() {
   if (request.readyState == 4) {
     request.onreadystatechange = doNothing;
     callback(request, request.status);
   }
 };

 request.open('GET', url, true);
 request.send(null);
}

downloadUrl('test1.xml', function(data) {
  var xml = data.responseXML;
  var markers = xml.documentElement.getElementsByTagName('marker');
  Array.prototype.forEach.call(markers, function(markerElem) {
    var id = markerElem.getAttribute('id');
    var name = markerElem.getAttribute('name');
    var year = markerElem.getAttribute('year');
    var point = new google.maps.LatLng(
        parseFloat(markerElem.getAttribute('lat')),
        parseFloat(markerElem.getAttribute('lng')));

    var infowincontent = document.createElement('div');
    var strong = document.createElement('strong');
    strong.textContent = name
    infowincontent.appendChild(strong);
    infowincontent.appendChild(document.createElement('br'));

    var text = document.createElement('text');
    text.textContent = year
    infowincontent.appendChild(text);
    var marker = new google.maps.Marker({
      map: map,
      position: point
   });
});
});

marker.addListener('click', function() {
  infoWindow.setContent(infowincontent);
  infoWindow.open(map, marker);
});

Body:
As for doNothing
Seems like you're missing (check the tutorial)

function doNothing() {}

As for marker
In your code marker is defined inside downloadUrl function, while used outside
In tutorial it is used inside

  var marker = new google.maps.Marker({
    map: map,
    position: point,
    label: icon.label
  });
  marker.addListener('click', function() {
    infoWindow.setContent(infowincontent);
    infoWindow.open(map, marker);
  });


来源: stackexchange

问:
How to use geometry data type as a parameter in asyncpg?
For context, I want to query something to the effect of:

```<code>select point '(1,1)' <@ box '((0,0),(2,2))';
</code>```

I tried something like this:

```<code>CREATE TABLE tbl (latlng POINT NOT NULL);

box = [[22.268764039073968, -140.09765625000003], [61.438767493682825, -56.42578125000001]]
await pool.fetch(f'SELECT * FROM tbl WHERE latlng <@ $1;', box)
</code>```

Then I tried this:

```<code>from asyncpg.types import Point, Box

v = [[22.268764039073968,-140.09765625000003],[61.438767493682825,-56.42578125000001]]
box = Box(Point(v[0][0], v[0][1]), Point(v[1][0], v[1][1]))
await pool.fetch(f'SELECT * FROM tbl WHERE latlng <@ $1;', box)
</code>```

Both attempts result in the error:

```<code>asyncpg.exceptions.AmbiguousFunctionError: operator is not unique: point <@ unknown
HINT:  Could not choose a best candidate operator. You might need to add explicit type casts.
</code>```

I'm guessing that I have to manually make asyncpg use box_encode() for this parameter (since it's not implied by any table definition), but how do I tell asyncpg to do that?

答:
(Repeating the answer given in Elvis's comment above so I can mark the question as solved)

The solution is to add ::box after the arg to cast it, like so:

```<code>box = [[22.268764039073968, -140.09765625000003], [61.438767493682825, -56.42578125000001]]
await pool.fetch(f'SELECT * FROM tbl WHERE latlng <@ $1::box;', box)
</code>```

ContentLicense: CC BY-SA 4.0

Body:
For context, I want to query something to the effect of:

select point '(1,1)' <@ box '((0,0),(2,2))';

I tried something like this:

CREATE TABLE tbl (latlng POINT NOT NULL);

box = [[22.268764039073968, -140.09765625000003], [61.438767493682825, -56.42578125000001]]
await pool.fetch(f'SELECT * FROM tbl WHERE latlng <@ $1;', box)

Then I tried this:

from asyncpg.types import Point, Box

v = [[22.268764039073968,-140.09765625000003],[61.438767493682825,-56.42578125000001]]
box = Box(Point(v[0][0], v[0][1]), Point(v[1][0], v[1][1]))
await pool.fetch(f'SELECT * FROM tbl WHERE latlng <@ $1;', box)

Both attempts result in the error:

asyncpg.exceptions.AmbiguousFunctionError: operator is not unique: point <@ unknown
HINT:  Could not choose a best candidate operator. You might need to add explicit type casts.

I'm guessing that I have to manually make asyncpg use box_encode() for this parameter (since it's not implied by any table definition), but how do I tell asyncpg to do that?

Body:
(Repeating the answer given in Elvis's comment above so I can mark the question as solved)

The solution is to add ::box after the arg to cast it, like so:

box = [[22.268764039073968, -140.09765625000003], [61.438767493682825, -56.42578125000001]]
await pool.fetch(f'SELECT * FROM tbl WHERE latlng <@ $1::box;', box)


问:
Why Am I Getting "Cannot read property of undefined error" When I Can Print the Undefined Variable?
I am trying to write a recursive function that reads a string with nested parentheses, and turns it into an array with nested arrays. For example:
(hello(hi)are(yo(u))) => ["hello",["hihow"],"are"["yo",["u"]]]

(you might ask why I'm putting a single item into an array. I am planning to divide up the strings by # separators but I will do that after I can at least nest the single strings)

My code so far:

 const preProcessString = element => {
    var elementComponents = [];
    var part = "";
    var rS;
    if (
      element.indexOf("(") < element.indexOf(")") &&
      element.indexOf("(") !== -1
    ) {
      part = element.slice(0, element.indexOf("("));
      elementComponents.push(part);
      rS = preProcessString(element.substr(element.indexOf("(") + 1));
      console.log(rS[0]);//Am able to print the exact value that is causing the error
      elementComponents.push(rS[0]);//Causing the "cannot read property of undefined error"
      element = rS[1];
    } else {
      part = element.slice(0, element.indexOf(")"));
      elementComponents.push(part);
      return [elementComponents, element.substr(element.indexOf(")") + 1)];
    }
};
console.log(preProcessString("(hello(hi)are(yo(u)))"));```
</div>
</div>
</p>

<p>I am getting this error:</p>

``` ParseStepFile.js:272 Uncaught TypeError: Cannot read property '0' of undefined
    at preProcessString (ParseStepFile.js:272)
```

But I am able to print the value (and the value is the expected value) of the "undefined" variable in console.log statement right before the error causing line.  How is this possible? What can I do to fix this? Any help is appreciated!

答:
Your output does not match the words in your input. I assume that is an error.

const input = `(hello(hi)are(yo(u)))`

console.log(
  JSON.parse(
    input.replace(/\(/g, `", ["`)
         .replace(/\)/g, `"], "`)
         .replace(/^", /, ``)
         .replace(/, "$/, ``)
         .replace(/, ""/g, ``)
  )
);```

Body:
I am trying to write a recursive function that reads a string with nested parentheses, and turns it into an array with nested arrays. For example:
(hello(hi)are(yo(u))) => ["hello",["hihow"],"are"["yo",["u"]]]

(you might ask why I'm putting a single item into an array. I am planning to divide up the strings by # separators but I will do that after I can at least nest the single strings)

My code so far:

 const preProcessString = element => {
    var elementComponents = [];
    var part = "";
    var rS;
    if (
      element.indexOf("(") < element.indexOf(")") &&
      element.indexOf("(") !== -1
    ) {
      part = element.slice(0, element.indexOf("("));
      elementComponents.push(part);
      rS = preProcessString(element.substr(element.indexOf("(") + 1));
      console.log(rS[0]);//Am able to print the exact value that is causing the error
      elementComponents.push(rS[0]);//Causing the "cannot read property of undefined error"
      element = rS[1];
    } else {
      part = element.slice(0, element.indexOf(")"));
      elementComponents.push(part);
      return [elementComponents, element.substr(element.indexOf(")") + 1)];
    }
};
console.log(preProcessString("(hello(hi)are(yo(u)))"));

I am getting this error:

 ParseStepFile.js:272 Uncaught TypeError: Cannot read property '0' of undefined
    at preProcessString (ParseStepFile.js:272)

But I am able to print the value (and the value is the expected value) of the "undefined" variable in console.log statement right before the error causing line.  How is this possible? What can I do to fix this? Any help is appreciated!


问:
Puzzled with the workings of these variable assignments?
Tried to figure out the working logic behind the results. I couldn't.

Could someone please help explain how Javascript works the output of each of the 4 situations and the reason behind it?

I think the 1st and 2nd are similar situations.

Thanks

var num = (1, 2, 3);    // num = 3 (last number returned, No error generated)
   console.log(num)

y = (1, 2, 3);          // y = 3  (last number returned, No error generated)
   console.log(y)

z = 1, 2, 3;            // z = 1  (first number returned, No error generated)
   console.log(z)

// Uncomment the following to run: (gives an error)

//var m = 1, 2, 3;        // Error: Unexpected number ```

答:
In var num = (1, 2, 3); num is being set to the value of the final expression in the set. It's like a shorthand to evaluate multiple expressions and return the last value.

y = (1, 2, 3); is the same thing when you're at top level scope.

z = 1, 2, 3; is three expressions, z = 1, 2, and 3. z is set to 1, but if you logged the output of that line, you'd get 3.

var m = 1, 2, 3; is a syntax error because in this situation, the interpreter is expecting a single var pattern like var m = 1, n = 2, o = 3.


问:
What is shortcut for uncomment in Visual Studio Code?
Old way with CTRL + K CTRL + C works for commenting but old way CTRL + K CTRL + U not working anymore for uncomment, if anyone know new shortcut I will be grateful.
Thanks.

答:
What worked for me is :
CTRL + Shift + K


问:
Why int i = 2; printf("%d%d%d",i*=2,++i,i++) ouput 882
code:

#include <stdio.h>

int main()
{
    int i = 2;
    printf("%d%d%d\n", i*=2, ++i, i++);
    return 0;
}
```

<p>output:</p>

```882
```

Why the second number is 8

答:
The output is undefined behaviour. There's no answer to this question. Arguments can be evaluated in any order and using pre and post-increment operators in the same expression is asking for trouble.

In other words, that output is arbitrary because you can't depend on those behaviours.

Body:
code:

#include <stdio.h>

int main()
{
    int i = 2;
    printf("%d%d%d\n", i*=2, ++i, i++);
    return 0;
}

output:

882

Why the second number is 8


问:
SQL Server ignores gel symbol
Why does Server ignore the ₾ symbol ?

Why this:

```<code>print iif(N'₾' = N'', 'true', 'false')
</code>```

is the same as:

```<code>print iif(N'₾2' = N'2', 'true', 'false')
</code>```

What role does collation play in this situation and what is happening under the hood?

答:
It looks to me that this is an issue related to the Unicode version when the character was introduced and the type of SQL Server collation that is used:

The € character was introduced in Unicode 2.1 and it returns false in all collations

The ₭ character was introduced in Unicode 3.0 and it returns false in the old collations (for example Latin1_General_CI_AS), but it returns true in the collations introduced in SQL Server 2008 (for example Latin1_General_100_CI_AS)

The ẞ character was introduced in Unicode 5.1 and it returns true in most collations, but it returns false in the collations introduced in SQL Server 2017 (for example Japanese_Bushu_Kakusu_140_CI_AS_VSS)

The ₸ character was introduced in Unicode 5.2 and it returns true in all collations (except BIN collations)

The ₾ character was introduced in Unicode 8.0 and it returns true in all collations (except BIN collations)

Title: SQL Server ignores gel symbol

Body:
Why does Server ignore the ₾ symbol ?

Why this:

print iif(N'₾' = N'', 'true', 'false')

is the same as:

print iif(N'₾2' = N'2', 'true', 'false')

What role does collation play in this situation and what is happening under the hood?


问:
Showing Errors on CardCornerRadius and CardElevation
I've defined my layout as below:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@drawable/background"
    android:descendantFocusability="beforeDescendants"
    android:focusableInTouchMode="true"
    tools:context=".MainActivity">

    <android.support.v7.widget.CardView
        xmlns:card_view="http://schemas.android.com/apk/res-auto"
        android:id="@+id/card_view"
        android:layout_gravity="center"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_margin="32dp"
        card_view:cardCornerRadius="8dp"
        card_view:cardElevation="16dp">

        <ScrollView
            android:layout_width="match_parent"
            android:layout_height="match_parent">

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:orientation="vertical"
                android:padding="16dp">

                <TextView
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:text="@string/question1title"
                    style="@style/questionTitle"/>

                <TextView
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:text="@string/question1"
                    style="@style/questionAndAnswers"/>

                <LinearLayout
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:orientation="horizontal">
                    <CheckBox
                        android:id="@+id/checkboxQuest1AnswerMario"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content" />

                    <TextView
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:text="@string/answerMario"/>
                </LinearLayout>

                <LinearLayout
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:orientation="horizontal">
                    <CheckBox
                        android:id="@+id/checkboxQuest1AnswerDonkey"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        />

                    <TextView
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:text="@string/answerDonkeyKong"/>
                </LinearLayout>

                <LinearLayout
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:orientation="horizontal">
                    <CheckBox
                        android:id="@+id/checkboxQuest1AnswerPortal"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        />

                    <TextView
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:text="@string/answerPortal"/>
                </LinearLayout>

                <TextView
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:text="@string/question2title"
                    style="@style/questionTitle"/>

                <TextView
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:text="@string/question2"
                    style="@style/questionAndAnswers"/>

                <RadioGroup xmlns:android="http://schemas.android.com/apk/res/android"
                    android:layout_width="fill_parent"
                    android:layout_height="wrap_content"
                    android:orientation="vertical">
                    <RadioButton android:id="@+id/radio_1979"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:text="@string/answer1979"/>
                    <RadioButton android:id="@+id/radio_1989"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:text="@string/answer1989"/>
                    <RadioButton android:id="@+id/radio_1999"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:text="@string/answer1999"/>
                </RadioGroup>

                <TextView
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:text="@string/question3title"
                    style="@style/questionTitle"/>

                <TextView
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:text="@string/question3"
                    style="@style/questionAndAnswers"/>

                <EditText
                    android:id="@+id/answerInputUserLastName"
                    android:layout_width="fill_parent"
                    android:layout_height="wrap_content"
                    android:hint="@string/LastNameLaraHint"
                    android:inputType="text"
                    android:maxLength="10"/>

                <TextView
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:text="@string/question4title"
                    style="@style/questionTitle"/>

                <TextView
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:text="@string/question4"
                    style="@style/questionAndAnswers"/>

                <RadioGroup xmlns:android="http://schemas.android.com/apk/res/android"
                    android:layout_width="fill_parent"
                    android:layout_height="wrap_content"
                    android:orientation="vertical">
                    <RadioButton android:id="@+id/radio_bioShock"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:text="@string/answerBioShock"/>
                    <RadioButton android:id="@+id/radio_borderlands"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:text="@string/answerBorderlands"/>
                    <RadioButton android:id="@+id/radio_portal"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:text="@string/answerPortal"/>
                </RadioGroup>

                <TextView
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:text="@string/question5title"
                    style="@style/questionTitle"/>

                <TextView
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:text="@string/question5"
                    style="@style/questionAndAnswers"/>

                <LinearLayout
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:orientation="horizontal">
                    <CheckBox
                        android:id="@+id/checkboxQuest5GameBoy"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        />

                    <TextView
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:text="@string/answerGameBoy"/>
                </LinearLayout>

                <LinearLayout
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:orientation="horizontal">
                    <CheckBox
                        android:id="@+id/checkboxQuestPSP"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content" />

                    <TextView
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:text="@string/answerPSP"/>
                </LinearLayout>

                <LinearLayout
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:orientation="horizontal">
                    <CheckBox
                        android:id="@+id/checkboxQuest5Wii"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content" />

                    <TextView
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:text="@string/answerWii"/>
                </LinearLayout>

                <Button
                    android:id="@+id/submitButton"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="@string/submit"
                    android:layout_gravity="center_horizontal"/>
            </LinearLayout>

        </ScrollView>

    </android.support.v7.widget.CardView>

</RelativeLayout>
```

I am getting the following errors in CardCornerRadius and CardElevation:

Android resource linking failed
  D:\AndroidStudioProjects\App\app\src\main\res\layout\activity_main.xml:12:
  AAPT: error: attribute cardCornerRadius (aka
  com.ksaitarun.app:cardCornerRadius) not found.

D:\AndroidStudioProjects\App\app\src\main\res\layout\activity_main.xml:12:
  AAPT: error: attribute cardElevation (aka
  com.ksaitarun.app:cardElevation) not found.

答:
I don't think there is something wrong but something that might help is just using one namespace for all your custom attributes.
In your parent container you are using the app namespace

```<code>xmlns:app="http://schemas.android.com/apk/res-auto"
</code>```

So, you need to use that namespace in the cardview attributes. Just replace card_view with app and remove the namespace in your CardView.

```<code><android.support.v7.widget.CardView
    android:id="@+id/card_view"
    android:layout_gravity="center"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_margin="32dp"
    app:cardCornerRadius="8dp"
    app:cardElevation="16dp">
</code>```

Body:
I've defined my layout as below:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@drawable/background"
    android:descendantFocusability="beforeDescendants"
    android:focusableInTouchMode="true"
    tools:context=".MainActivity">

    <android.support.v7.widget.CardView
        xmlns:card_view="http://schemas.android.com/apk/res-auto"
        android:id="@+id/card_view"
        android:layout_gravity="center"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_margin="32dp"
        card_view:cardCornerRadius="8dp"
        card_view:cardElevation="16dp">

        <ScrollView
            android:layout_width="match_parent"
            android:layout_height="match_parent">

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:orientation="vertical"
                android:padding="16dp">

                <TextView
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:text="@string/question1title"
                    style="@style/questionTitle"/>

                <TextView
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:text="@string/question1"
                    style="@style/questionAndAnswers"/>

                <LinearLayout
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:orientation="horizontal">
                    <CheckBox
                        android:id="@+id/checkboxQuest1AnswerMario"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content" />

                    <TextView
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:text="@string/answerMario"/>
                </LinearLayout>

                <LinearLayout
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:orientation="horizontal">
                    <CheckBox
                        android:id="@+id/checkboxQuest1AnswerDonkey"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        />

                    <TextView
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:text="@string/answerDonkeyKong"/>
                </LinearLayout>

                <LinearLayout
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:orientation="horizontal">
                    <CheckBox
                        android:id="@+id/checkboxQuest1AnswerPortal"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        />

                    <TextView
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:text="@string/answerPortal"/>
                </LinearLayout>

                <TextView
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:text="@string/question2title"
                    style="@style/questionTitle"/>

                <TextView
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:text="@string/question2"
                    style="@style/questionAndAnswers"/>

                <RadioGroup xmlns:android="http://schemas.android.com/apk/res/android"
                    android:layout_width="fill_parent"
                    android:layout_height="wrap_content"
                    android:orientation="vertical">
                    <RadioButton android:id="@+id/radio_1979"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:text="@string/answer1979"/>
                    <RadioButton android:id="@+id/radio_1989"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:text="@string/answer1989"/>
                    <RadioButton android:id="@+id/radio_1999"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:text="@string/answer1999"/>
                </RadioGroup>

                <TextView
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:text="@string/question3title"
                    style="@style/questionTitle"/>

                <TextView
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:text="@string/question3"
                    style="@style/questionAndAnswers"/>

                <EditText
                    android:id="@+id/answerInputUserLastName"
                    android:layout_width="fill_parent"
                    android:layout_height="wrap_content"
                    android:hint="@string/LastNameLaraHint"
                    android:inputType="text"
                    android:maxLength="10"/>

                <TextView
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:text="@string/question4title"
                    style="@style/questionTitle"/>

                <TextView
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:text="@string/question4"
                    style="@style/questionAndAnswers"/>

                <RadioGroup xmlns:android="http://schemas.android.com/apk/res/android"
                    android:layout_width="fill_parent"
                    android:layout_height="wrap_content"
                    android:orientation="vertical">
                    <RadioButton android:id="@+id/radio_bioShock"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:text="@string/answerBioShock"/>
                    <RadioButton android:id="@+id/radio_borderlands"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:text="@string/answerBorderlands"/>
                    <RadioButton android:id="@+id/radio_portal"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:text="@string/answerPortal"/>
                </RadioGroup>

                <TextView
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:text="@string/question5title"
                    style="@style/questionTitle"/>

                <TextView
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:text="@string/question5"
                    style="@style/questionAndAnswers"/>

                <LinearLayout
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:orientation="horizontal">
                    <CheckBox
                        android:id="@+id/checkboxQuest5GameBoy"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        />

                    <TextView
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:text="@string/answerGameBoy"/>
                </LinearLayout>

                <LinearLayout
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:orientation="horizontal">
                    <CheckBox
                        android:id="@+id/checkboxQuestPSP"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content" />

                    <TextView
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:text="@string/answerPSP"/>
                </LinearLayout>

                <LinearLayout
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:orientation="horizontal">
                    <CheckBox
                        android:id="@+id/checkboxQuest5Wii"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content" />

                    <TextView
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:text="@string/answerWii"/>
                </LinearLayout>

                <Button
                    android:id="@+id/submitButton"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="@string/submit"
                    android:layout_gravity="center_horizontal"/>
            </LinearLayout>

        </ScrollView>

    </android.support.v7.widget.CardView>

</RelativeLayout>

I am getting the following errors in CardCornerRadius and CardElevation:

Android resource linking failed
  D:\AndroidStudioProjects\App\app\src\main\res\layout\activity_main.xml:12:
  AAPT: error: attribute cardCornerRadius (aka
  com.ksaitarun.app:cardCornerRadius) not found.

D:\AndroidStudioProjects\App\app\src\main\res\layout\activity_main.xml:12:
  AAPT: error: attribute cardElevation (aka
  com.ksaitarun.app:cardElevation) not found.

Body:
I don't think there is something wrong but something that might help is just using one namespace for all your custom attributes.
In your parent container you are using the app namespace

xmlns:app="http://schemas.android.com/apk/res-auto"

So, you need to use that namespace in the cardview attributes. Just replace card_view with app and remove the namespace in your CardView.

<android.support.v7.widget.CardView
    android:id="@+id/card_view"
    android:layout_gravity="center"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_margin="32dp"
    app:cardCornerRadius="8dp"
    app:cardElevation="16dp">


问:
fill Na values in df according to other columns values
I would need help in R and deal with columns marging infomations depending on patterns.
In order to undestand here is an exemple :

```<code>       Groups                    Names   COL1 COL2 COL3
1      G1 KB640596.1_2-BICs_-__SP1   <NA>   10   30
2      G1  KB640596.1_32-33_-__SP1  YP_98   NA   NA
3      G1  KB640596.1_32-33_-__SP1  YP_99   NA   NA
4      G1  KB640596.1_32-33_-__SP1 YP_100   NA   NA
5      G1  KB640596.1_32-33_-__SP1 YP_101   NA   NA
6      G1 KB640588.1_2-BICs_-__SP1   <NA>   89   28
7      G1  KB640596.1_38-39_-__SP1 YP_102   NA   NA
8      G1  KB640588.1_38-39_-__SP1 YP_103   NA   NA
9      G1  KB640596.1_21-90_-__SP1 YP_102   NA   NA
10     G1  KB640588.1_78-32_-__SP1 YP_102   NA   NA
11     G1  KB640596.1_89-90_-__SP2 YP_104   90   76
12     G2    LO640571_89-90_-__SP3 YP_100   30   90
13     G2    LO640571_89-90_-__SP3 YP_101   40   10
14     G3    LO640571_89-90_-__SP3   YP_2   29   29
15     G3    LO640571_10-20_-__SP3   YP_2   29   29
16     G3    LO640571_09-99_-__SP3   YP_2   29   29
</code>```

From this df I would like for each Groups and each Names that have a -BICs pattern to fill its COL2 COL3 values and remplace them to the other Names that
have the same content part before the first'_'`

so for instance :

Within the G1, only KB640596.1_2-BICs_-__SP1 has a -BICs pattern,
  then I extract the content before the first '_' pattern and get : KB640596.1
    KB640596.1 is also present in other Names then I add COL2 and COL3 values (10   and 30 respectively) to them and get :

```<code>Groups Names COL1 COL2 COL3
G1 KB640596.1_2-BICs_-__SP1 NA 10 30
G1 KB640596.1_2-BICs_-__SP1 YP_98 10 30
G1 KB640596.1_2-BICs_-__SP1 YP_99 10 30
G1 KB640596.1_2-BICs_-__SP1 YP_100 10 30
G1 KB640596.1_2-BICs_-__SP1 YP_101 10 30
G1 KB640588.1_2-BICs_-__SP1 NA 89 28
G1 KB640596.1_2-BICs_-__SP1 YP_102 10 30
G1 KB640588.1_2-BICs_-__SP1 YP_103 89 28
G1 KB640596.1_2-BICs_-__SP1 YP_102 10 30
G1 KB640588.1_2-BICs_-__SP1 YP_102 89 28
G1 KB640596.1_2-BICs_-__SP1 YP_104 90 76
G2 LO640571_89-90_-__SP3 YP_100 30 90
G2 LO640571_89-90_-__SP3 YP_101 40 10
G3 LO640571_89-90_-__SP3   YP_2   29   29
G3 LO640571_10-20_-__SP3   YP_2   29   29
G3 LO640571_09-99_-__SP3   YP_2   29   29
</code>```

If someone had and idea it would be greate

data

```<code>   structure(list(Groups = structure(c(1L, 1L, 1L, 1L, 1L, 1L, 1L,
1L, 1L, 1L, 1L, 2L, 2L, 3L, 3L, 3L), .Label = c("G1", "G2", "G3"
), class = "factor"), Names = structure(c(4L, 6L, 6L, 6L, 6L,
1L, 7L, 2L, 5L, 3L, 8L, 11L, 11L, 11L, 10L, 9L), .Label = c("KB640588.1_2-BICs_-__SP1",
"KB640588.1_38-39_-__SP1", "KB640588.1_78-32_-__SP1", "KB640596.1_2-BICs_-__SP1",
"KB640596.1_21-90_-__SP1", "KB640596.1_32-33_-__SP1", "KB640596.1_38-39_-__SP1",
"KB640596.1_89-90_-__SP2", "LO640571_09-99_-__SP3", "LO640571_10-20_-__SP3",
"LO640571_89-90_-__SP3"), class = "factor"), COL1 = structure(c(NA,
7L, 8L, 1L, 2L, NA, 3L, 4L, 3L, 3L, 5L, 1L, 2L, 6L, 6L, 6L), .Label = c("YP_100",
"YP_101", "YP_102", "YP_103", "YP_104", "YP_2", "YP_98", "YP_99"
), class = "factor"), COL2 = c(10L, NA, NA, NA, NA, 89L, NA,
NA, NA, NA, 90L, 30L, 40L, 29L, 29L, 29L), COL3 = c(30L, NA,
NA, NA, NA, 28L, NA, NA, NA, NA, 76L, 90L, 10L, 29L, 29L, 29L
)), class = "data.frame", row.names = c(NA, -16L))
</code>```

答:
We can create a new column with row number, separate the Name column into two columns based on a delimiter (-). We can divide the data into two groups, one in which we keep groups with "BIC" value in it and another one without it. We fill the COL2, COL3 values by group and join the data to get the final dataframe.

```<code>library(dplyr)
library(tidyr)

df1 <- df %>% mutate(row = row_number())
df2 <- df1 %>%
         separate(Names, paste0('col', 1:2), sep = "-|\\.", extra = "merge") %>%
         group_by(Groups, col1) %>%
         filter(any(grepl('BIC', col2))) %>%
         fill(COL2, COL3) %>%
         mutate(col2 = first(col2)) %>%
         unite(Names, col1, col2, sep = "-")

bind_rows(df2, df1 %>% filter(!row %in% df2$row)) %>%
          arrange(row) %>%
          select(-row)

#   Groups Names                    COL1    COL2  COL3
#   <fct>  <chr>                    <fct>  <int> <int>
# 1 G1     KB640596-1_2-BICs_-__SP1 NA        10    30
# 2 G1     KB640596-1_2-BICs_-__SP1 YP_98     10    30
# 3 G1     KB640596-1_2-BICs_-__SP1 YP_99     10    30
# 4 G1     KB640596-1_2-BICs_-__SP1 YP_100    10    30
# 5 G1     KB640596-1_2-BICs_-__SP1 YP_101    10    30
# 6 G1     KB640588-1_2-BICs_-__SP1 NA        89    28
# 7 G1     KB640596-1_2-BICs_-__SP1 YP_102    10    30
# 8 G1     KB640588-1_2-BICs_-__SP1 YP_103    89    28
# 9 G1     KB640596-1_2-BICs_-__SP1 YP_102    10    30
#10 G1     KB640588-1_2-BICs_-__SP1 YP_102    89    28
#11 G1     KB640596-1_2-BICs_-__SP1 YP_104    90    76
#12 G2     LO640571_89-90_-__SP3    YP_100    30    90
#13 G2     LO640571_89-90_-__SP3    YP_101    40    10
#14 G3     LO640571_89-90_-__SP3    YP_2      29    29
#15 G3     LO640571_10-20_-__SP3    YP_2      29    29
#16 G3     LO640571_09-99_-__SP3    YP_2      29    29
</code>```

Body:
I would need help in R and deal with columns marging infomations depending on patterns.
In order to undestand here is an exemple :

       Groups                    Names   COL1 COL2 COL3
1      G1 KB640596.1_2-BICs_-__SP1   <NA>   10   30
2      G1  KB640596.1_32-33_-__SP1  YP_98   NA   NA
3      G1  KB640596.1_32-33_-__SP1  YP_99   NA   NA
4      G1  KB640596.1_32-33_-__SP1 YP_100   NA   NA
5      G1  KB640596.1_32-33_-__SP1 YP_101   NA   NA
6      G1 KB640588.1_2-BICs_-__SP1   <NA>   89   28
7      G1  KB640596.1_38-39_-__SP1 YP_102   NA   NA
8      G1  KB640588.1_38-39_-__SP1 YP_103   NA   NA
9      G1  KB640596.1_21-90_-__SP1 YP_102   NA   NA
10     G1  KB640588.1_78-32_-__SP1 YP_102   NA   NA
11     G1  KB640596.1_89-90_-__SP2 YP_104   90   76
12     G2    LO640571_89-90_-__SP3 YP_100   30   90
13     G2    LO640571_89-90_-__SP3 YP_101   40   10
14     G3    LO640571_89-90_-__SP3   YP_2   29   29
15     G3    LO640571_10-20_-__SP3   YP_2   29   29
16     G3    LO640571_09-99_-__SP3   YP_2   29   29

From this df I would like for each Groups and each Names that have a -BICs pattern to fill its COL2 COL3 values and remplace them to the other Names that
have the same content part before the first'_'`

so for instance :

Within the G1, only KB640596.1_2-BICs_-__SP1 has a -BICs pattern,
  then I extract the content before the first '_' pattern and get : KB640596.1
    KB640596.1 is also present in other Names then I add COL2 and COL3 values (10   and 30 respectively) to them and get :

Groups Names COL1 COL2 COL3
G1 KB640596.1_2-BICs_-__SP1 NA 10 30
G1 KB640596.1_2-BICs_-__SP1 YP_98 10 30
G1 KB640596.1_2-BICs_-__SP1 YP_99 10 30
G1 KB640596.1_2-BICs_-__SP1 YP_100 10 30
G1 KB640596.1_2-BICs_-__SP1 YP_101 10 30
G1 KB640588.1_2-BICs_-__SP1 NA 89 28
G1 KB640596.1_2-BICs_-__SP1 YP_102 10 30
G1 KB640588.1_2-BICs_-__SP1 YP_103 89 28
G1 KB640596.1_2-BICs_-__SP1 YP_102 10 30
G1 KB640588.1_2-BICs_-__SP1 YP_102 89 28
G1 KB640596.1_2-BICs_-__SP1 YP_104 90 76
G2 LO640571_89-90_-__SP3 YP_100 30 90
G2 LO640571_89-90_-__SP3 YP_101 40 10
G3 LO640571_89-90_-__SP3   YP_2   29   29
G3 LO640571_10-20_-__SP3   YP_2   29   29
G3 LO640571_09-99_-__SP3   YP_2   29   29

If someone had and idea it would be greate

data

   structure(list(Groups = structure(c(1L, 1L, 1L, 1L, 1L, 1L, 1L,
1L, 1L, 1L, 1L, 2L, 2L, 3L, 3L, 3L), .Label = c("G1", "G2", "G3"
), class = "factor"), Names = structure(c(4L, 6L, 6L, 6L, 6L,
1L, 7L, 2L, 5L, 3L, 8L, 11L, 11L, 11L, 10L, 9L), .Label = c("KB640588.1_2-BICs_-__SP1",
"KB640588.1_38-39_-__SP1", "KB640588.1_78-32_-__SP1", "KB640596.1_2-BICs_-__SP1",
"KB640596.1_21-90_-__SP1", "KB640596.1_32-33_-__SP1", "KB640596.1_38-39_-__SP1",
"KB640596.1_89-90_-__SP2", "LO640571_09-99_-__SP3", "LO640571_10-20_-__SP3",
"LO640571_89-90_-__SP3"), class = "factor"), COL1 = structure(c(NA,
7L, 8L, 1L, 2L, NA, 3L, 4L, 3L, 3L, 5L, 1L, 2L, 6L, 6L, 6L), .Label = c("YP_100",
"YP_101", "YP_102", "YP_103", "YP_104", "YP_2", "YP_98", "YP_99"
), class = "factor"), COL2 = c(10L, NA, NA, NA, NA, 89L, NA,
NA, NA, NA, 90L, 30L, 40L, 29L, 29L, 29L), COL3 = c(30L, NA,
NA, NA, NA, 28L, NA, NA, NA, NA, 76L, 90L, 10L, 29L, 29L, 29L
)), class = "data.frame", row.names = c(NA, -16L))

Body:
We can create a new column with row number, separate the Name column into two columns based on a delimiter (-). We can divide the data into two groups, one in which we keep groups with "BIC" value in it and another one without it. We fill the COL2, COL3 values by group and join the data to get the final dataframe.

library(dplyr)
library(tidyr)

df1 <- df %>% mutate(row = row_number())
df2 <- df1 %>%
         separate(Names, paste0('col', 1:2), sep = "-|\\.", extra = "merge") %>%
         group_by(Groups, col1) %>%
         filter(any(grepl('BIC', col2))) %>%
         fill(COL2, COL3) %>%
         mutate(col2 = first(col2)) %>%
         unite(Names, col1, col2, sep = "-")

bind_rows(df2, df1 %>% filter(!row %in% df2$row)) %>%
          arrange(row) %>%
          select(-row)

#   Groups Names                    COL1    COL2  COL3
#   <fct>  <chr>                    <fct>  <int> <int>
# 1 G1     KB640596-1_2-BICs_-__SP1 NA        10    30
# 2 G1     KB640596-1_2-BICs_-__SP1 YP_98     10    30
# 3 G1     KB640596-1_2-BICs_-__SP1 YP_99     10    30
# 4 G1     KB640596-1_2-BICs_-__SP1 YP_100    10    30
# 5 G1     KB640596-1_2-BICs_-__SP1 YP_101    10    30
# 6 G1     KB640588-1_2-BICs_-__SP1 NA        89    28
# 7 G1     KB640596-1_2-BICs_-__SP1 YP_102    10    30
# 8 G1     KB640588-1_2-BICs_-__SP1 YP_103    89    28
# 9 G1     KB640596-1_2-BICs_-__SP1 YP_102    10    30
#10 G1     KB640588-1_2-BICs_-__SP1 YP_102    89    28
#11 G1     KB640596-1_2-BICs_-__SP1 YP_104    90    76
#12 G2     LO640571_89-90_-__SP3    YP_100    30    90
#13 G2     LO640571_89-90_-__SP3    YP_101    40    10
#14 G3     LO640571_89-90_-__SP3    YP_2      29    29
#15 G3     LO640571_10-20_-__SP3    YP_2      29    29
#16 G3     LO640571_09-99_-__SP3    YP_2      29    29


问:
SSH Key: “Permissions 0644 for 'id_rsa.pub' are too open.” on mac
I generate a ssh key pair on my mac and add the public key to my ubuntu server(in fact, it is a virtual machine on my mac),but when I try to login the ubuntu server,it says:

```<code>@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@         WARNING: UNPROTECTED PRIVATE KEY FILE!          @
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
Permissions 0644 for '/Users/tudouya/.ssh/vm/vm_id_rsa.pub' are too open.
It is required that your private key files are NOT accessible by others.
This private key will be ignored.
bad permissions: ignore key: /Users/tudouya/.ssh/vm/vm_id_rsa.pub
Permission denied (publickey,password).
</code>```

I have tried many ways to solve this, change the key file mode, change the folder mode,as some answer on stackoverflow,but it doesn't work.

the key file permission:

```<code>vm dir:
drwxr-xr-x   4 tudouya  staff    136  4 29 10:37 vm

key file:
-rw-------  1 tudouya  staff  1679  4 29 10:30 vm_id_rsa
-rw-r--r--  1 tudouya  staff   391  4 29 10:30 vm_id_rsa.pub
</code>```

please give me some idea...
=========================================

I write the host infomation to ssh_config:

```<code>Host ubuntuvm
    Hostname 10.211.55.17
    PreferredAuthentications publickey
    IdentityFile /Users/tudouya/.ssh/vm/vm_id_rsa.pub
</code>```

I run command "ssh -v ubuntuvm",it displays:

```<code>ssh -v ubuntuvm
OpenSSH_6.2p2, OSSLShim 0.9.8r 8 Dec 2011
debug1: Reading configuration data /etc/ssh_config
debug1: /etc/ssh_config line 20: Applying options for *
debug1: /etc/ssh_config line 103: Applying options for *
debug1: /etc/ssh_config line 175: Applying options for ubuntuvm
debug1: Connecting to 10.211.55.17 [10.211.55.17] port 22.
debug1: Connection established.
debug1: identity file /Users/tudouya/.ssh/vm/vm_id_rsa.pub type 1
debug1: identity file /Users/tudouya/.ssh/vm/vm_id_rsa.pub-cert type -1
debug1: Enabling compatibility mode for protocol 2.0
debug1: Local version string SSH-2.0-OpenSSH_6.2
debug1: Remote protocol version 2.0, remote software version OpenSSH_6.6.1p1 Ubuntu-8
debug1: match: OpenSSH_6.6.1p1 Ubuntu-8 pat OpenSSH*
debug1: SSH2_MSG_KEXINIT sent
debug1: SSH2_MSG_KEXINIT received
debug1: kex: server->client aes128-ctr hmac-md5-etm@openssh.com none
debug1: kex: client->server aes128-ctr hmac-md5-etm@openssh.com none
debug1: SSH2_MSG_KEX_DH_GEX_REQUEST(1024<1024<8192) sent
debug1: expecting SSH2_MSG_KEX_DH_GEX_GROUP
debug1: SSH2_MSG_KEX_DH_GEX_INIT sent
debug1: expecting SSH2_MSG_KEX_DH_GEX_REPLY
debug1: Server host key: RSA 55:6d:4f:0f:23:51:ac:8e:70:01:ec:0e:62:9e:1c:10
debug1: Host '10.211.55.17' is known and matches the RSA host key.
debug1: Found key in /Users/tudouya/.ssh/known_hosts:54
debug1: ssh_rsa_verify: signature correct
debug1: SSH2_MSG_NEWKEYS sent
debug1: expecting SSH2_MSG_NEWKEYS
debug1: SSH2_MSG_NEWKEYS received
debug1: Roaming not allowed by server
debug1: SSH2_MSG_SERVICE_REQUEST sent
debug1: SSH2_MSG_SERVICE_ACCEPT received
debug1: Authentications that can continue: publickey,password
debug1: Next authentication method: publickey
debug1: Offering RSA public key: /Users/tudouya/.ssh/vm/vm_id_rsa.pub
debug1: Server accepts key: pkalg ssh-rsa blen 279
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@         WARNING: UNPROTECTED PRIVATE KEY FILE!          @
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
Permissions 0644 for '/Users/tudouya/.ssh/vm/vm_id_rsa.pub' are too open.
It is required that your private key files are NOT accessible by others.
This private key will be ignored.
bad permissions: ignore key: /Users/tudouya/.ssh/vm/vm_id_rsa.pub
debug1: No more authentication methods to try.
Permission denied (publickey,password).
</code>```

答:
SSH keys are meant to be private so a 644 permission is too open.

Binary references to set Permissions

```<code> r(read) = 4
 w(write) = 2
 x(execute) = 1
</code>```

So by adding these numbers and by passing the summed digit to chmod command,We set the permission of file/directory.
The first digit sets permission for the owner, second digit for group and the third one for all other users on the system who have no right to the file.

```<code>A permission of 644 means
(4+2) = read/write permission for the owner
(4) = read permission for the group
(4) = read permission for all other users

</code>```

By changing the the permission of the file to 400 using

```<code>chmod 400 <filename>
</code>```

solves the issue. As it makes the key read-only accessible to the owner.

Ref: https://www.linux.com/training-tutorials/understanding-linux-file-permissions/

ContentLicense: CC BY-SA 3.0

Body:
I generate a ssh key pair on my mac and add the public key to my ubuntu server(in fact, it is a virtual machine on my mac),but when I try to login the ubuntu server,it says:

@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@         WARNING: UNPROTECTED PRIVATE KEY FILE!          @
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
Permissions 0644 for '/Users/tudouya/.ssh/vm/vm_id_rsa.pub' are too open.
It is required that your private key files are NOT accessible by others.
This private key will be ignored.
bad permissions: ignore key: /Users/tudouya/.ssh/vm/vm_id_rsa.pub
Permission denied (publickey,password).

I have tried many ways to solve this, change the key file mode, change the folder mode,as some answer on stackoverflow,but it doesn't work.

the key file permission:

vm dir:
drwxr-xr-x   4 tudouya  staff    136  4 29 10:37 vm

key file:
-rw-------  1 tudouya  staff  1679  4 29 10:30 vm_id_rsa
-rw-r--r--  1 tudouya  staff   391  4 29 10:30 vm_id_rsa.pub

please give me some idea...
=========================================

I write the host infomation to ssh_config:

Host ubuntuvm
    Hostname 10.211.55.17
    PreferredAuthentications publickey
    IdentityFile /Users/tudouya/.ssh/vm/vm_id_rsa.pub

I run command "ssh -v ubuntuvm",it displays:

ssh -v ubuntuvm
OpenSSH_6.2p2, OSSLShim 0.9.8r 8 Dec 2011
debug1: Reading configuration data /etc/ssh_config
debug1: /etc/ssh_config line 20: Applying options for *
debug1: /etc/ssh_config line 103: Applying options for *
debug1: /etc/ssh_config line 175: Applying options for ubuntuvm
debug1: Connecting to 10.211.55.17 [10.211.55.17] port 22.
debug1: Connection established.
debug1: identity file /Users/tudouya/.ssh/vm/vm_id_rsa.pub type 1
debug1: identity file /Users/tudouya/.ssh/vm/vm_id_rsa.pub-cert type -1
debug1: Enabling compatibility mode for protocol 2.0
debug1: Local version string SSH-2.0-OpenSSH_6.2
debug1: Remote protocol version 2.0, remote software version OpenSSH_6.6.1p1 Ubuntu-8
debug1: match: OpenSSH_6.6.1p1 Ubuntu-8 pat OpenSSH*
debug1: SSH2_MSG_KEXINIT sent
debug1: SSH2_MSG_KEXINIT received
debug1: kex: server->client aes128-ctr hmac-md5-etm@openssh.com none
debug1: kex: client->server aes128-ctr hmac-md5-etm@openssh.com none
debug1: SSH2_MSG_KEX_DH_GEX_REQUEST(1024<1024<8192) sent
debug1: expecting SSH2_MSG_KEX_DH_GEX_GROUP
debug1: SSH2_MSG_KEX_DH_GEX_INIT sent
debug1: expecting SSH2_MSG_KEX_DH_GEX_REPLY
debug1: Server host key: RSA 55:6d:4f:0f:23:51:ac:8e:70:01:ec:0e:62:9e:1c:10
debug1: Host '10.211.55.17' is known and matches the RSA host key.
debug1: Found key in /Users/tudouya/.ssh/known_hosts:54
debug1: ssh_rsa_verify: signature correct
debug1: SSH2_MSG_NEWKEYS sent
debug1: expecting SSH2_MSG_NEWKEYS
debug1: SSH2_MSG_NEWKEYS received
debug1: Roaming not allowed by server
debug1: SSH2_MSG_SERVICE_REQUEST sent
debug1: SSH2_MSG_SERVICE_ACCEPT received
debug1: Authentications that can continue: publickey,password
debug1: Next authentication method: publickey
debug1: Offering RSA public key: /Users/tudouya/.ssh/vm/vm_id_rsa.pub
debug1: Server accepts key: pkalg ssh-rsa blen 279
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@         WARNING: UNPROTECTED PRIVATE KEY FILE!          @
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
Permissions 0644 for '/Users/tudouya/.ssh/vm/vm_id_rsa.pub' are too open.
It is required that your private key files are NOT accessible by others.
This private key will be ignored.
bad permissions: ignore key: /Users/tudouya/.ssh/vm/vm_id_rsa.pub
debug1: No more authentication methods to try.
Permission denied (publickey,password).

Body:
SSH keys are meant to be private so a 644 permission is too open.

Binary references to set Permissions

 r(read) = 4
 w(write) = 2
 x(execute) = 1

So by adding these numbers and by passing the summed digit to chmod command,We set the permission of file/directory.
The first digit sets permission for the owner, second digit for group and the third one for all other users on the system who have no right to the file.

A permission of 644 means
(4+2) = read/write permission for the owner
(4) = read permission for the group
(4) = read permission for all other users

By changing the the permission of the file to 400 using

chmod 400 <filename>

solves the issue. As it makes the key read-only accessible to the owner.

Ref: https://www.linux.com/training-tutorials/understanding-linux-file-permissions/


问:
How to merge "sourced" bash scripts to single bash script
I wrote a bash script tool, which contains main.sh, common.sh, config.sh. The main.sh used the commond source to load relative files.

I want to merge all files to single file for the convenience of distribution. Is there any best practice for that?

答:
Consider the following script from: Replacing 'source file' with its content, and expanding variables, in bash

It will "inline" the sourced file (referneced by '.' or by 'source' statement). It does not support calling source with parameters, locating files thru the PATH env var, etc. Hopefully, you do not need those features.

```<code>#!/usr/bin/env bash
while read line; do
    if [[ "$line" =~ (\.|source)\s+.+ ]]; then
        file="$(echo $line | cut -d' ' -f2)"
        echo "$(cat $file)"
    else
      echo "$line"
    fi
done < "$1"
</code>```

Body:
Consider the following script from: Replacing 'source file' with its content, and expanding variables, in bash

It will "inline" the sourced file (referneced by '.' or by 'source' statement). It does not support calling source with parameters, locating files thru the PATH env var, etc. Hopefully, you do not need those features.

#!/usr/bin/env bash
while read line; do
    if [[ "$line" =~ (\.|source)\s+.+ ]]; then
        file="$(echo $line | cut -d' ' -f2)"
        echo "$(cat $file)"
    else
      echo "$line"
    fi
done < "$1"


问:
Spark JDBC read ends up in one partition only
I have the below code snippet for reading data from a Postgresql table from where I am pulling all available data i.e. select * from table_name :

```<code> jdbcDF = spark.read \
    .format("jdbc") \
    .option("url", self.var_dict['jdbc_url']) \
    .option("dbtable", "({0}) as subq".format(query)) \
    .option("user", self.var_dict['db_user']) \
    .option("password", self.var_dict['db_password']) \
    .option("driver", self.var_dict['db_driver']) \
    .option("numPartitions", 10) \
    .option("fetchsize", 10000) \
    .load()
</code>```

Where var_dict is a dictionary containing my variables likes spark context , database creds etc.

Even when I am pulling millions of rows the result from below code returns 1 always:

```<code>partitions_num = jdbcDF.rdd.getNumPartitions()
</code>```

Can someone advise if I am doing something wrong here? Ideally I would be expected to use maximum available resources rather then pulling the data to my master node only.

partitionColumn, lowerBound, upperBound cannot be used as my partition column is a timestamp and not numeric.

答:
From spark 2.4.0, date and timestamp column is also supported for partitioning,
https://issues.apache.org/jira/browse/SPARK-22814</p>

Body:
I have the below code snippet for reading data from a Postgresql table from where I am pulling all available data i.e. select * from table_name :

 jdbcDF = spark.read \
    .format("jdbc") \
    .option("url", self.var_dict['jdbc_url']) \
    .option("dbtable", "({0}) as subq".format(query)) \
    .option("user", self.var_dict['db_user']) \
    .option("password", self.var_dict['db_password']) \
    .option("driver", self.var_dict['db_driver']) \
    .option("numPartitions", 10) \
    .option("fetchsize", 10000) \
    .load()

Where var_dict is a dictionary containing my variables likes spark context , database creds etc.

Even when I am pulling millions of rows the result from below code returns 1 always:

partitions_num = jdbcDF.rdd.getNumPartitions()

Can someone advise if I am doing something wrong here? Ideally I would be expected to use maximum available resources rather then pulling the data to my master node only.

partitionColumn, lowerBound, upperBound cannot be used as my partition column is a timestamp and not numeric.


问:
Time complexity analyze
Im trying to compute and analyze this here.

```<code>public static long double_for_loop(int z){
      long result = 0;
      for(int i =0; i<z;i++){
         for(int j =i + 1; j>i; j--){
            result +=(i*j);
         }
      }
    return result;
   }
</code>```

Need help in solving the time-complexity for each sequence of statements.I want to know the steps in solving it.

答:
For z =4 the process (inner loop) goes like this :

I=0, J runs for 1 step ==> O(1) , a constant time

I=1, J runs for 1 step ==> O(1), a constant time

I=2, J runs for 1 step ==> O(1) , a constant time

I=3, J runs for 1 step ==> O(1) , a constant time

So you have a O(1)  which is a constant time regardless how big Z value is. Some people I see write this as O(4) but normally we just write it as O(1). Generally O(C1) is seen as O(C2) for any positive integer constant C1 and C2. So it doesn't matter if you just write it as O(1). The point is C value doesn't depend on input Z size . The scenario will be different if it was J=Z instead of J=I+1. In that case the inner loop turns out to be linear O(Z) coz it depends on Z.

So overall you get  O(Z) for the outer  * O(1) for the inner  part which is an O(Z) linear time complexity.

Title: Time complexity analyze

Body:
Im trying to compute and analyze this here.

public static long double_for_loop(int z){
      long result = 0;
      for(int i =0; i<z;i++){
         for(int j =i + 1; j>i; j--){
            result +=(i*j);
         }
      }
    return result;
   }

Need help in solving the time-complexity for each sequence of statements.I want to know the steps in solving it.


问:
Android resource linking failed AAPT: unknown option '--proguard-minimal-keep-rules'
My Android Studio was working fine, everything was good but after updating Android Studio to the latest version and updating gradle I got the following error

Could you please provide the solution, thank you

Task :app:processDebugResources FAILED
AGPBI: {"kind":"error","text":"Android resource linking failed","sources":[{}],"original":"AAPT: unknown option '--proguard-minimal-keep-rules'.\n\naapt2 link [options] -o arg --manifest arg files...\n\nOptions:\n -o arg                                            Output path.\n --manifest arg                                    Path to the Android manifest to build.\n -I arg                                            Adds an Android APK to link against.\n -A arg                                            An assets directory to include in the APK. These are unprocessed.\n -R arg                                            Compilation unit to link, using overlay semantics.\n                                                   The last conflicting resource given takes precedence.\n --package-id arg                                  Specify the package ID to use for this app. Must be greater or equal to\n                                                   0x7f and can't be used with --static-lib or --shared-lib.\n --java arg                                        Directory in which to generate R.java.\n --proguard arg                                    Output file for generated Proguard rules.\n --proguard-main-dex arg                           Output file for generated Proguard rules for the main dex.\n --proguard-conditional-keep-rules                 Generate conditional Proguard keep rules.\n --no-auto-version                                 Disables automatic style and layout SDK versioning.\n --no-version-vectors                              Disables automatic versioning of vector drawables. Use this only\n                                                   when building with vector drawable support library.\n --no-version-transitions                          Disables automatic versioning of transition resources. Use this only\n                                                   when building with transition support library.\n --no-resource-deduping                            Disables automatic deduping of resources with\n                                                   identical values across compatible configurations.\n --enable-sparse-encoding                          This decreases APK size at the cost of resource retrieval performance.\n -x                                                Legacy flag that specifies to use the package identifier 0x01.\n -z                                                Require localization of strings marked 'suggested'.\n -c arg                                            Comma separated list of configurations to include. The default\n                                                   is all configurations.\n --preferred-density arg                           Selects the closest matching density and strips out all others.\n --product arg                                     Comma separated list of product names to keep\n --output-to-dir                                   Outputs the APK contents to a directory specified by -o.\n --no-xml-namespaces                               Removes XML namespace prefix and URI information\n                                                   from AndroidManifest.xml and XML binaries in res/*.\n --min-sdk-version arg                             Default minimum SDK version to use for AndroidManifest.xml.\n --target-sdk-version arg                          Default target SDK version to use for AndroidManifest.xml.\n --version-code arg                                Version code (integer) to inject into the AndroidManifest.xml if none is\n                                                   present.\n --version-code-major arg                          Version code major (integer) to inject into the AndroidManifest.xml if none is\n                                                   present.\n --version-name arg                                Version name to inject into the AndroidManifest.xml if none is present.\n --replace-version                                 If --version-code and/or --version-name are specified, these\n                                                   values will replace any value already in the manifest. By\n                                                   default, nothing is changed if the manifest already defines\n                                                   these attributes.\n --compile-sdk-version-code arg                    Version code (integer) to inject into the AndroidManifest.xml if none is\n                                                   present.\n --compile-sdk-version-name arg                    Version name to inject into the AndroidManifest.xml if none is present.\n --shared-lib                                      Generates a shared Android runtime library.\n --static-lib                                      Generate a static Android library.\n --proto-format                                    Generates compiled resources in Protobuf format.\n                                                   Suitable as input to the bundle tool for generating an App Bundle.\n --no-static-lib-packages                          Merge all library resources under the app's package.\n --non-final-ids                                   Generates R.java without the final modifier. This is implied when\n                                                   --static-lib is specified.\n --stable-ids arg                                  File containing a list of name to ID mapping.\n --emit-ids arg                                    Emit a file at the given path with a list of name to ID mappings,\n                                                   suitable for use with --stable-ids.\n --private-symbols arg                             Package name to use when generating R.java for private symbols.\n                                                   If not specified, public and private symbols will use the application's\n                                                   package name.\n --custom-package arg                              Custom Java package under which to generate R.java.\n --extra-packages arg                              Generate the same R.java but with different package names.\n --add-javadoc-annotation arg                      Adds a JavaDoc annotation to all generated Java classes.\n --output-text-symbols arg                         Generates a text file containing the resource symbols of the R class in\n                                                   the specified folder.\n --allow-reserved-package-id                       Allows the use of a reserved package ID. This should on be used for\n                                                   packages with a pre-O min-sdk\n                                                   \n --auto-add-overlay                                Allows the addition of new resources in overlays without\n                                                    tags.\n --rename-manifest-package arg                     Renames the package in AndroidManifest.xml.\n --rename-instrumentation-target-package arg       Changes the name of the target package for instrumentation. Most useful\n                                                   when used in conjunction with --rename-manifest-package.\n -0 arg                                            File extensions not to compress.\n --no-compress                                     Do not compress any resources.\n --warn-manifest-validation                        Treat manifest validation errors as warnings.\n --split arg                                       Split resources matching a set of configs out to a Split APK.\n                                                   Syntax: path/to/output.apk:[,[...]].\n                                                   On Windows, use a semicolon ';' separator instead.\n -v                                                Enables verbose logging.\n --debug-mode                                      Inserts android:debuggable=\"true\" in to the application node of the\n                                                   manifest, making the application debuggable even on production devices.\n --strict-visibility                               Do not allow overlays with different visibility levels.\n -h                                                Displays this help menu\n\n    ","tool":"AAPT"}
AAPT: unknown option '--proguard-minimal-keep-rules'.

aapt2 link [options] -o arg --manifest arg files...

Options:
 -o arg                                            Output path.
 --manifest arg                                    Path to the Android manifest to build.
 -I arg                                            Adds an Android APK to link against.
 -A arg                                            An assets directory to include in the APK. These are unprocessed.
 -R arg                                            Compilation unit to link, using overlay semantics.
                                                   The last conflicting resource given takes precedence.
 --package-id arg                                  Specify the package ID to use for this app. Must be greater or equal to
                                                   0x7f and can't be used with --static-lib or --shared-lib.
 --java arg                                        Directory in which to generate R.java.
 --proguard arg                                    Output file for generated Proguard rules.
 --proguard-main-dex arg                           Output file for generated Proguard rules for the main dex.
 --proguard-conditional-keep-rules                 Generate conditional Proguard keep rules.
 --no-auto-version                                 Disables automatic style and layout SDK versioning.
 --no-version-vectors                              Disables automatic versioning of vector drawables. Use this only
                                                   when building with vector drawable support library.
 --no-version-transitions                          Disables automatic versioning of transition resources. Use this only
                                                   when building with transition support library.
 --no-resource-deduping                            Disables automatic deduping of resources with
                                                   identical values across compatible configurations.
 --enable-sparse-encoding                          This decreases APK size at the cost of resource retrieval performance.
 -x                                                Legacy flag that specifies to use the package identifier 0x01.
 -z                                                Require localization of strings marked 'suggested'.
 -c arg                                            Comma separated list of configurations to include. The default
                                                   is all configurations.
 --preferred-density arg                           Selects the closest matching density and strips out all others.
 --product arg                                     Comma separated list of product names to keep
 --output-to-dir                                   Outputs the APK contents to a directory specified by -o.
 --no-xml-namespaces                               Removes XML namespace prefix and URI information
                                                   from AndroidManifest.xml and XML binaries in res/*.
 --min-sdk-version arg                             Default minimum SDK version to use for AndroidManifest.xml.
 --target-sdk-version arg                          Default target SDK version to use for AndroidManifest.xml.
 --version-code arg                                Version code (integer) to inject into the AndroidManifest.xml if none is
                                                   present.
 --version-code-major arg                          Version code major (integer) to inject into the AndroidManifest.xml if none is
                                                   present.
 --version-name arg                                Version name to inject into the AndroidManifest.xml if none is present.
 --replace-version                                 If --version-code and/or --version-name are specified, these
                                                   values will replace any value already in the manifest. By
                                                   default, nothing is changed if the manifest already defines
                                                   these attributes.
 --compile-sdk-version-code arg                    Version code (integer) to inject into the AndroidManifest.xml if none is
                                                   present.
 --compile-sdk-version-name arg                    Version name to inject into the AndroidManifest.xml if none is present.
 --shared-lib                                      Generates a shared Android runtime library.
 --static-lib                                      Generate a static Android library.
 --proto-format                                    Generates compiled resources in Protobuf format.
                                                   Suitable as input to the bundle tool for generating an App Bundle.
 --no-static-lib-packages                          Merge all library resources under the app's package.
 --non-final-ids                                   Generates R.java without the final modifier. This is implied when
                                                   --static-lib is specified.
 --stable-ids arg                                  File containing a list of name to ID mapping.
 --emit-ids arg                                    Emit a file at the given path with a list of name to ID mappings,
                                                   suitable for use with --stable-ids.
 --private-symbols arg                             Package name to use when generating R.java for private symbols.
                                                   If not specified, public and private symbols will use the application's
                                                   package name.
 --custom-package arg                              Custom Java package under which to generate R.java.
 --extra-packages arg                              Generate the same R.java but with different package names.
 --add-javadoc-annotation arg                      Adds a JavaDoc annotation to all generated Java classes.
 --output-text-symbols arg                         Generates a text file containing the resource symbols of the R class in
                                                   the specified folder.
 --allow-reserved-package-id                       Allows the use of a reserved package ID. This should on be used for
                                                   packages with a pre-O min-sdk

--auto-add-overlay                                Allows the addition of new resources in overlays without
                                                    tags.
 --rename-manifest-package arg                     Renames the package in AndroidManifest.xml.
 --rename-instrumentation-target-package arg       Changes the name of the target package for instrumentation. Most useful
                                                   when used in conjunction with --rename-manifest-package.
 -0 arg                                            File extensions not to compress.
 --no-compress                                     Do not compress any resources.
 --warn-manifest-validation                        Treat manifest validation errors as warnings.
 --split arg                                       Split resources matching a set of configs out to a Split APK.
                                                   Syntax: path/to/output.apk:[,[...]].
                                                   On Windows, use a semicolon ';' separator instead.
 -v                                                Enables verbose logging.
 --debug-mode                                      Inserts android:debuggable="true" in to the application node of the
                                                   manifest, making the application debuggable even on production devices.
 --strict-visibility                               Do not allow overlays with different visibility levels.
 -h                                                Displays this help menu

答:
This is a common issue
Try these basic solutions:
(Check if it works after trying every solution)

File->Invalidate Cache and restart

Build -> clean project.

Delete the build folder from your code.

Make sure that you have updated all dependencies in the project-level Gradle

file.


问:
Google Cloud Storage vs Google Cloud CDN
I have several video content that I share through my Google Cloud Storage through my Django Google App Engine Application with signed url mechanism associated with an expiration time.

```<code>def get_signed_url(self, entity):
    blob = bucket.get_blob(entity.url)
    logging.info(entity.url)
    expiration_time = timezone.now() + timedelta(minutes=120)
    signed_url = blob.generate_signed_url(expiration_time)
    logging.info(signed_url)

    return signed_url
</code>```

Although it has been explained in [here][1] possible usage relationship of GCS and Google Cloud CDN, would this be applicable to stream video content (MP4 or MPEG-DASH with MP4) through Google Cloud Storage as it is mentioned to have an implicit CDN itself.

If using Google CDN is a wiser way to broadcast online video content, what would be the best strategy to achieve this, how can I use the Google Cloud CDN on top of my current implementation with Google Cloud Storage ?

答:
To answer your question of how can I use the Google Cloud CDN on top of my current implementation with Google Cloud Storage on your django. You can base your implementation below with django-storages

requirements.txt (the versions are the latest up to this day: 05-31-2020)

```<code>...
django-storages==1.19.1
google-cloud-storage==1.28.1
</code>```

example/example/settings.py

```<code>...
...
SB_SA_FILE = os.environ.get('STORAGE_BUCKETS_FILE',
                            'storageBucketsBackendServiceKey.json')
STATICFILES_STORAGE = 'example.lib.storages.GoogleStaticFilesStorage'  # static
DEFAULT_FILE_STORAGE = 'example.lib.storages.GoogleMediaFilesStorage'  # media
GS_AUTO_CREATE_BUCKET = True
GS_DEFAULT_ACL = 'publicRead'
GS_CREDENTIALS = service_account.Credentials.from_service_account_file(
    f'/usr/src/app/{SB_SA_FILE}'
)
GS_BUCKET_NAME = os.environ.get('GS_BUCKET_NAME')
CDN_HOSTNAME = os.environ.get('CDN_HOSTNAME', '')
</code>```

example/example/lib/storages.py

```<code>from django.conf import settings
from storages.backends.gcloud import GoogleCloudStorage

class GoogleMediaFilesStorage(GoogleCloudStorage):

    def _save(self, name, content):
        name = f'{settings.MEDIA_URL[1:]}{name}'
        return super()._save(name, content)

    def url(self, name):
        """
        @brief      for implementation of CDN using image field url
        @return     Dynamic return of CDN or local URL
        """
        if settings.CDN_HOSTNAME:
            url = f'{settings.CDN_HOSTNAME}/{name}'
            return url
        return super().url(name)

class GoogleStaticFilesStorage(GoogleCloudStorage):
    def url(self, name):
        name = f'static/{name}'
        if settings.CDN_HOSTNAME:
            url = f'{settings.CDN_HOSTNAME}/{name}'
            return url
        return super().url(name)
</code>```

Lastly, you need to run your django application with a CDN_HOSTNAME environment variable. The value of CDN_HOSTNAME environment variable must be the domain mapped in your Google Cloud Global Load Balancer which your desired Cloud Storage is set as a backend bucket

Body:
I have several video content that I share through my Google Cloud Storage through my Django Google App Engine Application with signed url mechanism associated with an expiration time.

def get_signed_url(self, entity):
    blob = bucket.get_blob(entity.url)
    logging.info(entity.url)
    expiration_time = timezone.now() + timedelta(minutes=120)
    signed_url = blob.generate_signed_url(expiration_time)
    logging.info(signed_url)

    return signed_url

Although it has been explained in [here][1] possible usage relationship of GCS and Google Cloud CDN, would this be applicable to stream video content (MP4 or MPEG-DASH with MP4) through Google Cloud Storage as it is mentioned to have an implicit CDN itself.

If using Google CDN is a wiser way to broadcast online video content, what would be the best strategy to achieve this, how can I use the Google Cloud CDN on top of my current implementation with Google Cloud Storage ?

Body:
To answer your question of how can I use the Google Cloud CDN on top of my current implementation with Google Cloud Storage on your django. You can base your implementation below with django-storages

requirements.txt (the versions are the latest up to this day: 05-31-2020)

...
django-storages==1.19.1
google-cloud-storage==1.28.1

example/example/settings.py

...
...
SB_SA_FILE = os.environ.get('STORAGE_BUCKETS_FILE',
                            'storageBucketsBackendServiceKey.json')
STATICFILES_STORAGE = 'example.lib.storages.GoogleStaticFilesStorage'  # static
DEFAULT_FILE_STORAGE = 'example.lib.storages.GoogleMediaFilesStorage'  # media
GS_AUTO_CREATE_BUCKET = True
GS_DEFAULT_ACL = 'publicRead'
GS_CREDENTIALS = service_account.Credentials.from_service_account_file(
    f'/usr/src/app/{SB_SA_FILE}'
)
GS_BUCKET_NAME = os.environ.get('GS_BUCKET_NAME')
CDN_HOSTNAME = os.environ.get('CDN_HOSTNAME', '')

example/example/lib/storages.py

from django.conf import settings
from storages.backends.gcloud import GoogleCloudStorage

class GoogleMediaFilesStorage(GoogleCloudStorage):

    def _save(self, name, content):
        name = f'{settings.MEDIA_URL[1:]}{name}'
        return super()._save(name, content)

    def url(self, name):
        """
        @brief      for implementation of CDN using image field url
        @return     Dynamic return of CDN or local URL
        """
        if settings.CDN_HOSTNAME:
            url = f'{settings.CDN_HOSTNAME}/{name}'
            return url
        return super().url(name)

class GoogleStaticFilesStorage(GoogleCloudStorage):
    def url(self, name):
        name = f'static/{name}'
        if settings.CDN_HOSTNAME:
            url = f'{settings.CDN_HOSTNAME}/{name}'
            return url
        return super().url(name)

Lastly, you need to run your django application with a CDN_HOSTNAME environment variable. The value of CDN_HOSTNAME environment variable must be the domain mapped in your Google Cloud Global Load Balancer which your desired Cloud Storage is set as a backend bucket


问:
Why doesn't the move constructor get called in this contrived example?
Shouldn't the un-named return value from GetPerson bind to the move constructor?

person.hpp

```<code>#ifndef PERSON_H
#define PERSON_H

#include <string>

struct Person {

    Person(std::string name, int age) : name(name), age(age) {
        std::cout << "ctor" << std::endl;
    }

    Person(const Person& rhs) : name(rhs.name), age(rhs.age) {
        std::cout << "copy ctor" <<  std::endl;
    }

    Person(Person&& rhs) : name(std::move(rhs.name)), age(std::move(rhs.age)) {
        std::cout << "move ctor" <<  std::endl;
    }

    ~Person() {
        std::cout << "dtor" << std::endl;
    }

    std::string name;
    int age;
};

#endif
</code>```

main.cpp

```<code>#include <iostream>
#include "person.hpp"

Person GetPerson(std::string name, int age) {
    return Person(name, age);
}

int main(int argc, char* argv[]) {
    Person p(GetPerson("X", 21));
}
</code>```

I'm using gcc version 4.4.3 (Ubuntu 4.4.3-4ubuntu5) and compiling with:

```<code>gcc -g -x c++ -lstdc++ -std=c++0x -o main ./main.cpp
</code>```

Is RVO or NRVO the cause?

答:
Whether the move constructor is called or not is unimportant.  What's important is that the COPY constructor is NOT called.

If your code relies on the move constructor being called here, it is broken, per [class.copy] p31.

Body:
Shouldn't the un-named return value from GetPerson bind to the move constructor?

person.hpp

#ifndef PERSON_H
#define PERSON_H

#include <string>

struct Person {

    Person(std::string name, int age) : name(name), age(age) {
        std::cout << "ctor" << std::endl;
    }

    Person(const Person& rhs) : name(rhs.name), age(rhs.age) {
        std::cout << "copy ctor" <<  std::endl;
    }

    Person(Person&& rhs) : name(std::move(rhs.name)), age(std::move(rhs.age)) {
        std::cout << "move ctor" <<  std::endl;
    }

    ~Person() {
        std::cout << "dtor" << std::endl;
    }

    std::string name;
    int age;
};

#endif

main.cpp

#include <iostream>
#include "person.hpp"

Person GetPerson(std::string name, int age) {
    return Person(name, age);
}

int main(int argc, char* argv[]) {
    Person p(GetPerson("X", 21));
}

I'm using gcc version 4.4.3 (Ubuntu 4.4.3-4ubuntu5) and compiling with:

gcc -g -x c++ -lstdc++ -std=c++0x -o main ./main.cpp

Is RVO or NRVO the cause?


问:
How to stop end=' ' from putting the next line on the previous line
I have been given a task to basicly import a text file to a dictionary and then let the user input words to translate from English to an Indigeonous language. This is what i have so far, but when i want to re-ask words to translate, it puts the input question on the previous answer line. I have done all of the translation bits, i just need help with the printing part.

```<code>lan = {}
for line in open('dictionary.txt'):
  en, ab = line.rstrip().split(",")
  lan[en] = ab
req = input('English: ')
while req:
  words = req.split()
  for i in range(len(words)):
    print(lan[words[i]], end=' ')
  req = input('English: ')
</code>```

I get this:

```<code>English: I like python
ngaju kuja-piya malilyi English:
</code>```

But i want to get this:

```<code>English: I like python
ngaju kuja-piya malilyi
English:
</code>```

Thanks in advance!

答:
You can either put a blank print statement before you ask for input like so:

```<code>    for i in range(len(words)):
        print(lan[words[i]], end=' ')
    print()
    req = input('English: ')
</code>```

or just put a newline character before your input statement like so:

```<code>    for i in range(len(words)):
        print(lan[words[i]], end=' ')
    req = input('\nEnglish: ')
</code>```

Body:
I have been given a task to basicly import a text file to a dictionary and then let the user input words to translate from English to an Indigeonous language. This is what i have so far, but when i want to re-ask words to translate, it puts the input question on the previous answer line. I have done all of the translation bits, i just need help with the printing part.

lan = {}
for line in open('dictionary.txt'):
  en, ab = line.rstrip().split(",")
  lan[en] = ab
req = input('English: ')
while req:
  words = req.split()
  for i in range(len(words)):
    print(lan[words[i]], end=' ')
  req = input('English: ')

I get this:

English: I like python
ngaju kuja-piya malilyi English:

But i want to get this:

English: I like python
ngaju kuja-piya malilyi
English:

Thanks in advance!

Body:
You can either put a blank print statement before you ask for input like so:

    for i in range(len(words)):
        print(lan[words[i]], end=' ')
    print()
    req = input('English: ')

or just put a newline character before your input statement like so:

    for i in range(len(words)):
        print(lan[words[i]], end=' ')
    req = input('\nEnglish: ')


问:
verilog signed addition and subtraction
I am having trouble understanding how to handle overflow when adding or subtracting signed numbers in verilog.

When I did this with unsigned numbers, it was very simple:

```<code>input [15:0] A;
input [15:0] B;
input [3:0] S;
output reg [15:0] AddAB;
...
always@(*)
    begin
        {OFAdd, AddAB} <= A + B;
        {OFSub, SubAB} <= A - B;
...
        case(S)
            0:
            begin
                Display <= AddAB;
                DisplayOF <= OFAdd;
            end
            1:
            begin
                Display <= SubAB;
                DisplayOF <= OFSub;
            end
...
</code>```

And I would get the proper output.
But doing the same thing with signed inputs, I get the wrong value for my overflow

```<code>input signed [15:0] A;
input signed [15:0] B;
input [3:0] S;
output reg signed [15:0] AddAB;
...
always@(*)
    begin
        {OFAdd, AddAB} <= A + B;
        {OFSub, SubAB} <= A - B;
...
        case(S)
            0:
            begin
                Display <= AddAB;
                DisplayOF <= OFAdd;
            end
            1:
            begin
                Display <= SubAB;
                DisplayOF <= OFSub;
            end
...
</code>```

For instance, if A =-21846 and B = 88, I get the proper value AddAB = -21758, but I get DisplayOF = 1. The same happens with subtraction. I get the proper value for SubAB but I get an overflow on DisplayOF when I shouldn't.

If it makes any difference, my testbench looks basically like this

```<code>    A = 16'sb1010101010101010;
    B = 16'sd88;
    S = 4'd0;
    #10;

    A = 16'sb1010101010101010;
    B = 16'sd88;
    S = 4'd1;
    #10;
</code>```

I'm not concerned with synthesizability, I just want to figure out how to deal with overflow on unary arithmetic on signed values.

If anyone could point me in the right direction I would be very greatful, thank you!

答:
You have signed overflow if both inputs have the same sign and the result has the opposite sign. See
https://electronics.stackexchange.com/questions/476250/signed-overflow-detection/476254#476254</p>

Title: verilog signed addition and subtraction

Body:
I am having trouble understanding how to handle overflow when adding or subtracting signed numbers in verilog.

When I did this with unsigned numbers, it was very simple:

input [15:0] A;
input [15:0] B;
input [3:0] S;
output reg [15:0] AddAB;
...
always@(*)
    begin
        {OFAdd, AddAB} <= A + B;
        {OFSub, SubAB} <= A - B;
...
        case(S)
            0:
            begin
                Display <= AddAB;
                DisplayOF <= OFAdd;
            end
            1:
            begin
                Display <= SubAB;
                DisplayOF <= OFSub;
            end
...

And I would get the proper output.
But doing the same thing with signed inputs, I get the wrong value for my overflow

input signed [15:0] A;
input signed [15:0] B;
input [3:0] S;
output reg signed [15:0] AddAB;
...
always@(*)
    begin
        {OFAdd, AddAB} <= A + B;
        {OFSub, SubAB} <= A - B;
...
        case(S)
            0:
            begin
                Display <= AddAB;
                DisplayOF <= OFAdd;
            end
            1:
            begin
                Display <= SubAB;
                DisplayOF <= OFSub;
            end
...

For instance, if A =-21846 and B = 88, I get the proper value AddAB = -21758, but I get DisplayOF = 1. The same happens with subtraction. I get the proper value for SubAB but I get an overflow on DisplayOF when I shouldn't.

If it makes any difference, my testbench looks basically like this

    A = 16'sb1010101010101010;
    B = 16'sd88;
    S = 4'd0;
    #10;

    A = 16'sb1010101010101010;
    B = 16'sd88;
    S = 4'd1;
    #10;

I'm not concerned with synthesizability, I just want to figure out how to deal with overflow on unary arithmetic on signed values.

If anyone could point me in the right direction I would be very greatful, thank you!