问:
Show Stimulsoft reporting in Angular by Asp.net Core
I have a Webservice In Asp.net core for generate reporting and call this in Angular app for show reporting but angular doesn't show reporting, just show blank page

What's the problem? How can I solve It?

Asp.net Core WebService :

```<code>[HttpGet("[action]")]
public async Task<IActionResult> ShowPrint(int? id)
{
    var res = await _inquiryService.GetStudents(id);
    var result = res.Select(x => new InquiryValueViewModelsPrint()
    {
        SupplierContractorName = x.SupplierContractorName,
        SumTotalPrice = x.SumTotalPrice
    }).ToList();

    var report = new StiReport();
    report.Load(StiNetCoreHelper.MapPath(this, "Reports/inquiry.mrt"));

    report.RegBusinessObject("InquiryObj", result);

    return StiNetCoreViewer.GetReportResult(this, report);
}
</code>```

Angular function :

```<code>viewer: any;
options: any;
report: any = new Stimulsoft.Report.StiReport();
constructor(...

print(item: InquiryViewModel) {
    this.apiService.showPrint(item.id)
      .subscribe(data => {
        console.log( data)
        this.options = new Stimulsoft.Viewer.StiViewerOptions();
        this.viewer = new Stimulsoft.Viewer.StiViewer(this.options, 'StiViewer', false);

        this.report.load(data);

        this.viewer.report = this.report;
        this.viewer.renderHtml('viewer');
      });
}
</code>```

HTML:

```<code><div>
    <h2>Stimulsoft Viewer</h2>
    <div id="viewer"></div>
  </div>
</code>```

答:
I think it's better that way In Angular.</p>
```<code>    declare var Stimulsoft: any;
    let viewer = new Stimulsoft.Viewer.StiViewer(null, 'StiViewer', false);
    var report = new Stimulsoft.Report.StiReport();
    report.loadFile('./assets/reports/***.mrt');
    var ds ={ "Report": [
      { "NameField": ""},
      { "NameField": "" }
    ]};

    ds.FieldSport=data;
    report.regData("...", "...", ds);
    viewer.report = report;
    viewer.renderHtml("viewerContent");
</code>```

Body:
I have a Webservice In Asp.net core for generate reporting and call this in Angular app for show reporting but angular doesn't show reporting, just show blank page

What's the problem? How can I solve It?

Asp.net Core WebService :

[HttpGet("[action]")]
public async Task<IActionResult> ShowPrint(int? id)
{
    var res = await _inquiryService.GetStudents(id);
    var result = res.Select(x => new InquiryValueViewModelsPrint()
    {
        SupplierContractorName = x.SupplierContractorName,
        SumTotalPrice = x.SumTotalPrice
    }).ToList();

    var report = new StiReport();
    report.Load(StiNetCoreHelper.MapPath(this, "Reports/inquiry.mrt"));

    report.RegBusinessObject("InquiryObj", result);

    return StiNetCoreViewer.GetReportResult(this, report);
}

Angular function :

viewer: any;
options: any;
report: any = new Stimulsoft.Report.StiReport();
constructor(...

print(item: InquiryViewModel) {
    this.apiService.showPrint(item.id)
      .subscribe(data => {
        console.log( data)
        this.options = new Stimulsoft.Viewer.StiViewerOptions();
        this.viewer = new Stimulsoft.Viewer.StiViewer(this.options, 'StiViewer', false);

        this.report.load(data);

        this.viewer.report = this.report;
        this.viewer.renderHtml('viewer');
      });
}

HTML:

Stimulsoft Viewer

Body:
I think it's better that way In Angular.

    declare var Stimulsoft: any;
    let viewer = new Stimulsoft.Viewer.StiViewer(null, 'StiViewer', false);
    var report = new Stimulsoft.Report.StiReport();
    report.loadFile('./assets/reports/***.mrt');
    var ds ={ "Report": [
      { "NameField": ""},
      { "NameField": "" }
    ]};

    ds.FieldSport=data;
    report.regData("...", "...", ds);
    viewer.report = report;
    viewer.renderHtml("viewerContent");


来源: stackexchange

问:
How can I see the employee IDs for a project that lasts longer than 20 hours per week?
(assigned_name in works_on is percentage of time employee is assigned to project)

Question:
Find the IDs of employees assigned to a project that is more than 20 hours per week.

My attempt:

I have assumed 24 hours as working hours here. Is my query correct?
Here's the create and insert statements.

```<code>CREATE TABLE IF NOT EXISTS employees(
    employee_id NUMERIC(9),
    first_name VARCHAR(10),
    last_name VARCHAR(20),
    dept_code CHAR(5),
    salary NUMERIC(9, 2),
    PRIMARY KEY (employee_id)
);

CREATE TABLE IF NOT EXISTS departments(
    code CHAR(5),
    name VARCHAR(30),
    manager_id NUMERIC(9),
    sub_dept_of CHAR(5),
    PRIMARY KEY (code)
);

CREATE TABLE IF NOT EXISTS projects(
    project_id CHAR(8),
    dept_code CHAR(5),
    description VARCHAR(200),
    start_date DATE,
    stop_date DATE,
    revenue NUMERIC(12, 2),
    PRIMARY KEY (project_id)
);

CREATE TABLE IF NOT EXISTS works_on(
    employee_id NUMERIC(9),
    project_id CHAR(8),
    assigned_time NUMERIC(3, 2),
    PRIMARY KEY (employee_id, project_id)
);

INSERT INTO employees
VALUES (1, 'Al', 'Betheleader', 'ADMIN', 70000),
       (2, 'Pl', 'Rsquared', 'ACCNT', 40000),
       (3, 'Harry', 'Hardware', 'HDWRE', 50000),
       (4, 'Sussie', 'Software', 'CNSLT', 60000),
       (5, 'Abe', 'Advice', 'CNSLT', 30000),
       (6, 'Hardly', 'Aware', NULL, 65000),
       (7, 'Bucky', 'Nour', 'ACTNG', 25000);

INSERT INTO departments
VALUES ('ADMIN', 'Administration', 1, NULL),
       ('ACCNT', 'Accounting', 2, 'ADMIN'),
       ('HDWRE', 'Hardware', 3, 'CNSLT'),
       ('CNSLT', 'Consulting', 4, 'ADMIN'),
       ('ACTNG', 'Bug fixing', 7, 'ADMIN');

INSERT INTO projects
VALUES
('EMPHAPPY', 'ADMIN', 'Employee Moral', '2002-03-14', NULL, 0),
('ADT4MFIA', 'ACCNT', 'Mofia Audit', '2003-07-03', '2003-11-30', 100000),
('ROBOSPSE', 'CNSLT', 'Robotic Spouse', '2002-03-14', NULL, 242000),
('DNLDCLNT', 'CNSLT', 'Download Client', '2005-02-03', NULL, 18150),
('BOBBYFUN', 'ACTNG', 'Bug fixing', '2024-02-14', NULL, 17990);

INSERT INTO works_on
VALUES (2, 'ADT4MFIA', 0.50),
       (3, 'ROBOSPSE', 0.75),
       (4, 'ROBOSPSE', 0.75),
       (5, 'ROBOSPSE', 0.50),
       (5, 'ADT4MFIA', 0.60),
       (3, 'DNLDCLNT', 0.25);
</code>```
```<code>SELECT employee_id
FROM works_on
WHERE 1.68 * assigned_time > 20;
</code>```

答:
while you mention that you're looking for person > 20hr per week, you don't give us information about what the "assigned_time" is in reference to. Is that a percentage of each day, week, month? With the values you have now, you can see that none of these individuals is close to a value of '20' if you just add your math to the select statement.

```<code>SELECT employee_id, (assigned_time * 1.68) as'worked'
FROM works_on

employee_id worked
       2    0.8400
       3    0.4200
       3    1.2600
       4    1.2600
       5    1.0080
       5    0.8400
</code>```

I imagine you're looking for the sum of same employee id's working multiple times, which would be more along the lines of

```<code>SELECT employee_id, sum(assigned_time * 1.68) as'worked'
FROM works_on
group by employee_id

employee_id worked
       2    0.8400
       3    1.6800
       4    1.2600
       5    1.8480
</code>```

ContentLicense: CC BY-SA 4.0

Body:
(assigned_name in works_on is percentage of time employee is assigned to project)

Question:
Find the IDs of employees assigned to a project that is more than 20 hours per week.

My attempt:

I have assumed 24 hours as working hours here. Is my query correct?
Here's the create and insert statements.

CREATE TABLE IF NOT EXISTS employees(
    employee_id NUMERIC(9),
    first_name VARCHAR(10),
    last_name VARCHAR(20),
    dept_code CHAR(5),
    salary NUMERIC(9, 2),
    PRIMARY KEY (employee_id)
);

CREATE TABLE IF NOT EXISTS departments(
    code CHAR(5),
    name VARCHAR(30),
    manager_id NUMERIC(9),
    sub_dept_of CHAR(5),
    PRIMARY KEY (code)
);

CREATE TABLE IF NOT EXISTS projects(
    project_id CHAR(8),
    dept_code CHAR(5),
    description VARCHAR(200),
    start_date DATE,
    stop_date DATE,
    revenue NUMERIC(12, 2),
    PRIMARY KEY (project_id)
);

CREATE TABLE IF NOT EXISTS works_on(
    employee_id NUMERIC(9),
    project_id CHAR(8),
    assigned_time NUMERIC(3, 2),
    PRIMARY KEY (employee_id, project_id)
);

INSERT INTO employees
VALUES (1, 'Al', 'Betheleader', 'ADMIN', 70000),
       (2, 'Pl', 'Rsquared', 'ACCNT', 40000),
       (3, 'Harry', 'Hardware', 'HDWRE', 50000),
       (4, 'Sussie', 'Software', 'CNSLT', 60000),
       (5, 'Abe', 'Advice', 'CNSLT', 30000),
       (6, 'Hardly', 'Aware', NULL, 65000),
       (7, 'Bucky', 'Nour', 'ACTNG', 25000);

INSERT INTO departments
VALUES ('ADMIN', 'Administration', 1, NULL),
       ('ACCNT', 'Accounting', 2, 'ADMIN'),
       ('HDWRE', 'Hardware', 3, 'CNSLT'),
       ('CNSLT', 'Consulting', 4, 'ADMIN'),
       ('ACTNG', 'Bug fixing', 7, 'ADMIN');

INSERT INTO projects
VALUES
('EMPHAPPY', 'ADMIN', 'Employee Moral', '2002-03-14', NULL, 0),
('ADT4MFIA', 'ACCNT', 'Mofia Audit', '2003-07-03', '2003-11-30', 100000),
('ROBOSPSE', 'CNSLT', 'Robotic Spouse', '2002-03-14', NULL, 242000),
('DNLDCLNT', 'CNSLT', 'Download Client', '2005-02-03', NULL, 18150),
('BOBBYFUN', 'ACTNG', 'Bug fixing', '2024-02-14', NULL, 17990);

INSERT INTO works_on
VALUES (2, 'ADT4MFIA', 0.50),
       (3, 'ROBOSPSE', 0.75),
       (4, 'ROBOSPSE', 0.75),
       (5, 'ROBOSPSE', 0.50),
       (5, 'ADT4MFIA', 0.60),
       (3, 'DNLDCLNT', 0.25);

SELECT employee_id
FROM works_on
WHERE 1.68 * assigned_time > 20;

Body:
while you mention that you're looking for person > 20hr per week, you don't give us information about what the "assigned_time" is in reference to. Is that a percentage of each day, week, month? With the values you have now, you can see that none of these individuals is close to a value of '20' if you just add your math to the select statement.

SELECT employee_id, (assigned_time * 1.68) as'worked'
FROM works_on

employee_id worked
       2    0.8400
       3    0.4200
       3    1.2600
       4    1.2600
       5    1.0080
       5    0.8400

I imagine you're looking for the sum of same employee id's working multiple times, which would be more along the lines of

SELECT employee_id, sum(assigned_time * 1.68) as'worked'
FROM works_on
group by employee_id

employee_id worked
       2    0.8400
       3    1.6800
       4    1.2600
       5    1.8480


问:
Disabling default drag behavior on links in iOS Safari
I am developing a web app. I am trying to disable most of the default iOS Safari behavior on links so I set the "-webkit-touch-callout" CSS property on the links to "none". However, I still notice that if I hold my finger on a link for a second or so, then drag it, then let go of it, the link will open in a new window. I don't want this behavior. I would like it to either open in the same window, or do nothing at all. Does anyone know how to make this happen?

EDIT: I am using jQuery so it is OK to use jQuery's event-handling functions if that will simplify things.

EDIT 2: For some links, I am using handlers to override their default behavior. For example:

```<code>$(".categoryList a").live("click", function(e) {
    e.preventDefault();
    $.get(
        "someOtherUrl",
        {someVariable: "someValue"},
        function(result) {
            $(".result").html(render(result));
        }
    );
});
</code>```

My actual code is more complicated than this but my point is that I am overriding the default click action on some links and whatever solution I use to fix this problem should not interfere with these handlers. Sanooj's solution does not work for my purposes because the "window.location" assignment always redirects the browser regardless of whether I have any handlers to prevent this behavior. Maybe I arguably shouldn't use links for this purpose but this is how the app was before I started working on it and changing this would be a big project. I am wondering if there is an easier and simpler way to fix this.

答:
This worked for me:

a {
  -webkit-user-drag: none;
}
```

ContentLicense: CC BY-SA 3.0

Body:
I am developing a web app. I am trying to disable most of the default iOS Safari behavior on links so I set the "-webkit-touch-callout" CSS property on the links to "none". However, I still notice that if I hold my finger on a link for a second or so, then drag it, then let go of it, the link will open in a new window. I don't want this behavior. I would like it to either open in the same window, or do nothing at all. Does anyone know how to make this happen?

EDIT: I am using jQuery so it is OK to use jQuery's event-handling functions if that will simplify things.

EDIT 2: For some links, I am using handlers to override their default behavior. For example:

$(".categoryList a").live("click", function(e) {
    e.preventDefault();
    $.get(
        "someOtherUrl",
        {someVariable: "someValue"},
        function(result) {
            $(".result").html(render(result));
        }
    );
});

My actual code is more complicated than this but my point is that I am overriding the default click action on some links and whatever solution I use to fix this problem should not interfere with these handlers. Sanooj's solution does not work for my purposes because the "window.location" assignment always redirects the browser regardless of whether I have any handlers to prevent this behavior. Maybe I arguably shouldn't use links for this purpose but this is how the app was before I started working on it and changing this would be a big project. I am wondering if there is an easier and simpler way to fix this.


问:
Does it make sense to use Firestore Realtime as a way to interact with functions?
I have a good old fashioned piece of code that takes some inputs, runs some code and produces outputs for a variety of tasks. This code runs in a function, and it should be triggered by a UI action. It is relevant to store a history of these runs per user, to list them in a specific view of the UI, and, on returning users, put them back where they left.

Since the Firestore documentation and videos strongly encourage us to default to it for data exchange with the backend, I of course decided to entertain the idea before just moving on to simply implementing a callable.

First, it made sense to me to model the data as follows:

```<code>/users
  id

  /taskRuns
    id
    inputs
    outputs

    /history
      id
      date
      ...outputs
</code>```

and make the data flow as follows:

The UI writes to the inputs field and it listens to the document.

The unction is triggered. It runs happily and it writes to outputs.

A second function listening to /assets puts copies over the inputs and outputs onto its corresponding /history subcollection.

The UI reacts to the change.

At this point, a couple of red flags are raised on my mind:

Since the UI has to both read and write /assets, a malicious user could technically trigger infinite loops here. I'm aware that the same thing is possible with a callable, but it somehow seems even easier in this scenario.

I lose the ability to do timeout and error handling the way one would with a simple API call.

However, I also understand that:

My function needs to write to the database anyway to store the outputs even if it was returning it à la API.

Logic for who's responsible for what has somewhat been broken down into pieces.

So - Am I looking at it wrong? Is there a world in which this approach would make sense over the callable?

答:
The approach you're describing uses the database as a queue/cache/proxy for your backend functionality. I regularly use it myself with either Realtime Database or Firestore to expose backend functionality, because it:

Works more gracefully when there's intermittent loss of internet connection. Where a direct call to Cloud Functions would have to implement its own retries, the database SDKs already handle this scenario.

Uses the database as a proxy/cache for the result, so that repeated loads of the data don't cause additional calls to my Cloud Functions.

By setting a maximum number of instances on my Cloud Function, I can prevent overloading any legacy infrastructure my code calls, and the database becomes my queue of pending requests.

The pattern is also used in this video from Cloud Next 2019: Serverless in real life: a case study in the travel industry and this talk from Google I/O: Architecting for Data Contention in a Realtime World with Firebase.

That said, many of my team mates only ever use callable functions, so it's definitely a matter of preference and the requirements of your use-case.

Body:
I have a good old fashioned piece of code that takes some inputs, runs some code and produces outputs for a variety of tasks. This code runs in a function, and it should be triggered by a UI action. It is relevant to store a history of these runs per user, to list them in a specific view of the UI, and, on returning users, put them back where they left.

Since the Firestore documentation and videos strongly encourage us to default to it for data exchange with the backend, I of course decided to entertain the idea before just moving on to simply implementing a callable.

First, it made sense to me to model the data as follows:

/users
  id

  /taskRuns
    id
    inputs
    outputs

    /history
      id
      date
      ...outputs

and make the data flow as follows:

The UI writes to the inputs field and it listens to the document.

The unction is triggered. It runs happily and it writes to outputs.

A second function listening to /assets puts copies over the inputs and outputs onto its corresponding /history subcollection.

The UI reacts to the change.

At this point, a couple of red flags are raised on my mind:

Since the UI has to both read and write /assets, a malicious user could technically trigger infinite loops here. I'm aware that the same thing is possible with a callable, but it somehow seems even easier in this scenario.

I lose the ability to do timeout and error handling the way one would with a simple API call.

However, I also understand that:

My function needs to write to the database anyway to store the outputs even if it was returning it à la API.

Logic for who's responsible for what has somewhat been broken down into pieces.

So - Am I looking at it wrong? Is there a world in which this approach would make sense over the callable?


问:
Case When + IN combination
I'm a bit stuck in my coding here... I have this extense and complex code, but I'm actually failling by the end of it. I'm getting the SQL Error [42804]: ERROR: argument of CASE/WHEN must be type boolean, not type character varying

The thing, is: when "bairro" matches a row from "SUB_COUNTRY_DB", get psd.name, else get z.name. Any tips on how I could accomplish this?

select distinct
           aa.mes,
           --aa.modalidade,
           --to_date(aa.created_date, 'yyyy-mm-dd') data_captacao,
           ucl.ja_comprou_lf as comprou_lf,
           case when bairro in (select sub_country from sub_country_DB)
           then psd.name
           else z.name
           end loja,
           count (distinct aa.customer_uid) qtde_socios,
           count (distinct aa.assinatura_uid) qtde_assinaturas
from assinaturas_ativas aa
    left join ultima_compra_loja_fisica ucl           on (aa.customer_uid = ucl.customer_uid
                                                           and aa.mes = ucl.mes)
    left join zip_code z                              on (aa.customer_uid = z.customer_uid
                                                           and aa.mes = z.mes)
    left join SUB_COUNTRY_DB psd
    on (psd.district = aa.bairro)
group by 1,2,3--,4
```

答:
Try variants like:

moving condition to an inner query
```<code>CASE WHEN EXISTS (SELECT DISTINCT sub_country FROM sub_country_DB WHERE sub_country = barrio)
</code>```

ANY (PostgreSQL only)
```<code>CASE WHEN bairro = ANY(ARRAY_AGG(select sub_country from sub_country_DB))
</code>```

Title: Case When + IN combination

Body:
Try variants like:

moving condition to an inner query

CASE WHEN EXISTS (SELECT DISTINCT sub_country FROM sub_country_DB WHERE sub_country = barrio)

ANY (PostgreSQL only)

CASE WHEN bairro = ANY(ARRAY_AGG(select sub_country from sub_country_DB))


问:
How To write a function to Check for a Sequence of integers in an array in python
I'm trying to figure out why the code I wrote to find a sequence of integers in any given array is not catching all the instances. Could you help, please?

Here's the code:

```<code>def array123(nums):
  if len(nums) < 3:
    return False
  else:
    for i in range(len(nums) - 1):
      if nums[i:i + 3] == [1, 2, 3]:
        return True
      return False
</code>```

答:
The return False part should be indented as follows.

```<code>def array123(nums):
  if len(nums) < 3:
    return False
  else:
    for i in range(len(nums) - 1):
      if nums[i:i + 3] == [1, 2, 3]:
        return True
    return False    # This should be indented this way.
</code>```

Body:
I'm trying to figure out why the code I wrote to find a sequence of integers in any given array is not catching all the instances. Could you help, please?

Here's the code:

def array123(nums):
  if len(nums) < 3:
    return False
  else:
    for i in range(len(nums) - 1):
      if nums[i:i + 3] == [1, 2, 3]:
        return True
      return False

Body:
The return False part should be indented as follows.

def array123(nums):
  if len(nums) < 3:
    return False
  else:
    for i in range(len(nums) - 1):
      if nums[i:i + 3] == [1, 2, 3]:
        return True
    return False    # This should be indented this way.


问:
Is it possible to wait for either button A or button B?
This is code that waits for an event coming from button A.

control.waitForEvent(Button.A, EventBusValue.MICROBIT_EVT_ANY)

I want to wait for either button A OR button B to be pressed.

Is this possible?

EDIT

I know that in Scratch this is possible with something like button.any, also the above code is written in microjavascript, but it is written similarly in micropython, so maybe someone from this field can also help. Thank you.

答: In scratch, placing a [Wait for <Key Pressed (a) ||or|| Key Pressed (b)>], will do the trick, you can just slot a key pressed (a) and a key pressed (b) into the same or statement, and place the new blocks into a "Wait until" block, place this where you want the code to stop and continue on the keypress update and you're golden.</p>


问:
Count the number of multiple values in a single column in SQL
I have a long list of string values that I would like to count, in one particular column of a table.  I know this works for counting all unique values.

```<code>SELECT
    code_id ,
    COUNT(*) AS num
FROM
    mydb
GROUP BY
    code_id
ORDER BY
    code_id
</code>```

I only have a certain selection of values to count, therefore do now want all.  My list is long, but for example, if I just wanted to count the numbers of strings 'ax1', 'c39', and 'x1a' in my code_id column?  I've seen examples with multiple lines of code, one for each value which will be huge for counting many values.  I'm hoping for something like :

```<code>SELECT
    code_id ,
    COUNT(* = ('ax1, 'c39', 'x1a')) AS num
FROM
    mydb
GROUP BY
    code_id
ORDER BY
    code_id
</code>```

Desired output would be

```<code>code_id    count
ax1         39
c39         42
x1a          0
</code>```

Is there an easy way, rather than a line of code for each value to be counted?

答:
Create a CTE that returns all the string values and a LEFT join to your table to aggregate:

```<code>WITH cte AS (SELECT code_id FROM (VALUES ('ax1'), ('c39'), ('x1a')) c(code_id))
SELECT c.code_id,
       COUNT(t.code_id) AS num
FROM cte c LEFT JOIN tablename t
ON t.code_id = c.code_id
GROUP BY c.code_id;
</code>```

See the demo.

Body:
I have a long list of string values that I would like to count, in one particular column of a table.  I know this works for counting all unique values.

SELECT
    code_id ,
    COUNT(*) AS num
FROM
    mydb
GROUP BY
    code_id
ORDER BY
    code_id

I only have a certain selection of values to count, therefore do now want all.  My list is long, but for example, if I just wanted to count the numbers of strings 'ax1', 'c39', and 'x1a' in my code_id column?  I've seen examples with multiple lines of code, one for each value which will be huge for counting many values.  I'm hoping for something like :

SELECT
    code_id ,
    COUNT(* = ('ax1, 'c39', 'x1a')) AS num
FROM
    mydb
GROUP BY
    code_id
ORDER BY
    code_id

Desired output would be

code_id    count
ax1         39
c39         42
x1a          0

Is there an easy way, rather than a line of code for each value to be counted?

Body:
Create a CTE that returns all the string values and a LEFT join to your table to aggregate:

WITH cte AS (SELECT code_id FROM (VALUES ('ax1'), ('c39'), ('x1a')) c(code_id))
SELECT c.code_id,
       COUNT(t.code_id) AS num
FROM cte c LEFT JOIN tablename t
ON t.code_id = c.code_id
GROUP BY c.code_id;

See the demo.


问:
How to select ID by changing xml file with PHP
I’m trying to change an XML file by PHP.
It’s working but I can’t find how I can select the specific ID. any ideas?
For example, I would like to change the text of id ken1.
Thanks in advance!

PHP:

```<code>    <form method="post">
  <input name="ken1" id="ken1" type="text">
  <br>
  <input type="submit" name="submit" value="submit">
</form>

<?php

if(isset($_POST['submit'])) {

$data=simplexml_load_file('display.xml');
$data->data->SText->ken1->text=$_POST['ken1'];

$handle=fopen("display.xml","wb");
fwrite($handle,$data->asXML());
fclose($handle);
}

$data=simplexml_load_file('display.xml');
?>
</code>```

xml:

```<code><kendisplay>

  <meta>
    <request>setData</request>
    <version>1</version>
  </meta>
  <data>
    <SText id="p1">
      <text>test</text>
    </SText>
    <SText id="p2">
      <text>test</text>
    </SText>
    <SText id="ken1">
      <text>test</text>
    </SText>
    <SText id="wait">
      <text>test</text>
    </SText>
  </data>

</kedisplay>
</code>```

答:
So to actually use the xpath to update the document:

```<code>// assume $data has the fully parsed SimpleXMLElement document, as in the original post.
echo $data->asXML();
$ken = $data->xpath("//SText[@id='ken1']");
$ken[0]->text = "updated";
echo $data->asXML();
</code>```

And output:

(First echo of original)

```<code><?xml version="1.0"?>
<kendisplay>
<meta>
<request>setData</request>
<version>1</version>
</meta>
<data>
<SText id="p1">
<text>test</text>
</SText>
<SText id="p2">
<text>test</text>
</SText>
<SText id="ken1">
<text>test</text>
</SText>
<SText id="wait">
<text>test</text>
</SText>
</data>
</kendisplay>
</code>```

(And second echo with updated value)

```<code><?xml version="1.0"?>
<kendisplay>
<meta>
<request>setData</request>
<version>1</version>
</meta>
<data>
<SText id="p1">
<text>test</text>
</SText>
<SText id="p2">
<text>test</text>
</SText>
<SText id="ken1">
<text>updated</text>
</SText>
<SText id="wait">
<text>test</text>
</SText>
</data>
</kendisplay>
</code>```

Remember the xpath returns an array of 0 or more SimpleXMLElements which satisfy the path query.  So be sure to handle that appropriately.

Body:
I’m trying to change an XML file by PHP.
It’s working but I can’t find how I can select the specific ID. any ideas?
For example, I would like to change the text of id ken1.
Thanks in advance!

PHP:

    <form method="post">
  <input name="ken1" id="ken1" type="text">

  <input type="submit" name="submit" value="submit">
</form>

<?php

if(isset($_POST['submit'])) {

$data=simplexml_load_file('display.xml');
$data->data->SText->ken1->text=$_POST['ken1'];

$handle=fopen("display.xml","wb");
fwrite($handle,$data->asXML());
fclose($handle);
}

$data=simplexml_load_file('display.xml');
?>

xml:

<kendisplay>

  <meta>
    <request>setData</request>
    <version>1</version>
  </meta>
  <data>
    <SText id="p1">
      <text>test</text>
    </SText>
    <SText id="p2">
      <text>test</text>
    </SText>
    <SText id="ken1">
      <text>test</text>
    </SText>
    <SText id="wait">
      <text>test</text>
    </SText>
  </data>

</kedisplay>

Body:
So to actually use the xpath to update the document:

// assume $data has the fully parsed SimpleXMLElement document, as in the original post.
echo $data->asXML();
$ken = $data->xpath("//SText[@id='ken1']");
$ken[0]->text = "updated";
echo $data->asXML();

And output:

(First echo of original)

<?xml version="1.0"?>
<kendisplay>
<meta>
<request>setData</request>
<version>1</version>
</meta>
<data>
<SText id="p1">
<text>test</text>
</SText>
<SText id="p2">
<text>test</text>
</SText>
<SText id="ken1">
<text>test</text>
</SText>
<SText id="wait">
<text>test</text>
</SText>
</data>
</kendisplay>

(And second echo with updated value)

<?xml version="1.0"?>
<kendisplay>
<meta>
<request>setData</request>
<version>1</version>
</meta>
<data>
<SText id="p1">
<text>test</text>
</SText>
<SText id="p2">
<text>test</text>
</SText>
<SText id="ken1">
<text>updated</text>
</SText>
<SText id="wait">
<text>test</text>
</SText>
</data>
</kendisplay>

Remember the xpath returns an array of 0 or more SimpleXMLElements which satisfy the path query.  So be sure to handle that appropriately.


问:
Display tag like structure in Staggered Recyclerview
I am working on a tag structure currently and to display that I have used Staggeredgrid layout manager of Recyclerview to get the required result as below image:

But when I used StaggeredGrid, It is providing result as below:

My code to display adapter in Recyclerview is as given below:

```<code>val staggeredGridLayoutManager = StaggeredGridLayoutManager(2, LinearLayoutManager.VERTICAL)
rvTags.layoutManager = staggeredGridLayoutManager
rvTags.adapter = AllergyAdapter(tags)
</code>```

On increasing the span count to 3, all the items are contracting.
I want that if "Peanut butter" is big enough then only 1 item should come in 1 row and if "neem, garlic and soy" can fit in 1 row, then it should fit.

Basically, I need a way to dynamic span count according to the content size.

Any help will be appreciated.

The suggested answer is not working because it is counting span count for whole of Recyclerview and Not particular row wise.

答: I came across such a requirement and ideally, a Flexbox should be a good option to try.</p>

Body:
I am working on a tag structure currently and to display that I have used Staggeredgrid layout manager of Recyclerview to get the required result as below image:

But when I used StaggeredGrid, It is providing result as below:

My code to display adapter in Recyclerview is as given below:

val staggeredGridLayoutManager = StaggeredGridLayoutManager(2, LinearLayoutManager.VERTICAL)
rvTags.layoutManager = staggeredGridLayoutManager
rvTags.adapter = AllergyAdapter(tags)

On increasing the span count to 3, all the items are contracting.
I want that if "Peanut butter" is big enough then only 1 item should come in 1 row and if "neem, garlic and soy" can fit in 1 row, then it should fit.

Basically, I need a way to dynamic span count according to the content size.

Any help will be appreciated.

The suggested answer is not working because it is counting span count for whole of Recyclerview and Not particular row wise.


问:
Way to avoid nested ifelse statement in R
I have a dataframe that includes various ages and a value for each age. I would like to classify the different ages into broader age groups. To do so, I had to create a fairly complicated nested ifelse statement:

```<code>library(tidyverse)

df <- data.frame(age = c("15 to 17", "18 and 19", "20 to 24", "25 to 29", "30 to 34", "35 to 39", "40 to 44", "45 to 49", "50 to 54", "55 to 59"),
                 value = sample(1000:2000,10, replace=TRUE))

new_df = df %>%
  mutate(age_band =
           ifelse(age %in% c("15 to 17","18 and 19"), '15 to 19', ifelse(age %in% c("20 to 24","25 to 29"), '20s', ifelse(age %in% c("30 to 34","35 to 39"), '30s','40+'))))
</code>```

Is there any way to do this without using such complex nested statements? The data goes all the way to ages 85 and over, and it got very complicated to classify each different age group.

答:
Following @Claudiu Papasteri recommendations:

Package

```<code>library(dplyr)
</code>```

Solution

```<code>df %>%
  mutate(age_band = case_when( age %in% c("15 to 17","18 and 19") ~  '15 to 19',
                               age %in% c("20 to 24","25 to 29") ~ '20s',
                               age %in% c("30 to 34","35 to 39") ~ '30s',
                               TRUE ~'40+')
         )
</code>```

ps: I would include all specific statements in case_when, even the last one for "40+", this way you can keep track of any problem in your dataset. Because if something is missing, or you have a typo, everything else will be coded as "40+". So by stating every case you can catch the problem and fix everything before running an analysis or generating graphs. And the last statement could be changed to TRUE ~ age. This means, whatever remains, use the same value, or TRUE ~ NA, that you recode the remaining stuff for missing. So you know that all missing means you have a problem you have to fix.

Output

```<code>         age value age_band
1   15 to 17  1432 15 to 19
2  18 and 19  1112 15 to 19
3   20 to 24  1265      20s
4   25 to 29  1076      20s
5   30 to 34  1212      30s
6   35 to 39  1238      30s
7   40 to 44  1384      40+
8   45 to 49  1612      40+
9   50 to 54  1606      40+
10  55 to 59  1897      40+
</code>```

Body:
I have a dataframe that includes various ages and a value for each age. I would like to classify the different ages into broader age groups. To do so, I had to create a fairly complicated nested ifelse statement:

library(tidyverse)

df <- data.frame(age = c("15 to 17", "18 and 19", "20 to 24", "25 to 29", "30 to 34", "35 to 39", "40 to 44", "45 to 49", "50 to 54", "55 to 59"),
                 value = sample(1000:2000,10, replace=TRUE))

new_df = df %>%
  mutate(age_band =
           ifelse(age %in% c("15 to 17","18 and 19"), '15 to 19', ifelse(age %in% c("20 to 24","25 to 29"), '20s', ifelse(age %in% c("30 to 34","35 to 39"), '30s','40+'))))

Is there any way to do this without using such complex nested statements? The data goes all the way to ages 85 and over, and it got very complicated to classify each different age group.

Body:
Following @Claudiu Papasteri recommendations:

Package

library(dplyr)

Solution

df %>%
  mutate(age_band = case_when( age %in% c("15 to 17","18 and 19") ~  '15 to 19',
                               age %in% c("20 to 24","25 to 29") ~ '20s',
                               age %in% c("30 to 34","35 to 39") ~ '30s',
                               TRUE ~'40+')
         )

ps: I would include all specific statements in case_when, even the last one for "40+", this way you can keep track of any problem in your dataset. Because if something is missing, or you have a typo, everything else will be coded as "40+". So by stating every case you can catch the problem and fix everything before running an analysis or generating graphs. And the last statement could be changed to TRUE ~ age. This means, whatever remains, use the same value, or TRUE ~ NA, that you recode the remaining stuff for missing. So you know that all missing means you have a problem you have to fix.

Output

         age value age_band
1   15 to 17  1432 15 to 19
2  18 and 19  1112 15 to 19
3   20 to 24  1265      20s
4   25 to 29  1076      20s
5   30 to 34  1212      30s
6   35 to 39  1238      30s
7   40 to 44  1384      40+
8   45 to 49  1612      40+
9   50 to 54  1606      40+
10  55 to 59  1897      40+


问:
Vuejs how to pass image url as prop to be used as css variable for css animation
I have a component that has a hover animation where 4 images are rotated in a loop:

animation: changeImg-1 2.5s linear infinite;

```<code>@keyframes changeImg-1 {
  0%, 100% { background-image: url('images/wel1.png'); }
  25% { background-image: url('images/wel2.png'); }
  50% { background-image: url('images/wel3.png'); }
  75% { background-image: url('images/wel4.png'); }
}
</code>```

Now I want to make this component reusable by being able to pass image strings in as props, those get assigned as css variables which then get picked up by the animation.

I got as far as defining the css variable with a path in a computed property which is then used in the css:

```<code>computed: {
    userStyle () {
      return {
        '--myBackground': `url(${require('@/components/ImagesInText/images/wel1.png')})`,
      }
    }
  },
</code>```

CSS:

```<code>.image {
background:var(--myBackground);
}
</code>```

What I can't get to work is to pick up an image path from props and use it in the computed property...

```<code>   props: {
    image: { type: String, default: '@/components/ImagesInText/images/wel1.png' },
  },
</code>```

If I do this below I get en error: Cannot find module '@/components/ImagesInText/images/wel1.png'"

```<code>computed: {
    userStyle () {
      return {

        '--myBackground': `url(${require( this.image )})`,
      }
    }
  },
</code>```

答:
As the way mentioned In this thread. it's working perfectly for me.</p>
```<code><div class="register-img" :style="{'background-image': 'url(' + require('@/assets/images/register-image.png') + ')'}"></div>
</code>```

Body:
I have a component that has a hover animation where 4 images are rotated in a loop:

animation: changeImg-1 2.5s linear infinite;

@keyframes changeImg-1 {
  0%, 100% { background-image: url('images/wel1.png'); }
  25% { background-image: url('images/wel2.png'); }
  50% { background-image: url('images/wel3.png'); }
  75% { background-image: url('images/wel4.png'); }
}

Now I want to make this component reusable by being able to pass image strings in as props, those get assigned as css variables which then get picked up by the animation.

I got as far as defining the css variable with a path in a computed property which is then used in the css:

computed: {
    userStyle () {
      return {
        '--myBackground': `url(${require('@/components/ImagesInText/images/wel1.png')})`,
      }
    }
  },

CSS:

.image {
background:var(--myBackground);
}

What I can't get to work is to pick up an image path from props and use it in the computed property...

   props: {
    image: { type: String, default: '@/components/ImagesInText/images/wel1.png' },
  },

If I do this below I get en error: Cannot find module '@/components/ImagesInText/images/wel1.png'"

computed: {
    userStyle () {
      return {

        '--myBackground': `url(${require( this.image )})`,
      }
    }
  },

Body:
As the way mentioned In this thread. it's working perfectly for me.

<div class="register-img" :style="{'background-image': 'url(' + require('@/assets/images/register-image.png') + ')'}"></div>


问:
Android Jetpack Compose: Can't set backgroundColor for OutlinedTextField
I'm new to Jetpack Compose, and trying to set backgroundColor to an OutlinedTextField.

This is my code

```<code>fun MyTextField() {
    Column(Modifier
        .background(Color.Gray)
        .fillMaxSize()
        .padding(8.dp)
    ) {
        OutlinedTextField(
            value = "text",
            onValueChange = {},
            colors = TextFieldDefaults.outlinedTextFieldColors(
                backgroundColor = Color.White, // does not work
                unfocusedBorderColor = Color.Red,
                textColor = Color.Red
            ),
            // modifier = Modifier.background(Color.White) - works but not as I expected
        )
    }
}
</code>```

The backgroundColor = Color.White does not work at all. The OutlinedTextField stays transparent:

When using the modifier the background is changed, but also the part reserved for Label, even when I don't have a label:

Any ideas what am I doing wrong? Thank you.

答:
I found this

```<code>Row(
        Modifier
            .background(
                colorResource(id = R.color.col_EEEEEE)
            )
            .align(BottomEnd)
            .padding(10.dp)
    ) {
        OutlinedTextField(
            modifier = Modifier
                .fillMaxWidth()
                .padding(start = 20.dp, end = 20.dp).background(Color.White, RoundedCornerShape(22.dp)),
            shape = RoundedCornerShape(22.dp),
            value = "",
            onValueChange = {},
            textStyle = MaterialTheme.typography.caption
        )
    }
</code>```

In the above code, I added required background color with the shape in the modifier. The modifier shape property is the same as the OutlinedTextField shape property, which gives required effect.

Body:
I'm new to Jetpack Compose, and trying to set backgroundColor to an OutlinedTextField.

This is my code

fun MyTextField() {
    Column(Modifier
        .background(Color.Gray)
        .fillMaxSize()
        .padding(8.dp)
    ) {
        OutlinedTextField(
            value = "text",
            onValueChange = {},
            colors = TextFieldDefaults.outlinedTextFieldColors(
                backgroundColor = Color.White, // does not work
                unfocusedBorderColor = Color.Red,
                textColor = Color.Red
            ),
            // modifier = Modifier.background(Color.White) - works but not as I expected
        )
    }
}

The backgroundColor = Color.White does not work at all. The OutlinedTextField stays transparent:

When using the modifier the background is changed, but also the part reserved for Label, even when I don't have a label:

Any ideas what am I doing wrong? Thank you.

Body:
I found this

Row(
        Modifier
            .background(
                colorResource(id = R.color.col_EEEEEE)
            )
            .align(BottomEnd)
            .padding(10.dp)
    ) {
        OutlinedTextField(
            modifier = Modifier
                .fillMaxWidth()
                .padding(start = 20.dp, end = 20.dp).background(Color.White, RoundedCornerShape(22.dp)),
            shape = RoundedCornerShape(22.dp),
            value = "",
            onValueChange = {},
            textStyle = MaterialTheme.typography.caption
        )
    }

In the above code, I added required background color with the shape in the modifier. The modifier shape property is the same as the OutlinedTextField shape property, which gives required effect.


问:
Show field based on multiple enum values - Odin
I want to Show the field in UnityInspector based on specific enum field.

Lets say this is the enum class

```<code>  public enum Mode
    {
        None,
        Movement,
        Rotation,
        Scale
    }
</code>```

I want to enable this field if "Movement or Scale" is selected from the enum dropdown, otherwise hide the field.

```<code>        public Vector3 NewValues;
</code>```

With Odin I can do:

```<code>    [ShowIf("tweenMode", TweenMode.Movement)]
    public Vector3 NewValues;
</code>```

But that will work only on Movement enum. Any idea on how to make it work on multiple enums? Thanks

答:
Afaik you can simply do something like

```<code>private bool showNewValues => tweenMode == TweenMode.Movement || tweenMode == TweenMode.Rotation;

[ShowIf(nameof(showNewValues))]
public Vector3 NewValues;
</code>```

See ShowIf

Body:
I want to Show the field in UnityInspector based on specific enum field.

Lets say this is the enum class

  public enum Mode
    {
        None,
        Movement,
        Rotation,
        Scale
    }

I want to enable this field if "Movement or Scale" is selected from the enum dropdown, otherwise hide the field.

        public Vector3 NewValues;

With Odin I can do:

    [ShowIf("tweenMode", TweenMode.Movement)]
    public Vector3 NewValues;

But that will work only on Movement enum. Any idea on how to make it work on multiple enums? Thanks

Body:
Afaik you can simply do something like

private bool showNewValues => tweenMode == TweenMode.Movement || tweenMode == TweenMode.Rotation;

[ShowIf(nameof(showNewValues))]
public Vector3 NewValues;

See ShowIf


问:
Is it possible to control how often a Spring Kafka Message Listener switches between its assigned partitions?
When a Spring Kafka MessageListener is consuming messages from multiple partitions, it keeps processing messages from one partition until there are no more messages and only after that it continues with the next partition. (based on my observations)

Is it possible to set a max number of messages/batches and tell the Listener to switch faster to the next partition rather than later?

This would improve fairness and consume evenly from all assigned partitions.

答:
switch faster to the next partition, consume evenly from all assigned partitions

I don't think Kafka has any properties for this. kafka consumer config

It's weird. You could see a partition replica in Kafka as a log file. Your consumer poll runs in one thread, for better performance, it should consume from one file, and the next poll will consume from another file rather than separate it and consume evenly from many partitions for each poll, right? Eventually, you still need to consume all of the messages on the topic.


问:
JUnit test case for Camel route for ActiveMQ
I have a camel route in MyRouteBuilder.java file which is consuming messages from ActiveMQ:

```<code>from("activemq:queue:myQueue" )
.process(consumeDroppedMessage)
.log(">>> I am here");
</code>```

I wrote a test case for the following like this :

@Override
public RouteBuilder createRouteBuilder() throws Exception {
    return new MyRouteBuilder();
}

@Test
void testMyTest() throws Exception {
    String queueInputMessage = "My Msg";
    template.sendBody("activemq:queue:myQueue", queueInputMessage);
    assertMockEndpointsSatisfied();

}
```
<p>When I run the unit test case I get this strange error:</p>
```7:53:26.175 [main] DEBUG org.apache.camel.impl.engine.InternalRouteStartupManager - Route: route1 >>> Route[activemq://queue:null -> null]
17:53:26.175 [main] DEBUG org.apache.camel.impl.engine.InternalRouteStartupManager - Starting consumer (order: 1000) on route: route1
17:53:26.175 [main] DEBUG org.apache.camel.support.DefaultConsumer - Build consumer: Consumer[activemq://queue:null]
17:53:26.185 [main] DEBUG org.apache.camel.support.DefaultConsumer - Init consumer: Consumer[activemq://queue:null]
17:53:26.185 [main] DEBUG org.apache.camel.support.DefaultConsumer - Starting consumer: Consumer[activemq://queue:null]
17:53:26.213 [main] DEBUG org.apache.activemq.thread.TaskRunnerFactory - Initialized TaskRunnerFactory[ActiveMQ Task] using ExecutorService: java.util.concurrent.ThreadPoolExecutor@3fffff43[Running, pool size = 0, active threads = 0, queued tasks = 0, completed tasks = 0]
17:53:26.215 [main] DEBUG org.apache.activemq.transport.failover.FailoverTransport - Reconnect was triggered but transport is not started yet. Wait for start to connect the transport.
17:53:26.334 [main] DEBUG org.apache.activemq.transport.failover.FailoverTransport - Started unconnected
17:53:26.334 [main] DEBUG org.apache.activemq.transport.failover.FailoverTransport - Waking up reconnect task
17:53:26.335 [ActiveMQ Task-1] DEBUG org.apache.activemq.transport.failover.FailoverTransport - urlList connectionList:[tcp://localhost:61616], from: [tcp://localhost:61616]
17:53:26.339 [main] DEBUG org.apache.camel.component.jms.DefaultJmsMessageListenerContainer - Established shared JMS Connection
17:53:26.340 [main] DEBUG org.apache.camel.component.jms.DefaultJmsMessageListenerContainer - Resumed paused task: org.springframework.jms.listener.DefaultMessageListenerContainer$AsyncMessageListenerInvoker@58c34bb3
17:53:26.372 [ActiveMQ Task-1] DEBUG org.apache.activemq.transport.failover.FailoverTransport - Attempting 0th connect to: tcp://localhost:61616
17:53:28.393 [ActiveMQ Task-1] DEBUG org.apache.activemq.transport.failover.FailoverTransport - Connect fail to: tcp://localhost:61616, reason: {}
```
<p>I am especially stumped to see these messages:</p>
```Route: route1 >>> Route[activemq://queue:null -> null]
```
<p>and</p>
```urlList connectionList:[tcp://localhost:61616], from: [tcp://localhost:61616]
```

Why is the queue coming up as null though I have a proper queue name? Also why is the broker url tcp://localhost:61616?

I want to run this unit test case so that it runs properly in all environments like: local,  DIT , SIT, PROD etc. So, for that I cannot afford the broker url to be: tcp://localhost:61616.

Any ideas as to what I am doing wrong here and what I should be doing?

EDIT 1:

One of the issues that I am seeing is even before the test class is called, the MyRouteBuilder() inside createRouteBuilder() is invoked, leading to the issues that I see in the log.

答:
The "activemq:queue:.." is telling Camel to use the auto-configure magic behind the scenes (which uses default url) and your use case is beyond that.

You need to configure a connection factory (ActiveMQConnectionFactory) and configure a camel-jms component to use that connection factory.

The connection factory allows you to specify url, userName, password, default connection settings and setup SSL.

A best practice is to externalize the url, userName, password and queue to a properties file so you can change those across the environments-- local, DIT, SIT and prod, etc.

NOTE: Use org.apache.camel/camel-jms component, and not the org.apache.activemq/activemq-camel component. activemq-camel is deprecated and being removed in ActiveMQ 5.17.x.

Body:
I have a camel route in MyRouteBuilder.java file which is consuming messages from ActiveMQ:

from("activemq:queue:myQueue" )
.process(consumeDroppedMessage)
.log(">>> I am here");

I wrote a test case for the following like this :

@Override
public RouteBuilder createRouteBuilder() throws Exception {
    return new MyRouteBuilder();
}

@Test
void testMyTest() throws Exception {
    String queueInputMessage = "My Msg";
    template.sendBody("activemq:queue:myQueue", queueInputMessage);
    assertMockEndpointsSatisfied();

}

When I run the unit test case I get this strange error:

7:53:26.175 [main] DEBUG org.apache.camel.impl.engine.InternalRouteStartupManager - Route: route1 >>> Route[activemq://queue:null -> null]
17:53:26.175 [main] DEBUG org.apache.camel.impl.engine.InternalRouteStartupManager - Starting consumer (order: 1000) on route: route1
17:53:26.175 [main] DEBUG org.apache.camel.support.DefaultConsumer - Build consumer: Consumer[activemq://queue:null]
17:53:26.185 [main] DEBUG org.apache.camel.support.DefaultConsumer - Init consumer: Consumer[activemq://queue:null]
17:53:26.185 [main] DEBUG org.apache.camel.support.DefaultConsumer - Starting consumer: Consumer[activemq://queue:null]
17:53:26.213 [main] DEBUG org.apache.activemq.thread.TaskRunnerFactory - Initialized TaskRunnerFactory[ActiveMQ Task] using ExecutorService: java.util.concurrent.ThreadPoolExecutor@3fffff43[Running, pool size = 0, active threads = 0, queued tasks = 0, completed tasks = 0]
17:53:26.215 [main] DEBUG org.apache.activemq.transport.failover.FailoverTransport - Reconnect was triggered but transport is not started yet. Wait for start to connect the transport.
17:53:26.334 [main] DEBUG org.apache.activemq.transport.failover.FailoverTransport - Started unconnected
17:53:26.334 [main] DEBUG org.apache.activemq.transport.failover.FailoverTransport - Waking up reconnect task
17:53:26.335 [ActiveMQ Task-1] DEBUG org.apache.activemq.transport.failover.FailoverTransport - urlList connectionList:[tcp://localhost:61616], from: [tcp://localhost:61616]
17:53:26.339 [main] DEBUG org.apache.camel.component.jms.DefaultJmsMessageListenerContainer - Established shared JMS Connection
17:53:26.340 [main] DEBUG org.apache.camel.component.jms.DefaultJmsMessageListenerContainer - Resumed paused task: org.springframework.jms.listener.DefaultMessageListenerContainer$AsyncMessageListenerInvoker@58c34bb3
17:53:26.372 [ActiveMQ Task-1] DEBUG org.apache.activemq.transport.failover.FailoverTransport - Attempting 0th connect to: tcp://localhost:61616
17:53:28.393 [ActiveMQ Task-1] DEBUG org.apache.activemq.transport.failover.FailoverTransport - Connect fail to: tcp://localhost:61616, reason: {}

I am especially stumped to see these messages:

Route: route1 >>> Route[activemq://queue:null -> null]

and

urlList connectionList:[tcp://localhost:61616], from: [tcp://localhost:61616]

Why is the queue coming up as null though I have a proper queue name? Also why is the broker url tcp://localhost:61616?

I want to run this unit test case so that it runs properly in all environments like: local,  DIT , SIT, PROD etc. So, for that I cannot afford the broker url to be: tcp://localhost:61616.

Any ideas as to what I am doing wrong here and what I should be doing?

EDIT 1:

One of the issues that I am seeing is even before the test class is called, the MyRouteBuilder() inside createRouteBuilder() is invoked, leading to the issues that I see in the log.


问:
How to perform a simple calculation to with my bash script variables in gnuplot
I have variables M_i and M > M_i. I want to make a splot where one of the columns of my data file is evaluated using these variables...

Something like this:

splot "9.90000000orbs.dat" u 1:2:(10+4*($M-$M_i))

I can't figure out the correct syntax for the last column specification. How do I do it?

Thanks in advance.

答:
Your question is not clear enough.
Let's say you want to plot column 4 when data of column 3 are greater than variable m =>

```<code>if (!exist("m")){m=14}
splot "9.90000000orbs.dat" u 1:2:($3<m ? $3: $4)
</code>```

or give two line example of your file and more explanation.

You can invoke from bash using :

```<code>$> gnuplot file.plt -e "m=$M"
</code>```

Body:
Your question is not clear enough.
Let's say you want to plot column 4 when data of column 3 are greater than variable m =>

if (!exist("m")){m=14}
splot "9.90000000orbs.dat" u 1:2:($3<m ? $3: $4)

or give two line example of your file and more explanation.

You can invoke from bash using :

$> gnuplot file.plt -e "m=$M"


问:
"File not found" trying to listdir() a path dragged-and-dropped from Finder to terminal in Python
after researching this error the solution most suggested is to use absolute path instead of relative (which makes sense and obvious)

however this doesnt work in macos.

and I thought python works on all platforms the same

my code:

```<code>#!/usr/bin/python3
import os
directory = input("insert path: ")
for filename in os.listdir(directory):
    f = os.path.join(directory, filename)
    if os.path.isfile(f):
        print(f)
</code>```

once I run this I get a prompt asking me to insert the directory path. so I drag and drop the directory and the absolute path is inserted.

right after I hit enter. I get the famous error file or directory not found.
any help ?

答:
When I run your code and drag a folder from finder into the (iterm2) terminal window, it inserts a space after the path, probably to be helpful in case you want to pass other arguments to a shell, which would be space separated. Remove the space manually before hitting enter, and it should work.

When the path you drag in has spaces, Finder seems to try to quote these spaces, e.g., foo bar becomes foo\ bar. Again this makes sense for a shell, where spaces can be escaped like this, but your Python program is not a shell, so you'd check for \  and replace it with a plain   again:

directory = directory.replace(r"\ ", " ")
```
<p>And if you want to do that kind of processing, you could also remove the trailing space for better usability:</p>
```directory = directory.strip()
```

Body:
after researching this error the solution most suggested is to use absolute path instead of relative (which makes sense and obvious)

however this doesnt work in macos.

and I thought python works on all platforms the same

my code:

#!/usr/bin/python3
import os
directory = input("insert path: ")
for filename in os.listdir(directory):
    f = os.path.join(directory, filename)
    if os.path.isfile(f):
        print(f)

once I run this I get a prompt asking me to insert the directory path. so I drag and drop the directory and the absolute path is inserted.

right after I hit enter. I get the famous error file or directory not found.
any help ?

Body:
When I run your code and drag a folder from finder into the (iterm2) terminal window, it inserts a space after the path, probably to be helpful in case you want to pass other arguments to a shell, which would be space separated. Remove the space manually before hitting enter, and it should work.

When the path you drag in has spaces, Finder seems to try to quote these spaces, e.g., foo bar becomes foo\ bar. Again this makes sense for a shell, where spaces can be escaped like this, but your Python program is not a shell, so you'd check for \  and replace it with a plain   again:

directory = directory.replace(r"\ ", " ")

And if you want to do that kind of processing, you could also remove the trailing space for better usability:

directory = directory.strip()


问:
Unique record in Asp.Net SQL
I asked this question previously but the answers weren't what I was looking for.

I created a table in Asp.net without using code. It contains two columns.

YourUserId and FriendUserId

This is a many to many relationship.

Heres what I want:

There can be multiple records with your name as the UserId, there can also be multiple records with FriendUserId being the same...but there cannot be multiple records with both being the same. For example:

Dave : Greg

Dave : Chris

Greg : Chris

Chris : Greg

is good

Dave : Greg

Dave : Greg

is not good.

I right clicked on the table and chose Indexes/Keys. I then put both columns in the columns section and chose to make the unique. I thought this would make them unique as a whole but individually not unique.

If you go to the Dataset, it show keys next to both columns and says that there is a constraint with both columns being checked.

Is there a way of just making sure that you are not inserting a duplicate copy of a record into the table without individual columns being unique?

I tried controling it with my sql insert statement but that did not work. This is what I tried.

INSERT INTO [FriendRequests] ([UserId], [FriendUserId]) VALUES ('"+UserId+"', '"+PossibleFriend+"') WHERE NOT EXIST (SELECT [UserId], [FriendUserId] FROM [FriendRequests])

That didn't work for some reason.
Thank you for your help!

答:
I have a better idea.  Create a new table.  Called FriendRequestRelationships.  Have the following columns

FriendRelationshipId (PRIMARY KEY)
UserId_1 (FOREIGN KEY CONSTRAINT)
UserId_2 (FOREIGN KEY CONSTRAINT)

Put a unique constraint to only allow one relationship wit UserId_1 and UserId_2.  This table now serves as your many-to-many relationship harness.

Create a scalar function that can return the FriendUserId for a UserId, lets say it's called fn_GetFriendUserIdForUserId

You can now display your relationships by running the following query

SELECT dbo.fn_GetFriendUserIdForUserId(UserId_1) AS 'Friend1',
       dbo.fn_GetFriendUserIdForUserId(UserId_2) AS 'Friend2',
FROM FriendRelationshipId

ContentLicense: CC BY-SA 2.5

Title: Unique record in Asp.Net SQL

OwnerDisplayName: Danny G


问:
Error when using PutInfluxDatabaseRecord in Apache Ni-Fi due to time stamp
I have created a Apache Ni-Fi flow 1 to fetch a simple table from a MySQL server and copy it into InfluxDB after some data transformation.

I use the PutInfluxDataRecord processor to convert the data from AVRO format into In-Line protocol and to insert the data into Influx (by using StandardInfluxDatabaseService 1.15.0-SNAPSHOT controller service).

In the Avro Reader 1.15.2 controller service I have selected the option Schema Access Strategy: Use Embedded Avro Schema.

In the properties of the PutInfluxDataRecord processor I set the value of the Timestamp field property as "time_stamp", which is the name of the field containing the timestamp in the input flow of the processor.

When running the flow, I get the following error:

PutInfluxDatabaseRecord[id=6d21f785-017e-1000-e0da-0528ab2de725]
Failed procession flow file f0c553ef-7a4b-414c-bd9f-be2c6b7bf4f5 due
to For input string: "2021-01-11 09:00:00.0":
java.lang.NumberFormatException: For input string: "2021-01-11
09:00:00.0"

In the property tab of the PutInfluxDatabaseRecord processor, in the help text of the Timestamp field property it says that the supported types are: java.util.Date, java.lang.Number and java.lang.String.

Any hints how I could fix this?

Thanks,

Bernardo

Apache Ni-Fi flow

答:
I fixed the issue by changing the settings in the QueryDatabaseTable processor that I used to fetch the data from the MySQL server. I did the following change:

Use Avro Logical Types: true

This prevented Ni-Fi to set time_stamp as a string.


问:
fill a column with its most frequent
I want to fill a column 'col2' with its most frequent value grouped by some other column.However, it should not affect other columns of the dataframe.

```<code>import pandas as pd
d = {'col1': ['green','green','green','blue','blue','blue'],'col2': ['gx','gx','ow','nb','nb','mj'],'col3': ['omg','omg','omg','qwe','qwe','omg'],'col4':['s','u','s','s','u','u']}
dftest = pd.DataFrame(data=d)
dftest
</code>```

I ran below code which is working for col1 and col2 but no idea how to keep other columns intact.

```<code>dftest = dftest.groupby('col1')['col2'].apply(lambda x: x.value_counts().index[0]).reset_index()
</code>```

Expected dataframe:

col1
col2
col3
col4

green
gx
omg
s

green
gx
omg
u

green
gx
omg
s

blue
gx
qwe
s

blue
gx
qwe
u

blue
gx
omg
u

答:
Your expected output appears slightly off since blue has a different most seen string in the original DataFrame. The following code should get you the desired output.

```<code>dftest.assign(
    col2=dftest.groupby("col1", as_index=False)["col2"].transform(
        lambda x: x.value_counts().idxmax()
    )
)

    col1 col2 col3 col4
0  green   gx  omg    s
1  green   gx  omg    u
2  green   gx  omg    s
3   blue   nb  qwe    s
4   blue   nb  qwe    u
5   blue   nb  omg    u
</code>```

Title: fill a column with its most frequent

Body:
I want to fill a column 'col2' with its most frequent value grouped by some other column.However, it should not affect other columns of the dataframe.

import pandas as pd
d = {'col1': ['green','green','green','blue','blue','blue'],'col2': ['gx','gx','ow','nb','nb','mj'],'col3': ['omg','omg','omg','qwe','qwe','omg'],'col4':['s','u','s','s','u','u']}
dftest = pd.DataFrame(data=d)
dftest

I ran below code which is working for col1 and col2 but no idea how to keep other columns intact.

dftest = dftest.groupby('col1')['col2'].apply(lambda x: x.value_counts().index[0]).reset_index()

Expected dataframe:

col1
col2
col3
col4

green
gx
omg
s

green
gx
omg
u

green
gx
omg
s

blue
gx
qwe
s

blue
gx
qwe
u

blue
gx
omg
u

Body:
Your expected output appears slightly off since blue has a different most seen string in the original DataFrame. The following code should get you the desired output.

dftest.assign(
    col2=dftest.groupby("col1", as_index=False)["col2"].transform(
        lambda x: x.value_counts().idxmax()
    )
)

    col1 col2 col3 col4
0  green   gx  omg    s
1  green   gx  omg    u
2  green   gx  omg    s
3   blue   nb  qwe    s
4   blue   nb  qwe    u
5   blue   nb  omg    u


问:
Django docker logging
I am running docker on my Mac.  I am having an issue with my views.py and I am trying to print out to the Mac docker desktop some messages to try to debug my code.  I have followed

Django and docker: outputting information to console

and it doesn't seem to work for me.  The only thing that gets printed out to the docker desktop logs is just errors when they occur,  Normally all I get is just the 200 ok from the http request.  I have used the print statement and the info statement and neither of them print out.

```<code>------------------------------------ setttings.py ------------------------------------

from pathlib import Path
import os
import logging.config
import json

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

#Logging Config

LOGGING = {
        'version': 1,
        'disable_existing_loggers': False,
        'formatters': {
            'default': {
                'format': '[DJANGO] %(levelname)s %(asctime)s %(module)s '
                          '%(name)s.%(funcName)s:%(lineno)s: %(message)s'
            },
        },
        'handlers': {
            'console': {
                'level': 'DEBUG',
                'class': 'logging.StreamHandler',
                'formatter': 'default',
            }
        },
        'loggers': {
            '*': {
                'handlers': ['console'],
                'level': 'DEBUG',
                'propagate': True,
            }
        },
    }

------------------------------------ views.py ------------------------------------

from django.shortcuts import render
from django.http import HttpResponseRedirect
from django.urls import reverse_lazy
from .login_model import LoginForm
import logging
logger = logging.getLogger(__name__)

# Create your views here.

def load_index(request):
    logger.info('in index from logger\n')
    return render(request, 'index.html')

def login(request):
    logger.info('in login from logger\n')
    return render(request, 'login.html')

def login_validator(request):

    if request.method == 'POST':
        print(f"method is post")
        logger.info('in login validator')

    print("returning in login validator")
    return render(request, 'index.html')
</code>```

答:
Not sure why I am not able to see the logs on the Docker console, but as a workaround stdout.write works.  Removed all the log stuff from the settings.py and added the following to the views.py file.

```<code>import sys

sys.stdout.write("Message goes here. \n")
</code>```

in the docker console I am now able to see the messages.

Title: Django docker logging

Body:
I am running docker on my Mac.  I am having an issue with my views.py and I am trying to print out to the Mac docker desktop some messages to try to debug my code.  I have followed

Django and docker: outputting information to console

and it doesn't seem to work for me.  The only thing that gets printed out to the docker desktop logs is just errors when they occur,  Normally all I get is just the 200 ok from the http request.  I have used the print statement and the info statement and neither of them print out.

------------------------------------ setttings.py ------------------------------------

from pathlib import Path
import os
import logging.config
import json

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

#Logging Config

LOGGING = {
        'version': 1,
        'disable_existing_loggers': False,
        'formatters': {
            'default': {
                'format': '[DJANGO] %(levelname)s %(asctime)s %(module)s '
                          '%(name)s.%(funcName)s:%(lineno)s: %(message)s'
            },
        },
        'handlers': {
            'console': {
                'level': 'DEBUG',
                'class': 'logging.StreamHandler',
                'formatter': 'default',
            }
        },
        'loggers': {
            '*': {
                'handlers': ['console'],
                'level': 'DEBUG',
                'propagate': True,
            }
        },
    }

------------------------------------ views.py ------------------------------------

from django.shortcuts import render
from django.http import HttpResponseRedirect
from django.urls import reverse_lazy
from .login_model import LoginForm
import logging
logger = logging.getLogger(__name__)

# Create your views here.

def load_index(request):
    logger.info('in index from logger\n')
    return render(request, 'index.html')

def login(request):
    logger.info('in login from logger\n')
    return render(request, 'login.html')

def login_validator(request):

    if request.method == 'POST':
        print(f"method is post")
        logger.info('in login validator')

    print("returning in login validator")
    return render(request, 'index.html')

Body:
Not sure why I am not able to see the logs on the Docker console, but as a workaround stdout.write works.  Removed all the log stuff from the settings.py and added the following to the views.py file.

import sys

sys.stdout.write("Message goes here. \n")

in the docker console I am now able to see the messages.


问:
Generate Executable Jar
I need to generate a jar file in IntelliJ where my test scenarios can be executed. I tried searching in google but all the information I found is deprecated and not working of fitting what I need.
This is my project structure:

And this is my build.gradle file

```<code>plugins {
    id 'java'
    id 'application'
    id "com.github.johnrengelman.shadow" version "7.1.2"
}

mainClassName = 'TestRunner'

version '0.1.0'

repositories {
    mavenCentral()
}

configurations {
    cucumberRuntime {
        extendsFrom testImplementation
    }
}

dependencies {

    // https://mvnrepository.com/artifact/io.cucumber/cucumber-java
    implementation group: 'io.cucumber', name: 'cucumber-java', version: '7.2.3'

    // https://mvnrepository.com/artifact/io.cucumber/cucumber-testng
    implementation group: 'io.cucumber', name: 'cucumber-testng', version: '6.10.2'

}

distZip.shouldRunAfter(build)

jar {
    // Keep jar clean:
    exclude 'META-INF/*.SF', 'META-INF/*.DSA', 'META-INF/*.RSA', 'META-INF/*.MF'

    manifest {
        attributes 'Main-Class': 'TestRunner',
                'Class-Path': configurations.runtimeClasspath.files.collect { it.getName() }.join(' ')
    }
    // How-to add class path:
    //     https://stackoverflow.com/questions/22659463/add-classpath-in-manifest-using-gradle
    //     https://gist.github.com/simon04/6865179
}

def tags = (findProperty('tags') == null) ? 'not @Ignore' : findProperty('tags') + ' and not @Ignore'

task cucumber() {
    dependsOn assemble, testClasses
    doLast {
        javaexec {
            main = "io.cucumber.core.cli.Main"
            classpath = configurations.cucumberRuntime + sourceSets.main.output + sourceSets.test.output
            args = ['--plugin', 'pretty', '--glue', 'stepDefinitions', '--tags', "${tags}", 'src/test/resources/features']
        }
    }
}
</code>```

And this is my TestRunner.java file

```<code>public class TestRunner {
    public static void main(String[] args) throws Throwable {
        io.cucumber.core.cli.Main.main(args);
    }
}
</code>```

I tried with many ways, trying to generate the FatJar but I don't get anything working. Now I'm trying to use it with shadowJar but I don't get it. I don't have very much expertise in this.

By now I can execute by CLI using the command, gradle cucumber -Ptags="@Simple" and I want to get something like this but with the jar file generated.

Can anyone help me with this??
Thanks!

答:
Ok, I finally got the jar with the features and the step definitions within

Only have to add in the build.gradle

```<code>import com.github.jengelman.gradle.plugins.shadow.tasks.ShadowJar
    task testJar(type: ShadowJar) {
        archiveClassifier.set("tests")
        from sourceSets.test.output
        configurations = [project.configurations.runtimeClasspath]
    }
</code>```

I think the only problem is related with the TestRunner Class

I have to be capable to configure in someway the same that is configured in the build.gradle file for the cucumber task, and I really dont know having this jar generated, how to execute the "@Simple" feature

Title: Generate Executable Jar

Body:
I need to generate a jar file in IntelliJ where my test scenarios can be executed. I tried searching in google but all the information I found is deprecated and not working of fitting what I need.
This is my project structure:

And this is my build.gradle file

plugins {
    id 'java'
    id 'application'
    id "com.github.johnrengelman.shadow" version "7.1.2"
}

mainClassName = 'TestRunner'

version '0.1.0'

repositories {
    mavenCentral()
}

configurations {
    cucumberRuntime {
        extendsFrom testImplementation
    }
}

dependencies {

    // https://mvnrepository.com/artifact/io.cucumber/cucumber-java
    implementation group: 'io.cucumber', name: 'cucumber-java', version: '7.2.3'

    // https://mvnrepository.com/artifact/io.cucumber/cucumber-testng
    implementation group: 'io.cucumber', name: 'cucumber-testng', version: '6.10.2'

}

distZip.shouldRunAfter(build)

jar {
    // Keep jar clean:
    exclude 'META-INF/*.SF', 'META-INF/*.DSA', 'META-INF/*.RSA', 'META-INF/*.MF'

    manifest {
        attributes 'Main-Class': 'TestRunner',
                'Class-Path': configurations.runtimeClasspath.files.collect { it.getName() }.join(' ')
    }
    // How-to add class path:
    //     https://stackoverflow.com/questions/22659463/add-classpath-in-manifest-using-gradle
    //     https://gist.github.com/simon04/6865179
}

def tags = (findProperty('tags') == null) ? 'not @Ignore' : findProperty('tags') + ' and not @Ignore'

task cucumber() {
    dependsOn assemble, testClasses
    doLast {
        javaexec {
            main = "io.cucumber.core.cli.Main"
            classpath = configurations.cucumberRuntime + sourceSets.main.output + sourceSets.test.output
            args = ['--plugin', 'pretty', '--glue', 'stepDefinitions', '--tags', "${tags}", 'src/test/resources/features']
        }
    }
}

And this is my TestRunner.java file

public class TestRunner {
    public static void main(String[] args) throws Throwable {
        io.cucumber.core.cli.Main.main(args);
    }
}

I tried with many ways, trying to generate the FatJar but I don't get anything working. Now I'm trying to use it with shadowJar but I don't get it. I don't have very much expertise in this.

By now I can execute by CLI using the command, gradle cucumber -Ptags="@Simple" and I want to get something like this but with the jar file generated.

Can anyone help me with this??
Thanks!

Body:
Ok, I finally got the jar with the features and the step definitions within

Only have to add in the build.gradle

import com.github.jengelman.gradle.plugins.shadow.tasks.ShadowJar
    task testJar(type: ShadowJar) {
        archiveClassifier.set("tests")
        from sourceSets.test.output
        configurations = [project.configurations.runtimeClasspath]
    }

I think the only problem is related with the TestRunner Class

I have to be capable to configure in someway the same that is configured in the build.gradle file for the cucumber task, and I really dont know having this jar generated, how to execute the "@Simple" feature


问:
How to solve Unhandled exception error when importing csv file in MysqlWorkbench?
When I imported an .csv file using import wizard of MySQL Workbench (utf8), the following error popped out.

Unhandled exception: 'ascii' codec can't decode byte 0xc2 in position 444: ordinal not in range(128)

I'm new to SQL so I don't know how to fix this. Please help me.

答: I found out why there is an error. The column Product_name of my raw data contains values with special characters. Simply remove the special characters solves the problem. You can watch how to remove special characters here</p>


问:
Custom Logger Class python: How to make it work across classes?
I've been playing around with a custom logger class, which I created in order to have another "verbosity level" (which is trace) implemented.
I am aware, that it is not recommended according to the documentation of the logger class - however I have code, which has to have it in order to do extensive debugging.
That beeing said, I can call the logger with all methods (LOG.warning, LOG.trace, etc) as expected, but when I try to do the same in another class it does not work as intended. I guess the properties of the logger just get lost for some reason.

Basically what I want to achieve is, that the properties which I set initially (like the log format, log handlers, log level etc) are retained in every class.

I have a logger class, which implements "TRACE":

```<code>from logging import getLoggerClass, addLevelName, setLoggerClass, NOTSET

class AioLogger(getLoggerClass()) :
    TRACE = 1

    def __init__(self, name, level=NOTSET):
        super().__init__(name, level)

    addLevelName(TRACE, "TRACE")

    def trace(self, message, *args, **kwargs):
        if self.isEnabledFor(AioLogger.TRACE):
            self._log(AioLogger.TRACE, message, args, **kwargs)

setLoggerClass(AioLogger)
</code>```

class a:

```<code>import logging
from AioLogger import AioLogger
from b import b

LOG = AioLogger(logging.getLogger('myapp'))
class a:
    def __init__(self):
        LOG.setLevel(AioLogger.TRACE)

        # create a file handler
        file_handler = logging.FileHandler('test.log')
        file_handler.setLevel(logging.DEBUG)
        file_formatter = logging.Formatter('[%(asctime)s] %(filename)-15s: line %(lineno)-5d: %(levelname)-8s: '
                                           '%(funcName)-50s: %(message)s')
        file_handler.setFormatter(file_formatter)
        LOG.addHandler(file_handler)

        # create console handler
        console_handler = logging.StreamHandler()
        console_handler.setLevel(AioLogger.TRACE)
        console_formatter = logging.Formatter('[%(asctime)s] %(filename)-15s: line %(lineno)-5d: %(levelname)-8s: '
                                              '%(funcName)-50s: %(message)s')
        console_handler.setFormatter(console_formatter)
        LOG.addHandler(console_handler)

        LOG.trace('trace')
        LOG.debug('debug')
        LOG.info('info')
        LOG.warning('warning')
        LOG.error('error')
</code>```

class b:

```<code>import logging
from AioLogger import AioLogger

LOG = AioLogger(logging.getLogger('myapp'))
class b:
    def __init__(self):
        LOG.trace('trace')
        LOG.debug('debug')
        LOG.info('info')
        LOG.warning('warning')
        LOG.error('error')
</code>```

Adding following at the end of the file from class a:

```<code>ls = a()
cls2 = b()
</code>```

and running it, it produces following output:

```<code>[2019-05-05 18:03:19,908] a.py           : line 27   : TRACE   : __init__                                          : trace
[2019-05-05 18:03:19,908] a.py           : line 28   : DEBUG   : __init__                                          : debug
[2019-05-05 18:03:19,908] a.py           : line 29   : INFO    : __init__                                          : info
[2019-05-05 18:03:19,908] a.py           : line 30   : WARNING : __init__                                          : warning
[2019-05-05 18:03:19,908] a.py           : line 31   : ERROR   : __init__                                          : error
warning
error
</code>```

For some reason the defined properties for the custom logger class are just vanishing. I guess the error is somewhere in my custom logger class, as getting the "default" logger via logging.getlogger('myapp') just works fine - but it does not provide the needed TRACE loglevel (hence the custom logger class, which BTW I found somewhere on stackoverflow).

答:
The Logger class is not a singleton. In class a, you call LOG = AioLogger(logging.getLogger('myapp')). This returns an instance of AioLogger, not the class. Thus, in the subsequent code you customize that instance, not the class.

If you want AioLogger to have those handlers and formatters, it must be defined within the class, as properties of it. Then, every time you instantiate it, all those properties will be brought along.

Body:
I've been playing around with a custom logger class, which I created in order to have another "verbosity level" (which is trace) implemented.
I am aware, that it is not recommended according to the documentation of the logger class - however I have code, which has to have it in order to do extensive debugging.
That beeing said, I can call the logger with all methods (LOG.warning, LOG.trace, etc) as expected, but when I try to do the same in another class it does not work as intended. I guess the properties of the logger just get lost for some reason.

Basically what I want to achieve is, that the properties which I set initially (like the log format, log handlers, log level etc) are retained in every class.

I have a logger class, which implements "TRACE":

from logging import getLoggerClass, addLevelName, setLoggerClass, NOTSET

class AioLogger(getLoggerClass()) :
    TRACE = 1

    def __init__(self, name, level=NOTSET):
        super().__init__(name, level)

    addLevelName(TRACE, "TRACE")

    def trace(self, message, *args, **kwargs):
        if self.isEnabledFor(AioLogger.TRACE):
            self._log(AioLogger.TRACE, message, args, **kwargs)

setLoggerClass(AioLogger)

class a:

import logging
from AioLogger import AioLogger
from b import b

LOG = AioLogger(logging.getLogger('myapp'))
class a:
    def __init__(self):
        LOG.setLevel(AioLogger.TRACE)

        # create a file handler
        file_handler = logging.FileHandler('test.log')
        file_handler.setLevel(logging.DEBUG)
        file_formatter = logging.Formatter('[%(asctime)s] %(filename)-15s: line %(lineno)-5d: %(levelname)-8s: '
                                           '%(funcName)-50s: %(message)s')
        file_handler.setFormatter(file_formatter)
        LOG.addHandler(file_handler)

        # create console handler
        console_handler = logging.StreamHandler()
        console_handler.setLevel(AioLogger.TRACE)
        console_formatter = logging.Formatter('[%(asctime)s] %(filename)-15s: line %(lineno)-5d: %(levelname)-8s: '
                                              '%(funcName)-50s: %(message)s')
        console_handler.setFormatter(console_formatter)
        LOG.addHandler(console_handler)

        LOG.trace('trace')
        LOG.debug('debug')
        LOG.info('info')
        LOG.warning('warning')
        LOG.error('error')

class b:

import logging
from AioLogger import AioLogger

LOG = AioLogger(logging.getLogger('myapp'))
class b:
    def __init__(self):
        LOG.trace('trace')
        LOG.debug('debug')
        LOG.info('info')
        LOG.warning('warning')
        LOG.error('error')

Adding following at the end of the file from class a:

ls = a()
cls2 = b()

and running it, it produces following output:

[2019-05-05 18:03:19,908] a.py           : line 27   : TRACE   : __init__                                          : trace
[2019-05-05 18:03:19,908] a.py           : line 28   : DEBUG   : __init__                                          : debug
[2019-05-05 18:03:19,908] a.py           : line 29   : INFO    : __init__                                          : info
[2019-05-05 18:03:19,908] a.py           : line 30   : WARNING : __init__                                          : warning
[2019-05-05 18:03:19,908] a.py           : line 31   : ERROR   : __init__                                          : error
warning
error

For some reason the defined properties for the custom logger class are just vanishing. I guess the error is somewhere in my custom logger class, as getting the "default" logger via logging.getlogger('myapp') just works fine - but it does not provide the needed TRACE loglevel (hence the custom logger class, which BTW I found somewhere on stackoverflow).


问:
Pivot an observable collection
I have records like this in observable collection

```
ID Department salary joingdate
1    .NET   5000  04/08/2011
2    .NET   6000  04/07/2011
3    JAVA   7000  04/08/2011
4    JAVA   8000  04/07/2011
5    .NET   9000  04/06/2011
```

now I want new observable collection like

```
Joingdate    .NET(Salary)  JAVA(Salary)
04/08/2011  5000        7000
04/07/2011  6000        8000
04/06/2011  9000        NULL

```

How would I get this type of observable collection?

答:
Some time ago I played around with pivoting and the ExpandoObject. This is certainly not production code.

```<code>public static dynamic pivot(IEnumerable<Employee> rows)
{
    IDictionary<string, Object> expando = new ExpandoObject();
    expando["Joindate"] = rows.First().Joindate;
    foreach (var row in rows)
    {
        expando[row.Department] = row.Salary;
    }
    return (dynamic)expando;
}
</code>```

then in some method somewhere

```<code>var employees = new ObservableCollection<Employee>() {
    new Employee() {ID=1, Department="NET", Salary=5000, Joindate=new DateTime(2011,04,08)},
    new Employee() {ID=2, Department="NET", Salary=6000, Joindate=new DateTime(2011,04,07)},
    new Employee() {ID=3, Department="JAVA", Salary=7000, Joindate=new DateTime(2011,04,08)},
    new Employee() {ID=4, Department="JAVA", Salary=8000, Joindate=new DateTime(2011,04,07)},
    new Employee() {ID=5, Department="NET", Salary=9000, Joindate=new DateTime(2011,04,06)}
};

var distinctDates = employees.Select(j => j.Joindate).Distinct().OrderByDescending(d => d);

var salaryByDepartmentAndJoindate = distinctDates.Select(d => pivot(employees.Where(jd => jd.Joindate == d)));

var result = new ObservableCollection<dynamic>(salaryByDepartmentAndJoindate);
</code>```

Title: Pivot an observable collection

Body:
I have records like this in observable collection

ID Department salary joingdate
1    .NET   5000  04/08/2011
2    .NET   6000  04/07/2011
3    JAVA   7000  04/08/2011
4    JAVA   8000  04/07/2011
5    .NET   9000  04/06/2011

now I want new observable collection like

Joingdate    .NET(Salary)  JAVA(Salary)
04/08/2011  5000        7000
04/07/2011  6000        8000
04/06/2011  9000        NULL

How would I get this type of observable collection?

Body:
Some time ago I played around with pivoting and the ExpandoObject. This is certainly not production code.

public static dynamic pivot(IEnumerable<Employee> rows)
{
    IDictionary<string, Object> expando = new ExpandoObject();
    expando["Joindate"] = rows.First().Joindate;
    foreach (var row in rows)
    {
        expando[row.Department] = row.Salary;
    }
    return (dynamic)expando;
}

then in some method somewhere

var employees = new ObservableCollection<Employee>() {
    new Employee() {ID=1, Department="NET", Salary=5000, Joindate=new DateTime(2011,04,08)},
    new Employee() {ID=2, Department="NET", Salary=6000, Joindate=new DateTime(2011,04,07)},
    new Employee() {ID=3, Department="JAVA", Salary=7000, Joindate=new DateTime(2011,04,08)},
    new Employee() {ID=4, Department="JAVA", Salary=8000, Joindate=new DateTime(2011,04,07)},
    new Employee() {ID=5, Department="NET", Salary=9000, Joindate=new DateTime(2011,04,06)}
};

var distinctDates = employees.Select(j => j.Joindate).Distinct().OrderByDescending(d => d);

var salaryByDepartmentAndJoindate = distinctDates.Select(d => pivot(employees.Where(jd => jd.Joindate == d)));

var result = new ObservableCollection<dynamic>(salaryByDepartmentAndJoindate);


问:
multiple conditional renderings inside a map function
Hi there I'm looking if there's a better way to render my todos

I have this

```<code>         {
            todos.map((todo) => (

                todo.status === 1 && (
                    <p>{todo.title}</p>
                )
            ))
        }
        {
            todos.map((todo) => (
                todo.status === 2 && (
                    <p>{todo.title}</p>
                )
            ))
        }
        {
            todos.map((todo) => (
                todo.status === 3 && (
                    <p>{todo.title}</p>
                )
            ))
        }
</code>```

Is there a way to do this?

Thanks a lot

答:
If you want them to be in order, then sort them before you map them

```<code>todos.sort((a, b) => a.status - b.status).map((todo) => .....)
</code>```

if you do not want to change the order of the original array then copy it

```<code>todos.slice().sort((a, b) => a.status - b.status).map((todo) => .....)
</code>```

Body:
Hi there I'm looking if there's a better way to render my todos

I have this

         {
            todos.map((todo) => (

                todo.status === 1 && (

{todo.title}

                )
            ))
        }
        {
            todos.map((todo) => (
                todo.status === 2 && (

{todo.title}

                )
            ))
        }
        {
            todos.map((todo) => (
                todo.status === 3 && (

{todo.title}

                )
            ))
        }

Is there a way to do this?

Thanks a lot

Body:
If you want them to be in order, then sort them before you map them

todos.sort((a, b) => a.status - b.status).map((todo) => .....)

if you do not want to change the order of the original array then copy it

todos.slice().sort((a, b) => a.status - b.status).map((todo) => .....)


问:
Vue how to search all properties of array
In my vue-app I want to add a search component, so that I can search for different topics.

here is an example of the data:

```<code>persons: [
   {
    name: 'Mr.X',
    gender: 'Male',
    location: {
      address: 'some streetname',
      zipcode: '12345',
      city: 'Berlin',
      lng: 'longitude',
      lat: 'latitude',
    },
    skills: [
     { label: 'foo' },
     { label: 'bar' },
    ],
  },
 ...etc
]
</code>```

Then in my component I use a computed value:

```<code>computed: {
   filteredList() {
     return this.persons.filter((person) => {
       return person.name.toLowerCase().includes(this.search.toLowerCase())
     })
   },
}
</code>```

the HTML is:

```<code><input type="text" v-model="search" />

<div v-for="(person, index) in filteredList" :key="index">
    <p>{{ person.name }}</p>
</div>
</code>```

This of course only searches and returns the name. How can I search on all properties? For example If I search for "Berlin" it should also return the object data.

答:
If the results from your search are dynamically retrieved, I'd recommend adding the filtering capability to the service itself, then pass those filters in the request. This takes the load off of the client and places the responsibility on your database which is much more optimized for such a task.

If it must be entirely client-side, you can generalize the filter you have to perform comparisons on arbitrary properties.

filteredList() {
     const filterObj = {
         'name': 'Mr. X',
         'gender': 'Female'
     };

     return this.persons.filter((person) => {
       // For each of the filters defined in the filter object, determine if
       // the object passes the filter. Only take objects that pass all filters.
       let isMatch = Object.entries(filterObj).map(([key, value]) => {
           if (typeof value === 'string')
               return person[key].toLowerCase().includes(value);
           if (typeof value === 'boolean')
               return person[key] === value;
           // etc.
       }).every(i => i);

       return isMatch;
     })
},
```

Body:
In my vue-app I want to add a search component, so that I can search for different topics.

here is an example of the data:

persons: [
   {
    name: 'Mr.X',
    gender: 'Male',
    location: {
      address: 'some streetname',
      zipcode: '12345',
      city: 'Berlin',
      lng: 'longitude',
      lat: 'latitude',
    },
    skills: [
     { label: 'foo' },
     { label: 'bar' },
    ],
  },
 ...etc
]

Then in my component I use a computed value:

computed: {
   filteredList() {
     return this.persons.filter((person) => {
       return person.name.toLowerCase().includes(this.search.toLowerCase())
     })
   },
}

the HTML is:

<input type="text" v-model="search" />

{{ person.name }}

This of course only searches and returns the name. How can I search on all properties? For example If I search for "Berlin" it should also return the object data.


问:
How to sort the nested object data in react-native
```<code>    {
    "lion":{
    "age_in_years":"10",
    "name":"king",
    "country":"africa"
    },

    "elephant":{
    "age_in_years":"15",
    "name":"hero",
    "country":"usa"
    },

    "racoon":{
    "age_in_years":"5",
    "name":"thanos",
    "country":"syria"
    },
   }
</code>```

This is the data I'm getting through a web socket in react-native. I want to sort it in ascending order based on the "age_in_years". So the oldest animal's data should be shown at top and  the youngest data at the last.

答:
Store the values in array and make a sort function.

```<code>const numbers = [info.lion.age_in_years, info.elephant.age_in_years, info.racoon.age_in_years];

const ascNumbers = numbers.sort((a,b) =>  a-b);
</code>```

If you need descending make it like this:

```<code> const descNumbers = numbers.sort((a,b) =>  b-a);
</code>```

Body:
    {
    "lion":{
    "age_in_years":"10",
    "name":"king",
    "country":"africa"
    },

    "elephant":{
    "age_in_years":"15",
    "name":"hero",
    "country":"usa"
    },

    "racoon":{
    "age_in_years":"5",
    "name":"thanos",
    "country":"syria"
    },
   }

This is the data I'm getting through a web socket in react-native. I want to sort it in ascending order based on the "age_in_years". So the oldest animal's data should be shown at top and  the youngest data at the last.

Body:
Store the values in array and make a sort function.

const numbers = [info.lion.age_in_years, info.elephant.age_in_years, info.racoon.age_in_years];

const ascNumbers = numbers.sort((a,b) =>  a-b);

If you need descending make it like this:

 const descNumbers = numbers.sort((a,b) =>  b-a);


问:
problem about split a string
I wrote a program to read a registry entry from a file.
And the entry looks like this:

```<code>reg='HKEY_LOCAL_MACHINE\SOFTWARE\TT\Tools\SYS\exePath' #it means rootKey=HKEY_LOCAL_MACHINE, subKey='SOFTWARE\TT\Tools\SYS', property=exePath
</code>```

I want to read this entry from the file and break it into rootKey, subKey and property.
Apparently, I can do it this way:

```<code>rootKey = reg.split('\\', 1)[0]
subKey = reg.split('\\', 1)[1].rsplit('\\', 1)[0]  #might be a stupid way
property = reg.rsplit('\\, 1)[1]
</code>```

Maybe the entry is a stupid one, but any better way to break it into parts like above?

答:
How about doing the following?  There's no need to call .split() so many times, anyway...

```<code>s = reg.split('\\')
property = s.pop()
root_key = s.pop(0)
sub_key = '\\'.join(s)
</code>```

Title: problem about split a string

Body:
I wrote a program to read a registry entry from a file.
And the entry looks like this:

reg='HKEY_LOCAL_MACHINE\SOFTWARE\TT\Tools\SYS\exePath' #it means rootKey=HKEY_LOCAL_MACHINE, subKey='SOFTWARE\TT\Tools\SYS', property=exePath

I want to read this entry from the file and break it into rootKey, subKey and property.
Apparently, I can do it this way:

rootKey = reg.split('\\', 1)[0]
subKey = reg.split('\\', 1)[1].rsplit('\\', 1)[0]  #might be a stupid way
property = reg.rsplit('\\, 1)[1]

Maybe the entry is a stupid one, but any better way to break it into parts like above?

Body:
How about doing the following?  There's no need to call .split() so many times, anyway...

s = reg.split('\\')
property = s.pop()
root_key = s.pop(0)
sub_key = '\\'.join(s)