问:
counting row values with different ids in multidimensional array
I know there are a lot of topics about this, but just couldn't find any that would actually help me solve the problem.
Ok so i am having a problem with counting rows and values in multidimensional array (imported via .csv)

I am trying to achieve something like...

```<code>Array ( [0] => Array ( [0] => 1 [1] => 6278,31 [2] => 4)
        [1] => Array ( [0] => 2 [1] => 2,0 [2] => 2)
        [2] => Array ( [0] => 3 [1] => 3,01 [2] => 3)
         )
</code>```

where [0] would be buyer id, 1 is total number of buys and [2] total cost.

My current code:

```<code>if(($s_open = fopen("sales.csv", "r")) !== FALSE)
    {
        $s_count = count(file("sales.csv"));
        while(($sales = fgetcsv($s_open, 100, ";")) !== FALSE)
        {
            ...
        }
        fclose($s_open);
    }
</code>```

Thanks in advance.

答:
Try this</p>
```<code>$data = [];
if(($s_open = fopen("sales.csv", "r")) !== FALSE) {
    $s_count = count(file("sales.csv"));
    while( ([$id, $buyer_id, $amount] = fgetcsv($s_open, 100, ";")) !== FALSE ){
        if( $id !== 'id' ){
            $data[$buyer_id] = [
                $buyer_id,
                ($data[$buyer_id][1] ?? 0) + 1,
                ($data[$buyer_id][2] ?? 0) + $amount
            ];
        }
    }
    fclose($s_open);
    $data = array_values($data);
}
// print_r($data);
</code>```

Body:
I know there are a lot of topics about this, but just couldn't find any that would actually help me solve the problem.
Ok so i am having a problem with counting rows and values in multidimensional array (imported via .csv)

I am trying to achieve something like...

Array ( [0] => Array ( [0] => 1 [1] => 6278,31 [2] => 4)
        [1] => Array ( [0] => 2 [1] => 2,0 [2] => 2)
        [2] => Array ( [0] => 3 [1] => 3,01 [2] => 3)
         )

where [0] would be buyer id, 1 is total number of buys and [2] total cost.

My current code:

if(($s_open = fopen("sales.csv", "r")) !== FALSE)
    {
        $s_count = count(file("sales.csv"));
        while(($sales = fgetcsv($s_open, 100, ";")) !== FALSE)
        {
            ...
        }
        fclose($s_open);
    }

Thanks in advance.

Body:
Try this

$data = [];
if(($s_open = fopen("sales.csv", "r")) !== FALSE) {
    $s_count = count(file("sales.csv"));
    while( ([$id, $buyer_id, $amount] = fgetcsv($s_open, 100, ";")) !== FALSE ){
        if( $id !== 'id' ){
            $data[$buyer_id] = [
                $buyer_id,
                ($data[$buyer_id][1] ?? 0) + 1,
                ($data[$buyer_id][2] ?? 0) + $amount
            ];
        }
    }
    fclose($s_open);
    $data = array_values($data);
}
// print_r($data);


来源: stackexchange

问:
Loop through folders that have changes in a PR
In a github workflow (.yaml) script, I'm wondering how to loop through any folders that have changes as part of a particular PR.

For instance, suppose I have this structure:

```<code>Dir1\File1.txt
Dir2\File2.txt
Dir3\File3.txt
Dir4\File4.txt
</code>```

If a PR has changes to File2.txt and File4.txt, I want a workflow that will loop thru and do something in folders: Dir2 and Dir4.

I know of a way to do this for specific folders, but I don't want to have to specify all of the folders that exist in my source, i.e. this works for a list of specified directories:

```<code>   - name: myJob
        run: |
          myDirectories=("Dir1" "Dir2" "Dir3" "Dir4")

          for i in "${myDirectories[@]}"
          do
            if git diff --name-only --diff-filter=ACMRT ${{ github.event.pull_request.base.sha }} ${{ github.sha }} | grep -c "^$i/"; then
              ...do something...
            fi
          done
</code>```

Thank you.

答:
I don't know about GitHub workflows, but you can achieve want you want just using bash. You need to modify the sample you provided in your question to use find * -type d to get a (recursive) list of all subdirectories. So instead of for i in "${myDirectories[@]}" you just use for i in $(find * -type d).

Additionally, you could keep track of which directories you already handled and skip their subdirectories, if that is what you want (there is probably a better/faster way to do this, but this is what I could come up with):

handledDirs=()

for dir in $(find * -type d); do
    if ...; then # check if $dir contains changes
        for e in "${handledDirs[@]}"; do
            [[ "$dir" == "$e"* ]] && continue 2
        done
        handledDirs+=("$dir")

        # do something with $dir
    fi
done
```

ContentLicense: CC BY-SA 4.0

Body:
In a github workflow (.yaml) script, I'm wondering how to loop through any folders that have changes as part of a particular PR.

For instance, suppose I have this structure:

Dir1\File1.txt
Dir2\File2.txt
Dir3\File3.txt
Dir4\File4.txt

If a PR has changes to File2.txt and File4.txt, I want a workflow that will loop thru and do something in folders: Dir2 and Dir4.

I know of a way to do this for specific folders, but I don't want to have to specify all of the folders that exist in my source, i.e. this works for a list of specified directories:

   - name: myJob
        run: |
          myDirectories=("Dir1" "Dir2" "Dir3" "Dir4")

          for i in "${myDirectories[@]}"
          do
            if git diff --name-only --diff-filter=ACMRT ${{ github.event.pull_request.base.sha }} ${{ github.sha }} | grep -c "^$i/"; then
              ...do something...
            fi
          done

Thank you.


问:
SQL Case statement with subtraction and avoiding a negative value
I have a SQL stored procedure with a case statement. The statement is taking a cost and adding to it for the specific ExtCostCategory.

However, for WHSE-BRDR this needs to subtract 0.05 from the cost. How can I write this to avoid a negative value if PriceUOMCost is less than 0.05?

```<code>update t
set PriceUOMCost = cast(case c.ExtCostCategory
                            when 'WHSE-VEND' then x.PriceUOMCost + 0.05
                            when 'WHSE-RETL' then x.PriceUomCost + 0.08
                            when 'WHSE-BRDR' then x.PriceUOMCost - 0.05
                            when 'VEND-BRDR' then x.PriceUOMCost + 0.05
                            else x.PriceUOMCost
                        end as decimal(10,3))
</code>```

答:
I don't know If I am missing something but can't you just do that?</p>
```<code>when 'WHSE-BRDR' and x.PriceUOMCost >= 0.5 then x.PriceUOMCost - 0.05
</code>```

Body:
I have a SQL stored procedure with a case statement. The statement is taking a cost and adding to it for the specific ExtCostCategory.

However, for WHSE-BRDR this needs to subtract 0.05 from the cost. How can I write this to avoid a negative value if PriceUOMCost is less than 0.05?

update t
set PriceUOMCost = cast(case c.ExtCostCategory
                            when 'WHSE-VEND' then x.PriceUOMCost + 0.05
                            when 'WHSE-RETL' then x.PriceUomCost + 0.08
                            when 'WHSE-BRDR' then x.PriceUOMCost - 0.05
                            when 'VEND-BRDR' then x.PriceUOMCost + 0.05
                            else x.PriceUOMCost
                        end as decimal(10,3))

Body:
I don't know If I am missing something but can't you just do that?

when 'WHSE-BRDR' and x.PriceUOMCost >= 0.5 then x.PriceUOMCost - 0.05


问:
Element implicitly has an 'any' type because expression of type 'string' can't be used to index
Trying out TypeScript for a React project and I'm stuck on this error:

```<code>Element implicitly has an 'any' type because expression of type 'string' can't be used to index type '{ train_1: boolean; train_2: boolean; train_3: boolean; train_4: boolean; }'.
  No index signature with a parameter of type 'string' was found on type '{ train_1: boolean; train_2: boolean; train_3: boolean; train_4: boolean; }'
</code>```

Which appears when I try to filter the array in my component

```<code>.filter(({ name }) => plotOptions[name]);
</code>```

So far I looked at the article "Indexing objects in TypeScript" (https://dev.to/kingdaro/indexing-objects-in-typescript-1cgi) since it had a similar error, but I tried to add the index signature to type plotTypes and I still get the same error.

My component code:

```<code>import React, { Component } from "react";
import createPlotlyComponent from "react-plotly.js/factory";
import Plotly from "plotly.js-basic-dist";
const Plot = createPlotlyComponent(Plotly);

interface IProps {
  data: any;
}

interface IState {
  [key: string]: plotTypes;
  plotOptions: plotTypes;
}

type plotTypes = {
  [key: string]: boolean;
  train_1: boolean;
  train_2: boolean;
  train_3: boolean;
  train_4: boolean;
};

interface trainInfo {
  name: string;
  x: Array<number>;
  y: Array<number>;
  type: string;
  mode: string;
}

class FiltrationPlots extends Component<IProps, IState> {
  readonly state = {
    plotOptions: {
      train_1: true,
      train_2: true,
      train_3: true,
      train_4: true
    }
  };
  render() {
    const { data } = this.props;
    const { plotOptions } = this.state;

    if (data.filtrationData) {
      const plotData: Array<trainInfo> = [
        {
          name: "train_1",
          x: data.filtrationData.map((i: any) => i["1-CumVol"]),
          y: data.filtrationData.map((i: any) => i["1-PressureA"]),
          type: "scatter",
          mode: "lines"
        },
        {
          name: "train_2",
          x: data.filtrationData.map((i: any) => i["2-CumVol"]),
          y: data.filtrationData.map((i: any) => i["2-PressureA"]),
          type: "scatter",
          mode: "lines"
        },
        {
          name: "train_3",
          x: data.filtrationData.map((i: any) => i["3-CumVol"]),
          y: data.filtrationData.map((i: any) => i["3-PressureA"]),
          type: "scatter",
          mode: "lines"
        },
        {
          name: "train_4",
          x: data.filtrationData.map((i: any) => i["4-CumVol"]),
          y: data.filtrationData.map((i: any) => i["4-PressureA"]),
          type: "scatter",
          mode: "lines"
        }
      ].filter(({ name }) => plotOptions[name]);
      return (
        <Plot
          data={plotData}
          layout={{ width: 1000, height: 1000, title: "A Fancy Plot" }}
        />
      );
    } else {
      return <h1>No Data Loaded</h1>;
    }
  }
}

export default FiltrationPlots;

</code>```

答:
public getUserName(): string {

```<code>const accessToken = this.getAccessToken();
const claims:any = this.getUserClaims();
console.log('access token ',accessToken);
this.getUserInfo();
return claims['sub'].split('@')[0];
</code>```

}

//give any type to the variable

Body:
Trying out TypeScript for a React project and I'm stuck on this error:

Element implicitly has an 'any' type because expression of type 'string' can't be used to index type '{ train_1: boolean; train_2: boolean; train_3: boolean; train_4: boolean; }'.
  No index signature with a parameter of type 'string' was found on type '{ train_1: boolean; train_2: boolean; train_3: boolean; train_4: boolean; }'

Which appears when I try to filter the array in my component

.filter(({ name }) => plotOptions[name]);

So far I looked at the article "Indexing objects in TypeScript" (https://dev.to/kingdaro/indexing-objects-in-typescript-1cgi) since it had a similar error, but I tried to add the index signature to type plotTypes and I still get the same error.

My component code:

import React, { Component } from "react";
import createPlotlyComponent from "react-plotly.js/factory";
import Plotly from "plotly.js-basic-dist";
const Plot = createPlotlyComponent(Plotly);

interface IProps {
  data: any;
}

interface IState {
  [key: string]: plotTypes;
  plotOptions: plotTypes;
}

type plotTypes = {
  [key: string]: boolean;
  train_1: boolean;
  train_2: boolean;
  train_3: boolean;
  train_4: boolean;
};

interface trainInfo {
  name: string;
  x: Array<number>;
  y: Array<number>;
  type: string;
  mode: string;
}

class FiltrationPlots extends Component<IProps, IState> {
  readonly state = {
    plotOptions: {
      train_1: true,
      train_2: true,
      train_3: true,
      train_4: true
    }
  };
  render() {
    const { data } = this.props;
    const { plotOptions } = this.state;

    if (data.filtrationData) {
      const plotData: Array<trainInfo> = [
        {
          name: "train_1",
          x: data.filtrationData.map((i: any) => i["1-CumVol"]),
          y: data.filtrationData.map((i: any) => i["1-PressureA"]),
          type: "scatter",
          mode: "lines"
        },
        {
          name: "train_2",
          x: data.filtrationData.map((i: any) => i["2-CumVol"]),
          y: data.filtrationData.map((i: any) => i["2-PressureA"]),
          type: "scatter",
          mode: "lines"
        },
        {
          name: "train_3",
          x: data.filtrationData.map((i: any) => i["3-CumVol"]),
          y: data.filtrationData.map((i: any) => i["3-PressureA"]),
          type: "scatter",
          mode: "lines"
        },
        {
          name: "train_4",
          x: data.filtrationData.map((i: any) => i["4-CumVol"]),
          y: data.filtrationData.map((i: any) => i["4-PressureA"]),
          type: "scatter",
          mode: "lines"
        }
      ].filter(({ name }) => plotOptions[name]);
      return (
        <Plot
          data={plotData}
          layout={{ width: 1000, height: 1000, title: "A Fancy Plot" }}
        />
      );
    } else {
      return
No Data Loaded
;
    }
  }
}

export default FiltrationPlots;

Body:
public getUserName(): string {

const accessToken = this.getAccessToken();
const claims:any = this.getUserClaims();
console.log('access token ',accessToken);
this.getUserInfo();
return claims['sub'].split('@')[0];

}

//give any type to the variable


问:
Making a thread-unsafe DLL call in BizTalk Orchestration (or only running one Orchestration at a time)
I have an issue with a 3rd party DLL, which is NOT thread-safe, but which I need to call within an orchestration.

I'm making the DLL call within an Expression shape. The same DLL is called in a number of different orchestrations.

The problem I have is that for a series of incoming messages, BizTalk will run multiple orchestrations (or multiple instances of an orchestration) in parallel - which leads to exceptions within the DLL.

Is there any way around this, given that refactoring the DLL isn't an option. Or, is there a way to throttle BizTalk to only run one orchestration at any one time. (I've seen some hacks restricting the working pool to the number of processors, but this doesn't seem to help. We can't downgrade to a single-core machine!)

I would rather find a way of keeping the DLL happy (though I can't think how) than throttle BizTalk - but if there is a way to throttle that would be an acceptable short-term solution whilst we discuss with the 3rd party. (who are a large organisation and really should know better!)

答:
Even on a single core machine, BizTalk will run concurrent orchestrations.

You could throttle the orchestration by implementing the singleton pattern in the orchestration.

You do this by creating a loop in the orchestration and having two receive shapes, one before the start of the loop and one inside the loop.

Both these receive are bound to the same inbound logical port.

You create a correlation set which specifies something like BTS.MessageType and set the first receive shape to initiate the correlation and the second receive to follow the correlation.

As long as the loop does not end you can guarantee that any message of a certain type will always be processed by the same instance of the orchestration.

However, using singletons is a design decision which comes with drawbacks. For example, throughput suffers, and you have to ensure that your singleton cannot suspend, else it will create a block for all subsequent messages.

Hope this helps.

ContentLicense: CC BY-SA 3.0


问:
How can I fix this Import problem with vsCode
I'm having a little problem. I would like to import bs4 and request on my vscode file but I can't in tells me that there is a missign module source. I tried to change the interpreter but when I do it only one of them is recognized. So if anyone knows how I can import both of them I would gradely appreciate, thanks.

The error message that I get

答: Firstly install projected related extension then try to import.</p>


问:
CORS Issue when added OPENID Active Directory Authentication to Azure App service
we have two App services in Azure in tenant A

(a) Web APP (Angualr)
(b) API App (.NET Core)

'Web' App service calls 'API' App service to get data. 'Web' & 'API' app authentication is done by OpenID Active Directory Authentication. When we call the 'API' Service from the browser it works fine, but when we call the 'API' App within 'Web' App we are getting a CORS error

Access to XMLHttpRequest at 'https://login.microsoftonline.com/{tenant-id}/oauth2/v2.0/authorize?response_type=code&client_id={client-id}&redirect_uri=https%3A%2F%2F{AP%2F.api.azurewebsites.us%2Flogin%2F{auth provider}%2Fcallback&nonce=4&state=redir%3D%252Fapi%252Fbridge&scope=openid+profile+email' (redirected from 'https://api.azurewebsites.us/api/name') from origin 'https://webui.azurewebsites.us' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

Have anyone faced any similar issues, can provide some help on this

答:
I think you just need to use an application type / platform of Single Page App rather than Web App, as in step 6 of my blog post.

Azure AD will then add the CORS response headers to pre-flight OPTIONS requests, needed by the SPA.


问:
I need the url in the ajax script to be a variable from a php file but I don't know how to do this
The top section has the variables and forms.  The program calls an html page depending on who logs in.  I need to be able to pull the page based on login information.

I pull the page number from the url when the page is called.  I need to use that page number in the ajax part of the program at the bottom to pull the data off the right page and put it in the chatbox.

Right now I can't pull the right page.  I am having a problem setting a variable in the ajax url:

I tried using "" but it will load the chatbox inside the chatbox as an image.

```<code>    <?php
    if(isset($_POST['enter'])){
    if($_POST['name'] != ""){
    $_SESSION['name'] =
    stripslashes(htmlspecialchars($_POST['name']));
    }
    else{
    echo '<span class="error">Please type in a name</span>';
    }
    }
    ?>
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head>
    <title>Chat - Customer Module</title>
    <link type="text/css" rel="stylesheet" href="style1.css" />
    </head>
    <body>

    <?php
    if(!isset($_SESSION['name'])){
    loginForm();
    }
    else{
    ?>
    <div id="wrapper">
    <div id="menu">
    <p class="welcome">Welcome, <b><?php echo $_SESSION['name']; ?>
    </b></p>
    <p class="logout"><a id="exit" href="#">Exit Chat</a></p>
    <div style="clear:both"></div>
    </div>
    <div id="chatbox"><?php
    if(file_exists($log) && filesize($log) > 0){
        $handle = fopen($log, "r");
        $contents = fread($handle, filesize($log));
        fclose($handle);
        echo $contents;
    }
     else{
        if(!isset($log));
        $contents = 'Welcome!';
        file_put_contents($log, $contents);
        echo $contents;
    }
    ?>
    </div>

    <form name="message" action="">
    <input name="usermsg" type="text" id="usermsg" size="63" />
    <input name="submitmsg" type="submit"  id="submitmsg"
    value="Send" />
    </form>
    <br />
    <form action="upload.php" method="post" enctype="multipart/form-
     data">
    Select image to upload:
    <input type="file" name="fileToUpload" />
    <input type="submit" value="Upload Image" name="submit" />
    </form>
    </div>
    <script type="text/javascript"
  src="http://ajax.googleapis.com/ajax/libs/jquery/1.3/jquery.min.js">
    </script>
    <script type="text/javascript">
    // jQuery Document
    $(document).ready(function(){
        //If user submits the form
    $("#submitmsg").click(function(){
    var clientmsg = $("#usermsg").val();
    $.post("post.php", {text: clientmsg});
    $("#usermsg").attr("value", "");
    return false;
    });

    //Load the file containing the chat log
    function loadLog(){
       var oldscrollHeight = $("#chatbox").attr("scrollHeight") - 20;

    $.ajax({
    url: "chat/9999.html",

    cache: false,
    success: function(html){
    $("#chatbox").html(html); //Insert chat log into the #chatbox div
    var newscrollHeight = $("#chatbox").attr("scrollHeight") - 20;
    if(newscrollHeight > oldscrollHeight){
    $("#chatbox").animate({ scrollTop: newscrollHeight }, 'normal');
        //Autoscroll to bottom of div
                }
            },
        });
    }
    setInterval (loadLog, 2500);    //Reload file every 2.5 seconds

     //If user wants to end session
    $("#exit").click(function(){
        var exit = confirm("Are you sure you want to end the
            session?");
    if(exit==true){window.location = 'index.php?logout=true';}
    });
    });
    </script>
</code>```

I have updated to give you more code.  I tried using the "" but the form isn't acting right.  It keeps loading the form inside the form again.

I need the "chat/9999.html" to be a variable so it can bring up one of a few pages.

答:
You can save your JavaScript file as a .php extension or change your server config to interpret the given file with PHP.

Once you have PHP enabled to handle the file, you can use everything from PHP as usually.

To make sure the script is loaded by the browser with the correct MIME type, you can set it with PHP.

<?php

header('Content-Type: application/javascript');

$url = "chat/9999.html";

?>

$.ajax({
    url: "<?= $url ?>",
    // …
})
```

Body:
The top section has the variables and forms.  The program calls an html page depending on who logs in.  I need to be able to pull the page based on login information.

I pull the page number from the url when the page is called.  I need to use that page number in the ajax part of the program at the bottom to pull the data off the right page and put it in the chatbox.

Right now I can't pull the right page.  I am having a problem setting a variable in the ajax url:

I tried using "" but it will load the chatbox inside the chatbox as an image.

    <?php
    if(isset($_POST['enter'])){
    if($_POST['name'] != ""){
    $_SESSION['name'] =
    stripslashes(htmlspecialchars($_POST['name']));
    }
    else{
    echo 'Please type in a name';
    }
    }
    ?>
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <title>Chat - Customer Module</title>
    <link type="text/css" rel="stylesheet" href="style1.css" />

    <?php
    if(!isset($_SESSION['name'])){
    loginForm();
    }
    else{
    ?>

Welcome, <?php echo $_SESSION['name']; ?>

Exit Chat

<?php
    if(file_exists($log) && filesize($log) > 0){
        $handle = fopen($log, "r");
        $contents = fread($handle, filesize($log));
        fclose($handle);
        echo $contents;
    }
     else{
        if(!isset($log));
        $contents = 'Welcome!';
        file_put_contents($log, $contents);
        echo $contents;
    }
    ?>

    <form name="message" action="">
    <input name="usermsg" type="text" id="usermsg" size="63" />
    <input name="submitmsg" type="submit"  id="submitmsg"
    value="Send" />
    </form>

    <form action="upload.php" method="post" enctype="multipart/form-
     data">
    Select image to upload:
    <input type="file" name="fileToUpload" />
    <input type="submit" value="Upload Image" name="submit" />
    </form>

I have updated to give you more code.  I tried using the "" but the form isn't acting right.  It keeps loading the form inside the form again.

I need the "chat/9999.html" to be a variable so it can bring up one of a few pages.


问:
IllegalStateException using ExoPlayer on Sony TV
I'm trying to write a simple TvInputService for Android TV using ExoPlayer. On the emulator everything works fine, but on Sony TV (KDL-43WF804) I get IllegalStateException from video codec after a few seconds of video playing. What am I doing wrong?

Logs:

```<code>D/MtkACodecPlugin: MtkACodecPlugin createAPlugin
D/MtkACodecPlugin: OMX.MTK.VIDEO.DECODER.AVC needRmClient (673)
D/MtkACodecPlugin: OMX.MTK.VIDEO.DECODER.AVC mNeedVdpImgrz (679)
I/OMXClient: IOmx service obtained
D/SurfaceUtils: connecting to surface 0x8e25d808, reason connectToSurface
I/MediaCodec: [OMX.MTK.VIDEO.DECODER.AVC] setting surface generation to 21334017
D/SurfaceUtils: disconnecting from surface 0x8e25d808, reason connectToSurface(reconnect)
D/SurfaceUtils: connecting to surface 0x8e25d808, reason connectToSurface(reconnect)
D/MtkMediaCodecPlugin: [OMX.MTK.VIDEO.DECODER.AVC] set mOutputPath = 0 L(150)
E/ACodec: [OMX.MTK.VIDEO.DECODER.AVC] setPortMode on output to DynamicANWBuffer failed w/ err -1010
I/ACodec: codec does not support config priority (err -1010)
D/MtkACodecPlugin: add usage GRALLOC_USAGE_PATH_VDP0
D/SurfaceUtils: disconnecting from surface 0x8e25d808, reason setNativeWindowSizeFormatAndUsage
D/SurfaceUtils: connecting to surface 0x8e25d808, reason setNativeWindowSizeFormatAndUsage
D/SurfaceUtils: set up nativeWindow 0x8e25d808 for 1920x1088, color 0x7f000103, rotation 0, usage 0x30002900
D/MtkACodecPlugin: MtkACodecPlugin createAPlugin
I/OMXClient: IOmx service obtained
D/MtkMediaCodecPlugin: No surfaceTextureClient, [OMX.google.aac.decoder] set mOutputPath = 1024 L(159)
I/ACodec: codec does not support config priority (err -2147483648)
I/ACodec: codec does not support config operating rate (err -2147483648)
W/v.rudnev.tvlak: Accessing hidden method Landroid/media/AudioTrack$Builder;->setOffloadedPlayback(Z)Landroid/media/AudioTrack$Builder; (dark greylist, linking)
W/v.rudnev.tvlak: Accessing hidden method Landroid/media/AudioTrack$Builder;->setOffloadedPlayback(Z)Landroid/media/AudioTrack$Builder; (dark greylist, linking)
E/Surface: queueBuffer: error queuing buffer to SurfaceTexture, -19
E/ACodec: queueBuffer failed in onOutputBufferDrained: -19
E/ACodec: signalError(omxError 0x80001001, internalError -19)
E/MediaCodec: Codec reported err 0xffffffed, actionCode 0, while in state 6
D/SurfaceUtils: disconnecting from surface 0x8e25d808, reason disconnectFromSurface
E/MediaCodecVideoRenderer: Video codec error
      java.lang.IllegalStateException
        at android.media.MediaCodec.native_dequeueInputBuffer(Native Method)
        at android.media.MediaCodec.dequeueInputBuffer(MediaCodec.java:2635)
        at com.google.android.exoplayer2.mediacodec.SynchronousMediaCodecAdapter.dequeueInputBufferIndex(SynchronousMediaCodecAdapter.java:115)
        at com.google.android.exoplayer2.mediacodec.MediaCodecRenderer.feedInputBuffer(MediaCodecRenderer.java:1139)
        at com.google.android.exoplayer2.mediacodec.MediaCodecRenderer.render(MediaCodecRenderer.java:780)
        at com.google.android.exoplayer2.ExoPlayerImplInternal.doSomeWork(ExoPlayerImplInternal.java:982)
        at com.google.android.exoplayer2.ExoPlayerImplInternal.handleMessage(ExoPlayerImplInternal.java:486)
        at android.os.Handler.dispatchMessage(Handler.java:102)
        at android.os.Looper.loop(Looper.java:193)
        at android.os.HandlerThread.run(HandlerThread.java:65)
E/ExoPlayerImplInternal: Playback error
      com.google.android.exoplayer2.ExoPlaybackException: MediaCodecVideoRenderer error, index=0, format=Format(0, null, null, video/avc, avc1.4D4020, 5049176, null, [1920, 1080, 25.0], [-1, -1]), format_supported=YES
        at com.google.android.exoplayer2.ExoPlayerImplInternal.handleMessage(ExoPlayerImplInternal.java:562)
        at android.os.Handler.dispatchMessage(Handler.java:102)
        at android.os.Looper.loop(Looper.java:193)
        at android.os.HandlerThread.run(HandlerThread.java:65)
     Caused by: com.google.android.exoplayer2.video.MediaCodecVideoDecoderException: Decoder failed: OMX.MTK.VIDEO.DECODER.AVC
        at com.google.android.exoplayer2.video.MediaCodecVideoRenderer.createDecoderException(MediaCodecVideoRenderer.java:1470)
        at com.google.android.exoplayer2.mediacodec.MediaCodecRenderer.render(MediaCodecRenderer.java:799)
        at com.google.android.exoplayer2.ExoPlayerImplInternal.doSomeWork(ExoPlayerImplInternal.java:982)
        at com.google.android.exoplayer2.ExoPlayerImplInternal.handleMessage(ExoPlayerImplInternal.java:486)
        at android.os.Handler.dispatchMessage(Handler.java:102)
        at android.os.Looper.loop(Looper.java:193)
        at android.os.HandlerThread.run(HandlerThread.java:65)
     Caused by: java.lang.IllegalStateException
        at android.media.MediaCodec.native_dequeueInputBuffer(Native Method)
        at android.media.MediaCodec.dequeueInputBuffer(MediaCodec.java:2635)
        at com.google.android.exoplayer2.mediacodec.SynchronousMediaCodecAdapter.dequeueInputBufferIndex(SynchronousMediaCodecAdapter.java:115)
        at com.google.android.exoplayer2.mediacodec.MediaCodecRenderer.feedInputBuffer(MediaCodecRenderer.java:1139)
        at com.google.android.exoplayer2.mediacodec.MediaCodecRenderer.render(MediaCodecRenderer.java:780)
        at com.google.android.exoplayer2.ExoPlayerImplInternal.doSomeWork(ExoPlayerImplInternal.java:982)
        at com.google.android.exoplayer2.ExoPlayerImplInternal.handleMessage(ExoPlayerImplInternal.java:486)
        at android.os.Handler.dispatchMessage(Handler.java:102)
        at android.os.Looper.loop(Looper.java:193)
        at android.os.HandlerThread.run(HandlerThread.java:65)
E/ExoPlayerImplInternal: Disable failed.
      java.lang.IllegalStateException
        at android.media.MediaCodec.native_flush(Native Method)
        at android.media.MediaCodec.flush(MediaCodec.java:2131)
        at com.google.android.exoplayer2.mediacodec.SynchronousMediaCodecAdapter.flush(SynchronousMediaCodecAdapter.java:188)
        at com.google.android.exoplayer2.mediacodec.MediaCodecRenderer.flushCodec(MediaCodecRenderer.java:850)
        at com.google.android.exoplayer2.mediacodec.MediaCodecRenderer.flushOrReleaseCodec(MediaCodecRenderer.java:843)
        at com.google.android.exoplayer2.mediacodec.MediaCodecRenderer.onDisabled(MediaCodecRenderer.java:696)
        at com.google.android.exoplayer2.video.MediaCodecVideoRenderer.onDisabled(MediaCodecVideoRenderer.java:529)
        at com.google.android.exoplayer2.BaseRenderer.disable(BaseRenderer.java:178)
        at com.google.android.exoplayer2.ExoPlayerImplInternal.disableRenderer(ExoPlayerImplInternal.java:1642)
        at com.google.android.exoplayer2.ExoPlayerImplInternal.resetInternal(ExoPlayerImplInternal.java:1382)
        at com.google.android.exoplayer2.ExoPlayerImplInternal.stopInternal(ExoPlayerImplInternal.java:1345)
        at com.google.android.exoplayer2.ExoPlayerImplInternal.handleMessage(ExoPlayerImplInternal.java:578)
        at android.os.Handler.dispatchMessage(Handler.java:102)
        at android.os.Looper.loop(Looper.java:193)
        at android.os.HandlerThread.run(HandlerThread.java:65)
E/Surface: getSlotFromBufferLocked: unknown buffer: 0x8b2a6d00
W/ACodec: [OMX.MTK.VIDEO.DECODER.AVC] can not return buffer 22 to native window
D/gralloc: unregister FBM buffer
E/Surface: getSlotFromBufferLocked: unknown buffer: 0x8b2a6c00
W/ACodec: [OMX.MTK.VIDEO.DECODER.AVC] can not return buffer 21 to native window
E/Surface: getSlotFromBufferLocked: unknown buffer: 0x8b2a6700
W/ACodec: [OMX.MTK.VIDEO.DECODER.AVC] can not return buffer 16 to native window
D/gralloc: unregister FBM buffer
E/Surface: getSlotFromBufferLocked: unknown buffer: 0x8b2a6600
W/ACodec: [OMX.MTK.VIDEO.DECODER.AVC] can not return buffer 15 to native window
D/gralloc: unregister FBM buffer
E/Surface: getSlotFromBufferLocked: unknown buffer: 0x8b2a6500
W/ACodec: [OMX.MTK.VIDEO.DECODER.AVC] can not return buffer 14 to native window
D/gralloc: unregister FBM buffer
E/Surface: getSlotFromBufferLocked: unknown buffer: 0x8b2a6400
W/ACodec: [OMX.MTK.VIDEO.DECODER.AVC] can not return buffer 13 to native window
D/gralloc: unregister FBM buffer
E/Surface: getSlotFromBufferLocked: unknown buffer: 0x8b2a6300
W/ACodec: [OMX.MTK.VIDEO.DECODER.AVC] can not return buffer 12 to native window
D/gralloc: unregister FBM buffer
E/Surface: getSlotFromBufferLocked: unknown buffer: 0x8b2a6200
W/ACodec: [OMX.MTK.VIDEO.DECODER.AVC] can not return buffer 11 to native window
D/gralloc: unregister FBM buffer
E/Surface: getSlotFromBufferLocked: unknown buffer: 0x8b2a6100
W/ACodec: [OMX.MTK.VIDEO.DECODER.AVC] can not return buffer 10 to native window
D/gralloc: unregister FBM buffer
E/Surface: getSlotFromBufferLocked: unknown buffer: 0x8b2a6000
W/ACodec: [OMX.MTK.VIDEO.DECODER.AVC] can not return buffer 9 to native window
D/gralloc: unregister FBM buffer
E/Surface: getSlotFromBufferLocked: unknown buffer: 0x8b290f00
W/ACodec: [OMX.MTK.VIDEO.DECODER.AVC] can not return buffer 8 to native window
D/gralloc: unregister FBM buffer
E/Surface: getSlotFromBufferLocked: unknown buffer: 0x8b290e00
W/ACodec: [OMX.MTK.VIDEO.DECODER.AVC] can not return buffer 7 to native window
D/gralloc: unregister FBM buffer
E/Surface: getSlotFromBufferLocked: unknown buffer: 0x8b290d00
W/ACodec: [OMX.MTK.VIDEO.DECODER.AVC] can not return buffer 6 to native window
D/gralloc: unregister FBM buffer
E/Surface: getSlotFromBufferLocked: unknown buffer: 0x8b290c00
W/ACodec: [OMX.MTK.VIDEO.DECODER.AVC] can not return buffer 5 to native window
D/gralloc: unregister FBM buffer
E/Surface: getSlotFromBufferLocked: unknown buffer: 0x8b290b00
W/ACodec: [OMX.MTK.VIDEO.DECODER.AVC] can not return buffer 4 to native window
D/gralloc: unregister FBM buffer
E/Surface: getSlotFromBufferLocked: unknown buffer: 0x8b290a00
W/ACodec: [OMX.MTK.VIDEO.DECODER.AVC] can not return buffer 3 to native window
D/gralloc: unregister FBM buffer
D/MediaCodec: mState = 0, mHaveKick = 0, L(703)
D/MtkACodecPlugin: MtkACodecPlugin destoryAPlugin
D/gralloc: unregister FBM buffer
I/chatty: uid=10178(dev.rudnev.tvlake) identical 3 lines
D/gralloc: unregister FBM buffer
I/ExoPlayerImpl: Release b6e9764 [ExoPlayerLib/2.16.1] [BRAVIA_ATV3_2K, BRAVIA 2K GB ATV3, Sony, 28] [goog.exo.core, goog.exo.decoder, goog.exo.exoplayer, goog.exo.hls, goog.exo.datasource, goog.exo.extractor]
D/MediaCodec: mState = 0, mHaveKick = 0, L(703)
D/MtkACodecPlugin: MtkACodecPlugin destoryAPlugin
</code>```

Code:

public class IptvInputService extends TvInputService {
    private static final String TAG = "IptvInputService";

    @Override
    public Session onCreateSession(String inputId) {
        return new Session(this);
    }

    public static class Session extends TvInputService.Session {
        private final Context mContext;
        private final ExoPlayer mPlayer;

        public Session(Context context) {
            super(context);
            mContext = context;
            mPlayer = new ExoPlayer.Builder(context).build();
            mPlayer.addListener(new PlayerListener(this));
        }

        @Override
        public void onRelease() {
            mPlayer.release();
        }

        @Override
        public boolean onSetSurface(@Nullable Surface surface) {
            mPlayer.setVideoSurface(surface);
            return true;
        }

        @Override
        public void onSetStreamVolume(float volume) {
            mPlayer.setVolume(volume);
        }

        @Override
        public boolean onTune(Uri uri) {
            try {
                notifyVideoUnavailable(TvInputManager.VIDEO_UNAVAILABLE_REASON_TUNING);

                String streamUrl = "https://okkotv-live.cdnvideo.ru/channel/Viasat_Explore_HD.m3u8";

                mPlayer.setMediaItem(MediaItem.fromUri(streamUrl));
                mPlayer.prepare();
                mPlayer.play();

                return true;
            } catch (Throwable ex) {
                notifyVideoUnavailable(TvInputManager.VIDEO_UNAVAILABLE_REASON_UNKNOWN);
                Log.e(TAG, "Unable to play stream", ex);
            }

            return false;
        }

        @Override
        public void onSetCaptionEnabled(boolean b) {
        }
    }

    private static class PlayerListener implements Player.Listener {
        private final Session mSession;

        public PlayerListener(Session session) {
            mSession = session;
        }

        @Override
        public void onRenderedFirstFrame() {
            mSession.notifyVideoAvailable();
        }
    }
}
```

答:
I figured it out. In my case, this exception is caused by the crash of the system tv application, which owns the Surface object. The codec goes into the Error state when the Surface becomes invalid and at the same moment the ExoPlayer tries to work with the codec's buffers, not knowing that the codec has changed the Executing state to Error.

And the reason for the crash of the system tv app was the following exception:

```<code>02-10 21:31:39.606  7036  7218 E AndroidRuntime: FATAL EXCEPTION: TvCardUpdater-0
02-10 21:31:39.606  7036  7218 E AndroidRuntime: Process: com.sony.dtv.tvx, PID: 7036
02-10 21:31:39.606  7036  7218 E AndroidRuntime: java.lang.RuntimeException: An error occurred while executing doInBackground()
02-10 21:31:39.606  7036  7218 E AndroidRuntime:        at android.os.AsyncTask$3.done(AsyncTask.java:354)
02-10 21:31:39.606  7036  7218 E AndroidRuntime:        at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:383)
02-10 21:31:39.606  7036  7218 E AndroidRuntime:        at java.util.concurrent.FutureTask.setException(FutureTask.java:252)
02-10 21:31:39.606  7036  7218 E AndroidRuntime:        at java.util.concurrent.FutureTask.run(FutureTask.java:271)
02-10 21:31:39.606  7036  7218 E AndroidRuntime:        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1167)
02-10 21:31:39.606  7036  7218 E AndroidRuntime:        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:641)
02-10 21:31:39.606  7036  7218 E AndroidRuntime:        at java.lang.Thread.run(Thread.java:764)
02-10 21:31:39.606  7036  7218 E AndroidRuntime: Caused by: java.lang.ClassCastException: android.graphics.drawable.VectorDrawable cannot be cast to android.graphics.drawable.BitmapDrawable
02-10 21:31:39.606  7036  7218 E AndroidRuntime:        at com.sony.dtv.tvx.tvplayer.function.actionmenu.tvcardstate.AppLinkItemCreator.makeStateOfAppLink(AppLinkItemCreator.java:59)
</code>```

The fix is simple: you need to specify a bitmap for android:banner in AndroidManifest.xml instead of a vector image.

Because Sony has its own app instead of Live Channels, the problem only occurred on the physical device and not on the emulator where Live Channels is installed.

Body:
I'm trying to write a simple TvInputService for Android TV using ExoPlayer. On the emulator everything works fine, but on Sony TV (KDL-43WF804) I get IllegalStateException from video codec after a few seconds of video playing. What am I doing wrong?

Logs:

D/MtkACodecPlugin: MtkACodecPlugin createAPlugin
D/MtkACodecPlugin: OMX.MTK.VIDEO.DECODER.AVC needRmClient (673)
D/MtkACodecPlugin: OMX.MTK.VIDEO.DECODER.AVC mNeedVdpImgrz (679)
I/OMXClient: IOmx service obtained
D/SurfaceUtils: connecting to surface 0x8e25d808, reason connectToSurface
I/MediaCodec: [OMX.MTK.VIDEO.DECODER.AVC] setting surface generation to 21334017
D/SurfaceUtils: disconnecting from surface 0x8e25d808, reason connectToSurface(reconnect)
D/SurfaceUtils: connecting to surface 0x8e25d808, reason connectToSurface(reconnect)
D/MtkMediaCodecPlugin: [OMX.MTK.VIDEO.DECODER.AVC] set mOutputPath = 0 L(150)
E/ACodec: [OMX.MTK.VIDEO.DECODER.AVC] setPortMode on output to DynamicANWBuffer failed w/ err -1010
I/ACodec: codec does not support config priority (err -1010)
D/MtkACodecPlugin: add usage GRALLOC_USAGE_PATH_VDP0
D/SurfaceUtils: disconnecting from surface 0x8e25d808, reason setNativeWindowSizeFormatAndUsage
D/SurfaceUtils: connecting to surface 0x8e25d808, reason setNativeWindowSizeFormatAndUsage
D/SurfaceUtils: set up nativeWindow 0x8e25d808 for 1920x1088, color 0x7f000103, rotation 0, usage 0x30002900
D/MtkACodecPlugin: MtkACodecPlugin createAPlugin
I/OMXClient: IOmx service obtained
D/MtkMediaCodecPlugin: No surfaceTextureClient, [OMX.google.aac.decoder] set mOutputPath = 1024 L(159)
I/ACodec: codec does not support config priority (err -2147483648)
I/ACodec: codec does not support config operating rate (err -2147483648)
W/v.rudnev.tvlak: Accessing hidden method Landroid/media/AudioTrack$Builder;->setOffloadedPlayback(Z)Landroid/media/AudioTrack$Builder; (dark greylist, linking)
W/v.rudnev.tvlak: Accessing hidden method Landroid/media/AudioTrack$Builder;->setOffloadedPlayback(Z)Landroid/media/AudioTrack$Builder; (dark greylist, linking)
E/Surface: queueBuffer: error queuing buffer to SurfaceTexture, -19
E/ACodec: queueBuffer failed in onOutputBufferDrained: -19
E/ACodec: signalError(omxError 0x80001001, internalError -19)
E/MediaCodec: Codec reported err 0xffffffed, actionCode 0, while in state 6
D/SurfaceUtils: disconnecting from surface 0x8e25d808, reason disconnectFromSurface
E/MediaCodecVideoRenderer: Video codec error
      java.lang.IllegalStateException
        at android.media.MediaCodec.native_dequeueInputBuffer(Native Method)
        at android.media.MediaCodec.dequeueInputBuffer(MediaCodec.java:2635)
        at com.google.android.exoplayer2.mediacodec.SynchronousMediaCodecAdapter.dequeueInputBufferIndex(SynchronousMediaCodecAdapter.java:115)
        at com.google.android.exoplayer2.mediacodec.MediaCodecRenderer.feedInputBuffer(MediaCodecRenderer.java:1139)
        at com.google.android.exoplayer2.mediacodec.MediaCodecRenderer.render(MediaCodecRenderer.java:780)
        at com.google.android.exoplayer2.ExoPlayerImplInternal.doSomeWork(ExoPlayerImplInternal.java:982)
        at com.google.android.exoplayer2.ExoPlayerImplInternal.handleMessage(ExoPlayerImplInternal.java:486)
        at android.os.Handler.dispatchMessage(Handler.java:102)
        at android.os.Looper.loop(Looper.java:193)
        at android.os.HandlerThread.run(HandlerThread.java:65)
E/ExoPlayerImplInternal: Playback error
      com.google.android.exoplayer2.ExoPlaybackException: MediaCodecVideoRenderer error, index=0, format=Format(0, null, null, video/avc, avc1.4D4020, 5049176, null, [1920, 1080, 25.0], [-1, -1]), format_supported=YES
        at com.google.android.exoplayer2.ExoPlayerImplInternal.handleMessage(ExoPlayerImplInternal.java:562)
        at android.os.Handler.dispatchMessage(Handler.java:102)
        at android.os.Looper.loop(Looper.java:193)
        at android.os.HandlerThread.run(HandlerThread.java:65)
     Caused by: com.google.android.exoplayer2.video.MediaCodecVideoDecoderException: Decoder failed: OMX.MTK.VIDEO.DECODER.AVC
        at com.google.android.exoplayer2.video.MediaCodecVideoRenderer.createDecoderException(MediaCodecVideoRenderer.java:1470)
        at com.google.android.exoplayer2.mediacodec.MediaCodecRenderer.render(MediaCodecRenderer.java:799)
        at com.google.android.exoplayer2.ExoPlayerImplInternal.doSomeWork(ExoPlayerImplInternal.java:982)
        at com.google.android.exoplayer2.ExoPlayerImplInternal.handleMessage(ExoPlayerImplInternal.java:486)
        at android.os.Handler.dispatchMessage(Handler.java:102)
        at android.os.Looper.loop(Looper.java:193)
        at android.os.HandlerThread.run(HandlerThread.java:65)
     Caused by: java.lang.IllegalStateException
        at android.media.MediaCodec.native_dequeueInputBuffer(Native Method)
        at android.media.MediaCodec.dequeueInputBuffer(MediaCodec.java:2635)
        at com.google.android.exoplayer2.mediacodec.SynchronousMediaCodecAdapter.dequeueInputBufferIndex(SynchronousMediaCodecAdapter.java:115)
        at com.google.android.exoplayer2.mediacodec.MediaCodecRenderer.feedInputBuffer(MediaCodecRenderer.java:1139)
        at com.google.android.exoplayer2.mediacodec.MediaCodecRenderer.render(MediaCodecRenderer.java:780)
        at com.google.android.exoplayer2.ExoPlayerImplInternal.doSomeWork(ExoPlayerImplInternal.java:982)
        at com.google.android.exoplayer2.ExoPlayerImplInternal.handleMessage(ExoPlayerImplInternal.java:486)
        at android.os.Handler.dispatchMessage(Handler.java:102)
        at android.os.Looper.loop(Looper.java:193)
        at android.os.HandlerThread.run(HandlerThread.java:65)
E/ExoPlayerImplInternal: Disable failed.
      java.lang.IllegalStateException
        at android.media.MediaCodec.native_flush(Native Method)
        at android.media.MediaCodec.flush(MediaCodec.java:2131)
        at com.google.android.exoplayer2.mediacodec.SynchronousMediaCodecAdapter.flush(SynchronousMediaCodecAdapter.java:188)
        at com.google.android.exoplayer2.mediacodec.MediaCodecRenderer.flushCodec(MediaCodecRenderer.java:850)
        at com.google.android.exoplayer2.mediacodec.MediaCodecRenderer.flushOrReleaseCodec(MediaCodecRenderer.java:843)
        at com.google.android.exoplayer2.mediacodec.MediaCodecRenderer.onDisabled(MediaCodecRenderer.java:696)
        at com.google.android.exoplayer2.video.MediaCodecVideoRenderer.onDisabled(MediaCodecVideoRenderer.java:529)
        at com.google.android.exoplayer2.BaseRenderer.disable(BaseRenderer.java:178)
        at com.google.android.exoplayer2.ExoPlayerImplInternal.disableRenderer(ExoPlayerImplInternal.java:1642)
        at com.google.android.exoplayer2.ExoPlayerImplInternal.resetInternal(ExoPlayerImplInternal.java:1382)
        at com.google.android.exoplayer2.ExoPlayerImplInternal.stopInternal(ExoPlayerImplInternal.java:1345)
        at com.google.android.exoplayer2.ExoPlayerImplInternal.handleMessage(ExoPlayerImplInternal.java:578)
        at android.os.Handler.dispatchMessage(Handler.java:102)
        at android.os.Looper.loop(Looper.java:193)
        at android.os.HandlerThread.run(HandlerThread.java:65)
E/Surface: getSlotFromBufferLocked: unknown buffer: 0x8b2a6d00
W/ACodec: [OMX.MTK.VIDEO.DECODER.AVC] can not return buffer 22 to native window
D/gralloc: unregister FBM buffer
E/Surface: getSlotFromBufferLocked: unknown buffer: 0x8b2a6c00
W/ACodec: [OMX.MTK.VIDEO.DECODER.AVC] can not return buffer 21 to native window
E/Surface: getSlotFromBufferLocked: unknown buffer: 0x8b2a6700
W/ACodec: [OMX.MTK.VIDEO.DECODER.AVC] can not return buffer 16 to native window
D/gralloc: unregister FBM buffer
E/Surface: getSlotFromBufferLocked: unknown buffer: 0x8b2a6600
W/ACodec: [OMX.MTK.VIDEO.DECODER.AVC] can not return buffer 15 to native window
D/gralloc: unregister FBM buffer
E/Surface: getSlotFromBufferLocked: unknown buffer: 0x8b2a6500
W/ACodec: [OMX.MTK.VIDEO.DECODER.AVC] can not return buffer 14 to native window
D/gralloc: unregister FBM buffer
E/Surface: getSlotFromBufferLocked: unknown buffer: 0x8b2a6400
W/ACodec: [OMX.MTK.VIDEO.DECODER.AVC] can not return buffer 13 to native window
D/gralloc: unregister FBM buffer
E/Surface: getSlotFromBufferLocked: unknown buffer: 0x8b2a6300
W/ACodec: [OMX.MTK.VIDEO.DECODER.AVC] can not return buffer 12 to native window
D/gralloc: unregister FBM buffer
E/Surface: getSlotFromBufferLocked: unknown buffer: 0x8b2a6200
W/ACodec: [OMX.MTK.VIDEO.DECODER.AVC] can not return buffer 11 to native window
D/gralloc: unregister FBM buffer
E/Surface: getSlotFromBufferLocked: unknown buffer: 0x8b2a6100
W/ACodec: [OMX.MTK.VIDEO.DECODER.AVC] can not return buffer 10 to native window
D/gralloc: unregister FBM buffer
E/Surface: getSlotFromBufferLocked: unknown buffer: 0x8b2a6000
W/ACodec: [OMX.MTK.VIDEO.DECODER.AVC] can not return buffer 9 to native window
D/gralloc: unregister FBM buffer
E/Surface: getSlotFromBufferLocked: unknown buffer: 0x8b290f00
W/ACodec: [OMX.MTK.VIDEO.DECODER.AVC] can not return buffer 8 to native window
D/gralloc: unregister FBM buffer
E/Surface: getSlotFromBufferLocked: unknown buffer: 0x8b290e00
W/ACodec: [OMX.MTK.VIDEO.DECODER.AVC] can not return buffer 7 to native window
D/gralloc: unregister FBM buffer
E/Surface: getSlotFromBufferLocked: unknown buffer: 0x8b290d00
W/ACodec: [OMX.MTK.VIDEO.DECODER.AVC] can not return buffer 6 to native window
D/gralloc: unregister FBM buffer
E/Surface: getSlotFromBufferLocked: unknown buffer: 0x8b290c00
W/ACodec: [OMX.MTK.VIDEO.DECODER.AVC] can not return buffer 5 to native window
D/gralloc: unregister FBM buffer
E/Surface: getSlotFromBufferLocked: unknown buffer: 0x8b290b00
W/ACodec: [OMX.MTK.VIDEO.DECODER.AVC] can not return buffer 4 to native window
D/gralloc: unregister FBM buffer
E/Surface: getSlotFromBufferLocked: unknown buffer: 0x8b290a00
W/ACodec: [OMX.MTK.VIDEO.DECODER.AVC] can not return buffer 3 to native window
D/gralloc: unregister FBM buffer
D/MediaCodec: mState = 0, mHaveKick = 0, L(703)
D/MtkACodecPlugin: MtkACodecPlugin destoryAPlugin
D/gralloc: unregister FBM buffer
I/chatty: uid=10178(dev.rudnev.tvlake) identical 3 lines
D/gralloc: unregister FBM buffer
I/ExoPlayerImpl: Release b6e9764 [ExoPlayerLib/2.16.1] [BRAVIA_ATV3_2K, BRAVIA 2K GB ATV3, Sony, 28] [goog.exo.core, goog.exo.decoder, goog.exo.exoplayer, goog.exo.hls, goog.exo.datasource, goog.exo.extractor]
D/MediaCodec: mState = 0, mHaveKick = 0, L(703)
D/MtkACodecPlugin: MtkACodecPlugin destoryAPlugin

Code:

public class IptvInputService extends TvInputService {
    private static final String TAG = "IptvInputService";

    @Override
    public Session onCreateSession(String inputId) {
        return new Session(this);
    }

    public static class Session extends TvInputService.Session {
        private final Context mContext;
        private final ExoPlayer mPlayer;

        public Session(Context context) {
            super(context);
            mContext = context;
            mPlayer = new ExoPlayer.Builder(context).build();
            mPlayer.addListener(new PlayerListener(this));
        }

        @Override
        public void onRelease() {
            mPlayer.release();
        }

        @Override
        public boolean onSetSurface(@Nullable Surface surface) {
            mPlayer.setVideoSurface(surface);
            return true;
        }

        @Override
        public void onSetStreamVolume(float volume) {
            mPlayer.setVolume(volume);
        }

        @Override
        public boolean onTune(Uri uri) {
            try {
                notifyVideoUnavailable(TvInputManager.VIDEO_UNAVAILABLE_REASON_TUNING);

                String streamUrl = "https://okkotv-live.cdnvideo.ru/channel/Viasat_Explore_HD.m3u8";

                mPlayer.setMediaItem(MediaItem.fromUri(streamUrl));
                mPlayer.prepare();
                mPlayer.play();

                return true;
            } catch (Throwable ex) {
                notifyVideoUnavailable(TvInputManager.VIDEO_UNAVAILABLE_REASON_UNKNOWN);
                Log.e(TAG, "Unable to play stream", ex);
            }

            return false;
        }

        @Override
        public void onSetCaptionEnabled(boolean b) {
        }
    }

    private static class PlayerListener implements Player.Listener {
        private final Session mSession;

        public PlayerListener(Session session) {
            mSession = session;
        }

        @Override
        public void onRenderedFirstFrame() {
            mSession.notifyVideoAvailable();
        }
    }
}

Body:
I figured it out. In my case, this exception is caused by the crash of the system tv application, which owns the Surface object. The codec goes into the Error state when the Surface becomes invalid and at the same moment the ExoPlayer tries to work with the codec's buffers, not knowing that the codec has changed the Executing state to Error.

And the reason for the crash of the system tv app was the following exception:

02-10 21:31:39.606  7036  7218 E AndroidRuntime: FATAL EXCEPTION: TvCardUpdater-0
02-10 21:31:39.606  7036  7218 E AndroidRuntime: Process: com.sony.dtv.tvx, PID: 7036
02-10 21:31:39.606  7036  7218 E AndroidRuntime: java.lang.RuntimeException: An error occurred while executing doInBackground()
02-10 21:31:39.606  7036  7218 E AndroidRuntime:        at android.os.AsyncTask$3.done(AsyncTask.java:354)
02-10 21:31:39.606  7036  7218 E AndroidRuntime:        at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:383)
02-10 21:31:39.606  7036  7218 E AndroidRuntime:        at java.util.concurrent.FutureTask.setException(FutureTask.java:252)
02-10 21:31:39.606  7036  7218 E AndroidRuntime:        at java.util.concurrent.FutureTask.run(FutureTask.java:271)
02-10 21:31:39.606  7036  7218 E AndroidRuntime:        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1167)
02-10 21:31:39.606  7036  7218 E AndroidRuntime:        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:641)
02-10 21:31:39.606  7036  7218 E AndroidRuntime:        at java.lang.Thread.run(Thread.java:764)
02-10 21:31:39.606  7036  7218 E AndroidRuntime: Caused by: java.lang.ClassCastException: android.graphics.drawable.VectorDrawable cannot be cast to android.graphics.drawable.BitmapDrawable
02-10 21:31:39.606  7036  7218 E AndroidRuntime:        at com.sony.dtv.tvx.tvplayer.function.actionmenu.tvcardstate.AppLinkItemCreator.makeStateOfAppLink(AppLinkItemCreator.java:59)

The fix is simple: you need to specify a bitmap for android:banner in AndroidManifest.xml instead of a vector image.

Because Sony has its own app instead of Live Channels, the problem only occurred on the physical device and not on the emulator where Live Channels is installed.


问:
Python Daemon: ValueError: I/O operation on closed file
I'm trying to use DaemonContext as follows:

    with DaemonContext(
        working_directory=WORKDIR,
        umask=0o002,
        pidfile=pidfile.TimeoutPIDLockFile(PIDFILE),
    ):
        main()
```
<p>I get the error <code>ValueError: I/O operation on closed file</code>. It's unclear if this has to do with the pidfile, stdout/stderr, or something I'm doing inside <code>main()</code>. This is running inside a Docker container.</p>
<p>Here's my stack trace. Grateful for any insights.</p>
```Traceback (most recent call last):
...
    pidfile=pidfile.TimeoutPIDLockFile("/tmp/cwmetrics.pid"),
  File "/usr/local/lib/python3.7/site-packages/daemon/daemon.py", line 272, in __init__
    detach_process = is_detach_process_context_required()
  File "/usr/local/lib/python3.7/site-packages/daemon/daemon.py", line 819, in is_detach_process_context_required
    if is_process_started_by_init() or is_process_started_by_superserver():
  File "/usr/local/lib/python3.7/site-packages/daemon/daemon.py", line 795, in is_process_started_by_superserver
    stdin_fd = sys.__stdin__.fileno()
ValueError: I/O operation on closed file
```

I did report it over here as well: https://pagure.io/python-daemon/issue/64 I'm just unclear if it's an issue with the library or my usage of it.

答:
You are trying to detach (daemonize) process, but still want to preserve access to default stdin/stdout - but your detached process will not have files to write to. You should create some files, which would be used as stdin/stdout and point to them in arguments.

DaemonContext closes all opened streams on entering context. If you redirects your stdin/stdout somewhere in your code, you may avoid closing them with argument
files_preserve=[...], where you should put those files in the list.

Body:
I'm trying to use DaemonContext as follows:

    with DaemonContext(
        working_directory=WORKDIR,
        umask=0o002,
        pidfile=pidfile.TimeoutPIDLockFile(PIDFILE),
    ):
        main()

I get the error ValueError: I/O operation on closed file. It's unclear if this has to do with the pidfile, stdout/stderr, or something I'm doing inside main(). This is running inside a Docker container.

Here's my stack trace. Grateful for any insights.

Traceback (most recent call last):
...
    pidfile=pidfile.TimeoutPIDLockFile("/tmp/cwmetrics.pid"),
  File "/usr/local/lib/python3.7/site-packages/daemon/daemon.py", line 272, in __init__
    detach_process = is_detach_process_context_required()
  File "/usr/local/lib/python3.7/site-packages/daemon/daemon.py", line 819, in is_detach_process_context_required
    if is_process_started_by_init() or is_process_started_by_superserver():
  File "/usr/local/lib/python3.7/site-packages/daemon/daemon.py", line 795, in is_process_started_by_superserver
    stdin_fd = sys.__stdin__.fileno()
ValueError: I/O operation on closed file

I did report it over here as well: https://pagure.io/python-daemon/issue/64 I'm just unclear if it's an issue with the library or my usage of it.


问:
If else statements in numpy arange
Basicaly I want to compare a variable between two np.arange()

```<code>x = 22.03
first = np.arange(18.5, 24.99, 0.01)
second = np.arange(25.0, 29.99, 0.01)

if x in first:
    print("x is in first")
elif x in second:
    print("x is in second")
</code>```

I expect to see "x isin first" but rather I get nothing printed on the terminal.
If I add another else: statement it will execute whatever is in that.

I am using numpy because I want to have a range of floats. The native range() function doesn't support floats

There happens no comparison between the two, why is that?

Title: If else statements in numpy arange

Body:
Basicaly I want to compare a variable between two np.arange()

x = 22.03
first = np.arange(18.5, 24.99, 0.01)
second = np.arange(25.0, 29.99, 0.01)

if x in first:
    print("x is in first")
elif x in second:
    print("x is in second")

I expect to see "x isin first" but rather I get nothing printed on the terminal.
If I add another else: statement it will execute whatever is in that.

I am using numpy because I want to have a range of floats. The native range() function doesn't support floats

There happens no comparison between the two, why is that?

Body:
Your array:

In [254]: first = np.arange(18.5, 24.99, 0.01)
In [255]: first.shape
Out[255]: (649,)
In [256]: first[:10]
Out[256]:
array([18.5 , 18.51, 18.52, 18.53, 18.54, 18.55, 18.56, 18.57, 18.58,
       18.59])
In [257]: x=22.03

x isn't "found"

In [258]: x in first
Out[258]: False

Let's look for a close match:

In [259]: np.nonzero(np.isclose(x,first))
Out[259]: (array([353]),)
In [260]: first[353]
Out[260]: 22.030000000000552

The closest match is still a bit off - due to floating point calculations.  'in/equal' tests on floating point values are not reliable.

arange recommends linspace when using float steps.  The resulting values are a closer match to our expectations:

In [264]: first1 = np.linspace(18.5,24.98,len(first))
In [265]: np.nonzero(np.isclose(x,first1))
Out[265]: (array([353]),)
In [266]: first1[353]
Out[266]: 22.03
In [267]: x in first1
Out[267]: True

There still is a potential for a float mismatch.

To better see the full precision of the floats, lets display the arrays as lists

In [268]: first[:10].tolist()
Out[268]:
[18.5,
 18.51,
 18.520000000000003,
 18.530000000000005,
 18.540000000000006,
 18.550000000000008,
 18.56000000000001,
 18.57000000000001,
 18.580000000000013,
 18.590000000000014]
In [269]: first1[:10].tolist()
Out[269]: [18.5, 18.51, 18.52, 18.53, 18.54, 18.55, 18.56, 18.57, 18.58, 18.59]


问:
Socket rejoins again and again which causes Live View to emit events itself periodically. when using with Alpine js
Issue:
Socket rejoins again and again which causes Live View to emit events itself periodically.

Scenario: I have index page which contains phx-change events. When I left the page idle for sometime, the events started to triggered automatically periodically.
It is not limited to single page but it happen on each live view page, I googled the issue but couldn’t find any solution.

1 reason I noticed that sometimes heartbeat stops for more than 1 minute(timeout limit is 1 minute), in this case socket rejoined again.

I increased timeout at client side as well at server side in Endpoint to check if this is the only issue but it didn’t work and socket behaved the same.

Did anyone face same issue before, what could be a possible reasons and how to avoid this issue, any suggestion?

Stack: PETAL

Elixir: 1.11
Erlang: 23.0
phoenix: 1.5.3
phoenix_live_view: 0.15.7
alpinejs “^2.8.2”
Browsers: chrome, safari

I think issue is with Alpine Js but couldn’t figure out any solution.

Here is my app.js code

let csrfToken = document.querySelector("meta[name='csrf-token']").getAttribute("content");
let liveSocket = new LiveSocket("/live", Socket, {
    uploaders: Uploaders,
    hooks: Hooks,
    params: { _csrf_token: csrfToken },
    timeout: 60000,
    dom: {
        onBeforeElUpdated(from, to) {
            if (from.__x) {
                Alpine.clone(from.__x, to);
            }
            flatpickr(".date-picker", {
                wrap: true,
                disableMobile: true,
                dateFormat: "Ymd H:i:S.ssss"
            });
            flatpickr(".datetime-picker", {
                enableTime: true,
                wrap: true,
                disableMobile: true,
                "plugins": [new confirmDatePlugin({ confirmIcon: "", confirmText: "Confirm" })],
                time_24hr: true,
                dateFormat: "Ymd H:i:S.ssss"
            });
        }
    },
    heartbeatIntervalMs: 10000
});
```
<p>Endpoint Configuration:</p>
``` socket "/socket", PrintSimpleWeb.UserSocket,
  websocket: [
    timeout: :infinity,
  ],
    longpoll: false

  socket "/live", Phoenix.LiveView.Socket, websocket: [connect_info: [session: @session_options]]
```

答:
it was fixed by simple updating Elixir dependencies and npm packages.
Here are the steps which I followed:</p>
```<code>> remove _build, node_modules, deps folder
RUN:
> mix deps.get
> mix compile
> npm install (inside /assets)
> iex -S mix phx.server
</code>```

Body:
Issue:
Socket rejoins again and again which causes Live View to emit events itself periodically.

Scenario: I have index page which contains phx-change events. When I left the page idle for sometime, the events started to triggered automatically periodically.
It is not limited to single page but it happen on each live view page, I googled the issue but couldn’t find any solution.

1 reason I noticed that sometimes heartbeat stops for more than 1 minute(timeout limit is 1 minute), in this case socket rejoined again.

I increased timeout at client side as well at server side in Endpoint to check if this is the only issue but it didn’t work and socket behaved the same.

Did anyone face same issue before, what could be a possible reasons and how to avoid this issue, any suggestion?

Stack: PETAL

Elixir: 1.11
Erlang: 23.0
phoenix: 1.5.3
phoenix_live_view: 0.15.7
alpinejs “^2.8.2”
Browsers: chrome, safari

I think issue is with Alpine Js but couldn’t figure out any solution.

Here is my app.js code

let csrfToken = document.querySelector("meta[name='csrf-token']").getAttribute("content");
let liveSocket = new LiveSocket("/live", Socket, {
    uploaders: Uploaders,
    hooks: Hooks,
    params: { _csrf_token: csrfToken },
    timeout: 60000,
    dom: {
        onBeforeElUpdated(from, to) {
            if (from.__x) {
                Alpine.clone(from.__x, to);
            }
            flatpickr(".date-picker", {
                wrap: true,
                disableMobile: true,
                dateFormat: "Ymd H:i:S.ssss"
            });
            flatpickr(".datetime-picker", {
                enableTime: true,
                wrap: true,
                disableMobile: true,
                "plugins": [new confirmDatePlugin({ confirmIcon: "", confirmText: "Confirm" })],
                time_24hr: true,
                dateFormat: "Ymd H:i:S.ssss"
            });
        }
    },
    heartbeatIntervalMs: 10000
});

Endpoint Configuration:

 socket "/socket", PrintSimpleWeb.UserSocket,
  websocket: [
    timeout: :infinity,
  ],
    longpoll: false

  socket "/live", Phoenix.LiveView.Socket, websocket: [connect_info: [session: @session_options]]

Body:
it was fixed by simple updating Elixir dependencies and npm packages.
Here are the steps which I followed:

> remove _build, node_modules, deps folder
RUN:
> mix deps.get
> mix compile
> npm install (inside /assets)
> iex -S mix phx.server


问:
How to pass data between activities forward and backward, android, kotlin
Let's say my application has 4 activities (A -> B -> C -> D) when going forward, activity A pass a data value called category to activity B and then activity B pass category and also and data value called level and both used in activity D to get data from firebase realtime database. but when the user goes back to activity C and tries to go again to D data passed from A (category) is now null. so data can't retrieve from firebase. my question is how can I solve this situation.? "I pass data using Intent by putting extras." are there any other ways?

答:
You can use a shared ViewModel. Viewmodels are lifecycle-aware components. Data in ViewModels does not disappear when activity changes

Save your data (category,level) in ViewModel like this :

```<code>private val _categoryValue =
    MutableLiveData<CategoryType>()
val categoryValue:
LiveData<ResponseState<CategoryType> =
    _categoryValue
</code>```

And update your data in activity like this:

```<code>vm.categoryValue.value = newCategoryValue
</code>```

If you are using binding etc. observe and do stuff with your data like this:

```<code>vm.deleteFileResponse.observe(this){ category ->
  //Do stuff
 }
</code>```

Body:
You can use a shared ViewModel. Viewmodels are lifecycle-aware components. Data in ViewModels does not disappear when activity changes

Save your data (category,level) in ViewModel like this :

private val _categoryValue =
    MutableLiveData<CategoryType>()
val categoryValue:
LiveData<ResponseState<CategoryType> =
    _categoryValue

And update your data in activity like this:

vm.categoryValue.value = newCategoryValue

If you are using binding etc. observe and do stuff with your data like this:

vm.deleteFileResponse.observe(this){ category ->
  //Do stuff
 }


问:
How can I make overlay buttons that always stay over the same part of the picture that is under them?
I have an interesting issue or objective here. I have an image that is a yellow rectangle with 3 red rectangles in it. I'd like to add clickable buttons as an overlay on top of the picture, right over the red rectangles.

Thing is, I would like those buttons to always be exactly over each red rectangles, same size/position, no matter the aspect ratio of the pciture, the screen resolution of the user, or the zoom percentage of his browser (as if the buttons were part of the image)

As an example, I've included a picture where the yellow rectangles and the red rectangles are part of the same image, and the dotted green line would be the overlay buttons or their respective divs.

[Not enough reputation for picture, but here] : https://i.imgur.com/ms4xmMZ.png

MY HTML SO FAR

```<code><body>
    <div class="image-container">
        <img src="img/justelimage.png" alt="Nature" class="video" />

        <a href=“#”></a>

    </div>
</body>
</code>```

MY CSS SO FAR WORKS BUT THERE SHOULD BE A BETTER WAY ?
(works when I resize window, and change browser's zoom percentage, but what if we change the aspect ratio?)

```<code>
.image-container {
    display: inline-block;
    position: relative;
    margin-left: auto;
    margin-right: auto;
    width: 80vw;
    height: auto;
    z-index:0;

}

.video {
    position: absolute;
    width: 100%;
    height: auto;
    z-index:1;

}

.image-container a{
    position: absolute;
    margin-top:4.5%;

    margin-left: 57%;
    width:28.3vw;
    height: 7vw;
    color:white;
    border: 0.25vw solid green;
    z-index: 999;

}

}

</code>```

Any idea how I could manage to get this in a more logical way?

Any suggestions would be gladly appreciated. Thanks!

答:
I'd wrap the anchor in a div to center it. That way you could style
anchor separately with px while maintaining its position relative to the img.

```<code>    <body>
      <div class="image-container">
       <img src="img/justelimage.png" alt="Nature" class="video" />
       <div class="link-container">
         <a href=“#”></a>
       </div>
      </div>
    </body>

    .link-container {
       position: absolute;
       top: 50%;
       left: 50%;
    }
</code>```

If you also style the .image-container with a background color
and opacity you can toggle those values on :hover.

Body:
I have an interesting issue or objective here. I have an image that is a yellow rectangle with 3 red rectangles in it. I'd like to add clickable buttons as an overlay on top of the picture, right over the red rectangles.

Thing is, I would like those buttons to always be exactly over each red rectangles, same size/position, no matter the aspect ratio of the pciture, the screen resolution of the user, or the zoom percentage of his browser (as if the buttons were part of the image)

As an example, I've included a picture where the yellow rectangles and the red rectangles are part of the same image, and the dotted green line would be the overlay buttons or their respective divs.

[Not enough reputation for picture, but here] : https://i.imgur.com/ms4xmMZ.png

MY HTML SO FAR

MY CSS SO FAR WORKS BUT THERE SHOULD BE A BETTER WAY ?
(works when I resize window, and change browser's zoom percentage, but what if we change the aspect ratio?)

.image-container {
    display: inline-block;
    position: relative;
    margin-left: auto;
    margin-right: auto;
    width: 80vw;
    height: auto;
    z-index:0;

}

.video {
    position: absolute;
    width: 100%;
    height: auto;
    z-index:1;

}

.image-container a{
    position: absolute;
    margin-top:4.5%;

    margin-left: 57%;
    width:28.3vw;
    height: 7vw;
    color:white;
    border: 0.25vw solid green;
    z-index: 999;

}

}

Any idea how I could manage to get this in a more logical way?

Any suggestions would be gladly appreciated. Thanks!

Body:
I'd wrap the anchor in a div to center it. That way you could style
anchor separately with px while maintaining its position relative to the img.

    <body>
      <div class="image-container">
       <img src="img/justelimage.png" alt="Nature" class="video" />
       <div class="link-container">
         <a href=“#”></a>
       </div>
      </div>
    </body>

    .link-container {
       position: absolute;
       top: 50%;
       left: 50%;
    }

If you also style the .image-container with a background color
and opacity you can toggle those values on :hover.


问:
How to replace dataframe values by other dataframe values, keeping values that are equal to both in R?
I have two dataframes, toy1 and toy2. I would like to create a new dataframe, replacing the different values that are in toy2 in toy1 and keeping the same values (0) that are in toy1. Taking into account that there are different numbers of columns and rows.
So in this example below, i want a result that is a dataframe of 208 columns and 2 rows.

toy1:

```<code>structure(list(revenue = 0, risk = 0, target_amount = 0, company_years = 0,
approved_commitee = 0, score = 0, reason_Capital_giro = 0,
reason_Compra_equip = 0, reason_Compra_estoque = 0, reason_Cons_div = 0,
reason_Expansao = 0, reason_Outros = 0, reason_working_capital = 0,
serasa_0 = 0, serasa_1 = 0, serasa_1.5 = 0, serasa_1.8 = 0,
serasa_2 = 0, serasa_2.6 = 0, serasa_3 = 0, serasa_3.1 = 0,
serasa_3.2 = 0, serasa_3.3 = 0, serasa_3.4 = 0, serasa_3.6 = 0,
serasa_3.8 = 0, serasa_4 = 0, serasa_4.2 = 0, serasa_4.4 = 0,
serasa_4.6 = 0, serasa_5 = 0, pontualidade_0.75neg = 0, pontualidade_0 = 0,
pontualidade_0.25 = 0, pontualidade_0.75 = 0, pontualidade_2.25 = 0,
pontualidade_2.5 = 0, pontualidade_2.75 = 0, pontualidade_3 = 0,
pontualidade_3.25 = 0, pontualidade_3.5 = 0, pontualidade_3.75 = 0,
pontualidade_4 = 0, pontualidade_4.25 = 0, pontualidade_4.5 = 0,
pontualidade_4.75 = 0, pontualidade_5 = 0, qualidade_divida_0 = 0,
qualidade_divida_1 = 0, qualidade_divida_1.4 = 0, qualidade_divida_1.6 = 0,
qualidade_divida_2 = 0, qualidade_divida_2.2 = 0, qualidade_divida_2.8 = 0,
qualidade_divida_3.4 = 0, qualidade_divida_3.5 = 0, qualidade_divida_3.7 = 0,
qualidade_divida_3.8 = 0, qualidade_divida_4 = 0, qualidade_divida_4.2 = 0,
qualidade_divida_4.5 = 0, qualidade_divida_4.6 = 0, qualidade_divida_4.8 = 0,
qualidade_divida_5 = 0, bancabilidade_0 = 0, bancabilidade_0.1 = 0,
bancabilidade_0.2 = 0, bancabilidade_0.5 = 0, bancabilidade_0.6 = 0,
bancabilidade_0.7 = 0, bancabilidade_0.8 = 0, bancabilidade_1 = 0,
bancabilidade_1.2 = 0, bancabilidade_1.3 = 0, bancabilidade_1.4 = 0,
bancabilidade_1.5 = 0, bancabilidade_1.6 = 0, bancabilidade_1.7 = 0,
bancabilidade_1.8 = 0, bancabilidade_2 = 0, bancabilidade_2.1 = 0,
bancabilidade_2.2 = 0, bancabilidade_2.3 = 0, bancabilidade_2.4 = 0,
bancabilidade_2.5 = 0, bancabilidade_2.6 = 0, bancabilidade_2.7 = 0,
bancabilidade_2.8 = 0, bancabilidade_3 = 0, bancabilidade_3.1 = 0,
bancabilidade_3.2 = 0, bancabilidade_3.3 = 0, bancabilidade_3.4 = 0,
bancabilidade_3.5 = 0, bancabilidade_3.6 = 0, bancabilidade_3.8 = 0,
bancabilidade_3.9 = 0, bancabilidade_4 = 0, bancabilidade_4.1 = 0,
bancabilidade_4.2 = 0, bancabilidade_4.4 = 0, bancabilidade_4.5 = 0,
bancabilidade_4.6 = 0, bancabilidade_4.7 = 0, bancabilidade_4.8 = 0,
bancabilidade_5 = 0, alavancagem_0 = 0, alavancagem_0.2 = 0,
alavancagem_1 = 0, alavancagem_1.6 = 0, alavancagem_2 = 0,
alavancagem_2.4 = 0, alavancagem_2.5 = 0, alavancagem_3 = 0,
alavancagem_3.4 = 0, alavancagem_4 = 0, alavancagem_5 = 0,
porte_0 = 0, porte_1 = 0, porte_1.4 = 0, porte_2 = 0, porte_2.4 = 0,
porte_2.8 = 0, porte_3 = 0, porte_3.2 = 0, porte_3.6 = 0,
porte_4 = 0, porte_4.4 = 0, porte_4.6 = 0, porte_4.8 = 0,
porte_5 = 0, receita_recorrencias_0.6 = 0, receita_recorrencias_0.8 = 0,
receita_recorrencias_1 = 0, receita_recorrencias_1.4 = 0,
receita_recorrencias_2 = 0, receita_recorrencias_2.4 = 0,
receita_recorrencias_2.6 = 0, receita_recorrencias_3 = 0,
receita_recorrencias_3.2 = 0, receita_recorrencias_3.4 = 0,
receita_recorrencias_3.8 = 0, receita_recorrencias_4 = 0,
receita_recorrencias_4.4 = 0, receita_recorrencias_5 = 0,
respaldo_patrimonio_0 = 0, respaldo_patrimonio_0.4 = 0, respaldo_patrimonio_0.5 = 0,
respaldo_patrimonio_0.7 = 0, respaldo_patrimonio_0.75 = 0,
respaldo_patrimonio_0.8 = 0, respaldo_patrimonio_1 = 0, respaldo_patrimonio_1.2 = 0,
respaldo_patrimonio_1.3 = 0, respaldo_patrimonio_1.4 = 0,
respaldo_patrimonio_1.5 = 0, respaldo_patrimonio_1.7 = 0,
respaldo_patrimonio_1.9 = 0, respaldo_patrimonio_2.2 = 0,
respaldo_patrimonio_2.3 = 0, respaldo_patrimonio_2.6 = 0,
respaldo_patrimonio_3 = 0, respaldo_patrimonio_3.2 = 0, respaldo_patrimonio_3.5 = 0,
respaldo_patrimonio_3.6 = 0, respaldo_patrimonio_4 = 0, respaldo_patrimonio_4.4 = 0,
respaldo_patrimonio_5 = 0, reputacional_1 = 0, reputacional_2 = 0,
reputacional_2.5 = 0, reputacional_3 = 0, reputacional_3.5 = 0,
reputacional_3.65 = 0, reputacional_4 = 0, reputacional_5 = 0,
impacto_covid_1 = 0, impacto_covid_1.5 = 0, impacto_covid_2 = 0,
impacto_covid_2.5 = 0, impacto_covid_3 = 0, impacto_covid_3.5 = 0,
impacto_covid_3.65 = 0, impacto_covid_4 = 0, impacto_covid_5 = 0,
business_sector_Comercio = 0, business_sector_Industria = 0,
business_sector_Servicos = 0, state_AC = 0, state_AM = 0,
state_BA = 0, state_CE = 0, state_DF = 0, state_GO = 0, state_MG = 0,
state_MS = 0, state_MT = 0, state_PA = 0, state_PB = 0, state_PE = 0,
state_PR = 0, state_RJ = 0, state_RS = 0, state_SC = 0, state_SP = 0,
state_TO = 0, decision_motor_approved = 0, decision_motor_denied = 0), row.names = 1L, class = "data.frame")
</code>```

toy2

```<code> structure(list(revenue = c(4397487.34, 198019.75), risk = c(12137650.06,
469506.24), target_amount = c(150000, 1e+05), company_years = c(18,
9), approved_commitee = structure(c(2L, 2L), .Label = c("NO",
"YES"), class = "factor"), score = c(134, 128), reason_Compra_equip = c(1,
1), serasa_1.8 = c(1, 1), pontualidade_0.25 = c(1, 1), qualidade_divida_1 = c(1,
1), bancabilidade_0.2 = c(1, 1), alavancagem_1.6 = c(1L, 1L),
    porte_4.6 = c(1, 1), receita_recorrencias_3 = c(1, 1), respaldo_patrimonio_0.5 = c(1,
    1), reputacional_5 = c(1, 1), impacto_covid_3 = c(1, 1),
    business_sector_Comercio = c(1, 1), state_GO = c(1, 1)), row.names = c(10L,
12L), class = "data.frame")
</code>```

答:
Check this :

```<code>a <- which(names(toy1) %in% names(toy2))
toy1[2,] <- 0
toy1[a] <- toy2
</code>```

toy1 has only 1 row while toy2 has two. So I added an extra 0 row in toy1.

Body:
I have two dataframes, toy1 and toy2. I would like to create a new dataframe, replacing the different values that are in toy2 in toy1 and keeping the same values (0) that are in toy1. Taking into account that there are different numbers of columns and rows.
So in this example below, i want a result that is a dataframe of 208 columns and 2 rows.

toy1:

structure(list(revenue = 0, risk = 0, target_amount = 0, company_years = 0,
approved_commitee = 0, score = 0, reason_Capital_giro = 0,
reason_Compra_equip = 0, reason_Compra_estoque = 0, reason_Cons_div = 0,
reason_Expansao = 0, reason_Outros = 0, reason_working_capital = 0,
serasa_0 = 0, serasa_1 = 0, serasa_1.5 = 0, serasa_1.8 = 0,
serasa_2 = 0, serasa_2.6 = 0, serasa_3 = 0, serasa_3.1 = 0,
serasa_3.2 = 0, serasa_3.3 = 0, serasa_3.4 = 0, serasa_3.6 = 0,
serasa_3.8 = 0, serasa_4 = 0, serasa_4.2 = 0, serasa_4.4 = 0,
serasa_4.6 = 0, serasa_5 = 0, pontualidade_0.75neg = 0, pontualidade_0 = 0,
pontualidade_0.25 = 0, pontualidade_0.75 = 0, pontualidade_2.25 = 0,
pontualidade_2.5 = 0, pontualidade_2.75 = 0, pontualidade_3 = 0,
pontualidade_3.25 = 0, pontualidade_3.5 = 0, pontualidade_3.75 = 0,
pontualidade_4 = 0, pontualidade_4.25 = 0, pontualidade_4.5 = 0,
pontualidade_4.75 = 0, pontualidade_5 = 0, qualidade_divida_0 = 0,
qualidade_divida_1 = 0, qualidade_divida_1.4 = 0, qualidade_divida_1.6 = 0,
qualidade_divida_2 = 0, qualidade_divida_2.2 = 0, qualidade_divida_2.8 = 0,
qualidade_divida_3.4 = 0, qualidade_divida_3.5 = 0, qualidade_divida_3.7 = 0,
qualidade_divida_3.8 = 0, qualidade_divida_4 = 0, qualidade_divida_4.2 = 0,
qualidade_divida_4.5 = 0, qualidade_divida_4.6 = 0, qualidade_divida_4.8 = 0,
qualidade_divida_5 = 0, bancabilidade_0 = 0, bancabilidade_0.1 = 0,
bancabilidade_0.2 = 0, bancabilidade_0.5 = 0, bancabilidade_0.6 = 0,
bancabilidade_0.7 = 0, bancabilidade_0.8 = 0, bancabilidade_1 = 0,
bancabilidade_1.2 = 0, bancabilidade_1.3 = 0, bancabilidade_1.4 = 0,
bancabilidade_1.5 = 0, bancabilidade_1.6 = 0, bancabilidade_1.7 = 0,
bancabilidade_1.8 = 0, bancabilidade_2 = 0, bancabilidade_2.1 = 0,
bancabilidade_2.2 = 0, bancabilidade_2.3 = 0, bancabilidade_2.4 = 0,
bancabilidade_2.5 = 0, bancabilidade_2.6 = 0, bancabilidade_2.7 = 0,
bancabilidade_2.8 = 0, bancabilidade_3 = 0, bancabilidade_3.1 = 0,
bancabilidade_3.2 = 0, bancabilidade_3.3 = 0, bancabilidade_3.4 = 0,
bancabilidade_3.5 = 0, bancabilidade_3.6 = 0, bancabilidade_3.8 = 0,
bancabilidade_3.9 = 0, bancabilidade_4 = 0, bancabilidade_4.1 = 0,
bancabilidade_4.2 = 0, bancabilidade_4.4 = 0, bancabilidade_4.5 = 0,
bancabilidade_4.6 = 0, bancabilidade_4.7 = 0, bancabilidade_4.8 = 0,
bancabilidade_5 = 0, alavancagem_0 = 0, alavancagem_0.2 = 0,
alavancagem_1 = 0, alavancagem_1.6 = 0, alavancagem_2 = 0,
alavancagem_2.4 = 0, alavancagem_2.5 = 0, alavancagem_3 = 0,
alavancagem_3.4 = 0, alavancagem_4 = 0, alavancagem_5 = 0,
porte_0 = 0, porte_1 = 0, porte_1.4 = 0, porte_2 = 0, porte_2.4 = 0,
porte_2.8 = 0, porte_3 = 0, porte_3.2 = 0, porte_3.6 = 0,
porte_4 = 0, porte_4.4 = 0, porte_4.6 = 0, porte_4.8 = 0,
porte_5 = 0, receita_recorrencias_0.6 = 0, receita_recorrencias_0.8 = 0,
receita_recorrencias_1 = 0, receita_recorrencias_1.4 = 0,
receita_recorrencias_2 = 0, receita_recorrencias_2.4 = 0,
receita_recorrencias_2.6 = 0, receita_recorrencias_3 = 0,
receita_recorrencias_3.2 = 0, receita_recorrencias_3.4 = 0,
receita_recorrencias_3.8 = 0, receita_recorrencias_4 = 0,
receita_recorrencias_4.4 = 0, receita_recorrencias_5 = 0,
respaldo_patrimonio_0 = 0, respaldo_patrimonio_0.4 = 0, respaldo_patrimonio_0.5 = 0,
respaldo_patrimonio_0.7 = 0, respaldo_patrimonio_0.75 = 0,
respaldo_patrimonio_0.8 = 0, respaldo_patrimonio_1 = 0, respaldo_patrimonio_1.2 = 0,
respaldo_patrimonio_1.3 = 0, respaldo_patrimonio_1.4 = 0,
respaldo_patrimonio_1.5 = 0, respaldo_patrimonio_1.7 = 0,
respaldo_patrimonio_1.9 = 0, respaldo_patrimonio_2.2 = 0,
respaldo_patrimonio_2.3 = 0, respaldo_patrimonio_2.6 = 0,
respaldo_patrimonio_3 = 0, respaldo_patrimonio_3.2 = 0, respaldo_patrimonio_3.5 = 0,
respaldo_patrimonio_3.6 = 0, respaldo_patrimonio_4 = 0, respaldo_patrimonio_4.4 = 0,
respaldo_patrimonio_5 = 0, reputacional_1 = 0, reputacional_2 = 0,
reputacional_2.5 = 0, reputacional_3 = 0, reputacional_3.5 = 0,
reputacional_3.65 = 0, reputacional_4 = 0, reputacional_5 = 0,
impacto_covid_1 = 0, impacto_covid_1.5 = 0, impacto_covid_2 = 0,
impacto_covid_2.5 = 0, impacto_covid_3 = 0, impacto_covid_3.5 = 0,
impacto_covid_3.65 = 0, impacto_covid_4 = 0, impacto_covid_5 = 0,
business_sector_Comercio = 0, business_sector_Industria = 0,
business_sector_Servicos = 0, state_AC = 0, state_AM = 0,
state_BA = 0, state_CE = 0, state_DF = 0, state_GO = 0, state_MG = 0,
state_MS = 0, state_MT = 0, state_PA = 0, state_PB = 0, state_PE = 0,
state_PR = 0, state_RJ = 0, state_RS = 0, state_SC = 0, state_SP = 0,
state_TO = 0, decision_motor_approved = 0, decision_motor_denied = 0), row.names = 1L, class = "data.frame")

toy2

 structure(list(revenue = c(4397487.34, 198019.75), risk = c(12137650.06,
469506.24), target_amount = c(150000, 1e+05), company_years = c(18,
9), approved_commitee = structure(c(2L, 2L), .Label = c("NO",
"YES"), class = "factor"), score = c(134, 128), reason_Compra_equip = c(1,
1), serasa_1.8 = c(1, 1), pontualidade_0.25 = c(1, 1), qualidade_divida_1 = c(1,
1), bancabilidade_0.2 = c(1, 1), alavancagem_1.6 = c(1L, 1L),
    porte_4.6 = c(1, 1), receita_recorrencias_3 = c(1, 1), respaldo_patrimonio_0.5 = c(1,
    1), reputacional_5 = c(1, 1), impacto_covid_3 = c(1, 1),
    business_sector_Comercio = c(1, 1), state_GO = c(1, 1)), row.names = c(10L,
12L), class = "data.frame")

Body:
Check this :

a <- which(names(toy1) %in% names(toy2))
toy1[2,] <- 0
toy1[a] <- toy2

toy1 has only 1 row while toy2 has two. So I added an extra 0 row in toy1.


问:
Read image from Google Cloud storage and send it using Google Cloud function
I'd like to do the following:
Create a Google Cloud Function (http triggered) that simply read an image file from a bucket (Google Cloud Storage) and send it as a response.

I've tried some combinations and I think that it should be something like that:

```<code>'use strict';
const gcs = require('@google-cloud/storage')();

exports.sendImage = function sendImage(req, res) {
    let bucket = gcs.bucket('my-bucket-name');
    let myImage = bucket.file('my-image-file.jpg');

    res.contentType('image/jpeg');
    res.end(myImage, 'binary');
};
</code>```

The function above deploys successfully but when I trigger it just using the url (on browser) it shows no results.

I'm doing that as simple as possible because if it works with one image, I can improve the code to call any image.

My final goal is to have something similar to that showed on this post:
https://medium.com/google-cloud/uploading-resizing-and-serving-images-with-google-cloud-platform-ca9631a2c556

But running on Google Cloud Functions. If I manage to send a simple image, I can use some module such as node-image-resize to the final result.

答:
Thanks for this, it was super helpful and got me on the right track. I wanted to get a file from a bucket using a Firebase cloud function, which is tightly integrated with Google Cloud Storage, and then serve it over https.

I also wanted to first check if the file in the bucket existed and if not, serve a placeholder image I have in the bucket.

After some googling which brought me to the file.exists() method examples I ended up with this:

First

```<code>const functions = require("firebase-functions");
const {initializeApp} = require("firebase-admin/app");
const {getStorage} = require("firebase-admin/storage");
</code>```

Then

```<code>initializeApp({
  storageBucket: "my-bucket-name",
});
</code>```

Then I exported a returnPhoto function to serve the photo via https

```<code>exports.returnPhoto = functions.https.onRequest((req, res) => {
  let file = bucket.file("image_name.jpg");
  file.exists().then(function(data) {
    const exists = data[0];
    if (exists) {
      file.createReadStream()
          .on("error", function() {
            console.log("Error while fetching the requested photo.");
            res.end();
          })
          .pipe(res.setHeader("content-type", "image/jpeg"));
    } else {
      file = bucket.file("notfound_image.jpg");
      file.createReadStream()
          .on("error", function() {
            console.log("Error while fetching notfound_image.jpg");
            res.end();
          })
          .pipe(res.setHeader("content-type", "image/jpeg"));
    }
  });
});
</code>```

Body:
I'd like to do the following:
Create a Google Cloud Function (http triggered) that simply read an image file from a bucket (Google Cloud Storage) and send it as a response.

I've tried some combinations and I think that it should be something like that:

'use strict';
const gcs = require('@google-cloud/storage')();

exports.sendImage = function sendImage(req, res) {
    let bucket = gcs.bucket('my-bucket-name');
    let myImage = bucket.file('my-image-file.jpg');

    res.contentType('image/jpeg');
    res.end(myImage, 'binary');
};

The function above deploys successfully but when I trigger it just using the url (on browser) it shows no results.

I'm doing that as simple as possible because if it works with one image, I can improve the code to call any image.

My final goal is to have something similar to that showed on this post:
https://medium.com/google-cloud/uploading-resizing-and-serving-images-with-google-cloud-platform-ca9631a2c556

But running on Google Cloud Functions. If I manage to send a simple image, I can use some module such as node-image-resize to the final result.

Body:
Thanks for this, it was super helpful and got me on the right track. I wanted to get a file from a bucket using a Firebase cloud function, which is tightly integrated with Google Cloud Storage, and then serve it over https.

I also wanted to first check if the file in the bucket existed and if not, serve a placeholder image I have in the bucket.

After some googling which brought me to the file.exists() method examples I ended up with this:

First

const functions = require("firebase-functions");
const {initializeApp} = require("firebase-admin/app");
const {getStorage} = require("firebase-admin/storage");

Then

initializeApp({
  storageBucket: "my-bucket-name",
});

Then I exported a returnPhoto function to serve the photo via https

exports.returnPhoto = functions.https.onRequest((req, res) => {
  let file = bucket.file("image_name.jpg");
  file.exists().then(function(data) {
    const exists = data[0];
    if (exists) {
      file.createReadStream()
          .on("error", function() {
            console.log("Error while fetching the requested photo.");
            res.end();
          })
          .pipe(res.setHeader("content-type", "image/jpeg"));
    } else {
      file = bucket.file("notfound_image.jpg");
      file.createReadStream()
          .on("error", function() {
            console.log("Error while fetching notfound_image.jpg");
            res.end();
          })
          .pipe(res.setHeader("content-type", "image/jpeg"));
    }
  });
});


问:
Python script to run Django commands
I want to run a python scripts which should do:

Create a django project: django-admin startproject foobar

Create a app in the project: python manage.py barfoo

Add an entry of newly created app barfoo in the setting's INSTALLED_APP.

How can I achieve this?

答:
Read a little abour subprocess and Popen method. This might be what you're looking for.

Popen(["django-admin", "startproject", "%s" % your_name ], stdout=PIPE).communicate()

Popen(["python", "manage.py", "%s" % your_app_name ], stdout=PIPE).communicate()

3.
I know that's not a perfect code, but I'm just giving an idea.

```<code>with open("settings.py", 'r') as file:
    settings = file.readlines()

new_settings = []
for line in settings:
    if "INSTALLED APPS" in line:
        new_settings.append(line.replace("INSTALLED_APPS = (", "INSTALLED_APPS = (\n'%s'," % your_app_name))
    else:
        new_settings.append(line)
with open("settings.py", 'w') as file:
    file.write("".join(new_settings))
</code>```

Title: Python script to run Django commands

Body:
Read a little abour subprocess and Popen method. This might be what you're looking for.

Popen(["django-admin", "startproject", "%s" % your_name ], stdout=PIPE).communicate()

Popen(["python", "manage.py", "%s" % your_app_name ], stdout=PIPE).communicate()

3.
I know that's not a perfect code, but I'm just giving an idea.

with open("settings.py", 'r') as file:
    settings = file.readlines()

new_settings = []
for line in settings:
    if "INSTALLED APPS" in line:
        new_settings.append(line.replace("INSTALLED_APPS = (", "INSTALLED_APPS = (\n'%s'," % your_app_name))
    else:
        new_settings.append(line)
with open("settings.py", 'w') as file:
    file.write("".join(new_settings))


问:
Can I display D3 graphs on .epub?
I'm making a research project about .epub and I've been trying to hack my way into executing JS code into an EPUB and display some kind of data visualization.

Right now, I'm using calibre to create the epub from an HTML file. The HTML file has the code for very simple D3 scatterplots, and it works fine when opening the file from the browser. However, after creating the .epub in calibre, the page is just empty. Do you guys know if this is even possible? I know that EPUB 3 should be somewhat similar to a modern browser, so theoretically anything that can be rendered into a browser should also be possible on a .epub. Is it because I am loading d3.js? Calibre does not provide any kind of feedback.

<!DOCTYPE html>
<meta charset="utf-8">

```

答:
Your sample code generates an SVG. Provided you include the rendered SVG in your EPUB document, you should be fine.

As already mentioned, EPUBs need to be viewable in offline settings. And, the readers' embedded HTML engine is a subset of a mobile/desktop browser which might process basic JavaScript in some cases, but don't expect to do anything complex. Especially since most reading devices have very limited active memory.

For SVG support in EPUB documents, see: https://wiki.mobileread.com/wiki/SVG

Title: Can I display D3 graphs on .epub?


问:
Is AWS Lambda preferred over AWS Glue Job?
In AWS Glue job, we can write some script and execute the script via job.

In AWS Lambda too, we can write the same script and execute the same logic provided in above job.

So, my query is not whats the difference between AWS Glue Job vs AWS Lambda, BUT iam trying to undestand when AWS Glue job should be preferred over AWS Lambda, especially while when both does the same job? If both does the same job, then ideally I would blindly prefer using AWS Lambda itself, right?

Please try to understand my query..

答:
The answer to this can involve some foundational design decisions. What is this job doing? What kind of data are you dealing with? Is there a decision to be made whether the task should be executed in a batch or event oriented paradigm?

Batch

This may be necessary or desirable because the task:

Is being done over large monolithic data (e.g., binary).

Relies on context of multiple records in a dataset such that they must be loaded into a single job.

Order matters.

I feel like just as often I see batch handling chosen by default because "this is the way we've always done it" but breaking from this approach could be worth consideration.

Glue is built for batch operations. With a current maximum execution time of 15 minutes and maximum memory of 10gb, Lambda has become capable of processing fairly large datasets in a single execution, as well. It can be difficult to pin down a direct cost comparison without specifics of the workload. When it comes to development, I feel that Lambda has the edge as far as tooling to build, test, deploy.

Event

In the case where your data consists of a set of records, it might behoove you to parse and "stream" them into Lambda. Consider a flow like:

CSV lands in S3.

S3 event triggers Lambda.

Lambda reads and parses CSV into discrete events, submits to another Lambda or publishes to SNS for downstream processing. Concurrent instances of this Lambda can be employed to speed up ingest, where each instance is responsible for certain lines of the S3 object.

This pushes all logic and error handling, as well as resources required, to the level of individual event/record level. Often mechanisms such as dead-letter queues are employed for remediation. While context of a given container persists across invocations - assuming the container has not been idle and torn down - Lambda should generally be considered stateless such that the processing of an event/record is thought of as occurring within its own scope, outside that of others in the dataset.


问:
Error database connect is not a function Nodejs with Mysql in docker
I have deployed my docker application (to DigitalOcean). Everything work's, but I can't connect mysql with nodejs.

When I run docker-compose up I get error database.connect is not a function.

My server.js file is look like this

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

const database = mysql.createPool({
    host: process.env.MYSQL_HOST_IP,
    user: "db_user",
    password: "db_user_pass",
    database: "guess-game",
    port: 3306,
});

database.connect((err) => {
    if (err) {
        console.error("error connecting: " + err.stack);
        return;
    }
    console.log("connected as id " + db.threadId);
});

module.exports = db;
</code>```

I don't know what I need to write this line to make it work.

```<code>host: process.env.MYSQL_HOST_IP,
</code>```

I tried to add droplet IP as host, but this is also don't work.

```<code>host: "http://46.101.162.111/",
</code>```

Also, I try this.

```<code>host: "46.101.162.111",
</code>```

My docker-compose.yml file

```<code>version: "3"

networks:
  dbnet:

services:
  phpmyadmin:
    image: phpmyadmin/phpmyadmin
    container_name: phpmyadmin1
    environment:
      - PMA_ARBITRARY=1
      - PMA_HOST=db
    restart: always
    links:
      - db
    ports:
      - 8899:80
    depends_on:
      - db
    networks:
      - dbnet

  api:
    build: ./api
    container_name: api1
    command: npm run start
    restart: unless-stopped
    ports:
      - "3005:3005"
    environment:
      - PORT=3005
      - MYSQL_HOST_IP=172.18.0.2
    depends_on:
      - phpmyadmin
    networks:
      - dbnet

  db:
    image: mysql:latest
    container_name: db
    command: --default-authentication-plugin=mysql_native_password
    environment:
      - MYSQL_ROOT_PASSWORD=my_secret_password
      - MYSQL_DATABASE=guess-game
      - MYSQL_USER=db_user
      - MYSQL_PASSWORD=db_user_pass
    restart: always
    ports:
      - 6033:3306
    networks:
      - dbnet
</code>```

Struggling almost 3 days.

答:
You just need to indicate a DB container name instead of IP like this:</p>
```<code>MYSQL_HOST_IP=db
</code>```

Body:
I have deployed my docker application (to DigitalOcean). Everything work's, but I can't connect mysql with nodejs.

When I run docker-compose up I get error database.connect is not a function.

My server.js file is look like this

const mysql = require("mysql");

const database = mysql.createPool({
    host: process.env.MYSQL_HOST_IP,
    user: "db_user",
    password: "db_user_pass",
    database: "guess-game",
    port: 3306,
});

database.connect((err) => {
    if (err) {
        console.error("error connecting: " + err.stack);
        return;
    }
    console.log("connected as id " + db.threadId);
});

module.exports = db;

I don't know what I need to write this line to make it work.

host: process.env.MYSQL_HOST_IP,

I tried to add droplet IP as host, but this is also don't work.

host: "http://46.101.162.111/",

Also, I try this.

host: "46.101.162.111",

My docker-compose.yml file

version: "3"

networks:
  dbnet:

services:
  phpmyadmin:
    image: phpmyadmin/phpmyadmin
    container_name: phpmyadmin1
    environment:
      - PMA_ARBITRARY=1
      - PMA_HOST=db
    restart: always
    links:
      - db
    ports:
      - 8899:80
    depends_on:
      - db
    networks:
      - dbnet

  api:
    build: ./api
    container_name: api1
    command: npm run start
    restart: unless-stopped
    ports:
      - "3005:3005"
    environment:
      - PORT=3005
      - MYSQL_HOST_IP=172.18.0.2
    depends_on:
      - phpmyadmin
    networks:
      - dbnet

  db:
    image: mysql:latest
    container_name: db
    command: --default-authentication-plugin=mysql_native_password
    environment:
      - MYSQL_ROOT_PASSWORD=my_secret_password
      - MYSQL_DATABASE=guess-game
      - MYSQL_USER=db_user
      - MYSQL_PASSWORD=db_user_pass
    restart: always
    ports:
      - 6033:3306
    networks:
      - dbnet

Struggling almost 3 days.

Body:
You just need to indicate a DB container name instead of IP like this:

MYSQL_HOST_IP=db


问:
How to add multiple columns in a MySQL table with PHP form?
I have a table in my database with 2 columns.What I want to do is to let the admin (of the web application ) have the possibility from a simple php/html form to add multiple columns in the table already created.

Thanks.

答:
To add multiple table columns if they don not exist
alter table_name add column IF NOT EXISTS (
<colname1> <datatype> DEFAULT VALUE,
<colname2> <datatype> DEFAULT VALUE,
<colname3> <datatype> DEFAULT VALUE,
<colname4> <datatype> DEFAULT VALUE)