问:
More than one grouping in lodash
I have this sample data to group

```<code> [
            {
                heading: "pikachu",
                sideHeading: "yellow",
                subSideHeading: "electric",
                comment: "its a pokemon"
            },
            {
                heading: "pikachu",
                sideHeading: "yellow",
                subSideHeading: "rat",
                comment: "Ash pokemon"
            },
            {
                heading: "bulbasaur",
                sideHeading: "green",
                subSideHeading: "frog",
                comment: "Ash pokemon"
            },
            {
                heading: "pikachu",
                sideHeading: "ash",
                subSideHeading: "pet",
                comment: "not in pokeball"
            }
 ]
</code>```

looking for lodash method which can get me this output:

```<code>  [
        {
            heading:"pikachu",
            sideHeading:
            [
                {
                    sideHeading:"yellow",
                    subSideHeading:
                    [
                        {
                            subSideHeading: "electric",
                            comment: "its a pokemon"
                        },
                        {
                            subSideHeading: "rat",
                            comment: "Ash pokemon"
                        }
                    ]
                },
                {
                    sideHeading:"ash",
                    subSideHeading:[
                        {
                            subSideHeading: "pet",
                            comment: "not in pokeball"
                        }
                    ]
                }
            ]
        },
        {
            heading:"bulbasaur",
            sideHeading:
            [
                {
                    sideHeading:"green",
                    subSideHeading:
                    [
                        {
                            subSideHeading: "frog",
                            comment: "Ash pokemon"
                        }
                    ]
                }
            ]
        }
    ]
</code>```

I tried very hard referring lodash documentation and stack overflow questions and used the methods like chain groupBy each map filter but the luck was not in my favor. Can anyone come up with the solution to solve this or direct me to the correct path.

答:
It's not perfect, but this does exactly what you need it to do.

const data = [
  {
    heading: "pikachu",
    sideHeading: "yellow",
    subSideHeading: "electric",
    comment: "its a pokemon"
  },
  {
    heading: "pikachu",
    sideHeading: "yellow",
    subSideHeading: "rat",
    comment: "Ash pokemon"
  },
  {
    heading: "bulbasaur",
    sideHeading: "green",
    subSideHeading: "frog",
    comment: "Ash pokemon"
  },
  {
    heading: "pikachu",
    sideHeading: "ash",
    subSideHeading: "pet",
    comment: "not in pokeball"
  }
];

function getNested(dt, key, value, ...nestedArgs) {
  return _.chain(dt)
    .groupBy(key)
    .map((v, k) => {
      const nestedData = _.map(v, ({ [key]: kv, ...rest }) => rest);
      const [nextVal, ...restOfArgs] = nestedArgs;

      return {
        [key]: k,
        [value]: _.isNil(nextVal)
          ? nestedData
          : getNested.apply(null, [nestedData, value, nextVal].concat(restOfArgs))
      };
    })
    .value();
}

console.log(getNested(data, 'heading', 'sideHeading', 'subSideHeading'));

//console.log(group);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdn.jsdelivr.net/npm/lodash@4.17.15/lodash.min.js"></script></code>```

Title: More than one grouping in lodash

Body:
I have this sample data to group

 [
            {
                heading: "pikachu",
                sideHeading: "yellow",
                subSideHeading: "electric",
                comment: "its a pokemon"
            },
            {
                heading: "pikachu",
                sideHeading: "yellow",
                subSideHeading: "rat",
                comment: "Ash pokemon"
            },
            {
                heading: "bulbasaur",
                sideHeading: "green",
                subSideHeading: "frog",
                comment: "Ash pokemon"
            },
            {
                heading: "pikachu",
                sideHeading: "ash",
                subSideHeading: "pet",
                comment: "not in pokeball"
            }
 ]

looking for lodash method which can get me this output:

  [
        {
            heading:"pikachu",
            sideHeading:
            [
                {
                    sideHeading:"yellow",
                    subSideHeading:
                    [
                        {
                            subSideHeading: "electric",
                            comment: "its a pokemon"
                        },
                        {
                            subSideHeading: "rat",
                            comment: "Ash pokemon"
                        }
                    ]
                },
                {
                    sideHeading:"ash",
                    subSideHeading:[
                        {
                            subSideHeading: "pet",
                            comment: "not in pokeball"
                        }
                    ]
                }
            ]
        },
        {
            heading:"bulbasaur",
            sideHeading:
            [
                {
                    sideHeading:"green",
                    subSideHeading:
                    [
                        {
                            subSideHeading: "frog",
                            comment: "Ash pokemon"
                        }
                    ]
                }
            ]
        }
    ]

I tried very hard referring lodash documentation and stack overflow questions and used the methods like chain groupBy each map filter but the luck was not in my favor. Can anyone come up with the solution to solve this or direct me to the correct path.

Body:
It's not perfect, but this does exactly what you need it to do.

const data = [
  {
    heading: "pikachu",
    sideHeading: "yellow",
    subSideHeading: "electric",
    comment: "its a pokemon"
  },
  {
    heading: "pikachu",
    sideHeading: "yellow",
    subSideHeading: "rat",
    comment: "Ash pokemon"
  },
  {
    heading: "bulbasaur",
    sideHeading: "green",
    subSideHeading: "frog",
    comment: "Ash pokemon"
  },
  {
    heading: "pikachu",
    sideHeading: "ash",
    subSideHeading: "pet",
    comment: "not in pokeball"
  }
];

function getNested(dt, key, value, ...nestedArgs) {
  return _.chain(dt)
    .groupBy(key)
    .map((v, k) => {
      const nestedData = _.map(v, ({ [key]: kv, ...rest }) => rest);
      const [nextVal, ...restOfArgs] = nestedArgs;

      return {
        [key]: k,
        [value]: _.isNil(nextVal)
          ? nestedData
          : getNested.apply(null, [nestedData, value, nextVal].concat(restOfArgs))
      };
    })
    .value();
}

console.log(getNested(data, 'heading', 'sideHeading', 'subSideHeading'));

//console.log(group);

<script src="https://cdn.jsdelivr.net/npm/lodash@4.17.15/lodash.min.js"></script>


来源: stackexchange

问:
Check previous model value on save
I have a model that saves an Excursion. The user can change this excursion, but I need to know what the excursion was before he change it, because I keep track of how many "bookings" are made per excursion, and if you change your excursion, I need to remove one booking from the previous excursion.

Im not entirely sure how this should be done.

Im guessing you use a signal for this?

Should I use pre_save, pre_init or what would be the best for this?

pre_save is not the correct one it seems, as it prints the new values, not the "old value" as I expected

```<code>@receiver(pre_save, sender=Delegate)
def my_callback(sender, instance, *args, **kwargs):
    print instance.excursion
</code>```

答:
You can use django model utils to track django model fields. check this example.

```<code>pip install django-model-utils
</code>```

Then you can define your model and use fieldtracker in your model .

```<code>from django.db import models
from model_utils import FieldTracker

class Post(models.Model):
    title = models.CharField(max_length=100)
    body = models.TextField()
    tracker = FieldTracker()
    status = models.CharField(choices=STATUS, default=STATUS.draft, max_length=20)
</code>```

after that in post save you can use like this :

```<code>@receiver(post_save, sender=Post)
def my_callback(sender, instance,*args, **kwargs):
    print (instance.title)
    print (instance.tracker.previous('title'))
    print (instance.status)
    print (instance.tracker.previous('status'))
</code>```

This will help you a lot to do activity on status change. as because overwrite  save method is not good idea.

ContentLicense: CC BY-SA 3.0

Title: Check previous model value on save

Body:
I have a model that saves an Excursion. The user can change this excursion, but I need to know what the excursion was before he change it, because I keep track of how many "bookings" are made per excursion, and if you change your excursion, I need to remove one booking from the previous excursion.

Im not entirely sure how this should be done.

Im guessing you use a signal for this?

Should I use pre_save, pre_init or what would be the best for this?

pre_save is not the correct one it seems, as it prints the new values, not the "old value" as I expected

@receiver(pre_save, sender=Delegate)
def my_callback(sender, instance, *args, **kwargs):
    print instance.excursion

Body:
You can use django model utils to track django model fields. check this example.

pip install django-model-utils

Then you can define your model and use fieldtracker in your model .

from django.db import models
from model_utils import FieldTracker

class Post(models.Model):
    title = models.CharField(max_length=100)
    body = models.TextField()
    tracker = FieldTracker()
    status = models.CharField(choices=STATUS, default=STATUS.draft, max_length=20)

after that in post save you can use like this :

@receiver(post_save, sender=Post)
def my_callback(sender, instance,*args, **kwargs):
    print (instance.title)
    print (instance.tracker.previous('title'))
    print (instance.status)
    print (instance.tracker.previous('status'))

This will help you a lot to do activity on status change. as because overwrite  save method is not good idea.

ContentLicense: CC BY-SA 4.0


问:
Here.com API format
I am pretty new to this so all help you could provide would be greatly appreciated!

I am trying to use Here.com API's and on their example page for Traffic Incidents it has this example:

https://traffic.hereapi.cn/traffic/6.3/incidents.json

?app_id={YOUR_APP_ID}

&app_code={YOUR_APP_CODE}

&bbox=37.586,126.969;37.477,127.106

&criticality=minor

When I go to my account all I have are:

1) APP ID

2) API Key

There is nothing labeled "YOUR APP CODE".  Can someone please tell me what they are looking for?  Also when I do get the right info do I replace everything AFTER the '=' sign with these ID's or do I put the data between the curly brackets?

Thanks in advance for any guidance you can give...

答:
When we log into Developer Portal, we

Create a project

We then generate an App by clicking on Generate APP. This creates your application and shows you application authentication credentials. An APP ID is generated for identifying your application.

Next, you click on Create API Key and you get your API KEY.

This API KEY is what you will be using for all your API calls and write it wherever it says {YOUR_API_KEY} by replacing the complete curly bracket and the content inside it with your API KEY.

For Traffic API, see Traffic Dev Guide

Title: Here.com API format


问:
How to run javascript unit tests against different dependency versions?
In Python, I can do this by using Tox and pytest.
They enable me to run my unit tests in different combinations of Python versions and dependencies.

In example, for some reason, i need to test this function to run against currency.js@~1.1.0 and currency.js@~1.2.0.

import * as currency from 'currency.js';

export function getAmount(amountStr: string): number {
  return currency(amountStr).intValue;
}
```

<pre class="lang-js prettyprint-override"><code>import { getAmount } from './get-amount';

describe('getAmount', () => {
  [
    { given: 'A$ 1.00', expecting: 100 },
    { given: 'A$ 1.33', expecting: 133 },
    { given: 'A$ 1.89', expecting: 189 },
  ].forEach(({ given, expecting }) => {
    describe(`given ${given}`, () => {
      it(`should return ${expecting}`, () => {
        expect(getAmount(given)).toEqual(expecting);
      });
    });
  });
});
</code>```

So it's like I am asking:  What is the NodeJS equivalent of Python Tox?

For more context, i am using TypeScript, Angular and jest.

答:
NPM allows you to alias libraries when you install them:

npm install currency.js-legacy@npm:currency.js@1.1.0

So you can install multiple versions of a library in question and make them available under different names.

Then import both in your test files and use whichever you need. Eg:

```<code>import currency from 'currency.js';
import currency-legacy from `currency.js-legacy';
</code>```

I haven't tested the code but you can get the idea from the above anyway.

Body:
In Python, I can do this by using Tox and pytest.
They enable me to run my unit tests in different combinations of Python versions and dependencies.

In example, for some reason, i need to test this function to run against currency.js@~1.1.0 and currency.js@~1.2.0.

import * as currency from 'currency.js';

export function getAmount(amountStr: string): number {
  return currency(amountStr).intValue;
}

import { getAmount } from './get-amount';

describe('getAmount', () => {
  [
    { given: 'A$ 1.00', expecting: 100 },
    { given: 'A$ 1.33', expecting: 133 },
    { given: 'A$ 1.89', expecting: 189 },
  ].forEach(({ given, expecting }) => {
    describe(`given ${given}`, () => {
      it(`should return ${expecting}`, () => {
        expect(getAmount(given)).toEqual(expecting);
      });
    });
  });
});

So it's like I am asking:  What is the NodeJS equivalent of Python Tox?

For more context, i am using TypeScript, Angular and jest.

Body:
NPM allows you to alias libraries when you install them:

npm install currency.js-legacy@npm:currency.js@1.1.0

So you can install multiple versions of a library in question and make them available under different names.

Then import both in your test files and use whichever you need. Eg:

import currency from 'currency.js';
import currency-legacy from `currency.js-legacy';

I haven't tested the code but you can get the idea from the above anyway.


问:
The storing data in DB by Ajax in ASP.NET MVC don’t be run
I want to save data to database by ajax in ASP.NET MVC. I read very article and write them in [y project, but I face to wrong.

I don’t know what it works properly.

For example - my code in controller :

```<code>public ActionResult InsertData_5()
{
     return View();
}

[HttpPost]
public ActionResult InsertData_5(Personal objdata)
{
    try
    {
        //SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings[connectionString].ToString());
        string constr = "Data Source=192.168.100.1;Initial Catalog=ContosoUniversity1;Persist Security Info=True;User ID=sa;Password=Abhar70";
        SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings[constr].ToString());

        con.Open();

        SqlCommand cmd = new SqlCommand("InsertData_SP", con);
        cmd.CommandType = CommandType.StoredProcedure;

        cmd.Parameters.AddWithValue("@FirstName", objdata.FirstName);
        cmd.Parameters.AddWithValue("@LastName", objdata.LastName);
        cmd.Parameters.AddWithValue("@Phone", objdata.Phone);

        cmd.ExecuteNonQuery();
        con.Close();
    }
    catch (Exception)
    {
        throw;
    }

    return View("InsertData_5");
}
</code>```

Stored procedure:

```<code>SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

ALTER PROCEDURE [dbo].[InsertData_SP]
    (@FirstName nvarchar(MAX),
     @LastName nvarchar(MAX),
     @Phone nvarchar(MAX))
AS
BEGIN
    INSERT INTO Personal_tbl2 (FirstName, LastName, Phone)
    VALUES (@FirstName, @LastName, @Phone)
END
</code>```

View InsertData_5.cshtml :

```<code>@model ContosoUniversity.Models.Personal

@using System.Web.Optimization;

@{
    ViewBag.Title = "InsertData_5";
}

<h2>Index</h2>
<script src="~/Scripts/jquery-3.4.1.js"></script>
<script src="~/Scripts/jquery.unobtrusive-ajax.js"></script>
<script src=”-/Scripts/jquery.unobtrusive-ajax.min.js”></script>

<div id="divEmp">

    @using (Ajax.BeginForm("InsertData_5", "Post", new AjaxOptions { HttpMethod = "POST", UpdateTargetId = "divEmp" }))
    {
        <table>
            <tr>
                <td>FirstName</td>
                <td>
                    <input type="text" id="txtFirstName" />
                </td>
            </tr>
            <tr>
                <td>LastName</td>
                <td>
                    <input type="text" id="txtLastName" />
                </td>
            </tr>
            <tr>
                <td>Phone</td>
                <td>
                    <input type="text" id="txtPhone" />
                </td>
            </tr>
            <tr>
                <td>
                    <input type="button" id="btnsubmit" value="Save" />
                </td>
            </tr>
        </table>

        <script type="text/javascript">
            $(document).ready(function () {
                $("#btnsubmit").click(function () {
                    $.ajax(
                    {
                        type: "POST",
                        url: "Home/InsertData_5",
                        data: {
                            FirstName: $("#txtFirstName").val(),
                            LastName: $("#txtLastName").val(),
                            Phone: $("#txtPhone").val()
                        }

                    });

                });
            });
        </script>
    }
    </div>
</code>```

Index.cshtml

I have a button in this file. When program run, I click button. It get the data. But don't store in database.

```<code>@{ ViewBag.Title = "first page";  }
<div class="jumbotron">
    <h1>aa</h1>
</div>

<div class="row">

    <div class="col-md-4">
        <div class="navbar-collapse collapse">
            <ul class="btn btn-default">
                <li>@Html.ActionLink("saving", "InsertData_5", "Home")</li>
            </ul>

        </div>
    </div>

</div>
</code>```

What should I do?

Thanks

答:
This code wrong i think. You write constr as variable but you try to get connection with this string from configuration.

```<code>string constr = "Data Source=192.168.100.1;Initial Catalog=ContosoUniversity1;Persist Security Info=True;User ID=sa;Password=Abhar70";
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings[constr].ToString());
</code>```

Please recplace it to this

```<code>SqlConnection con = new SqlConnection(constr);
</code>```

Body:
I want to save data to database by ajax in ASP.NET MVC. I read very article and write them in [y project, but I face to wrong.

I don’t know what it works properly.

For example - my code in controller :

public ActionResult InsertData_5()
{
     return View();
}

[HttpPost]
public ActionResult InsertData_5(Personal objdata)
{
    try
    {
        //SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings[connectionString].ToString());
        string constr = "Data Source=192.168.100.1;Initial Catalog=ContosoUniversity1;Persist Security Info=True;User ID=sa;Password=Abhar70";
        SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings[constr].ToString());

        con.Open();

        SqlCommand cmd = new SqlCommand("InsertData_SP", con);
        cmd.CommandType = CommandType.StoredProcedure;

        cmd.Parameters.AddWithValue("@FirstName", objdata.FirstName);
        cmd.Parameters.AddWithValue("@LastName", objdata.LastName);
        cmd.Parameters.AddWithValue("@Phone", objdata.Phone);

        cmd.ExecuteNonQuery();
        con.Close();
    }
    catch (Exception)
    {
        throw;
    }

    return View("InsertData_5");
}

Stored procedure:

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

ALTER PROCEDURE [dbo].[InsertData_SP]
    (@FirstName nvarchar(MAX),
     @LastName nvarchar(MAX),
     @Phone nvarchar(MAX))
AS
BEGIN
    INSERT INTO Personal_tbl2 (FirstName, LastName, Phone)
    VALUES (@FirstName, @LastName, @Phone)
END

View InsertData_5.cshtml :

@model ContosoUniversity.Models.Personal

@using System.Web.Optimization;

@{
    ViewBag.Title = "InsertData_5";
}

Index

    @using (Ajax.BeginForm("InsertData_5", "Post", new AjaxOptions { HttpMethod = "POST", UpdateTargetId = "divEmp" }))
    {

                FirstName

                    <input type="text" id="txtFirstName" />

                LastName

                    <input type="text" id="txtLastName" />

                Phone

                    <input type="text" id="txtPhone" />

                    <input type="button" id="btnsubmit" value="Save" />

    }

Index.cshtml

I have a button in this file. When program run, I click button. It get the data. But don't store in database.

@{ ViewBag.Title = "first page";  }

aa

@Html.ActionLink("saving", "InsertData_5", "Home")

What should I do?

Thanks

Body:
This code wrong i think. You write constr as variable but you try to get connection with this string from configuration.

string constr = "Data Source=192.168.100.1;Initial Catalog=ContosoUniversity1;Persist Security Info=True;User ID=sa;Password=Abhar70";
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings[constr].ToString());

Please recplace it to this

SqlConnection con = new SqlConnection(constr);


问:
how to display image content of a Zip file without extracting its content first with php?
I tried this but not work</p>

```<code><?php
  $za = new ZipArchive();

  $za->open('zip1.zip');

  for ($i=0; $i < $za->numFiles ; $i++) {
    $stat = $za->statIndex($i);
    print_r("<img src=" .basename($stat['name']) . PHP_EOL . "/>");
  }
?>
</code>```

答:
Take a look on the function zip_entry_read()

An example how to use it you can find here

Body:
I tried this but not work

<?php
  $za = new ZipArchive();

  $za->open('zip1.zip');

  for ($i=0; $i < $za->numFiles ; $i++) {
    $stat = $za->statIndex($i);
    print_r("");
  }
?>


问:
Regex to count the total number of words in a string
The total number of words in this string is 11. But my code returns 13.</p>

```<code>var txt = "Helllo, my -! This is a great day to say helllo.\n\n\tHelllo! 2 3 4 23";
txt = txt.replace(/[0-9]/g, '');
var words_count = txt.match(/\S+/g).length;
</code>```

答:
\S+ will match any non-space character, which will include substrings like -!. You might match sequences of non-space characters which also include at least one alphabetical character in them, with \S*[a-z]\S*:

var txt = "Helllo, my -! This is a great day to sayhelllo.\n\n\tHelllo! 2 3 4 23";
console.log(txt.match(/\S*[a-z]\S*/gi).length);```
</div>
</div>
</p>

<p>If you can count on what you want to count as a "word" to start with an alphabetical character, you can remove the leading <code>\S*</code>.</p>

<p>If you want to make the trailing <code>\S*</code> more restrictive, you could whitelist a list of permitted characters inside "words", like <code>'</code> if you want:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>var txt = "Helllo, my -! This is a great day to sayhelllo.\n\n\tHelllo! 2 3 4 23";
console.log(txt.match(/[a-z][a-z']*/gi).length);</code>```

(to add more characters to the whitelist, just expand the [a-z'] character set to whatever you need)

Body:
The total number of words in this string is 11. But my code returns 13.

var txt = "Helllo, my -! This is a great day to say helllo.\n\n\tHelllo! 2 3 4 23";
txt = txt.replace(/[0-9]/g, '');
var words_count = txt.match(/\S+/g).length;

Body:
\S+ will match any non-space character, which will include substrings like -!. You might match sequences of non-space characters which also include at least one alphabetical character in them, with \S*[a-z]\S*:

var txt = "Helllo, my -! This is a great day to sayhelllo.\n\n\tHelllo! 2 3 4 23";
console.log(txt.match(/\S*[a-z]\S*/gi).length);

If you can count on what you want to count as a "word" to start with an alphabetical character, you can remove the leading \S*.

If you want to make the trailing \S* more restrictive, you could whitelist a list of permitted characters inside "words", like ' if you want:

var txt = "Helllo, my -! This is a great day to sayhelllo.\n\n\tHelllo! 2 3 4 23";
console.log(txt.match(/[a-z][a-z']*/gi).length);

(to add more characters to the whitelist, just expand the [a-z'] character set to whatever you need)


问:
Calculating the speed of routines?
What would be the best and most accurate way to determine how long it took to process a routine, such as a procedure of function?

I ask because I am currently trying to optimize a few functions in my Application, when i test the changes it is hard to determine just by looking at it if there was any improvements at all. So if I could return an accurate or near accurate time it took to process a routine, I then have a more clear idea of how well, if any changes to the code have been made.

I considered using GetTickCount, but I am unsure if this would be anything near accurate?

It would be useful to have a resuable function/procedure to calculate the time of a routine, and use it something like this:

```<code>// < prepare for calcuation of code
...
ExecuteSomeCode; // < code to test
...
// < stop calcuating code and return time it took to process
</code>```

I look forward to hearing some suggestions.

Thanks.

Craig.

答:
You didn't specify your Delphi version, but Delphi XE has a TStopWatch declared in unit Diagnostics. This will allow you to measure the runtime with reasonable precision.</p>

```<code>uses
  Diagnostics;
var
  sw: TStopWatch;
begin
  sw := TStopWatch.StartNew;
  <dosomething>
  Writeln(Format('runtime: %d ms', [sw.ElapsedMilliseconds]));
end;
</code>```

Title: Calculating the speed of routines?

Body:
What would be the best and most accurate way to determine how long it took to process a routine, such as a procedure of function?

I ask because I am currently trying to optimize a few functions in my Application, when i test the changes it is hard to determine just by looking at it if there was any improvements at all. So if I could return an accurate or near accurate time it took to process a routine, I then have a more clear idea of how well, if any changes to the code have been made.

I considered using GetTickCount, but I am unsure if this would be anything near accurate?

It would be useful to have a resuable function/procedure to calculate the time of a routine, and use it something like this:

// < prepare for calcuation of code
...
ExecuteSomeCode; // < code to test
...
// < stop calcuating code and return time it took to process

I look forward to hearing some suggestions.

Thanks.

Craig.

Body:
You didn't specify your Delphi version, but Delphi XE has a TStopWatch declared in unit Diagnostics. This will allow you to measure the runtime with reasonable precision.

uses
  Diagnostics;
var
  sw: TStopWatch;
begin
  sw := TStopWatch.StartNew;
  <dosomething>
  Writeln(Format('runtime: %d ms', [sw.ElapsedMilliseconds]));
end;


问:
Could not index class module-info.class atlog4j-api.jar: java.lang.IllegalStateException: Unknown tag! pos=4 poolCount = 24
We have updated log4j jar from log4j-api-2.7.jar to log4j-api-2.10.0.jar. We are getting below warning at the startup of JBoss(we are using JBoss-EAP-7.0).

2018-09-05 05:31:28,669 WARN  [org.jboss.as.server.deployment] (MSC
  service thread 1-2) WFLYSRV0003: Could not index class
  module-info.class at /content/project.ear/shared/log4j-api.jar:
  java.lang.IllegalStateException: Unknown tag! pos=4 poolCount = 24    at
  org.jboss.jandex.Indexer.processConstantPool(Indexer.java:1416)   at
  org.jboss.jandex.Indexer.index(Indexer.java:1450)     at
  org.jboss.as.server.deployment.annotation.ResourceRootIndexer.indexResourceRoot(ResourceRootIndexer.java:99)
    at
  org.jboss.as.server.deployment.annotation.AnnotationIndexProcessor.deploy(AnnotationIndexProcessor.java:51)
    at
  org.jboss.as.server.deployment.DeploymentUnitPhaseService.start(DeploymentUnitPhaseService.java:165)
    at
  org.jboss.msc.service.ServiceControllerImpl$StartTask.startService(ServiceControllerImpl.java:2032)
    at
  org.jboss.msc.service.ServiceControllerImpl$StartTask.run(ServiceControllerImpl.java:1955)
    at
  java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
    at
  java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
    at java.lang.Thread.run(Thread.java:748)

After my analysis it seems that module-info.class is newly introduced in log4j-api-2.10.0.jar and now it is not able to index that class on startup. It is using JBoss's jandex-2.0.2.Final-redhat-1.jar for the same which is coming from dependency information of eap-runtime-artifacts-7.0.5.GA.pom.

Can anyone please help me to resolve this issue?

Thanks in Advance.

答:
This is a warning message, it occured because of jandex supports Java9 is to simply ignore module-info.class files in dependent archives. To avoid this warning messages, replace jandex jar present in (wildfly_HOME\modules\system\layers\base\org\jboss\jandex\main\jande-version.jar with jandex-2.0.5.Final-redhat-1 and the respective module.xml also.
Ref : https://issues.redhat.com/browse/JBEAP-15262
      https://issues.redhat.com/browse/JBEAP-15715</p>


问:
How to check permission and request permission in (Easy coding & easy to understand)
I search for Run-Time-Permission in android and I find lots of links but I see there is complex code.

Note: I share my simple code here so it's helpful for a new developer or Fraser. Also, I didn't use any third party library here.

答:
First of all, Write permission in Manifest file(I take some bagic permissions):

```<code><uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
</code>```

Now I make two methods checkPermission() AND requestPermission() also @Override one method name is onRequestPermissionsResult() this is take care of result.

Now I'll show you how it looks like:

```<code>private boolean checkPermission() {
        int internetPermission = ContextCompat.checkSelfPermission(getApplicationContext(), INTERNET);
        int cameraPermission = ContextCompat.checkSelfPermission(getApplicationContext(), CAMERA);
        int readStoragePermission = ContextCompat.checkSelfPermission(getApplicationContext(), READ_EXTERNAL_STORAGE);
        int writeStoragePermission = ContextCompat.checkSelfPermission(getApplicationContext(), WRITE_EXTERNAL_STORAGE);

        return internetPermission == PackageManager.PERMISSION_GRANTED &&
                cameraPermission == PackageManager.PERMISSION_GRANTED &&
                readStoragePermission == PackageManager.PERMISSION_GRANTED &&
                writeStoragePermission == PackageManager.PERMISSION_GRANTED;
    }
</code>```

You see in above code there is define INTERNET, CAMERA etc.. This is an import by clicking Alt + Enter And it is look like see below code:

```<code>import static android.Manifest.permission.CAMERA;
import static android.Manifest.permission.INTERNET;
import static android.Manifest.permission.READ_EXTERNAL_STORAGE;
import static android.Manifest.permission.WRITE_EXTERNAL_STORAGE;
</code>```

Now Please see below code of requestPermission() Method :

```<code>private void requestPermission() {
        ActivityCompat.requestPermissions(MainActivity.this, new String[]{INTERNET, CAMERA, READ_EXTERNAL_STORAGE, WRITE_EXTERNAL_STORAGE}, 1);
    }
</code>```

Now the Last method is onRequestPermissionsResult(). In this method you can see either permission is GRANTED or DENY:

```<code>@Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {

        switch (requestCode) {

            case 1:
                if (grantResults.length > 0) {
                    boolean internet = grantResults[0] == PackageManager.PERMISSION_GRANTED;
                    boolean camera = grantResults[1] == PackageManager.PERMISSION_GRANTED;
                    boolean readStorage = grantResults[2] == PackageManager.PERMISSION_GRANTED;
                    boolean writeStorage = grantResults[3] == PackageManager.PERMISSION_GRANTED;

                    if (internet && camera && readStorage && writeStorage) {
                        init();
                       // Permission GRANTED (Here write your code what you want).
                    } else {
                        // Permission DENY (If user click on DENY then finish the activity);
                        finish();
                    }
                }
        }
    }
</code>```

Great you are done with checkPermission & requestPermission.

NOTE:

This above code is working for Activity. There is a minor change in the fragment.

If I use this code in fragment then what should I change:

You want to just change in requestPermission() Method:

```<code>private void requestPermission() {
            requestPermissions(new String[]{INTERNET, CAMERA, READ_EXTERNAL_STORAGE, WRITE_EXTERNAL_STORAGE}, 1);
        }
</code>```

Body:
First of all, Write permission in Manifest file(I take some bagic permissions):

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

Now I make two methods checkPermission() AND requestPermission() also @Override one method name is onRequestPermissionsResult() this is take care of result.

Now I'll show you how it looks like:

private boolean checkPermission() {
        int internetPermission = ContextCompat.checkSelfPermission(getApplicationContext(), INTERNET);
        int cameraPermission = ContextCompat.checkSelfPermission(getApplicationContext(), CAMERA);
        int readStoragePermission = ContextCompat.checkSelfPermission(getApplicationContext(), READ_EXTERNAL_STORAGE);
        int writeStoragePermission = ContextCompat.checkSelfPermission(getApplicationContext(), WRITE_EXTERNAL_STORAGE);

        return internetPermission == PackageManager.PERMISSION_GRANTED &&
                cameraPermission == PackageManager.PERMISSION_GRANTED &&
                readStoragePermission == PackageManager.PERMISSION_GRANTED &&
                writeStoragePermission == PackageManager.PERMISSION_GRANTED;
    }

You see in above code there is define INTERNET, CAMERA etc.. This is an import by clicking Alt + Enter And it is look like see below code:

import static android.Manifest.permission.CAMERA;
import static android.Manifest.permission.INTERNET;
import static android.Manifest.permission.READ_EXTERNAL_STORAGE;
import static android.Manifest.permission.WRITE_EXTERNAL_STORAGE;

Now Please see below code of requestPermission() Method :

private void requestPermission() {
        ActivityCompat.requestPermissions(MainActivity.this, new String[]{INTERNET, CAMERA, READ_EXTERNAL_STORAGE, WRITE_EXTERNAL_STORAGE}, 1);
    }

Now the Last method is onRequestPermissionsResult(). In this method you can see either permission is GRANTED or DENY:

@Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {

        switch (requestCode) {

            case 1:
                if (grantResults.length > 0) {
                    boolean internet = grantResults[0] == PackageManager.PERMISSION_GRANTED;
                    boolean camera = grantResults[1] == PackageManager.PERMISSION_GRANTED;
                    boolean readStorage = grantResults[2] == PackageManager.PERMISSION_GRANTED;
                    boolean writeStorage = grantResults[3] == PackageManager.PERMISSION_GRANTED;

                    if (internet && camera && readStorage && writeStorage) {
                        init();
                       // Permission GRANTED (Here write your code what you want).
                    } else {
                        // Permission DENY (If user click on DENY then finish the activity);
                        finish();
                    }
                }
        }
    }

Great you are done with checkPermission & requestPermission.

NOTE:

This above code is working for Activity. There is a minor change in the fragment.

If I use this code in fragment then what should I change:

You want to just change in requestPermission() Method:

private void requestPermission() {
            requestPermissions(new String[]{INTERNET, CAMERA, READ_EXTERNAL_STORAGE, WRITE_EXTERNAL_STORAGE}, 1);
        }


问:
How to empty a directory in PHP except specific files
I'm creating a cron job that will autoflush the tmp directory everyday to make sure the tmp directory is not flooded with unwanted files.

However i want to delete all files and folders in the tmp directory except some files like .htaccess i'm using the below code, but is giving an error

```<code>    $filesToKeep = array(
                            '.htaccess'
                            // 'i.php',
                            // 'c.php'
                        );

    $dir = '../tmp/';

    $it = new RecursiveDirectoryIterator($dir, RecursiveDirectoryIterator::SKIP_DOTS);
    $files = new RecursiveIteratorIterator($it, RecursiveIteratorIterator::CHILD_FIRST);

    foreach($files as $file)
        {
            if (! in_array($file, $filesToKeep))
                {
                    if ($file->isDir())
                        rmdir($file->getRealPath());
                }
            else
                unlink($file->getRealPath());
        }
</code>```

Warning: rmdir(D:\Development(s)\Project(s)\blog\app\tmp\error_pages): Directory not empty

before this is used to run the below code which ran perfectly but also used to delete the .htaccess file

```<code>    $dir = '../tmp/';

    $it = new RecursiveDirectoryIterator($dir, RecursiveDirectoryIterator::SKIP_DOTS);
    $files = new RecursiveIteratorIterator($it, RecursiveIteratorIterator::CHILD_FIRST);

    foreach($files as $file)
        {

            if ($file->isDir())
                rmdir($file->getRealPath());
            else
                unlink($file->getRealPath());
        }
</code>```

答:
Your error states that you can't delete non-empty dir.

So just check if dir is empty first.

```<code>$filesToKeep = ['.htaccess', /*'i.php', 'c.php'*/];

$dir = '../tmp/';

$it = new RecursiveDirectoryIterator($dir, RecursiveDirectoryIterator::SKIP_DOTS);
$files = new RecursiveIteratorIterator($it, RecursiveIteratorIterator::CHILD_FIRST);

foreach ($files as $file) {
    if (in_array($file->getBasename(), $filesToKeep)) {
        continue;
    }

    if (!$file->isDir()) {
        unlink($file->getRealPath());
        continue;
    }

    if (isEmptyDir($file->getRealPath())) {
        rmdir($file->getRealPath());
    }
}

function isEmptyDir($dir){
    $files = scandir($dir);

    // $files contains `..` and `.` along with list of files
    return count($files) <= 2;
}
</code>```

Body:
I'm creating a cron job that will autoflush the tmp directory everyday to make sure the tmp directory is not flooded with unwanted files.

However i want to delete all files and folders in the tmp directory except some files like .htaccess i'm using the below code, but is giving an error

    $filesToKeep = array(
                            '.htaccess'
                            // 'i.php',
                            // 'c.php'
                        );

    $dir = '../tmp/';

    $it = new RecursiveDirectoryIterator($dir, RecursiveDirectoryIterator::SKIP_DOTS);
    $files = new RecursiveIteratorIterator($it, RecursiveIteratorIterator::CHILD_FIRST);

    foreach($files as $file)
        {
            if (! in_array($file, $filesToKeep))
                {
                    if ($file->isDir())
                        rmdir($file->getRealPath());
                }
            else
                unlink($file->getRealPath());
        }

Warning: rmdir(D:\Development(s)\Project(s)\blog\app\tmp\error_pages): Directory not empty

before this is used to run the below code which ran perfectly but also used to delete the .htaccess file

    $dir = '../tmp/';

    $it = new RecursiveDirectoryIterator($dir, RecursiveDirectoryIterator::SKIP_DOTS);
    $files = new RecursiveIteratorIterator($it, RecursiveIteratorIterator::CHILD_FIRST);

    foreach($files as $file)
        {

            if ($file->isDir())
                rmdir($file->getRealPath());
            else
                unlink($file->getRealPath());
        }

Body:
Your error states that you can't delete non-empty dir.

So just check if dir is empty first.

$filesToKeep = ['.htaccess', /*'i.php', 'c.php'*/];

$dir = '../tmp/';

$it = new RecursiveDirectoryIterator($dir, RecursiveDirectoryIterator::SKIP_DOTS);
$files = new RecursiveIteratorIterator($it, RecursiveIteratorIterator::CHILD_FIRST);

foreach ($files as $file) {
    if (in_array($file->getBasename(), $filesToKeep)) {
        continue;
    }

    if (!$file->isDir()) {
        unlink($file->getRealPath());
        continue;
    }

    if (isEmptyDir($file->getRealPath())) {
        rmdir($file->getRealPath());
    }
}

function isEmptyDir($dir){
    $files = scandir($dir);

    // $files contains `..` and `.` along with list of files
    return count($files) <= 2;
}


问:
how can I format this string as the question asks?
I am stumped on a homework problem. I don't need to describe it because its all explained in the image. But I have no clue where to start I'm new to Python and I'm on a time limit so this is my only option, thanks guys.

答:
You could use something like this,

```<code>user_input = input()
lines = user_input.split(',')

multi_table = [[ int(num) for num in line.split()] for line in lines]

for l1 in multi_table:
    line = ""
    for l2 in l1:
        line += f" {l2} |"
    print(line[:-1].strip())
</code>```

And output will be:

```<code>1 | 2 | 3
2 | 4 | 6
3 | 6 | 9
</code>```

Hope it helps you!

Body:
You could use something like this,

user_input = input()
lines = user_input.split(',')

multi_table = [[ int(num) for num in line.split()] for line in lines]

for l1 in multi_table:
    line = ""
    for l2 in l1:
        line += f" {l2} |"
    print(line[:-1].strip())

And output will be:

1 | 2 | 3
2 | 4 | 6
3 | 6 | 9

Hope it helps you!


问:
Result set larger than one row when Corda node use postgresql and schema
I'm currently trying to have 2 node (one notary , one normal node) using the same Postgresql DB for storing data (instead of the embedded H2), but with a different schema for each (node schema, notary schema) .

Ah , I'm using the non-enterprise version btw, version 4.3 .

The notary node is the first one to start, it creates the needed tables in the notary schema , all seems fine there .

But when the 'normal' node boot, it crash saying :

```<code>[ERROR] 10:17:50+0000 [main] changelog.ChangeSet. - Change Set migration/node-core.changelog-postgres-blob.xml::modify checkpoint_value column type::R3.Corda failed.  Error: Migration failed for change set mig │
│      Reason:                                                                                │
│           master.changelog.json : liquibase.precondition.core.SqlPrecondition@7c682e26 : Result set larger than one row                                                                                │
│  {changeSet=migration/node-core.changelog-postgres-blob.xml::modify checkpoint_value column type::R3.Corda, databaseChangeLog=master.changelog.json}                                                              │
│ [ERROR] 10:17:50+0000 [main] internal.NodeStartupLogging. - Exception during node registration: Could not create the DataSource: Migration failed for change set migration/node-core.changelog-postgres-blob.xml: │
│      Reason:                                                                                │
│           master.changelog.json : liquibase.precondition.core.SqlPrecondition@7c682e26 : Result set larger than one row                                                                                │
│  [errorCode=14m37zv, moreInformationAt=https://errors.corda.net/OS/4.3/14m37zv]                                                                                │
[ERROR] 10:17:50+0000 [main] internal.NodeStartupLogging. - Exception during node startup: net.corda.core.utilities.Try$Failure cannot be cast to net.corda.core.utilities.Try$Success [errorCode=rmnkpl, moreInf │

</code>```

The node.conf I have for the notary is the following :

```<code>dataSourceProperties: {
    dataSourceClassName="org.postgresql.ds.PGSimpleDataSource"
    dataSource.url="jdbc:postgresql://psql-path:5432/postgres?currentSchema=notary"
    dataSource.user="dbUser"
    dataSource.password="xxxxxx"
}
</code>```

And the one for the 'normal' node is :

```<code>dataSourceProperties: {
    dataSourceClassName="org.postgresql.ds.PGSimpleDataSource"
    dataSource.url="jdbc:postgresql://psql-path:5432/postgres?currentSchema=node"
    dataSource.user="dbUser"
    dataSource.password="xxxxxx"
}

</code>```

So as you can see, the only difference is the ?currentSchema value .

Am I missing something ?

EDIT :

in the doc , they are saying :

If your PostgresSQL database is hosting multiple schema instances (using the JDBC URL currentSchema=my_schema) for different Corda nodes, you will need to create a hibernate_sequence sequence object manually for each subsequent schema added after the first instance. Corda doesn’t provision Hibernate with a schema namespace setting and a sequence object may be not created. Run the DDL statement and replace my_schema with your schema namespace:

I have done that and when connecting to the db , I can see taht for both schema I have tables created . Though for the notary I have 32 tables and only 26 for the 'normal' node .

答:
Classic case of documentation overlooking , the solution is :

If your PostgresSQL database is hosting multiple schema instances (using the JDBC URL currentSchema=my_schema) for different Corda nodes, you will need to create a hibernate_sequence sequence object manually for each subsequent schema added after the first instance. Corda doesn’t provision Hibernate with a schema namespace setting and a sequence object may be not created. Run the DDL statement and replace my_schema with your schema namespace:

Body:
I'm currently trying to have 2 node (one notary , one normal node) using the same Postgresql DB for storing data (instead of the embedded H2), but with a different schema for each (node schema, notary schema) .

Ah , I'm using the non-enterprise version btw, version 4.3 .

The notary node is the first one to start, it creates the needed tables in the notary schema , all seems fine there .

But when the 'normal' node boot, it crash saying :

[ERROR] 10:17:50+0000 [main] changelog.ChangeSet. - Change Set migration/node-core.changelog-postgres-blob.xml::modify checkpoint_value column type::R3.Corda failed.  Error: Migration failed for change set mig │
│      Reason:                                                                                │
│           master.changelog.json : liquibase.precondition.core.SqlPrecondition@7c682e26 : Result set larger than one row                                                                                │
│  {changeSet=migration/node-core.changelog-postgres-blob.xml::modify checkpoint_value column type::R3.Corda, databaseChangeLog=master.changelog.json}                                                              │
│ [ERROR] 10:17:50+0000 [main] internal.NodeStartupLogging. - Exception during node registration: Could not create the DataSource: Migration failed for change set migration/node-core.changelog-postgres-blob.xml: │
│      Reason:                                                                                │
│           master.changelog.json : liquibase.precondition.core.SqlPrecondition@7c682e26 : Result set larger than one row                                                                                │
│  [errorCode=14m37zv, moreInformationAt=https://errors.corda.net/OS/4.3/14m37zv]                                                                                │
[ERROR] 10:17:50+0000 [main] internal.NodeStartupLogging. - Exception during node startup: net.corda.core.utilities.Try$Failure cannot be cast to net.corda.core.utilities.Try$Success [errorCode=rmnkpl, moreInf │

The node.conf I have for the notary is the following :

dataSourceProperties: {
    dataSourceClassName="org.postgresql.ds.PGSimpleDataSource"
    dataSource.url="jdbc:postgresql://psql-path:5432/postgres?currentSchema=notary"
    dataSource.user="dbUser"
    dataSource.password="xxxxxx"
}

And the one for the 'normal' node is :

dataSourceProperties: {
    dataSourceClassName="org.postgresql.ds.PGSimpleDataSource"
    dataSource.url="jdbc:postgresql://psql-path:5432/postgres?currentSchema=node"
    dataSource.user="dbUser"
    dataSource.password="xxxxxx"
}

So as you can see, the only difference is the ?currentSchema value .

Am I missing something ?

EDIT :

in the doc , they are saying :

If your PostgresSQL database is hosting multiple schema instances (using the JDBC URL currentSchema=my_schema) for different Corda nodes, you will need to create a hibernate_sequence sequence object manually for each subsequent schema added after the first instance. Corda doesn’t provision Hibernate with a schema namespace setting and a sequence object may be not created. Run the DDL statement and replace my_schema with your schema namespace:

I have done that and when connecting to the db , I can see taht for both schema I have tables created . Though for the notary I have 32 tables and only 26 for the 'normal' node .


问:
How to pass column name into parameter in pandas
I am trying to create a xml from a dataframe .  Issue that I am facing i want pass column into paramter and its not working.

```<code>    ORDER_NO        1175        1304          1421
   7283630          2019-12-04  2019-12-10   2019-12-12
   7283650          2019-12-25  NaN          2019-12-20
</code>```

My code

```<code>header = """<ORD>{}</ORD>"""
body ="""
<osi:ORDSTSINF types:STSCDE="{}">
<DTM>{}</DTM>
</osi:ORDSTSINF>
<osi:ORDSTSINF types:STSCDE="{}">
<DTM>{}</DTM>
</osi:ORDSTSINF>
<osi:ORDSTSINF types:STSCDE="{}">
<DTM>{}</DTM>
</osi:ORDSTSINF>"""

for row in df.itertuples():
    with open(f'{row[1]}.xml', 'w') as f:
        f.write(header.format(row[1]))
        f.write(body.format(col[2], row[2], col[3],row[3],col[4],row[4]))
</code>```

I want to pass then columnname wherever STS={} is coming.

Expected output

```<code><ORD> 7283630</ORD>
<osi:ORDSTSINF types:STSCDE="1175">
<DTM>2019-12-04</DTM>
<osi:ORDSTSINF types:STSCDE="1304">
<DTM>2019-12-10</DTM>
<osi:ORDSTSINF types:STSCDE="1421">
<DTM>22019-12-12</DTM>
</code>```

How can this be done in python?

答:
Because python count from 0 in indexing subtract 1 from selecting columns names like cols[2] to cols[1] for all values:

```<code>cols = df.columns
for row in df.itertuples():
    with open(f'{row[1]}.xml', 'w') as f:
        f.write(header.format(row[1]))
        f.write(body.format(cols[1], row[2], cols[2],row[3],cols[3],row[4]))
</code>```

```<code><ORD>7283630</ORD>
<osi:ORDSTSINF types:STSCDE="1175">
<DTM>2019-12-04</DTM>
</osi:ORDSTSINF>
<osi:ORDSTSINF types:STSCDE="1304">
<DTM>2019-12-10</DTM>
</osi:ORDSTSINF>
<osi:ORDSTSINF types:STSCDE="1421">
<DTM>2019-12-12</DTM>
</osi:ORDSTSINF>
</code>```

EDIT:

More dynamic solution with loop:

```<code>header = """<ORD>{}</ORD>"""
body ="""
<osi:ORDSTSINF types:STSCDE="{}">
<DTM>{}</DTM>"""

cols = df.columns
for row in df.itertuples():
    with open(f'{row[1]}.xml', 'w') as f:
        f.write(header.format(row[1]))
        for c, r in zip(row[2:], cols[1:]):
            f.write(body.format(r, c))
</code>```

EDIT1: For mit missing values add notna:

```<code>header = """<ORD>{}</ORD>"""
body ="""
<osi:ORDSTSINF types:STSCDE="{}">
<DTM>{}</DTM>"""

cols = df.columns
for row in df.itertuples():
    with open(f'{row[1]}.xml', 'w') as f:
        f.write(header.format(row[1]))
        for c, r in zip(row[2:], cols[1:]):
            if pd.notna(c):
                f.write(body.format(r, c))
</code>```

Body:
I am trying to create a xml from a dataframe .  Issue that I am facing i want pass column into paramter and its not working.

    ORDER_NO        1175        1304          1421
   7283630          2019-12-04  2019-12-10   2019-12-12
   7283650          2019-12-25  NaN          2019-12-20

My code

header = """<ORD>{}</ORD>"""
body ="""
<osi:ORDSTSINF types:STSCDE="{}">
<DTM>{}</DTM>
</osi:ORDSTSINF>
<osi:ORDSTSINF types:STSCDE="{}">
<DTM>{}</DTM>
</osi:ORDSTSINF>
<osi:ORDSTSINF types:STSCDE="{}">
<DTM>{}</DTM>
</osi:ORDSTSINF>"""

for row in df.itertuples():
    with open(f'{row[1]}.xml', 'w') as f:
        f.write(header.format(row[1]))
        f.write(body.format(col[2], row[2], col[3],row[3],col[4],row[4]))

I want to pass then columnname wherever STS={} is coming.

Expected output

<ORD> 7283630</ORD>
<osi:ORDSTSINF types:STSCDE="1175">
<DTM>2019-12-04</DTM>
<osi:ORDSTSINF types:STSCDE="1304">
<DTM>2019-12-10</DTM>
<osi:ORDSTSINF types:STSCDE="1421">
<DTM>22019-12-12</DTM>

How can this be done in python?

Body:
Because python count from 0 in indexing subtract 1 from selecting columns names like cols[2] to cols[1] for all values:

cols = df.columns
for row in df.itertuples():
    with open(f'{row[1]}.xml', 'w') as f:
        f.write(header.format(row[1]))
        f.write(body.format(cols[1], row[2], cols[2],row[3],cols[3],row[4]))

<ORD>7283630</ORD>
<osi:ORDSTSINF types:STSCDE="1175">
<DTM>2019-12-04</DTM>
</osi:ORDSTSINF>
<osi:ORDSTSINF types:STSCDE="1304">
<DTM>2019-12-10</DTM>
</osi:ORDSTSINF>
<osi:ORDSTSINF types:STSCDE="1421">
<DTM>2019-12-12</DTM>
</osi:ORDSTSINF>

EDIT:

More dynamic solution with loop:

header = """<ORD>{}</ORD>"""
body ="""
<osi:ORDSTSINF types:STSCDE="{}">
<DTM>{}</DTM>"""

cols = df.columns
for row in df.itertuples():
    with open(f'{row[1]}.xml', 'w') as f:
        f.write(header.format(row[1]))
        for c, r in zip(row[2:], cols[1:]):
            f.write(body.format(r, c))

EDIT1: For mit missing values add notna:

header = """<ORD>{}</ORD>"""
body ="""
<osi:ORDSTSINF types:STSCDE="{}">
<DTM>{}</DTM>"""

cols = df.columns
for row in df.itertuples():
    with open(f'{row[1]}.xml', 'w') as f:
        f.write(header.format(row[1]))
        for c, r in zip(row[2:], cols[1:]):
            if pd.notna(c):
                f.write(body.format(r, c))


问:
How to add meta description/title to contact page in opencart
The contact page of my site is https://example.com/contact_us . On google, it shows like

which is not very good.
It seems there is no way to edit from admin panel the meta title and meta description of this page. neither on theme panel.
So, how to edit this from core files?

```<code>catalog/view/theme/default/template/information/contact.tpl
</code>```

seems not having any related, and don't see a way to edit loading header just for this one page

can you have any idea ?

答:
I hope it's 100% working for you.

Find the controller Path of Page. you wish to edit and then do the below,

PATH : catalog\controller\information\contact.php

Find:

```<code>$this->document->setTitle($this->language->get('heading_title'));
</code>```

Add After:

```<code>$this->document->setDescription('My description, this is where i type my text after i remove this text.');
$this->document->setKeywords('my, keyword, this, is, the place, holder, for, my, keywords');
</code>```

Body:
The contact page of my site is https://example.com/contact_us . On google, it shows like

which is not very good.
It seems there is no way to edit from admin panel the meta title and meta description of this page. neither on theme panel.
So, how to edit this from core files?

catalog/view/theme/default/template/information/contact.tpl

seems not having any related, and don't see a way to edit loading header just for this one page

can you have any idea ?

Body:
I hope it's 100% working for you.

Find the controller Path of Page. you wish to edit and then do the below,

PATH : catalog\controller\information\contact.php

Find:

$this->document->setTitle($this->language->get('heading_title'));

Add After:

$this->document->setDescription('My description, this is where i type my text after i remove this text.');
$this->document->setKeywords('my, keyword, this, is, the place, holder, for, my, keywords');


问:
How do you fight design complexity?
I often find myself fighting overengineering -- the person in charge of designing the software comes up with an architecture that's, way, way overcomplicated.

It's all fine and dandy to have all the esoteric features that users will never know about and get that sense of achievement when you're doing something that all the magazine articles are telling you is the latest, cool thing, but we are going to spend half of our  engineering time on this monument to our cleverness, and not, you know, the actual product that our users need and upper management expects to be completed within a reasonable or at least a bounded time frame.

And you'll probably just have to revert back to the simpler solution anyway when you start running out of time, that is, if you get that chance.

We've all heard the refrain: Keep It Simple, Stupid™.

How do you fight with overcomplexity in your team?

One example I've had to work with repeatedly lately is when the decision has been made to go to a fully denormalized database design rather than an RDBMS. "because it's faster!" Fully denormalized databases are really hard to get right, and are only appropriate for really specialized data problems like Flickr or ebay, and which can be extremely expensive in terms of developer time relative to the rest of your development.

答:
Your example isn't really a complicated design, it's a design choice that you don't agree with.  Since you're working on the code, you could easily be right because many of these decisions are made by people reading an article in an article and thinking it sounds like a good goal, or the decision could have been made by someone who ran into problems before and was trying to prevent it from happening again.

Personally I've done a lot of stuff the easy way and a lot of it the hard way, and I'm never happy when I choose doing something the easy way over the hard way.  Now I've learned tricks like "never pass around a naked collection, always wrap it in a business class".

If I were to explain the reasoning behind that to someone who hadn't been through the same experiences, they wouldn't understand it until they tried comparing the "easy way" to the "hard way" a few times.

OwnerDisplayName: ʞɔıu

ContentLicense: CC BY-SA 2.5

Title: How do you fight design complexity?

LastEditorDisplayName: philippe

OwnerDisplayName: Bill K


问:
C struct with a pointer to be wrapped in a unique_ptr
I have a memory struct as shown below.

```<code>struct memoryStruct {
    uint8_t* memory;
    size_t size;
};
</code>```

My code requires me to call free(memory) at multiple places in my code. To avoid this scenario I am thinking of wrapping it in a unique_ptr.

I have the following

```<code>struct memoryStruct {
    uint8_t* memory;
    size_t size;
};

struct memoryStructDeleter {
    void operator()(memoryStruct* p) const
    {
        free(p);
    }
};
</code>```

How do I initialize m_chunk shown below. I want to allocate a memory of size using malloc to memory field and update size accordingly.

```<code>std::unique_ptr<memoryStruct> m_chunk;
</code>```

答:
Assuming you cannot change the struct at all (you should, if you can) and you only want to call malloc and free and not new and delete (which are superior), you can do the following:

```<code>struct memoryStructDeleter {
    void operator()(memoryStruct* p) const
    {
        if (p) {
            if (p->memory) {
                 free(p->memory);
            }
            free(p);
        }
    }
};

std::unique_ptr<memoryStruct, memoryStructDeleter> create(size_t s) {
    std::unique_ptr<memoryStruct, memoryStructDeleter> ret(static_cast<memoryStruct*>(malloc(sizeof(memoryStruct))));
    if (!ret) {
        return nullptr;
    }
    ret->memory = static_cast<uint8_t*>(malloc(s * sizeof(uint8_t)));
    if (ret->memory) {
        return ret;
    } else {
        return nullptr;
    }
}
</code>```

Body:
I have a memory struct as shown below.

struct memoryStruct {
    uint8_t* memory;
    size_t size;
};

My code requires me to call free(memory) at multiple places in my code. To avoid this scenario I am thinking of wrapping it in a unique_ptr.

I have the following

struct memoryStruct {
    uint8_t* memory;
    size_t size;
};

struct memoryStructDeleter {
    void operator()(memoryStruct* p) const
    {
        free(p);
    }
};

How do I initialize m_chunk shown below. I want to allocate a memory of size using malloc to memory field and update size accordingly.

std::unique_ptr<memoryStruct> m_chunk;

Body:
Assuming you cannot change the struct at all (you should, if you can) and you only want to call malloc and free and not new and delete (which are superior), you can do the following:

struct memoryStructDeleter {
    void operator()(memoryStruct* p) const
    {
        if (p) {
            if (p->memory) {
                 free(p->memory);
            }
            free(p);
        }
    }
};

std::unique_ptr<memoryStruct, memoryStructDeleter> create(size_t s) {
    std::unique_ptr<memoryStruct, memoryStructDeleter> ret(static_cast<memoryStruct*>(malloc(sizeof(memoryStruct))));
    if (!ret) {
        return nullptr;
    }
    ret->memory = static_cast<uint8_t*>(malloc(s * sizeof(uint8_t)));
    if (ret->memory) {
        return ret;
    } else {
        return nullptr;
    }
}


问:
Concatenate strings from array in PHP ignoring blanks
Similar to this question but for PHP.  I want to concatenate an array of strings but ignore blanks.

For instance, suppose I want to build a full_name attribute in Laravel using $this->title, $this->first_name, and $this->last_name, each separated by single space.  The simplest thought I had was to put them all into an array and pass it into implode() as in below:

implode(' ', [$this->title, $this->first_name, $this->last_name]);
```

<p>However I don't know whether those values are actually going to be set or not.  And if they are set, I don't want empty strings to pollute the output with multiple spaces between non-empty elements.  Is there a built-in function or at least a simpler/shorter way to do the below?</p>

<pre class="lang-php prettyprint-override"><code>public function concatenateStringsFromArray($glue = ' ', $arrayOfStrings)
{
    $result = '';
    foreach($arrayOfStrings as $piece)
        $result .= isset($piece) ? $piece . $glue : '';
    return $result;
}
</code>```

答:
array_map with trim as function removes all spaces at the beginning and end of a string, not in the middle.
array_filter removes then all elements that are empty, including zero and "".

```<code>$arrayOfStrings = ['a', 'b    c',null, '    ','ef ','  012'];

$result = implode(' ', array_filter(array_map('trim',$arrayOfStrings)));

echo '```'.$result;  //a b    c ef 012
```

I wrote everything on one line because you wanted it to be short.

Body:
Similar to this question but for PHP.  I want to concatenate an array of strings but ignore blanks.

For instance, suppose I want to build a full_name attribute in Laravel using $this->title, $this->first_name, and $this->last_name, each separated by single space.  The simplest thought I had was to put them all into an array and pass it into implode() as in below:

implode(' ', [$this->title, $this->first_name, $this->last_name]);

However I don't know whether those values are actually going to be set or not.  And if they are set, I don't want empty strings to pollute the output with multiple spaces between non-empty elements.  Is there a built-in function or at least a simpler/shorter way to do the below?

public function concatenateStringsFromArray($glue = ' ', $arrayOfStrings)
{
    $result = '';
    foreach($arrayOfStrings as $piece)
        $result .= isset($piece) ? $piece . $glue : '';
    return $result;
}

Body:
array_map with trim as function removes all spaces at the beginning and end of a string, not in the middle.
array_filter removes then all elements that are empty, including zero and "".

$arrayOfStrings = ['a', 'b    c',null, '    ','ef ','  012'];

$result = implode(' ', array_filter(array_map('trim',$arrayOfStrings)));

echo '<pre>'.$result;  //a b    c ef 012

I wrote everything on one line because you wanted it to be short.


问:
Is there a tool for assisting with ruby/rails internationalization?
I'm looking for something that will help me to internationalize an existing rails application using I18n. Ideally it would locate string constants (with parameters) and allow me to extract those into a .yml or .rb file replacing the original string with the appropriate t(...) call. Also, or alternatively, a macro to do the same on selected text. I mainly use eclipse but could use something else for this task (vim?) as long as it is free to use.

There appears to be a plugin for TextMate that does the job (though mainly for new code) and I know that rgettext/xgettext will do a similar job for gettext localization but I was wondering if anyone knew of anything to make the job easier with I18n.

答:
Here are a few Gems, github search for 'i18n' in Ruby:

https://github.com/balinterdi/i15r

https://github.com/zigzag/ready_for_i18n

https://github.com/japetheape/gettext_to_i18n

https://github.com/Bertg/i18n_extractor

From my cursory assessment, i15r looks the best and the most up-to-date. I'll likely using one of these soon (chances are i15r) to at least get a starting point - inserting <%=t "translate me please" -%> hundreds of times will drive me nuts before too long; this could be a shortcut for the initial phase.

Hope this helps!


答:
Try this:

```<code>import re
for line in lines:
 print(re.sub(' ',' | ',line))
</code>```

or

In your case:

```<code>for l in mult_table:
  for i,x in enumerate(l):
    if i != len(l)-1:
      print(x,end=' | ')
    else:
      print(x,end=' ')

  print('')
</code>```

Title: how can I format this string as the question asks?

Body: I am stumped on a homework problem. I don't need to describe it because its all explained in the image. But I have no clue where to start I'm new to Python and I'm on a time limit so this is my only option, thanks guys.

Body:
Try this:

import re
for line in lines:
 print(re.sub(' ',' | ',line))

or

In your case:

for l in mult_table:
  for i,x in enumerate(l):
    if i != len(l)-1:
      print(x,end=' | ')
    else:
      print(x,end=' ')

  print('')


问:
Need help in converting old php code to php 7.4.2
Below is the small block of code in old version of php.

It have some deprecated methods can anyone help me to convert them into PHP 7 compatible PDO methods.

```<code>    // Delete the message residing at the tail end of their list so they cannot archive more than 100 PMs ..................
$sqldeleteTail = mysql_query("SELECT * FROM private_messages WHERE to_id = '$to' ORDER BY time_sent DESC LIMIT 0,100");
    $dci = 1;
    while($row = mysql_fetch_array($sqldeleteTail)){
        $pm_id = $row['memberID'];
        if ($dci > 99){
            $deleteTail = mysql_query("DELETE FROM private_msg WHERE id='$pm_id'");
        }
        $dci++;
    }
</code>```

Any help would be appreciated.

答:
This is the updated code as per PHP 7 and above

```<code>  // $conn is the instance of your database connection here.
$sqldeleteTail = "SELECT * FROM private_messages WHERE to_id = '$to' ORDER BY time_sent DESC LIMIT 0,100";
$dci = 1;
foreach ($conn->query($sqldeleteTail) as $row) {
    $pm_id = $row['memberID'];
    if ($dci > 99){
        $deleteTail ="DELETE FROM private_msg WHERE id='$pm_id'";
        $conn->query($deleteTail);
    }
    $dci++;
}
</code>```

I hope it'll help you

Body:
Below is the small block of code in old version of php.

It have some deprecated methods can anyone help me to convert them into PHP 7 compatible PDO methods.

    // Delete the message residing at the tail end of their list so they cannot archive more than 100 PMs ..................
$sqldeleteTail = mysql_query("SELECT * FROM private_messages WHERE to_id = '$to' ORDER BY time_sent DESC LIMIT 0,100");
    $dci = 1;
    while($row = mysql_fetch_array($sqldeleteTail)){
        $pm_id = $row['memberID'];
        if ($dci > 99){
            $deleteTail = mysql_query("DELETE FROM private_msg WHERE id='$pm_id'");
        }
        $dci++;
    }

Any help would be appreciated.

Body:
This is the updated code as per PHP 7 and above

  // $conn is the instance of your database connection here.
$sqldeleteTail = "SELECT * FROM private_messages WHERE to_id = '$to' ORDER BY time_sent DESC LIMIT 0,100";
$dci = 1;
foreach ($conn->query($sqldeleteTail) as $row) {
    $pm_id = $row['memberID'];
    if ($dci > 99){
        $deleteTail ="DELETE FROM private_msg WHERE id='$pm_id'";
        $conn->query($deleteTail);
    }
    $dci++;
}

I hope it'll help you


问:
How do I get executor related info from a sparkcontext?
Spark version is 2.3.3.
I am trying to find total/used memory along with active/total tasks and other executor specific info.

In my driver :-

```<code>sc.statusTracker.getExecutorInfos.foreach{
      x=>
        x.numRunningTasks()
    }
</code>```

I can get the number of running tasks. But I also need total/used memory from these executors as well. I have thousands of job running on a Yarn cluster. The idea is to get actual usage vs allocated memory so that these can be optimized further.

Update:
http://:8088/proxy//api/v1/applications//executors provides all the information available on UI. Except memory used during computation. Which is what I am looking for majorly.

答:
All this information can be seen on Spark UI or Spark History server .

There is executors tab in Spark which provides information about the executors and memory allocation, total executors, tasks.

If submitted through YARN ,you can also go through YARN and check the logs it will show the details related to memory allocated to executors.

Body:
Spark version is 2.3.3.
I am trying to find total/used memory along with active/total tasks and other executor specific info.

In my driver :-

sc.statusTracker.getExecutorInfos.foreach{
      x=>
        x.numRunningTasks()
    }

I can get the number of running tasks. But I also need total/used memory from these executors as well. I have thousands of job running on a Yarn cluster. The idea is to get actual usage vs allocated memory so that these can be optimized further.

Update:
http://:8088/proxy//api/v1/applications//executors provides all the information available on UI. Except memory used during computation. Which is what I am looking for majorly.


问:
Combination of Voice Over and Speech Recognition in iOS
I want to combine voice over and Speech recognizer functionality. I have survey and with questions and to help user to select the option, I added UIAccessibilityCustomAction, so when user ready to select he selects this action, which in turn activates Speech recognition, he pronounce selected option and after UI updated.

```<code>- (void)startRecognizingProcess {
     __weak typeof(self) weakSelf = self;
     self.audioEngine = [[AVAudioEngine alloc] init];

     if (self.recognitionTask) {
         [self.recognitionTask cancel];
         self.recognitionTask = nil;
     }

     NSError *error;
     AVAudioSession *audioSession = [AVAudioSession sharedInstance];
     [audioSession setCategory:AVAudioSessionCategoryRecord error:&error];
     [audioSession setActive:YES withOptions:AVAudioSessionSetActiveOptionNotifyOthersOnDeactivation error:&error];

     self.recognitionRequest = [[SFSpeechAudioBufferRecognitionRequest alloc] init];
     AVAudioInputNode *inputNode = self.audioEngine.inputNode;
     self.recognitionRequest.shouldReportPartialResults = YES;
    if (@available(iOS 13, *)) {
        if ([self.speechRecognizer supportsOnDeviceRecognition]) {
            self.recognitionRequest.requiresOnDeviceRecognition = true;
        }
    }
     self.recognitionTask = [self.speechRecognizer recognitionTaskWithRequest:self.recognitionRequest resultHandler:^(SFSpeechRecognitionResult * _Nullable result, NSError * _Nullable error) {
         __strong typeof(self) strongSelf = weakSelf;
         BOOL isFinal = NO;
         if (result) {
             NSString *selectedOption = result.bestTranscription.formattedString;
             NSLog(@"RESULT:%@",result.bestTranscription.formattedString);
             isFinal = !result.isFinal;
             if (isFinal) {
                 [strongSelf activateSelectedOption:selectedOption];
                 [strongSelf.recognitionTask cancel];
                 [strongSelf.audioEngine stop];
                 [inputNode removeTapOnBus:0];
                 [strongSelf.recognitionRequest endAudio];
                 strongSelf.recognitionRequest = nil;
                 strongSelf.recognitionTask = nil;
             }
         }
         if (error) {
             [strongSelf.audioEngine stop];
             [inputNode removeTapOnBus:0];
             strongSelf.recognitionRequest = nil;
             strongSelf.recognitionTask = nil;
         }
     }];

     AVAudioFormat *recordingFormat = [inputNode outputFormatForBus:0];
     [inputNode installTapOnBus:0 bufferSize:1024 format:recordingFormat block:^(AVAudioPCMBuffer * _Nonnull buffer, AVAudioTime * _Nonnull when) {
         [self.recognitionRequest appendAudioPCMBuffer:buffer];
     }];

     [self.audioEngine prepare];
     [self.audioEngine startAndReturnError:&error];
}
</code>```

all works, except, Voice Over lost its sound.
When I press Home button and then ones again open application, it again has voice and works as required.
So I have a question:
Maybe some additional steps is needed to make Voice over again? Or I miss smth.

Thank you in advance.

答:
I managed to found out what was wrong.

```<code>AVAudioSession *audioSession = [AVAudioSession sharedInstance];
[audioSession setCategory:AVAudioSessionCategoryRecord error:&error];
[audioSession setActive:YES withOptions:AVAudioSessionSetActiveOptionNotifyOthersOnDeactivation error:&error];
</code>```

During implementation, at the beginning I added these lines of code, that lived in memory, and when the app was sent to background - audioSession - deallocated.
So removing these lines fixed the issue.

Body:
I want to combine voice over and Speech recognizer functionality. I have survey and with questions and to help user to select the option, I added UIAccessibilityCustomAction, so when user ready to select he selects this action, which in turn activates Speech recognition, he pronounce selected option and after UI updated.

- (void)startRecognizingProcess {
     __weak typeof(self) weakSelf = self;
     self.audioEngine = [[AVAudioEngine alloc] init];

     if (self.recognitionTask) {
         [self.recognitionTask cancel];
         self.recognitionTask = nil;
     }

     NSError *error;
     AVAudioSession *audioSession = [AVAudioSession sharedInstance];
     [audioSession setCategory:AVAudioSessionCategoryRecord error:&error];
     [audioSession setActive:YES withOptions:AVAudioSessionSetActiveOptionNotifyOthersOnDeactivation error:&error];

     self.recognitionRequest = [[SFSpeechAudioBufferRecognitionRequest alloc] init];
     AVAudioInputNode *inputNode = self.audioEngine.inputNode;
     self.recognitionRequest.shouldReportPartialResults = YES;
    if (@available(iOS 13, *)) {
        if ([self.speechRecognizer supportsOnDeviceRecognition]) {
            self.recognitionRequest.requiresOnDeviceRecognition = true;
        }
    }
     self.recognitionTask = [self.speechRecognizer recognitionTaskWithRequest:self.recognitionRequest resultHandler:^(SFSpeechRecognitionResult * _Nullable result, NSError * _Nullable error) {
         __strong typeof(self) strongSelf = weakSelf;
         BOOL isFinal = NO;
         if (result) {
             NSString *selectedOption = result.bestTranscription.formattedString;
             NSLog(@"RESULT:%@",result.bestTranscription.formattedString);
             isFinal = !result.isFinal;
             if (isFinal) {
                 [strongSelf activateSelectedOption:selectedOption];
                 [strongSelf.recognitionTask cancel];
                 [strongSelf.audioEngine stop];
                 [inputNode removeTapOnBus:0];
                 [strongSelf.recognitionRequest endAudio];
                 strongSelf.recognitionRequest = nil;
                 strongSelf.recognitionTask = nil;
             }
         }
         if (error) {
             [strongSelf.audioEngine stop];
             [inputNode removeTapOnBus:0];
             strongSelf.recognitionRequest = nil;
             strongSelf.recognitionTask = nil;
         }
     }];

     AVAudioFormat *recordingFormat = [inputNode outputFormatForBus:0];
     [inputNode installTapOnBus:0 bufferSize:1024 format:recordingFormat block:^(AVAudioPCMBuffer * _Nonnull buffer, AVAudioTime * _Nonnull when) {
         [self.recognitionRequest appendAudioPCMBuffer:buffer];
     }];

     [self.audioEngine prepare];
     [self.audioEngine startAndReturnError:&error];
}

all works, except, Voice Over lost its sound.
When I press Home button and then ones again open application, it again has voice and works as required.
So I have a question:
Maybe some additional steps is needed to make Voice over again? Or I miss smth.

Thank you in advance.

Body:
I managed to found out what was wrong.

AVAudioSession *audioSession = [AVAudioSession sharedInstance];
[audioSession setCategory:AVAudioSessionCategoryRecord error:&error];
[audioSession setActive:YES withOptions:AVAudioSessionSetActiveOptionNotifyOthersOnDeactivation error:&error];

During implementation, at the beginning I added these lines of code, that lived in memory, and when the app was sent to background - audioSession - deallocated.
So removing these lines fixed the issue.


问:
Reading values from opened desktopapplication windows
I'm developing a web framework which needs to interact with a desktop application. The desktop application can vary between companies. For instance when a user logs in using the desktop application, the username should be send to the browser (for instance using get).

Is there something available that can read windows? For instance created in Windows Forms, Java Swing or other frameworks?

I only found AutoIT which can read the titlebar but we'd also like to read values from textboxes, checkboxes, comboboxes, etc.

Thanks in advance!

答: If i understand it you need something like Pipes. You can use Pipes to pass information between applications.


问:
Kafka Topic And Offset
I have a question,Suppose there is a TOPIC T1 and there are two Consumer C1 and C2 belongs to two different groups and current offset is 0.We know that Kafka maintains the Offset for consumer.So if C1 consume the message and Offset becomes 1 then what will happen if C2 consume the message will it start from 1 offset or it will start consume the message from 0 offset?. Means how offset will be maintains for two different consumer Group?.

Thanks

答:
Whenever a new ConsumerGroup is created and a consumer tries to read the data from a topic, the consumer always gets the data from the beginning of the topic (Offset 0).

Kafka maintains the offsets for each ConsumerGroup. Even if a consumer is in no ConsumerGroup, the consumer is added to a Kafka generated group in order to maintain the offsets of such a consumer. This process is carried out for all individual consumers.

In your case, consumer C2 will hence read the data from the offset 0.

Title: Kafka Topic And Offset


问:
What is the best way to scale an Canvas with css or js to the screen? And how do I make the width of the canvas equal to the height?
I want to make an TIC TAC TOE and im pretty new to js. I want to draw the x's and 0's to the canvas.
1. How do I make the height equal to the width of the canvas?
2. What is the best way to scale the canvas to use this for example also on phones and have the same experience?</p>

答:
You can make a full-screen canvas and use it to display your code.

Here is a boilerplate to get you started:

HTML

```<code><canvas id="canvas"></canvas>
</code>```

CSS

```<code>* {
  margin: 0;
}

canvas {
  display: block;
}
</code>```

JS

```<code>window.onload = function() {
  var canvas = document.getElementById("canvas"),
      context = canvas.getContext("2d"),
      width = canvas.width = window.innerWidth,
      height = canvas.height = window.innerHeight;

  context.fillRect(0, 0, width, height);
};
</code>```

Body:
You can make a full-screen canvas and use it to display your code.

Here is a boilerplate to get you started:

HTML

<canvas id="canvas"></canvas>

CSS

* {
  margin: 0;
}

canvas {
  display: block;
}

JS

window.onload = function() {
  var canvas = document.getElementById("canvas"),
      context = canvas.getContext("2d"),
      width = canvas.width = window.innerWidth,
      height = canvas.height = window.innerHeight;

  context.fillRect(0, 0, width, height);
};


问:
Servelt Page doesn't Redirect to second Page using Servlet
I am a beginner of servlet jsp. I am creating a simple login form if the login successful page redirects to the second servlet along with the username. but it doesn't work it shows the error java.lang.IllegalArgumentException: Path second does not start with a "/" character
what I tried so far I attached below.

Form

```<code> <div class="row">
                <form method="POST" action="login">
                <div class="form-group">
                    <label>Username</label>
                    <input type="text" id="uname" name="uname" placeholder="uname" class="form-control">
                </div>

                 <div class="form-group">
                    <label>Password</label>
                    <input type="password" id="pword" name="pword" placeholder="pword" class="form-control">

                </div>

                 <div class="form-group">

                     <input type="submit" value="submit" class="btn btn-success">

                </div>

                </form>

            </div>
</code>```

Login Servlet Page

```<code>@WebServlet("/login")
public class login extends HttpServlet {
  @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException
    {

         String uname = request.getParameter("uname");
         String pass = request.getParameter("pword");

         if(uname.equals("John") && pass.equals("123"))
         {
            PrintWriter out = response.getWriter();
            HttpSession session = request.getSession(true);
            session.putValue("username", uname);

            ServletContext context=getServletContext();
            RequestDispatcher rd=context.getRequestDispatcher("second");

            rd.forward(request, response);

         }

    }
</code>```

Second Servlet Page

```<code>@WebServlet("/second")
public class second extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException
    {
        PrintWriter out = response.getWriter();
         HttpSession session = request.getSession(true);
       String uname = (String)session.getValue("uname");
        out.println("User Name is " + uname);

    }
</code>```

答:
this exception indicates, path does not start with a "/".
try below instead.</p>

```<code> RequestDispatcher rd=context.getRequestDispatcher(request.getContextPath() +"/second");
</code>```

Body:
I am a beginner of servlet jsp. I am creating a simple login form if the login successful page redirects to the second servlet along with the username. but it doesn't work it shows the error java.lang.IllegalArgumentException: Path second does not start with a "/" character
what I tried so far I attached below.

Form

                <form method="POST" action="login">

                    Username
                    <input type="text" id="uname" name="uname" placeholder="uname" class="form-control">

                    Password
                    <input type="password" id="pword" name="pword" placeholder="pword" class="form-control">

                     <input type="submit" value="submit" class="btn btn-success">

                </form>

Login Servlet Page

@WebServlet("/login")
public class login extends HttpServlet {
  @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException
    {

         String uname = request.getParameter("uname");
         String pass = request.getParameter("pword");

         if(uname.equals("John") && pass.equals("123"))
         {
            PrintWriter out = response.getWriter();
            HttpSession session = request.getSession(true);
            session.putValue("username", uname);

            ServletContext context=getServletContext();
            RequestDispatcher rd=context.getRequestDispatcher("second");

            rd.forward(request, response);

         }

    }

Second Servlet Page

@WebServlet("/second")
public class second extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException
    {
        PrintWriter out = response.getWriter();
         HttpSession session = request.getSession(true);
       String uname = (String)session.getValue("uname");
        out.println("User Name is " + uname);

    }

Body:
this exception indicates, path does not start with a "/".
try below instead.

 RequestDispatcher rd=context.getRequestDispatcher(request.getContextPath() +"/second");


问:
Airflow DAG explodes with RecursionError when triggered via WebUI

I'm testing changes after major refactoring / re-write of my current Airflow workflow

I'm still on LocalExecutor since all my tasks execute some commands / on remote machines (no actual computation heavy-lifting done within same Airflow machine)

DAGs are being generated via a python script that reads locally stored JSON files (one DAG per JSON object in file)

After several days of rewrite I was able to generate my DAGs in the said way (programmatically)

However upon trying to trigger the DAG via UI (while testing, I set schedule_interval=None so triggers are manual), the DAG explodes (nuclear bomb text image) with following stacktrace (see complete stacktrace here) likely thrown from this place

```<code>  recurse_nodes(t, visited) for t in task.upstream_list
  File "/home/admin/.pyenv/versions/3.7.3/lib/python3.7/site-packages/airflow/www/views.py", line 1483, in <listcomp>
    if node_count[0] < node_limit or t not in visited]
  File "/home/admin/.pyenv/versions/3.7.3/lib/python3.7/site-packages/airflow/www/views.py", line 1478, in recurse_nodes
    visited.add(task)
  File "/home/admin/.pyenv/versions/3.7.3/lib/python3.7/site-packages/airflow/models/__init__.py", line 2304, in __hash__
    hash(val)
  File "/home/admin/.pyenv/versions/3.7.3/lib/python3.7/site-packages/airflow/models/__init__.py", line 2304, in __hash__
    hash(val)
  File "/home/admin/.pyenv/versions/3.7.3/lib/python3.7/site-packages/airflow/models/__init__.py", line 2304, in __hash__
    hash(val)
  [Previous line repeated 477 more times]
  File "/home/admin/.pyenv/versions/3.7.3/lib/python3.7/site-packages/airflow/models/__init__.py", line 2302, in __hash__
    val = getattr(self, c, None)
  File "/home/admin/.pyenv/versions/3.7.3/lib/python3.7/site-packages/airflow/models/__init__.py", line 2396, in dag_id
    if self.has_dag():
  File "/home/admin/.pyenv/versions/3.7.3/lib/python3.7/site-packages/airflow/models/__init__.py", line 2392, in has_dag
    return getattr(self, '_dag', None) is not None
RecursionError: maximum recursion depth exceeded while calling a Python object
</code>```

Additionally, when I reload the webUI (or open a different browser tab), I can see the DAG stuck in RUNNING state (all TaskInstances have state / PID = NULL).

Interestingly enough, once this happens, until I mark the DAG as failed via UI, I start getting the following stacktrace at /logs/scheduler/latest/<path/to/my/dag_script.py.log> (apparently thrown from here)

```<code>[2019-12-24 06:27:32,851] {jobs.py:1446} INFO - Processing derived_tables_presto_cbot_events_1
[2019-12-24 06:27:32,855] {jobs.py:921} INFO - Examining DAG run <DagRun derived_tables_presto_cbot_events_1 @ 2019-12-23 13:08:36.747641+00:00: manual__2019-12-23T13:08:36.747641+00:00, externally triggered: True>
[2019-12-24 06:27:32,856] {jobs.py:410} ERROR - Got an exception! Propagating...
Traceback (most recent call last):
  File "/home/admin/.pyenv/versions/3.7.3/lib/python3.7/site-packages/airflow/jobs.py", line 402, in helper
    pickle_dags)
  File "/home/admin/.pyenv/versions/3.7.3/lib/python3.7/site-packages/airflow/utils/db.py", line 73, in wrapper
    return func(*args, **kwargs)
  File "/home/admin/.pyenv/versions/3.7.3/lib/python3.7/site-packages/airflow/jobs.py", line 1760, in process_file
    self._process_dags(dagbag, dags, ti_keys_to_schedule)
  File "/home/admin/.pyenv/versions/3.7.3/lib/python3.7/site-packages/airflow/jobs.py", line 1451, in _process_dags
    self._process_task_instances(dag, tis_out)
  File "/home/admin/.pyenv/versions/3.7.3/lib/python3.7/site-packages/airflow/utils/db.py", line 73, in wrapper
    return func(*args, **kwargs)
  File "/home/admin/.pyenv/versions/3.7.3/lib/python3.7/site-packages/airflow/jobs.py", line 930, in _process_task_instances
    if len(active_dag_runs) >= dag.max_active_runs:
TypeError: '>=' not supported between instances of 'int' and 'NoneType'
</code>```

Once I mark the Dag as failed via WebUI, the above stacktrace from scheduler logs disappears (the TaskInstances of that DAG continue to exist in Airflow's meta-db unless I manually delete them using a DELETE FROM.. SQL query)

I've tried several things without success

Ascertained that my Airflow LocalExecutor deployment is still intact (older workflow's DAGs are still running fine)

Killing and restarting Airflow's scheduler & webserver several times

airflow initdb

Checked airflow.cfg file for any discrepancies

I'm using

Python 3.7.3 (installed via PyEnv)

Airflow 1.10.3 with LocalExecutor

Linux ip-XXX-XX-XX-XX 4.9.0-8-amd64 #1 SMP Debian 4.9.130-2 (2018-10-27) x86_64 GNU/Linux

答:
As rightly pointed out by @kaxil, the bug was in one of the custom operators

I had carelessly used a method defined within operator's class as on_failure_callback, and therefore the self param of that kill_task() method was leading to RecursionError and exploding of DAG

```<code>class MyCustomOperator(BaseOperator):

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.on_failure_callback = self.kill_task
    ..
    def kill_task(self) -> None:
        // do some cleanup work
</code>```

Moving the kill_task() method outside the class resolved the issue

Body:
I'm testing changes after major refactoring / re-write of my current Airflow workflow

I'm still on LocalExecutor since all my tasks execute some commands / on remote machines (no actual computation heavy-lifting done within same Airflow machine)

DAGs are being generated via a python script that reads locally stored JSON files (one DAG per JSON object in file)

After several days of rewrite I was able to generate my DAGs in the said way (programmatically)

However upon trying to trigger the DAG via UI (while testing, I set schedule_interval=None so triggers are manual), the DAG explodes (nuclear bomb text image) with following stacktrace (see complete stacktrace here) likely thrown from this place

  recurse_nodes(t, visited) for t in task.upstream_list
  File "/home/admin/.pyenv/versions/3.7.3/lib/python3.7/site-packages/airflow/www/views.py", line 1483, in <listcomp>
    if node_count[0] < node_limit or t not in visited]
  File "/home/admin/.pyenv/versions/3.7.3/lib/python3.7/site-packages/airflow/www/views.py", line 1478, in recurse_nodes
    visited.add(task)
  File "/home/admin/.pyenv/versions/3.7.3/lib/python3.7/site-packages/airflow/models/__init__.py", line 2304, in __hash__
    hash(val)
  File "/home/admin/.pyenv/versions/3.7.3/lib/python3.7/site-packages/airflow/models/__init__.py", line 2304, in __hash__
    hash(val)
  File "/home/admin/.pyenv/versions/3.7.3/lib/python3.7/site-packages/airflow/models/__init__.py", line 2304, in __hash__
    hash(val)
  [Previous line repeated 477 more times]
  File "/home/admin/.pyenv/versions/3.7.3/lib/python3.7/site-packages/airflow/models/__init__.py", line 2302, in __hash__
    val = getattr(self, c, None)
  File "/home/admin/.pyenv/versions/3.7.3/lib/python3.7/site-packages/airflow/models/__init__.py", line 2396, in dag_id
    if self.has_dag():
  File "/home/admin/.pyenv/versions/3.7.3/lib/python3.7/site-packages/airflow/models/__init__.py", line 2392, in has_dag
    return getattr(self, '_dag', None) is not None
RecursionError: maximum recursion depth exceeded while calling a Python object

Additionally, when I reload the webUI (or open a different browser tab), I can see the DAG stuck in RUNNING state (all TaskInstances have state / PID = NULL).

Interestingly enough, once this happens, until I mark the DAG as failed via UI, I start getting the following stacktrace at /logs/scheduler/latest/<path/to/my/dag_script.py.log> (apparently thrown from here)

[2019-12-24 06:27:32,851] {jobs.py:1446} INFO - Processing derived_tables_presto_cbot_events_1
[2019-12-24 06:27:32,855] {jobs.py:921} INFO - Examining DAG run <DagRun derived_tables_presto_cbot_events_1 @ 2019-12-23 13:08:36.747641+00:00: manual__2019-12-23T13:08:36.747641+00:00, externally triggered: True>
[2019-12-24 06:27:32,856] {jobs.py:410} ERROR - Got an exception! Propagating...
Traceback (most recent call last):
  File "/home/admin/.pyenv/versions/3.7.3/lib/python3.7/site-packages/airflow/jobs.py", line 402, in helper
    pickle_dags)
  File "/home/admin/.pyenv/versions/3.7.3/lib/python3.7/site-packages/airflow/utils/db.py", line 73, in wrapper
    return func(*args, **kwargs)
  File "/home/admin/.pyenv/versions/3.7.3/lib/python3.7/site-packages/airflow/jobs.py", line 1760, in process_file
    self._process_dags(dagbag, dags, ti_keys_to_schedule)
  File "/home/admin/.pyenv/versions/3.7.3/lib/python3.7/site-packages/airflow/jobs.py", line 1451, in _process_dags
    self._process_task_instances(dag, tis_out)
  File "/home/admin/.pyenv/versions/3.7.3/lib/python3.7/site-packages/airflow/utils/db.py", line 73, in wrapper
    return func(*args, **kwargs)
  File "/home/admin/.pyenv/versions/3.7.3/lib/python3.7/site-packages/airflow/jobs.py", line 930, in _process_task_instances
    if len(active_dag_runs) >= dag.max_active_runs:
TypeError: '>=' not supported between instances of 'int' and 'NoneType'

Once I mark the Dag as failed via WebUI, the above stacktrace from scheduler logs disappears (the TaskInstances of that DAG continue to exist in Airflow's meta-db unless I manually delete them using a DELETE FROM.. SQL query)

I've tried several things without success

Ascertained that my Airflow LocalExecutor deployment is still intact (older workflow's DAGs are still running fine)

Killing and restarting Airflow's scheduler & webserver several times

airflow initdb

Checked airflow.cfg file for any discrepancies

I'm using

Python 3.7.3 (installed via PyEnv)

Airflow 1.10.3 with LocalExecutor

Linux ip-XXX-XX-XX-XX 4.9.0-8-amd64 #1 SMP Debian 4.9.130-2 (2018-10-27) x86_64 GNU/Linux

Body:
As rightly pointed out by @kaxil, the bug was in one of the custom operators

I had carelessly used a method defined within operator's class as on_failure_callback, and therefore the self param of that kill_task() method was leading to RecursionError and exploding of DAG

class MyCustomOperator(BaseOperator):

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.on_failure_callback = self.kill_task
    ..
    def kill_task(self) -> None:
        // do some cleanup work

Moving the kill_task() method outside the class resolved the issue