问:
How can I open a pdf file directly in my browser?
I would like to view a PDF file directly in my browser. I know this question is already asked but I haven't found a solution that works for me.

Here is my action's controller code so far:

```<code>public ActionResult GetPdf(string fileName)
{
    string filePath = "~/Content/files/" + fileName;
    return File(filePath, "application/pdf", fileName);
}
</code>```

Here is my view:

```<code>@{
   doc = "Mode_d'emploi.pdf";
}

<p>@Html.ActionLink(UserResource.DocumentationLink, "GetPdf", "General", new { fileName = doc }, null)</p>
</code>```

When I mouse hover the link here is the link:

The problem with my code is that the pdf file is not viewed in the browser but I get a message asking me if I wand to open or save the file.

I know it is possible and my browser support it because I already test it with another website allowing me to view pdf directly in my browser.

For example, here is the link when I mouse hover a link (on another website):

As you can see there is a difference in the generated link. I don't know if this is useful.

Any idea how can I view my pdf directly in the browser?

答:
Yes You Can do It Simply by redirecting . it ends extension like u need , .pdf ..

```<code>protected void OpenPdfPdf_Click(object sender, EventArgs e)
        {
            Response.Redirect("jun.pdf");
        }
</code>```

Or another Method ,its opens like .aspx page--

```<code> protected void OpenPdf_Click(object sender, EventArgs e)
        {
            string path = Server.MapPath("jun.pdf");
            //or you want to load from url change path to
//string path="https://www.w3.org/WAI/ER/tests/xhtml/testfiles/resources/pdf/dummy.pdf";
            WebClient client = new WebClient();
            Byte[] buffer = client.DownloadData(path);
            if (buffer != null)
            {
                Response.ContentType = "application/pdf";
                Response.AddHeader("content-length", buffer.Length.ToString());
                Response.BinaryWrite(buffer);
            }
        }
</code>```

Body:
I would like to view a PDF file directly in my browser. I know this question is already asked but I haven't found a solution that works for me.

Here is my action's controller code so far:

public ActionResult GetPdf(string fileName)
{
    string filePath = "~/Content/files/" + fileName;
    return File(filePath, "application/pdf", fileName);
}

Here is my view:

@{
   doc = "Mode_d'emploi.pdf";
}

@Html.ActionLink(UserResource.DocumentationLink, "GetPdf", "General", new { fileName = doc }, null)

When I mouse hover the link here is the link:

The problem with my code is that the pdf file is not viewed in the browser but I get a message asking me if I wand to open or save the file.

I know it is possible and my browser support it because I already test it with another website allowing me to view pdf directly in my browser.

For example, here is the link when I mouse hover a link (on another website):

As you can see there is a difference in the generated link. I don't know if this is useful.

Any idea how can I view my pdf directly in the browser?

Body:
Yes You Can do It Simply by redirecting . it ends extension like u need , .pdf ..

protected void OpenPdfPdf_Click(object sender, EventArgs e)
        {
            Response.Redirect("jun.pdf");
        }

Or another Method ,its opens like .aspx page--

 protected void OpenPdf_Click(object sender, EventArgs e)
        {
            string path = Server.MapPath("jun.pdf");
            //or you want to load from url change path to
//string path="https://www.w3.org/WAI/ER/tests/xhtml/testfiles/resources/pdf/dummy.pdf";
            WebClient client = new WebClient();
            Byte[] buffer = client.DownloadData(path);
            if (buffer != null)
            {
                Response.ContentType = "application/pdf";
                Response.AddHeader("content-length", buffer.Length.ToString());
                Response.BinaryWrite(buffer);
            }
        }


来源: stackexchange

问:
how to filter data from array and apply conditions angular8
I am getting below sample data from api dynamically.

Can anyone suggest how to apply condition based on data.

答:
You need to check values in array </p>

```<code>if (this.tagSchemaDetails.schema_context.providers.indexOf('All') < 0) {
   request['schema_context'] = this.createConditionsData();
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
You need to check values in array

if (this.tagSchemaDetails.schema_context.providers.indexOf('All') < 0) {
   request['schema_context'] = this.createConditionsData();
}


问:
Passing a commandline parameter containing quotes to installer
I'm trying to pass a custom commandline parameter to an installer created with Inno Setup. The parameter value actually consists of several parameters that will be used to launch the installed program when installation is complete, so the value contains spaces as well as quotes to group together parameters.

For example, when -arg "C:\path with spaces" -moreargs should be used as Parameters in a [Run] section entry, I would like to launch the installer like this:

```<code>setup.exe /abc="-arg "C:\path with spaces" -moreargs"
</code>```

Outputting the parameters that the installer receives in a [Code] section via ParamStr() shows them (of course) split up: /abc=-arg C:\path, with, spaces -moreargs

How do I escape the quotes to retain them?

I tried doubling the inner quotes:

```<code>setup.exe /abc="-arg ""C:\path with spaces"" -moreargs"
</code>```

This correctly keeps the parameter together (/abc=-arg C:\path with spaces -moreargs), however it seems that ParamStr() removes all quotes.

Is there a way to retain quotes within a parameter retrieved with ParamStr() or a param constant {param:abc|DefaultValue}?

Alternatives seem to be to either do my own parameter parsing from GetCmdTail (which contains the original parameter string) or use another character instead of the inner quotes that are retained in ParamStr() and then replace them with quotes afterwards. But I would prefer not doing that if there is a way to use the built-in functions.

答:
It seems both {param} and ParamStr() strip out double quotes, but as you pointed out (thanks!) the GetCmdTail function returns the original.

So here's a function to get the original parameters with quotes:

```<code>function ParamStrWithQuotes(ParamName: String) : string;
var
  fullCmd : String;
  currentParamName : string;
  i : Integer;
  startPos : Integer;
  endPos : Integer;
begin

  fullCmd := GetCmdTail
  // default to end of string, in case the option is the last item
  endPos := Length(fullCmd);

  for i := 0 to ParamCount-1 do
  begin
    // extract parameter name (eg, "/Option=")
    currentParamName := Copy(ParamStr(i), 0, pos('=',ParamStr(i)));

    // once found, we want the following item
    if (startPos > 0) then
    begin
      endPos := pos(currentParamName,fullCmd)-2; // -1 to move back to actual end position, -1 for space
      break; // exit loop
    end;

    if (CompareText(currentParamName, '/'+ParamName+'=') = 0) then // case-insensitive compare
    begin
      // found target item, so save its string position
      StartPos := pos(currentParamName,fullCmd)+2+Length(ParamName);
    end;
  end;

  if ((fullCmd[StartPos] = fullCmd[EndPos])
     and ((fullCmd[StartPos] = '"') or (fullCmd[StartPos] = ''''))) then
  begin
    // exclude surrounding quotes
    Result := Copy(fullCmd, StartPos+1, EndPos-StartPos-1);
  end
  else
  begin
    // return as-is
    Result := Copy(fullCmd, StartPos, EndPos-StartPos+1);
  end;
end;
</code>```

You can access this with {code:ParamStrWithQuotes|abc}

When invoking the setup.exe, you do have to escape the quotes, so one of the following works for that:

```<code>setup.exe /abc="-arg ""C:\path with spaces"" -moreargs"
</code>```

or

```<code>setup.exe /abc='-arg "C:\path with spaces" -moreargs'
</code>```

Body:
I'm trying to pass a custom commandline parameter to an installer created with Inno Setup. The parameter value actually consists of several parameters that will be used to launch the installed program when installation is complete, so the value contains spaces as well as quotes to group together parameters.

For example, when -arg "C:\path with spaces" -moreargs should be used as Parameters in a [Run] section entry, I would like to launch the installer like this:

setup.exe /abc="-arg "C:\path with spaces" -moreargs"

Outputting the parameters that the installer receives in a [Code] section via ParamStr() shows them (of course) split up: /abc=-arg C:\path, with, spaces -moreargs

How do I escape the quotes to retain them?

I tried doubling the inner quotes:

setup.exe /abc="-arg ""C:\path with spaces"" -moreargs"

This correctly keeps the parameter together (/abc=-arg C:\path with spaces -moreargs), however it seems that ParamStr() removes all quotes.

Is there a way to retain quotes within a parameter retrieved with ParamStr() or a param constant {param:abc|DefaultValue}?

Alternatives seem to be to either do my own parameter parsing from GetCmdTail (which contains the original parameter string) or use another character instead of the inner quotes that are retained in ParamStr() and then replace them with quotes afterwards. But I would prefer not doing that if there is a way to use the built-in functions.

Body:
It seems both {param} and ParamStr() strip out double quotes, but as you pointed out (thanks!) the GetCmdTail function returns the original.

So here's a function to get the original parameters with quotes:

function ParamStrWithQuotes(ParamName: String) : string;
var
  fullCmd : String;
  currentParamName : string;
  i : Integer;
  startPos : Integer;
  endPos : Integer;
begin

  fullCmd := GetCmdTail
  // default to end of string, in case the option is the last item
  endPos := Length(fullCmd);

  for i := 0 to ParamCount-1 do
  begin
    // extract parameter name (eg, "/Option=")
    currentParamName := Copy(ParamStr(i), 0, pos('=',ParamStr(i)));

    // once found, we want the following item
    if (startPos > 0) then
    begin
      endPos := pos(currentParamName,fullCmd)-2; // -1 to move back to actual end position, -1 for space
      break; // exit loop
    end;

    if (CompareText(currentParamName, '/'+ParamName+'=') = 0) then // case-insensitive compare
    begin
      // found target item, so save its string position
      StartPos := pos(currentParamName,fullCmd)+2+Length(ParamName);
    end;
  end;

  if ((fullCmd[StartPos] = fullCmd[EndPos])
     and ((fullCmd[StartPos] = '"') or (fullCmd[StartPos] = ''''))) then
  begin
    // exclude surrounding quotes
    Result := Copy(fullCmd, StartPos+1, EndPos-StartPos-1);
  end
  else
  begin
    // return as-is
    Result := Copy(fullCmd, StartPos, EndPos-StartPos+1);
  end;
end;

You can access this with {code:ParamStrWithQuotes|abc}

When invoking the setup.exe, you do have to escape the quotes, so one of the following works for that:

setup.exe /abc="-arg ""C:\path with spaces"" -moreargs"

or

setup.exe /abc='-arg "C:\path with spaces" -moreargs'


问:
How do I extract only numbers from a string in Dart?
I was trying to sort the string using -

```<code>for (var t in creditcards) {
  print(t['firstyear'].toString().replaceAll('/[^0-9]/', ''));
}
</code>```

Its output -

```<code>Rs.500
Rs.1000
Rs.500
Rs.0
Rs.499
Rs.499 + applicable taxes
Rs.500
Rs.500
Rs.495 + taxes
Rs.0
</code>```

I want to remove ' + applicable taxes' from this and parse it as integer.

答:
Without an example of how your String is it's hard to say what or how can we avoid certain patterns. This works as long as your Strings is always in the format Letters.numbers (any amount of letters, then a dot, then any amount of numbers)

```<code>String x = 'Rs.499 + applicable taxes';
String y = ' asdhui Euro.3243 + applicable taxes';
final RegExp firstRegExp = RegExp('[a-zA-Z]+(\.[0-9]+)');
final RegExp example = RegExp(r'\w+(\.\d+)'); //this is basically the same that the one above, but also check for numbers before the dot

//consider static final RegExp to avoid creating a new instance every time a value is checked

print(firstRegExp.stringMatch(x));
print(example.stringMatch(x));
print(example.stringMatch(y));

for (var t in creditcards) {
  print(example.stringMatch(t['firstyear'].toString()));
}
</code>```

RegExp check for the pattern [a-zA-Z] which means any letter, + match the previous one or more times (the prvious means it will match a one or more letters, but not space, tabs or any special character), (.[0-9]+) the . checks for a dot (\ is used because . is a special character in regExp and you want to search explicitly for the dot), [0-9]+ checks for one or more numbers after the dot

RegExp is used to check for patterns, check more about it in
regExp Dart and some examples about special characters in RegExp

Body:
I was trying to sort the string using -

for (var t in creditcards) {
  print(t['firstyear'].toString().replaceAll('/[^0-9]/', ''));
}

Its output -

Rs.500
Rs.1000
Rs.500
Rs.0
Rs.499
Rs.499 + applicable taxes
Rs.500
Rs.500
Rs.495 + taxes
Rs.0

I want to remove ' + applicable taxes' from this and parse it as integer.

Body:
Without an example of how your String is it's hard to say what or how can we avoid certain patterns. This works as long as your Strings is always in the format Letters.numbers (any amount of letters, then a dot, then any amount of numbers)

String x = 'Rs.499 + applicable taxes';
String y = ' asdhui Euro.3243 + applicable taxes';
final RegExp firstRegExp = RegExp('[a-zA-Z]+(\.[0-9]+)');
final RegExp example = RegExp(r'\w+(\.\d+)'); //this is basically the same that the one above, but also check for numbers before the dot

//consider static final RegExp to avoid creating a new instance every time a value is checked

print(firstRegExp.stringMatch(x));
print(example.stringMatch(x));
print(example.stringMatch(y));

for (var t in creditcards) {
  print(example.stringMatch(t['firstyear'].toString()));
}

RegExp check for the pattern [a-zA-Z] which means any letter, + match the previous one or more times (the prvious means it will match a one or more letters, but not space, tabs or any special character), (.[0-9]+) the . checks for a dot (\ is used because . is a special character in regExp and you want to search explicitly for the dot), [0-9]+ checks for one or more numbers after the dot

RegExp is used to check for patterns, check more about it in
regExp Dart and some examples about special characters in RegExp


问:
How to pass additional parameter to jquery $.(post) callback function?
I am writing this code where I am sending a sequence of asynchronous post requests by using a loop. When the callback related with the post request is called I want to use the loop variable which I directly cannot use because of javascript scoping rules. The code is like this:

```<code>for(i=0;i<10;i++)
{
$.post(url,requestData,function(data,status,xhr){
// use variable i
}
</code>```

I cannot directly use i due to scoping rules related to callbacks in javascript. So I want to pass 'i' as a parameter to the callback but the documentation says there can be only 3 parameters associated with this callback. Is there any way to pass additional parameter?

答:
I am using setTimeout here to demonstrate an async task (such as your $.post event).

for (i=0; i<10; i++) {
  setTimeout(() => {
    console.log(i);
  }, 1000);
}```
</div>
</div>
</p>

<p><code>i</code> has changed before you get to run your <code>console.log</code>.</p>

<p>Instead, you must retain a COPY of the <code>i</code> value at the appropriate number.</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>for (i=0; i<10; i++) {
  const idx = i;
  setTimeout(() => {
    console.log(idx);
  }, 1000);
}</code>```

Body:
I am writing this code where I am sending a sequence of asynchronous post requests by using a loop. When the callback related with the post request is called I want to use the loop variable which I directly cannot use because of javascript scoping rules. The code is like this:

for(i=0;i<10;i++)
{
$.post(url,requestData,function(data,status,xhr){
// use variable i
}

I cannot directly use i due to scoping rules related to callbacks in javascript. So I want to pass 'i' as a parameter to the callback but the documentation says there can be only 3 parameters associated with this callback. Is there any way to pass additional parameter?

Body:
I am using setTimeout here to demonstrate an async task (such as your $.post event).

for (i=0; i<10; i++) {
  setTimeout(() => {
    console.log(i);
  }, 1000);
}

i has changed before you get to run your console.log.

Instead, you must retain a COPY of the i value at the appropriate number.

for (i=0; i<10; i++) {
  const idx = i;
  setTimeout(() => {
    console.log(idx);
  }, 1000);
}


问:
Send Proactive Adaptive Card Message to MS Teams Channel
I have been trying to send proactive adaptive message card with buttons to a channel in MS TEAMS, but I am not able to find any solution to this.

Any solution in REST API (https://smba.trafficmanager.net) or BotBuilder SDK for nodejs is appreciated.

答:
Based on recommendation from Hilton , I could figure out this

You could design your own adaptive card here: Adaptive Card Design and edit attachments.body as per your requirement.

sending a proactive message

METHOD: POST
URL: https://smba.trafficmanager.net/{api}/v3/conversations/{channelId}/activities

sending reply as bot

METHOD: POST
URL: https://smba.trafficmanager.net/{api}/v3/conversations/{channelId};messageid={messageid}/activities

```<code>{
    "type": "message",
    "attachments": [
        {
       "contentType": "application/vnd.microsoft.card.adaptive",
       "content": {
        "type": "AdaptiveCard",
        "version": "1.0",
        "body": [
            {
                "type": "TextBlock",
                "size": "Medium",
                "weight": "Bolder",
                "text": "text"
            },
            {
                "type": "TextBlock",
                "size": "small",
                "text": "text",
                "wrap": true
            },
         ],
        "actions": [
            {
                "type": "Action.Submit",
                "title": "Accept",
                "data": {
                    "accept": true
                }
            },
            {
                "type": "Action.Submit",
                 "id": "id",
                  "title": "title",
                  "data": {
                    "msteams": {
                      "type": "task/fetch",
                    }
                  }
            }]
        }
        }
    ]
}
</code>```

Body:
Based on recommendation from Hilton , I could figure out this

You could design your own adaptive card here: Adaptive Card Design and edit attachments.body as per your requirement.

sending a proactive message

METHOD: POST
URL: https://smba.trafficmanager.net/{api}/v3/conversations/{channelId}/activities

sending reply as bot

METHOD: POST
URL: https://smba.trafficmanager.net/{api}/v3/conversations/{channelId};messageid={messageid}/activities

{
    "type": "message",
    "attachments": [
        {
       "contentType": "application/vnd.microsoft.card.adaptive",
       "content": {
        "type": "AdaptiveCard",
        "version": "1.0",
        "body": [
            {
                "type": "TextBlock",
                "size": "Medium",
                "weight": "Bolder",
                "text": "text"
            },
            {
                "type": "TextBlock",
                "size": "small",
                "text": "text",
                "wrap": true
            },
         ],
        "actions": [
            {
                "type": "Action.Submit",
                "title": "Accept",
                "data": {
                    "accept": true
                }
            },
            {
                "type": "Action.Submit",
                 "id": "id",
                  "title": "title",
                  "data": {
                    "msteams": {
                      "type": "task/fetch",
                    }
                  }
            }]
        }
        }
    ]
}


问:
Unwrapping issue with AXUIElementCopyAttributeValue in Mac OS
I'm trying to copy some information regarding an accessibility window option. Unfortunately, I can't resolve an error that's caused by the AXUIElementCopyAttributeValue method, despite passing in what appears to be all the correct types as parameters.

Code:

```<code>for entry in windowList! as Array {
  let ownerName: String = entry.object(forKey: kCGWindowName) as? String ?? "N/A"

  let ownerPID: Int = entry.object(forKey: kCGWindowOwnerPID) as? Int ?? 0
  let pid = Int32(ownerPID)

  //3. Get AXUIElement using PID
  let windowAccessibilityElem : AXUIElement = AXUIElementCreateApplication(pid)
  print(windowAccessibilityElem)

  var position : CFTypeRef? = nil

  /****
  * This line throws the error
  ****/
  let res : AXError = AXUIElementCopyAttributeValue(windowAccessibilityElem, kAXPositionAttribute as CFString, position as! UnsafeMutablePointer<CFTypeRef?>)

print("res is: \(res)")
...
</code>```

I'm new to Swift, yet I've read and re-read the documentation on optionals and it really isn't apparent what unexpected value is being passed in- I think it has to do with the position variable, but from what I see I should be passing in the reference correctly.  Any help would be apprediated.

答:
You have to assign the pointer to the variable with the in-out operator &

```<code>var position : CFTypeRef?
let res : AXError = AXUIElementCopyAttributeValue(windowAccessibilityElem,
                    kAXPositionAttribute as CFString,
                    &position)
</code>```

res contains the error on failure.

position contains the position on success.

In the documentation an in-out parameter is indicated by On return, ...

Body:
I'm trying to copy some information regarding an accessibility window option. Unfortunately, I can't resolve an error that's caused by the AXUIElementCopyAttributeValue method, despite passing in what appears to be all the correct types as parameters.

Code:

for entry in windowList! as Array {
  let ownerName: String = entry.object(forKey: kCGWindowName) as? String ?? "N/A"

  let ownerPID: Int = entry.object(forKey: kCGWindowOwnerPID) as? Int ?? 0
  let pid = Int32(ownerPID)

  //3. Get AXUIElement using PID
  let windowAccessibilityElem : AXUIElement = AXUIElementCreateApplication(pid)
  print(windowAccessibilityElem)

  var position : CFTypeRef? = nil

  /****
  * This line throws the error
  ****/
  let res : AXError = AXUIElementCopyAttributeValue(windowAccessibilityElem, kAXPositionAttribute as CFString, position as! UnsafeMutablePointer<CFTypeRef?>)

print("res is: \(res)")
...

I'm new to Swift, yet I've read and re-read the documentation on optionals and it really isn't apparent what unexpected value is being passed in- I think it has to do with the position variable, but from what I see I should be passing in the reference correctly.  Any help would be apprediated.

Body:
You have to assign the pointer to the variable with the in-out operator &

var position : CFTypeRef?
let res : AXError = AXUIElementCopyAttributeValue(windowAccessibilityElem,
                    kAXPositionAttribute as CFString,
                    &position)

res contains the error on failure.

position contains the position on success.

In the documentation an in-out parameter is indicated by On return, ...


问:
Cannot find module '@material-ui/core'
I had a problem with importing "@material-ui/core" to my react/typescript/webpack app. Always when I ran

webpack --config webpack.config.js

it failed with error

Cannot find module '@material-ui/core'

The same error was also underlined in the Visual Studio Code.

My index.tsx looked like this

```<code>import React from "react";
import ReactDOM from 'react-dom';
import { Button } from "@material-ui/core";

function App() {
    return <Button>Hi dudes</Button>
}
ReactDOM.render(<App />, document.getElementById("root"));
</code>```

答:
Set tsconfig.json as below

```<code>{
    "compilerOptions": {
        "outDir": "./dist",
        "target": "es5",
        "lib": ["es6", "dom"],
        "module": "ES6",
        "jsx": "react",
        "moduleResolution": "node",
        "noImplicitAny": true,
        "allowSyntheticDefaultImports": true,
        "allowJs": true
    },
    "exclude": [
        "dist"
    ]
}
</code>```

allowJs made it importable and other fixed webpack build.

Title: Cannot find module '@material-ui/core'

Body:
I had a problem with importing "@material-ui/core" to my react/typescript/webpack app. Always when I ran

webpack --config webpack.config.js

it failed with error

Cannot find module '@material-ui/core'

The same error was also underlined in the Visual Studio Code.

My index.tsx looked like this

import React from "react";
import ReactDOM from 'react-dom';
import { Button } from "@material-ui/core";

function App() {
    return <Button>Hi dudes</Button>
}
ReactDOM.render(<App />, document.getElementById("root"));

Body:
Set tsconfig.json as below

{
    "compilerOptions": {
        "outDir": "./dist",
        "target": "es5",
        "lib": ["es6", "dom"],
        "module": "ES6",
        "jsx": "react",
        "moduleResolution": "node",
        "noImplicitAny": true,
        "allowSyntheticDefaultImports": true,
        "allowJs": true
    },
    "exclude": [
        "dist"
    ]
}

allowJs made it importable and other fixed webpack build.


答:
You can use the variable i inside the callback if i is block scoped. Declare i with let keyword

```<code>for(let i=0;i<10;i++)
{
   $.post(url,requestData,function(data,status,xhr){
      // use variable i
   }
}
</code>```

Here's a demo

const $ = {
  post: function(callback) {
    setTimeout(() => callback(123, 'OK', null), 1000);
  }
}

for(let i=0;i<5;i++)
{
     $.post(function(data,status,xhr) {
         // use variable i
       console.log(i);
     })
}```

Title: How to pass additional parameter to jquery $.(post) callback function?

Body:
You can use the variable i inside the callback if i is block scoped. Declare i with let keyword

for(let i=0;i<10;i++)
{
   $.post(url,requestData,function(data,status,xhr){
      // use variable i
   }
}

Here's a demo

const $ = {
  post: function(callback) {
    setTimeout(() => callback(123, 'OK', null), 1000);
  }
}

for(let i=0;i<5;i++)
{
     $.post(function(data,status,xhr) {
         // use variable i
       console.log(i);
     })
}


问:
MATLAB Concatenate matrices with unequal dimensions
Is there any easy way to concatenate matrices with unequal dimensions using zero padding?

```<code>short = [1 2 3]';
long = [4 5 6 7]';
desiredResult = horzcat(short, long);
</code>```

I would like something like:

```<code>desiredResult =
1 4
2 5
3 6
0 7
</code>```

答:
Matrices in MATLAB are automatically grown and padded with zeroes when you assign to indices outside the current bounds of the matrix. For example:</p>

```<code>>> short = [1 2 3]';
>> long = [4 5 6 7]';
>> desiredResult(1:numel(short),1) = short;  %# Add short to column 1
>> desiredResult(1:numel(long),2) = long;    %# Add long to column 2
>> desiredResult

desiredResult =

     1     4
     2     5
     3     6
     0     7
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Is there any easy way to concatenate matrices with unequal dimensions using zero padding?

short = [1 2 3]';
long = [4 5 6 7]';
desiredResult = horzcat(short, long);

I would like something like:

desiredResult =
1 4
2 5
3 6
0 7

Body:
Matrices in MATLAB are automatically grown and padded with zeroes when you assign to indices outside the current bounds of the matrix. For example:

>> short = [1 2 3]';
>> long = [4 5 6 7]';
>> desiredResult(1:numel(short),1) = short;  %# Add short to column 1
>> desiredResult(1:numel(long),2) = long;    %# Add long to column 2
>> desiredResult

desiredResult =

     1     4
     2     5
     3     6
     0     7


问:
Activity not opening when clicking menu item
I am trying to tap on the "logout" option whose id is logout but nothing happens. Below is my code

```<code>@Override
public boolean onCreateOptionsMenu(Menu menu) {
    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.requestpayment,menu);
    return super.onCreateOptionsMenu(menu);
}

@Override
public boolean onOptionsItemSelected(@NonNull MenuItem item) {
    switch (item.getItemId()){
        case R.id.logout:
            Intent intent=new Intent(this,Logout.class);
            this.startActivity(intent);
            break;
    }
    return super.onOptionsItemSelected(item);
}
</code>```

please help

答:
If you chain a overridden method to its superclass(i.e call super.someMethod()), it means you are requesting the superclass to handle the implementation on its own.

You should return true here to tell that you successfully inflated the menu in this child Activity OR succesfully handled the onClick() event on the option items.

NOTE: Mostly, you need to chain a superclass method call, where superclass is reponsible for doing some critical stuffs. For eg:

```<code>public class ChildActivity extends AppCompatActivity{
@Override
    protected void onCreate(Bundle savedInstanceState) {
        //request superclass to do its critical stuffs
        super.onCreate(savedInstanceState);

        //continue with your logics here
}
</code>```

Body:
I am trying to tap on the "logout" option whose id is logout but nothing happens. Below is my code

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.requestpayment,menu);
    return super.onCreateOptionsMenu(menu);
}

@Override
public boolean onOptionsItemSelected(@NonNull MenuItem item) {
    switch (item.getItemId()){
        case R.id.logout:
            Intent intent=new Intent(this,Logout.class);
            this.startActivity(intent);
            break;
    }
    return super.onOptionsItemSelected(item);
}

please help

Body:
If you chain a overridden method to its superclass(i.e call super.someMethod()), it means you are requesting the superclass to handle the implementation on its own.

You should return true here to tell that you successfully inflated the menu in this child Activity OR succesfully handled the onClick() event on the option items.

NOTE: Mostly, you need to chain a superclass method call, where superclass is reponsible for doing some critical stuffs. For eg:

public class ChildActivity extends AppCompatActivity{
@Override
    protected void onCreate(Bundle savedInstanceState) {
        //request superclass to do its critical stuffs
        super.onCreate(savedInstanceState);

        //continue with your logics here
}


问:
How to get the current Azure FunctionNameAttribute?
How do I access the function name set with [FunctionName("SomeFunctionName")] programmatically inside the function?

This is the function attribute name and not the method name.

eg: In the code below, I would like to do something like if (!await PermissionsHelper.userHasPermission(getCurrentFunctionAttributeName(), TokenHelper.getTokenValue(req, "oid")))

```<code>
  public static class GetUser
  {
    [FunctionName("GetUser")]
    public static async Task<IActionResult> Run(
        [HttpTrigger(AuthorizationLevel.Anonymous, "get", Route = "users/{id}")]
          HttpRequest req,
          String id,
          ILogger log)
    {

      if (!await PermissionsHelper.userHasPermission("GetUser", TokenHelper.getTokenValue(req, "oid")))
        return new UnauthorizedResult();

</code>```

答:
try the following:</p>

```<code>public static class GetUser
{
  [FunctionName("GetUser")]
  public static async Task<IActionResult> Run(
    [HttpTrigger(AuthorizationLevel.Anonymous, "get", Route = "users/{id}")]
      HttpRequest req,
      String id,
      ExecutionContext executionContext,
      ILogger log)
  {

    if (!await PermissionsHelper.userHasPermission(executionContext.FunctionName, TokenHelper.getTokenValue(req, "oid")))
    return new UnauthorizedResult();
</code>```

Body:
How do I access the function name set with [FunctionName("SomeFunctionName")] programmatically inside the function?

This is the function attribute name and not the method name.

eg: In the code below, I would like to do something like if (!await PermissionsHelper.userHasPermission(getCurrentFunctionAttributeName(), TokenHelper.getTokenValue(req, "oid")))

  public static class GetUser
  {
    [FunctionName("GetUser")]
    public static async Task<IActionResult> Run(
        [HttpTrigger(AuthorizationLevel.Anonymous, "get", Route = "users/{id}")]
          HttpRequest req,
          String id,
          ILogger log)
    {

      if (!await PermissionsHelper.userHasPermission("GetUser", TokenHelper.getTokenValue(req, "oid")))
        return new UnauthorizedResult();

Body:
try the following:

public static class GetUser
{
  [FunctionName("GetUser")]
  public static async Task<IActionResult> Run(
    [HttpTrigger(AuthorizationLevel.Anonymous, "get", Route = "users/{id}")]
      HttpRequest req,
      String id,
      ExecutionContext executionContext,
      ILogger log)
  {

    if (!await PermissionsHelper.userHasPermission(executionContext.FunctionName, TokenHelper.getTokenValue(req, "oid")))
    return new UnauthorizedResult();


问:
Checking if input box is empty using Python
I just wanted to ask how can we check if the value of an input box is empty using Python, on the image below, I wanted to check the input box if empty and print some values if the statement is true also if it is false. Currently it is error because of the value (note that I did not put any value as indicated in the image with boxed red).

答:
You have to evaluate if the value attribute is an empty string </p>

```<code>if pashu == "":
</code>```

Body:
You have to evaluate if the value attribute is an empty string

if pashu == "":


问:
Zeppelin unable to start IPython kernel
For quite some time I've been facing an issue with Zeppelin which seem to be unable to launch IPython. I followed this guide and this one. Pyspark interpreter is correctly set with the right python path and IPython activated by default. However, when I try to run any of the examples in the guides such as:

```<code>%ipyspark
import pandas as pd
df = pd.DataFrame({'name':['a','b','c'], 'count':[12,24,18]})
z.show(df)
</code>```

I get the following error from the logs which doesn't tell much:

```<code>INFO [2018-11-30 15:17:08,653] ({pool-3-thread-2} IPythonInterpreter.java[setAdditionalPythonPath]:103) - setAdditionalPythonPath: /usr/hdp/current/spark2-client/python/lib/pyspark.zip:/usr/hdp/current/spark2-client/python/lib/py4j-0.10.7-src.zip:/usr/hdp/current/zeppelin-server/interpreter/lib/python
INFO [2018-11-30 15:17:08,654] ({pool-3-thread-2} IPythonInterpreter.java[open]:135) - Python Exec: python3
INFO [2018-11-30 15:17:09,189] ({pool-3-thread-2} IPythonInterpreter.java[checkIPythonPrerequisite]:195) - IPython prerequisite is meet
INFO [2018-11-30 15:17:09,191] ({pool-3-thread-2} IPythonInterpreter.java[open]:146) - Launching IPython Kernel at port: 39753
INFO [2018-11-30 15:17:09,191] ({pool-3-thread-2} IPythonInterpreter.java[open]:147) - Launching JVM Gateway at port: 36511
INFO [2018-11-30 15:17:09,402] ({pool-3-thread-2} IPythonInterpreter.java[setupIPythonEnv]:315) - PYTHONPATH:/usr/hdp/current/spark2-client/python/lib/pyspark.zip:/usr/hdp/current/spark2-client/python/lib/py4j-0.10.7-src.zip:/usr/hdp/current/zeppelin-server/interpreter/lib/python:/usr/hdp/current/spark2-client//python/lib/py4j-0.10.7-src.zip:/usr/hdp/current/spark2-client//python/:/usr/hdp/current/spark2-client//python:/usr/hdp/current/spark2-client//python/lib/py4j-0.8.2.1-src.zip
INFO [2018-11-30 15:17:09,743] ({pool-3-thread-2} IPythonInterpreter.java[launchIPythonKernel]:293) - Wait for IPython Kernel to be started
INFO [2018-11-30 15:17:09,844] ({pool-3-thread-2} IPythonInterpreter.java[launchIPythonKernel]:293) - Wait for IPython Kernel to be started
WARN [2018-11-30 15:17:09,926] ({Exec Default Executor} IPythonInterpreter.java[onProcessFailed]:394) - Exception happens in Python Process
org.apache.commons.exec.ExecuteException: Process exited with an error: 1 (Exit value: 1)
    at org.apache.commons.exec.DefaultExecutor.executeInternal(DefaultExecutor.java:404)
    at org.apache.commons.exec.DefaultExecutor.access$200(DefaultExecutor.java:48)
    at org.apache.commons.exec.DefaultExecutor$1.run(DefaultExecutor.java:200)
    at java.lang.Thread.run(Thread.java:745)
INFO [2018-11-30 15:17:09,944] ({pool-3-thread-2} IPythonInterpreter.java[launchIPythonKernel]:293) - Wait for IPython Kernel to be started
INFO [2018-11-30 15:17:10,044] ({pool-3-thread-2} IPythonInterpreter.java[launchIPythonKernel]:293) - Wait for IPython Kernel to be started
INFO [2018-11-30 15:17:39,465] ({pool-3-thread-2} IPythonInterpreter.java[launchIPythonKernel]:293) - Wait for IPython Kernel to be started
WARN [2018-11-30 15:17:39,466] ({pool-3-thread-2} PySparkInterpreter.java[open]:134) - Fail to open IPySparkInterpreter
java.lang.RuntimeException: Fail to open IPythonInterpreter
    at org.apache.zeppelin.python.IPythonInterpreter.open(IPythonInterpreter.java:157)
    at org.apache.zeppelin.spark.IPySparkInterpreter.open(IPySparkInterpreter.java:66)
    at org.apache.zeppelin.spark.PySparkInterpreter.open(PySparkInterpreter.java:129)
    at org.apache.zeppelin.interpreter.LazyOpenInterpreter.open(LazyOpenInterpreter.java:69)
    at org.apache.zeppelin.interpreter.remote.RemoteInterpreterServer$InterpretJob.jobRun(RemoteInterpreterServer.java:617)
    at org.apache.zeppelin.scheduler.Job.run(Job.java:188)
    at org.apache.zeppelin.scheduler.FIFOScheduler$1.run(FIFOScheduler.java:140)
    at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.access$201(ScheduledThreadPoolExecutor.java:180)
    at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:293)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at java.lang.Thread.run(Thread.java:745)
Caused by: java.io.IOException: Fail to launch IPython Kernel in 30 seconds
    at org.apache.zeppelin.python.IPythonInterpreter.launchIPythonKernel(IPythonInterpreter.java:297)
    at org.apache.zeppelin.python.IPythonInterpreter.open(IPythonInterpreter.java:154)
    at org.apache.zeppelin.spark.IPySparkInterpreter.open(IPySparkInterpreter.java:66)
    at org.apache.zeppelin.interpreter.LazyOpenInterpreter.open(LazyOpenInterpreter.java:69)
    at org.apache.zeppelin.interpreter.remote.RemoteInterpreterServer$InterpretJob.jobRun(RemoteInterpreterServer.java:617)
    at org.apache.zeppelin.scheduler.Job.run(Job.java:188)
    at org.apache.zeppelin.scheduler.FIFOScheduler$1.run(FIFOScheduler.java:140)
    at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.access$201(ScheduledThreadPoolExecutor.java:180)
    at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:293)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at java.lang.Thread.run(Thread.java:745)
INFO [2018-11-30 15:17:39,466] ({pool-3-thread-2} PySparkInterpreter.java[open]:140) - IPython is not available, use the native PySparkInterpreter
INFO [2018-11-30 15:17:39,533] ({pool-3-thread-2} PySparkInterpreter.java[createPythonScript]:118) - File /tmp/zeppelin_pyspark-5362368451576072994.py created
INFO [2018-11-30 15:17:39,534] ({pool-3-thread-2} Py4JUtils.java[createGatewayServer]:44) - Launching GatewayServer at 127.0.0.1:34508
INFO [2018-11-30 15:17:39,565] ({pool-3-thread-2} PySparkInterpreter.java[createGatewayServerAndStartScript]:265) - pythonExec: python3
INFO [2018-11-30 15:17:39,567] ({pool-3-thread-2} PySparkInterpreter.java[setupPySparkEnv]:236) - PYTHONPATH: /usr/hdp/current/spark2-client/python/lib/pyspark.zip:/usr/hdp/current/spark2-client/python/lib/py4j-0.10.7-src.zip:/usr/hdp/current/zeppelin-server/interpreter/lib/python:/usr/hdp/current/spark2-client//python/lib/py4j-0.10.7-src.zip:/usr/hdp/current/spark2-client//python/:/usr/hdp/current/spark2-client//python:/usr/hdp/current/spark2-client//python/lib/py4j-0.8.2.1-src.zip
INFO [2018-11-30 15:17:41,953] ({pool-3-thread-2} SchedulerFactory.java[jobFinished]:115) - Job 20181129-172919_2135817500 finished by scheduler interpreter_131607019
</code>```

I'm using HDP3.0.1 which comes with Zeppelin 0.8.0. All the nodes have python 3.7.1 installed with the latest version of jupyter and grpcio. From Zeppelin notebook I checked ipython and python version:

```<code>%pyspark
import sys
import IPython
print(IPython.__version__)
print(sys.version)
</code>```

7.2.0

3.7.1 (default, Nov 29 2018, 17:37:37)

I can start IPython from any node without a problem and Zeppelin can correctly get IPython's version. I tried to find if there are other logs than Zeppelin reporting the error but couldn't find anything.

Any idea of what could be preventing the launch of IPython kernel from Zeppelin?

答:
pip install --upgrade setuptools pip

or potentially

pip install --upgrade ipython

there are a few other quick things to try here github.com/jupyter/notebook/issues/270

Title: Zeppelin unable to start IPython kernel

Body:
For quite some time I've been facing an issue with Zeppelin which seem to be unable to launch IPython. I followed this guide and this one. Pyspark interpreter is correctly set with the right python path and IPython activated by default. However, when I try to run any of the examples in the guides such as:

%ipyspark
import pandas as pd
df = pd.DataFrame({'name':['a','b','c'], 'count':[12,24,18]})
z.show(df)

I get the following error from the logs which doesn't tell much:

INFO [2018-11-30 15:17:08,653] ({pool-3-thread-2} IPythonInterpreter.java[setAdditionalPythonPath]:103) - setAdditionalPythonPath: /usr/hdp/current/spark2-client/python/lib/pyspark.zip:/usr/hdp/current/spark2-client/python/lib/py4j-0.10.7-src.zip:/usr/hdp/current/zeppelin-server/interpreter/lib/python
INFO [2018-11-30 15:17:08,654] ({pool-3-thread-2} IPythonInterpreter.java[open]:135) - Python Exec: python3
INFO [2018-11-30 15:17:09,189] ({pool-3-thread-2} IPythonInterpreter.java[checkIPythonPrerequisite]:195) - IPython prerequisite is meet
INFO [2018-11-30 15:17:09,191] ({pool-3-thread-2} IPythonInterpreter.java[open]:146) - Launching IPython Kernel at port: 39753
INFO [2018-11-30 15:17:09,191] ({pool-3-thread-2} IPythonInterpreter.java[open]:147) - Launching JVM Gateway at port: 36511
INFO [2018-11-30 15:17:09,402] ({pool-3-thread-2} IPythonInterpreter.java[setupIPythonEnv]:315) - PYTHONPATH:/usr/hdp/current/spark2-client/python/lib/pyspark.zip:/usr/hdp/current/spark2-client/python/lib/py4j-0.10.7-src.zip:/usr/hdp/current/zeppelin-server/interpreter/lib/python:/usr/hdp/current/spark2-client//python/lib/py4j-0.10.7-src.zip:/usr/hdp/current/spark2-client//python/:/usr/hdp/current/spark2-client//python:/usr/hdp/current/spark2-client//python/lib/py4j-0.8.2.1-src.zip
INFO [2018-11-30 15:17:09,743] ({pool-3-thread-2} IPythonInterpreter.java[launchIPythonKernel]:293) - Wait for IPython Kernel to be started
INFO [2018-11-30 15:17:09,844] ({pool-3-thread-2} IPythonInterpreter.java[launchIPythonKernel]:293) - Wait for IPython Kernel to be started
WARN [2018-11-30 15:17:09,926] ({Exec Default Executor} IPythonInterpreter.java[onProcessFailed]:394) - Exception happens in Python Process
org.apache.commons.exec.ExecuteException: Process exited with an error: 1 (Exit value: 1)
    at org.apache.commons.exec.DefaultExecutor.executeInternal(DefaultExecutor.java:404)
    at org.apache.commons.exec.DefaultExecutor.access$200(DefaultExecutor.java:48)
    at org.apache.commons.exec.DefaultExecutor$1.run(DefaultExecutor.java:200)
    at java.lang.Thread.run(Thread.java:745)
INFO [2018-11-30 15:17:09,944] ({pool-3-thread-2} IPythonInterpreter.java[launchIPythonKernel]:293) - Wait for IPython Kernel to be started
INFO [2018-11-30 15:17:10,044] ({pool-3-thread-2} IPythonInterpreter.java[launchIPythonKernel]:293) - Wait for IPython Kernel to be started
INFO [2018-11-30 15:17:39,465] ({pool-3-thread-2} IPythonInterpreter.java[launchIPythonKernel]:293) - Wait for IPython Kernel to be started
WARN [2018-11-30 15:17:39,466] ({pool-3-thread-2} PySparkInterpreter.java[open]:134) - Fail to open IPySparkInterpreter
java.lang.RuntimeException: Fail to open IPythonInterpreter
    at org.apache.zeppelin.python.IPythonInterpreter.open(IPythonInterpreter.java:157)
    at org.apache.zeppelin.spark.IPySparkInterpreter.open(IPySparkInterpreter.java:66)
    at org.apache.zeppelin.spark.PySparkInterpreter.open(PySparkInterpreter.java:129)
    at org.apache.zeppelin.interpreter.LazyOpenInterpreter.open(LazyOpenInterpreter.java:69)
    at org.apache.zeppelin.interpreter.remote.RemoteInterpreterServer$InterpretJob.jobRun(RemoteInterpreterServer.java:617)
    at org.apache.zeppelin.scheduler.Job.run(Job.java:188)
    at org.apache.zeppelin.scheduler.FIFOScheduler$1.run(FIFOScheduler.java:140)
    at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.access$201(ScheduledThreadPoolExecutor.java:180)
    at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:293)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at java.lang.Thread.run(Thread.java:745)
Caused by: java.io.IOException: Fail to launch IPython Kernel in 30 seconds
    at org.apache.zeppelin.python.IPythonInterpreter.launchIPythonKernel(IPythonInterpreter.java:297)
    at org.apache.zeppelin.python.IPythonInterpreter.open(IPythonInterpreter.java:154)
    at org.apache.zeppelin.spark.IPySparkInterpreter.open(IPySparkInterpreter.java:66)
    at org.apache.zeppelin.interpreter.LazyOpenInterpreter.open(LazyOpenInterpreter.java:69)
    at org.apache.zeppelin.interpreter.remote.RemoteInterpreterServer$InterpretJob.jobRun(RemoteInterpreterServer.java:617)
    at org.apache.zeppelin.scheduler.Job.run(Job.java:188)
    at org.apache.zeppelin.scheduler.FIFOScheduler$1.run(FIFOScheduler.java:140)
    at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.access$201(ScheduledThreadPoolExecutor.java:180)
    at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:293)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at java.lang.Thread.run(Thread.java:745)
INFO [2018-11-30 15:17:39,466] ({pool-3-thread-2} PySparkInterpreter.java[open]:140) - IPython is not available, use the native PySparkInterpreter
INFO [2018-11-30 15:17:39,533] ({pool-3-thread-2} PySparkInterpreter.java[createPythonScript]:118) - File /tmp/zeppelin_pyspark-5362368451576072994.py created
INFO [2018-11-30 15:17:39,534] ({pool-3-thread-2} Py4JUtils.java[createGatewayServer]:44) - Launching GatewayServer at 127.0.0.1:34508
INFO [2018-11-30 15:17:39,565] ({pool-3-thread-2} PySparkInterpreter.java[createGatewayServerAndStartScript]:265) - pythonExec: python3
INFO [2018-11-30 15:17:39,567] ({pool-3-thread-2} PySparkInterpreter.java[setupPySparkEnv]:236) - PYTHONPATH: /usr/hdp/current/spark2-client/python/lib/pyspark.zip:/usr/hdp/current/spark2-client/python/lib/py4j-0.10.7-src.zip:/usr/hdp/current/zeppelin-server/interpreter/lib/python:/usr/hdp/current/spark2-client//python/lib/py4j-0.10.7-src.zip:/usr/hdp/current/spark2-client//python/:/usr/hdp/current/spark2-client//python:/usr/hdp/current/spark2-client//python/lib/py4j-0.8.2.1-src.zip
INFO [2018-11-30 15:17:41,953] ({pool-3-thread-2} SchedulerFactory.java[jobFinished]:115) - Job 20181129-172919_2135817500 finished by scheduler interpreter_131607019

I'm using HDP3.0.1 which comes with Zeppelin 0.8.0. All the nodes have python 3.7.1 installed with the latest version of jupyter and grpcio. From Zeppelin notebook I checked ipython and python version:

%pyspark
import sys
import IPython
print(IPython.__version__)
print(sys.version)

7.2.0

3.7.1 (default, Nov 29 2018, 17:37:37)

I can start IPython from any node without a problem and Zeppelin can correctly get IPython's version. I tried to find if there are other logs than Zeppelin reporting the error but couldn't find anything.

Any idea of what could be preventing the launch of IPython kernel from Zeppelin?


答:
Change the dates to date class which will turn blanks to NA automatically and then subtract days using difftime.

```<code>date_strings[] <- lapply(date_strings, as.Date, format = '%d-%m-%Y')
date_strings$diff_in_days = difftime(date_strings$b, date_strings$a,
                                      units = "days")

date_strings
#           a          b diff_in_days
#1 2012-07-02       <NA>           NA
#2 2012-08-18       <NA>           NA
#3 2012-08-13       <NA>           NA
#4 2012-04-16       <NA>           NA
#5 2012-04-26       <NA>           NA
#6 2012-05-03 2012-05-12            9
</code>```

Or directly subtract

```<code>date_strings$diff_in_days = date_strings$b -  date_strings$a
</code>```

data

```<code>date_strings <- structure(list(a = c("02-07-2012", "18-08-2012", "13-08-2012",
"16-04-2012", "26-04-2012", "03-05-2012"), b = c("", "", "",
"", "", "12-05-2012")), class = "data.frame", row.names = c(NA, -6L))
</code>```

Title: Calculate the difference in time in Days for Character Dates and also with Blank Spaces in one of the column

Body:
I have the following data, Both columns are dates & have to take the difference in days. However most of the values in one of date column is blank so I have to return NA for them.

a              b
02-07-2012

18-08-2012

13-08-2012

16-04-2012

26-04-2012

03-05-2012  12-05-2012

09-06-2012

30-05-2012

22-06-2012

05-07-2012

30-06-2012

09-05-2012

22-06-2012

02-07-2012

17-07-2012

17-08-2012

16-07-2012

01-08-2012

05-08-2012

17-08-2012

30-04-2012

05-07-2012

07-04-2012

27-04-2012

21-06-2012

03-07-2012

21-07-2012

24-04-2012

05-06-2012

03-07-2012

02-04-2012  01-06-2012

06-04-2012

15-04-2012

16-06-2012

01-08-2012

13-05-2012

09-07-2012

09-07-2012

18-04-2012

09-08-2012

10-04-2012

12-05-2012

04-04-2012

04-06-2012  04-06-2012

15-06-2012

02-07-2012

05-07-2012

21-08-2012

19-07-2012

06-08-2012

15-06-2012

06-04-2012

04-06-2012

23-07-2012

06-04-2012

12-04-2012  11-06-2012

24-05-2012

03-08-2012

04-05-2012  09-05-2012

07-05-2012

07-06-2012

06-07-2012

13-07-2012

26-07-2012

26-04-2012

22-06-2012

26-07-2012

12-04-2012

07-08-2012

27-06-2012

03-04-2012  02-06-2012

13-04-2012

28-07-2012

07-05-2012

29-06-2012

03-04-2012  02-06-2012

04-04-2012

04-04-2012  24-05-2012

04-04-2012

05-04-2012

07-04-2012

10-04-2012

11-04-2012

13-04-2012

13-04-2012

13-04-2012

13-04-2012

14-04-2012

14-04-2012

14-04-2012

18-04-2012

19-04-2012

21-04-2012

25-04-2012

25-04-2012

26-04-2012

26-04-2012

26-04-2012

27-04-2012

30-04-2012

04-06-2012

04-06-2012

05-06-2012

05-06-2012

05-06-2012

05-06-2012

05-06-2012  16-07-2012

06-06-2012  29-06-2012

I tried the following but couldnt succeed

date_strings[date_strings==""]<-NA      # Replaced blank spaces with NA & removed them
head(date_strings)
newdata<-na.omit(date_strings)
str(newdata)

newdata$a<-as.Date(newdata$a,"%m%d%y")
newdata$b<-as.Date(newdata$b,"%m%d%y")

diff_in_days = difftime(newdata$a, newdata$b, units = "days") # days

Body:
Change the dates to date class which will turn blanks to NA automatically and then subtract days using difftime.

date_strings[] <- lapply(date_strings, as.Date, format = '%d-%m-%Y')
date_strings$diff_in_days = difftime(date_strings$b, date_strings$a,
                                      units = "days")

date_strings
#           a          b diff_in_days
#1 2012-07-02       <NA>           NA
#2 2012-08-18       <NA>           NA
#3 2012-08-13       <NA>           NA
#4 2012-04-16       <NA>           NA
#5 2012-04-26       <NA>           NA
#6 2012-05-03 2012-05-12            9

Or directly subtract

date_strings$diff_in_days = date_strings$b -  date_strings$a

data

date_strings <- structure(list(a = c("02-07-2012", "18-08-2012", "13-08-2012",
"16-04-2012", "26-04-2012", "03-05-2012"), b = c("", "", "",
"", "", "12-05-2012")), class = "data.frame", row.names = c(NA, -6L))


问:
Developer Tools: Instruments command line interface
Do you know if it is possible to launch or attach UIAutomation tool to a process on the actual iOS device using Instruments command line interface ?

I know that there is command line interface for instruments but so far I haven't been able to connect to the device.

答:
There is currently a bug in the command line Instruments interface. It's documented here:

http://openradar.appspot.com/9150033

I filed a bug through my job, and they closed it as a dupe of this one.

When it is fixed, it should work like the following:

http://developer.apple.com/library/mac/#documentation/Darwin/Reference/ManPages/man1/instruments.1.html

The workarounds would all be hacky, the Instruments product lacks osascript extensions as well. I'm going to be investigating hacks, while waiting for this fix to come through.

ContentLicense: CC BY-SA 2.5


问:
How to convert this function into a pure function?
I have the following function.

const array = [1, 2, 3];

// Impure function

function addElementToArray(element) {
  array.push(element);
}
```

<p>This is an impure function because it mutates the global array. So, I thought that giving the whole array as a function argument will make the function pure.</p>

```function addElement(array, element) {
  array.push(element);
}
```

But, I found that it has also side effects.

so, what would be the best approach to make it a pure function?

答:
Using the push method, you can simply make a local copy of array inside the function, push the item into the copied array, and then finally return the array.
Here's is the code.

function addNewelement(array,item){
    const newArr = array.slice();
    newArr.push(item);
    return newArr;
}
```

Now, it will not change the global array.

Body:
I have the following function.

const array = [1, 2, 3];

// Impure function

function addElementToArray(element) {
  array.push(element);
}

This is an impure function because it mutates the global array. So, I thought that giving the whole array as a function argument will make the function pure.

function addElement(array, element) {
  array.push(element);
}

But, I found that it has also side effects.

so, what would be the best approach to make it a pure function?

Body:
Using the push method, you can simply make a local copy of array inside the function, push the item into the copied array, and then finally return the array.
Here's is the code.

function addNewelement(array,item){
    const newArr = array.slice();
    newArr.push(item);
    return newArr;
}

Now, it will not change the global array.


问:
List displays its precedent value
So I am using a modelmapper to convert all my entities, worked fine until now.
I have an entity TaskDTO with a List of Double in its attributes.
I can recuperate this list but once a request is made, all next requests get me the same list.

Here is the part for my converter:

```<code>public static TaskDTO converTaskToDTO(Task source) {
    List<Double> icList = new ArrayList<>();
    for (ChargeInitial c : source.getCharge()) {
        icList.add(c.getCharge());
    }
    System.out.println(icList);
    TypeMap<Task, TaskDTO> typeMap = modelMapper.getTypeMap(Task.class, TaskDTO.class);
    if (typeMap == null) {

        modelMapper.addMappings(new PropertyMap<Task, TaskDTO>() {
            @Override
            protected void configure() {
                map().setLot(source.getLot().getName());
                map().setProject(source.getLot().getProject().getName());
                map().setCollaborator(source.getCollaborator().getEmail());
                map().setCharge(icList);

            }
        });
    }

    return modelMapper.map(source, TaskDTO.class);

}
</code>```

However the sysout prints the right list for me.

For exemple if in the first request I get charge[1,2] for that list, the second request will be also [1,2] for every charge list even though I get the right esult which is [1,2,3,4,5] in my system.out.

What could be the problem?

EDIT

I changed the method setCharge in TaskDTO as follows, works fine.

```<code>public void setCharge(List<ChargeInitial> charge) {
    List<Double> list = new ArrayList<>();
    for (ChargeInitial c : charge) {
        list.add(c.getCharge());
    }
    this.charge=list;
}
</code>```

答:
You can use Converter, List<ChargeInitial> to List<Double>.

```<code>public static TaskDTO converTaskToDTO(Task source) {

    TypeMap<Task, TaskDTO> typeMap = modelMapper.getTypeMap(Task.class, TaskDTO.class);
    if (typeMap == null) {

        PropertyMap<Task, TaskDTO> mapping = new PropertyMap<Task, TaskDTO>() {
            @Override
            protected void configure() {
                map().setLot(source.getLot().getName());
                map().setProject(source.getLot().getProject().getName());
                map().setCollaborator(source.getCollaborator().getEmail());
            }
        };
        modelMapper.addMappings(mapping);

        Converter<List<ChargeInitial>, List<Double>> chargeInitialConverter = new AbstractConverter<>() {
            @Override
            protected List<Double> convert(List<ChargeInitial> source) {
                List<Double> icList = new ArrayList<>();
                for (ChargeInitial c : source) {
                    icList.add(c.getCharge());
                }
                System.out.println(icList);
                return icList;
            }
        };
        modelMapper.addConverter(chargeInitialConverter);

    }

    return modelMapper.map(source, TaskDTO.class);

}
</code>```

Title: List displays its precedent value

Body:
So I am using a modelmapper to convert all my entities, worked fine until now.
I have an entity TaskDTO with a List of Double in its attributes.
I can recuperate this list but once a request is made, all next requests get me the same list.

Here is the part for my converter:

public static TaskDTO converTaskToDTO(Task source) {
    List<Double> icList = new ArrayList<>();
    for (ChargeInitial c : source.getCharge()) {
        icList.add(c.getCharge());
    }
    System.out.println(icList);
    TypeMap<Task, TaskDTO> typeMap = modelMapper.getTypeMap(Task.class, TaskDTO.class);
    if (typeMap == null) {

        modelMapper.addMappings(new PropertyMap<Task, TaskDTO>() {
            @Override
            protected void configure() {
                map().setLot(source.getLot().getName());
                map().setProject(source.getLot().getProject().getName());
                map().setCollaborator(source.getCollaborator().getEmail());
                map().setCharge(icList);

            }
        });
    }

    return modelMapper.map(source, TaskDTO.class);

}

However the sysout prints the right list for me.

For exemple if in the first request I get charge[1,2] for that list, the second request will be also [1,2] for every charge list even though I get the right esult which is [1,2,3,4,5] in my system.out.

What could be the problem?

EDIT

I changed the method setCharge in TaskDTO as follows, works fine.

public void setCharge(List<ChargeInitial> charge) {
    List<Double> list = new ArrayList<>();
    for (ChargeInitial c : charge) {
        list.add(c.getCharge());
    }
    this.charge=list;
}

Body:
You can use Converter, List<ChargeInitial> to List<Double>.

public static TaskDTO converTaskToDTO(Task source) {

    TypeMap<Task, TaskDTO> typeMap = modelMapper.getTypeMap(Task.class, TaskDTO.class);
    if (typeMap == null) {

        PropertyMap<Task, TaskDTO> mapping = new PropertyMap<Task, TaskDTO>() {
            @Override
            protected void configure() {
                map().setLot(source.getLot().getName());
                map().setProject(source.getLot().getProject().getName());
                map().setCollaborator(source.getCollaborator().getEmail());
            }
        };
        modelMapper.addMappings(mapping);

        Converter<List<ChargeInitial>, List<Double>> chargeInitialConverter = new AbstractConverter<>() {
            @Override
            protected List<Double> convert(List<ChargeInitial> source) {
                List<Double> icList = new ArrayList<>();
                for (ChargeInitial c : source) {
                    icList.add(c.getCharge());
                }
                System.out.println(icList);
                return icList;
            }
        };
        modelMapper.addConverter(chargeInitialConverter);

    }

    return modelMapper.map(source, TaskDTO.class);

}


问:
How to assign an object from column values in Google Sheet?
I have a google sheet with some data in a single column.
How to assign these values to new object like {'value[0]':value[0], 'value[1]':value[1],..., 'value[i]':value[i]}?

I wrote this script, but it assigns pair from last value of names only:

```<code>function getIngredientsList() {
  const url = "SPREADSHEET_URL";
  const ss = SpreadsheetApp.openByUrl(url);
  const ws = ss.getSheetByName('Base');
  const names = ws.getRange(2, 3, ws.getLastRow() - 1).getValues().map(a => a[0]);
  let nameList;
  for (let i = 0; i < names.length; i++){
    if (names[i] !== ""){
      let name = {[names[i]]:names[i]};
      nameList = Object.assign(name);
    }
  }
  return nameList;
}
</code>```

Where I'm wrong and how to fix it?

答:
I believe your goal as follows.

You want to retrieve the values from the cells "C2:C28", and want to create an object that the key and value are the same.

For this, how about this modification? The arguments of Object.assign() is Object.assign(target, ...sources). So in your script, nameList of let nameList = {} is required to be used like nameList = Object.assign(nameList, name).

From:

```<code>let nameList;
for (let i = 0; i < names.length; i++){
  if (names[i] !== ""){
    let name = {[names[i]]:names[i]};
    nameList = Object.assign(name);
  }
}
</code>```

To:

```<code>let nameList = {};  // Modified
for (let i = 0; i < names.length; i++){
  if (names[i] !== ""){
    let name = {[names[i]]:names[i]};
    nameList = Object.assign(nameList, name);  // Modified
  }
}
</code>```

Or, as other pattern, when reduce is used, the following script can also return the same value with above modified script.

```<code>const nameList = ws.getRange(2, 3, ws.getLastRow() - 1).getValues()
.reduce((o, [e]) => {
  if (e != "") Object.assign(o, {[e]: e});
  return o;
}, {});
</code>```

Reference:

Object.assign()

Body:
I have a google sheet with some data in a single column.
How to assign these values to new object like {'value[0]':value[0], 'value[1]':value[1],..., 'value[i]':value[i]}?

I wrote this script, but it assigns pair from last value of names only:

function getIngredientsList() {
  const url = "SPREADSHEET_URL";
  const ss = SpreadsheetApp.openByUrl(url);
  const ws = ss.getSheetByName('Base');
  const names = ws.getRange(2, 3, ws.getLastRow() - 1).getValues().map(a => a[0]);
  let nameList;
  for (let i = 0; i < names.length; i++){
    if (names[i] !== ""){
      let name = {[names[i]]:names[i]};
      nameList = Object.assign(name);
    }
  }
  return nameList;
}

Where I'm wrong and how to fix it?

Body:
I believe your goal as follows.

You want to retrieve the values from the cells "C2:C28", and want to create an object that the key and value are the same.

For this, how about this modification? The arguments of Object.assign() is Object.assign(target, ...sources). So in your script, nameList of let nameList = {} is required to be used like nameList = Object.assign(nameList, name).

From:

let nameList;
for (let i = 0; i < names.length; i++){
  if (names[i] !== ""){
    let name = {[names[i]]:names[i]};
    nameList = Object.assign(name);
  }
}

To:

let nameList = {};  // Modified
for (let i = 0; i < names.length; i++){
  if (names[i] !== ""){
    let name = {[names[i]]:names[i]};
    nameList = Object.assign(nameList, name);  // Modified
  }
}

Or, as other pattern, when reduce is used, the following script can also return the same value with above modified script.

const nameList = ws.getRange(2, 3, ws.getLastRow() - 1).getValues()
.reduce((o, [e]) => {
  if (e != "") Object.assign(o, {[e]: e});
  return o;
}, {});

Reference:

Object.assign()


问:
Get Blobs with no metadata
I am setting blob metadata of all the blobs in a container using an azure function. But due to huge number of blobs the function time outs. If I run the function again it again starts getting the blobs which already have metadata. Is there a way in which I can get only the blobs which do not have metadata?</p>

答:
Is there a way in which I can get only the blobs which do not have
  metadata?

It is not possible to do so. Azure Blob Storage does not have server-side filtering capability on metadata. In fact, only thing you could perform server-side filter is on blob name prefix. What you need to do (and this is something you're already doing) is list all blobs and then filter out the blobs with no metadata in your function code.

```<code>var response = await container.ListBlobsSegmentedAsync(prefix, true, BlobListingDetails.None, 200, continuationToken, null, null); continuationToken = response.ContinuationToken;
</code>```

I noticed that in your code above you are only fetching 200 blobs at a time. This is not really efficient. In a single request to Azure Blob Storage, you can ask Storage Service to return a maximum of 5000 blobs. If you change this 200 to 5000, then the number of requests that you'll make to Storage will reduce considerably and there's a possibility that you will be able to get all blobs before the function times out.

Title: Get Blobs with no metadata

Body:
Is there a way in which I can get only the blobs which do not have
  metadata?

It is not possible to do so. Azure Blob Storage does not have server-side filtering capability on metadata. In fact, only thing you could perform server-side filter is on blob name prefix. What you need to do (and this is something you're already doing) is list all blobs and then filter out the blobs with no metadata in your function code.

var response = await container.ListBlobsSegmentedAsync(prefix, true, BlobListingDetails.None, 200, continuationToken, null, null); continuationToken = response.ContinuationToken;

I noticed that in your code above you are only fetching 200 blobs at a time. This is not really efficient. In a single request to Azure Blob Storage, you can ask Storage Service to return a maximum of 5000 blobs. If you change this 200 to 5000, then the number of requests that you'll make to Storage will reduce considerably and there's a possibility that you will be able to get all blobs before the function times out.


问:
In php, Number of rows and columns in a 2 D array?
I have a two dimensional array with unknown number of elements.

$two_darray[row][column]; //there will be an unknown integer values instead of row and column keywords

If I were to write a for loop as follows, how can I determine how many rows and columns in my $two_darray. Can you please tell me if there is a library function in php that can tell me the value inside [????] [????]

```<code>for($row=0; $row<………; $row++)
{
    for($column =0; $column  <………; $ column ++)
    {
        echo $two_darray[$row][$column];
    }
    echo “\n end of one column \n”;
}
</code>```

I really need to know the value of rows and columns in order to perform other calculations.

答:
for a php indexed two-dimensional array:

```<code>$arName = array(
  array(10,11,12,13),
  array(20,21,22,23),
  array(30,31,32,33)
);

$col_size=count($arName[$index=0]);

for($row=0; $row<count($arName); $row++)
{
  for($col=0; $col<$col_size; $col++)
  {
    echo $arName[$row][$col]. " ";
  }
  echo "<br>";
}
</code>```

Output:

```<code>10 11 12 13
20 21 22 23
30 31 32 33
</code>```

Body:
I have a two dimensional array with unknown number of elements.

$two_darray[row][column]; //there will be an unknown integer values instead of row and column keywords

If I were to write a for loop as follows, how can I determine how many rows and columns in my $two_darray. Can you please tell me if there is a library function in php that can tell me the value inside [????] [????]

for($row=0; $row<………; $row++)
{
    for($column =0; $column  <………; $ column ++)
    {
        echo $two_darray[$row][$column];
    }
    echo “\n end of one column \n”;
}

I really need to know the value of rows and columns in order to perform other calculations.

Body:
for a php indexed two-dimensional array:

$arName = array(
  array(10,11,12,13),
  array(20,21,22,23),
  array(30,31,32,33)
);

$col_size=count($arName[$index=0]);

for($row=0; $row<count($arName); $row++)
{
  for($col=0; $col<$col_size; $col++)
  {
    echo $arName[$row][$col]. " ";
  }
  echo "<br>";
}

Output:

10 11 12 13
20 21 22 23
30 31 32 33


问:
Splitting /proc/cmdline arguments with spaces
Most scripts that parse /proc/cmdline break it up into words and then filter out arguments with a case statement, example:

```<code>CMDLINE="quiet union=aufs wlan=FOO"
for x in $CMDLINE
do
»···case $x in
»···»···wlan=*)
»···»···echo "${x//wlan=}"
»···»···;;
»···esac
done
</code>```

The problem is when the WLAN ESSID has spaces. Users expect to set wlan='FOO
BAR' (like a shell variable) and then get the unexpected result of 'FOO with the above code, since the for loop splits on spaces.

Is there a better way of parsing the /proc/cmdline from a shell script falling short of almost evaling it?

Or is there some quoting tricks? I was thinking I could perhaps ask users to entity quote spaces and decode like so: /bin/busybox httpd -d "FOO%20BAR". Or is that a bad solution?

答:
You could do something like the following using bash, which would turn those arguments in to variables like $cmdline_union and $cmdline_wlan:

```<code>bash -c "for i in $(cat /proc/cmdline); do printf \"cmdline_%q\n\" \"\$i\"; done" | grep = > /tmp/cmdline.sh
. /tmp/cmdline.sh
</code>```

Then you would quote and/or escape things just like you would in a normal shell.

Body:
Most scripts that parse /proc/cmdline break it up into words and then filter out arguments with a case statement, example:

CMDLINE="quiet union=aufs wlan=FOO"
for x in $CMDLINE
do
»···case $x in
»···»···wlan=*)
»···»···echo "${x//wlan=}"
»···»···;;
»···esac
done

The problem is when the WLAN ESSID has spaces. Users expect to set wlan='FOO
BAR' (like a shell variable) and then get the unexpected result of 'FOO with the above code, since the for loop splits on spaces.

Is there a better way of parsing the /proc/cmdline from a shell script falling short of almost evaling it?

Or is there some quoting tricks? I was thinking I could perhaps ask users to entity quote spaces and decode like so: /bin/busybox httpd -d "FOO%20BAR". Or is that a bad solution?

Body:
You could do something like the following using bash, which would turn those arguments in to variables like $cmdline_union and $cmdline_wlan:

bash -c "for i in $(cat /proc/cmdline); do printf \"cmdline_%q\n\" \"\$i\"; done" | grep = > /tmp/cmdline.sh
. /tmp/cmdline.sh

Then you would quote and/or escape things just like you would in a normal shell.


问:
Referencing Docker container from server-side (from another container) AND from client-side (browser) with same URL
I have two docker containers frontend and data-service.

frontend is using NextJS which is only relevant because NextJS has a method called getInitialProps() which can be run on the server, or can be run in the visitor's browser (I have no control over this).

In getInitialProps() I need to call an API to get the data for the page:

fetch('http://data-service:3001/user/123').then(...
```

<p>When this is called on the server the API returns fine because my frontend container has access to the internal docker network and therefor can reference the data-service using the hostname <code>http://data-service</code>.</p>

<p>When this is called on the client, however, it fails (obviously) because Docker is now exposed as <code>http://localhost</code> and I can't reference <code>http://data-service</code> anymore.</p>

<p>How can I configure Docker so that I can use 1 URL for both use cases. I would prefer not to have to figure out which environment I'm in in my NextJS code if possible.</p>

<p>If seeing my docker-compose is useful I have included it below:</p>

```version: '2.2'
services:
  data-service:
    build: ./data-service
    command: npm run dev
    volumes:
      - ./data-service:/usr/src/app/
      - /usr/src/app/node_modules
    ports:
      - "3001:3001"
    environment:
      SDKKEY: "whatever"
  frontend:
    build: ./frontend
    command: npm run dev
    volumes:
      - ./frontend:/usr/src/app/
      - /usr/src/app/node_modules
    environment:
      API_PORT: "3000"
      API_HOST: "http://catalog-service"
    ports:
      - "3000:3000"
```

答:
The most elegant solution I've found is described in this post: Docker-compose make 2 microservices (frontend+backend) communicate to each other with http requests

Example implementation:

In next.config.js:

```<code>module.exports = {
  serverRuntimeConfig: {
    // Will only be available on the server side
    URI: 'your-docker-uri:port'
  },
  publicRuntimeConfig: {
    // Will be available on both server and client
    URI: 'http://localhost:port'
  }
}
</code>```

In pages/index.js:

```<code>import getConfig from 'next/config';
const { serverRuntimeConfig, publicRuntimeConfig } = getConfig();
const API_URI = serverRuntimeConfig.apiUrl || publicRuntimeConfig.apiUrl;

const Index = ({ json }) => <div>Index</div>;

Index.getInitialProps = async () => {
       ...
       const res = await fetch(`${API_URI}/endpoint`);
       ...
}
</code>```

Body:
I have two docker containers frontend and data-service.

frontend is using NextJS which is only relevant because NextJS has a method called getInitialProps() which can be run on the server, or can be run in the visitor's browser (I have no control over this).

In getInitialProps() I need to call an API to get the data for the page:

fetch('http://data-service:3001/user/123').then(...

When this is called on the server the API returns fine because my frontend container has access to the internal docker network and therefor can reference the data-service using the hostname http://data-service.

When this is called on the client, however, it fails (obviously) because Docker is now exposed as http://localhost and I can't reference http://data-service anymore.

How can I configure Docker so that I can use 1 URL for both use cases. I would prefer not to have to figure out which environment I'm in in my NextJS code if possible.

If seeing my docker-compose is useful I have included it below:

version: '2.2'
services:
  data-service:
    build: ./data-service
    command: npm run dev
    volumes:
      - ./data-service:/usr/src/app/
      - /usr/src/app/node_modules
    ports:
      - "3001:3001"
    environment:
      SDKKEY: "whatever"
  frontend:
    build: ./frontend
    command: npm run dev
    volumes:
      - ./frontend:/usr/src/app/
      - /usr/src/app/node_modules
    environment:
      API_PORT: "3000"
      API_HOST: "http://catalog-service"
    ports:
      - "3000:3000"

Body:
The most elegant solution I've found is described in this post: Docker-compose make 2 microservices (frontend+backend) communicate to each other with http requests

Example implementation:

In next.config.js:

module.exports = {
  serverRuntimeConfig: {
    // Will only be available on the server side
    URI: 'your-docker-uri:port'
  },
  publicRuntimeConfig: {
    // Will be available on both server and client
    URI: 'http://localhost:port'
  }
}

In pages/index.js:

import getConfig from 'next/config';
const { serverRuntimeConfig, publicRuntimeConfig } = getConfig();
const API_URI = serverRuntimeConfig.apiUrl || publicRuntimeConfig.apiUrl;

const Index = ({ json }) => <div>Index</div>;

Index.getInitialProps = async () => {
       ...
       const res = await fetch(`${API_URI}/endpoint`);
       ...
}


问:
MediaRecorder - How to play chunk/blob of video without black frames?
I am recording shorts videos of my webcam about 1 sec thanks to MediaRecorder. When the video is recorded, I push it into a table. At the end, when I have some videos pushed into the table, I try to read each video one after one (like only one big video). But I have some kind of black frames between each video. It is as if the transition between the video is not perfect and reading is choppy. Someone could tell me the reason why it occurs ?

Here is some part of the code I use to record the small videos:

```<code>                navigator.mediaDevices.getUserMedia().then(function(media_stream) {
                    var recorder = new MediaRecorder(media_stream);

                    recorder.start();

                    recorder.onstart = function(event) {
                        setTimeout(function(){ recorder.stop(); }, 1000);
                    };

                    recorder.ondataavailable = event => {
                        tableau_rondelle.push(event.data);
                    };

                    recorder.onstop = function(event) {
                        recorder.start();
                    };
                })
                .catch(function(error) {});
</code>```

And here is some part of the code I use to read the big video:

```<code>                            document.getElementById("video_output").onended = function(event) {
                                document.getElementById("video_output").src = URL.createObjectURL(tableau_rondelle.shift());
                            };

                            document.getElementById("video_output").src = URL.createObjectURL(tableau_rondelle.shift());
</code>```

Thanks.

答: Try using recorder.pause and recorder.resume to tackle this problem.</p>

Body:
I am recording shorts videos of my webcam about 1 sec thanks to MediaRecorder. When the video is recorded, I push it into a table. At the end, when I have some videos pushed into the table, I try to read each video one after one (like only one big video). But I have some kind of black frames between each video. It is as if the transition between the video is not perfect and reading is choppy. Someone could tell me the reason why it occurs ?

Here is some part of the code I use to record the small videos:

                navigator.mediaDevices.getUserMedia().then(function(media_stream) {
                    var recorder = new MediaRecorder(media_stream);

                    recorder.start();

                    recorder.onstart = function(event) {
                        setTimeout(function(){ recorder.stop(); }, 1000);
                    };

                    recorder.ondataavailable = event => {
                        tableau_rondelle.push(event.data);
                    };

                    recorder.onstop = function(event) {
                        recorder.start();
                    };
                })
                .catch(function(error) {});

And here is some part of the code I use to read the big video:

                            document.getElementById("video_output").onended = function(event) {
                                document.getElementById("video_output").src = URL.createObjectURL(tableau_rondelle.shift());
                            };

                            document.getElementById("video_output").src = URL.createObjectURL(tableau_rondelle.shift());

Thanks.


问:
writeImageDataToSavedPhotosAlbum Slows Dramatically After A Few Uses
I save images to the iPhone's photo album using the api "writeImageDataToSavedPhotosAlbum". However, after several uses (such as 4), it begins to take approximately twice as long each time to save.

I have created a test method to reproduce it, where it saves the exact same image each time. The method is as follows:

```<code>-(IBAction)testButton {
    NSData *data = [NSData dataWithContentsOfFile:[[self photosDirectory] stringByAppendingPathComponent:[[self contentsOfPhotoDirectory] objectAtIndex:0]]];
    ALAssetsLibrary *al = [[ALAssetsLibrary alloc] init];
    __block NSDate *date = [[NSDate date] retain];
    [al writeImageDataToSavedPhotosAlbum:data metadata:nil completionBlock:^(NSURL *assetURL, NSError *error) {
        NSLog(@"Saving Time: %g", [[NSDate date] timeIntervalSinceDate:date]);
        [date release];
    }];
    [al release];
}
</code>```

On a freshly restarted iPhone 4, I get the following save times.

```<code>2011-06-01 21:23:13.641 myapp[95:707] Saving Time: 5.30819
2011-06-01 21:23:17.101 myapp[95:707] Saving Time: 1.5311
2011-06-01 21:23:21.916 myapp[95:707] Saving Time: 2.52412
2011-06-01 21:23:25.974 myapp[95:707] Saving Time: 2.85623
2011-06-01 21:23:32.275 myapp[95:707] Saving Time: 4.93484
2011-06-01 21:23:42.024 myapp[95:707] Saving Time: 7.93288
2011-06-01 21:24:00.317 myapp[95:707] Saving Time: 15.8561
2011-06-01 21:24:33.199 myapp[95:707] Saving Time: 29.7571
</code>```

What is wrong?

答:
Possibly the problem is that you are using memory and not freeing it, so later saves generate a lot of memory warnings... this is exactly the kind of thing the Time Profiler and Object Alloc instruments should be able to help you with, figuring out why it slows after just a few images.

In my own app I do not think I saw that much of a slowdown after repeated shots.

Body:
I save images to the iPhone's photo album using the api "writeImageDataToSavedPhotosAlbum". However, after several uses (such as 4), it begins to take approximately twice as long each time to save.

I have created a test method to reproduce it, where it saves the exact same image each time. The method is as follows:

-(IBAction)testButton {
    NSData *data = [NSData dataWithContentsOfFile:[[self photosDirectory] stringByAppendingPathComponent:[[self contentsOfPhotoDirectory] objectAtIndex:0]]];
    ALAssetsLibrary *al = [[ALAssetsLibrary alloc] init];
    __block NSDate *date = [[NSDate date] retain];
    [al writeImageDataToSavedPhotosAlbum:data metadata:nil completionBlock:^(NSURL *assetURL, NSError *error) {
        NSLog(@"Saving Time: %g", [[NSDate date] timeIntervalSinceDate:date]);
        [date release];
    }];
    [al release];
}

On a freshly restarted iPhone 4, I get the following save times.

2011-06-01 21:23:13.641 myapp[95:707] Saving Time: 5.30819
2011-06-01 21:23:17.101 myapp[95:707] Saving Time: 1.5311
2011-06-01 21:23:21.916 myapp[95:707] Saving Time: 2.52412
2011-06-01 21:23:25.974 myapp[95:707] Saving Time: 2.85623
2011-06-01 21:23:32.275 myapp[95:707] Saving Time: 4.93484
2011-06-01 21:23:42.024 myapp[95:707] Saving Time: 7.93288
2011-06-01 21:24:00.317 myapp[95:707] Saving Time: 15.8561
2011-06-01 21:24:33.199 myapp[95:707] Saving Time: 29.7571

What is wrong?


问:
Android Room Migration test fails, although nothing changed
I am trying to test a Room migration, but the test always fails. There is not even a change in the model. I only increase the version number and the migration is empty - the test still fails. I don't understand what I'm doing wrong.

Let's say we have an entity EntityExample, with two columns a and b. The primary key is composed of both a and b, and we have indices for both columns. The code looks like:

@Entity(primaryKeys = {"a", "b"}, indices = {@Index("a"), @Index("b")})
public class EntityExample {
    @NonNull public Long a;
    @NonNull public Long b;
}
```

<p>Further, our database in version 1:</p>

<pre class="lang-java prettyprint-override"><code>@Database(version=1,entities={EntityExample.class})
public abstract class DBExample extends RoomDatabase {
}
</code>```

and in version 2:

@Database(version=2,entities={EntityExample.class})
public abstract class DBExample extends RoomDatabase {
}
```

<p>Also, there are the migrations:</p>

<pre class="lang-java prettyprint-override"><code>public class MigrationExample {
    public final static Migration MIGRATION_1_2 = new Migration(1,2) {
        @Override
        public void migrate(@NonNull SupportSQLiteDatabase database) {

        }
    };
}
</code>```

To access the schema in tests, in the build.gradle was added:

```<code>android {
    sourceSets {
        // Adds exported schema location as test app assets.
        debug.assets.srcDirs += files("$projectDir/schemas".toString())
    }
}
</code>```

And, finally, the test:

@Config(sdk = Build.VERSION_CODES.O_MR1)
@RunWith(RobolectricTestRunner.class)
public class MigrationExampleTest {

    @Rule
    public MigrationTestHelper helper;

    public MigrationExampleTest() {
        helper = new MigrationTestHelper(InstrumentationRegistry.getInstrumentation(),
                DBExample.class.getCanonicalName(),
                new FrameworkSQLiteOpenHelperFactory());
    }

    @Test
    public void migrationTest() throws IOException {

        SupportSQLiteDatabase dbV1 = helper.createDatabase("migration-test", 1);
        dbV1.close();

        DBExample dbV2 = Room.databaseBuilder(
                InstrumentationRegistry.getInstrumentation().getTargetContext(),
                DBExample.class,
                "migration-test")
                .addMigrations(MigrationExample.MIGRATION_1_2)
                .build();
        dbV2.getOpenHelper().getWritableDatabase();
        dbV2.close();
    }

}
```

<p>The test fails on the line <code>dbV2.getOpenHelper().getWritableDatabase();</code> with </p>

```java.lang.IllegalStateException: Migration didn't properly handle: EntityExample(....EntityExample).
 Expected:
TableInfo{name='EntityExample', columns={a=Column{name='a', type='INTEGER', affinity='3', notNull=true, primaryKeyPosition=1, defaultValue='null'}, b=Column{name='b', type='INTEGER', affinity='3', notNull=true, primaryKeyPosition=2, defaultValue='null'}}, foreignKeys=[], indices=[Index{name='index_EntityExample_a', unique=false, columns=[a]}, Index{name='index_EntityExample_b', unique=false, columns=[b]}]}
 Found:
TableInfo{name='EntityExample', columns={a=Column{name='a', type='INTEGER', affinity='3', notNull=true, primaryKeyPosition=1, defaultValue='null'}, b=Column{name='b', type='INTEGER', affinity='3', notNull=true, primaryKeyPosition=1, defaultValue='null'}}, foreignKeys=[], indices=null}
```

As you can see (when scrolling the test output to the right), the indices part is missing in the found TableInfo. Also, the primaryKeyPosition for b differs between 1 and 2. I don't understand why, I don't know what exactly causes the test to fail, and I don't know how to fix this. Running the app works, no exceptions are thrown. I checked the schemas, they are completely the same except for the updated version number (see https://justpaste.it/68l2b and https://justpaste.it/3r45p). However, the test fails!

答:
If you haven't yet, you can check this good article on migration testing : https://medium.com/androiddevelopers/testing-room-migrations-be93cdb0d975

Then, in your migration you have to actually migrate the database, execute the SQL to go from 1 to 2,  by creating indices for example.

Room handles migration chaining, structure integrity and testing, but not the migration itself.
In the documentation https://developer.android.com/training/data-storage/room/migrating-db-versions they do migrations of their database, you should do the same.

Body:
I am trying to test a Room migration, but the test always fails. There is not even a change in the model. I only increase the version number and the migration is empty - the test still fails. I don't understand what I'm doing wrong.

Let's say we have an entity EntityExample, with two columns a and b. The primary key is composed of both a and b, and we have indices for both columns. The code looks like:

@Entity(primaryKeys = {"a", "b"}, indices = {@Index("a"), @Index("b")})
public class EntityExample {
    @NonNull public Long a;
    @NonNull public Long b;
}

Further, our database in version 1:

@Database(version=1,entities={EntityExample.class})
public abstract class DBExample extends RoomDatabase {
}

and in version 2:

@Database(version=2,entities={EntityExample.class})
public abstract class DBExample extends RoomDatabase {
}

Also, there are the migrations:

public class MigrationExample {
    public final static Migration MIGRATION_1_2 = new Migration(1,2) {
        @Override
        public void migrate(@NonNull SupportSQLiteDatabase database) {

        }
    };
}

To access the schema in tests, in the build.gradle was added:

android {
    sourceSets {
        // Adds exported schema location as test app assets.
        debug.assets.srcDirs += files("$projectDir/schemas".toString())
    }
}

And, finally, the test:

@Config(sdk = Build.VERSION_CODES.O_MR1)
@RunWith(RobolectricTestRunner.class)
public class MigrationExampleTest {

    @Rule
    public MigrationTestHelper helper;

    public MigrationExampleTest() {
        helper = new MigrationTestHelper(InstrumentationRegistry.getInstrumentation(),
                DBExample.class.getCanonicalName(),
                new FrameworkSQLiteOpenHelperFactory());
    }

    @Test
    public void migrationTest() throws IOException {

        SupportSQLiteDatabase dbV1 = helper.createDatabase("migration-test", 1);
        dbV1.close();

        DBExample dbV2 = Room.databaseBuilder(
                InstrumentationRegistry.getInstrumentation().getTargetContext(),
                DBExample.class,
                "migration-test")
                .addMigrations(MigrationExample.MIGRATION_1_2)
                .build();
        dbV2.getOpenHelper().getWritableDatabase();
        dbV2.close();
    }

}

The test fails on the line dbV2.getOpenHelper().getWritableDatabase(); with

java.lang.IllegalStateException: Migration didn't properly handle: EntityExample(....EntityExample).
 Expected:
TableInfo{name='EntityExample', columns={a=Column{name='a', type='INTEGER', affinity='3', notNull=true, primaryKeyPosition=1, defaultValue='null'}, b=Column{name='b', type='INTEGER', affinity='3', notNull=true, primaryKeyPosition=2, defaultValue='null'}}, foreignKeys=[], indices=[Index{name='index_EntityExample_a', unique=false, columns=[a]}, Index{name='index_EntityExample_b', unique=false, columns=[b]}]}
 Found:
TableInfo{name='EntityExample', columns={a=Column{name='a', type='INTEGER', affinity='3', notNull=true, primaryKeyPosition=1, defaultValue='null'}, b=Column{name='b', type='INTEGER', affinity='3', notNull=true, primaryKeyPosition=1, defaultValue='null'}}, foreignKeys=[], indices=null}

As you can see (when scrolling the test output to the right), the indices part is missing in the found TableInfo. Also, the primaryKeyPosition for b differs between 1 and 2. I don't understand why, I don't know what exactly causes the test to fail, and I don't know how to fix this. Running the app works, no exceptions are thrown. I checked the schemas, they are completely the same except for the updated version number (see https://justpaste.it/68l2b and https://justpaste.it/3r45p). However, the test fails!


问:
Is it possible to add extra indentation to a line in a foldable Yaml text block without breaking the folding?
Consider the following Yaml that specifies a fixed indentation of two spaces:

```<code>yaml: >-2
  First line
  will fold.

  Second line
  should fold
  as well.
</code>```

Which, de-serializes to:

```<code>{
  "yaml": "First line will fold.\nSecond line should fold as well."
}
</code>```

The result text is folded as expected. There are two separate lines only (the newline character can be found between the "fold." and the "Second" words).

Now, if some extra blank spaces are added before the "Second" word, the folding logic breaks. Let's assume this extra space is part of the text itself, not part of the Yaml indentation (as the latter was fixed to two blank spaces):

```<code>yaml: >-2
  First line
  will fold.

       Second line
  should fold
  as well.
</code>```

This de-serializes to:

```<code>{
  "yaml": "First line will fold.\n\n     Second line\nshould fold as well."
}
</code>```

Now, three separate lines are generated, and the first one contains two consecutive newline characters, which is unexpected.

Is it possible to add some extra spacing indentation to Yaml text blocks (indentation that is part of the text data, not part of the Yaml indentation), without breaking the folding logic?

答:
YAML behaves as specified:

Folded newlines are preserved for "more indented" and blank lines

You can use a quoted scalar instead, which also does line folding but handles indentation differently:

yaml:
 "First line
  will fold.

  \     Second line
  should fold
  as well."
```

<p>Here, you escape the first space that should be content since leading space is completely stripped. This evaluates to</p>

<pre class="lang-yaml prettyprint-override"><code>%YAML 1.2
---
!!map {
  ? !!str "yaml"
  : !!str "First line will fold.\n     Second line should fold as well."
}
</code>```

Body:
Consider the following Yaml that specifies a fixed indentation of two spaces:

yaml: >-2
  First line
  will fold.

  Second line
  should fold
  as well.

Which, de-serializes to:

{
  "yaml": "First line will fold.\nSecond line should fold as well."
}

The result text is folded as expected. There are two separate lines only (the newline character can be found between the "fold." and the "Second" words).

Now, if some extra blank spaces are added before the "Second" word, the folding logic breaks. Let's assume this extra space is part of the text itself, not part of the Yaml indentation (as the latter was fixed to two blank spaces):

yaml: >-2
  First line
  will fold.

       Second line
  should fold
  as well.

This de-serializes to:

{
  "yaml": "First line will fold.\n\n     Second line\nshould fold as well."
}

Now, three separate lines are generated, and the first one contains two consecutive newline characters, which is unexpected.

Is it possible to add some extra spacing indentation to Yaml text blocks (indentation that is part of the text data, not part of the Yaml indentation), without breaking the folding logic?

Body:
YAML behaves as specified:

Folded newlines are preserved for "more indented" and blank lines

You can use a quoted scalar instead, which also does line folding but handles indentation differently:

yaml:
 "First line
  will fold.

  \     Second line
  should fold
  as well."

Here, you escape the first space that should be content since leading space is completely stripped. This evaluates to

%YAML 1.2
---
!!map {
  ? !!str "yaml"
  : !!str "First line will fold.\n     Second line should fold as well."
}


问:
I want to print any text without using Print function in java?
I want to print any text without using system.out.println() in java? It is possible If yes
then how; Any idea.</p>

答:
Its actually possible and there is an awesome method to do it

make a class, call it so

make it like this

```<code>public class so
{
    public static void p(Object o){
        System.out.print(o);
    }
    public static void pln(Object o){
        System.out.println(o);
    }
}
</code>```

then call the method like

```<code>so.pln("hi");
</code>```

or

```<code>so.p("hi");
</code>```

you can actually use it like an ordinary print or println function just writing lesser...

if you just done want to use println use print

like this

```<code>System.out.print("\n whatever you want");
</code>```

\n takes it to the next line.........

Or what you can do is using your IDE go to the println function and do whatever is done in there.........

Body:
Its actually possible and there is an awesome method to do it

make a class, call it so

make it like this

public class so
{
    public static void p(Object o){
        System.out.print(o);
    }
    public static void pln(Object o){
        System.out.println(o);
    }
}

then call the method like

so.pln("hi");

or

so.p("hi");

you can actually use it like an ordinary print or println function just writing lesser...

if you just done want to use println use print

like this

System.out.print("\n whatever you want");

\n takes it to the next line.........

Or what you can do is using your IDE go to the println function and do whatever is done in there.........