问:
Refreshing OAuth token using Retrofit without modifying all calls
We are using Retrofit in our Android app, to communicate with an OAuth2 secured server. Everything works great, we use the RequestInterceptor to include the access token with each call.
However there will be times, when the access token will expire, and the token needs to be refreshed. When the token expires, the next call will return with an Unauthorized HTTP code, so that's easy to monitor.
We could modify each Retrofit call the following way:
In the failure callback, check for the error code, if it equals Unauthorized, refresh the OAuth token, then repeat the Retrofit call.
However, for this, all calls should be modified, which is not an easily maintainable, and good solution.
Is there a way to do this without modifying all Retrofit calls?</p>

答:
Using one Interceptor (inject the token) and one Authenticator (refresh operations) do the job but:

I had a double call problem too: the first call always returned a 401:
 the token wasn't inject at the first call (interceptor) and the authenticator was called: two requests were made.

The fix was just to reaffect the request to the build in the Interceptor:

BEFORE:

```<code>private Interceptor getInterceptor() {
    return (chain) -> {
        Request request = chain.request();
        //...
        request.newBuilder()
                .header(AUTHORIZATION, token))
                .build();
        return chain.proceed(request);
    };
}
</code>```

AFTER:

```<code>private Interceptor getInterceptor() {
    return (chain) -> {
        Request request = chain.request();
        //...
        request = request.newBuilder()
                .header(AUTHORIZATION, token))
                .build();
        return chain.proceed(request);
    };
}
</code>```

IN ONE BLOCK:

```<code>private Interceptor getInterceptor() {
    return (chain) -> {
        Request request = chain.request().newBuilder()
                .header(AUTHORIZATION, token))
                .build();
        return chain.proceed(request);
    };
}
</code>```

Hope it helps.

Edit: I didn't find a way to avoid the first call to always returning 401 using only the authenticator and no interceptor

Body:
Using one Interceptor (inject the token) and one Authenticator (refresh operations) do the job but:

I had a double call problem too: the first call always returned a 401:
 the token wasn't inject at the first call (interceptor) and the authenticator was called: two requests were made.

The fix was just to reaffect the request to the build in the Interceptor:

BEFORE:

private Interceptor getInterceptor() {
    return (chain) -> {
        Request request = chain.request();
        //...
        request.newBuilder()
                .header(AUTHORIZATION, token))
                .build();
        return chain.proceed(request);
    };
}

AFTER:

private Interceptor getInterceptor() {
    return (chain) -> {
        Request request = chain.request();
        //...
        request = request.newBuilder()
                .header(AUTHORIZATION, token))
                .build();
        return chain.proceed(request);
    };
}

IN ONE BLOCK:

private Interceptor getInterceptor() {
    return (chain) -> {
        Request request = chain.request().newBuilder()
                .header(AUTHORIZATION, token))
                .build();
        return chain.proceed(request);
    };
}

Hope it helps.

Edit: I didn't find a way to avoid the first call to always returning 401 using only the authenticator and no interceptor


来源: stackexchange

问:
Shortcut to generate an NSRange for entire length of NSString?
Is there a short way to say "entire string" rather than typing out:

```<code>NSMakeRange(0, myString.length)]
</code>```

It seems silly that the longest part of this kind of code is the least important (because I usually want to search/replace within entire string)…

```<code>[myString replaceOccurrencesOfString:@"replace_me"
                          withString:replacementString
                             options:NSCaseInsensitiveSearch
                               range:NSMakeRange(0, myString.length)];
</code>```

答:
Swift 4+, useful for NSRegularExpression and NSAttributedString

```<code>extension String {
    var nsRange : NSRange {
        return NSRange(self.startIndex..., in: self)
    }

    func range(from nsRange: NSRange) -> Range<String.Index>? {
        return Range(nsRange, in: self)
    }
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Is there a short way to say "entire string" rather than typing out:

NSMakeRange(0, myString.length)]

It seems silly that the longest part of this kind of code is the least important (because I usually want to search/replace within entire string)…

[myString replaceOccurrencesOfString:@"replace_me"
                          withString:replacementString
                             options:NSCaseInsensitiveSearch
                               range:NSMakeRange(0, myString.length)];

Body:
Swift 4+, useful for NSRegularExpression and NSAttributedString

extension String {
    var nsRange : NSRange {
        return NSRange(self.startIndex..., in: self)
    }

    func range(from nsRange: NSRange) -> Range<String.Index>? {
        return Range(nsRange, in: self)
    }
}

ContentLicense: CC BY-SA 4.0


问:
Is it possible to index nested attributes with ArangoSearch Views?
I would like to create an ArangoSearch view on the following document:

```<code>  "Title": [
    {
      "lang": "en",
      "value": "Game of thrones"
    },
    {
      "lang": "fr",
      "value": "Throne de fer"
    }
  ]
}
</code>```

I have tried to link the view like this :

```<code>{"links": {
    "SearchTest": {
      "analyzers": [
        "identity",
        "text_en",
        "text_fr"
      ],
      "fields": {
        "Title[0].value": {
          "analyzers": [
            "text_en"
          ]
        },
        "Title[1].value": {
          "analyzers": [
            "text_fr"
          ]
        }
      },
      "includeAllFields": true,
      "storeValues": "id",
      "trackListPositions": false
    }
  }}
</code>```

But I doesn't seem to work

Here's the query

```<code>FOR d IN SearchTestVW SEARCH PHRASE(d.Title[0].value,'Game','text_en') RETURN d
</code>```

It doesn't return any results. Is it even possible to do this? I have tried with root attributes and it works fine. But our documents are structured like this.

答:
Nesting is possible using fields: { "objectName": fields: "fieldName"}. If you define all analyzers on the "root" level and set includeAllFields to true, you don't even need to specify the fields individually.

You have the possibility to use the analyzer at the object level and just define which attributes should be covered by the search index. That reduces the size of the index and you could exclude fields that may just add 'noise' to the results.

```<code>  "links": {
    "SearchTest": {
      "analyzers": [
        "identity"
      ],
      "fields": {
        "Title": {
          "analyzers": [
            "text_en"
          ],
          "fields": {
            "value": {},
            "lang": {}
          }
        }
      },
      "includeAllFields": false,
      "storeValues": "none",
      "trackListPositions": false
</code>```

Now this should work:

FOR d IN SearchTestVW SEARCH PHRASE(d.Title.value,'Game','text_en') RETURN d

Body:
I would like to create an ArangoSearch view on the following document:

  "Title": [
    {
      "lang": "en",
      "value": "Game of thrones"
    },
    {
      "lang": "fr",
      "value": "Throne de fer"
    }
  ]
}

I have tried to link the view like this :

{"links": {
    "SearchTest": {
      "analyzers": [
        "identity",
        "text_en",
        "text_fr"
      ],
      "fields": {
        "Title[0].value": {
          "analyzers": [
            "text_en"
          ]
        },
        "Title[1].value": {
          "analyzers": [
            "text_fr"
          ]
        }
      },
      "includeAllFields": true,
      "storeValues": "id",
      "trackListPositions": false
    }
  }}

But I doesn't seem to work

Here's the query

FOR d IN SearchTestVW SEARCH PHRASE(d.Title[0].value,'Game','text_en') RETURN d

It doesn't return any results. Is it even possible to do this? I have tried with root attributes and it works fine. But our documents are structured like this.

Body:
Nesting is possible using fields: { "objectName": fields: "fieldName"}. If you define all analyzers on the "root" level and set includeAllFields to true, you don't even need to specify the fields individually.

You have the possibility to use the analyzer at the object level and just define which attributes should be covered by the search index. That reduces the size of the index and you could exclude fields that may just add 'noise' to the results.

  "links": {
    "SearchTest": {
      "analyzers": [
        "identity"
      ],
      "fields": {
        "Title": {
          "analyzers": [
            "text_en"
          ],
          "fields": {
            "value": {},
            "lang": {}
          }
        }
      },
      "includeAllFields": false,
      "storeValues": "none",
      "trackListPositions": false

Now this should work:

FOR d IN SearchTestVW SEARCH PHRASE(d.Title.value,'Game','text_en') RETURN d


问:
What is window.Globalization?? It's cited in jQuery UI Spinner
What is window.Globalization?? It's cited in jQuery UI Spinner.

My Googling skills have failed me.

See https://github.com/Bocoup/jquery-ui/raw/master/ui/jquery.ui.spinner.js

Thanks.

答:
I believe that's the jquery-global plugin. Referenced here: https://github.com/jquery/jquery-ui/blob/master/external/jquery.global.js as a resource. The original is here: https://github.com/jquery/jquery-global.

This is just a guess as I'm actually unable to find where the association is made to the window object.


问:
Faster ways of slicing a big data set
I need to slice a large data set in accordance to some specific length. I have made a code but it takes a lot of execution time.

First, i have data frame which consists of values that the large data set to be sliced.

```<code>df
sl no    length_of each_column
1           3
2           20
3           30
4           40
5           50
</code>```

The large data set contains about hundred thousand of rows and somewhat looks like this

```<code>sl no      values
0           10
1           20
3           30
4           40
5           50
6           60
7           10
8           49
9           59
10          20
and so on
</code>```

My resultant data set should slice the large data set by taking values from the data frame which contains length of each column. If suppose length of each column is 3, then it should slice the large data set by 3, then move forward by one row, then again slice 3 data points

Again move forward by one row and slice 3 data points and so on till it takes all possible combinations of required length.

The resultant data set is mentioned below

Resultant data set if sliced by 3

```<code>Resultant data frame for column length 3
sl no    col1     col2   col3  - - - - - - -
0          10      20     30
1          20      30     40
2          30      40     50
</code>```

and so on till it makes all possible combinations of length 3.

答:
Here you go:

```<code>import pandas as pd

# setup test data
slice_options = {'length_of each_column': ['3', '5']}
slice_options = pd.DataFrame(data=slice_options)

data = {'values': ['1', '2', '3', '4', '5', '6', '7', '8', '9']}
data = pd.DataFrame(data=data)

# store data frames in list
out_data = list(range(slice_options.shape[0]))

count = 0
for index, row in slice_options.iterrows():
    # create empty data frame
    out_data[count] = pd.DataFrame()
    # collect data
    for i in range(data.shape[0]):
        # select data rows
        select_data = data.iloc[i:i+int(row.values[0])]
        # handle rows number
        if select_data.shape[0] == int(row.values[0]):
            # fill data frame
            out_data[count]['column' + str(i)] = select_data.values.ravel()
    count += 1
</code>```

Output:

```<code>df1 (3 elements):

  column0 column1 column2 column3 column4 column5 column6
0       1       2       3       4       5       6       7
1       2       3       4       5       6       7       8
2       3       4       5       6       7       8       9

df2 (5 elements):

  column0 column1 column2 column3 column4
0       1       2       3       4       5
1       2       3       4       5       6
2       3       4       5       6       7
3       4       5       6       7       8
4       5       6       7       8       9
</code>```

Title: Faster ways of slicing a big data set

Body:
I need to slice a large data set in accordance to some specific length. I have made a code but it takes a lot of execution time.

First, i have data frame which consists of values that the large data set to be sliced.

df
sl no    length_of each_column
1           3
2           20
3           30
4           40
5           50

The large data set contains about hundred thousand of rows and somewhat looks like this

sl no      values
0           10
1           20
3           30
4           40
5           50
6           60
7           10
8           49
9           59
10          20
and so on

My resultant data set should slice the large data set by taking values from the data frame which contains length of each column. If suppose length of each column is 3, then it should slice the large data set by 3, then move forward by one row, then again slice 3 data points

Again move forward by one row and slice 3 data points and so on till it takes all possible combinations of required length.

The resultant data set is mentioned below

Resultant data set if sliced by 3

Resultant data frame for column length 3
sl no    col1     col2   col3  - - - - - - -
0          10      20     30
1          20      30     40
2          30      40     50

and so on till it makes all possible combinations of length 3.

Body:
Here you go:

import pandas as pd

# setup test data
slice_options = {'length_of each_column': ['3', '5']}
slice_options = pd.DataFrame(data=slice_options)

data = {'values': ['1', '2', '3', '4', '5', '6', '7', '8', '9']}
data = pd.DataFrame(data=data)

# store data frames in list
out_data = list(range(slice_options.shape[0]))

count = 0
for index, row in slice_options.iterrows():
    # create empty data frame
    out_data[count] = pd.DataFrame()
    # collect data
    for i in range(data.shape[0]):
        # select data rows
        select_data = data.iloc[i:i+int(row.values[0])]
        # handle rows number
        if select_data.shape[0] == int(row.values[0]):
            # fill data frame
            out_data[count]['column' + str(i)] = select_data.values.ravel()
    count += 1

Output:

df1 (3 elements):

  column0 column1 column2 column3 column4 column5 column6
0       1       2       3       4       5       6       7
1       2       3       4       5       6       7       8
2       3       4       5       6       7       8       9

df2 (5 elements):

  column0 column1 column2 column3 column4
0       1       2       3       4       5
1       2       3       4       5       6
2       3       4       5       6       7
3       4       5       6       7       8
4       5       6       7       8       9


问:
JavaScript test() Method changes return value
I am writing a small form validation and for some reason, when I call de test() Method, it returns true, and if without changing the input value, when calling the Method again, it returns false, then true again and so on.

This is the form in html it is in a modal:

```<code><form class="modal-content" (submit)="dashboard.altaCliente()">
  <div class="input-group">
    <input type="text" name="" id="clienteNombre" placeholder="Nombre" class="form-control">
    <input type="text" name="" id="clienteApellido" placeholder="Apellidos" class="form-control">
  </div>
  <input type="email" name="" id="clienteEmail" placeholder="Correo electronico" class="form-control my-2">
  <div class="input-group">
    <input type="text" name="" id="clienteDNI" placeholder="DNI" class="form-control">
    <input type="date" name="" id="clienteDate" placeholder="Fecha de nacimiento" class="form-control">
  </div>
  <input type="password" name="" id="clientePasswd" placeholder="Contraseña" class="form-control mt-2">
  <div class="mt-2 alert" role="alert"></div>
  <button type="submit" class="btn btn-primary">Añadir cliente</button>
</form>
</code>```

This is the fragment the function :

```<code>altaCliente() {
const $inputNombre = $("#clienteNombre");
const $inputApellidos = $("#clienteApellido");
const $inputEmail = $("#clienteEmail");
const $inputDNI = $("#clienteDNI");
const $inputDate = $("#clienteDate");
const $inputPasswd = $("#clientePasswd");
const $msg = $(".alert");
let todoOK = true;
$msg.html("");

$inputNombre.on("focus",function(){$(this).removeClass("is-invalid")});
$inputApellidos.on("focus",function(){$(this).removeClass("is-invalid")});
$inputEmail.on("focus",function(){$(this).removeClass("is-invalid")});
$inputDNI.on("focus",function(){$(this).removeClass("is-invalid")});
$inputDate.on("focus",function(){$(this).removeClass("is-invalid")});
$inputPasswd.on("focus",function(){$(this).removeClass("is-invalid")});

//Nombre
if ($inputNombre.val() === "") {
  $msg.html($msg.html() + "Nombre vacio<br>").addClass(["alert-danger", "show"]);
  $inputNombre.addClass("is-invalid");
  todoOK = false;
} else if (!this.regexNombre.test($inputNombre.val().toString())) {
  $msg.html($msg.html() + "Nombre mal formado<br>").addClass(["alert-danger", "show"]);
  $inputNombre.addClass("is-invalid");
  todoOK = false;
}
//Apellidos
if ($inputApellidos.val() === "") {
  $msg.html($msg.html() + "Apellidos vacios<br>").addClass(["alert-danger", "show"]);
  $inputApellidos.addClass("is-invalid");
  todoOK = false;
} else if (!this.regexApellidos.test(<string>$inputApellidos.val())) {
  $msg.html($msg.html() + "Apellidos mal formados<br>").addClass(["alert-danger", "show"]);
  $inputApellidos.addClass("is-invalid");
  todoOK = false;
}

if (todoOK) {
  $msg.html("Usuario añadido con éxito<br>").removeClass("alert-danger").addClass(["alert-success", "show"]);
}
}
</code>```

Right now I am only validating name and surname.

The patterns are properties of the typeScript and are:

/^[aA-zZñÑ]+( [aA-zZñÑ]+)*$/g

The problem comes with the else if, as I have said, test() returns true then when calling the function again it returns false.

To be clear, if for example I write 'John' in the name input and click in the 'send' button it would be valid the first time, invalid the second, valid again the third and so on.

答:
So I finally found out that removing the 'g' at the end of the regex pattern solved the problem.

With /^[aA-zZñÑ]+( [aA-zZñÑ]+)*$/g , return value oscillate between true and false, but   /^[aA-zZñÑ]+( [aA-zZñÑ]+)*$/ works properly.

Body:
I am writing a small form validation and for some reason, when I call de test() Method, it returns true, and if without changing the input value, when calling the Method again, it returns false, then true again and so on.

This is the form in html it is in a modal:

<form class="modal-content" (submit)="dashboard.altaCliente()">

    <input type="text" name="" id="clienteNombre" placeholder="Nombre" class="form-control">
    <input type="text" name="" id="clienteApellido" placeholder="Apellidos" class="form-control">

  <input type="email" name="" id="clienteEmail" placeholder="Correo electronico" class="form-control my-2">

    <input type="text" name="" id="clienteDNI" placeholder="DNI" class="form-control">
    <input type="date" name="" id="clienteDate" placeholder="Fecha de nacimiento" class="form-control">

  <input type="password" name="" id="clientePasswd" placeholder="Contraseña" class="form-control mt-2">

  <button type="submit" class="btn btn-primary">Añadir cliente</button>
</form>

This is the fragment the function :

altaCliente() {
const $inputNombre = $("#clienteNombre");
const $inputApellidos = $("#clienteApellido");
const $inputEmail = $("#clienteEmail");
const $inputDNI = $("#clienteDNI");
const $inputDate = $("#clienteDate");
const $inputPasswd = $("#clientePasswd");
const $msg = $(".alert");
let todoOK = true;
$msg.html("");

$inputNombre.on("focus",function(){$(this).removeClass("is-invalid")});
$inputApellidos.on("focus",function(){$(this).removeClass("is-invalid")});
$inputEmail.on("focus",function(){$(this).removeClass("is-invalid")});
$inputDNI.on("focus",function(){$(this).removeClass("is-invalid")});
$inputDate.on("focus",function(){$(this).removeClass("is-invalid")});
$inputPasswd.on("focus",function(){$(this).removeClass("is-invalid")});

//Nombre
if ($inputNombre.val() === "") {
  $msg.html($msg.html() + "Nombre vacio
").addClass(["alert-danger", "show"]);
  $inputNombre.addClass("is-invalid");
  todoOK = false;
} else if (!this.regexNombre.test($inputNombre.val().toString())) {
  $msg.html($msg.html() + "Nombre mal formado
").addClass(["alert-danger", "show"]);
  $inputNombre.addClass("is-invalid");
  todoOK = false;
}
//Apellidos
if ($inputApellidos.val() === "") {
  $msg.html($msg.html() + "Apellidos vacios
").addClass(["alert-danger", "show"]);
  $inputApellidos.addClass("is-invalid");
  todoOK = false;
} else if (!this.regexApellidos.test(<string>$inputApellidos.val())) {
  $msg.html($msg.html() + "Apellidos mal formados
").addClass(["alert-danger", "show"]);
  $inputApellidos.addClass("is-invalid");
  todoOK = false;
}

if (todoOK) {
  $msg.html("Usuario añadido con éxito
").removeClass("alert-danger").addClass(["alert-success", "show"]);
}
}

Right now I am only validating name and surname.

The patterns are properties of the typeScript and are:

/^[aA-zZñÑ]+( [aA-zZñÑ]+)*$/g

The problem comes with the else if, as I have said, test() returns true then when calling the function again it returns false.

To be clear, if for example I write 'John' in the name input and click in the 'send' button it would be valid the first time, invalid the second, valid again the third and so on.


问:
How do I set activity backstack on Android?
I want to set the onBackPress button to start activities that started before orderly. If I don't finish activities that started before when I start another activity, I can show the activity that started before with finish() current activity. This is possible. Because I don't finish any activity. So finish() current activity will cause show activity that started before. But, RAM will be overload when I open 50 activities may be. So because of this problem I need to finish() activity that started before. On the other hand, I want to start the activity that started before orderly when clicking to the back button. For example

```<code>   ActivityA --> ActivityB --> ActivityC --> ActivityD
</code>```

In this scenario, I finish ActivityA, ActivityB, ActivityC orderly. But I want to start ActivityC back press of the ActivityD and I want to start ActivityB on the back press of ActivityC.

Lastly, I have a complex path in the application. And, I navigate to the ActivityD and I finished the ActivityF when my current activity is ActivityF

```<code> ActivityF --> ActivityD
 ActivityF finished
</code>```

Current activity:

```<code> ActivityD
</code>```

In this scenario, I want to start the ActivityF not the ActivityC on back button of the ActivityD.

Normally:

```<code> ActivityA --> ActivityB --> ActivityC --> ActivityD /// click back button
 ActivityA --> ActivityB --> ActivityC /// click back button
 ActivityA --> ActivityB /// click back button
 ActivityA
</code>```

or

```<code> ActivityA --> ActivityF --> ActivityD /// click back button
 ActivityA --> ActivityF /// click back button
 ActivityA
</code>```

But I want to generate this scenario:

```<code> ActivityA
 --> ActivityB
 --> ActivityC
 --> ActivityD /// click back button
 ActivityC <-- /// click back button
 ActivityB <-- /// click back button
 ActivityA
</code>```

or

```<code> ActivityA
 --> ActivityF
 --> ActivityD /// click back button
 ActivityF <-- /// click back button
 ActivityA <--
</code>```

Update:

I found the solution here

答:
In Activity A do this,

```<code>startActivity(new Intent(ActivityA.this, ActivityB.class));
    finish();
</code>```

This will finish ActivityA when moving to Activity B.

Next, in ActivityB override the onBackPressed in your Activity class and use an intent to revert to the previous activity.

```<code>@Override
public void onBackPressed() {
startActivity(new Intent(ActivityB.this, ActivityA.class));
finish();
}
</code>```

NOTE:

If you do not override onBackPressed then it will go to the Activity before ActivityA (if not available exit from the app).

Links that might help you on getting started with Activity lifecycle:

https://developer.android.com/guide/components/activities/activity-lifecycle

https://developer.android.com/guide/components/activities/tasks-and-back-stack

Body:
I want to set the onBackPress button to start activities that started before orderly. If I don't finish activities that started before when I start another activity, I can show the activity that started before with finish() current activity. This is possible. Because I don't finish any activity. So finish() current activity will cause show activity that started before. But, RAM will be overload when I open 50 activities may be. So because of this problem I need to finish() activity that started before. On the other hand, I want to start the activity that started before orderly when clicking to the back button. For example

   ActivityA --> ActivityB --> ActivityC --> ActivityD

In this scenario, I finish ActivityA, ActivityB, ActivityC orderly. But I want to start ActivityC back press of the ActivityD and I want to start ActivityB on the back press of ActivityC.

Lastly, I have a complex path in the application. And, I navigate to the ActivityD and I finished the ActivityF when my current activity is ActivityF

 ActivityF --> ActivityD
 ActivityF finished

Current activity:

 ActivityD

In this scenario, I want to start the ActivityF not the ActivityC on back button of the ActivityD.

Normally:

 ActivityA --> ActivityB --> ActivityC --> ActivityD /// click back button
 ActivityA --> ActivityB --> ActivityC /// click back button
 ActivityA --> ActivityB /// click back button
 ActivityA

or

 ActivityA --> ActivityF --> ActivityD /// click back button
 ActivityA --> ActivityF /// click back button
 ActivityA

But I want to generate this scenario:

 ActivityA
 --> ActivityB
 --> ActivityC
 --> ActivityD /// click back button
 ActivityC <-- /// click back button
 ActivityB <-- /// click back button
 ActivityA

or

 ActivityA
 --> ActivityF
 --> ActivityD /// click back button
 ActivityF <-- /// click back button
 ActivityA <--

Update:

I found the solution here

Body:
In Activity A do this,

startActivity(new Intent(ActivityA.this, ActivityB.class));
    finish();

This will finish ActivityA when moving to Activity B.

Next, in ActivityB override the onBackPressed in your Activity class and use an intent to revert to the previous activity.

@Override
public void onBackPressed() {
startActivity(new Intent(ActivityB.this, ActivityA.class));
finish();
}

NOTE:

If you do not override onBackPressed then it will go to the Activity before ActivityA (if not available exit from the app).

Links that might help you on getting started with Activity lifecycle:

https://developer.android.com/guide/components/activities/activity-lifecycle

https://developer.android.com/guide/components/activities/tasks-and-back-stack


问:
Responsiveness - iPad in Chrome vs iPad in Mozilla Firefox
I am developing a website in a Windows system. I have Firefox and Chrome browsers installed. When I checked the responsiveness of my webpage by setting the device as iPad(768 X 1024) using 'inspect element' feature in these browsers, I could get different resultant UI for same device. Why is it so? On which browser can I rely on as I don't have any Mac/Apple devices with me to test? I am concerned of using other online web tools due to security issues. Please help. Thanks in advance.</p>

答: Unfortunately there's no real substitute for device testing. Companies like BrowserStack offer real remote device testing but at a cost. With regard to browsers rendering differently, this has always been a pain. Look at CSS resets.</p>


问:
My question is about addition of an array of different wrapper classes through java generics
```<code>public static void doProcess(){
   Integer [] intArray = {2,5,3,8,9};
   returnArray(intArray);
   //Expected output:  27 (sum of all number)
   String[]  strArray =  {"Jack", "Daniel", "Richel"};
   returnArray(strArray);
   //Expected output:  Jack Daniel Richel
   Character[]  charArray = {'A', 'X', 'E'};
   returnArray(charArray);
   //Expected output:  AXE
}
</code>```

I have the above code and the method below which need to complete.

```<code>private static <E> *** returnArray(E[] value) {
    for(E ele : value) {
        //code for expected output
    }
    //return Expected output
}
</code>```

I need to fill above method as well as fill the return type which is here shown as ***.
I can't use separate method or introduce any new method.

答:
You may want to use the instanceof, e.g. you can have a construct like this:

```<code>public static <E> Object returnArray(E[] value) {
    if(value instanceof String[]) {
        String[] strings = (String[]) value;
        // concat the strings with spaces
    } else if(value instanceof Integer[]) {
        Integer[] ints = (Integer[]) value;
        // sum the integers
    } else if(value instanceof Character[]) {
        Character[] chars = (Character[]) value;
        // concat the characters
    } else {
        // throw exception or handle more cases
    }
}
</code>```

I've deliberatly left out the real code for the different operations as this should just point you into the right direction, (and I won't do your work for you).

The only real tricky thing is the return type. As it can't be E. It works with Strings and Integers, but will break with Characters as 'ABC' is not a valid char and thus you can't return it.

Note: using generics and instanceof breaks the whole concept of generics. You can aswell just remove it and have a method like this:

```<code>public static Object returnArray(Object[] value) {
</code>```

Body:
public static void doProcess(){
   Integer [] intArray = {2,5,3,8,9};
   returnArray(intArray);
   //Expected output:  27 (sum of all number)
   String[]  strArray =  {"Jack", "Daniel", "Richel"};
   returnArray(strArray);
   //Expected output:  Jack Daniel Richel
   Character[]  charArray = {'A', 'X', 'E'};
   returnArray(charArray);
   //Expected output:  AXE
}

I have the above code and the method below which need to complete.

private static <E> *** returnArray(E[] value) {
    for(E ele : value) {
        //code for expected output
    }
    //return Expected output
}

I need to fill above method as well as fill the return type which is here shown as ***.
I can't use separate method or introduce any new method.

Body:
You may want to use the instanceof, e.g. you can have a construct like this:

public static <E> Object returnArray(E[] value) {
    if(value instanceof String[]) {
        String[] strings = (String[]) value;
        // concat the strings with spaces
    } else if(value instanceof Integer[]) {
        Integer[] ints = (Integer[]) value;
        // sum the integers
    } else if(value instanceof Character[]) {
        Character[] chars = (Character[]) value;
        // concat the characters
    } else {
        // throw exception or handle more cases
    }
}

I've deliberatly left out the real code for the different operations as this should just point you into the right direction, (and I won't do your work for you).

The only real tricky thing is the return type. As it can't be E. It works with Strings and Integers, but will break with Characters as 'ABC' is not a valid char and thus you can't return it.

Note: using generics and instanceof breaks the whole concept of generics. You can aswell just remove it and have a method like this:

public static Object returnArray(Object[] value) {


问:
how to duplicate MC in macromedia flash 8
I'm having problems to duplicate movie clips in AS2. Can someone help me to get the general idea how I do this?</p>

答:
First of all, the IDE: Right click on a symbol in the library and select 'Duplicate'.

Now, code:

```<code>var duplicate:MovieClip = original.duplicateMovieClip("duplicateClip",this.getNextHighestDepth());
</code>```

What you're doing here is calling the duplicateMovieClip function of your existing clip, telling it a name and depth for your new clip.  It returns a reference to the new clip, which is stored in the duplicate variable.

Body:
First of all, the IDE: Right click on a symbol in the library and select 'Duplicate'.

Now, code:

var duplicate:MovieClip = original.duplicateMovieClip("duplicateClip",this.getNextHighestDepth());

What you're doing here is calling the duplicateMovieClip function of your existing clip, telling it a name and depth for your new clip.  It returns a reference to the new clip, which is stored in the duplicate variable.


问:
How to remove the decimal place when number before decimal is 0
Im trying to remove the decimal places from certain values

for example, my current code is

```<code>select po_id, AVG(price*quantity) * count(*) AS 'Total Cost'
from po_items natural join items
group by po_id;
</code>```

this is the output im getting

```<code>po_id       Total Cost
----------  ----------
AAA         2217.5
BBB         255.0
CCC         5787.5
DDD         10000.0
GGG         1000.0
</code>```

and the output im trying to get is

```<code>po_id       Total Cost
----------  ----------
AAA         2217.5
BBB         255
CCC         5787.5
DDD         10000
GGG         1000
</code>```

答:
OK, as below:

```<code>sqlite> select cost from my_table;
2217.5
255.0
5787.5
10000.0
1000.0

sqlite> select replace(cast(cost as string),'.0','') from my_table;
2217.5
255
5787.5
10000
1000
</code>```

Your complete SQL maybe:

```<code>select
    po_id,
    replace(cast(avg(price*quantity)*count(1) as string),'.0','') as 'Total Cost'
from
    po_items
join
    items
group by
    po_id;
</code>```

Body:
Im trying to remove the decimal places from certain values

for example, my current code is

select po_id, AVG(price*quantity) * count(*) AS 'Total Cost'
from po_items natural join items
group by po_id;

this is the output im getting

po_id       Total Cost
----------  ----------
AAA         2217.5
BBB         255.0
CCC         5787.5
DDD         10000.0
GGG         1000.0

and the output im trying to get is

po_id       Total Cost
----------  ----------
AAA         2217.5
BBB         255
CCC         5787.5
DDD         10000
GGG         1000

Body:
OK, as below:

sqlite> select cost from my_table;
2217.5
255.0
5787.5
10000.0
1000.0

sqlite> select replace(cast(cost as string),'.0','') from my_table;
2217.5
255
5787.5
10000
1000

Your complete SQL maybe:

select
    po_id,
    replace(cast(avg(price*quantity)*count(1) as string),'.0','') as 'Total Cost'
from
    po_items
join
    items
group by
    po_id;


问:
Google Maps API - Multiple keywords in place searches
Is it possible search multiple individual keywords in one place search request using Google Maps JavaScript API v3?

In the Google Places API documentation it states that multiple keywords can be used https://developers.google.com/places/training/additional-places-features

?keyword=theater+gym

but this does not work in the JavaScript API. I tried:

```<code>function performSearch() {
  var request = {
    location: map.center,
    radius: '500',
    keyword: 'theater+gym+tacos',
    rankBy: 'distance'
  };
  service.radarSearch(request, callback);
}
</code>```

...and does not return places for each keyword. Does anyone have an idea how to search multiple keywords?

Note: I'm trying to search multiple individual keywords in one request not a phrase with spaces.

答:
I had the same problem as I tried to figure out how to use multiple keywords with one request. At first the answer of @netoale helped me, but this is no longer possible. After some general problems with Google I asked in the support and one of the employees wrote me that it is possible to link several keywords with a simple "|".

As an example:

```<code>https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=lat,lng&key=API_KEY&keyword=theater|castle|park&rankby=distance
</code>```

Works for me now.

Body:
Is it possible search multiple individual keywords in one place search request using Google Maps JavaScript API v3?

In the Google Places API documentation it states that multiple keywords can be used https://developers.google.com/places/training/additional-places-features

?keyword=theater+gym

but this does not work in the JavaScript API. I tried:

function performSearch() {
  var request = {
    location: map.center,
    radius: '500',
    keyword: 'theater+gym+tacos',
    rankBy: 'distance'
  };
  service.radarSearch(request, callback);
}

...and does not return places for each keyword. Does anyone have an idea how to search multiple keywords?

Note: I'm trying to search multiple individual keywords in one request not a phrase with spaces.

Body:
I had the same problem as I tried to figure out how to use multiple keywords with one request. At first the answer of @netoale helped me, but this is no longer possible. After some general problems with Google I asked in the support and one of the employees wrote me that it is possible to link several keywords with a simple "|".

As an example:

https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=lat,lng&key=API_KEY&keyword=theater|castle|park&rankby=distance

Works for me now.


问:
Tensorflow dilation behave differently than morphological dilation
As the following piece of code shows, the tensorflow tf.nn.dilation2D function doesn't behave as a conventional dilation operator.

```<code>import tensorflow as tf
tf.InteractiveSession()
A = [[0, 0, 0, 0, 0, 0, 0],
     [0, 0, 0, 0, 1, 0, 0],
     [0, 0, 0, 1, 1, 1, 0],
     [0, 0, 0, 0, 1, 0, 0],
     [0, 0, 0, 0, 0, 0, 0],
     [0, 0, 0, 0, 0, 0, 0]]
kernel = tf.ones((3,3,1))
input4D = tf.cast(tf.expand_dims(tf.expand_dims(A, -1), 0), tf.float32)
output4D = tf.nn.dilation2d(input4D, filter=kernel, strides=(1,1,1,1), rates=(1,1,1,1), padding="SAME")
print(tf.cast(output4D[0,:,:,0], tf.int32).eval())
</code>```

Returns the following tensor:

```<code>array([[1, 1, 1, 2, 2, 2, 1],
       [1, 1, 2, 2, 2, 2, 2],
       [1, 1, 2, 2, 2, 2, 2],
       [1, 1, 2, 2, 2, 2, 2],
       [1, 1, 1, 2, 2, 2, 1],
       [1, 1, 1, 1, 1, 1, 1]], dtype=int32)
</code>```

I don't understand neither why it behaves like that, neither how I should use tf.nn.dilation2d to retrieve the expected output:

```<code>array([[0, 0, 0, 1, 1, 1, 0],
       [0, 0, 1, 1, 1, 1, 1],
       [0, 0, 1, 1, 1, 1, 1],
       [0, 0, 1, 1, 1, 1, 1],
       [0, 0, 0, 1, 1, 1, 0],
       [0, 0, 0, 0, 0, 0, 0]], dtype=int32)
</code>```

Can someone enlighten the succinct documentation of tensorflow and give an explanation of what the the tf.nn.dilation2D function does ?

答:
can do it like this:</p>

```<code>def dilation2d(self, img4D):
    '''
    '''
    with tf.variable_scope('dilation2d'):
        kernel = tf.ones((3, 3, img4D.get_shape()[3]))
        output4D = tf.nn.dilation2d(img4D, filter=kernel, strides=(1,1,1,1), rates=(1,1,1,1), padding="SAME")
        output4D = output4D - tf.ones_like(output4D)

        return output4D
</code>```

Body:
As the following piece of code shows, the tensorflow tf.nn.dilation2D function doesn't behave as a conventional dilation operator.

import tensorflow as tf
tf.InteractiveSession()
A = [[0, 0, 0, 0, 0, 0, 0],
     [0, 0, 0, 0, 1, 0, 0],
     [0, 0, 0, 1, 1, 1, 0],
     [0, 0, 0, 0, 1, 0, 0],
     [0, 0, 0, 0, 0, 0, 0],
     [0, 0, 0, 0, 0, 0, 0]]
kernel = tf.ones((3,3,1))
input4D = tf.cast(tf.expand_dims(tf.expand_dims(A, -1), 0), tf.float32)
output4D = tf.nn.dilation2d(input4D, filter=kernel, strides=(1,1,1,1), rates=(1,1,1,1), padding="SAME")
print(tf.cast(output4D[0,:,:,0], tf.int32).eval())

Returns the following tensor:

array([[1, 1, 1, 2, 2, 2, 1],
       [1, 1, 2, 2, 2, 2, 2],
       [1, 1, 2, 2, 2, 2, 2],
       [1, 1, 2, 2, 2, 2, 2],
       [1, 1, 1, 2, 2, 2, 1],
       [1, 1, 1, 1, 1, 1, 1]], dtype=int32)

I don't understand neither why it behaves like that, neither how I should use tf.nn.dilation2d to retrieve the expected output:

array([[0, 0, 0, 1, 1, 1, 0],
       [0, 0, 1, 1, 1, 1, 1],
       [0, 0, 1, 1, 1, 1, 1],
       [0, 0, 1, 1, 1, 1, 1],
       [0, 0, 0, 1, 1, 1, 0],
       [0, 0, 0, 0, 0, 0, 0]], dtype=int32)

Can someone enlighten the succinct documentation of tensorflow and give an explanation of what the the tf.nn.dilation2D function does ?

Body:
can do it like this:

def dilation2d(self, img4D):
    '''
    '''
    with tf.variable_scope('dilation2d'):
        kernel = tf.ones((3, 3, img4D.get_shape()[3]))
        output4D = tf.nn.dilation2d(img4D, filter=kernel, strides=(1,1,1,1), rates=(1,1,1,1), padding="SAME")
        output4D = output4D - tf.ones_like(output4D)

        return output4D


问:
WPF - Resource not loading from Generic.xaml
Themes\Generic.xaml:

```<code><ResourceDictionary
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
    <ResourceDictionary.MergedDictionaries>
        <ResourceDictionary Source="WPF Commons;component/Controls/Layout/Foo/FooItem.xaml" />
    </ResourceDictionary.MergedDictionaries>
</ResourceDictionary>
</code>```

Controls\Layout\Foo\FooItem.xaml:

```<code><Style TargetType="{x:Type l:FooItem}">
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="{x:Type l:FooItem}">
                <Border>
                    <ContentPresenter ContentSource="Header" />
                </Border>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>
</code>```

If I copy the entire style into my usercontrol resources it works fine. But, if I don't, the usercontrol shows up empty. In Expression Blend 4, I right-clicked and chose Edit Template>, but it won't let me select Edit a Copy... which leads me to believe that something is severely wrong and the Generic.xaml isn't loading properly. I figure it's Generic.xaml because if I remove the MergedDictionary call and copy/paste the xaml style directly into Generic.xaml it still doesn't work.

答:
I'm gonna take a wild guess that you altered your AssemblyInfo.cs file and either changed (or removed) the following line:

```<code>[assembly: ThemeInfo(
    ResourceDictionaryLocation.None, //where theme specific resource dictionaries are located
    //(used if a resource is not found in the page,
    // or application resource dictionaries)
    ResourceDictionaryLocation.SourceAssembly //where the generic resource dictionary is located
    //(used if a resource is not found in the page,
    // app, or any theme specific resource dictionaries)
)]
</code>```

You need to tell your assembly about your ThemeInfo. :)

Body:
Themes\Generic.xaml:

<ResourceDictionary
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
    <ResourceDictionary.MergedDictionaries>
        <ResourceDictionary Source="WPF Commons;component/Controls/Layout/Foo/FooItem.xaml" />
    </ResourceDictionary.MergedDictionaries>
</ResourceDictionary>

Controls\Layout\Foo\FooItem.xaml:

If I copy the entire style into my usercontrol resources it works fine. But, if I don't, the usercontrol shows up empty. In Expression Blend 4, I right-clicked and chose Edit Template>, but it won't let me select Edit a Copy... which leads me to believe that something is severely wrong and the Generic.xaml isn't loading properly. I figure it's Generic.xaml because if I remove the MergedDictionary call and copy/paste the xaml style directly into Generic.xaml it still doesn't work.

Body:
I'm gonna take a wild guess that you altered your AssemblyInfo.cs file and either changed (or removed) the following line:

[assembly: ThemeInfo(
    ResourceDictionaryLocation.None, //where theme specific resource dictionaries are located
    //(used if a resource is not found in the page,
    // or application resource dictionaries)
    ResourceDictionaryLocation.SourceAssembly //where the generic resource dictionary is located
    //(used if a resource is not found in the page,
    // app, or any theme specific resource dictionaries)
)]

You need to tell your assembly about your ThemeInfo. :)


问:
gRPC Name Resolution Failure
While trying to run tensorflow-serving with docker, I am getting the following error issuing a client request using gRPC with following code:

```<code>`python client.py --server=172.17.0.2/16:9000 --image=./test_images/image2.jpg

debug_error_string = "{"created":"@1551888435.208113000","description":"Failed to create subchannel","file":"src/core/ext/filters/client_channel/client_channel.cc","file_line":2267,"referenced_errors":[{"created":"@1551888435.208109000","description":"Name resolution failure","file":"src/core/ext/filters/client_channel/request_routing.cc","file_line":165,"grpc_status":14}]}"`
</code>```

Information about my environment:

OS: macOS virtual env.: Anaconda 3 Python 3.6 gRPC/tools 1.19

Would you please help me in resolving the issue?

答:
The IP Address, 172.17.0.2/16, which looks slightly different seems to cause the problem. You can use localhost instead.

So, the command for running the client.py can be

```<code>python client.py --server=localhost:9000 --image=./test_images/image2.jpg
</code>```

Title: gRPC Name Resolution Failure

Body:
While trying to run tensorflow-serving with docker, I am getting the following error issuing a client request using gRPC with following code:

`python client.py --server=172.17.0.2/16:9000 --image=./test_images/image2.jpg

debug_error_string = "{"created":"@1551888435.208113000","description":"Failed to create subchannel","file":"src/core/ext/filters/client_channel/client_channel.cc","file_line":2267,"referenced_errors":[{"created":"@1551888435.208109000","description":"Name resolution failure","file":"src/core/ext/filters/client_channel/request_routing.cc","file_line":165,"grpc_status":14}]}"`

Information about my environment:

OS: macOS virtual env.: Anaconda 3 Python 3.6 gRPC/tools 1.19

Would you please help me in resolving the issue?

Body:
The IP Address, 172.17.0.2/16, which looks slightly different seems to cause the problem. You can use localhost instead.

So, the command for running the client.py can be

python client.py --server=localhost:9000 --image=./test_images/image2.jpg


问:
Reading csv ,saving in dataframe, putting if condition, not getting exectped result
I'm reading csv, saving it into dataframe and using if condition but I'm not getting expected result.

My python code below :

```<code>import pandas as pd
import numpy as np
import datetime
import operator
from datetime import datetime
dt = datetime.now ( ).strftime ( '%m/%d/%Y' )
stockRules = pd.read_csv("C:\stock_rules.csv", dtype={"Product Currently Out of Stock": str}).drop_duplicates(subset="Product Currently Out of Stock", keep="last" )

pd.to_datetime(stockRules['FROMMONTH'], format='%m/%d/%Y')
pd.to_datetime(stockRules['TOMONTH'], format='%m/%d/%Y')

 if stockRules['FROMMONTH'] <= dt and stockRules['TOMONTH'] >= dt:
        print(stockRules)
</code>```

My csv file is below :

```<code>Productno   FROMMONTH   TOMONTH
120041      2/1/2019    5/30/2019
112940      2/1/2019    5/30/2019
121700      2/1/2019    2/1/2019
</code>```

I want to read csv file and want to print the product number, which meets the condition only.

答:
I played around with the code a bit and simplified it somewhat, but the idea behind the selection should still work the same:

```<code>dt = datetime.now().strftime("%m/%d/%Y")
stockRules = pd.read_csv("data.csv", delimiter=";")

stockRules["FROMMONTH"] = pd.to_datetime(stockRules["FROMMONTH"], format="%m/%d/%Y")
stockRules["TOMONTH"] = pd.to_datetime(stockRules["TOMONTH"], format="%m/%d/%Y")

sub = stockRules[(stockRules["FROMMONTH"] <= dt) & (dt <= stockRules["TOMONTH"])]
print(sub["Productno"])
</code>```

Notice that when using pd.to_datetime I am assigning the result of the operation to the original column, overriding whatever was in it before.

Hope this helps.

EDIT:

For my tests I changed the CSV to use ; as delimiter, since I had trouble reading in the data you provided in your question. Might be that you will have to specify another delimiter. For tabs for example:

```<code>stockRules = pd.read_csv("data.csv", delimiter="\t")
</code>```

Body:
I'm reading csv, saving it into dataframe and using if condition but I'm not getting expected result.

My python code below :

import pandas as pd
import numpy as np
import datetime
import operator
from datetime import datetime
dt = datetime.now ( ).strftime ( '%m/%d/%Y' )
stockRules = pd.read_csv("C:\stock_rules.csv", dtype={"Product Currently Out of Stock": str}).drop_duplicates(subset="Product Currently Out of Stock", keep="last" )

pd.to_datetime(stockRules['FROMMONTH'], format='%m/%d/%Y')
pd.to_datetime(stockRules['TOMONTH'], format='%m/%d/%Y')

 if stockRules['FROMMONTH'] <= dt and stockRules['TOMONTH'] >= dt:
        print(stockRules)

My csv file is below :

Productno   FROMMONTH   TOMONTH
120041      2/1/2019    5/30/2019
112940      2/1/2019    5/30/2019
121700      2/1/2019    2/1/2019

I want to read csv file and want to print the product number, which meets the condition only.

Body:
I played around with the code a bit and simplified it somewhat, but the idea behind the selection should still work the same:

dt = datetime.now().strftime("%m/%d/%Y")
stockRules = pd.read_csv("data.csv", delimiter=";")

stockRules["FROMMONTH"] = pd.to_datetime(stockRules["FROMMONTH"], format="%m/%d/%Y")
stockRules["TOMONTH"] = pd.to_datetime(stockRules["TOMONTH"], format="%m/%d/%Y")

sub = stockRules[(stockRules["FROMMONTH"] <= dt) & (dt <= stockRules["TOMONTH"])]
print(sub["Productno"])

Notice that when using pd.to_datetime I am assigning the result of the operation to the original column, overriding whatever was in it before.

Hope this helps.

EDIT:

For my tests I changed the CSV to use ; as delimiter, since I had trouble reading in the data you provided in your question. Might be that you will have to specify another delimiter. For tabs for example:

stockRules = pd.read_csv("data.csv", delimiter="\t")


问:
Unable to get wanted output using for and range functions
For my homework assignment, I am using the for loop and the range function. I have to create a loop that prints

```<code>Hello 0
Hello 1
Hello 3
Hello 6
Hello 10
</code>```

The question says that the number corresponds to the accumulated summation over the successive indexes, but I am not really sure how to implement it into my code. I was thinking it was setting the range from 0 to 10 and trying to make a formula, but nothing has come yet. Any help would be appreciated. It has to be in a for i in range function and loop for this assignment.

```<code>for i in range(0,10,2):
    print("Hello",i)
</code>```

答:
the integers can be formed by cumulatively adding from 0 to 5 like so:

```<code>x = 0
for n in range(1,6):
    print(x)
    x += n
</code>```

Output:

```<code>0
1
3
6
10
</code>```

If you must add, a string Hello to each, depending on how far you are in your learning, there are 3 ways to go about this. Either:

text = 'Hello %s' % x - SUPER OLD string formatting for Python.

text = 'Hello {}'.format(x) - called %-formatting.

text = f'Hello {x}' - called F-strings suggested.

So to complete the code:

```<code>x = 0
for n in range(1,6):
    print(f'Hello {x}')
    x += n
</code>```

Output:

```<code>Hello 0
Hello 1
Hello 3
Hello 6
Hello 10
</code>```

Body:
For my homework assignment, I am using the for loop and the range function. I have to create a loop that prints

Hello 0
Hello 1
Hello 3
Hello 6
Hello 10

The question says that the number corresponds to the accumulated summation over the successive indexes, but I am not really sure how to implement it into my code. I was thinking it was setting the range from 0 to 10 and trying to make a formula, but nothing has come yet. Any help would be appreciated. It has to be in a for i in range function and loop for this assignment.

for i in range(0,10,2):
    print("Hello",i)

Body:
the integers can be formed by cumulatively adding from 0 to 5 like so:

x = 0
for n in range(1,6):
    print(x)
    x += n

Output:

0
1
3
6
10

If you must add, a string Hello to each, depending on how far you are in your learning, there are 3 ways to go about this. Either:

text = 'Hello %s' % x - SUPER OLD string formatting for Python.

text = 'Hello {}'.format(x) - called %-formatting.

text = f'Hello {x}' - called F-strings suggested.

So to complete the code:

x = 0
for n in range(1,6):
    print(f'Hello {x}')
    x += n

Output:

Hello 0
Hello 1
Hello 3
Hello 6
Hello 10


问:
Change SWT tree node text foreground when highlighted
I’m pretty new in SWT/JFace technology and I’ve found a problem that it’s driving me crazy. In an Eclipse RCP application I have a view where I’ve placed a SWT tree with a JFace TreeViewer which provides the labels and the icons by means of a label provider. By requirements of the customer the background colour of the tree is dark blue and the font colour is white. This combination of colours results in a bad visualization of a node’s text when the node is selected, the text does not fit the tree region and we place the mouse pointer over the node. Somehow a “native highlighting” appears. This can be shown in the following image.

On the other side, this problem does not happen when the node where we place the mouse over is not selected. The highlighting changes the colour of the font to make it more visible. This can be shown in the following image.

After doing some research I’ve found that by adding a listener for the SWT.EraseItem event I am able to modify the background’s colour of a selected node and then disable the selection. This allows me to define my own selection background style and also disable the SWT.SELECTED flag of the event.detail in order to force the OS to highlight as the node is not selected.

```<code>private final class EraseItemListener implements Listener {

    public void handleEvent(Event event) {
        // Only perform the node highlight when it is selected.
        if ((event.detail & SWT.SELECTED) == SWT.SELECTED) {
            // Modify background, emulate Windows highlighting.

            ...

            // Set Windows that we do not want to draw this item as a selection (we have already highlighted the item in our way).
            event.detail &= ~SWT.SELECTED;
        }
    }
}
</code>```

This “solution” can be reasonable. The main drawbacks I see is that my selection style only fits for the Windows 7 default visual themes. For those “Windows classic” or “High contrast” I’ll get visualization problems. Moreover (and this is the most annoying issue), the fact of adding a listener for the SWT.EraseItem (even without code to handle the event) produces two new problems.

This makes either SWT or JFace to draw the icon of the tree node in
the wrong place as you can see in the following image.

The highlight of the tree’s root node is completely wrong. As you
can see in the following image, the node seems to be highlighted in
2 different ways and the icon is repeated.

My questions are basically two.

Do you think there is an easier solution for the main problem? What
I would like is to show a selected node (the one of the first image)
in the same way as in the second image. I would like to change the
foreground colour of the selected node to make it more visible.

In case of using the SWT.EraseItem approach, is there any way of
showing the icons in the correct location? Is this behaviour a known
bug?

Thanks in advance.

答:
Just stumbled across this old post and realized it matches a bug that I opened recently on eclipse.

My workaround to have the text in the correct color was to paint over the text with a different color using a PaintListener (registered in the tree with SWT.PaintItem):

```<code>private static class TreePaintListener implements Listener {
    @Override
    public void handleEvent(Event event) {
        boolean isSelected = (event.detail & SWT.SELECTED) != 0;
        if (isSelected && event.item instanceof TreeItem) {
            TreeItem treeItem = (TreeItem) event.item;
            Tree parent = treeItem.getParent();

            GC gc = event.gc;
            Color foreground = null/* Some Color */;
            gc.setForeground(foreground);

            Rectangle imageBounds = treeItem.getImageBounds(0);
            Rectangle textBounds = treeItem.getTextBounds(0);
            Point stringExtent = gc.stringExtent(treeItem.getText());

            int offsetX = imageBounds.width != 0 ? imageBounds.height - imageBounds.width : 0;
            int offsetY = (textBounds.height - stringExtent.y) / 2;

            int x = textBounds.x + offsetX;
            int y = textBounds.y + offsetY;

            if (gc.getClipping().contains(x, y)) {
                gc.drawString(treeItem.getText(), x, y);
            }
        }
    }
}
</code>```

But it still misbehaves when there are multiple columns defined (only the first one is painted over), and depending on the operating system and DPI the calculations might be a bit off.

Body:
I’m pretty new in SWT/JFace technology and I’ve found a problem that it’s driving me crazy. In an Eclipse RCP application I have a view where I’ve placed a SWT tree with a JFace TreeViewer which provides the labels and the icons by means of a label provider. By requirements of the customer the background colour of the tree is dark blue and the font colour is white. This combination of colours results in a bad visualization of a node’s text when the node is selected, the text does not fit the tree region and we place the mouse pointer over the node. Somehow a “native highlighting” appears. This can be shown in the following image.

On the other side, this problem does not happen when the node where we place the mouse over is not selected. The highlighting changes the colour of the font to make it more visible. This can be shown in the following image.

After doing some research I’ve found that by adding a listener for the SWT.EraseItem event I am able to modify the background’s colour of a selected node and then disable the selection. This allows me to define my own selection background style and also disable the SWT.SELECTED flag of the event.detail in order to force the OS to highlight as the node is not selected.

private final class EraseItemListener implements Listener {

    public void handleEvent(Event event) {
        // Only perform the node highlight when it is selected.
        if ((event.detail & SWT.SELECTED) == SWT.SELECTED) {
            // Modify background, emulate Windows highlighting.

            ...

            // Set Windows that we do not want to draw this item as a selection (we have already highlighted the item in our way).
            event.detail &= ~SWT.SELECTED;
        }
    }
}

This “solution” can be reasonable. The main drawbacks I see is that my selection style only fits for the Windows 7 default visual themes. For those “Windows classic” or “High contrast” I’ll get visualization problems. Moreover (and this is the most annoying issue), the fact of adding a listener for the SWT.EraseItem (even without code to handle the event) produces two new problems.

This makes either SWT or JFace to draw the icon of the tree node in
the wrong place as you can see in the following image.

The highlight of the tree’s root node is completely wrong. As you
can see in the following image, the node seems to be highlighted in
2 different ways and the icon is repeated.

My questions are basically two.

Do you think there is an easier solution for the main problem? What
I would like is to show a selected node (the one of the first image)
in the same way as in the second image. I would like to change the
foreground colour of the selected node to make it more visible.

In case of using the SWT.EraseItem approach, is there any way of
showing the icons in the correct location? Is this behaviour a known
bug?

Thanks in advance.

Body:
Just stumbled across this old post and realized it matches a bug that I opened recently on eclipse.

My workaround to have the text in the correct color was to paint over the text with a different color using a PaintListener (registered in the tree with SWT.PaintItem):

private static class TreePaintListener implements Listener {
    @Override
    public void handleEvent(Event event) {
        boolean isSelected = (event.detail & SWT.SELECTED) != 0;
        if (isSelected && event.item instanceof TreeItem) {
            TreeItem treeItem = (TreeItem) event.item;
            Tree parent = treeItem.getParent();

            GC gc = event.gc;
            Color foreground = null/* Some Color */;
            gc.setForeground(foreground);

            Rectangle imageBounds = treeItem.getImageBounds(0);
            Rectangle textBounds = treeItem.getTextBounds(0);
            Point stringExtent = gc.stringExtent(treeItem.getText());

            int offsetX = imageBounds.width != 0 ? imageBounds.height - imageBounds.width : 0;
            int offsetY = (textBounds.height - stringExtent.y) / 2;

            int x = textBounds.x + offsetX;
            int y = textBounds.y + offsetY;

            if (gc.getClipping().contains(x, y)) {
                gc.drawString(treeItem.getText(), x, y);
            }
        }
    }
}

But it still misbehaves when there are multiple columns defined (only the first one is painted over), and depending on the operating system and DPI the calculations might be a bit off.


问:
Wordpress: Woocommerce without e-commerce for affiliate site
I'm building an affiliate site and obviously for every product I use page not post. But pages don't have categories or tags and even if we add them to pages, our pages won't appear on categories' pages and in widget areas of front page.

Woocommerce functionality is perfect but it looks a little bit weird to use it for an affiliate site, not a store. Is it okay to delete e-commerce features (price, add to card and stuff like that) and use the rest of Woocommerce?

答:
It is nothing weird to use Woocommerce without cart stuff.
Sometimes clients want a catalog of goods, but not always need the cart and delivery staff on a site.
In this plugin it is much more comfortable to organize categories and editing of many products. Plus you get interaction with other plugins that build for Woocommerce.
If you make it thru "Custom Post Type", then it is normal if there are about 10.
If they are more, than you will need to create many solutions by yourself and you will have problems with their further maintenance.</p>


问:
How can i display form success message on same { div } without refreshing the page?
How can I submit a form on same  without refreshing page? Here I'm submitting a pdf to drag and drop container and when I submit the form it's redirecting to upload.php. I need to display the successful message on the same container . I have not enough knowledge about the ajax. Kindly please help me to solve the issue

Here is the drag and drop container below:

Here is the result page (upload.php) below:

HTML Form:

```<code><form method="POST" action="upload.php" enctype="multipart/form-data">
  <input type="file" multiple name="file[]" accept="application/pdf">
      <input class="button-primary" type="submit" value="Submit">
</form>
</code>```

Upload.php file:

```<code><?php
//echo 'done';
$output = '';

    if(isset($_FILES['file']['name'][0])){
        //echo 'ok';
        foreach($_FILES['file']['name'] as $keys => $values) {

            if(move_uploaded_file($_FILES['file']['tmp_name'][$keys], 'upload/' .$values)) {

                $output .= 'Form submited succesfully';
            }
        }
    }
echo $output;
?>
</code>```

答:
Use the following code</p>

```<code><form method="POST" enctype="multipart/form-data">
            <input id='file' type="file" multiple name="file[]" accept="application/pdf">
            <input id='submit'class="button-primary" type="submit" value="Submit">
        </form>
</code>```

```<code> $("#submit").submit(function(e){
    e.preventDefault();
 var xhr = new XMLHttpRequest();
          var data = new FormData();

          data.append("file",document.getElementById("file").files[0]);
          xhr.open("post","/upload.php",true);

          xhr.send(data);

            });

</code>```

Body:
How can I submit a form on same  without refreshing page? Here I'm submitting a pdf to drag and drop container and when I submit the form it's redirecting to upload.php. I need to display the successful message on the same container . I have not enough knowledge about the ajax. Kindly please help me to solve the issue

Here is the drag and drop container below:

Here is the result page (upload.php) below:

HTML Form:

<form method="POST" action="upload.php" enctype="multipart/form-data">
  <input type="file" multiple name="file[]" accept="application/pdf">
      <input class="button-primary" type="submit" value="Submit">
</form>

Upload.php file:

<?php
//echo 'done';
$output = '';

    if(isset($_FILES['file']['name'][0])){
        //echo 'ok';
        foreach($_FILES['file']['name'] as $keys => $values) {

            if(move_uploaded_file($_FILES['file']['tmp_name'][$keys], 'upload/' .$values)) {

                $output .= 'Form submited succesfully';
            }
        }
    }
echo $output;
?>

Body:
Use the following code

<form method="POST" enctype="multipart/form-data">
            <input id='file' type="file" multiple name="file[]" accept="application/pdf">
            <input id='submit'class="button-primary" type="submit" value="Submit">
        </form>

 $("#submit").submit(function(e){
    e.preventDefault();
 var xhr = new XMLHttpRequest();
          var data = new FormData();

          data.append("file",document.getElementById("file").files[0]);
          xhr.open("post","/upload.php",true);

          xhr.send(data);

            });


问:
Making TextView scrollable on Android
I am displaying text in a TextView that appears to be too long to fit
into one screen. I need to make my TextView scrollable. How can I do
that?

Here is the code:

```<code>final TextView tv = new TextView(this);
tv.setBackgroundResource(R.drawable.splash);
tv.setTypeface(face);
tv.setTextSize(18);
tv.setTextColor(R.color.BROWN);
tv.setGravity(Gravity.CENTER_VERTICAL| Gravity.CENTER_HORIZONTAL);
tv.setOnTouchListener(new OnTouchListener() {
    public boolean onTouch(View v, MotionEvent e) {
        Random r = new Random();
        int i = r.nextInt(101);
        if (e.getAction() == e.ACTION_DOWN) {
            tv.setText(tips[i]);
            tv.setBackgroundResource(R.drawable.inner);
        }
        return true;
    }
});
setContentView(tv);
</code>```

答:
All that is really necessary is the setMovementMethod(). Here's an example using a LinearLayout.

File main.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
<TextView
    android:id="@+id/tv1"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:text="@string/hello"
    />
</LinearLayout>
</code>```

File WordExtractTest.java

```<code>public class WordExtractTest extends Activity {

    TextView tv1;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        tv1 = (TextView)findViewById(R.id.tv1);

        loadDoc();
    }

    private void loadDoc() {

        String s = "";

        for(int x=0; x<=100; x++) {
            s += "Line: " + String.valueOf(x) + "\n";
        }

        tv1.setMovementMethod(new ScrollingMovementMethod());

        tv1.setText(s);
    }
}
</code>```

Title: Making TextView scrollable on Android

Body:
I am displaying text in a TextView that appears to be too long to fit
into one screen. I need to make my TextView scrollable. How can I do
that?

Here is the code:

final TextView tv = new TextView(this);
tv.setBackgroundResource(R.drawable.splash);
tv.setTypeface(face);
tv.setTextSize(18);
tv.setTextColor(R.color.BROWN);
tv.setGravity(Gravity.CENTER_VERTICAL| Gravity.CENTER_HORIZONTAL);
tv.setOnTouchListener(new OnTouchListener() {
    public boolean onTouch(View v, MotionEvent e) {
        Random r = new Random();
        int i = r.nextInt(101);
        if (e.getAction() == e.ACTION_DOWN) {
            tv.setText(tips[i]);
            tv.setBackgroundResource(R.drawable.inner);
        }
        return true;
    }
});
setContentView(tv);

Body:
All that is really necessary is the setMovementMethod(). Here's an example using a LinearLayout.

File main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
<TextView
    android:id="@+id/tv1"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:text="@string/hello"
    />
</LinearLayout>

File WordExtractTest.java

public class WordExtractTest extends Activity {

    TextView tv1;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        tv1 = (TextView)findViewById(R.id.tv1);

        loadDoc();
    }

    private void loadDoc() {

        String s = "";

        for(int x=0; x<=100; x++) {
            s += "Line: " + String.valueOf(x) + "\n";
        }

        tv1.setMovementMethod(new ScrollingMovementMethod());

        tv1.setText(s);
    }
}


问:
Crypto.js SHA1 vs MessageDigest java SHA1: why different results?
I need to encrypt a string. The initial version was written in Java, but it needs to be rewritten in javascript now. But i have different results.
Here is the code in java:

Java Version:

```<code>private static String getEncrypt(String input, String salt) throws NoSuchAlgorithmException {
        byte[] raw_salt = Base64.getDecoder().decode(salt);
        byte[] raw_data = input.getBytes(StandardCharsets.UTF_8);
        byte[] test_data = new byte[raw_salt.length + raw_data.length];
        MessageDigest mdTemp = MessageDigest.getInstance("SHA1");
        System.arraycopy(raw_salt, 0, test_data, 0, raw_salt.length);
        System.arraycopy(raw_data, 0, test_data, raw_salt.length, raw_data.length);
        mdTemp.update(test_data);
        byte[] bytes = mdTemp.digest();
        return new String(Base64.getEncoder().encode(bytes));
    }
input: 123456789
salt: pMm6kWsoWjR18sWKnoG4Az==
output: 6u/VAXS9ZKmLEbHw/OZ1AVarth4=
</code>```

JS Version: (use crypto.js)

```<code>const crypto = require("crypto");

function getEncrypt(input, salt){
   const sha1 = crypto.createHash('sha1');
   const beforeCrypto = salt + input;
   const afterCrypto = sha1.update(beforeCrypto).digest('base64');
   return afterCrypto;
}

input: 123456789
salt: pMm6kWsoWjR18sWKnoG4Az==
output: ie/3j+92nxvcNT5i+3WUJbWsEAg=
</code>```

The MessageDigest method in java requires me to enter input in byte[] format. While in javascript, I use ·string· type input.
They also use salt to make the encryption more safe, but it brings more different that i cannot rewrite it in javascript.
I try many ways to solve it. But I still cannot get the same result.

答:
The following snippet also gives me the correct answer:

98O8HYCOBHMq32eZZczDTKeuNEE=

There must be some detail in your code that is different.
One thing I did was to use the UTF8 standard charset, to avoid any mishaps with the way "utf-8", vs. "UTF8" etc is specified.

Your code does not compile (missing return type on getEncrypt, for example) so there might be something else that is different.

import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Base64;

public class Main {

  private static String getEncrypt(String input) throws NoSuchAlgorithmException {
    byte[] raw_data = input.getBytes(StandardCharsets.UTF_8);
    MessageDigest mdTemp = MessageDigest.getInstance("SHA1");
    mdTemp.update(raw_data);
    byte[] bytes = mdTemp.digest();
    return new String(Base64.getEncoder().encode(bytes));
  }

  public static void main(String[] args){

    try {
      System.out.println(getEncrypt("123456789"));
    } catch (NoSuchAlgorithmException e) {
      e.printStackTrace();
    }

  }

}
```

Body:
I need to encrypt a string. The initial version was written in Java, but it needs to be rewritten in javascript now. But i have different results.
Here is the code in java:

Java Version:

private static String getEncrypt(String input, String salt) throws NoSuchAlgorithmException {
        byte[] raw_salt = Base64.getDecoder().decode(salt);
        byte[] raw_data = input.getBytes(StandardCharsets.UTF_8);
        byte[] test_data = new byte[raw_salt.length + raw_data.length];
        MessageDigest mdTemp = MessageDigest.getInstance("SHA1");
        System.arraycopy(raw_salt, 0, test_data, 0, raw_salt.length);
        System.arraycopy(raw_data, 0, test_data, raw_salt.length, raw_data.length);
        mdTemp.update(test_data);
        byte[] bytes = mdTemp.digest();
        return new String(Base64.getEncoder().encode(bytes));
    }
input: 123456789
salt: pMm6kWsoWjR18sWKnoG4Az==
output: 6u/VAXS9ZKmLEbHw/OZ1AVarth4=

JS Version: (use crypto.js)

const crypto = require("crypto");

function getEncrypt(input, salt){
   const sha1 = crypto.createHash('sha1');
   const beforeCrypto = salt + input;
   const afterCrypto = sha1.update(beforeCrypto).digest('base64');
   return afterCrypto;
}

input: 123456789
salt: pMm6kWsoWjR18sWKnoG4Az==
output: ie/3j+92nxvcNT5i+3WUJbWsEAg=

The MessageDigest method in java requires me to enter input in byte[] format. While in javascript, I use ·string· type input.
They also use salt to make the encryption more safe, but it brings more different that i cannot rewrite it in javascript.
I try many ways to solve it. But I still cannot get the same result.


问:
Tukey five number summary in Python
I have been unable to find this function in any of the standard packages, so I wrote the one below. Before throwing it toward the Cheeseshop, however, does anyone know of an already published version? Alternatively, please suggest any improvements. Thanks. </p>

```<code>def fivenum(v):
    """Returns Tukey's five number summary (minimum, lower-hinge, median, upper-hinge, maximum) for the input vector, a list or array of numbers based on 1.5 times the interquartile distance"""
    import numpy as np
    from scipy.stats import scoreatpercentile
    try:
        np.sum(v)
    except TypeError:
        print('Error: you must provide a list or array of only numbers')
    q1 = scoreatpercentile(v,25)
    q3 = scoreatpercentile(v,75)
    iqd = q3-q1
    md = np.median(v)
    whisker = 1.5*iqd
    return np.min(v), md-whisker, md, md+whisker, np.max(v),
</code>```

答:
```<code>import numpy as np
# np_array = np.array(np.random.random(100))
np.percentile(np_array, [0, 25, 50, 75, 100])
</code>```

percentiles selection can be configured with the interpolation argument which is linear by default

ContentLicense: CC BY-SA 2.5

Title: Tukey five number summary in Python

Body:
I have been unable to find this function in any of the standard packages, so I wrote the one below. Before throwing it toward the Cheeseshop, however, does anyone know of an already published version? Alternatively, please suggest any improvements. Thanks.

def fivenum(v):
    """Returns Tukey's five number summary (minimum, lower-hinge, median, upper-hinge, maximum) for the input vector, a list or array of numbers based on 1.5 times the interquartile distance"""
    import numpy as np
    from scipy.stats import scoreatpercentile
    try:
        np.sum(v)
    except TypeError:
        print('Error: you must provide a list or array of only numbers')
    q1 = scoreatpercentile(v,25)
    q3 = scoreatpercentile(v,75)
    iqd = q3-q1
    md = np.median(v)
    whisker = 1.5*iqd
    return np.min(v), md-whisker, md, md+whisker, np.max(v),

Body:
import numpy as np
# np_array = np.array(np.random.random(100))
np.percentile(np_array, [0, 25, 50, 75, 100])

percentiles selection can be configured with the interpolation argument which is linear by default


问:
table header in email announcing twice(only first column announcing twice) in voice over(ADA) in iOS
I'm designing email template with ADA(accessibility) compliance.

The issue here is, the first header in the table announcing twice when read through voice over.

For e.g. if Item is the first column, voice over is announcing like "Item, Item". This issue is happening only in iOS devices. For other devices it is working as expected.

```<code><table class="setDisplayWidthInner" border="0" cellpadding="0" cellspacing="0" align="center">
    <caption style="text-align:left; padding-top: 20px;">
        <span style="height: 26px;  font-family: Arial;  font-size: 24px;  line-height: 1.08; text-align: left;  color: #000000;">
                        <h2 style="font-size:24px;margin: 0px;font-weight: normal;">
                                    Canceled service appointment
                        </h2>
                    </span>
    </caption>
    <thead>
        <tr style="height: 22px;  font-family: Arial;  font-size: 20px;  line-height: 1.22;  text-align: left;  color: #000000;">
            <th scope="col" style="padding-top: 24px; width:30%; font-weight: normal" align="left">Auto service</th>
            <th scope="col" style="padding-top: 24px; width:40%; font-weight: normal" align="left">Service location</th>
            <th scope="col" style="padding-top: 24px; font-weight: normal" align="left">Customer</th>
        </tr>
        <tr>
            <td aria-hidden="true">
                <hr aria-hidden="true">
            </td>
            <td aria-hidden="true">
                <hr aria-hidden="true">
            </td>
            <td aria-hidden="true">
                <hr aria-hidden="true">
            </td>
        </tr>
    </thead>
    <tbody>
        <!-- body goes here -->
    </tbody>
</code>```

Expected Result in iOS(iPhone devices) with voice over on:

Item should announce as "Item" only once.

Actual result in iOS(iPhone devices) with voice over on:

Item is announcing as "Item Item"(twice).

答:
Reading this - https://a11y-101.com/development/tables

...I see you're using table header tags (<th>) to achieve semantic table structure but I think you're actually misleading screen reader software.

My thinking is that you are supposed to use table headers to link content with the header but in your case you aren't actually providing any content in the table cells.
So VoiceOver is getting confused and simply repeating the table header because it can't find the linked content.

In this case you're fortunate that only VoiceOver is picking up on it, but I would suggest changing those <th> tags to <td>s and testing again...?

Body:
I'm designing email template with ADA(accessibility) compliance.

The issue here is, the first header in the table announcing twice when read through voice over.

For e.g. if Item is the first column, voice over is announcing like "Item, Item". This issue is happening only in iOS devices. For other devices it is working as expected.

                                    Canceled service appointment

            Auto service
            Service location
            Customer

Expected Result in iOS(iPhone devices) with voice over on:

Item should announce as "Item" only once.

Actual result in iOS(iPhone devices) with voice over on:

Item is announcing as "Item Item"(twice).


问:
scrollIntoView Scrolls just too far
I have a page where a scroll bar containing table rows with divs in them is dynamically generated from the database. Each table row acts like a link, sort of like you'd see on a YouTube playlist next to the video player.

When a user visits the page, the option they are on is supposed to go to the top of the scrolling div. This functionality is working. The issue is that it goes just a tad too far. Like the option they are on is about 10px too high. So, the page is visited, the url is used to identify which option was selected and then scrolls that option to the top of the scrolling div. Note: This is not the scroll bar for the window, it is a div with a scrollbar.

I am using this code to make it move the selected option to the top of the div:

```<code>var pathArray = window.location.pathname.split( '/' );

var el = document.getElementById(pathArray[5]);

el.scrollIntoView(true);
</code>```

It moves it to the top of the div but about 10 pixels too far up.
Anyone know how to fix that?

答:
Smooth scroll to the proper position

Here is better answer for the most cases. It uses scroll-margin and scroll-padding CSS rules.
The solution below uses getBoundingClientRect which triggers an additional forced layout.

Get correct y coordinate and use window.scrollTo({top: y, behavior: 'smooth'})

```<code>const id = 'profilePhoto';
const yOffset = -10;
const element = document.getElementById(id);
const y = element.getBoundingClientRect().top + window.pageYOffset + yOffset;

window.scrollTo({top: y, behavior: 'smooth'});
</code>```

Title: scrollIntoView Scrolls just too far

Body:
I have a page where a scroll bar containing table rows with divs in them is dynamically generated from the database. Each table row acts like a link, sort of like you'd see on a YouTube playlist next to the video player.

When a user visits the page, the option they are on is supposed to go to the top of the scrolling div. This functionality is working. The issue is that it goes just a tad too far. Like the option they are on is about 10px too high. So, the page is visited, the url is used to identify which option was selected and then scrolls that option to the top of the scrolling div. Note: This is not the scroll bar for the window, it is a div with a scrollbar.

I am using this code to make it move the selected option to the top of the div:

var pathArray = window.location.pathname.split( '/' );

var el = document.getElementById(pathArray[5]);

el.scrollIntoView(true);

It moves it to the top of the div but about 10 pixels too far up.
Anyone know how to fix that?

Body:
Smooth scroll to the proper position

Here is better answer for the most cases. It uses scroll-margin and scroll-padding CSS rules.
The solution below uses getBoundingClientRect which triggers an additional forced layout.

Get correct y coordinate and use window.scrollTo({top: y, behavior: 'smooth'})

const id = 'profilePhoto';
const yOffset = -10;
const element = document.getElementById(id);
const y = element.getBoundingClientRect().top + window.pageYOffset + yOffset;

window.scrollTo({top: y, behavior: 'smooth'});


问:
write Data to a file in Formta Form
I have Data which is in this below format in FILE 1

```<code>NAME :  Ram
AGE :  12
NAME :  Rahul
AGE:  13
NAME:   Raj
AGE:   14
</code>```

My Desired Output => In this Below Format I needed

I want to Write Data to the FILE 2 in this below Format like

```<code>NAME| AGE
Ram|12
Rahul|13
Raj|14
</code>```

My code :

```<code>head -2 file1.txt | nl | tr '\n' '|' >> file2.txt
</code>```

But my Above Code Prints Only in first Two line in File2.txt

```<code>1 NAME : Ram | 2 AGE : 12|
</code>```

it has to loop until the end and write to file 2

答:
Comments in code. The script:

```<code># input test file as provided by OP
cat <<EOF >file
NAME :  Ram
AGE :  12
NAME :  Rahul
AGE:  13
NAME:   Raj
AGE:   14
EOF

# My first solution - a simple bash while read loop
echo "NAME|AGE"
while IFS=': ' read -r _ name && IFS=': ' read -r _ age; do
    echo "$name|$age"
done <file

# Second solution - some parsing + xargs
# first remove spaces, then substitue `:` for a space
# then run printf, don't print any NAME and AGE %.0s and print the names and ages %s
echo "NAME|AGE"
<file tr -d ' ' | tr ':' ' ' | xargs printf "%.0s%s|%.0s%s\n"

# Third solution - sed!
# first remove spaces and remove everything before :
# then read two lines, substitue newline for a | and print
echo "NAME|AGE"
<file sed 's/ //g; s/.*://' | sed 'N;s/\n/|/'
</code>```

will output:

```<code>NAME|AGE
Ram|12
Rahul|13
Raj|14
NAME|AGE
Ram|12
Rahul|13
Raj|14
NAME|AGE
Ram|12
Rahul|13
Raj|14
</code>```

Tested at tutorialspoint

Title: write Data to a file in Formta Form

Body:
I have Data which is in this below format in FILE 1

NAME :  Ram
AGE :  12
NAME :  Rahul
AGE:  13
NAME:   Raj
AGE:   14

My Desired Output => In this Below Format I needed

I want to Write Data to the FILE 2 in this below Format like

NAME| AGE
Ram|12
Rahul|13
Raj|14

My code :

head -2 file1.txt | nl | tr '\n' '|' >> file2.txt

But my Above Code Prints Only in first Two line in File2.txt

1 NAME : Ram | 2 AGE : 12|

it has to loop until the end and write to file 2

Body:
Comments in code. The script:

# input test file as provided by OP
cat <<EOF >file
NAME :  Ram
AGE :  12
NAME :  Rahul
AGE:  13
NAME:   Raj
AGE:   14
EOF

# My first solution - a simple bash while read loop
echo "NAME|AGE"
while IFS=': ' read -r _ name && IFS=': ' read -r _ age; do
    echo "$name|$age"
done <file

# Second solution - some parsing + xargs
# first remove spaces, then substitue `:` for a space
# then run printf, don't print any NAME and AGE %.0s and print the names and ages %s
echo "NAME|AGE"
<file tr -d ' ' | tr ':' ' ' | xargs printf "%.0s%s|%.0s%s\n"

# Third solution - sed!
# first remove spaces and remove everything before :
# then read two lines, substitue newline for a | and print
echo "NAME|AGE"
<file sed 's/ //g; s/.*://' | sed 'N;s/\n/|/'

will output:

NAME|AGE
Ram|12
Rahul|13
Raj|14
NAME|AGE
Ram|12
Rahul|13
Raj|14
NAME|AGE
Ram|12
Rahul|13
Raj|14

Tested at tutorialspoint