问:
Oracle SQL Lag Function using previous row calculation/condition
I'm trying to calculate using constanta as first value

and then the second row will calculate based on first row calculation result and so on(3rd row using second row result)

the base table look like this, already ordered by date as key

```<code>CREATE TABLE T42
    ("Daytime" timestamp, "A" int, "B" int, "C" int)
;

INSERT ALL
    INTO T42 ("Daytime", "A", "B", "C")
         VALUES ('01-Apr-2020 12:00:00 AM', -7021, 151.6445, -15)
    INTO T42 ("Daytime", "A", "B", "C")
         VALUES ('02-Apr-2020 12:00:00 AM', -7037, 152.3164, -15)
    INTO T42 ("Daytime", "A", "B", "C")
         VALUES ('03-Apr-2020 12:00:00 AM', -7053, 155.0313, -16)
    INTO T42 ("Daytime", "A", "B", "C")
         VALUES ('04-Apr-2020 12:00:00 AM', -7065, 151.9258, -11)
SELECT * FROM dual
;
</code>```

For the first april,the constanta is 7005.98.

the result i need should be like this

```<code>+----------+-------+-----+-----+---------+----------+
| Daytime  |   A   |  B  |  C  |  CALC1  | PREV_SAL |
+----------+-------+-----+-----+---------+----------+
| 4/1/2020 | -7021 | 152 | -15 | 7020.98 |        0 |
| 4/2/2020 | -7037 | 152 | -15 | 7035.98 |  7020.98 |
| 4/3/2020 | -7053 | 155 | -16 | 7051.98 |  7035.98 |
| 4/4/2020 | -7065 | 152 | -11 | 7062.98 |  7051.98 |
+----------+-------+-----+-----+---------+----------+
</code>```

My First try for 1st April is to use this

```<code>SELECT "Daytime",
    A ,
    B ,
    C ,
    CASE
      WHEN "Daytime" = '1-APR-20'
      THEN
        CASE
          WHEN 7005.98 +(C*-1)>7080
          THEN 7080
          ELSE 7005.98 +(C*-1)
        END
       ELSE    null
    END calc1

  FROM T42
</code>```

but then i try using LAG function to get previous result but it error invalid identifier on calc1

```<code>SELECT "Daytime",
    A ,
    B ,
    C ,
    CASE
      WHEN "Daytime" = '1-APR-20'
      THEN
        CASE
          WHEN 7005.98 +(C*-1)>7080
          THEN 7080
          ELSE 7005.98 +(C*-1)
        END
      WHEN "Daytime" > '1-APR-20'
      THEN
        CASE
          WHEN calc1 +(C*-1)>7080
          THEN 7080
          ELSE calc1 +(C*-1)
        END

       ELSE    null
    END calc1

  FROM T42
</code>```

I also try using CTE, it good for 2nd april, but for the rest are  null

```<code>with cte as
(
SELECT "Daytime",
    A ,
    B ,
    C ,
    CASE
      WHEN "Daytime" = '1-APR-20'
      THEN
        CASE
          WHEN 7005.98 +(C*-1)>7080
          THEN 7080
          ELSE 7005.98 +(C*-1)
        END

    END calc1

  FROM T42
  )

  select

  cc."Daytime",
  A,
  B,
  C,
  cc.calc1,
  LAG(cc. calc1, 1, 0) OVER (ORDER BY cc."Daytime") AS prev_sal,
  CASE
    WHEN cc."Daytime" > '1-APR-20'
    THEN
      CASE
        WHEN LAG(cc. calc1, 1, 0) OVER (ORDER BY cc."Daytime")+(cc.C*-1) >7080
        THEN 7080
        ELSE LAG(cc. calc1, 1, 0) OVER (ORDER BY cc."Daytime")+(cc.C*-1)
      END
  END calc2

  from cte cc
</code>```

cte result

```<code>+---------+-------+-----+-----+---------+----------+---------+
| Daytime |   A   |  B  |  C  |  CALC1  | PREV_SAL |  CALC2  |
+---------+-------+-----+-----+---------+----------+---------+
| 00:00.0 | -7021 | 152 | -15 | 7020.98 | 0        | (null)  |
| 00:00.0 | -7037 | 152 | -15 | (null)  | 7020.98  | 7035.98 |
| 00:00.0 | -7053 | 155 | -16 | (null)  | (null)   | (null)  |
| 00:00.0 | -7065 | 152 | -11 | (null)  | (null)   | (null)  |
+---------+-------+-----+-----+---------+----------+---------+
</code>```

is it possible to do this kind of calculation?

here  my fiddle link

答:
You can generate the results you want with a recursive CTE; first generating a list of row numbers according to Daytime to make recursion easier, then computing CALC1 from the previous value and the current C, and PREV_SAL from the previous CALC1:

```<code>WITH CTE AS (
  SELECT T42.*,
         ROW_NUMBER() OVER (ORDER BY Daytime) AS rn
  FROM T42
),
CTE2 (Daytime, A, B, C, CALC1, PREV_SAL, rn) AS (
  SELECT Daytime, A, B, C,
         LEAST(7005.98 - C, 7080.0) AS CALC1,
         0 AS PREV_SAL,
         rn
  FROM CTE
  WHERE rn = 1
  UNION ALL
  SELECT c.Daytime, c.A, c.B, c.C,
         LEAST(c2.CALC1 - c.C, 7080.0),
         c2.CALC1,
         c.rn
  FROM CTE c
  JOIN CTE2 c2 ON c.rn = c2.rn + 1
)
SELECT Daytime, A, B, C, CALC1, PREV_SAL
FROM CTE2
</code>```

Output:

```<code>DAYTIME                 A       B       C       CALC1       PREV_SAL
2020-04-01 00:00:00.0   -7021   152     -15     7020.98     0
2020-04-02 00:00:00.0   -7037   152     -15     7035.98     7020.98
2020-04-03 00:00:00.0   -7053   155     -16     7051.98     7035.98
2020-04-04 00:00:00.0   -7065   152     -11     7062.98     7051.98
</code>```

Demo on SQLFiddle

Body:
I'm trying to calculate using constanta as first value

and then the second row will calculate based on first row calculation result and so on(3rd row using second row result)

the base table look like this, already ordered by date as key

CREATE TABLE T42
    ("Daytime" timestamp, "A" int, "B" int, "C" int)
;

INSERT ALL
    INTO T42 ("Daytime", "A", "B", "C")
         VALUES ('01-Apr-2020 12:00:00 AM', -7021, 151.6445, -15)
    INTO T42 ("Daytime", "A", "B", "C")
         VALUES ('02-Apr-2020 12:00:00 AM', -7037, 152.3164, -15)
    INTO T42 ("Daytime", "A", "B", "C")
         VALUES ('03-Apr-2020 12:00:00 AM', -7053, 155.0313, -16)
    INTO T42 ("Daytime", "A", "B", "C")
         VALUES ('04-Apr-2020 12:00:00 AM', -7065, 151.9258, -11)
SELECT * FROM dual
;

For the first april,the constanta is 7005.98.

the result i need should be like this

+----------+-------+-----+-----+---------+----------+
| Daytime  |   A   |  B  |  C  |  CALC1  | PREV_SAL |
+----------+-------+-----+-----+---------+----------+
| 4/1/2020 | -7021 | 152 | -15 | 7020.98 |        0 |
| 4/2/2020 | -7037 | 152 | -15 | 7035.98 |  7020.98 |
| 4/3/2020 | -7053 | 155 | -16 | 7051.98 |  7035.98 |
| 4/4/2020 | -7065 | 152 | -11 | 7062.98 |  7051.98 |
+----------+-------+-----+-----+---------+----------+

My First try for 1st April is to use this

SELECT "Daytime",
    A ,
    B ,
    C ,
    CASE
      WHEN "Daytime" = '1-APR-20'
      THEN
        CASE
          WHEN 7005.98 +(C*-1)>7080
          THEN 7080
          ELSE 7005.98 +(C*-1)
        END
       ELSE    null
    END calc1

  FROM T42

but then i try using LAG function to get previous result but it error invalid identifier on calc1

SELECT "Daytime",
    A ,
    B ,
    C ,
    CASE
      WHEN "Daytime" = '1-APR-20'
      THEN
        CASE
          WHEN 7005.98 +(C*-1)>7080
          THEN 7080
          ELSE 7005.98 +(C*-1)
        END
      WHEN "Daytime" > '1-APR-20'
      THEN
        CASE
          WHEN calc1 +(C*-1)>7080
          THEN 7080
          ELSE calc1 +(C*-1)
        END

       ELSE    null
    END calc1

  FROM T42

I also try using CTE, it good for 2nd april, but for the rest are  null

with cte as
(
SELECT "Daytime",
    A ,
    B ,
    C ,
    CASE
      WHEN "Daytime" = '1-APR-20'
      THEN
        CASE
          WHEN 7005.98 +(C*-1)>7080
          THEN 7080
          ELSE 7005.98 +(C*-1)
        END

    END calc1

  FROM T42
  )

  select

  cc."Daytime",
  A,
  B,
  C,
  cc.calc1,
  LAG(cc. calc1, 1, 0) OVER (ORDER BY cc."Daytime") AS prev_sal,
  CASE
    WHEN cc."Daytime" > '1-APR-20'
    THEN
      CASE
        WHEN LAG(cc. calc1, 1, 0) OVER (ORDER BY cc."Daytime")+(cc.C*-1) >7080
        THEN 7080
        ELSE LAG(cc. calc1, 1, 0) OVER (ORDER BY cc."Daytime")+(cc.C*-1)
      END
  END calc2

  from cte cc

cte result

+---------+-------+-----+-----+---------+----------+---------+
| Daytime |   A   |  B  |  C  |  CALC1  | PREV_SAL |  CALC2  |
+---------+-------+-----+-----+---------+----------+---------+
| 00:00.0 | -7021 | 152 | -15 | 7020.98 | 0        | (null)  |
| 00:00.0 | -7037 | 152 | -15 | (null)  | 7020.98  | 7035.98 |
| 00:00.0 | -7053 | 155 | -16 | (null)  | (null)   | (null)  |
| 00:00.0 | -7065 | 152 | -11 | (null)  | (null)   | (null)  |
+---------+-------+-----+-----+---------+----------+---------+

is it possible to do this kind of calculation?

here  my fiddle link

Body:
You can generate the results you want with a recursive CTE; first generating a list of row numbers according to Daytime to make recursion easier, then computing CALC1 from the previous value and the current C, and PREV_SAL from the previous CALC1:

WITH CTE AS (
  SELECT T42.*,
         ROW_NUMBER() OVER (ORDER BY Daytime) AS rn
  FROM T42
),
CTE2 (Daytime, A, B, C, CALC1, PREV_SAL, rn) AS (
  SELECT Daytime, A, B, C,
         LEAST(7005.98 - C, 7080.0) AS CALC1,
         0 AS PREV_SAL,
         rn
  FROM CTE
  WHERE rn = 1
  UNION ALL
  SELECT c.Daytime, c.A, c.B, c.C,
         LEAST(c2.CALC1 - c.C, 7080.0),
         c2.CALC1,
         c.rn
  FROM CTE c
  JOIN CTE2 c2 ON c.rn = c2.rn + 1
)
SELECT Daytime, A, B, C, CALC1, PREV_SAL
FROM CTE2

Output:

DAYTIME                 A       B       C       CALC1       PREV_SAL
2020-04-01 00:00:00.0   -7021   152     -15     7020.98     0
2020-04-02 00:00:00.0   -7037   152     -15     7035.98     7020.98
2020-04-03 00:00:00.0   -7053   155     -16     7051.98     7035.98
2020-04-04 00:00:00.0   -7065   152     -11     7062.98     7051.98

Demo on SQLFiddle


来源: stackexchange

问:
Get date and hour in datetime format in ASP.NET Core view
I write a simple project in ASP.NET Core. I want a user to only pick Date and Hour without minutes part in datetime in view. I tried, but minute part is always shown and pickable! Any solution to not show minute part or disable it is acceptable.

This is what I wrote in the view model:

```<code>[DisplayFormat(ApplyFormatInEditMode = true,ConvertEmptyStringToNull =false,
 DataFormatString = "{0:yyyy-MM-dd HH}")]
public DateTime StartDate { get; set; }
</code>```

View is a get:

```<code><input type="datetime-local" asp-for="StartDate" name="StartDate" id="StartDate" data-date-format="{0:yyyy-MM-dd HH}" asp-format="{0:yyyy-MM-dd HH}" class="form-control" />
</code>```

答:
Any solution to not show minute part or disable it is acceptable.

If you are using browser default datepicker widget as the screenshot you shared, which seems not enable us to customize and disable minute picker part within that default datepicker widget.

If possible, you can try to use some jQuery datepicker widget to achieving the requirement, like below.

```<code><div class="input-append date form_datetime">
    <input type="text" asp-for="StartDate" id="StartDate" class="form-control" readonly />
    <span class="add-on"><i class="icon-th"></i></span>
</div>
</code>```

Required references and js code

```<code><link rel="stylesheet" href="https://www.malot.fr/bootstrap-datetimepicker/bootstrap-datetimepicker/css/bootstrap-datetimepicker.css" />
<script src="https://www.malot.fr/bootstrap-datetimepicker/bootstrap-datetimepicker/js/bootstrap-datetimepicker.min.js"></script>
<script>
    $(function () {
        $(".form_datetime").datetimepicker({
        format: "yyyy-MM-dd HH:00",
        minView:1,
        autoclose:true
        });
    })
</script>
</code>```

Test Result

ContentLicense: CC BY-SA 4.0

Body:
I write a simple project in ASP.NET Core. I want a user to only pick Date and Hour without minutes part in datetime in view. I tried, but minute part is always shown and pickable! Any solution to not show minute part or disable it is acceptable.

This is what I wrote in the view model:

[DisplayFormat(ApplyFormatInEditMode = true,ConvertEmptyStringToNull =false,
 DataFormatString = "{0:yyyy-MM-dd HH}")]
public DateTime StartDate { get; set; }

View is a get:

<input type="datetime-local" asp-for="StartDate" name="StartDate" id="StartDate" data-date-format="{0:yyyy-MM-dd HH}" asp-format="{0:yyyy-MM-dd HH}" class="form-control" />

Body:
Any solution to not show minute part or disable it is acceptable.

If you are using browser default datepicker widget as the screenshot you shared, which seems not enable us to customize and disable minute picker part within that default datepicker widget.

If possible, you can try to use some jQuery datepicker widget to achieving the requirement, like below.

<div class="input-append date form_datetime">
    <input type="text" asp-for="StartDate" id="StartDate" class="form-control" readonly />
    <span class="add-on"><i class="icon-th"></i></span>
</div>

Required references and js code

<link rel="stylesheet" href="https://www.malot.fr/bootstrap-datetimepicker/bootstrap-datetimepicker/css/bootstrap-datetimepicker.css" />
<script src="https://www.malot.fr/bootstrap-datetimepicker/bootstrap-datetimepicker/js/bootstrap-datetimepicker.min.js"></script>
<script>
    $(function () {
        $(".form_datetime").datetimepicker({
        format: "yyyy-MM-dd HH:00",
        minView:1,
        autoclose:true
        });
    })
</script>

Test Result


问:
What is exactly the process of transaction manager in JTA
After reading a lot of blogs about JTA, there is still some points confuse me.

For example I found in JTA Example

The blog provide a picture to explain relationship between components of a distributed-transaction

This picture seems to imply Java Application can directly access to Resource Manager which in this case is JDBC Driver.

But in my opinion, the Java Application can only access to Transaction Manager and all the accesses for DataSource is controlled by Transaction Manager.

Is it something wrong with my understanding?

For another confusion.

Since we can control transaction like this:

XADataSource xaDS;
XAConnection xaCon;
XAResource xaRes;
Xid xid;
Connection con;
Statement stmt;
int ret;

xaDS = getDataSource();
xaCon = xaDS.getXAConnection("jdbc_user", "jdbc_password");
xaRes = xaCon.getXAResource();
con = xaCon.getConnection();
stmt = con.createStatement();
xid = new MyXid(100, new byte[]{0x01}, new byte[]{0x02});
try {
    xaRes.start(xid, XAResource.TMNOFLAGS);
    stmt.executeUpdate("insert into test_table values (100)");
    xaRes.end(xid, XAResource.TMSUCCESS);

    ret = xaRes.prepare(xid);
    if (ret == XAResource.XA_OK) {
        xaRes.commit(xid, false);
    }
} catch (XAException e) {
    e.printStackTrace();
} finally {
    stmt.close();
    con.close();
    xaCon.close();
}
```

Is Transaction Manager just a convenient way to do things that we can manually did above?

答:
Your example has only one resource and could be executed only with JDBC without JTA.

JTA is about distributed transactions

that is, transactions that
  access and update data on two or more networked computer resources.

A good example should involve at least two resources:

2 different databases

or

1 database and 1 file system.

Body:
After reading a lot of blogs about JTA, there is still some points confuse me.

For example I found in JTA Example

The blog provide a picture to explain relationship between components of a distributed-transaction

This picture seems to imply Java Application can directly access to Resource Manager which in this case is JDBC Driver.

But in my opinion, the Java Application can only access to Transaction Manager and all the accesses for DataSource is controlled by Transaction Manager.

Is it something wrong with my understanding?

For another confusion.

Since we can control transaction like this:

XADataSource xaDS;
XAConnection xaCon;
XAResource xaRes;
Xid xid;
Connection con;
Statement stmt;
int ret;

xaDS = getDataSource();
xaCon = xaDS.getXAConnection("jdbc_user", "jdbc_password");
xaRes = xaCon.getXAResource();
con = xaCon.getConnection();
stmt = con.createStatement();
xid = new MyXid(100, new byte[]{0x01}, new byte[]{0x02});
try {
    xaRes.start(xid, XAResource.TMNOFLAGS);
    stmt.executeUpdate("insert into test_table values (100)");
    xaRes.end(xid, XAResource.TMSUCCESS);

    ret = xaRes.prepare(xid);
    if (ret == XAResource.XA_OK) {
        xaRes.commit(xid, false);
    }
} catch (XAException e) {
    e.printStackTrace();
} finally {
    stmt.close();
    con.close();
    xaCon.close();
}

Is Transaction Manager just a convenient way to do things that we can manually did above?


问:
How to optimize layout performance for events within the child component?
I have a component with such design. this is not code, just a high-level representation of the component structure.

```<code>Container {
   child1 : {

   },
   child2 : {

   },
   child3 : {

   },
   ...
}

Child component : {
   event that will cause layout update
}
</code>```

Now the page become very slow whenever the event triggered in the child components. Since the event code is written within component, I'm not sure how can I make use of suspendLayout().

Any idea?

答:
You could use batchLayout. This will suspend all layouts until your function is done.</p>

```<code>Container {
   child1 : {

   },
   child2 : {

   },
   child3 : {

   },
   ...
}

    Child component : {
        // event that will cause layout update
        event: function() {
            const me = this;

            Ext.batchLayouts(function() {
                // Your code
            }, me);
        }
    }
</code>```

Body:
I have a component with such design. this is not code, just a high-level representation of the component structure.

Container {
   child1 : {

   },
   child2 : {

   },
   child3 : {

   },
   ...
}

Child component : {
   event that will cause layout update
}

Now the page become very slow whenever the event triggered in the child components. Since the event code is written within component, I'm not sure how can I make use of suspendLayout().

Any idea?

Body:
You could use batchLayout. This will suspend all layouts until your function is done.

Container {
   child1 : {

   },
   child2 : {

   },
   child3 : {

   },
   ...
}

    Child component : {
        // event that will cause layout update
        event: function() {
            const me = this;

            Ext.batchLayouts(function() {
                // Your code
            }, me);
        }
    }


问:
Are methods that modify reference type parameters bad?
I've seen methods like this:

```<code>public void Foo(List<string> list)
{
    list.Add("Bar");
}
</code>```

Is this good practice to modify parameters in a method?

Wouldn't this be better?

```<code>public List<string> Foo(List<string> list)
{
    // Edit
    List<string> newlist = new List<string>(list);
    newlist.Add("Bar");
    return newlist;
}
</code>```

It just feels like the first example has unexpected side effects.

答:
The advent of extension methods has made it a bit easier to deal with methods that introduce side effects.  For example, in your example it becomes much more intuitive to say

```<code>public static class Extensions
{
  public static void AddBar(this List<string> list)
  {
     list.Add("Bar");
  }
}
</code>```

and call it with

```<code>mylist.AddBar();
</code>```

which makes it clearer that something is happening to the list.

As mentioned in the comments, this is most useful on lists since modifications to a list can tend to be more confusing. On a simple object, I would tend to just to modify the object in place.

OwnerDisplayName: Jonathan Parker

ContentLicense: CC BY-SA 2.5

Body:
I've seen methods like this:

public void Foo(List<string> list)
{
    list.Add("Bar");
}

Is this good practice to modify parameters in a method?

Wouldn't this be better?

public List<string> Foo(List<string> list)
{
    // Edit
    List<string> newlist = new List<string>(list);
    newlist.Add("Bar");
    return newlist;
}

It just feels like the first example has unexpected side effects.

LastEditorDisplayName: Jonathan Parker

Body:
The advent of extension methods has made it a bit easier to deal with methods that introduce side effects.  For example, in your example it becomes much more intuitive to say

public static class Extensions
{
  public static void AddBar(this List<string> list)
  {
     list.Add("Bar");
  }
}

and call it with

mylist.AddBar();

which makes it clearer that something is happening to the list.

As mentioned in the comments, this is most useful on lists since modifications to a list can tend to be more confusing. On a simple object, I would tend to just to modify the object in place.

OwnerDisplayName: Steve Mitcham

LastEditorDisplayName: Steve Mitcham


问:
How to let Flash app communicate with server?
What's an easy and secure way to let my Flash app communicate with my back-end server?

The Flash app, which is a video player, should retrieve the person's username and send back an ID. How would I do this?

Note: Back-end is written in Javascript.

答: If you want to connect flash with JS to actionscript use ExternalInterface. If you want to connect to e.g. PHP use NetConnection or UrlLoader</p>

ContentLicense: CC BY-SA 3.0


问:
Is it possible to change Firebase domain to custom domain without Firebase Hosting?
I have a fully-built web app that uses Firebase auth and database. It's hosted on Netlify.

I want my users to see my custom domain when authenticating with Google, here:

Is it possible to do this without hosting my app files on Firebase Hosting?

Thank you.

答: If you are asking about customized email handlers (verification email, password reset emails etc) then yes, you can generate links pointing to any site, put there your custom handlers and from their implementation call appropriate firebase API to complete the process. </p>


问:
Apache Beam write to BigQuery table and schema as params
I'm using Python SDK for Apache Beam. The values of the datatable and the schema are in the PCollection. This is the message I read from the PubSub:

```<code>{"DEVICE":"rms005_m1","DATESTAMP":"2020-05-29 20:54:26.733 UTC","SINUMERIK__x_position":69.54199981689453,"SINUMERIK__y_position":104.31400299072266,"SINUMERIK__z_position":139.0850067138672}
</code>```

Then I want to write it to BigQuery using the values in the json message with the lambda function for the datatable and this function for the schema:

```<code>def set_schema(data):
    list = []
    for name in data:
        if name == 'STATUS' or name == 'DEVICE':
            type = 'STRING'
        elif name == 'DATESTAMP':
            type = 'TIMESTAMP'
        else:
            type = 'FLOAT'
        list.append(name + ':' + type)
    schema = ",".join(list)
    return schema

data = (p
        | "Read from PubSub" >> beam.io.ReadFromPubSub(topic=topic)
        | "Parse json" >> beam.Map(json_parse)
        | "Write to BQ" >> beam.io.WriteToBigQuery(
            table='project:dataset{datatable}__opdata'.format(datatable = lambda element: element["DEVICE"]),
            schema=set_schema,
            write_disposition=beam.io.BigQueryDisposition.WRITE_APPEND
        )
       )
</code>```

When I execute it I get this error:

```<code>ValueError: Expected a table reference (PROJECT:DATASET.TABLE or DATASET.TABLE) instead of project:dataset.<function <lambda> at 0x7fa0dc378710>__opdata
</code>```

How can I use the values of the PCollection as variables in the PTransform?

答:
You have to pass a function into table. Try this, instead:</p>

```<code>| "Write to BQ" >> beam.io.WriteToBigQuery(
            table=lambda element: 'project:dataset{datatable}__opdata'.format(datatable = element["DEVICE"]),
            schema=set_schema,
            write_disposition=beam.io.BigQueryDisposition.WRITE_APPEND
        )
</code>```

Body:
I'm using Python SDK for Apache Beam. The values of the datatable and the schema are in the PCollection. This is the message I read from the PubSub:

{"DEVICE":"rms005_m1","DATESTAMP":"2020-05-29 20:54:26.733 UTC","SINUMERIK__x_position":69.54199981689453,"SINUMERIK__y_position":104.31400299072266,"SINUMERIK__z_position":139.0850067138672}

Then I want to write it to BigQuery using the values in the json message with the lambda function for the datatable and this function for the schema:

def set_schema(data):
    list = []
    for name in data:
        if name == 'STATUS' or name == 'DEVICE':
            type = 'STRING'
        elif name == 'DATESTAMP':
            type = 'TIMESTAMP'
        else:
            type = 'FLOAT'
        list.append(name + ':' + type)
    schema = ",".join(list)
    return schema

data = (p
        | "Read from PubSub" >> beam.io.ReadFromPubSub(topic=topic)
        | "Parse json" >> beam.Map(json_parse)
        | "Write to BQ" >> beam.io.WriteToBigQuery(
            table='project:dataset{datatable}__opdata'.format(datatable = lambda element: element["DEVICE"]),
            schema=set_schema,
            write_disposition=beam.io.BigQueryDisposition.WRITE_APPEND
        )
       )

When I execute it I get this error:

ValueError: Expected a table reference (PROJECT:DATASET.TABLE or DATASET.TABLE) instead of project:dataset.<function <lambda> at 0x7fa0dc378710>__opdata

How can I use the values of the PCollection as variables in the PTransform?

Body:
You have to pass a function into table. Try this, instead:

| "Write to BQ" >> beam.io.WriteToBigQuery(
            table=lambda element: 'project:dataset{datatable}__opdata'.format(datatable = element["DEVICE"]),
            schema=set_schema,
            write_disposition=beam.io.BigQueryDisposition.WRITE_APPEND
        )


问:
How can I keep number and increment in child component with Vue JS?
Practicing to make a todo application with Vue JS

Input items save in the localStrage.

UPDATED

When you have some added list and reload a page, ID number start from 1(defalut).

Ideal behaviour:

when reload a page, ID number continues number increment.

if some items removed, then, add new item, ID number should be the biggest ID number in array(if 8) +1 (should be 9).

My code: Link

Problem is around here.

Child2.vue

```<code>  created() {
    let keyObject = JSON.parse(localStorage.getItem(this.keyName));

    if (keyObject) {
      this.$emit("update:todos", keyObject);
    } else {
      return;
    }

    if (this.todos.length > 0) {
      console.log(this.todos.id);
      const setId = this.todos.reduce(function(a,b){ return a > b.id ? a : b.id} ,0)
      this.todos.id = setId + 1
      console.log(this.todos.id);

      this.$emit('update:todos', keyObject)
      // this.$emit('update:todos', this.todos.id)
    }
  },
</code>```

Do you know how?

答:
There is inconsistent formatting in keyObject and this.todos( this.todos is actually nested), and you are not suppose to mutate props.

ALSO NOTICE THE ID INCREMENTATION TO AVOID DUPLICATE ERROR IN LOOPS

My suggestion App.vue:

```<code>methods: {
    addBtn() {

      const todo = { id: this.target.id, name: this.target.name, done: false };
      this.todos.push(todo);
      localStorage.setItem(this.keyName, JSON.stringify(this.todos));
      this.target.name = "";
      //it is important to increment the id based on current length
      this.target.id = this.todos.length + 1;
    },
    onInputChange(val) {
      this.target.name = val;
    }
  },
  created() {
     let todosObject  = JSON.parse(localStorage.getItem(this.keyName));
     if(todosObject){
       this.todos = todosObject
       //again base the id on the current length, to avoid duplicate error in loops later
       this.target.id = this.todos.length+1
     }

  }
</code>```

Child2:

```<code><template>
  <div>
    <ul>
      <li v-for="todo in todos" :key="todo.id">
        ID: {{ todo.id }} / Name: {{ todo.name }}
        <input
          type="checkbox"
          v-model="todo.done"
          @click="status(todo)"
        >
        <button @click="removeBtn(todo)">Remove item</button>
      </li>
    </ul>
  </div>
</template>

<script>
export default {
  props: {
    todos: {
      type: Array,
      required: true
    },
    keyName: {
      type: String,
      required: true
    }
  },

  methods: {
    removeBtn(item) {
      const index = this.todos.indexOf(item);
      this.todos.splice(index, 1);
      localStorage.setItem(this.keyName, JSON.stringify(this.todos));
      if (this.todos.length === 0) {
        console.log("no item");
      }
    },
    status(todo) {
      todo.done = !todo.done;
      localStorage.setItem(this.keyName, JSON.stringify(this.todos));
    }
  }
};
</script>
</code>```

Body:
Practicing to make a todo application with Vue JS

Input items save in the localStrage.

UPDATED

When you have some added list and reload a page, ID number start from 1(defalut).

Ideal behaviour:

when reload a page, ID number continues number increment.

if some items removed, then, add new item, ID number should be the biggest ID number in array(if 8) +1 (should be 9).

My code: Link

Problem is around here.

Child2.vue

  created() {
    let keyObject = JSON.parse(localStorage.getItem(this.keyName));

    if (keyObject) {
      this.$emit("update:todos", keyObject);
    } else {
      return;
    }

    if (this.todos.length > 0) {
      console.log(this.todos.id);
      const setId = this.todos.reduce(function(a,b){ return a > b.id ? a : b.id} ,0)
      this.todos.id = setId + 1
      console.log(this.todos.id);

      this.$emit('update:todos', keyObject)
      // this.$emit('update:todos', this.todos.id)
    }
  },

Do you know how?

Body:
There is inconsistent formatting in keyObject and this.todos( this.todos is actually nested), and you are not suppose to mutate props.

ALSO NOTICE THE ID INCREMENTATION TO AVOID DUPLICATE ERROR IN LOOPS

My suggestion App.vue:

methods: {
    addBtn() {

      const todo = { id: this.target.id, name: this.target.name, done: false };
      this.todos.push(todo);
      localStorage.setItem(this.keyName, JSON.stringify(this.todos));
      this.target.name = "";
      //it is important to increment the id based on current length
      this.target.id = this.todos.length + 1;
    },
    onInputChange(val) {
      this.target.name = val;
    }
  },
  created() {
     let todosObject  = JSON.parse(localStorage.getItem(this.keyName));
     if(todosObject){
       this.todos = todosObject
       //again base the id on the current length, to avoid duplicate error in loops later
       this.target.id = this.todos.length+1
     }

  }

Child2:

<template>
  <div>
    <ul>
      <li v-for="todo in todos" :key="todo.id">
        ID: {{ todo.id }} / Name: {{ todo.name }}
        <input
          type="checkbox"
          v-model="todo.done"
          @click="status(todo)"
        >
        <button @click="removeBtn(todo)">Remove item</button>
      </li>
    </ul>
  </div>
</template>

<script>
export default {
  props: {
    todos: {
      type: Array,
      required: true
    },
    keyName: {
      type: String,
      required: true
    }
  },

  methods: {
    removeBtn(item) {
      const index = this.todos.indexOf(item);
      this.todos.splice(index, 1);
      localStorage.setItem(this.keyName, JSON.stringify(this.todos));
      if (this.todos.length === 0) {
        console.log("no item");
      }
    },
    status(todo) {
      todo.done = !todo.done;
      localStorage.setItem(this.keyName, JSON.stringify(this.todos));
    }
  }
};
</script>


问:
Call a Postgresql function passing an array of integer using mybatis
It might be a direct question but I'm trying many options which is not working.
I've given the below details for your reference.
Mybatis xml configuration:-

```<code><select id="updateComps" statementType="CALLABLE" parameterType="java.util.List">
  <![CDATA[ {call vivo.select_workout (#{list, mode=IN, jdbcType=ARRAY})}]]>
</select>
</code>```

Postgres Function:-

```<code>CREATE OR REPLACE FUNCTION vivo.delete_completed_activity_logged_workout(INT[])
    RETURNS integer
 LANGUAGE plpgsql
AS $function$
declare
ids ALIAS FOR $1;
dist BIGINT[];
</code>```

Mapper config:-

```<code>void deleteCompletedActivityRecords(List<Integer> users);
</code>```

Error facing:-

aused by: org.apache.ibatis.type.TypeException: Error setting non null
  for parameter #1 with JdbcType ARRAY . Try setting a different
  JdbcType for this parameter or a different configuration property.
  Cause: java.lang.ClassCastException: java.util.Arrays$ArrayList cannot
  be cast to java.sql.Array     at
  org.apache.ibatis.type.BaseTypeHandler.setParameter(BaseTypeHandler.java:55)
    at
  org.apache.ibatis.scripting.defaults.DefaultParameterHandler.setParameters(DefaultParameterHandler.java:87)
    ... 68 more Caused by: java.lang.ClassCastException:
  java.util.Arrays$ArrayList cannot be cast to java.sql.Array   at
  org.apache.ibatis.type.ArrayTypeHandler.setNonNullParameter(ArrayTypeHandler.java:35)
    at
  org.apache.ibatis.type.BaseTypeHandler.setParameter(BaseTypeHandler.java:53)
    ... 69 more [WARNING] Could not send response error 500:
  javax.servlet.ServletException: javax.servlet.ServletException:
  org.mybatis.spring.MyBatisSystemException: nested exception is
  org.apache.ibatis.type.TypeException: Could not set parameters for
  mapping: ParameterMapping{property='list', mode=IN, javaType=class
  java.lang.Object, jdbcType=ARRAY, numericScale=null,
  resultMapId='null', jdbcTypeName='null', expression='null'}. Cause:
  org.apache.ibatis.type.TypeException: Error setting non null for
  parameter #1 with JdbcType ARRAY . Try setting a different JdbcType
  for this parameter or a different configuration property. Cause:
  java.lang.ClassCastException: java.util.Arrays$ArrayList cannot be
  cast to java.sql.Array

答:
I created the below custom ArrayTypeHandler.

```<code>package com.lf.util;

import com.google.common.collect.Lists;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.MappedJdbcTypes;
import org.apache.ibatis.type.JdbcType;

import java.sql.*;
import java.util.List;

@MappedJdbcTypes(JdbcType.ARRAY)
public class CustomArrayTypeHandler extends BaseTypeHandler<List<Long>> {
    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, List<Long> parameter, JdbcType jdbcType) throws SQLException {
        Array array = ps.getConnection().createArrayOf("integer", parameter.toArray());
        ps.setArray(i, array);
    }

    @Override
    public List<Long> getNullableResult(ResultSet rs, String columnName) throws SQLException {
        return toList(rs.getArray(columnName));
    }

    @Override
    public List<Long> getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        return toList(rs.getArray(columnIndex));
    }

    @Override
    public List<Long> getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        return toList(cs.getArray(columnIndex));
    }

    private List<Long> toList(Array pgArray) throws SQLException {
        if (pgArray == null) return Lists.newArrayList();

        Long[] strings = (Long[]) pgArray.getArray();
        return containsOnlyNulls(strings) ? Lists.<Long>newArrayList() : Lists.newArrayList(strings);
    }

    private boolean containsOnlyNulls(Long[] strings) {
        for (Long s : strings) {
            if (s != null) {
                return false;
            }
        }
        return true;
    }
}
</code>```

And in the xml file:

```<code><select id="deleteRecords" statementType="CALLABLE" resultType="java.lang.Integer" parameterType="java.util.List">
        <![CDATA[ {call vivo.delete_records (#{list, mode=IN, typeHandler=com.lf.util.CustomArrayTypeHandler})}]]>
    </select>
</code>```

Body:
It might be a direct question but I'm trying many options which is not working.
I've given the below details for your reference.
Mybatis xml configuration:-

<select id="updateComps" statementType="CALLABLE" parameterType="java.util.List">
  <![CDATA[ {call vivo.select_workout (#{list, mode=IN, jdbcType=ARRAY})}]]>
</select>

Postgres Function:-

CREATE OR REPLACE FUNCTION vivo.delete_completed_activity_logged_workout(INT[])
    RETURNS integer
 LANGUAGE plpgsql
AS $function$
declare
ids ALIAS FOR $1;
dist BIGINT[];

Mapper config:-

void deleteCompletedActivityRecords(List<Integer> users);

Error facing:-

aused by: org.apache.ibatis.type.TypeException: Error setting non null
  for parameter #1 with JdbcType ARRAY . Try setting a different
  JdbcType for this parameter or a different configuration property.
  Cause: java.lang.ClassCastException: java.util.Arrays$ArrayList cannot
  be cast to java.sql.Array     at
  org.apache.ibatis.type.BaseTypeHandler.setParameter(BaseTypeHandler.java:55)
    at
  org.apache.ibatis.scripting.defaults.DefaultParameterHandler.setParameters(DefaultParameterHandler.java:87)
    ... 68 more Caused by: java.lang.ClassCastException:
  java.util.Arrays$ArrayList cannot be cast to java.sql.Array   at
  org.apache.ibatis.type.ArrayTypeHandler.setNonNullParameter(ArrayTypeHandler.java:35)
    at
  org.apache.ibatis.type.BaseTypeHandler.setParameter(BaseTypeHandler.java:53)
    ... 69 more [WARNING] Could not send response error 500:
  javax.servlet.ServletException: javax.servlet.ServletException:
  org.mybatis.spring.MyBatisSystemException: nested exception is
  org.apache.ibatis.type.TypeException: Could not set parameters for
  mapping: ParameterMapping{property='list', mode=IN, javaType=class
  java.lang.Object, jdbcType=ARRAY, numericScale=null,
  resultMapId='null', jdbcTypeName='null', expression='null'}. Cause:
  org.apache.ibatis.type.TypeException: Error setting non null for
  parameter #1 with JdbcType ARRAY . Try setting a different JdbcType
  for this parameter or a different configuration property. Cause:
  java.lang.ClassCastException: java.util.Arrays$ArrayList cannot be
  cast to java.sql.Array

Body:
I created the below custom ArrayTypeHandler.

package com.lf.util;

import com.google.common.collect.Lists;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.MappedJdbcTypes;
import org.apache.ibatis.type.JdbcType;

import java.sql.*;
import java.util.List;

@MappedJdbcTypes(JdbcType.ARRAY)
public class CustomArrayTypeHandler extends BaseTypeHandler<List<Long>> {
    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, List<Long> parameter, JdbcType jdbcType) throws SQLException {
        Array array = ps.getConnection().createArrayOf("integer", parameter.toArray());
        ps.setArray(i, array);
    }

    @Override
    public List<Long> getNullableResult(ResultSet rs, String columnName) throws SQLException {
        return toList(rs.getArray(columnName));
    }

    @Override
    public List<Long> getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        return toList(rs.getArray(columnIndex));
    }

    @Override
    public List<Long> getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        return toList(cs.getArray(columnIndex));
    }

    private List<Long> toList(Array pgArray) throws SQLException {
        if (pgArray == null) return Lists.newArrayList();

        Long[] strings = (Long[]) pgArray.getArray();
        return containsOnlyNulls(strings) ? Lists.<Long>newArrayList() : Lists.newArrayList(strings);
    }

    private boolean containsOnlyNulls(Long[] strings) {
        for (Long s : strings) {
            if (s != null) {
                return false;
            }
        }
        return true;
    }
}

And in the xml file:

<select id="deleteRecords" statementType="CALLABLE" resultType="java.lang.Integer" parameterType="java.util.List">
        <![CDATA[ {call vivo.delete_records (#{list, mode=IN, typeHandler=com.lf.util.CustomArrayTypeHandler})}]]>
    </select>


问:
Chronic for Javascript?
I'm looking for something like the Ruby Chronic library, but for Javascript. The main things I need to be able to do is parse natural time entry, not dates. For example:

```<code>Typing   Would Give
------   ----------
8a       08:00
8:30p    20:30
8:01 AM  08:01
21:22    21:22
noon     12:00
midnight 00:00
</code>```

I could write it myself, but before I go off and tackle it, I wanted to know if there was something already available.

I'm using jQuery already, so if there's a plugin, that would be hoopy too.

Thanks!

答:
Comparison support for Ruby Chronic.com date and time input formats.

Check this out
http://www.datejs.com/test/ruby_chronic/index.html

Title: Chronic for Javascript?

Body:
I'm looking for something like the Ruby Chronic library, but for Javascript. The main things I need to be able to do is parse natural time entry, not dates. For example:

Typing   Would Give
------   ----------
8a       08:00
8:30p    20:30
8:01 AM  08:01
21:22    21:22
noon     12:00
midnight 00:00

I could write it myself, but before I go off and tackle it, I wanted to know if there was something already available.

I'm using jQuery already, so if there's a plugin, that would be hoopy too.

Thanks!


问:
Playing in-built webcam feed in a UWP app stopped working after?
I'm trying to play the built-in webcam feed in a MediaElement within a UWP app. It works fine for a few users but there is no feed played for most and I'm lost on what could be the issue.

Some observations when the webcam feed doesn't play:

The code executes without any exceptions

The dialog that requests user permission to access the camera is shown

The LED indicating the webcam is in use turns on soon as it is executed, but there is no feed.

Skype and Camera apps work fine.

The app was working as expected until a week back. A few things that changed in the mean time that could have had an impact are

Installed Kaspersky

A bunch of windows updates

Uninstalled VS2017 professional edition & VS2019 Community edition and installed VS2019 Professional Edition

Some additional information that might be needed to narrow down the reason.

Webcam is enabled in the Package manifest of the app

App Target version: 18362

App Min version: 18362

Windows OS Version : 18362

Any help on this would be highly appreciated. Thanks much in advance!

Here is the piece of code used to play the webcam feed where VideoStreamer is a MediaElement.

```<code>private async Task PlayLiveVideo()
    {
        var allGroups = await MediaFrameSourceGroup.FindAllAsync();
        var eligibleGroups = allGroups.Select(g => new
        {
            Group = g,

            // For each source kind, find the source which offers that kind of media frame,
            // or null if there is no such source.
            SourceInfos = new MediaFrameSourceInfo[]
            {
    g.SourceInfos.FirstOrDefault(info => info.DeviceInformation?.EnclosureLocation.Panel == Windows.Devices.Enumeration.Panel.Front
        && info.SourceKind == MediaFrameSourceKind.Color),
    g.SourceInfos.FirstOrDefault(info => info.DeviceInformation?.EnclosureLocation.Panel == Windows.Devices.Enumeration.Panel.Back
        && info.SourceKind == MediaFrameSourceKind.Color)
            }
        }).Where(g => g.SourceInfos.Any(info => info != null)).ToList();

        if (eligibleGroups.Count == 0)
        {
            System.Diagnostics.Debug.WriteLine("No source group with front and back-facing camera found.");
            return;
        }

        var selectedGroupIndex = 0; // Select the first eligible group
        MediaFrameSourceGroup selectedGroup = eligibleGroups[selectedGroupIndex].Group;
        MediaFrameSourceInfo frontSourceInfo = selectedGroup.SourceInfos[0];

        MediaCapture mediaCapture = new MediaCapture();
        MediaCaptureInitializationSettings settings = new MediaCaptureInitializationSettings()
        {
            SourceGroup = selectedGroup,
            SharingMode = MediaCaptureSharingMode.ExclusiveControl,
            MemoryPreference = MediaCaptureMemoryPreference.Cpu,
            StreamingCaptureMode = StreamingCaptureMode.Video,
        };
        try
        {
            await mediaCapture.InitializeAsync(settings);
        }
        catch (Exception ex)
        {
            System.Diagnostics.Debug.WriteLine("MediaCapture initialization failed: " + ex.Message);
            return;
        }
        var frameMediaSource1 = MediaSource.CreateFromMediaFrameSource(mediaCapture.FrameSources[frontSourceInfo.Id]);
        VideoStreamer.SetPlaybackSource(frameMediaSource1);
        VideoStreamer.Play();
    }
</code>```

答: As mentioned by Faywang-MSFT here , it worked after marking the application as trusted in Kaspersky.</p>

Body:
I'm trying to play the built-in webcam feed in a MediaElement within a UWP app. It works fine for a few users but there is no feed played for most and I'm lost on what could be the issue.

Some observations when the webcam feed doesn't play:

The code executes without any exceptions

The dialog that requests user permission to access the camera is shown

The LED indicating the webcam is in use turns on soon as it is executed, but there is no feed.

Skype and Camera apps work fine.

The app was working as expected until a week back. A few things that changed in the mean time that could have had an impact are

Installed Kaspersky

A bunch of windows updates

Uninstalled VS2017 professional edition & VS2019 Community edition and installed VS2019 Professional Edition

Some additional information that might be needed to narrow down the reason.

Webcam is enabled in the Package manifest of the app

App Target version: 18362

App Min version: 18362

Windows OS Version : 18362

Any help on this would be highly appreciated. Thanks much in advance!

Here is the piece of code used to play the webcam feed where VideoStreamer is a MediaElement.

private async Task PlayLiveVideo()
    {
        var allGroups = await MediaFrameSourceGroup.FindAllAsync();
        var eligibleGroups = allGroups.Select(g => new
        {
            Group = g,

            // For each source kind, find the source which offers that kind of media frame,
            // or null if there is no such source.
            SourceInfos = new MediaFrameSourceInfo[]
            {
    g.SourceInfos.FirstOrDefault(info => info.DeviceInformation?.EnclosureLocation.Panel == Windows.Devices.Enumeration.Panel.Front
        && info.SourceKind == MediaFrameSourceKind.Color),
    g.SourceInfos.FirstOrDefault(info => info.DeviceInformation?.EnclosureLocation.Panel == Windows.Devices.Enumeration.Panel.Back
        && info.SourceKind == MediaFrameSourceKind.Color)
            }
        }).Where(g => g.SourceInfos.Any(info => info != null)).ToList();

        if (eligibleGroups.Count == 0)
        {
            System.Diagnostics.Debug.WriteLine("No source group with front and back-facing camera found.");
            return;
        }

        var selectedGroupIndex = 0; // Select the first eligible group
        MediaFrameSourceGroup selectedGroup = eligibleGroups[selectedGroupIndex].Group;
        MediaFrameSourceInfo frontSourceInfo = selectedGroup.SourceInfos[0];

        MediaCapture mediaCapture = new MediaCapture();
        MediaCaptureInitializationSettings settings = new MediaCaptureInitializationSettings()
        {
            SourceGroup = selectedGroup,
            SharingMode = MediaCaptureSharingMode.ExclusiveControl,
            MemoryPreference = MediaCaptureMemoryPreference.Cpu,
            StreamingCaptureMode = StreamingCaptureMode.Video,
        };
        try
        {
            await mediaCapture.InitializeAsync(settings);
        }
        catch (Exception ex)
        {
            System.Diagnostics.Debug.WriteLine("MediaCapture initialization failed: " + ex.Message);
            return;
        }
        var frameMediaSource1 = MediaSource.CreateFromMediaFrameSource(mediaCapture.FrameSources[frontSourceInfo.Id]);
        VideoStreamer.SetPlaybackSource(frameMediaSource1);
        VideoStreamer.Play();
    }


问:
C language strlen function with new line character in the string
Generally strlen() function in C language returns unsigned int but if the string has new line character then what will be the output ?
For example :
What will be the output of strlen("stack\n") in C language ?</p>

答:
"What will be the output of strlen("stack\n")?"

6. The newline character such as any character except '\0' (NUL) is counted as any  character else.

"Generally strlen() function in C language returns unsigned int."

That is not correct. strlen() returns a size_t value which is quite a distinct type from unsigned int, although in most implementations size_t can be an alias for unsigned int. But to keep the difference is important.

Note: If the string is stored in an char array instead (it is not a string literal and with that immutable) and you want to remove the newline, you can use strcspn():

```<code>char a[7] = "stack\n";        // 7 elements, not 6. Required to store terminating NUL.

printf("%zu\n", strlen(a));   // This will print 6.

a[strcspn(a, "\n")] = 0;      // Replace newline with NUL.

printf("%zu", strlen(a));     // This will print 5.
</code>```

Body:
"What will be the output of strlen("stack\n")?"

6. The newline character such as any character except '\0' (NUL) is counted as any  character else.

"Generally strlen() function in C language returns unsigned int."

That is not correct. strlen() returns a size_t value which is quite a distinct type from unsigned int, although in most implementations size_t can be an alias for unsigned int. But to keep the difference is important.

Note: If the string is stored in an char array instead (it is not a string literal and with that immutable) and you want to remove the newline, you can use strcspn():

char a[7] = "stack\n";        // 7 elements, not 6. Required to store terminating NUL.

printf("%zu\n", strlen(a));   // This will print 6.

a[strcspn(a, "\n")] = 0;      // Replace newline with NUL.

printf("%zu", strlen(a));     // This will print 5.


问:
Mapstruct 1.2.0 not generating mapper class in springboot 2.0.0.M3 + lombok
I'm trying to put together a sample project combining the following technologies:

Spring boot (2.0.0.M3)

Mapstruct (1.2.0.CR1)

Lombok (1.16.18)

I have defined this mapper:

```<code>@Mapper(componentModel = "spring")
public interface SourceToTargetMapper {

    SourceToTargetMapper MAPPER = Mappers.getMapper( SourceToTargetMapper.class );

    @Mappings({
        @Mapping(source = "characteristics", target = "description"),
        @Mapping(source = "identifier", target = "id")
    })
    public Target toTarget(Source source);
}
</code>```

The problem I am having is that the class implementing the SourceToTargetMapper interface is not being generated.

That 's the trace I'm getting when i run the unit test:

```<code>2017-09-04 00:13:24.726 ERROR 1712 --- [           main] o.s.test.context.TestContextManager      : Caught exception while allowing TestExecutionListener [org.springframework.boot.test.autoconfigure.SpringBootDependencyInjectionTestExecutionListener@568bf312] to prepare test instance [io.alfredux.demo.MapperTest@5ccbeb64]

org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'io.alfredux.demo.MapperTest': Unsatisfied dependency expressed through field 'sourceToTargetMapper'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'io.alfredux.demo.mapper.SourceToTargetMapper' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:570) ~[spring-beans-5.0.0.RC3.jar:5.0.0.RC3]
    at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:91) ~[spring-beans-5.0.0.RC3.jar:5.0.0.RC3]
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:356) ~[spring-beans-5.0.0.RC3.jar:5.0.0.RC3]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1352) ~[spring-beans-5.0.0.RC3.jar:5.0.0.RC3]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.autowireBeanProperties(AbstractAutowireCapableBeanFactory.java:399) ~[spring-beans-5.0.0.RC3.jar:5.0.0.RC3]
    at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.injectDependencies(DependencyInjectionTestExecutionListener.java:118) ~[spring-test-5.0.0.RC3.jar:5.0.0.RC3]
    at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.prepareTestInstance(DependencyInjectionTestExecutionListener.java:83) ~[spring-test-5.0.0.RC3.jar:5.0.0.RC3]
    at org.springframework.boot.test.autoconfigure.SpringBootDependencyInjectionTestExecutionListener.prepareTestInstance(SpringBootDependencyInjectionTestExecutionListener.java:44) ~[spring-boot-test-autoconfigure-2.0.0.M3.jar:2.0.0.M3]
    at org.springframework.test.context.TestContextManager.prepareTestInstance(TestContextManager.java:242) ~[spring-test-5.0.0.RC3.jar:5.0.0.RC3]
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.createTest(SpringJUnit4ClassRunner.java:227) [spring-test-5.0.0.RC3.jar:5.0.0.RC3]
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner$1.runReflectiveCall(SpringJUnit4ClassRunner.java:289) [spring-test-5.0.0.RC3.jar:5.0.0.RC3]
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12) [junit-4.12.jar:4.12]
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.methodBlock(SpringJUnit4ClassRunner.java:291) [spring-test-5.0.0.RC3.jar:5.0.0.RC3]
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:246) [spring-test-5.0.0.RC3.jar:5.0.0.RC3]
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:97) [spring-test-5.0.0.RC3.jar:5.0.0.RC3]
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290) [junit-4.12.jar:4.12]
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71) [junit-4.12.jar:4.12]
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288) [junit-4.12.jar:4.12]
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58) [junit-4.12.jar:4.12]
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268) [junit-4.12.jar:4.12]
    at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61) [spring-test-5.0.0.RC3.jar:5.0.0.RC3]
    at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70) [spring-test-5.0.0.RC3.jar:5.0.0.RC3]
    at org.junit.runners.ParentRunner.run(ParentRunner.java:363) [junit-4.12.jar:4.12]
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:190) [spring-test-5.0.0.RC3.jar:5.0.0.RC3]
    at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:86) [.cp/:na]
    at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38) [.cp/:na]
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:459) [.cp/:na]
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:678) [.cp/:na]
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382) [.cp/:na]
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192) [.cp/:na]
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'io.alfredux.demo.mapper.SourceToTargetMapper' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoMatchingBeanFound(DefaultListableBeanFactory.java:1486) ~[spring-beans-5.0.0.RC3.jar:5.0.0.RC3]
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1097) ~[spring-beans-5.0.0.RC3.jar:5.0.0.RC3]
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1058) ~[spring-beans-5.0.0.RC3.jar:5.0.0.RC3]
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:567) ~[spring-beans-5.0.0.RC3.jar:5.0.0.RC3]
    ... 29 common frames omitted
</code>```

I believe there’s something missing or misplaced in the build/plugin section  of my pom.xml
 file

```<code><build>
    <plugins>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
            <configuration>
                <source>${java.version}</source>
                <target>${java.version}</target>
                <annotationProcessorPaths>
                    <path>
                        <groupId>org.mapstruct</groupId>
                        <artifactId>mapstruct-processor</artifactId>
                        <version>${org.mapstruct.version}</version>
                    </path>
                </annotationProcessorPaths>
            </configuration>
        </plugin>
    </plugins>
</build>
</code>```

The source code for the project can be checked here:

https://github.com/Alfredux79/mapstruct-lombock-springboot/tree/stack-overflow-question

The problem can be reproduced downloading the branch and running the command:

```<code>mvn test
</code>```

Thanks!

答:
Add the below changes in pom.xml to make sure to use the latest m2e-apt plugin in maven.

```<code><properties>
  <!-- automatically run annotation processors within the incremental compilation -->
  <m2e.apt.activation>jdt_apt</m2e.apt.activation>
</properties>
</code>```

For eclipse or spring suite IDE support install the official mapstruct plugin.

https://marketplace.eclipse.org/content/mapstruct-eclipse-plugin#group-external-install-button

Body:
I'm trying to put together a sample project combining the following technologies:

Spring boot (2.0.0.M3)

Mapstruct (1.2.0.CR1)

Lombok (1.16.18)

I have defined this mapper:

@Mapper(componentModel = "spring")
public interface SourceToTargetMapper {

    SourceToTargetMapper MAPPER = Mappers.getMapper( SourceToTargetMapper.class );

    @Mappings({
        @Mapping(source = "characteristics", target = "description"),
        @Mapping(source = "identifier", target = "id")
    })
    public Target toTarget(Source source);
}

The problem I am having is that the class implementing the SourceToTargetMapper interface is not being generated.

That 's the trace I'm getting when i run the unit test:

2017-09-04 00:13:24.726 ERROR 1712 --- [           main] o.s.test.context.TestContextManager      : Caught exception while allowing TestExecutionListener [org.springframework.boot.test.autoconfigure.SpringBootDependencyInjectionTestExecutionListener@568bf312] to prepare test instance [io.alfredux.demo.MapperTest@5ccbeb64]

org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'io.alfredux.demo.MapperTest': Unsatisfied dependency expressed through field 'sourceToTargetMapper'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'io.alfredux.demo.mapper.SourceToTargetMapper' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:570) ~[spring-beans-5.0.0.RC3.jar:5.0.0.RC3]
    at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:91) ~[spring-beans-5.0.0.RC3.jar:5.0.0.RC3]
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:356) ~[spring-beans-5.0.0.RC3.jar:5.0.0.RC3]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1352) ~[spring-beans-5.0.0.RC3.jar:5.0.0.RC3]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.autowireBeanProperties(AbstractAutowireCapableBeanFactory.java:399) ~[spring-beans-5.0.0.RC3.jar:5.0.0.RC3]
    at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.injectDependencies(DependencyInjectionTestExecutionListener.java:118) ~[spring-test-5.0.0.RC3.jar:5.0.0.RC3]
    at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.prepareTestInstance(DependencyInjectionTestExecutionListener.java:83) ~[spring-test-5.0.0.RC3.jar:5.0.0.RC3]
    at org.springframework.boot.test.autoconfigure.SpringBootDependencyInjectionTestExecutionListener.prepareTestInstance(SpringBootDependencyInjectionTestExecutionListener.java:44) ~[spring-boot-test-autoconfigure-2.0.0.M3.jar:2.0.0.M3]
    at org.springframework.test.context.TestContextManager.prepareTestInstance(TestContextManager.java:242) ~[spring-test-5.0.0.RC3.jar:5.0.0.RC3]
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.createTest(SpringJUnit4ClassRunner.java:227) [spring-test-5.0.0.RC3.jar:5.0.0.RC3]
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner$1.runReflectiveCall(SpringJUnit4ClassRunner.java:289) [spring-test-5.0.0.RC3.jar:5.0.0.RC3]
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12) [junit-4.12.jar:4.12]
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.methodBlock(SpringJUnit4ClassRunner.java:291) [spring-test-5.0.0.RC3.jar:5.0.0.RC3]
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:246) [spring-test-5.0.0.RC3.jar:5.0.0.RC3]
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:97) [spring-test-5.0.0.RC3.jar:5.0.0.RC3]
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290) [junit-4.12.jar:4.12]
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71) [junit-4.12.jar:4.12]
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288) [junit-4.12.jar:4.12]
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58) [junit-4.12.jar:4.12]
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268) [junit-4.12.jar:4.12]
    at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61) [spring-test-5.0.0.RC3.jar:5.0.0.RC3]
    at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70) [spring-test-5.0.0.RC3.jar:5.0.0.RC3]
    at org.junit.runners.ParentRunner.run(ParentRunner.java:363) [junit-4.12.jar:4.12]
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:190) [spring-test-5.0.0.RC3.jar:5.0.0.RC3]
    at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:86) [.cp/:na]
    at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38) [.cp/:na]
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:459) [.cp/:na]
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:678) [.cp/:na]
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382) [.cp/:na]
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192) [.cp/:na]
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'io.alfredux.demo.mapper.SourceToTargetMapper' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoMatchingBeanFound(DefaultListableBeanFactory.java:1486) ~[spring-beans-5.0.0.RC3.jar:5.0.0.RC3]
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1097) ~[spring-beans-5.0.0.RC3.jar:5.0.0.RC3]
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1058) ~[spring-beans-5.0.0.RC3.jar:5.0.0.RC3]
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:567) ~[spring-beans-5.0.0.RC3.jar:5.0.0.RC3]
    ... 29 common frames omitted

I believe there’s something missing or misplaced in the build/plugin section  of my pom.xml
 file

<build>
    <plugins>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
            <configuration>
                <source>${java.version}</source>
                <target>${java.version}</target>
                <annotationProcessorPaths>
                    <path>
                        <groupId>org.mapstruct</groupId>
                        <artifactId>mapstruct-processor</artifactId>
                        <version>${org.mapstruct.version}</version>
                    </path>
                </annotationProcessorPaths>
            </configuration>
        </plugin>
    </plugins>
</build>

The source code for the project can be checked here:

https://github.com/Alfredux79/mapstruct-lombock-springboot/tree/stack-overflow-question

The problem can be reproduced downloading the branch and running the command:

mvn test

Thanks!

Body:
Add the below changes in pom.xml to make sure to use the latest m2e-apt plugin in maven.

<properties>
  <!-- automatically run annotation processors within the incremental compilation -->
  <m2e.apt.activation>jdt_apt</m2e.apt.activation>
</properties>

For eclipse or spring suite IDE support install the official mapstruct plugin.

https://marketplace.eclipse.org/content/mapstruct-eclipse-plugin#group-external-install-button


问:
How to rebuild node modules after node.js version upgrade?
I upgraded my node.js version from 9.x.x to a version 12.x.x. Do i now need to rebuild all my old node modules to "bind" them to the new node.js version? How is it done? What if i run command (from windows) "npm rebuild /node_modules" (put the whole folder as parameter)? Will it work?

EDIT: Perhaps this was a useless question. It looks like i needed only to rebuild node-sass-module, not others.

答: After node version update i only needed to reduild node-sass module. I thought i have to do a similar rebuild to all modules i use, but all the other npm modules work without problems.</p>


问:
Wrapping props component in React js
I have prop 'drawerComponent' which goes in Drawer prop 'component'

This code works fine.

render() {
    return(
        <Drawer component={this.props.drawerComponent} />
    )
}
```

<p>But if I try to wrap drawerComponent by other one it fails. I get 'Element type error' or drawerComponent  is not rendering</p>

<pre class="lang-js prettyprint-override"><code>render() {

    const Wrapper = (props) => <div>{this.props.drawerComponent}</div>

    return(
        <Drawer component={() => <Wrapper drawerComponent={this.props.drawerComponent} />} />
    )
}
</code>```

What's wrong with it?

答:
You Drawer component accepts a component instance and not a component, you can simply write the wrapper like</p>

```<code>render() {

    const Wrapper = (props) => <div>{props.drawerComponent}</div>

    return(
        <Drawer component={<Wrapper drawerComponent={this.props.drawerComponent} />} />
}
</code>```

Title: Wrapping props component in React js

Body:
I have prop 'drawerComponent' which goes in Drawer prop 'component'

This code works fine.

render() {
    return(
        <Drawer component={this.props.drawerComponent} />
    )
}

But if I try to wrap drawerComponent by other one it fails. I get 'Element type error' or drawerComponent  is not rendering

render() {

    const Wrapper = (props) =>
{this.props.drawerComponent}

    return(
        <Drawer component={() => <Wrapper drawerComponent={this.props.drawerComponent} />} />
    )
}

What's wrong with it?

Body:
You Drawer component accepts a component instance and not a component, you can simply write the wrapper like

render() {

    const Wrapper = (props) => <div>{props.drawerComponent}</div>

    return(
        <Drawer component={<Wrapper drawerComponent={this.props.drawerComponent} />} />
}


问:
How to match a Spring @RequestMapping having a @pathVariable containing "/"?
I am doing the following request from the client:

/search/hello%2Fthere/

where the search term "hello/there" has been URLencoded.

On the server I am trying to match this URL using the following request mapping:

```<code>
@RequestMapping("/search/{searchTerm}/")
public Map searchWithSearchTerm(@PathVariable String searchTerm) {
// more code here
}
</code>```

But I am getting error 404 on the server, due I don't have any match for the URL. I noticed that the URL is decoded before Spring gets it. Therefore is trying to match /search/hello/there which does not have any match.

I found a Jira related to this problem here: http://jira.springframework.org/browse/SPR-6780 .But I still don't know how to solve my problem.

Any ideas?

Thanks

答:
```<code>    @Configuration
    public class AdditionalWebConfig extends WebMvcConfigurationSupport {
     .......
     ...........
     ...........
    @Override
    public void configureContentNegotiation(ContentNegotiationConfigurer
    configurer) {
       configurer.favorPathExtension(false);
    }
    .......
    .......
  }
</code>```

and add regex like this in @PathVariable("user/{username:.+}")

Body:
I am doing the following request from the client:

/search/hello%2Fthere/

where the search term "hello/there" has been URLencoded.

On the server I am trying to match this URL using the following request mapping:

@RequestMapping("/search/{searchTerm}/")
public Map searchWithSearchTerm(@PathVariable String searchTerm) {
// more code here
}

But I am getting error 404 on the server, due I don't have any match for the URL. I noticed that the URL is decoded before Spring gets it. Therefore is trying to match /search/hello/there which does not have any match.

I found a Jira related to this problem here: http://jira.springframework.org/browse/SPR-6780 .But I still don't know how to solve my problem.

Any ideas?

Thanks

Body:
    @Configuration
    public class AdditionalWebConfig extends WebMvcConfigurationSupport {
     .......
     ...........
     ...........
    @Override
    public void configureContentNegotiation(ContentNegotiationConfigurer
    configurer) {
       configurer.favorPathExtension(false);
    }
    .......
    .......
  }

and add regex like this in @PathVariable("user/{username:.+}")


问:
Hide TextView when SearchView is open
I am using TextView on top of SearchView as a heading. The other option is customising the search query hint by changing the font, color, text size and centering. This seems like a simpler method.

```<code><androidx.constraintlayout.widget.ConstraintLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <SearchView
            android:id="@+id/searchview"
            android:layout_width="match_parent"
            android:layout_height="43dp"
            android:layout_marginStart="12dp"
            android:layout_marginTop="40dp"
            android:layout_marginEnd="12dp"
            android:background="@drawable/searchbackground"
            android:closeIcon="@drawable/search_x_button"
            android:iconifiedByDefault="false"
            android:paddingStart="2dp"
            android:paddingTop="11dp"
            android:paddingEnd="15dp"
            android:paddingBottom="11dp"
            android:queryBackground="@android:color/transparent"
            android:gravity="center"
            android:searchIcon="@drawable/ic_ssearch"
            android:textSize="15sp"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent"/>

        <TextView
            android:id="@+id/textView13"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginStart="24dp"
            android:layout_marginTop="49dp"
            android:layout_marginEnd="24dp"
            android:fontFamily="@font/manrope_semibold"
            android:text="@string/search"
            android:textColor="@color/font_title"
            android:textSize="19sp"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent" />
</code>```

How can I set the textview to hide once the searchview is in focus, aka user taps on it and the blinking cursor appears?

Edit: fixed by doing this

```<code>searchHint = view.findViewById(R.id.textView13);
</code>```

and then

```<code>public boolean onQueryTextChange(String query) {
            if (query.equals("")) {
                searchHint.setVisibility(View.VISIBLE);
            } else {
                searchHint.setVisibility(View.GONE);
            }
            return true;
        }
</code>```

答:
If I understand you correctly, you just want to hide the Hint text (@+id/textView13) when user click on SearchView(@+id/searchview).
If so, seem that you can add below codes(you can check if can meet your requirement)</p>

```<code>    searchview.setOnQueryTextFocusChangeListener { _, hasFocus ->
        if (hasFocus) {
            textView13.visibility = View.INVISIBLE
        } else {
            textView13.visibility = View.VISIBLE
        }
    }
</code>```

Title: Hide TextView when SearchView is open

Body:
I am using TextView on top of SearchView as a heading. The other option is customising the search query hint by changing the font, color, text size and centering. This seems like a simpler method.

<androidx.constraintlayout.widget.ConstraintLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <SearchView
            android:id="@+id/searchview"
            android:layout_width="match_parent"
            android:layout_height="43dp"
            android:layout_marginStart="12dp"
            android:layout_marginTop="40dp"
            android:layout_marginEnd="12dp"
            android:background="@drawable/searchbackground"
            android:closeIcon="@drawable/search_x_button"
            android:iconifiedByDefault="false"
            android:paddingStart="2dp"
            android:paddingTop="11dp"
            android:paddingEnd="15dp"
            android:paddingBottom="11dp"
            android:queryBackground="@android:color/transparent"
            android:gravity="center"
            android:searchIcon="@drawable/ic_ssearch"
            android:textSize="15sp"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent"/>

        <TextView
            android:id="@+id/textView13"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginStart="24dp"
            android:layout_marginTop="49dp"
            android:layout_marginEnd="24dp"
            android:fontFamily="@font/manrope_semibold"
            android:text="@string/search"
            android:textColor="@color/font_title"
            android:textSize="19sp"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent" />

How can I set the textview to hide once the searchview is in focus, aka user taps on it and the blinking cursor appears?

Edit: fixed by doing this

searchHint = view.findViewById(R.id.textView13);

and then

public boolean onQueryTextChange(String query) {
            if (query.equals("")) {
                searchHint.setVisibility(View.VISIBLE);
            } else {
                searchHint.setVisibility(View.GONE);
            }
            return true;
        }

Body:
If I understand you correctly, you just want to hide the Hint text (@+id/textView13) when user click on SearchView(@+id/searchview).
If so, seem that you can add below codes(you can check if can meet your requirement)

    searchview.setOnQueryTextFocusChangeListener { _, hasFocus ->
        if (hasFocus) {
            textView13.visibility = View.INVISIBLE
        } else {
            textView13.visibility = View.VISIBLE
        }
    }


问:
How do I include another file in an httpHandler?
I'm creating a webhandler and want to include classes from another file.  How do I do this?</p>

答: Move the code from the .aspx file to a .vb file.  If the .vb file is not in the same project as the .ashx file, then compile the file into an assembly and reference the assembly in the project where the .ashx exists.  Then you can instantiate the classes in the vb file in your ashx.


问:
Create kubernetes secret for docker registry - Terraform
Using kubectl we can create docker registry authentication secret as follows

```<code>kubectl create secret docker-registry regsecret \
--docker-server=docker.example.com \
--docker-username=kube \
--docker-password=PW_STRING \
--docker-email=my@email.com \
</code>```

How do i create this secret using terraform, i saw this link, it has data, in the flow of terraform the kubernetes instance is being created in azure and i get the data required from there and i created something like below

```<code>resource "kubernetes_secret" "docker-registry" {
  metadata {
    name = "registry-credentials"
  }

  data = {
    docker-server = data.azurerm_container_registry.docker_registry_data.login_server
    docker-username = data.azurerm_container_registry.docker_registry_data.admin_username
    docker-password = data.azurerm_container_registry.docker_registry_data.admin_password
  }

}
</code>```

It seems that it is wrong as the images are not being pulled. What am i missing here.

答:
I would suggest creating a azurerm_role_assignement to give aks access to the acr:

```<code>resource "azurerm_role_assignment" "aks_sp_acr" {
  scope                = azurerm_container_registry.acr.id
  role_definition_name = "AcrPull"
  principal_id         = var.service_principal_obj_id

  depends_on = [
    azurerm_kubernetes_cluster.aks,
    azurerm_container_registry.acr
  ]
}
</code>```

Update

You can create the service principal in the azure portal or with az cli and use client_id, client_secret and object-id in terraform.

Get Client_id and Object_id by running az ad sp list --filter "displayName eq '<name>'". The secret has to be created in the Certificates & secrets tab of the service principal. See this guide: https://pixelrobots.co.uk/2018/11/first-look-at-terraform-and-the-azure-cloud-shell/

Just set all three as variable, eg for obj_id:

```<code>variable "service_principal_obj_id" {
   default = "<object-id>"
}
</code>```

Now use the credentials with aks:

```<code>resource "azurerm_kubernetes_cluster" "aks" {

  ...

  service_principal {
    client_id     = var.service_principal_app_id
    client_secret = var.service_principal_password
  }

  ...

}
</code>```

And set the object id in the acr as described above.

Alternative

You can create the service principal with terraform (only works if you have the necessary permissions).  https://www.terraform.io/docs/providers/azuread/r/service_principal.html combined with a random_password resource:

```<code>resource "azuread_application" "aks_sp" {
  name                       = "somename"
  available_to_other_tenants = false
  oauth2_allow_implicit_flow = false
}

resource "azuread_service_principal" "aks_sp" {
  application_id = azuread_application.aks_sp.application_id

  depends_on = [
    azuread_application.aks_sp
  ]
}

resource "azuread_service_principal_password" "aks_sp_pwd" {
  service_principal_id = azuread_service_principal.aks_sp.id
  value                = random_password.aks_sp_pwd.result
  end_date             = "2099-01-01T01:02:03Z"

  depends_on = [
    azuread_service_principal.aks_sp
  ]
}
</code>```

You need to assign the role "Conributer" to the sp and can use it directly in aks / acr.

```<code>resource "azurerm_role_assignment" "aks_sp_role_assignment" {
  scope                = var.subscription_id
  role_definition_name = "Contributor"
  principal_id         = azuread_service_principal.aks_sp.id

  depends_on = [
    azuread_service_principal_password.aks_sp_pwd
  ]
}
</code>```

Use them with aks:

```<code>resource "azurerm_kubernetes_cluster" "aks" {

  ...

  service_principal {
    client_id     = azuread_service_principal.aks_sp.app_id
    client_secret = azuread_service_principal_password.aks_sp_pwd.value
  }

  ...

}
</code>```

and the role assignment:

```<code>resource "azurerm_role_assignment" "aks_sp_acr" {
  scope                = azurerm_container_registry.acr.id
  role_definition_name = "AcrPull"
  principal_id         = azuread_service_principal.aks_sp.object_id

  depends_on = [
    azurerm_kubernetes_cluster.aks,
    azurerm_container_registry.acr
  ]
}
</code>```

Update secret example

```<code>resource "random_password" "aks_sp_pwd" {
  length = 32
  special = true
}
</code>```

Body:
Using kubectl we can create docker registry authentication secret as follows

kubectl create secret docker-registry regsecret \
--docker-server=docker.example.com \
--docker-username=kube \
--docker-password=PW_STRING \
--docker-email=my@email.com \

How do i create this secret using terraform, i saw this link, it has data, in the flow of terraform the kubernetes instance is being created in azure and i get the data required from there and i created something like below

resource "kubernetes_secret" "docker-registry" {
  metadata {
    name = "registry-credentials"
  }

  data = {
    docker-server = data.azurerm_container_registry.docker_registry_data.login_server
    docker-username = data.azurerm_container_registry.docker_registry_data.admin_username
    docker-password = data.azurerm_container_registry.docker_registry_data.admin_password
  }

}

It seems that it is wrong as the images are not being pulled. What am i missing here.

Body:
I would suggest creating a azurerm_role_assignement to give aks access to the acr:

resource "azurerm_role_assignment" "aks_sp_acr" {
  scope                = azurerm_container_registry.acr.id
  role_definition_name = "AcrPull"
  principal_id         = var.service_principal_obj_id

  depends_on = [
    azurerm_kubernetes_cluster.aks,
    azurerm_container_registry.acr
  ]
}

Update

You can create the service principal in the azure portal or with az cli and use client_id, client_secret and object-id in terraform.

Get Client_id and Object_id by running az ad sp list --filter "displayName eq '<name>'". The secret has to be created in the Certificates & secrets tab of the service principal. See this guide: https://pixelrobots.co.uk/2018/11/first-look-at-terraform-and-the-azure-cloud-shell/

Just set all three as variable, eg for obj_id:

variable "service_principal_obj_id" {
   default = "<object-id>"
}

Now use the credentials with aks:

resource "azurerm_kubernetes_cluster" "aks" {

  ...

  service_principal {
    client_id     = var.service_principal_app_id
    client_secret = var.service_principal_password
  }

  ...

}

And set the object id in the acr as described above.

Alternative

You can create the service principal with terraform (only works if you have the necessary permissions).  https://www.terraform.io/docs/providers/azuread/r/service_principal.html combined with a random_password resource:

resource "azuread_application" "aks_sp" {
  name                       = "somename"
  available_to_other_tenants = false
  oauth2_allow_implicit_flow = false
}

resource "azuread_service_principal" "aks_sp" {
  application_id = azuread_application.aks_sp.application_id

  depends_on = [
    azuread_application.aks_sp
  ]
}

resource "azuread_service_principal_password" "aks_sp_pwd" {
  service_principal_id = azuread_service_principal.aks_sp.id
  value                = random_password.aks_sp_pwd.result
  end_date             = "2099-01-01T01:02:03Z"

  depends_on = [
    azuread_service_principal.aks_sp
  ]
}

You need to assign the role "Conributer" to the sp and can use it directly in aks / acr.

resource "azurerm_role_assignment" "aks_sp_role_assignment" {
  scope                = var.subscription_id
  role_definition_name = "Contributor"
  principal_id         = azuread_service_principal.aks_sp.id

  depends_on = [
    azuread_service_principal_password.aks_sp_pwd
  ]
}

Use them with aks:

resource "azurerm_kubernetes_cluster" "aks" {

  ...

  service_principal {
    client_id     = azuread_service_principal.aks_sp.app_id
    client_secret = azuread_service_principal_password.aks_sp_pwd.value
  }

  ...

}

and the role assignment:

resource "azurerm_role_assignment" "aks_sp_acr" {
  scope                = azurerm_container_registry.acr.id
  role_definition_name = "AcrPull"
  principal_id         = azuread_service_principal.aks_sp.object_id

  depends_on = [
    azurerm_kubernetes_cluster.aks,
    azurerm_container_registry.acr
  ]
}

Update secret example

resource "random_password" "aks_sp_pwd" {
  length = 32
  special = true
}