问:
ASP.NET Core Swagger uses incorrect json url when web application is hosted in a subdirectory
I followed these instructions to add swagger to my ASP.NET Core application.

It works fine when I host it as a root website but when I host the app as an alias on an existing website, say myserver.com/myapp, swagger will look for swagger.json at an incorrect URL and report: *Can't read swagger JSON from https://myserver.com/swagger/v1/swagger.json. It should instead use https://myserver.com/myapp/swagger/v1/swagger.json.

The message I get is:

Can't read swagger JSON from https://myserver.com/swagger/v1/swagger.json

How can I configure swashbuckle/swagger to use the application base path and look for the swagger.json file at the right place?

I'm hosting on IIS.

The version of swashbuckle is:

```<code>"Swashbuckle": "6.0.0-beta902"
</code>```

I suspect that I'll have to add something to the app.UseSwaggerUi() in the Configure method in Startup.cs but I'm not sure what.

Startup Configure:

```<code>public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
    loggerFactory.AddConsole(Configuration.GetSection("Logging"));
    loggerFactory.AddDebug();

    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
        app.UseBrowserLink();
    }
    else
    {
        app.UseExceptionHandler("/Home/Error");
    }

    app.UseStaticFiles();

    app.UseMvc(routes =>
    {
        routes.MapRoute(
            name: "default",
            template: "{controller=Home}/{action=Index}/{id?}");
    });

    // Enable middleware to serve generated Swagger as a JSON endpoint
    app.UseSwagger();

    // Enable middleware to serve swagger-ui assets (HTML, JS, CSS etc.)
    app.UseSwaggerUi();
}
</code>```

答:
You can use the ASPNETCORE_APPL_PATH environment variable to get the application basepath.</p>

```<code>app.UseSwaggerUI(c =>
{
    string basePath = Environment.GetEnvironmentVariable("ASPNETCORE_APPL_PATH");
    if (basePath == null) basePath = "/";
    c.SwaggerEndpoint($"{basePath}swagger/v1/swagger.json", "My API");
});
</code>```

Body:
I followed these instructions to add swagger to my ASP.NET Core application.

It works fine when I host it as a root website but when I host the app as an alias on an existing website, say myserver.com/myapp, swagger will look for swagger.json at an incorrect URL and report: *Can't read swagger JSON from https://myserver.com/swagger/v1/swagger.json. It should instead use https://myserver.com/myapp/swagger/v1/swagger.json.

The message I get is:

Can't read swagger JSON from https://myserver.com/swagger/v1/swagger.json

How can I configure swashbuckle/swagger to use the application base path and look for the swagger.json file at the right place?

I'm hosting on IIS.

The version of swashbuckle is:

"Swashbuckle": "6.0.0-beta902"

I suspect that I'll have to add something to the app.UseSwaggerUi() in the Configure method in Startup.cs but I'm not sure what.

Startup Configure:

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
    loggerFactory.AddConsole(Configuration.GetSection("Logging"));
    loggerFactory.AddDebug();

    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
        app.UseBrowserLink();
    }
    else
    {
        app.UseExceptionHandler("/Home/Error");
    }

    app.UseStaticFiles();

    app.UseMvc(routes =>
    {
        routes.MapRoute(
            name: "default",
            template: "{controller=Home}/{action=Index}/{id?}");
    });

    // Enable middleware to serve generated Swagger as a JSON endpoint
    app.UseSwagger();

    // Enable middleware to serve swagger-ui assets (HTML, JS, CSS etc.)
    app.UseSwaggerUi();
}

Body:
You can use the ASPNETCORE_APPL_PATH environment variable to get the application basepath.

app.UseSwaggerUI(c =>
{
    string basePath = Environment.GetEnvironmentVariable("ASPNETCORE_APPL_PATH");
    if (basePath == null) basePath = "/";
    c.SwaggerEndpoint($"{basePath}swagger/v1/swagger.json", "My API");
});


来源: stackexchange

问:
how to fix slow loading actions in asp.net mvc on azure web apps
We have notice a huge performance impact on our asp.net mvc application since we moved to azure web apps. One thing we've noticed is that request times slow down significantly when an action is loaded the first time in a couple hours. Our app is not used a lot so there's a lot of idle time. I'll give a few examples (please note these are just back-end request response times, and exclude dom, js, image, etc. load times):

user dashboard - first request will take around 20 seconds. Subsequent loads are around 1 second

loading some object - first request will be around 7 seconds. refreshing will get you around 2 secs. loading other objects using same action is also faster after that action is hit the first time

I realize that some of the speed up might be due to query caching, but I am wondering if that's all. I am on a standard plan and do have "Always On" enabled, so I know that's not the issue.  And this seems to be happening per action. So even if the user visited action1 already and now visits action2 for the first time, they'll still experience slowness.

What can I look for here to fix? Are there any azure specific settings?

答:
Please run your query as shown below:

`--your query goes here

go

select * from sys.dm_exec_session_wait_stats
  where session_id = @@spid
  order by wait_time_ms desc `

The last SELECT statement will provide us the cause it takes so much time to run the first time.

It could be poor IO performance on large queries running on lower tiers.

Hope this helps.

ContentLicense: CC BY-SA 3.0


问:
how to retrieve exact text width for RenderText in Graphics32
I think my question is clear enough, but I explain more. Simply, when we are using AntiAlias on RenderText procedure, the value gotten within TextWidth function is not correct. What can I do to get the right text width?</p>

答:
You can look for the algorithm in their own code. They must also calculate it. Anyway this is how I do it.

```<code>function TGR32Canvas.TextWidth(const Text: string): Integer;
var
  TempFont: TFont;
  TempWidth: Integer;
begin
  if Text <> '' then
  begin
    TempFont := TFont.Create;
    try
      TempFont.Assign(Font);
      TempFont.Size := Font.Size shl AA_MODE;
      TempWidth := GetTextWidth(Text, TempFont);
    finally
      TempFont.Free;
    end;
  end
  else
    TempWidth := 0;

  TempWidth := (TempWidth shr AA_MODE + 1) shl AA_MODE;
  Result := TempWidth shr AA_MODE;
end;
</code>```

The GetTextWidth function is simple. You can do it differently.

```<code>function GetTextWidth(const Text: string; const Font: TFont): Integer;
var
  Canvas: TCanvas;
begin
  Canvas := TCanvas.Create;
  try
    Canvas.Handle := GetDC(0);
    try
      Canvas.Font.Assign(Font);
      Result := Canvas.TextWidth(Text);
    finally
      ReleaseDC(0, Canvas.Handle);
    end;
  finally
    Canvas.Free;
  end;
end;
</code>```

Body:
You can look for the algorithm in their own code. They must also calculate it. Anyway this is how I do it.

function TGR32Canvas.TextWidth(const Text: string): Integer;
var
  TempFont: TFont;
  TempWidth: Integer;
begin
  if Text <> '' then
  begin
    TempFont := TFont.Create;
    try
      TempFont.Assign(Font);
      TempFont.Size := Font.Size shl AA_MODE;
      TempWidth := GetTextWidth(Text, TempFont);
    finally
      TempFont.Free;
    end;
  end
  else
    TempWidth := 0;

  TempWidth := (TempWidth shr AA_MODE + 1) shl AA_MODE;
  Result := TempWidth shr AA_MODE;
end;

The GetTextWidth function is simple. You can do it differently.

function GetTextWidth(const Text: string; const Font: TFont): Integer;
var
  Canvas: TCanvas;
begin
  Canvas := TCanvas.Create;
  try
    Canvas.Handle := GetDC(0);
    try
      Canvas.Font.Assign(Font);
      Result := Canvas.TextWidth(Text);
    finally
      ReleaseDC(0, Canvas.Handle);
    end;
  finally
    Canvas.Free;
  end;
end;

ContentLicense: CC BY-SA 2.5


问:
In sql how to find max from the columns
Suppose in a table I have 5 columns (a,b,c,d,e) each an integer value and this table has 100 of rows how can we find the maximum from the sum of each column and the column name by sql?That is max(sum(a),sum(b),sum(c),sum(d),sum(e)) and columnname</p>

答:
In many databases, you can use greatest():

```<code>select greatest(sum(a), sum(b), sum(c), sum(d), sum(e))
from t;
</code>```

In databases that don't have this function, you can use case or unpivot and reaggregate:

```<code>select sum(val)
from ((select a as val, 'a' as which from t) union all
      (select b as val, 'b' as which from t) union all
      (select c as val, 'c' as which from t) union all
      (select d as val, 'd' as which from t) union all
      (select e as val, 'e' as which from t)
     ) abcde
group by which
order by sum(val) desc
fetch first 1 row only;
</code>```

This is ANSI syntax.  Some databases use TOP or LIMIT instead of FETCH FIRST.

Title: In sql how to find max from the columns

Body:
In many databases, you can use greatest():

select greatest(sum(a), sum(b), sum(c), sum(d), sum(e))
from t;

In databases that don't have this function, you can use case or unpivot and reaggregate:

select sum(val)
from ((select a as val, 'a' as which from t) union all
      (select b as val, 'b' as which from t) union all
      (select c as val, 'c' as which from t) union all
      (select d as val, 'd' as which from t) union all
      (select e as val, 'e' as which from t)
     ) abcde
group by which
order by sum(val) desc
fetch first 1 row only;

This is ANSI syntax.  Some databases use TOP or LIMIT instead of FETCH FIRST.


问:
How to split a Thai sentence, which does not use spaces, into words?
How to split word from Thai sentence? English we can split word by space.

Example: I go to school, split = ['I', 'go', 'to' ,'school']  Split by looking only space.

But Thai language had no space, so I don't know how to do.
Example spit ฉันจะไปโรงเรียน to from txt file to ['ฉัน' 'จะ' 'ไป' 'โรง' 'เรียน'] = output another txt file.

Are there any programs or libraries that identify Thai word boundaries and split?

答:
There are multiple ways to do 'Thai words tokenization'. One way is to use dictionary-based or pattern-based. In this case, the algorithm will go through characters and if it appears in the dictionary, we'll count as a word.

Also, there are also recent libraries to tokenize Thai text where it trained Deep learning to tokenize Thai word on BEST corpus including rkcosmos/deepcut,  pucktada/cutkum and more.

Example usage of deepcut:

```<code>import deepcut
deepcut.tokenize('ฉันจะไปโรงเรียน')
# output as ['ฉัน', 'จะ', 'ไป', 'โรง', 'เรียน']
</code>```

Body:
There are multiple ways to do 'Thai words tokenization'. One way is to use dictionary-based or pattern-based. In this case, the algorithm will go through characters and if it appears in the dictionary, we'll count as a word.

Also, there are also recent libraries to tokenize Thai text where it trained Deep learning to tokenize Thai word on BEST corpus including rkcosmos/deepcut,  pucktada/cutkum and more.

Example usage of deepcut:

import deepcut
deepcut.tokenize('ฉันจะไปโรงเรียน')
# output as ['ฉัน', 'จะ', 'ไป', 'โรง', 'เรียน']


问:
C# Update or insert from a List by some criteria
I have 2 lists, both with a different number of items, both with 1 parameter in common that I have to compare. If the value of the parameter is the same I have to update the DB, but if the item in a list doesn't have an item in the second list, I have to insert it into the DB.

This is what I was trying:

foreach (var rep in prodrep)
{
    foreach (var crm in prodcrm)
    {
        if (rep.VEHI_SERIE.Equals(crm.VEHI_SERIE))
        {
            updateRecord(rep.Data);

        }
        else
        {
            insertRecords(rep.Data);
        }
    }
}
```

The first problem with this is that it is very slow. The second problem is that obviously the insert statement would't work, but I don't want to do another for each inside a foreach to verify if it doesn't exist, because that would take double the time.

How can I make this more efficient?

答:
This is now not as efficient but this should work.</p>

```<code>var existing = prodrep.Where(rep => prodcrm.Any(crm => rep.VEHI_SERIE.Equals(crm.VEHI_SERIE)).Select(rep=> Rep = rep, Crm=prodcrm.FirstOrDefault(crm=>rep.VEHI_SERIE.Equals(crm.VEHI_SERIE));

existing.ForEach(mix=>updateRecord(mix.Rep.Data, mix.Crm.Id));

prodrep.Where(rep => !existing.Any(mix=>mix.Rep==rep)).ForEach(rep=>insertRecords(rep.Data));
</code>```

Body:
I have 2 lists, both with a different number of items, both with 1 parameter in common that I have to compare. If the value of the parameter is the same I have to update the DB, but if the item in a list doesn't have an item in the second list, I have to insert it into the DB.

This is what I was trying:

foreach (var rep in prodrep)
{
    foreach (var crm in prodcrm)
    {
        if (rep.VEHI_SERIE.Equals(crm.VEHI_SERIE))
        {
            updateRecord(rep.Data);

        }
        else
        {
            insertRecords(rep.Data);
        }
    }
}

The first problem with this is that it is very slow. The second problem is that obviously the insert statement would't work, but I don't want to do another for each inside a foreach to verify if it doesn't exist, because that would take double the time.

How can I make this more efficient?

Body:
This is now not as efficient but this should work.

var existing = prodrep.Where(rep => prodcrm.Any(crm => rep.VEHI_SERIE.Equals(crm.VEHI_SERIE)).Select(rep=> Rep = rep, Crm=prodcrm.FirstOrDefault(crm=>rep.VEHI_SERIE.Equals(crm.VEHI_SERIE));

existing.ForEach(mix=>updateRecord(mix.Rep.Data, mix.Crm.Id));

prodrep.Where(rep => !existing.Any(mix=>mix.Rep==rep)).ForEach(rep=>insertRecords(rep.Data));


问:
Load user session with spring security
I'm developing a web app that will be used inside Cisco Jabber as a Custom Tab.

In my app the user needs to be logged in. The first authentication is done using Spring SAML (SSO). if this authentication fail then the user fallback to one of those auth process :

- A: directly with his userid (not a real auth but needed for some client)

- B: a login form (auth against client database)

The problem is that some actions are creating popups and with Jabber those popup are opened in Internet Explorer which doesn't have any information concerning my user and thus my app tries to authenticate him again. If SSO works no problem no action required by the user, if that fails auth A works fine but if auth B is selected then I have an issue because I need the user to be authenticated without him entering his credentials.

Is there a way with Spring, Spring Security to copy the session from Jabber to IE skipping the log-in page?

I followed the advice here and tried to set the jsessionid as parameter of my popup url like this:

```<code>var logUrl = 'login.do' + (this.user === '' ? ';jsessionid=' + sessionId : '?userId=' + this.user);
var w = window.open(logUrl, number, 'width=800,height=600,resizeable=yes,scrollbars=yes,toolbar=no,location=yes,status=yes,menubar=yes');
</code>```

The problem is that when the user open the popup, the jsessionid in the url is not the same as the one in Jabber. And if I try to log in with the JSESSIONID of the user in Jabber it doesn't work.

Is there some configuration parameter I haven't set for this to work?

答:
The session is tracked using the JSESSIONID cookie so you could pass this as a URL parameter on referral.

However, there are security concerns around session hijacking to consider with this approach.

For example, you must use SSL/HTTPS.

See this answer for more information.

Title: Load user session with spring security

Body:
I'm developing a web app that will be used inside Cisco Jabber as a Custom Tab.

In my app the user needs to be logged in. The first authentication is done using Spring SAML (SSO). if this authentication fail then the user fallback to one of those auth process :

- A: directly with his userid (not a real auth but needed for some client)

- B: a login form (auth against client database)

The problem is that some actions are creating popups and with Jabber those popup are opened in Internet Explorer which doesn't have any information concerning my user and thus my app tries to authenticate him again. If SSO works no problem no action required by the user, if that fails auth A works fine but if auth B is selected then I have an issue because I need the user to be authenticated without him entering his credentials.

Is there a way with Spring, Spring Security to copy the session from Jabber to IE skipping the log-in page?

I followed the advice here and tried to set the jsessionid as parameter of my popup url like this:

var logUrl = 'login.do' + (this.user === '' ? ';jsessionid=' + sessionId : '?userId=' + this.user);
var w = window.open(logUrl, number, 'width=800,height=600,resizeable=yes,scrollbars=yes,toolbar=no,location=yes,status=yes,menubar=yes');

The problem is that when the user open the popup, the jsessionid in the url is not the same as the one in Jabber. And if I try to log in with the JSESSIONID of the user in Jabber it doesn't work.

Is there some configuration parameter I haven't set for this to work?


问:
xsl fo render Empty Table Structure when no Data is available in table Body
I am using XSL FO to transform XML data from a file into Tables rendered as PDF document. I am being asked to render empty table structure if no data came in the XML - leaving the table body empty.

I tried the below code

```<code>        <!-- Addresses -->
            <fo:table border="1px solid black" table-layout="fixed" width="100%">
            <fo:table-column column-width="2in"/>
            <fo:table-column column-width="2in"/>
            <fo:table-column column-width="2.5in"/>
            <fo:table-column column-width="2.5in"/>
            <fo:table-column column-width="2in"/>
            <fo:table-header>
                <fo:table-row>
                    <fo:table-cell border="0.1pt solid black" text-align="left" font-size="12pt" font-weight="bold" number-columns-spanned="5" background-color= "#B6B6B4"><fo:block>Addresses</fo:block></fo:table-cell>
                </fo:table-row>
                        <fo:table-row>
                        <fo:table-cell border="0.1pt solid black" text-align="left" font-size="10pt" font-weight="bold">
                                <fo:block> Address Type </fo:block>
                            </fo:table-cell>
                            <fo:table-cell border="0.1pt solid black" text-align="left" font-size="10pt" font-weight="bold">
                                <fo:block> Fields</fo:block>
                            </fo:table-cell>
                            <fo:table-cell border="0.1pt solid black" text-align="left" font-size="10pt" font-weight="bold">
                                <fo:block> Values </fo:block>
                            </fo:table-cell>
                            <fo:table-cell border="0.1pt solid black" text-align="left" font-size="10pt" font-weight="bold">
                                <fo:block> Data Source</fo:block>
                            </fo:table-cell>
                            <fo:table-cell border="0.1pt solid black" text-align="left" font-size="10pt" font-weight="bold">
                                <fo:block> DMC Doc Link</fo:block>
                            </fo:table-cell>
                        </fo:table-row>
                    </fo:table-header>
                    <fo:table-body>

                        <xsl:if test="core/clientMembers/address">
                            <xsl:apply-templates select="core/clientMembers/address"/>
                        </xsl:if>
                        <xsl:if test="not(core/clientMembers/address)">
                            <fo:table-row>
                            <fo:table-cell border="0.1pt solid black" text-align="left" font-size="9pt"><fo:block>Primary Address</fo:block></fo:table-cell>
                            <fo:table-cell border="0.1pt solid black"><fo:block white-space-treatment="preserve"><fo:leader /></fo:block></fo:table-cell>
                            <fo:table-cell border="0.1pt solid black"><fo:block white-space-treatment="preserve"><fo:leader /></fo:block></fo:table-cell>
                            <fo:table-cell border="0.1pt solid black"><fo:block white-space-treatment="preserve"><fo:leader /></fo:block></fo:table-cell>
                            <fo:table-cell border="0.1pt solid black"><fo:block white-space-treatment="preserve"><fo:leader /></fo:block></fo:table-cell>
                         </fo:table-row>
                         <fo:table-row>
                            <fo:table-cell border="0.1pt solid black" text-align="left" font-size="9pt"><fo:block>Incorporated Address</fo:block></fo:table-cell>
                            <fo:table-cell border="0.1pt solid black"><fo:block white-space-treatment="preserve"><fo:leader /></fo:block></fo:table-cell>
                            <fo:table-cell border="0.1pt solid black"><fo:block white-space-treatment="preserve"><fo:leader /></fo:block></fo:table-cell>
                            <fo:table-cell border="0.1pt solid black"><fo:block white-space-treatment="preserve"><fo:leader /></fo:block></fo:table-cell>
                            <fo:table-cell border="0.1pt solid black"><fo:block white-space-treatment="preserve"><fo:leader /></fo:block></fo:table-cell>
                            </fo:table-row>
                            <fo:table-row>
                            <fo:table-cell border="0.1pt solid black" text-align="left" font-size="9pt"><fo:block>Registered Address</fo:block></fo:table-cell>
                            <fo:table-cell border="0.1pt solid black"><fo:block white-space-treatment="preserve"><fo:leader /></fo:block></fo:table-cell>
                            <fo:table-cell border="0.1pt solid black"><fo:block white-space-treatment="preserve"><fo:leader /></fo:block></fo:table-cell>
                            <fo:table-cell border="0.1pt solid black"><fo:block white-space-treatment="preserve"><fo:leader /></fo:block></fo:table-cell>
                            <fo:table-cell border="0.1pt solid black"><fo:block white-space-treatment="preserve"><fo:leader /></fo:block></fo:table-cell>
                            </fo:table-row>
                            <fo:table-row>
                            <fo:table-cell border="0.1pt solid black" text-align="left" font-size="9pt"><fo:block>Mailing Address</fo:block></fo:table-cell>
                            <fo:table-cell border="0.1pt solid black"><fo:block white-space-treatment="preserve"><fo:leader /></fo:block></fo:table-cell>
                            <fo:table-cell border="0.1pt solid black"><fo:block white-space-treatment="preserve"><fo:leader /></fo:block></fo:table-cell>
                            <fo:table-cell border="0.1pt solid black"><fo:block white-space-treatment="preserve"><fo:leader /></fo:block></fo:table-cell>
                            <fo:table-cell border="0.1pt solid black"><fo:block white-space-treatment="preserve"><fo:leader /></fo:block></fo:table-cell>
                            </fo:table-row>
                        </xsl:if>
                    </fo:table-body>
                </fo:table>
</code>```

However this piece of code is not working as expected.
Could the experts here pls pls pls advise if there is a way to achieve the desired behavior in XSL FO ???
"core/clientMain/coverage" is xsl template .

答:
It is a bit unclear what you mean by "leaving the table body empty" given the code you're presenting.  Certainly I can believe that it doesn't do what you want in the event that the XPath expression core/clientMain/coverage evaluates to an empty node set, for then it will produce inside the <fo:table-body> element a single <fo:table-cell> child element, without any intervening <fo:table-row>.

I could see you wanting to produce a row of empty cells (apparently five of them to match the five headings) or, alternatively, no row at all, but what you've presented doesn't make sense.

The no row at all case is easy: simply omit the second xsl:if element and its contents, leaving just

```<code>                        <xsl:if test="core/clientMain/coverage">
                            <xsl:apply-templates select="core/clientMain/coverage"/>
                        </xsl:if>
</code>```

(I presume that that part works as intended when in fact there is data.)

If in fact you want to provide an empty data row, then provide it!  Details depend on your specific needs, but it might look like this:

```<code>                    <xsl:if test="core/clientMain/coverage">
                        <xsl:apply-templates select="core/clientMain/coverage"/>
                    </xsl:if>
                    <xsl:if test="not(core/clientMain/coverage)">
                      <fo:table-row>
                        <fo:table-cell><fo:block white-space-treatment="preserve"><fo:leader /></fo:block></fo:table-cell>
                        <fo:table-cell><fo:block white-space-treatment="preserve"><fo:leader /></fo:block></fo:table-cell>
                        <fo:table-cell><fo:block white-space-treatment="preserve"><fo:leader /></fo:block></fo:table-cell>
                        <fo:table-cell><fo:block white-space-treatment="preserve"><fo:leader /></fo:block></fo:table-cell>
                        <fo:table-cell><fo:block white-space-treatment="preserve"><fo:leader /></fo:block></fo:table-cell>
                      </fo:table-row>
                    </xsl:if>
</code>```

Body:
I am using XSL FO to transform XML data from a file into Tables rendered as PDF document. I am being asked to render empty table structure if no data came in the XML - leaving the table body empty.

I tried the below code

            <fo:table border="1px solid black" table-layout="fixed" width="100%">
            <fo:table-column column-width="2in"/>
            <fo:table-column column-width="2in"/>
            <fo:table-column column-width="2.5in"/>
            <fo:table-column column-width="2.5in"/>
            <fo:table-column column-width="2in"/>
            <fo:table-header>
                <fo:table-row>
                    <fo:table-cell border="0.1pt solid black" text-align="left" font-size="12pt" font-weight="bold" number-columns-spanned="5" background-color= "#B6B6B4"><fo:block>Addresses</fo:block></fo:table-cell>
                </fo:table-row>
                        <fo:table-row>
                        <fo:table-cell border="0.1pt solid black" text-align="left" font-size="10pt" font-weight="bold">
                                <fo:block> Address Type </fo:block>
                            </fo:table-cell>
                            <fo:table-cell border="0.1pt solid black" text-align="left" font-size="10pt" font-weight="bold">
                                <fo:block> Fields</fo:block>
                            </fo:table-cell>
                            <fo:table-cell border="0.1pt solid black" text-align="left" font-size="10pt" font-weight="bold">
                                <fo:block> Values </fo:block>
                            </fo:table-cell>
                            <fo:table-cell border="0.1pt solid black" text-align="left" font-size="10pt" font-weight="bold">
                                <fo:block> Data Source</fo:block>
                            </fo:table-cell>
                            <fo:table-cell border="0.1pt solid black" text-align="left" font-size="10pt" font-weight="bold">
                                <fo:block> DMC Doc Link</fo:block>
                            </fo:table-cell>
                        </fo:table-row>
                    </fo:table-header>
                    <fo:table-body>

                        <xsl:if test="core/clientMembers/address">
                            <xsl:apply-templates select="core/clientMembers/address"/>
                        </xsl:if>
                        <xsl:if test="not(core/clientMembers/address)">
                            <fo:table-row>
                            <fo:table-cell border="0.1pt solid black" text-align="left" font-size="9pt"><fo:block>Primary Address</fo:block></fo:table-cell>
                            <fo:table-cell border="0.1pt solid black"><fo:block white-space-treatment="preserve"><fo:leader /></fo:block></fo:table-cell>
                            <fo:table-cell border="0.1pt solid black"><fo:block white-space-treatment="preserve"><fo:leader /></fo:block></fo:table-cell>
                            <fo:table-cell border="0.1pt solid black"><fo:block white-space-treatment="preserve"><fo:leader /></fo:block></fo:table-cell>
                            <fo:table-cell border="0.1pt solid black"><fo:block white-space-treatment="preserve"><fo:leader /></fo:block></fo:table-cell>
                         </fo:table-row>
                         <fo:table-row>
                            <fo:table-cell border="0.1pt solid black" text-align="left" font-size="9pt"><fo:block>Incorporated Address</fo:block></fo:table-cell>
                            <fo:table-cell border="0.1pt solid black"><fo:block white-space-treatment="preserve"><fo:leader /></fo:block></fo:table-cell>
                            <fo:table-cell border="0.1pt solid black"><fo:block white-space-treatment="preserve"><fo:leader /></fo:block></fo:table-cell>
                            <fo:table-cell border="0.1pt solid black"><fo:block white-space-treatment="preserve"><fo:leader /></fo:block></fo:table-cell>
                            <fo:table-cell border="0.1pt solid black"><fo:block white-space-treatment="preserve"><fo:leader /></fo:block></fo:table-cell>
                            </fo:table-row>
                            <fo:table-row>
                            <fo:table-cell border="0.1pt solid black" text-align="left" font-size="9pt"><fo:block>Registered Address</fo:block></fo:table-cell>
                            <fo:table-cell border="0.1pt solid black"><fo:block white-space-treatment="preserve"><fo:leader /></fo:block></fo:table-cell>
                            <fo:table-cell border="0.1pt solid black"><fo:block white-space-treatment="preserve"><fo:leader /></fo:block></fo:table-cell>
                            <fo:table-cell border="0.1pt solid black"><fo:block white-space-treatment="preserve"><fo:leader /></fo:block></fo:table-cell>
                            <fo:table-cell border="0.1pt solid black"><fo:block white-space-treatment="preserve"><fo:leader /></fo:block></fo:table-cell>
                            </fo:table-row>
                            <fo:table-row>
                            <fo:table-cell border="0.1pt solid black" text-align="left" font-size="9pt"><fo:block>Mailing Address</fo:block></fo:table-cell>
                            <fo:table-cell border="0.1pt solid black"><fo:block white-space-treatment="preserve"><fo:leader /></fo:block></fo:table-cell>
                            <fo:table-cell border="0.1pt solid black"><fo:block white-space-treatment="preserve"><fo:leader /></fo:block></fo:table-cell>
                            <fo:table-cell border="0.1pt solid black"><fo:block white-space-treatment="preserve"><fo:leader /></fo:block></fo:table-cell>
                            <fo:table-cell border="0.1pt solid black"><fo:block white-space-treatment="preserve"><fo:leader /></fo:block></fo:table-cell>
                            </fo:table-row>
                        </xsl:if>
                    </fo:table-body>
                </fo:table>

However this piece of code is not working as expected.
Could the experts here pls pls pls advise if there is a way to achieve the desired behavior in XSL FO ???
"core/clientMain/coverage" is xsl template .

Body:
It is a bit unclear what you mean by "leaving the table body empty" given the code you're presenting.  Certainly I can believe that it doesn't do what you want in the event that the XPath expression core/clientMain/coverage evaluates to an empty node set, for then it will produce inside the <fo:table-body> element a single <fo:table-cell> child element, without any intervening <fo:table-row>.

I could see you wanting to produce a row of empty cells (apparently five of them to match the five headings) or, alternatively, no row at all, but what you've presented doesn't make sense.

The no row at all case is easy: simply omit the second xsl:if element and its contents, leaving just

                        <xsl:if test="core/clientMain/coverage">
                            <xsl:apply-templates select="core/clientMain/coverage"/>
                        </xsl:if>

(I presume that that part works as intended when in fact there is data.)

If in fact you want to provide an empty data row, then provide it!  Details depend on your specific needs, but it might look like this:

                    <xsl:if test="core/clientMain/coverage">
                        <xsl:apply-templates select="core/clientMain/coverage"/>
                    </xsl:if>
                    <xsl:if test="not(core/clientMain/coverage)">
                      <fo:table-row>
                        <fo:table-cell><fo:block white-space-treatment="preserve"><fo:leader /></fo:block></fo:table-cell>
                        <fo:table-cell><fo:block white-space-treatment="preserve"><fo:leader /></fo:block></fo:table-cell>
                        <fo:table-cell><fo:block white-space-treatment="preserve"><fo:leader /></fo:block></fo:table-cell>
                        <fo:table-cell><fo:block white-space-treatment="preserve"><fo:leader /></fo:block></fo:table-cell>
                        <fo:table-cell><fo:block white-space-treatment="preserve"><fo:leader /></fo:block></fo:table-cell>
                      </fo:table-row>
                    </xsl:if>


问:
Bootstrap button drop-down inside responsive table not visible because of scroll
I have a problem with drop-down buttons inside tables when are responsive and scroll active because the drop-down is not visible because of overflow: auto; property. How can I fix that in order to show drop-down option of button when this is collapsed? I can use some jQuery but after I have problems with scroll left-right so I decided to find another solution.
I have attached a photo to understand better.

Here is a small js fiddle:

答:
This could be useful for someone else. I'm using DatatablesJS. I add 500px to the current height of the table. I do this because Datatables allow you to use 10, 20, etc pages in your table. So I need to calculate dinamically the table's height.

When dropdown is shown, I add extra height.

When dropdown is hiden, I reset original table's height.

```<code>$(document).ready(function() {
    $('.table-responsive .dropdown').on('shown.bs.dropdown', function () {
          console.log($('#table-responsive-cliente').height() + 500)
          $("#table-responsive-cliente").css("height",$('#table-responsive-cliente').height() + 500 );
    })

    $('.table-responsive .dropdown').on('hide.bs.dropdown', function () {
           $("#table-responsive-cliente").css("height","auto");
    })
})
</code>```

And the HTML

```<code><div class="table-responsive" id="table-responsive-cliente">
    <table class="table-striped table-hover">
     ....

     ....
    </table>
</div>
</code>```

Before:

After dropdown is shown:

Body:
This could be useful for someone else. I'm using DatatablesJS. I add 500px to the current height of the table. I do this because Datatables allow you to use 10, 20, etc pages in your table. So I need to calculate dinamically the table's height.

When dropdown is shown, I add extra height.

When dropdown is hiden, I reset original table's height.

$(document).ready(function() {
    $('.table-responsive .dropdown').on('shown.bs.dropdown', function () {
          console.log($('#table-responsive-cliente').height() + 500)
          $("#table-responsive-cliente").css("height",$('#table-responsive-cliente').height() + 500 );
    })

    $('.table-responsive .dropdown').on('hide.bs.dropdown', function () {
           $("#table-responsive-cliente").css("height","auto");
    })
})

And the HTML

<div class="table-responsive" id="table-responsive-cliente">
    <table class="table-striped table-hover">
     ....

     ....
    </table>
</div>

Before:

After dropdown is shown:


问:
Remove a specific item from a list by iterating
I want to remove specific items from python list by iterating and checking if it meet some requirements. At first, I just operate on a list of customized class objects, but it actually meet some errors, and I experiment on a python list of primitive type int, just to find strange result!

Here is some code excerpts:

```<code>>>> a=[1,2,3,4,5]
>>> for i in a:
...     a.remove(i)
...
>>> a
[2, 4]
</code>```

I expect the a should be [] after the loop, but it proves to be [2,4], I wonder why actually. I found a related question in Remove items from a list while iterating, but it only gives a solution on how to remove specific items, not concerning the mechanism actually. I really want to know the reason of this strange result.

答:
lets try to print the values of i and a while iterating.

```<code>for i in a:
     print i, a
     a.remove(i)
</code>```

the output will be:

```<code>1 [1, 2, 3, 4, 5]
3 [2, 3, 4, 5]
5 [2, 4, 5]
</code>```

so when you remove an element, the indices will change, so while value at index 1 was 2 earlier, now it is 3. This will be the value of i.

Body:
I want to remove specific items from python list by iterating and checking if it meet some requirements. At first, I just operate on a list of customized class objects, but it actually meet some errors, and I experiment on a python list of primitive type int, just to find strange result!

Here is some code excerpts:

>>> a=[1,2,3,4,5]
>>> for i in a:
...     a.remove(i)
...
>>> a
[2, 4]

I expect the a should be [] after the loop, but it proves to be [2,4], I wonder why actually. I found a related question in Remove items from a list while iterating, but it only gives a solution on how to remove specific items, not concerning the mechanism actually. I really want to know the reason of this strange result.

Body:
lets try to print the values of i and a while iterating.

for i in a:
     print i, a
     a.remove(i)

the output will be:

1 [1, 2, 3, 4, 5]
3 [2, 3, 4, 5]
5 [2, 4, 5]

so when you remove an element, the indices will change, so while value at index 1 was 2 earlier, now it is 3. This will be the value of i.


问:
How do I embed javascript in clojure Hiccup?
I'm writing a webserver app in clojure with Hiccup (and other things).
I'm trying to have a check-box enable and disable two drop-down fields with a little JS but I can't make it work.</p>

```<code>[:head
[:script "function toggleText(cb, t1, t2) {
    document.getElementById(t1).disabled = !cb.checked;
    document.getElementById(t2).disabled = !cb.checked;
}"]]

[:td (hf/check-box {:on-change (str "toggleText(" (name endtag) "," (name tytag) "," (name tmtag) ")")} endtag)]
[:td (hf/drop-down tytag (range 2013 2031) 2017)]
[:td (hf/drop-down tmtag (range 1 13) 6)]
</code>```

答:
on-change is a React handler and won't work in server-side HTML.

If you don't want to create a separate JS file, you can use the onclick attribute: the below should work (provided that the hf/check-box function creates an element with the given properties):

```<code>[:td (hf/check-box
      {:onclick (str "toggleText(" (name endtag) ","
                     (name tytag) "," (name tmtag) ")")}
      endtag)]
</code>```

Body:
I'm writing a webserver app in clojure with Hiccup (and other things).
I'm trying to have a check-box enable and disable two drop-down fields with a little JS but I can't make it work.

[:head
[:script "function toggleText(cb, t1, t2) {
    document.getElementById(t1).disabled = !cb.checked;
    document.getElementById(t2).disabled = !cb.checked;
}"]]

[:td (hf/check-box {:on-change (str "toggleText(" (name endtag) "," (name tytag) "," (name tmtag) ")")} endtag)]
[:td (hf/drop-down tytag (range 2013 2031) 2017)]
[:td (hf/drop-down tmtag (range 1 13) 6)]

Body:
on-change is a React handler and won't work in server-side HTML.

If you don't want to create a separate JS file, you can use the onclick attribute: the below should work (provided that the hf/check-box function creates an element with the given properties):

[:td (hf/check-box
      {:onclick (str "toggleText(" (name endtag) ","
                     (name tytag) "," (name tmtag) ")")}
      endtag)]


问:
Ubuntu install IntelliJIDEA (running environment of Spark)
Ubuntu install IntelliJIDEA at the command line. The problem is：
Startup Error:Unable to detect graphics environment.</p>

答: I found that this seems to be an issue when I run intellij using sudo and it can't access the $DISPLAY environment variable. You can work around it by using sudo -E.


问:
How to make a responsive centered div follow the viewport?
I want to make a div that follows the viewport. I am not able to use fixed positioning. For some reason the div doesn't follow the viewport properly, it always 'lags' behind, especially when changing scroll direction. You can see what I mean on plunker here.

That is the first part of the problem. The second is that I need the div to immediately move into the viewport when it appears. (Clicking anywhere in the output panel in the plunker will toggle the div to appear). The *ngIf part of the appearing is important because in my actual app I am using a component with entry animations instead of a div, so no [hidden] I'm afraid.

So why can't I use fixed positioning?

Basically, fixed positioning causes the element to calculate the width differently to its sibling elements when the viewport contains scrollbars. I also can't use the overflow: scroll trick on the element because it has shadows that get clipped by the viewport. It also looks ugly having two scrollbars.

答:
Here is a fixed centered div in a wrapper using flex.
Demo Here</p>

```<code>   #wrapper{
        position:absolute;
        width:100%;
        height:100%;
        position:fixed;
        display: flex;
  justify-content: center;
      }
      #my-app{
        position:relative;
        width:50%;
       height:50%;
        background-color:green;
      }

  <div id="wrapper">
        <div id="my-app">
      </div>
      </div>
</code>```

Body:
Here is a fixed centered div in a wrapper using flex.
Demo Here

   #wrapper{
        position:absolute;
        width:100%;
        height:100%;
        position:fixed;
        display: flex;
  justify-content: center;
      }
      #my-app{
        position:relative;
        width:50%;
       height:50%;
        background-color:green;
      }

  <div id="wrapper">
        <div id="my-app">
      </div>
      </div>


问:
How do you change rank of tf.random_normal as a shape
I'm new to tensorflow and I'm following a tutorial by sentdex.
No matter how many syntax issues I resolve, I keep on getting the same error.

```<code>ValueError: Shape must be rank 1 but is rank 0 for
'random_normal_7/RandomStandardNormal' (op: 'RandomStandardNormal')
with input shapes: []
</code>```

I believe the issue is here, but I have no idea how to fix it.

```<code>def neural_network_model(data):
hidden_1_layer = {'weights': tf.Variable(tf.random_normal([784,
n_nodes_hl1])),
                  'biases':
tf.Variable(tf.random_normal([n_nodes_hl1]))}

hidden_2_layer = {'weights': tf.Variable(tf.random_normal([n_nodes_hl1,
n_nodes_hl2])),
                  'biases':
tf.Variable(tf.random_normal([n_nodes_hl2]))}

hidden_3_layer = {'weights': tf.Variable(tf.random_normal([n_nodes_hl2,
n_nodes_hl3])),
                  'biases':
tf.Variable(tf.random_normal([n_nodes_hl3]))}

output_layer = {'weights': tf.Variable(tf.random_normal([n_nodes_hl3,
n_classes])),
                'biases': tf.Variable(tf.random_normal(n_classes))}
</code>```

My entire code is

```<code>import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data

mnist = input_data.read_data_sets("/tmp/ data/", one_hot=True)

n_nodes_hl1 = 500
n_nodes_hl2 = 500
n_nodes_hl3 = 500

n_classes = 10
batch_size = 100

x = tf.placeholder('float', [None, 784])
y = tf.placeholder('float')

def neural_network_model(data):
hidden_1_layer = {'weights': tf.Variable(tf.random_normal([784,
n_nodes_hl1])),
                  'biases':
tf.Variable(tf.random_normal([n_nodes_hl1]))}

hidden_2_layer = {'weights': tf.Variable(tf.random_normal([n_nodes_hl1,
n_nodes_hl2])),
                  'biases':
tf.Variable(tf.random_normal([n_nodes_hl2]))}

hidden_3_layer = {'weights': tf.Variable(tf.random_normal([n_nodes_hl2,
n_nodes_hl3])),
                  'biases':
tf.Variable(tf.random_normal([n_nodes_hl3]))}

output_layer = {'weights': tf.Variable(tf.random_normal([n_nodes_hl3,
n_classes])),
                'biases': tf.Variable(tf.random_normal(n_classes))}

l1 = tf.add(tf.matmul(data, hidden_1_layer['weights']),
hidden_1_layer['biases'])
l1 = tf.nn.relu(l1)

l2 = tf.add(tf.matmul(data, hidden_2_layer['weights']),
hidden_2_layer['biases'])
l2 = tf.nn.relu(l2)

l3 = tf.add(tf.matmul(data, hidden_3_layer['weights']),
hidden_3_layer['biases'])
l3 = tf.nn.relu(l3)

output = tf.matmul(l3, output_layer['weights']) +
output_layer['biases']

return output

def train_neural_network(x):
prediction = neural_network_model(x)
cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits
(logits=prediction, labels=y))
optimizer = tf.train.AdamOptimizer().minimize(cost)

hm_epochs = 10

with tf.Session() as sess:
    sess.run(tf.global_variables_initializer())

    for epoch in range(hm_epochs):
        epoch_loss = 0
        for _ in range(int(mnist.train.num_examples / batch_size)):
            epoch_x, epoch_y = mnist.train.next_batch(batch_size)
            _, c = sess.run([optimizer, cost], feed_dict={x: epoch_x,
y: epoch_y})
            epoch_loss += c
        print('Epoch', epoch, 'completed out of', hm_epochs, 'loss:',
epoch_loss)

    correct = tf.equal(tf.argmax(prediction, 1), tf.argmax(y, 1))
    accuracy = tf.reduce_mean(tf.cast(correct, 'float'))
    print('Accuracy:', accuracy.eval({x: mnist.test.images, y:
mnist.test.labels}))

train_neural_network(x)
</code>```

答: The first argument to tf.random_normal() (the shape) must be a one-dimensional tensor or a list of integers, representing length of each dimension of the random tensor. Assuming that n_classes is an integer, replacing tf.random_normal(n_classes) with tf.random_normal([n_classes]) should fix the error.

Body:
I'm new to tensorflow and I'm following a tutorial by sentdex.
No matter how many syntax issues I resolve, I keep on getting the same error.

ValueError: Shape must be rank 1 but is rank 0 for
'random_normal_7/RandomStandardNormal' (op: 'RandomStandardNormal')
with input shapes: []

I believe the issue is here, but I have no idea how to fix it.

def neural_network_model(data):
hidden_1_layer = {'weights': tf.Variable(tf.random_normal([784,
n_nodes_hl1])),
                  'biases':
tf.Variable(tf.random_normal([n_nodes_hl1]))}

hidden_2_layer = {'weights': tf.Variable(tf.random_normal([n_nodes_hl1,
n_nodes_hl2])),
                  'biases':
tf.Variable(tf.random_normal([n_nodes_hl2]))}

hidden_3_layer = {'weights': tf.Variable(tf.random_normal([n_nodes_hl2,
n_nodes_hl3])),
                  'biases':
tf.Variable(tf.random_normal([n_nodes_hl3]))}

output_layer = {'weights': tf.Variable(tf.random_normal([n_nodes_hl3,
n_classes])),
                'biases': tf.Variable(tf.random_normal(n_classes))}

My entire code is

import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data

mnist = input_data.read_data_sets("/tmp/ data/", one_hot=True)

n_nodes_hl1 = 500
n_nodes_hl2 = 500
n_nodes_hl3 = 500

n_classes = 10
batch_size = 100

x = tf.placeholder('float', [None, 784])
y = tf.placeholder('float')

def neural_network_model(data):
hidden_1_layer = {'weights': tf.Variable(tf.random_normal([784,
n_nodes_hl1])),
                  'biases':
tf.Variable(tf.random_normal([n_nodes_hl1]))}

hidden_2_layer = {'weights': tf.Variable(tf.random_normal([n_nodes_hl1,
n_nodes_hl2])),
                  'biases':
tf.Variable(tf.random_normal([n_nodes_hl2]))}

hidden_3_layer = {'weights': tf.Variable(tf.random_normal([n_nodes_hl2,
n_nodes_hl3])),
                  'biases':
tf.Variable(tf.random_normal([n_nodes_hl3]))}

output_layer = {'weights': tf.Variable(tf.random_normal([n_nodes_hl3,
n_classes])),
                'biases': tf.Variable(tf.random_normal(n_classes))}

l1 = tf.add(tf.matmul(data, hidden_1_layer['weights']),
hidden_1_layer['biases'])
l1 = tf.nn.relu(l1)

l2 = tf.add(tf.matmul(data, hidden_2_layer['weights']),
hidden_2_layer['biases'])
l2 = tf.nn.relu(l2)

l3 = tf.add(tf.matmul(data, hidden_3_layer['weights']),
hidden_3_layer['biases'])
l3 = tf.nn.relu(l3)

output = tf.matmul(l3, output_layer['weights']) +
output_layer['biases']

return output

def train_neural_network(x):
prediction = neural_network_model(x)
cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits
(logits=prediction, labels=y))
optimizer = tf.train.AdamOptimizer().minimize(cost)

hm_epochs = 10

with tf.Session() as sess:
    sess.run(tf.global_variables_initializer())

    for epoch in range(hm_epochs):
        epoch_loss = 0
        for _ in range(int(mnist.train.num_examples / batch_size)):
            epoch_x, epoch_y = mnist.train.next_batch(batch_size)
            _, c = sess.run([optimizer, cost], feed_dict={x: epoch_x,
y: epoch_y})
            epoch_loss += c
        print('Epoch', epoch, 'completed out of', hm_epochs, 'loss:',
epoch_loss)

    correct = tf.equal(tf.argmax(prediction, 1), tf.argmax(y, 1))
    accuracy = tf.reduce_mean(tf.cast(correct, 'float'))
    print('Accuracy:', accuracy.eval({x: mnist.test.images, y:
mnist.test.labels}))

train_neural_network(x)


问:
Value based conditional Formatting in Excel
I have 2 cells a1 and  a2, which may have negative or postive values. I want the color of both the cells to change to green if value in either cell is between -10 to 10. And red if the value in either cell is between 10 to 20 or -10 to -20 and purple if the value in either cell exceeds 20 or -20. Can any one help me with the query. </p>

答:
Koby Douek gave a great instructional answer to this question.  I will add step-by-step instructions for you.

Click on "Conditional Formatting" in the "Home" tab.  Click on "Manage Rules..." (Alternatively, type Alt+H, Alt+L, Alt+R)

Click "New Rule..."

Select the last option: "Use a formula to determine which cells to format"

In the formula bar, type =AND($A$1<10,$A$1>-10)

Click "Format", change Fill color to Red.

Click OK.  You will now see the screen you were on before.  Change the "Applies to" column to =$A$1:$A$2.

Click "New Rule..." again

Select the last option: "Use a formula to determine which cells to format"

In the formula bar, type =AND($A$2<10,$A$2>-10)

Click "Format", change Fill color to Red.

Click OK.  You will now see the screen you were on before.  Change the "Applies to" column to =$A$1:$A$2.  You should see this screen now:

Continue this process... Add =AND($A$1<20,$A$1>10) with red format, =AND($A$2<20,$A$2>10) with red format, =AND($A$1<-10,$A$1>-20) with purple format, =AND($A$2<-10,$A$2>-20) with purple format

Now you should see this screen:

Finally, this is what you are looking for.  You can change the priority of the conditional formatting using the up and down arrows in the top part of the "Manage Rules" popup window (meaning you can make green take precedence over red, if you would like).

There you are, an overview of conditional formatting!  Happy formatting.  Also, next time, please try this yourself before asking us for help, and show us your progress so we do not need to go step-by-step if you don't need it.


问:
Libav AVFrame to Opencv Mat to AVPacket conversion
I am new to libav and I am writing a video manipulation software which uses opencv as its heart. What I did is briefly as below:

1- read the video packet

2- decode the packet into AVFrame

3- convert
the AVFrame to CV Mat

4- manipulate the Mat

5- convert the CV Mat
into AVFrame

6- encode the AVFrame into AVPacket

7- write the packet

8- goto 1

I read dranger tutorial in http://dranger.com/ffmpeg/tutorial01.html and I also used decoding_encoding example. I can read the video, extract video frames and convert them to CV Mat. My problem starts from converting from cv Mat to AVFrame and encode it to AVPacket.

Would you please help me with this?

Here is my code :

```<code>int main(int argc, char **argv)
{
AVOutputFormat *ofmt = NULL;
AVFormatContext *ifmt_ctx = NULL, *ofmt_ctx = NULL;
AVPacket pkt;
AVCodecContext    *pCodecCtx = NULL;
AVCodec           *pCodec = NULL;
AVFrame           *pFrame = NULL;
AVFrame           *pFrameRGB = NULL;
int videoStream=-1;
int audioStream=-1;
int               frameFinished;
int               numBytes;
uint8_t           *buffer = NULL;
struct SwsContext *sws_ctx = NULL;
FrameManipulation *mal_frame;

const char *in_filename, *out_filename;
int ret, i;
if (argc < 3) {

    printf("usage: %s input output\n"
           "API example program to remux a media file with libavformat and libavcodec.\n"
           "The output format is guessed according to the file extension.\n"
           "\n", argv[0]);
    return 1;
}
in_filename  = arg[1];
out_filename = arg[2];
av_register_all();
if ((ret = avformat_open_input(&ifmt_ctx, in_filename, 0, 0)) < 0) {
    fprintf(stderr, "Could not open input file '%s'", in_filename);
    goto end;
}

if ((ret = avformat_find_stream_info(ifmt_ctx, 0)) < 0) {
    fprintf(stderr, "Failed to retrieve input stream information");
    goto end;
}

av_dump_format(ifmt_ctx, 0, in_filename, 0);
avformat_alloc_output_context2(&ofmt_ctx, NULL, NULL, out_filename);

if (!ofmt_ctx) {
    fprintf(stderr, "Could not create output context\n");
    ret = AVERROR_UNKNOWN;
    goto end;
}

ofmt = ofmt_ctx->oformat;

for (i = 0; i < ifmt_ctx->nb_streams; i++) {
    AVStream *in_stream = ifmt_ctx->streams[i];
    AVStream *out_stream = avformat_new_stream(ofmt_ctx, in_stream->codec->codec);

    if(ifmt_ctx->streams[i]->codec->codec_type==AVMEDIA_TYPE_VIDEO &&
       videoStream < 0) {
           videoStream=i;
    }

    if(ifmt_ctx->streams[i]->codec->codec_type==AVMEDIA_TYPE_AUDIO &&
       audioStream < 0) {
            audioStream=i;
    }

    if (!out_stream) {
        fprintf(stderr, "Failed allocating output stream\n");
        ret = AVERROR_UNKNOWN;
        goto end;
    }

    ret = avcodec_copy_context(out_stream->codec, in_stream->codec);

    if (ret < 0) {
        fprintf(stderr, "Failed to copy context from input to output stream codec context\n");
        goto end;
    }

    out_stream->codec->codec_tag = 0;

    if (ofmt_ctx->oformat->flags & AVFMT_GLOBALHEADER)
       out_stream->codec->flags |= AV_CODEC_FLAG_GLOBAL_HEADER;
}

pCodec=avcodec_find_decoder(ifmt_ctx->streams[videoStream]->codec->codec_id);
pCodecCtx = avcodec_alloc_context3(pCodec);

if(avcodec_copy_context(pCodecCtx, ifmt_ctx->streams[videoStream]->codec) != 0) {
  fprintf(stderr, "Couldn't copy codec context");
  return -1; // Error copying codec context
}

// Open codec
 if(avcodec_open2(pCodecCtx, pCodec, NULL)<0)
   return -1; // Could not open codec

// Allocate video frame
 pFrame=av_frame_alloc();

 // Allocate an AVFrame structure
 pFrameRGB=av_frame_alloc();

 // Determine required buffer size and allocate buffer
 numBytes=avpicture_get_size(AV_PIX_FMT_RGB24, ifmt_ctx->streams[videoStream]->codec->width,
                 ifmt_ctx->streams[videoStream]->codec->height);

 buffer=(uint8_t *)av_malloc(numBytes*sizeof(uint8_t));

 // Assign appropriate parts of buffer to image planes in pFrameRGB
 // Note that pFrameRGB is an AVFrame, but AVFrame is a superset
 // of AVPicture
 avpicture_fill((AVPicture *)pFrameRGB, buffer, AV_PIX_FMT_BGR24,
        ifmt_ctx->streams[videoStream]->codec->width, ifmt_ctx->streams[videoStream]->codec->height);

 av_dump_format(ofmt_ctx, 0, out_filename, 1);

 if (!(ofmt->flags & AVFMT_NOFILE)) {
    ret = avio_open(&ofmt_ctx->pb, out_filename, AVIO_FLAG_WRITE);
    if (ret < 0) {
        fprintf(stderr, "Could not open output file '%s'", out_filename);
        goto end;
    }
}

ret = avformat_write_header(ofmt_ctx, NULL);
if (ret < 0) {
    fprintf(stderr, "Error occurred when opening output file\n");
    goto end;
}

// Assign appropriate parts of buffer to image planes in pFrameRGB
// Note that pFrameRGB is an AVFrame, but AVFrame is a superset
// of AVPicture

avpicture_fill((AVPicture *)pFrameRGB, buffer, AV_PIX_FMT_BGR24,
                   ifmt_ctx->streams[videoStream]->codec->width,
                   ifmt_ctx->streams[videoStream]->codec->height);

// initialize SWS context for software scaling
sws_ctx = sws_getContext(
             ifmt_ctx->streams[videoStream]->codec->width,
             ifmt_ctx->streams[videoStream]->codec->height,
             ifmt_ctx->streams[videoStream]->codec->pix_fmt,
             ifmt_ctx->streams[videoStream]->codec->width,
             ifmt_ctx->streams[videoStream]->codec->height,
             AV_PIX_FMT_BGR24,
             SWS_BICUBIC,
             NULL,
             NULL,
             NULL
             );
// Loop through packets
while (1) {

    AVStream *in_stream, *out_stream;
    ret = av_read_frame(ifmt_ctx, &pkt);
    if(pkt.stream_index==videoStream)

     // Decode video frame
      avcodec_decode_video2(pCodecCtx, pFrame, &frameFinished, &pkt);

      if(frameFinished) {
                sws_scale(sws_ctx, (uint8_t const * const *)pFrame->data,
                pFrame->linesize, 0, pCodecCtx->height,
                pFrameRGB->data, pFrameRGB->linesize);
                cv::Mat img= mal_frame->process(
                          pFrameRGB,pFrame->width,pFrame->height);
/* My problem is Here ------------*/

    avpicture_fill((AVPicture*)pFrameRGB,
                     img.data,
                     PIX_FMT_BGR24,
                     outStream->codec->width,
                     outStream->codec->height);

    pFrameRGB->width =  ifmt_ctx->streams[videoStream]->codec->width;
    pFrameRGB->height = ifmt_ctx->streams[videoStream]->codec->height;

            avcodec_encode_video2(ifmt_ctx->streams[videoStream]->codec ,
                                                     &pkt , pFrameRGB , &gotPacket);
/*
I get this error
[swscaler @ 0x14b58a0] bad src image pointers
[swscaler @ 0x14b58a0] bad src image pointers
*/

/* My Problem Ends here ---------- */

    }

    if (ret < 0)

        break;

    in_stream  = ifmt_ctx->streams[pkt.stream_index];

    out_stream = ofmt_ctx->streams[pkt.stream_index];

    //log_packet(ifmt_ctx, &pkt, "in");

    /* copy packet */

    pkt.pts = av_rescale_q_rnd(pkt.pts, in_stream->time_base, out_stream->time_base,

                               AV_ROUND_NEAR_INF);

    pkt.dts = av_rescale_q_rnd(pkt.dts, in_stream->time_base, out_stream->time_base, AV_ROUND_NEAR_INF);

    pkt.duration = av_rescale_q(pkt.duration, in_stream->time_base, out_stream->time_base);

    pkt.pos = -1;

    log_packet(ofmt_ctx, &pkt, "out");

    ret = av_interleaved_write_frame(ofmt_ctx, &pkt);

    if (ret < 0) {

        fprintf(stderr, "Error muxing packet\n");

        break;

    }

    av_free_packet(&pkt);

}

av_write_trailer(ofmt_ctx);

end:

avformat_close_input(&ifmt_ctx);

/* close output */

if (ofmt_ctx && !(ofmt->flags & AVFMT_NOFILE))

    avio_closep(&ofmt_ctx->pb);

avformat_free_context(ofmt_ctx);

if (ret < 0 && ret != AVERROR_EOF) {

    return 1;

}

return 0;

}
</code>```

When I run this code, I get unknown fatal error in this part:

```<code>   /* My problem is Here ------------*/

    avpicture_fill((AVPicture*)pFrameRGB,
                     img.data,
                     PIX_FMT_BGR24,
                     outStream->codec->width,
                     outStream->codec->height);

    pFrameRGB->width =  ifmt_ctx->streams[videoStream]->codec->width;
    pFrameRGB->height = ifmt_ctx->streams[videoStream]->codec->height;

            avcodec_encode_video2(ifmt_ctx->streams[videoStream]->codec ,
                                                     &pkt , pFrameRGB , &gotPacket);
/*
I get this error
[swscaler @ 0x14b58a0] bad src image pointers
[swscaler @ 0x14b58a0] bad src image pointers
*/

/* My Problem Ends here ---------- */
</code>```

Here is where I want to convert back cv Mat to AVFrame and encode it to AVPacket. I appreciate your help.

答:
After reading some examples, reading source code and some helps people offered, I managed to make the code run. I used transcoding and encoding examples and mixed them up. Here is my code

here are the highlights:
1- libswscale should be used to convert AVFrame with required packet format to be fed into openCV Mat. To do so, we define

```<code>struct SwsContext *sws_ctx = NULL;
sws_ctx = sws_getContext(pCodecCtx->width,
             pCodecCtx->height,
             pCodecCtx->pix_fmt,
             pCodecCtx->width,
             pCodecCtx->height,
             AV_PIX_FMT_BGR24,
             SWS_BICUBIC,
             NULL,
             NULL,
             NULL
             );
</code>```

To convert back the opencv Mat to AVFrame, one should again use swscale and translate opencv BGR frame format to YUV. So, I do this:

```<code> struct SwsContext *sws_ctx_bgr_yuv = NULL;
 sws_ctx_bgr_yuv = sws_getContext(pCodecCtx->width,
                                 pCodecCtx->height,
                                 AV_PIX_FMT_BGR24,
                                 pCodecCtx->width,
                                 pCodecCtx->height,
                                 pCodecCtx->pix_fmt //AV_PIX_FMT_YUV420p
                                 ,0,0,NULL,NULL);
</code>```

And, here is frame reading/decoding/encoding loop:

```<code>while (1) {
    if ((ret = av_read_frame(ifmt_ctx, &packet)) < 0)
        break;
    stream_index = packet.stream_index;
    type = ifmt_ctx->streams[packet.stream_index]->codec->codec_type;
    av_log(NULL, AV_LOG_DEBUG, "Demuxer gave frame of stream_index %u\n",
            stream_index);
    if (filter_ctx[stream_index].filter_graph) {
        av_log(NULL, AV_LOG_DEBUG, "Going to reencode&filter the frame\n");
        frame = av_frame_alloc();
        if (!frame) {
            ret = AVERROR(ENOMEM);
            break;
        }
        av_packet_rescale_ts(&packet,
                             ifmt_ctx->streams[stream_index]->time_base,
                             ifmt_ctx->streams[stream_index]->codec->time_base);
        dec_func = (type == AVMEDIA_TYPE_VIDEO) ? avcodec_decode_video2 :
            avcodec_decode_audio4;
        ret = dec_func(ifmt_ctx->streams[stream_index]->codec, frame,
                &got_frame, &packet);
        if (ret < 0) {
            av_frame_free(&frame);
            av_log(NULL, AV_LOG_ERROR, "Decoding failed\n");
            break;
        }
        if (got_frame) {
            if(stream_index==video_index){

                sws_scale(sws_ctx, (uint8_t const * const *)frame->data,
                      frame->linesize, 0, pCodecCtx->height,
                      pFrameRGB->data, pFrameRGB->linesize);
    /*------------------------------------------------------------------------
    /* Frame converts to opencv Mat
    /*------------------------------------------------------------------------*/
                cv::Mat img(frame->height,frame->width,CV_8UC3,pFrameRGB->data[0]);
                img=manipulate_image(img); //this is opencv Mat, do whatever you want, but don't change its dimensions and format
    //manipulate_function can be considered as as simple as blurring
                const int stride[] = {img.step[0] };
    /* opencv Mat converts back to AVFrame         */
                sws_scale(sws_ctx_bgr_yuv, &img.data, stride, 0, img.rows, frame->data, frame->linesize);

            }
            frame->pts = av_frame_get_best_effort_timestamp(frame);
    /* AVFrame re-encodes to AVPacket and will be sent to encoder */
            ret = filter_encode_write_frame(frame, stream_index);
            av_frame_free(&frame);

            if (ret < 0)
                goto end;
        } else {
            av_frame_free(&frame);
        }
    } else {
        /* remux this frame without reencoding */
        av_packet_rescale_ts(&packet,
                             ifmt_ctx->streams[stream_index]->time_base,
                             ofmt_ctx->streams[stream_index]->time_base);
        ret = av_interleaved_write_frame(ofmt_ctx, &packet);
        if (ret < 0)
            goto end;
    }
    av_free_packet(&packet);
}
</code>```

Body:
I am new to libav and I am writing a video manipulation software which uses opencv as its heart. What I did is briefly as below:

1- read the video packet

2- decode the packet into AVFrame

3- convert
the AVFrame to CV Mat

4- manipulate the Mat

5- convert the CV Mat
into AVFrame

6- encode the AVFrame into AVPacket

7- write the packet

8- goto 1

I read dranger tutorial in http://dranger.com/ffmpeg/tutorial01.html and I also used decoding_encoding example. I can read the video, extract video frames and convert them to CV Mat. My problem starts from converting from cv Mat to AVFrame and encode it to AVPacket.

Would you please help me with this?

Here is my code :

int main(int argc, char **argv)
{
AVOutputFormat *ofmt = NULL;
AVFormatContext *ifmt_ctx = NULL, *ofmt_ctx = NULL;
AVPacket pkt;
AVCodecContext    *pCodecCtx = NULL;
AVCodec           *pCodec = NULL;
AVFrame           *pFrame = NULL;
AVFrame           *pFrameRGB = NULL;
int videoStream=-1;
int audioStream=-1;
int               frameFinished;
int               numBytes;
uint8_t           *buffer = NULL;
struct SwsContext *sws_ctx = NULL;
FrameManipulation *mal_frame;

const char *in_filename, *out_filename;
int ret, i;
if (argc < 3) {

    printf("usage: %s input output\n"
           "API example program to remux a media file with libavformat and libavcodec.\n"
           "The output format is guessed according to the file extension.\n"
           "\n", argv[0]);
    return 1;
}
in_filename  = arg[1];
out_filename = arg[2];
av_register_all();
if ((ret = avformat_open_input(&ifmt_ctx, in_filename, 0, 0)) < 0) {
    fprintf(stderr, "Could not open input file '%s'", in_filename);
    goto end;
}

if ((ret = avformat_find_stream_info(ifmt_ctx, 0)) < 0) {
    fprintf(stderr, "Failed to retrieve input stream information");
    goto end;
}

av_dump_format(ifmt_ctx, 0, in_filename, 0);
avformat_alloc_output_context2(&ofmt_ctx, NULL, NULL, out_filename);

if (!ofmt_ctx) {
    fprintf(stderr, "Could not create output context\n");
    ret = AVERROR_UNKNOWN;
    goto end;
}

ofmt = ofmt_ctx->oformat;

for (i = 0; i < ifmt_ctx->nb_streams; i++) {
    AVStream *in_stream = ifmt_ctx->streams[i];
    AVStream *out_stream = avformat_new_stream(ofmt_ctx, in_stream->codec->codec);

    if(ifmt_ctx->streams[i]->codec->codec_type==AVMEDIA_TYPE_VIDEO &&
       videoStream < 0) {
           videoStream=i;
    }

    if(ifmt_ctx->streams[i]->codec->codec_type==AVMEDIA_TYPE_AUDIO &&
       audioStream < 0) {
            audioStream=i;
    }

    if (!out_stream) {
        fprintf(stderr, "Failed allocating output stream\n");
        ret = AVERROR_UNKNOWN;
        goto end;
    }

    ret = avcodec_copy_context(out_stream->codec, in_stream->codec);

    if (ret < 0) {
        fprintf(stderr, "Failed to copy context from input to output stream codec context\n");
        goto end;
    }

    out_stream->codec->codec_tag = 0;

    if (ofmt_ctx->oformat->flags & AVFMT_GLOBALHEADER)
       out_stream->codec->flags |= AV_CODEC_FLAG_GLOBAL_HEADER;
}

pCodec=avcodec_find_decoder(ifmt_ctx->streams[videoStream]->codec->codec_id);
pCodecCtx = avcodec_alloc_context3(pCodec);

if(avcodec_copy_context(pCodecCtx, ifmt_ctx->streams[videoStream]->codec) != 0) {
  fprintf(stderr, "Couldn't copy codec context");
  return -1; // Error copying codec context
}

// Open codec
 if(avcodec_open2(pCodecCtx, pCodec, NULL)<0)
   return -1; // Could not open codec

// Allocate video frame
 pFrame=av_frame_alloc();

 // Allocate an AVFrame structure
 pFrameRGB=av_frame_alloc();

 // Determine required buffer size and allocate buffer
 numBytes=avpicture_get_size(AV_PIX_FMT_RGB24, ifmt_ctx->streams[videoStream]->codec->width,
                 ifmt_ctx->streams[videoStream]->codec->height);

 buffer=(uint8_t *)av_malloc(numBytes*sizeof(uint8_t));

 // Assign appropriate parts of buffer to image planes in pFrameRGB
 // Note that pFrameRGB is an AVFrame, but AVFrame is a superset
 // of AVPicture
 avpicture_fill((AVPicture *)pFrameRGB, buffer, AV_PIX_FMT_BGR24,
        ifmt_ctx->streams[videoStream]->codec->width, ifmt_ctx->streams[videoStream]->codec->height);

 av_dump_format(ofmt_ctx, 0, out_filename, 1);

 if (!(ofmt->flags & AVFMT_NOFILE)) {
    ret = avio_open(&ofmt_ctx->pb, out_filename, AVIO_FLAG_WRITE);
    if (ret < 0) {
        fprintf(stderr, "Could not open output file '%s'", out_filename);
        goto end;
    }
}

ret = avformat_write_header(ofmt_ctx, NULL);
if (ret < 0) {
    fprintf(stderr, "Error occurred when opening output file\n");
    goto end;
}

// Assign appropriate parts of buffer to image planes in pFrameRGB
// Note that pFrameRGB is an AVFrame, but AVFrame is a superset
// of AVPicture

avpicture_fill((AVPicture *)pFrameRGB, buffer, AV_PIX_FMT_BGR24,
                   ifmt_ctx->streams[videoStream]->codec->width,
                   ifmt_ctx->streams[videoStream]->codec->height);

// initialize SWS context for software scaling
sws_ctx = sws_getContext(
             ifmt_ctx->streams[videoStream]->codec->width,
             ifmt_ctx->streams[videoStream]->codec->height,
             ifmt_ctx->streams[videoStream]->codec->pix_fmt,
             ifmt_ctx->streams[videoStream]->codec->width,
             ifmt_ctx->streams[videoStream]->codec->height,
             AV_PIX_FMT_BGR24,
             SWS_BICUBIC,
             NULL,
             NULL,
             NULL
             );
// Loop through packets
while (1) {

    AVStream *in_stream, *out_stream;
    ret = av_read_frame(ifmt_ctx, &pkt);
    if(pkt.stream_index==videoStream)

     // Decode video frame
      avcodec_decode_video2(pCodecCtx, pFrame, &frameFinished, &pkt);

      if(frameFinished) {
                sws_scale(sws_ctx, (uint8_t const * const *)pFrame->data,
                pFrame->linesize, 0, pCodecCtx->height,
                pFrameRGB->data, pFrameRGB->linesize);
                cv::Mat img= mal_frame->process(
                          pFrameRGB,pFrame->width,pFrame->height);
/* My problem is Here ------------*/

    avpicture_fill((AVPicture*)pFrameRGB,
                     img.data,
                     PIX_FMT_BGR24,
                     outStream->codec->width,
                     outStream->codec->height);

    pFrameRGB->width =  ifmt_ctx->streams[videoStream]->codec->width;
    pFrameRGB->height = ifmt_ctx->streams[videoStream]->codec->height;

            avcodec_encode_video2(ifmt_ctx->streams[videoStream]->codec ,
                                                     &pkt , pFrameRGB , &gotPacket);
/*
I get this error
[swscaler @ 0x14b58a0] bad src image pointers
[swscaler @ 0x14b58a0] bad src image pointers
*/

/* My Problem Ends here ---------- */

    }

    if (ret < 0)

        break;

    in_stream  = ifmt_ctx->streams[pkt.stream_index];

    out_stream = ofmt_ctx->streams[pkt.stream_index];

    //log_packet(ifmt_ctx, &pkt, "in");

    /* copy packet */

    pkt.pts = av_rescale_q_rnd(pkt.pts, in_stream->time_base, out_stream->time_base,

                               AV_ROUND_NEAR_INF);

    pkt.dts = av_rescale_q_rnd(pkt.dts, in_stream->time_base, out_stream->time_base, AV_ROUND_NEAR_INF);

    pkt.duration = av_rescale_q(pkt.duration, in_stream->time_base, out_stream->time_base);

    pkt.pos = -1;

    log_packet(ofmt_ctx, &pkt, "out");

    ret = av_interleaved_write_frame(ofmt_ctx, &pkt);

    if (ret < 0) {

        fprintf(stderr, "Error muxing packet\n");

        break;

    }

    av_free_packet(&pkt);

}

av_write_trailer(ofmt_ctx);

end:

avformat_close_input(&ifmt_ctx);

/* close output */

if (ofmt_ctx && !(ofmt->flags & AVFMT_NOFILE))

    avio_closep(&ofmt_ctx->pb);

avformat_free_context(ofmt_ctx);

if (ret < 0 && ret != AVERROR_EOF) {

    return 1;

}

return 0;

}

When I run this code, I get unknown fatal error in this part:

   /* My problem is Here ------------*/

    avpicture_fill((AVPicture*)pFrameRGB,
                     img.data,
                     PIX_FMT_BGR24,
                     outStream->codec->width,
                     outStream->codec->height);

    pFrameRGB->width =  ifmt_ctx->streams[videoStream]->codec->width;
    pFrameRGB->height = ifmt_ctx->streams[videoStream]->codec->height;

            avcodec_encode_video2(ifmt_ctx->streams[videoStream]->codec ,
                                                     &pkt , pFrameRGB , &gotPacket);
/*
I get this error
[swscaler @ 0x14b58a0] bad src image pointers
[swscaler @ 0x14b58a0] bad src image pointers
*/

/* My Problem Ends here ---------- */

Here is where I want to convert back cv Mat to AVFrame and encode it to AVPacket. I appreciate your help.

Body:
After reading some examples, reading source code and some helps people offered, I managed to make the code run. I used transcoding and encoding examples and mixed them up. Here is my code

here are the highlights:
1- libswscale should be used to convert AVFrame with required packet format to be fed into openCV Mat. To do so, we define

struct SwsContext *sws_ctx = NULL;
sws_ctx = sws_getContext(pCodecCtx->width,
             pCodecCtx->height,
             pCodecCtx->pix_fmt,
             pCodecCtx->width,
             pCodecCtx->height,
             AV_PIX_FMT_BGR24,
             SWS_BICUBIC,
             NULL,
             NULL,
             NULL
             );

To convert back the opencv Mat to AVFrame, one should again use swscale and translate opencv BGR frame format to YUV. So, I do this:

 struct SwsContext *sws_ctx_bgr_yuv = NULL;
 sws_ctx_bgr_yuv = sws_getContext(pCodecCtx->width,
                                 pCodecCtx->height,
                                 AV_PIX_FMT_BGR24,
                                 pCodecCtx->width,
                                 pCodecCtx->height,
                                 pCodecCtx->pix_fmt //AV_PIX_FMT_YUV420p
                                 ,0,0,NULL,NULL);

And, here is frame reading/decoding/encoding loop:

while (1) {
    if ((ret = av_read_frame(ifmt_ctx, &packet)) < 0)
        break;
    stream_index = packet.stream_index;
    type = ifmt_ctx->streams[packet.stream_index]->codec->codec_type;
    av_log(NULL, AV_LOG_DEBUG, "Demuxer gave frame of stream_index %u\n",
            stream_index);
    if (filter_ctx[stream_index].filter_graph) {
        av_log(NULL, AV_LOG_DEBUG, "Going to reencode&filter the frame\n");
        frame = av_frame_alloc();
        if (!frame) {
            ret = AVERROR(ENOMEM);
            break;
        }
        av_packet_rescale_ts(&packet,
                             ifmt_ctx->streams[stream_index]->time_base,
                             ifmt_ctx->streams[stream_index]->codec->time_base);
        dec_func = (type == AVMEDIA_TYPE_VIDEO) ? avcodec_decode_video2 :
            avcodec_decode_audio4;
        ret = dec_func(ifmt_ctx->streams[stream_index]->codec, frame,
                &got_frame, &packet);
        if (ret < 0) {
            av_frame_free(&frame);
            av_log(NULL, AV_LOG_ERROR, "Decoding failed\n");
            break;
        }
        if (got_frame) {
            if(stream_index==video_index){

                sws_scale(sws_ctx, (uint8_t const * const *)frame->data,
                      frame->linesize, 0, pCodecCtx->height,
                      pFrameRGB->data, pFrameRGB->linesize);
    /*------------------------------------------------------------------------
    /* Frame converts to opencv Mat
    /*------------------------------------------------------------------------*/
                cv::Mat img(frame->height,frame->width,CV_8UC3,pFrameRGB->data[0]);
                img=manipulate_image(img); //this is opencv Mat, do whatever you want, but don't change its dimensions and format
    //manipulate_function can be considered as as simple as blurring
                const int stride[] = {img.step[0] };
    /* opencv Mat converts back to AVFrame         */
                sws_scale(sws_ctx_bgr_yuv, &img.data, stride, 0, img.rows, frame->data, frame->linesize);

            }
            frame->pts = av_frame_get_best_effort_timestamp(frame);
    /* AVFrame re-encodes to AVPacket and will be sent to encoder */
            ret = filter_encode_write_frame(frame, stream_index);
            av_frame_free(&frame);

            if (ret < 0)
                goto end;
        } else {
            av_frame_free(&frame);
        }
    } else {
        /* remux this frame without reencoding */
        av_packet_rescale_ts(&packet,
                             ifmt_ctx->streams[stream_index]->time_base,
                             ofmt_ctx->streams[stream_index]->time_base);
        ret = av_interleaved_write_frame(ofmt_ctx, &packet);
        if (ret < 0)
            goto end;
    }
    av_free_packet(&packet);
}


问:
Spotfire IF statement not working when including date functions
I am trying to convert an excel formula for use in spotfire.

In excel =IF(MONTH(A1294)<>MONTH(B1294),(EOMONTH(A1294,0))+1,"")

For context =IF(MONTH(Start Time)<>MONTH(End Time),(EOMONTH(Start Time,0))+1,"")

In Spotfire I have a calculated column and I am trying to use the following code but receiving an error "Invalid type for Function call 'If'"

My code is as follows:

```<code>case when Month([START_TIME_LOCALTIME])!= Month([END_TIME_LOCALTIME])
then Date(Year([END_TIME_LOCALTIME]),Month([END_TIME_LOCALTIME]),1)
else ''
END
</code>```

Any help or ideas would be appreciated

答: I figured out it was because I was looking at different data types, which excel accepts but i required to use Null and convert to the same data type

Body:
I am trying to convert an excel formula for use in spotfire.

In excel =IF(MONTH(A1294)<>MONTH(B1294),(EOMONTH(A1294,0))+1,"")

For context =IF(MONTH(Start Time)<>MONTH(End Time),(EOMONTH(Start Time,0))+1,"")

In Spotfire I have a calculated column and I am trying to use the following code but receiving an error "Invalid type for Function call 'If'"

My code is as follows:

case when Month([START_TIME_LOCALTIME])!= Month([END_TIME_LOCALTIME])
then Date(Year([END_TIME_LOCALTIME]),Month([END_TIME_LOCALTIME]),1)
else ''
END

Any help or ideas would be appreciated


问:
Swift 3 add new row to uitableviewcontroller with uialertcontroller
I'm building a todo-list app. I'm trying to add a todo clicking an add button. It opens an alert with input title inside. I made a class for the added Item :

```<code>class ToDoItem
{
    var title: String

    public init(title: String)
    {
        self.title = title
    }
}
</code>```

Here is my code to add a new row :

```<code>func didTapAddItemButton(_ sender: UIBarButtonItem)
    {

        let alert = UIAlertController(
            title: "New to-do item",
            message: "Insert the title of the new to-do item:",
            preferredStyle: .alert)

        alert.addTextField(configurationHandler: nil)

        alert.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil))

        alert.addAction(UIAlertAction(title: "OK", style: .default, handler: { (_) in
            if let title = alert.textFields?[0].text
            {
                self.addNewToDoItem(title: title)
            }
        }))

        self.present(alert, animated: true, completion: nil)
    }

    private func addNewToDoItem(title: String)
    {

        let newIndex = listCourse?.count

        listCourse?.append(ToDoItem(title: title))

        tableView.insertRows(at: [IndexPath(row: newIndex!, section: 0)], with: .top)
    }
</code>```

But I get that error :

```<code>Cannot convert value of type "ToDoItem" to expected argument type "myItems"
</code>```

Here is myItems class :

```<code>class myItems {
    var title: String?
    var content: String?
    var date: String?
    var author: String?

    init(title: String, content: String, date: String, author: String){
        self.title = title
        self.content = content
        self.date = date
        self.author = author
    }

    func mapping(map: Map) {
        title <- map["title"]
        content <- map["description"]
        date <- map["pubDate"]
        author <- map["author"]
    }
}
</code>```

This "myItems" class is used to get json data, and later I will get data from a database.

Last thing :

```<code>var listCourse : [myItems]?
</code>```

listCourse is the list of cells displaying in tableViewController.

I don't understand that error I just want to add the title entered in the list

[EDIT]

```<code>override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "macell1", for: indexPath)
        return cell
    }
</code>```

答:
You're trying to append to listCourse an item with a wrong type. Since you defined listCourse as array of myItems instances you can append to it  instances of that class only. To fix it just change var listCourse : [myItems]? to var listCourse = [ToDoItem]()

Also fix your UITableViewDataSource method:

```<code>override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "macell1", for: indexPath)
    let item = listCourse[indexPath.item]
    cell.textLabel.text = item.title
    return cell
}
</code>```

Body:
I'm building a todo-list app. I'm trying to add a todo clicking an add button. It opens an alert with input title inside. I made a class for the added Item :

class ToDoItem
{
    var title: String

    public init(title: String)
    {
        self.title = title
    }
}

Here is my code to add a new row :

func didTapAddItemButton(_ sender: UIBarButtonItem)
    {

        let alert = UIAlertController(
            title: "New to-do item",
            message: "Insert the title of the new to-do item:",
            preferredStyle: .alert)

        alert.addTextField(configurationHandler: nil)

        alert.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil))

        alert.addAction(UIAlertAction(title: "OK", style: .default, handler: { (_) in
            if let title = alert.textFields?[0].text
            {
                self.addNewToDoItem(title: title)
            }
        }))

        self.present(alert, animated: true, completion: nil)
    }

    private func addNewToDoItem(title: String)
    {

        let newIndex = listCourse?.count

        listCourse?.append(ToDoItem(title: title))

        tableView.insertRows(at: [IndexPath(row: newIndex!, section: 0)], with: .top)
    }

But I get that error :

Cannot convert value of type "ToDoItem" to expected argument type "myItems"

Here is myItems class :

class myItems {
    var title: String?
    var content: String?
    var date: String?
    var author: String?

    init(title: String, content: String, date: String, author: String){
        self.title = title
        self.content = content
        self.date = date
        self.author = author
    }

    func mapping(map: Map) {
        title <- map["title"]
        content <- map["description"]
        date <- map["pubDate"]
        author <- map["author"]
    }
}

This "myItems" class is used to get json data, and later I will get data from a database.

Last thing :

var listCourse : [myItems]?

listCourse is the list of cells displaying in tableViewController.

I don't understand that error I just want to add the title entered in the list

[EDIT]

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "macell1", for: indexPath)
        return cell
    }

Body:
You're trying to append to listCourse an item with a wrong type. Since you defined listCourse as array of myItems instances you can append to it  instances of that class only. To fix it just change var listCourse : [myItems]? to var listCourse = [ToDoItem]()

Also fix your UITableViewDataSource method:

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "macell1", for: indexPath)
    let item = listCourse[indexPath.item]
    cell.textLabel.text = item.title
    return cell
}


问:
React Native - Force ListView Re-render when data has not changed
Is it possible to force a ListView to re-render, even if the data in the dataSource has not changed? I have a ListView within a tab bar in my app and I want it to redraw every time that tab is selected, regardless of if the data is the same or has changed.

```<code>this.state = {
  data: props.data,
  dataSource: new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2})
}

componentWillMount() {
  this.setState({
    dataSource: this.state.dataSource.cloneWithRows(nextProps.data)
  })
}

render() {
  <ListView
   dataSource={this.state.data}
   renderRow={this._renderRow}
  />
}
</code>```

I tried playing with the rowHasChanged arguments but that did not help. Any help would be much appreciated

答:
I know I'm a bit late but I'm sure that this is still relevant. There's an even easier approach to this... The first example provided by Jason is by all means a good solution but I'm thinking of those whom easily gets confused. If so, use this.

```<code>// On component initalization
componentWillMount() {
    this.UpdateData();
}

// When the component updates
componentDidUpdate() {
    if (this.state.data != this.props.data)
        this.UpdateData();
}

// Function to update the ListView component data
UpdateData() {
    var source = new ListView.DataSource({
        rowHasChanged: (r1, r2) => r1 !== r2
    });

    this.setState({
        data: this.props.data,
        dataSource: source.cloneWithRows(this.props.data)
    });
}
</code>```

I also recommend to implement Redux in your application. That way you could store the new, updated array value in a reducer and then store it locally in a state and later use an if statement in the componentDidUpdate function to determine whether the data is updated or not.

The React debugger logs no performance based complaints or warnings whatsoever...

Body:
Is it possible to force a ListView to re-render, even if the data in the dataSource has not changed? I have a ListView within a tab bar in my app and I want it to redraw every time that tab is selected, regardless of if the data is the same or has changed.

this.state = {
  data: props.data,
  dataSource: new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2})
}

componentWillMount() {
  this.setState({
    dataSource: this.state.dataSource.cloneWithRows(nextProps.data)
  })
}

render() {
  <ListView
   dataSource={this.state.data}
   renderRow={this._renderRow}
  />
}

I tried playing with the rowHasChanged arguments but that did not help. Any help would be much appreciated

Body:
I know I'm a bit late but I'm sure that this is still relevant. There's an even easier approach to this... The first example provided by Jason is by all means a good solution but I'm thinking of those whom easily gets confused. If so, use this.

// On component initalization
componentWillMount() {
    this.UpdateData();
}

// When the component updates
componentDidUpdate() {
    if (this.state.data != this.props.data)
        this.UpdateData();
}

// Function to update the ListView component data
UpdateData() {
    var source = new ListView.DataSource({
        rowHasChanged: (r1, r2) => r1 !== r2
    });

    this.setState({
        data: this.props.data,
        dataSource: source.cloneWithRows(this.props.data)
    });
}

I also recommend to implement Redux in your application. That way you could store the new, updated array value in a reducer and then store it locally in a state and later use an if statement in the componentDidUpdate function to determine whether the data is updated or not.

The React debugger logs no performance based complaints or warnings whatsoever...


问:
How to change the background image of a QMainWindow central widget?
I'm trying to change the background image of the QMainWindow central widget. The QMainWindow's background is fairly easy to change but I can't get the same result with it's central widget. What I tried is the code

```<code>self.mdi = QMdiArea()
self.options_window = Options()
self.central_widget = QStackedWidget()
self.mdi.setStyleSheet("{background-image: url(ninja.png);}")
self.setCentralWidget(self.central_widget)
self.central_widget.addWidget(self.mdi)
self.central_widget.addWidget(self.options_window)
self.central_widget.setCurrentWidget(self.mdi)
</code>```

I also tried with this one

```<code>self.mdi = QMdiArea()
self.options_window = Options()
self.central_widget = QStackedWidget()
self.central_widget.setStyleSheet("{background-image: url(ninja.png);}")
self.setCentralWidget(self.central_widget)
self.central_widget.addWidget(self.mdi)
self.central_widget.addWidget(self.options_window)
self.central_widget.setCurrentWidget(self.mdi)
</code>```

Could anyone give me a light in this problem?

答:
To change the background image of a QWidget you should override the paintEvent method, in your case yours in a QStackedWidget, we create a class that inherits from this:

```<code>class StackedWidget(QStackedWidget):
    def __init__(self, parent=None):
        QStackedWidget.__init__(self, parent=parent)

    def paintEvent(self, event):
        painter = QPainter(self)
        painter.drawPixmap(self.rect(), QPixmap("ninja.png"))
        QStackedWidget.paintEvent(self, event)
</code>```

And then you change:

```<code>self.central_widget = QStackedWidget()
</code>```

to:

```<code>self.central_widget = StackedWidget()
</code>```

Example:

```<code>import sys
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *

class StackedWidget(QStackedWidget):
    def __init__(self, parent=None):
        QStackedWidget.__init__(self, parent=parent)

    def paintEvent(self, event):
        painter = QPainter(self)
        painter.drawPixmap(self.rect(), QPixmap("image.png"))
        QStackedWidget.paintEvent(self, event)

class MainWindow(QMainWindow):
    def __init__(self, parent=None):
        QMainWindow.__init__(self, parent=parent)
        self.setCentralWidget(StackedWidget())

if __name__ == '__main__':

    app = QApplication(sys.argv)
    w = MainWindow()
    w.show()
    sys.exit(app.exec_())
</code>```

Screenshot:

The case of QStackedWidget is a special case since this is not shown, this serves to show other widgets, to those widgets you must change the background image.

From your code, the first widget they attach is a QMdiArea, this is also a special case since it has a viewport and this should be changed.

```<code>class MdiArea(QMdiArea):
    def __init__(self, parent=None):
        QMdiArea.__init__(self, parent=parent)

    def paintEvent(self, event):
        QMdiArea.paintEvent(self, event)
        painter = QPainter(self.viewport())
        painter.drawPixmap(self.rect(), QPixmap("image.png"))
</code>```

In your code change:

```<code>self.mdi = QMdiArea()
</code>```

to:

```<code>self.mdi = MdiArea()
</code>```

Screenshots:

Body:
I'm trying to change the background image of the QMainWindow central widget. The QMainWindow's background is fairly easy to change but I can't get the same result with it's central widget. What I tried is the code

self.mdi = QMdiArea()
self.options_window = Options()
self.central_widget = QStackedWidget()
self.mdi.setStyleSheet("{background-image: url(ninja.png);}")
self.setCentralWidget(self.central_widget)
self.central_widget.addWidget(self.mdi)
self.central_widget.addWidget(self.options_window)
self.central_widget.setCurrentWidget(self.mdi)

I also tried with this one

self.mdi = QMdiArea()
self.options_window = Options()
self.central_widget = QStackedWidget()
self.central_widget.setStyleSheet("{background-image: url(ninja.png);}")
self.setCentralWidget(self.central_widget)
self.central_widget.addWidget(self.mdi)
self.central_widget.addWidget(self.options_window)
self.central_widget.setCurrentWidget(self.mdi)

Could anyone give me a light in this problem?

Body:
To change the background image of a QWidget you should override the paintEvent method, in your case yours in a QStackedWidget, we create a class that inherits from this:

class StackedWidget(QStackedWidget):
    def __init__(self, parent=None):
        QStackedWidget.__init__(self, parent=parent)

    def paintEvent(self, event):
        painter = QPainter(self)
        painter.drawPixmap(self.rect(), QPixmap("ninja.png"))
        QStackedWidget.paintEvent(self, event)

And then you change:

self.central_widget = QStackedWidget()

to:

self.central_widget = StackedWidget()

Example:

import sys
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *

class StackedWidget(QStackedWidget):
    def __init__(self, parent=None):
        QStackedWidget.__init__(self, parent=parent)

    def paintEvent(self, event):
        painter = QPainter(self)
        painter.drawPixmap(self.rect(), QPixmap("image.png"))
        QStackedWidget.paintEvent(self, event)

class MainWindow(QMainWindow):
    def __init__(self, parent=None):
        QMainWindow.__init__(self, parent=parent)
        self.setCentralWidget(StackedWidget())

if __name__ == '__main__':

    app = QApplication(sys.argv)
    w = MainWindow()
    w.show()
    sys.exit(app.exec_())

Screenshot:

The case of QStackedWidget is a special case since this is not shown, this serves to show other widgets, to those widgets you must change the background image.

From your code, the first widget they attach is a QMdiArea, this is also a special case since it has a viewport and this should be changed.

class MdiArea(QMdiArea):
    def __init__(self, parent=None):
        QMdiArea.__init__(self, parent=parent)

    def paintEvent(self, event):
        QMdiArea.paintEvent(self, event)
        painter = QPainter(self.viewport())
        painter.drawPixmap(self.rect(), QPixmap("image.png"))

In your code change:

self.mdi = QMdiArea()

to:

self.mdi = MdiArea()

Screenshots:


问:
Need to listen to a table for changes in Firebase
In my Angular 2 app I need to listen to a table for changes in Firebase. I'm using Angular2, Firebase, and TypeScript. I have a listener but it doesn't fire when I change the database table.

I need it to always hit the listener when the table is updated/changed.
It seems like I need to put my listener in a global place. Currently, my listener is in a service file.

This is my attempt:

```<code>this.adminNotifications = new Firebase(_environment.firebaseUrl + "/adminNotifications");

taskSchedulerListner = (): Promise<any> => {
    this.adminNotifications.on('value', function(snapshot: any) {
        console.log("admin notification hit!");
    });
}
</code>```

Let me know if you need to see any other code. Currently, I just want the listener to be hit when the adminNotifications table is changed. I other words, I want the console.log method in the above example to be hit.

I don't get any console errors, just nothing happens when table adminNotifications is changed.

答:
I experienced this same problem and came to realize that you don't have to wrap your listener in a promise when returning it. Just readjust your code to this.</p>

```<code>this.adminNotifications = new Firebase(_environment.firebaseUrl + "/adminNotifications");

taskSchedulerListner = this.adminNotifications.on('value', function(snapshot: any) {
        console.log("admin notification hit!");
    });
</code>```

Body:
In my Angular 2 app I need to listen to a table for changes in Firebase. I'm using Angular2, Firebase, and TypeScript. I have a listener but it doesn't fire when I change the database table.

I need it to always hit the listener when the table is updated/changed.
It seems like I need to put my listener in a global place. Currently, my listener is in a service file.

This is my attempt:

this.adminNotifications = new Firebase(_environment.firebaseUrl + "/adminNotifications");

taskSchedulerListner = (): Promise<any> => {
    this.adminNotifications.on('value', function(snapshot: any) {
        console.log("admin notification hit!");
    });
}

Let me know if you need to see any other code. Currently, I just want the listener to be hit when the adminNotifications table is changed. I other words, I want the console.log method in the above example to be hit.

I don't get any console errors, just nothing happens when table adminNotifications is changed.

Body:
I experienced this same problem and came to realize that you don't have to wrap your listener in a promise when returning it. Just readjust your code to this.

this.adminNotifications = new Firebase(_environment.firebaseUrl + "/adminNotifications");

taskSchedulerListner = this.adminNotifications.on('value', function(snapshot: any) {
        console.log("admin notification hit!");
    });


问:
reset auto increment id after deletion of last row
I made a table in a mysql database for testing purposes.
The id is auto incremented. After doing this(not together)

```<code>delete from test where id=4;
alter table test auto_increment = 4;
insert into test(nume) values('dan');
</code>```

It does not give any errors. But the last id is 5, not 4. Should not this be working?

答:
This whole procedure has only use in case you do delete the record with the highest id.
Should you delete where id=2, you cannot change the autoincrement id. For whatever reason you do not like to get a gap in the id line at id=4, in case of deleting id =2 there will be a gap. So why mess with the ids when after adding a new record id =5 you would have the same kind of gap.

But what about racing conditions. You delete record id=4. two millisec later I add a record, getting id=5. What will happen to the auto increment id?

What legit reason is there for avoiding these gaps?

Body:
I made a table in a mysql database for testing purposes.
The id is auto incremented. After doing this(not together)

delete from test where id=4;
alter table test auto_increment = 4;
insert into test(nume) values('dan');

It does not give any errors. But the last id is 5, not 4. Should not this be working?