问:
Opengl proper lighting problem
I have written the following program to display a teapot on a table in a room with 2side walls and a floor.

```<code>#include <stdio.h>
#include <glut.h>

void wall1(float thickness)
{
    glPushMatrix();
    glTranslatef(100,100,0);
    glRotatef(90,1,0,0);
    glScalef(thickness,1,1);
    glutSolidCube(100);
    glPopMatrix();
}
void wall2(float thickness)
{
    glPushMatrix();
    glTranslatef(150,100,-50);
    glScalef(1,1,thickness);
    glutSolidCube(100);
    glPopMatrix();
}
void floor(float thickness)
{
    glPushMatrix();
    glTranslatef(150,50,0);
    glScalef(1,thickness,1);
    glutSolidCube(100);
    glPopMatrix();
}
void leg(float thickness)
{
    glPushMatrix();
    glScalef(thickness,.5,thickness);
    glutSolidCube(100);
    glPopMatrix();
}
void tableTop(float thickess)
{
    glPushMatrix();
    glTranslatef(150,100,0);
    glScalef(.5,thickess,.5);
    glutSolidCube(100);
    glPopMatrix();
}
void table()
{
    tableTop(.05);

    glPushMatrix();
    glTranslatef(125,75,-25);
    leg(.05);
    glPopMatrix();

    glPushMatrix();
    glTranslatef(175,75,-25);
    leg(.05);
    glPopMatrix();

    glPushMatrix();
    glTranslatef(175,75,25);
    leg(.05);
    glPopMatrix();

    glPushMatrix();
    glTranslatef(125,75,25);
    leg(.05);
    glPopMatrix();

    glPushMatrix();
    glTranslatef(150,110,0);
    glScalef(.1,.1,.1);
    glutSolidTeapot(100);
    glPopMatrix();
}
void display()
{
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

    float pos[] = {200,200,0};
    float dif[] = {.3,.3,.3,3};
    float spe[] = {1,1,1,1};
    float amb[] = {1,1,1,0};
    glLightfv(GL_LIGHT0,GL_POSITION,pos);
    glLightfv(GL_LIGHT0,GL_DIFFUSE,dif);
    glLightfv(GL_LIGHT0,GL_AMBIENT,amb);
    glLightfv(GL_LIGHT0,GL_SPECULAR,spe);

    glTranslatef(50,50,0);
    glRotatef(30,1,0,0);
    glRotatef(-30,0,1,0);
    wall1(.05);
    wall2(.05);
    floor(0.05);
    table();

    glFlush();
}
void reshape(int w,int h)
{
    glViewport(0,0,w,h);
    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();
    glOrtho(0,400,0,400,-400,400);
    glMatrixMode(GL_MODELVIEW);
}

void main(int argc,char** argv)
{
    glutInit(&argc,argv);
    glutInitDisplayMode(GLUT_RGB | GLUT_SINGLE | GLUT_DEPTH);
    glutInitWindowPosition(100,100);
    glutInitWindowSize(400,400);
    glutCreateWindow("woot");
    glClearColor(1,1,1,1);
    glEnable(GL_DEPTH_TEST);
    glEnable(GL_LIGHTING);
    glEnable(GL_LIGHT0);

    glShadeModel(GL_SMOOTH);
    glutReshapeFunc(reshape);
    glutDisplayFunc(display);
    glutMainLoop();
}
</code>```

The problem with this is my lighting part is not working as expected. Its not illuminating evenly all my objects... What am i missing? This making even the teapot hard to sea.
My lighting part is in display function.

答:
I was missing

glEnable(GL_NORMALIZE);

in the main function, and thus opengl was not rendering it properly! Alse @Christian's answer of using ambient only worked.

:)

Title: Opengl proper lighting problem

Body:
I have written the following program to display a teapot on a table in a room with 2side walls and a floor.

#include <stdio.h>
#include <glut.h>

void wall1(float thickness)
{
    glPushMatrix();
    glTranslatef(100,100,0);
    glRotatef(90,1,0,0);
    glScalef(thickness,1,1);
    glutSolidCube(100);
    glPopMatrix();
}
void wall2(float thickness)
{
    glPushMatrix();
    glTranslatef(150,100,-50);
    glScalef(1,1,thickness);
    glutSolidCube(100);
    glPopMatrix();
}
void floor(float thickness)
{
    glPushMatrix();
    glTranslatef(150,50,0);
    glScalef(1,thickness,1);
    glutSolidCube(100);
    glPopMatrix();
}
void leg(float thickness)
{
    glPushMatrix();
    glScalef(thickness,.5,thickness);
    glutSolidCube(100);
    glPopMatrix();
}
void tableTop(float thickess)
{
    glPushMatrix();
    glTranslatef(150,100,0);
    glScalef(.5,thickess,.5);
    glutSolidCube(100);
    glPopMatrix();
}
void table()
{
    tableTop(.05);

    glPushMatrix();
    glTranslatef(125,75,-25);
    leg(.05);
    glPopMatrix();

    glPushMatrix();
    glTranslatef(175,75,-25);
    leg(.05);
    glPopMatrix();

    glPushMatrix();
    glTranslatef(175,75,25);
    leg(.05);
    glPopMatrix();

    glPushMatrix();
    glTranslatef(125,75,25);
    leg(.05);
    glPopMatrix();

    glPushMatrix();
    glTranslatef(150,110,0);
    glScalef(.1,.1,.1);
    glutSolidTeapot(100);
    glPopMatrix();
}
void display()
{
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

    float pos[] = {200,200,0};
    float dif[] = {.3,.3,.3,3};
    float spe[] = {1,1,1,1};
    float amb[] = {1,1,1,0};
    glLightfv(GL_LIGHT0,GL_POSITION,pos);
    glLightfv(GL_LIGHT0,GL_DIFFUSE,dif);
    glLightfv(GL_LIGHT0,GL_AMBIENT,amb);
    glLightfv(GL_LIGHT0,GL_SPECULAR,spe);

    glTranslatef(50,50,0);
    glRotatef(30,1,0,0);
    glRotatef(-30,0,1,0);
    wall1(.05);
    wall2(.05);
    floor(0.05);
    table();

    glFlush();
}
void reshape(int w,int h)
{
    glViewport(0,0,w,h);
    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();
    glOrtho(0,400,0,400,-400,400);
    glMatrixMode(GL_MODELVIEW);
}

void main(int argc,char** argv)
{
    glutInit(&argc,argv);
    glutInitDisplayMode(GLUT_RGB | GLUT_SINGLE | GLUT_DEPTH);
    glutInitWindowPosition(100,100);
    glutInitWindowSize(400,400);
    glutCreateWindow("woot");
    glClearColor(1,1,1,1);
    glEnable(GL_DEPTH_TEST);
    glEnable(GL_LIGHTING);
    glEnable(GL_LIGHT0);

    glShadeModel(GL_SMOOTH);
    glutReshapeFunc(reshape);
    glutDisplayFunc(display);
    glutMainLoop();
}

The problem with this is my lighting part is not working as expected. Its not illuminating evenly all my objects... What am i missing? This making even the teapot hard to sea.
My lighting part is in display function.


来源: stackexchange

问:
how to get parent folder name in spark?
file:/C:/workspace/Spark_Scala_Exercise2/src/main/Resources/exercise-2/input/run_1/batch_id=73/part-00000-7489f493-c825-469a-9877-0b0e2c75cd4b.c000.snappy.parquet like i have many files

from this
i only want batch_id column with 73

答:
I think, you are trying to read a saved files with a partition batch_id
Try this-

create the files partitioned by batch_id

This is how it looks in my case /Users/sokale/models/run_1/batch_id=73/part-00001-5fa5aebb-a836-43d2-97d2-7cf9bb722c26.c000.snappy.parquet

  val df = spark.range(1,5)
      .withColumn("batch_id", lit(70) + col("id"))

    df.show(false)
    df.printSchema()

    /**
      * +---+--------+
      * |id |batch_id|
      * +---+--------+
      * |1  |71      |
      * |2  |72      |
      * |3  |73      |
      * |4  |74      |
      * +---+--------+
      *
      * root
      * |-- id: long (nullable = false)
      * |-- batch_id: long (nullable = false)
      */

    df.write.partitionBy("batch_id")
      .mode(SaveMode.Overwrite)
      .parquet("/Users/sokale/models/run_1")
    /**
      * $ cd run_1/
      * $ ls -l
      * total 0
      * ............ _SUCCESS
      * ............ batch_id=71
      * ............ batch_id=72
      * ............ batch_id=73
      * ............ batch_id=74
      */

```

<h2>2. Read the parquet file for partition <code>barch_id=73</code></h2>

<p>From the spark doc-</p>

```spark.sql.parquet.filterPushdown    default-true    Enables Parquet filter push-down optimization when set to true.
```

<p>that means <code>df.read.parquet(dir).where(partitionCOndition)</code> only read the the specified partitioned directory using filter push down</p>

<pre class="lang-scala prettyprint-override"><code> // read only file with batch_id=73
    spark.read.parquet("/Users/sokale/models/run_1").where(col("batch_id").equalTo(73))
      .show(false)

    /**
      * +---+--------+
      * |id |batch_id|
      * +---+--------+
      * |3  |73      |
      * +---+--------+
      */
    // read all partitions
    val readDF = spark.read.parquet("/Users/sokale/models/run_1")
    readDF.show(false)
    readDF.printSchema()

    /**
      * +---+--------+
      * |id |batch_id|
      * +---+--------+
      * |3  |73      |
      * |2  |72      |
      * |1  |71      |
      * |4  |74      |
      * +---+--------+
      *
      * root
      * |-- id: long (nullable = true)
      * |-- batch_id: integer (nullable = true)
      */
</code>```

ContentLicense: CC BY-SA 4.0

Title: how to get parent folder name in spark?

Body:
I think, you are trying to read a saved files with a partition batch_id
Try this-

create the files partitioned by batch_id

This is how it looks in my case /Users/sokale/models/run_1/batch_id=73/part-00001-5fa5aebb-a836-43d2-97d2-7cf9bb722c26.c000.snappy.parquet

  val df = spark.range(1,5)
      .withColumn("batch_id", lit(70) + col("id"))

    df.show(false)
    df.printSchema()

    /**
      * +---+--------+
      * |id |batch_id|
      * +---+--------+
      * |1  |71      |
      * |2  |72      |
      * |3  |73      |
      * |4  |74      |
      * +---+--------+
      *
      * root
      * |-- id: long (nullable = false)
      * |-- batch_id: long (nullable = false)
      */

    df.write.partitionBy("batch_id")
      .mode(SaveMode.Overwrite)
      .parquet("/Users/sokale/models/run_1")
    /**
      * $ cd run_1/
      * $ ls -l
      * total 0
      * ............ _SUCCESS
      * ............ batch_id=71
      * ............ batch_id=72
      * ............ batch_id=73
      * ............ batch_id=74
      */

2. Read the parquet file for partition barch_id=73

From the spark doc-

spark.sql.parquet.filterPushdown    default-true    Enables Parquet filter push-down optimization when set to true.

that means df.read.parquet(dir).where(partitionCOndition) only read the the specified partitioned directory using filter push down

 // read only file with batch_id=73
    spark.read.parquet("/Users/sokale/models/run_1").where(col("batch_id").equalTo(73))
      .show(false)

    /**
      * +---+--------+
      * |id |batch_id|
      * +---+--------+
      * |3  |73      |
      * +---+--------+
      */
    // read all partitions
    val readDF = spark.read.parquet("/Users/sokale/models/run_1")
    readDF.show(false)
    readDF.printSchema()

    /**
      * +---+--------+
      * |id |batch_id|
      * +---+--------+
      * |3  |73      |
      * |2  |72      |
      * |1  |71      |
      * |4  |74      |
      * +---+--------+
      *
      * root
      * |-- id: long (nullable = true)
      * |-- batch_id: integer (nullable = true)
      */


问:
2 columns in two different sheets transferred to a third column
I am working currently on an Excel-file which consists of 3 sheets. The three sheets consist of following, firstly the sheet "Datenquelle", secondly the sheet "Datenunterschied" and thirdly the sheet "Daten".

All three sheets contain identical column names and similar data. I want to highlight the differences of the data in "Datenquelle" and "Daten" into the sheet "Datenunterschied" via a VBA Macro.

The reference point should be the column "Identifier".

As you can see, the sheet "Daten" contains four datasets with following Identifier numbers:

6257 - 6258 - 6259 - 6260

The sheet "Datenquelle" contains six Identifier numbers:

6257 - 6258 - 6259 - 6260 - 6261 - 6268

The goal would be that all the datasets which are not contained in sheet "Daten", but are contained "Datenquelle", should be taken via a VBA Macro into the sheet "Datenunterschied". In my example, those would be the datasets which following Identifiers "6261" & "6268". The whole cell of the datasets "6261" & "6268" should be transferred to "Datenunterschied".

I tried following Macro, but it didn't produce the right outcome.

```<code>Sub Unterschied()
Dim CompareRange As Object, x As Object, y As Object
Dim lastRow As Integer

Set CompareRange = Sheets("Datenquelle").Range("H2:H" & Sheets("Datenquelle").Cells(Rows.Count,  _
9).End(xlUp).Row)

    For Each x In Sheets("Daten").Range("H2:H" & Sheets("Daten").Cells(Rows.Count, 9).End(xlUp). _
Row)
        For Each y In CompareRange

        If y <> x Then
            lastRow = Sheets("Datenunterschied").Cells(Rows.Count, 1).End(xlUp).Row + 1
            Sheets("Datenunterschied").Cells(lastRow, 9).Value = x.Value
            Sheets("Datenunterschied").Cells(lastRow, 10).Value = x.Offset(0, 1).Value
            Sheets("Datenunterschied").Cells(lastRow, 11).Value = x.Offset(0, 2).Value
            Sheets("Datenunterschied").Cells(lastRow, 8).Value = x.Offset(0, -1).Value
            Sheets("Datenunterschied").Cells(lastRow, 7).Value = x.Offset(0, -2).Value
            Sheets("Datenunterschied").Cells(lastRow, 6).Value = x.Offset(0, -3).Value
            Sheets("Datenunterschied").Cells(lastRow, 5).Value = x.Offset(0, -4).Value
            Sheets("Datenunterschied").Cells(lastRow, 4).Value = x.Offset(0, -5).Value
            Sheets("Datenunterschied").Cells(lastRow, 3).Value = x.Offset(0, -6).Value
            Sheets("Datenunterschied").Cells(lastRow, 2).Value = x.Offset(0, -7).Value
            Sheets("Datenunterschied").Cells(lastRow, 1).Value = x.Offset(0, -8).Value
        End If
        Next y
    Next x
End Sub
</code>```

I have provided the data in here:

https://www.herber.de/bbs/user/137783.xlsm

Greetings
Kanime

答:
The solution to the problem looks like following:</p>

```<code>Sub Difference()

Dim lastRow As Long
Dim x, y As Object 'Cells which will loop through, but declared as objects.

    For Each x In Sheets("Datenquelle").Range("I2:I" & Sheets("Datenquelle").Cells(Rows.Count, 9).End(xlUp).Row)
        Dim foundMatch As Boolean 'setup marker that tells us if no match has been found
        foundMatch = False

        For Each y In Sheets("Daten").Range("I2:I" & Sheets("Daten").Cells(Rows.Count, 9).End(xlUp).Row)
            If x.Value = y.Value Then
                foundMatch = True
                Exit For
            End If
        Next y

        If Not foundMatch Then          'only when y has been looped through without finding a match
            lastRow = Sheets("Datenunterschied").Cells(Rows.Count, 9).End(xlUp).Row + 1
            Sheets("Datenunterschied").Cells(lastRow, 9).Value = x.Value ' Copying and setting the data in last available free row
            Debug.Print x.Value
        End If
    Next x
End Sub

</code>```

Body:
I am working currently on an Excel-file which consists of 3 sheets. The three sheets consist of following, firstly the sheet "Datenquelle", secondly the sheet "Datenunterschied" and thirdly the sheet "Daten".

All three sheets contain identical column names and similar data. I want to highlight the differences of the data in "Datenquelle" and "Daten" into the sheet "Datenunterschied" via a VBA Macro.

The reference point should be the column "Identifier".

As you can see, the sheet "Daten" contains four datasets with following Identifier numbers:

6257 - 6258 - 6259 - 6260

The sheet "Datenquelle" contains six Identifier numbers:

6257 - 6258 - 6259 - 6260 - 6261 - 6268

The goal would be that all the datasets which are not contained in sheet "Daten", but are contained "Datenquelle", should be taken via a VBA Macro into the sheet "Datenunterschied". In my example, those would be the datasets which following Identifiers "6261" & "6268". The whole cell of the datasets "6261" & "6268" should be transferred to "Datenunterschied".

I tried following Macro, but it didn't produce the right outcome.

Sub Unterschied()
Dim CompareRange As Object, x As Object, y As Object
Dim lastRow As Integer

Set CompareRange = Sheets("Datenquelle").Range("H2:H" & Sheets("Datenquelle").Cells(Rows.Count,  _
9).End(xlUp).Row)

    For Each x In Sheets("Daten").Range("H2:H" & Sheets("Daten").Cells(Rows.Count, 9).End(xlUp). _
Row)
        For Each y In CompareRange

        If y <> x Then
            lastRow = Sheets("Datenunterschied").Cells(Rows.Count, 1).End(xlUp).Row + 1
            Sheets("Datenunterschied").Cells(lastRow, 9).Value = x.Value
            Sheets("Datenunterschied").Cells(lastRow, 10).Value = x.Offset(0, 1).Value
            Sheets("Datenunterschied").Cells(lastRow, 11).Value = x.Offset(0, 2).Value
            Sheets("Datenunterschied").Cells(lastRow, 8).Value = x.Offset(0, -1).Value
            Sheets("Datenunterschied").Cells(lastRow, 7).Value = x.Offset(0, -2).Value
            Sheets("Datenunterschied").Cells(lastRow, 6).Value = x.Offset(0, -3).Value
            Sheets("Datenunterschied").Cells(lastRow, 5).Value = x.Offset(0, -4).Value
            Sheets("Datenunterschied").Cells(lastRow, 4).Value = x.Offset(0, -5).Value
            Sheets("Datenunterschied").Cells(lastRow, 3).Value = x.Offset(0, -6).Value
            Sheets("Datenunterschied").Cells(lastRow, 2).Value = x.Offset(0, -7).Value
            Sheets("Datenunterschied").Cells(lastRow, 1).Value = x.Offset(0, -8).Value
        End If
        Next y
    Next x
End Sub

I have provided the data in here:

https://www.herber.de/bbs/user/137783.xlsm

Greetings
Kanime

Body:
The solution to the problem looks like following:

Sub Difference()

Dim lastRow As Long
Dim x, y As Object 'Cells which will loop through, but declared as objects.

    For Each x In Sheets("Datenquelle").Range("I2:I" & Sheets("Datenquelle").Cells(Rows.Count, 9).End(xlUp).Row)
        Dim foundMatch As Boolean 'setup marker that tells us if no match has been found
        foundMatch = False

        For Each y In Sheets("Daten").Range("I2:I" & Sheets("Daten").Cells(Rows.Count, 9).End(xlUp).Row)
            If x.Value = y.Value Then
                foundMatch = True
                Exit For
            End If
        Next y

        If Not foundMatch Then          'only when y has been looped through without finding a match
            lastRow = Sheets("Datenunterschied").Cells(Rows.Count, 9).End(xlUp).Row + 1
            Sheets("Datenunterschied").Cells(lastRow, 9).Value = x.Value ' Copying and setting the data in last available free row
            Debug.Print x.Value
        End If
    Next x
End Sub


问:
Image can't be uploaded using multipart in react
I am trying to upload images in the database using multipart. But I got an error from API ' Files can't be uploaded". I checked API in postman. It is working fine there. So there must be an issue be my code. I wasn't able to find any bugs. What am I doing wrong?

Screenshot of Error - https://prnt.sc/ss6ecp

Code

```<code>import React from 'react';
import axios from 'axios';

const URL="https://api.hello.com/admin/fetch_image_settings";

const POST_URL="https://api.hello.com/admin/save_image_settings";

const header = {
    "content-type": "multipart/form-data"
}

class ImageSetting extends React.Component{
    constructor(props)
    {
        super(props);
        this.state={
            logo_image:null,
            app_icon:null,
            favicon:null,
            admin_id:localStorage.getItem("admin_id"),
            website:null

    }
    }
    handleFile=(event)=>
    {
        let file=event.target.files[0];
        console.log(file);
        this.setState({[event.target.name]:event.target.files[0]});
    }
    handleInput=(event)=>
    {
        this.setState({[event.target.name]:event.target.value})
    }
    handleSubmit=(event)=>
    {
        event.preventDefault();
        const { logo_image, app_icon,favicon, website, admin_id}=this.state;
        let data=new FormData();
        data.append("logo_image",logo_image);
        data.append("app_icon",app_icon);
        data.append("favicon",favicon);

        axios.post(POST_URL,{data},{
            params:{
                admin_id, website
            },
            headers:header
        })
        .then((res)=>
        {
            console.log(res);
        })
        .catch((err)=>
        {
            console.log(err);
        })

    }
    componentDidMount()
    {
        const { admin_id}=this.state;
        axios.get(URL,{
            params:{
                admin_id
            }
        })
        .then((res)=>{
            console.log(res.data)
        })
        .catch((err)=>
        {
            console.log(err);
        })
    }
    render()
    {
        return(
            <React.Fragment>
            <h1>Image setting</h1>
            <form name="image-setting" onSubmit={this.handleSubmit}>
                <input type="text" value={this.state.website} onChange={this.handleInput} name="website" placeholder="Website" />
                <input type="file" onChange={this.handleFile} name="logo_image" />
                <input type="file" onChange={this.handleFile} name="app_icon" />
                <input type="file"  onChange={this.handleFile} name="favicon" />
            </form>
            </React.Fragment>
        )
    }
}
export default ImageSetting;

</code>```

答:
Issue must be with letter case. It should look like Content-Type MDN.

An object can contain properties with same name but different case.

const header = {
    "content-type": "multipart/form-data",
    "Content-Type": "multipart/form-data"
}

console.log(header)```

Body:
I am trying to upload images in the database using multipart. But I got an error from API ' Files can't be uploaded". I checked API in postman. It is working fine there. So there must be an issue be my code. I wasn't able to find any bugs. What am I doing wrong?

Screenshot of Error - https://prnt.sc/ss6ecp

Code

import React from 'react';
import axios from 'axios';

const URL="https://api.hello.com/admin/fetch_image_settings";

const POST_URL="https://api.hello.com/admin/save_image_settings";

const header = {
    "content-type": "multipart/form-data"
}

class ImageSetting extends React.Component{
    constructor(props)
    {
        super(props);
        this.state={
            logo_image:null,
            app_icon:null,
            favicon:null,
            admin_id:localStorage.getItem("admin_id"),
            website:null

    }
    }
    handleFile=(event)=>
    {
        let file=event.target.files[0];
        console.log(file);
        this.setState({[event.target.name]:event.target.files[0]});
    }
    handleInput=(event)=>
    {
        this.setState({[event.target.name]:event.target.value})
    }
    handleSubmit=(event)=>
    {
        event.preventDefault();
        const { logo_image, app_icon,favicon, website, admin_id}=this.state;
        let data=new FormData();
        data.append("logo_image",logo_image);
        data.append("app_icon",app_icon);
        data.append("favicon",favicon);

        axios.post(POST_URL,{data},{
            params:{
                admin_id, website
            },
            headers:header
        })
        .then((res)=>
        {
            console.log(res);
        })
        .catch((err)=>
        {
            console.log(err);
        })

    }
    componentDidMount()
    {
        const { admin_id}=this.state;
        axios.get(URL,{
            params:{
                admin_id
            }
        })
        .then((res)=>{
            console.log(res.data)
        })
        .catch((err)=>
        {
            console.log(err);
        })
    }
    render()
    {
        return(
            <React.Fragment>

Image setting

            <form name="image-setting" onSubmit={this.handleSubmit}>
                <input type="text" value={this.state.website} onChange={this.handleInput} name="website" placeholder="Website" />
                <input type="file" onChange={this.handleFile} name="logo_image" />
                <input type="file" onChange={this.handleFile} name="app_icon" />
                <input type="file"  onChange={this.handleFile} name="favicon" />
            </form>
            </React.Fragment>
        )
    }
}
export default ImageSetting;


问:
Can obtain the condition applied in my if conditional in Python?
I would like to keep in a variable the condition applied, for example:

l = "test.log"
if l.endswith('.csv') or l.endswith('.log') or l.endswith('.xlsx'):
    print(someVariable)
```

<blockquote>
  <p>.log</p>
</blockquote>

<pre class="lang-py prettyprint-override"><code>l = "test.csv"
if l.endswith('.csv') or l.endswith('.log') or l.endswith('.xlsx'):
    print(someVariable)
</code>```

.csv

How can I perform that without a switch case? I just wanna know which condition was performed.

答:
You can do this like by @Adam.Er8. But i think that the thing you want to achieve here is find the file extension. You can use os.path.splitext. Iıt will extract the .log even from path like /path/to/file/test.log.

import os

file_path = "test.log"
file_extension = os.path.splitext(file_path)[1]
if file_extension in ['.csv', '.log', '.xlsx']:
  print(file_extension)
```

Body:
I would like to keep in a variable the condition applied, for example:

l = "test.log"
if l.endswith('.csv') or l.endswith('.log') or l.endswith('.xlsx'):
    print(someVariable)

.log

l = "test.csv"
if l.endswith('.csv') or l.endswith('.log') or l.endswith('.xlsx'):
    print(someVariable)

.csv

How can I perform that without a switch case? I just wanna know which condition was performed.


问:
is it possible to debug javascript code with XCode 4?
I want to run the simulator and when it is running, debug my javascript code that is launching the pages. I did not find any way to debug javascript code using xcode. Is it possible to do so?</p>

答:
Not as is.

However, Dashcode is meant for this sort of thing. Additionally you can use Safari's rather good developer tools. Open Safari's preferences, click the Advanced tab, and at the bottom, check the "Show Develop menu in menu bar". Explore and go nuts.

Alternatively, you could install Cappuccino but I believe it only helps you with Objective-J.

ContentLicense: CC BY-SA 3.0


问:
How to get Laravel Passport oauth_client from request?
I have different frontend websites from which users can sign in through Laravel Passport on my backend website. Each frontend has its own oauth_client entry (id, name and secret).

The backend is currently only returning user information this way:

```<code>Route::middleware('auth:api')->get('/user', function (Request $request) {
    return $request->user()->load('foo');
});
</code>```

How to check from which website or oauth_client the request comes from (in order to load the correct foo) ?

答:
Oauth client ID and redirect URI are available from:

```<code>$request->user()->token()->client;
</code>```

Body:
I have different frontend websites from which users can sign in through Laravel Passport on my backend website. Each frontend has its own oauth_client entry (id, name and secret).

The backend is currently only returning user information this way:

Route::middleware('auth:api')->get('/user', function (Request $request) {
    return $request->user()->load('foo');
});

How to check from which website or oauth_client the request comes from (in order to load the correct foo) ?

Body:
Oauth client ID and redirect URI are available from:

$request->user()->token()->client;


问:
Using custom jackson serializer to replace an Enum value
I'm writing a spring boot project in Kotlin. One of the POJO/data classes I had,

data class Employee(
        //... other properties
        val designation: Designation
)

enum class Designation {
    JUN, MID, SEN
}
```

<p>this <code>Employee</code> object by default serializes as <code>{"designation" : "JUN"}</code>. I wanted to add a custom serializer so that this object will serialize like this, <code>{"designation" : "Junior"}</code>.</p>

<p>The serializer I added, </p>

<pre class="lang-java prettyprint-override"><code>@JsonComponent
class DesignationSerialization {
    class Serializer: JsonObjectSerializer<Designation>() {
        override fun serializeObject(designation: Designation, gen: JsonGenerator, provider: SerializerProvider) {
            gen.writeString(designation.pretty)
        }

        private val Designation.pretty: String
            get() = when(this) {
                Designation.JUN -> "Junior"
                Designation.MID -> "Mid-Level"
                Designation.SEN -> "Senior"
            }
    }
}
</code>```

But while running this, I am getting this error,

```<code>JSON encoding error: Can not write a string, expecting field name (context: Object); nested exception is com.fasterxml.jackson.core.JsonGenerationException: Can not write a string, expecting field name (context: Object)
</code>```

I also tried using gen.writeStringField("designation", designation.pretty) but that serializes the object like this instead

```<code>{
"designation": {"designation": "Mid-Level"}
}
</code>```

答: You should add a property to your enum class and mark it with @JsonValue https://www.baeldung.com/jackson-serialize-enums

Body:
I'm writing a spring boot project in Kotlin. One of the POJO/data classes I had,

data class Employee(
        //... other properties
        val designation: Designation
)

enum class Designation {
    JUN, MID, SEN
}

this Employee object by default serializes as {"designation" : "JUN"}. I wanted to add a custom serializer so that this object will serialize like this, {"designation" : "Junior"}.

The serializer I added,

@JsonComponent
class DesignationSerialization {
    class Serializer: JsonObjectSerializer<Designation>() {
        override fun serializeObject(designation: Designation, gen: JsonGenerator, provider: SerializerProvider) {
            gen.writeString(designation.pretty)
        }

        private val Designation.pretty: String
            get() = when(this) {
                Designation.JUN -> "Junior"
                Designation.MID -> "Mid-Level"
                Designation.SEN -> "Senior"
            }
    }
}

But while running this, I am getting this error,

JSON encoding error: Can not write a string, expecting field name (context: Object); nested exception is com.fasterxml.jackson.core.JsonGenerationException: Can not write a string, expecting field name (context: Object)

I also tried using gen.writeStringField("designation", designation.pretty) but that serializes the object like this instead

{
"designation": {"designation": "Mid-Level"}
}


问:
How to cancel an calendar event using ics files?
One of our requirements is to create iCalendar files (.ics) and send them each in emails as an attachment. We are using DDay.Ical.dll to create ics files as under:

// Create a new iCalendar
iCalendar iCal = new iCalendar();

// Create the event, and add it to the iCalendar
Event evt = iCal.Create<Event>();

// Set information about the event
evt.Start = new iCalDateTime(SomeStartTime);
evt.End = new iCalDateTime(SomeEndTime);
evt.Location = "At so and so place";
evt.Description = "Some Description";
evt.Summary = "About Some Subject";
iCal.Method = "PUBLISH";

// Serialize (save) the iCalendar
iCalendarSerializer serializer = new iCalendarSerializer();
serializer.Serialize(iCal, @"iCalendar.ics");
```

Complete process is:

User1 create an iCal file for specific date and time and send it to User2.

User2 will open the ics file and accept the invitation. An appointment item will be created in User2's LOCAL outlook.

Now, Suppose, because of any reason if appointment is cancelled, then User1 HAS to create an ics file and send it to User2, so that User2 can cancel his event from the local outlook.

How to create such ics file?

答:
I had the issue when i sent mail containing ics file for delete event but in outlook it show me not supported format
then i figured out somewhere on net and i found that i just need to change
METHOD: CANCEL to METHOD: REQUEST

when i import this in outlook

Body:
One of our requirements is to create iCalendar files (.ics) and send them each in emails as an attachment. We are using DDay.Ical.dll to create ics files as under:

// Create a new iCalendar
iCalendar iCal = new iCalendar();

// Create the event, and add it to the iCalendar
Event evt = iCal.Create<Event>();

// Set information about the event
evt.Start = new iCalDateTime(SomeStartTime);
evt.End = new iCalDateTime(SomeEndTime);
evt.Location = "At so and so place";
evt.Description = "Some Description";
evt.Summary = "About Some Subject";
iCal.Method = "PUBLISH";

// Serialize (save) the iCalendar
iCalendarSerializer serializer = new iCalendarSerializer();
serializer.Serialize(iCal, @"iCalendar.ics");

Complete process is:

User1 create an iCal file for specific date and time and send it to User2.

User2 will open the ics file and accept the invitation. An appointment item will be created in User2's LOCAL outlook.

Now, Suppose, because of any reason if appointment is cancelled, then User1 HAS to create an ics file and send it to User2, so that User2 can cancel his event from the local outlook.

How to create such ics file?


问:
TS2339: Property 'style' does not exist on type 'Element'?
Here's the code:

```<code>ngOnInit() {
const navSlide = () => {
  const burger = document.querySelector('.burger');
  const nav = document.querySelector('.nav-links');
  const navLinks = document.querySelectorAll('.nav-links li');
  burger.addEventListener('click', () => {
    nav.classList.toggle('nav-active');
  });
  navLinks.forEach((link, index) => {
  link.style.animation = `navLinkFade 0.5s ease forwards ${index / 7 + 0.3}s`;
   });
};
navSlide();
</code>```

}

Error I get when compiled:

```<code>Property 'style' does not exist on type 'Element'.ts(2339)
</code>```

How can I fix it?

答:
querySelectorAll returns a NodeList known to contain Elements, but not specifically HTMLElements. In your case, you know that these are HTMLElements (specifically HTMLLIElements), so you can use a type assertion saying that:

```<code>navLinks.forEach((link, index) => {
    (link as HTMLElement).style.animation = `navLinkFade 0.5s ease forwards ${index / 7 + 0.3}s`;
});
</code>```

But see Mike S.'s comment - I don't do Angular, but it sounds like there's a more Angular-specific solution here.

Body:
Here's the code:

ngOnInit() {
const navSlide = () => {
  const burger = document.querySelector('.burger');
  const nav = document.querySelector('.nav-links');
  const navLinks = document.querySelectorAll('.nav-links li');
  burger.addEventListener('click', () => {
    nav.classList.toggle('nav-active');
  });
  navLinks.forEach((link, index) => {
  link.style.animation = `navLinkFade 0.5s ease forwards ${index / 7 + 0.3}s`;
   });
};
navSlide();

}

Error I get when compiled:

Property 'style' does not exist on type 'Element'.ts(2339)

How can I fix it?

Body:
querySelectorAll returns a NodeList known to contain Elements, but not specifically HTMLElements. In your case, you know that these are HTMLElements (specifically HTMLLIElements), so you can use a type assertion saying that:

navLinks.forEach((link, index) => {
    (link as HTMLElement).style.animation = `navLinkFade 0.5s ease forwards ${index / 7 + 0.3}s`;
});

But see Mike S.'s comment - I don't do Angular, but it sounds like there's a more Angular-specific solution here.


问:
C++ Question about two class constructors
My teacher gave me a sample code, but I'm a bit confused.

```<code>class CBook
{
...
    pubic:
        CBook();
        CBook(string Title, string Auther, int Year); // I know this is the constructor
        ~CBook(); // and this is the destructor
};
</code>```

I wish to know the use of CBook();, is this line of code really necessary?

Thanks

答:
Actually compiler will call this constructor in case you will do like that:

```<code>CBook obj;
</code>```

in another words, you will not pass any arguments to it.

So, if you delete it and try for example:

```<code>CBook obj;
</code>```

compiler will give you an error like "no default constructor"

Sometimes we need object without any of its members filled to fill the later.

Body:
My teacher gave me a sample code, but I'm a bit confused.

class CBook
{
...
    pubic:
        CBook();
        CBook(string Title, string Auther, int Year); // I know this is the constructor
        ~CBook(); // and this is the destructor
};

I wish to know the use of CBook();, is this line of code really necessary?

Thanks

Body:
Actually compiler will call this constructor in case you will do like that:

CBook obj;

in another words, you will not pass any arguments to it.

So, if you delete it and try for example:

CBook obj;

compiler will give you an error like "no default constructor"

Sometimes we need object without any of its members filled to fill the later.


问:
Multiple Column Duplicate in SQL
I have a table with fields (id , gid, uid)
For some rows (gid, uid) are same. There is duplicate.

Example 1:(repeated)

```<code>id      gid     uid

5802    1032    1247

5806    1032    1247

5807    1032    1247

5808    1032    1247
</code>```

Example 2: (occurs once)

```<code>id      gid     uid

5103    1132    1290
</code>```

In my case I want to pass uid and gid and check if there are duplicates
- Return True if (gid,uid) doesnot occur in the table
- Otherwise it return false.( for Example 1 and Example 2 )

I tried this query to return true or false.

```<code>SELECT  CASE WHEN EXISTS  (SELECT A.*
FROM table1 A
INNER JOIN (SELECT gid, uid
            FROM table1
            GROUP BY gid, uid
            HAVING COUNT(*) = 0)
ON A.gid = '1011' AND A.uid = '1086') THEN 'TRUE' ELSE 'FALSE' END from dual;
</code>```

But it always returns True ; Please help in solving the same

答:
You can use aggregation as follows:</p>

```<code>SELECT CASE WHEN COUNT(1) = 1 THEN 'TRUE' else 'FALSE' END FROM YOUR_tABLE
WHERE gid = '1011' AND uid = '1086'
</code>```

Title: Multiple Column Duplicate in SQL

Body:
I have a table with fields (id , gid, uid)
For some rows (gid, uid) are same. There is duplicate.

Example 1:(repeated)

id      gid     uid

5802    1032    1247

5806    1032    1247

5807    1032    1247

5808    1032    1247

Example 2: (occurs once)

id      gid     uid

5103    1132    1290

In my case I want to pass uid and gid and check if there are duplicates
- Return True if (gid,uid) doesnot occur in the table
- Otherwise it return false.( for Example 1 and Example 2 )

I tried this query to return true or false.

SELECT  CASE WHEN EXISTS  (SELECT A.*
FROM table1 A
INNER JOIN (SELECT gid, uid
            FROM table1
            GROUP BY gid, uid
            HAVING COUNT(*) = 0)
ON A.gid = '1011' AND A.uid = '1086') THEN 'TRUE' ELSE 'FALSE' END from dual;

But it always returns True ; Please help in solving the same

Body:
You can use aggregation as follows:

SELECT CASE WHEN COUNT(1) = 1 THEN 'TRUE' else 'FALSE' END FROM YOUR_tABLE
WHERE gid = '1011' AND uid = '1086'


问:
Match keys of sub-documents using $exists and $regex - MongoDb
I want to get documents having a particular key in its sub-document using regex. I had a look at the following post: " Mongodb - regex match of keys for subdocuments ", but since it was answered more than 8 years ago, is there any update on the question? Is it possible to do this now?

my collection is similar to one below :

```<code>{
    item : a,
    payload:{
        url_google.com:1,
        url_apple.com:1
    }
},
{
    item : b,
    payload:{
        url_t.co:1,
        t.co:1
    }
},
{
    item : c,
    payload:{
        google.com:2,
        facebook.com:2
    }
}
</code>```

and I want to get all those documents having at least one of the keys of payload that contain 'url' in them. In the above case, the query would return

```<code>{
    item : a,
    payload:{
        url_google.com:1,
        url_apple.com:1
    }
},
{
    item : b,
    payload:{
        url_t.co:1,
        t.co:1
    }
}
</code>```

答:
It is possible, yes.

You can use $objectToArray, like

```<code>db.collection.aggregate([
    {$addFields:{
          payload_array: {$objectToArray: "$payload"}
    }},
    {$match:{
          "payload_array.k": {$regex: "^url_"}
    }},
    {$project:{ payload_array:0 }}
])
</code>```

Playground

Note that because the selection occurs after modifying the input document, this query will not be able to use an index, so every time it runs will be a collection scan.

Body:
I want to get documents having a particular key in its sub-document using regex. I had a look at the following post: " Mongodb - regex match of keys for subdocuments ", but since it was answered more than 8 years ago, is there any update on the question? Is it possible to do this now?

my collection is similar to one below :

{
    item : a,
    payload:{
        url_google.com:1,
        url_apple.com:1
    }
},
{
    item : b,
    payload:{
        url_t.co:1,
        t.co:1
    }
},
{
    item : c,
    payload:{
        google.com:2,
        facebook.com:2
    }
}

and I want to get all those documents having at least one of the keys of payload that contain 'url' in them. In the above case, the query would return

{
    item : a,
    payload:{
        url_google.com:1,
        url_apple.com:1
    }
},
{
    item : b,
    payload:{
        url_t.co:1,
        t.co:1
    }
}

Body:
It is possible, yes.

You can use $objectToArray, like

db.collection.aggregate([
    {$addFields:{
          payload_array: {$objectToArray: "$payload"}
    }},
    {$match:{
          "payload_array.k": {$regex: "^url_"}
    }},
    {$project:{ payload_array:0 }}
])

Playground

Note that because the selection occurs after modifying the input document, this query will not be able to use an index, so every time it runs will be a collection scan.


问:
Activeform in VB.NET
I am an old VB6 user and relatively new to VB.NET.
I have a MDI Container form and several ChildForms. I need to find the active child form to pass a variable.
In VB6 i could call the ActiveForm function.
Any help would be grateful.

Thanks in advance.
Kappa.

答:
Thanks Albert,
I ended up using the below code to solve my problem:</p>

```<code>If (activeChild IsNot Nothing) Then
        Try
            name = activeChild.Name

            Select Case name
                Case "frmEmployee"
                    frmEmployee.CommandPass(tsb.Text)
                Case "frmClient"
                    frmClient.CommandPass(tsb.Text)
                Case "frmAllocations"
                    'pass tsb.text to form's CommandPass Sub
                Case "frmBilling"
                    'pass tsb.text to form's CommandPass Sub
            End Select

        Catch ex As Exception
            MsgBox(ex)

        End Try
    End If
</code>```

Title: Activeform in VB.NET

Body:
Thanks Albert,
I ended up using the below code to solve my problem:

If (activeChild IsNot Nothing) Then
        Try
            name = activeChild.Name

            Select Case name
                Case "frmEmployee"
                    frmEmployee.CommandPass(tsb.Text)
                Case "frmClient"
                    frmClient.CommandPass(tsb.Text)
                Case "frmAllocations"
                    'pass tsb.text to form's CommandPass Sub
                Case "frmBilling"
                    'pass tsb.text to form's CommandPass Sub
            End Select

        Catch ex As Exception
            MsgBox(ex)

        End Try
    End If


问:
Is there a way to export Allure Report to a single html file? To share with the team
Right now, I am generating the Allure Report through the terminal by running the command: allure serve {folder that contains the json files}, but with this way the HTML report will only be available to my local because

The json files that generated the report are in my computer

I ran the command through the terminal (if i kill the terminal, the report is gone)

I have tried: Saving the Allure Report as Webpage, Complete, but the results did not reflect to the page, all i was seeing was blank fields.

So, what im trying to to do is after I execute the command to generate the report, I want to have an html file of the report that i can store, save to my computer or send through email, so i do not have to execute the command to see the previous reports. (as much as possible into 1 html file)

答:
You can use this docker container to render and export an emailable report
https://github.com/fescobar/allure-docker-service#customize-emailable-report</p>


问:
How to add a condition to a variable - GAMS
In the model I'm trying to build, I have a variable defined as:

```<code>Variables
    x(i,j)  number of motors produced in month i to be delivered in month j ;
</code>```

In that variable, j must always be equal or greater than i for it to make sense (you can't produce something in this month to be delivered in the previous month).
However, I have no clue as to how I can properly model this. I've searched and couldn't find an easy solution to this.

Any ideas?

答:
So, I add this, right after declaring the variable:

```<code>x.fx(i,j)$(ord(i)>ord(j))=0;
</code>```

It is fixing the values of the variables you are not using to zero. In your model:

And the results are:

I believe that should do it :)

Body:
In the model I'm trying to build, I have a variable defined as:

Variables
    x(i,j)  number of motors produced in month i to be delivered in month j ;

In that variable, j must always be equal or greater than i for it to make sense (you can't produce something in this month to be delivered in the previous month).
However, I have no clue as to how I can properly model this. I've searched and couldn't find an easy solution to this.

Any ideas?

Body:
So, I add this, right after declaring the variable:

x.fx(i,j)$(ord(i)>ord(j))=0;

It is fixing the values of the variables you are not using to zero. In your model:

And the results are:

I believe that should do it :)


问:
Operator > not defined for T
trying to check if a given number is less than the other or not, so wrote the below:

package main

import "fmt"

type T interface {}

func Less(i, j T) bool {
    return i > j
}
```

<p>But got the below error:</p>

<pre class="lang-sh prettyprint-override"><code># command-line-arguments
.\hashmap.go:23:11: invalid operation: i > j (operator > not defined on interface)
</code>```

How can I add such mathematical operations to general type element (number or string)?

答:
interface is not a type, nor is it a generic value representing intersection of all types like string and int. When you ask for whether a is greater than or equal to b, you'll have to also specify which exact types those two belong (implicitly, they should have the same type), to answer that question. Similarly, Go also needs that information. Doing that for interface can be come a little cumbersome. However, there are a couple of ways:

Define the Less function individually on both types:

```<code>func LessString(n1, n2 string) bool {
    return strings.Compare(n1, n2) == -1
}

// no need to define a less function, but whatever
func LessInt(n1, n2 int) bool {
    return n1 < n2
}

</code>```

Or, using type aliases:

```<code>type Name string
type Age int

func (name Name) Less(compare string) bool {
    return strings.Compare(string(name), compare) == -1
}

func (age Age) LessInt(compare int) bool {
    return int(age) < compare
}
</code>```

A second way to implement Less functionality on interface would be to do type assertions:

```<code>// This isn't all that useful, but whatever
type T interface{}

func main() {
    fmt.Println(Less(10, 20))
    fmt.Println(Less("10", "20"))
}

func Less(t1, t2 T) bool {
    switch v1 := t1.(type) {
    case string:
        return strings.Compare(v1, t2.(string)) < 0   // import "strings"
        // return v1 < t2.(string)
    case int:
        return v1 < t2.(int)
    }

    return false
}
</code>```

There is no way in Go to define operators over types. It prefers adding functions to achieve that. Many standard library modules follow similar patterns.

Title: Operator > not defined for T

Body:
trying to check if a given number is less than the other or not, so wrote the below:

package main

import "fmt"

type T interface {}

func Less(i, j T) bool {
    return i > j
}

But got the below error:

# command-line-arguments
.\hashmap.go:23:11: invalid operation: i > j (operator > not defined on interface)

How can I add such mathematical operations to general type element (number or string)?

Body:
interface is not a type, nor is it a generic value representing intersection of all types like string and int. When you ask for whether a is greater than or equal to b, you'll have to also specify which exact types those two belong (implicitly, they should have the same type), to answer that question. Similarly, Go also needs that information. Doing that for interface can be come a little cumbersome. However, there are a couple of ways:

Define the Less function individually on both types:

func LessString(n1, n2 string) bool {
    return strings.Compare(n1, n2) == -1
}

// no need to define a less function, but whatever
func LessInt(n1, n2 int) bool {
    return n1 < n2
}

Or, using type aliases:

type Name string
type Age int

func (name Name) Less(compare string) bool {
    return strings.Compare(string(name), compare) == -1
}

func (age Age) LessInt(compare int) bool {
    return int(age) < compare
}

A second way to implement Less functionality on interface would be to do type assertions:

// This isn't all that useful, but whatever
type T interface{}

func main() {
    fmt.Println(Less(10, 20))
    fmt.Println(Less("10", "20"))
}

func Less(t1, t2 T) bool {
    switch v1 := t1.(type) {
    case string:
        return strings.Compare(v1, t2.(string)) < 0   // import "strings"
        // return v1 < t2.(string)
    case int:
        return v1 < t2.(int)
    }

    return false
}

There is no way in Go to define operators over types. It prefers adding functions to achieve that. Many standard library modules follow similar patterns.


问:
Problem with XslCompiledTransform and xslt in VB.NET
I am getting now where with this. I have an XML document that must be transformed using an xslt sheet. My code is as follows:

```<code>        Dim xStream As New IO.MemoryStream

        ' Create the XslCompiledTransform and load the stylesheet.
        Dim xslt As New XslCompiledTransform()
        xslt.Load(strLKxsl)

        ' Create the XslCompiledTransform and load the stylesheet.
        Dim xslt As New XslCompiledTransform()
        xslt.Load(strXSLfolder & "xslt_lookup.xslt")

        ' Create the XsltArgumentList.
        Dim xslArg As New XsltArgumentList()

        Using w As XmlWriter = XmlWriter.Create(xStream)
            ' Transform the file.
            xslt.Transform(xmldLookup, Nothing, w)
        End Using
</code>```

I get the following error at the xslt.Transform(xmldLookup, Nothing, w) line:

Token StartElement in state EndRootElement would result in an invalid XML document. Make sure that the ConformanceLevel setting is set to ConformanceLevel.Fragment or ConformanceLevel.Auto if you want to write an XML fragment.

This is the contents of the XMl file:

```<code><?xml version="1.0" encoding="utf-8"?>
<?xml-stylesheet type="text/xsl" href="includes/xslt_lookup.xslt"?>
<lookup xmlns="logis-online:lk"
title="<Document Title>"
nexturl="<URL>">

  <search visible="false">
    <field id="SUPPLIER_NO" hidden="true" size="10"
    value="<Value>" />
    <field id="WEB_STORE_NO" hidden="true" size="10"
    value="<Value>" />
    <field id="REST" hidden="true" size="40" value="" />
    <field id="LOOKUP_ACTION" hidden="true" size="1" value="<Value>" />
    <field id="WEB_ACTION" hidden="true" size="2" value="<Value>" />
  </search>
  <results>
    <header>
      <section>
        <item id="SUPPLIER_NO" title="Supplier No" value="<Value>"
        HelpID="10" />
        <item id="SUPPLIER_NAME_SHORT" title="Supplier Name"
        value="<Value>" HelpID="10" />
        <item id="LIABLE_STORE_NO" title="Liable Store No"
        value="<Value>" HelpID="98" />
      </section>
    </header>
    <list target="<lookup aspx page>" />
  </results>
</lookup>
</code>```

答:
The problem is probably caused by your XSLT code creating some output that is not a well-formed XML document but only a fragment, probably having several top level elements. That is possible with XSLT and if you simply write to a file or stream you shouldn't have any problems. Your code, for reasons you have not explained, constructs an XmlWriter over a MemoryStream, and by default any XmlWriter created with XmlWriter.Create(stream) checks that any output is a well-formed XML document and throws an exception if not.
So to avoid the problem you either don't create an XmlWriter at all and simply do

```<code>xslt.Transform(xmldLookup, Nothing, xStream)
</code>```

or you create an XmlWriter with the OutputSettings of the XslCompiledTransform instance e.g.

```<code>Using xw As XmlWriter = XmlWriter.Create(xStream, xslt.OutputSettings)
</code>```

Body:
I am getting now where with this. I have an XML document that must be transformed using an xslt sheet. My code is as follows:

        Dim xStream As New IO.MemoryStream

        ' Create the XslCompiledTransform and load the stylesheet.
        Dim xslt As New XslCompiledTransform()
        xslt.Load(strLKxsl)

        ' Create the XslCompiledTransform and load the stylesheet.
        Dim xslt As New XslCompiledTransform()
        xslt.Load(strXSLfolder & "xslt_lookup.xslt")

        ' Create the XsltArgumentList.
        Dim xslArg As New XsltArgumentList()

        Using w As XmlWriter = XmlWriter.Create(xStream)
            ' Transform the file.
            xslt.Transform(xmldLookup, Nothing, w)
        End Using

I get the following error at the xslt.Transform(xmldLookup, Nothing, w) line:

Token StartElement in state EndRootElement would result in an invalid XML document. Make sure that the ConformanceLevel setting is set to ConformanceLevel.Fragment or ConformanceLevel.Auto if you want to write an XML fragment.

This is the contents of the XMl file:

<?xml version="1.0" encoding="utf-8"?>
<?xml-stylesheet type="text/xsl" href="includes/xslt_lookup.xslt"?>
<lookup xmlns="logis-online:lk"
title="<Document Title>"
nexturl="<URL>">

  <search visible="false">
    <field id="SUPPLIER_NO" hidden="true" size="10"
    value="<Value>" />
    <field id="WEB_STORE_NO" hidden="true" size="10"
    value="<Value>" />
    <field id="REST" hidden="true" size="40" value="" />
    <field id="LOOKUP_ACTION" hidden="true" size="1" value="<Value>" />
    <field id="WEB_ACTION" hidden="true" size="2" value="<Value>" />
  </search>
  <results>

        <item id="SUPPLIER_NO" title="Supplier No" value="<Value>"
        HelpID="10" />
        <item id="SUPPLIER_NAME_SHORT" title="Supplier Name"
        value="<Value>" HelpID="10" />
        <item id="LIABLE_STORE_NO" title="Liable Store No"
        value="<Value>" HelpID="98" />

    <list target="<lookup aspx page>" />
  </results>
</lookup>

Body:
The problem is probably caused by your XSLT code creating some output that is not a well-formed XML document but only a fragment, probably having several top level elements. That is possible with XSLT and if you simply write to a file or stream you shouldn't have any problems. Your code, for reasons you have not explained, constructs an XmlWriter over a MemoryStream, and by default any XmlWriter created with XmlWriter.Create(stream) checks that any output is a well-formed XML document and throws an exception if not.
So to avoid the problem you either don't create an XmlWriter at all and simply do

xslt.Transform(xmldLookup, Nothing, xStream)

or you create an XmlWriter with the OutputSettings of the XslCompiledTransform instance e.g.

Using xw As XmlWriter = XmlWriter.Create(xStream, xslt.OutputSettings)


问:
How to delete label on Kubernetes namespace
I labeled a Kubernetes namespace like so:

```<code>kubectl label namespace kube-system name=kube-system
</code>```

How do I get rid of this label?

答:
Use below command to remove the label</p>

```<code> kubectl label namespace kube-system name-
</code>```

Body:
I labeled a Kubernetes namespace like so:

kubectl label namespace kube-system name=kube-system

How do I get rid of this label?

Body:
Use below command to remove the label

 kubectl label namespace kube-system name-


问:
Java Records StackOverflow RuntimeException
I am learning Java Records, preview feature and I am getting a StackOverflow exception when I run the below piece of code .

```<code>    import java.util.ArrayList;
    import java.util.List;
    import java.util.stream.Collectors;
    public class Example {
        public record Course(String name, Student topper) { }
        public record Student(String name, List<Course> enrolled) {}

        public static void main(String[] args) {
            Student john = new Student("John", new ArrayList<>());
            john.enrolled().add(new Course("Enrolled for Math", john));
            john.enrolled().add(new Course("Enrolled for History", john));
            System.out.println(john);
        }
    }

Below is the exception trace :

 java --enable-preview Example
 Exception in thread "main" java.lang.StackOverflowError
    at Example$Course.toString(Example.java:6)
    at java.base/java.lang.String.valueOf(String.java:3388)
    at java.base/java.lang.StringBuilder.append(StringBuilder.java:167)
    at java.base/java.util.AbstractCollection.toString(AbstractCollection.java:457)
</code>```

From the exception I realize that it has to do with toString() and when I have override toString() in the records as below code I don't see the Exception .

```<code>// code with implementation of toString()
public class Example {

    public record Course(String name, Student topper) {
    public String toString()
        {
            return name;
        }
   }
   public record Student(String name, List<Course> enrolled) {
   public String toString()
        {
             return this.name+" : "+enrolled.stream().map(s->s.toString()).collect(Collectors.joining(","));
        }
   }
   public static void main(String... args) {
       Student john = new Student("John", new ArrayList<>());
       john.enrolled().add(new Course("Enrolled for Math", john));
       john.enrolled().add(new Course("Enrolled for History", john));
       System.out.println(john);
   }
}
</code>```

This code prints John : Enrolled for Math,Enrolled for History . Can someone please explain why if I don't override  toString() I get StackOverflow? Also I see StackOverflow when I print john.hashCode()

答:
It's because you're trying to print a list of courses that the student is enrolled in, and each of those courses has that same student listed as enrolled. So you have a circular reference. Course -> Student -> Course -> Student etc.

When you overrode Course toString(), you only printed the name so this was no longer an issue.

Body:
I am learning Java Records, preview feature and I am getting a StackOverflow exception when I run the below piece of code .

    import java.util.ArrayList;
    import java.util.List;
    import java.util.stream.Collectors;
    public class Example {
        public record Course(String name, Student topper) { }
        public record Student(String name, List<Course> enrolled) {}

        public static void main(String[] args) {
            Student john = new Student("John", new ArrayList<>());
            john.enrolled().add(new Course("Enrolled for Math", john));
            john.enrolled().add(new Course("Enrolled for History", john));
            System.out.println(john);
        }
    }

Below is the exception trace :

 java --enable-preview Example
 Exception in thread "main" java.lang.StackOverflowError
    at Example$Course.toString(Example.java:6)
    at java.base/java.lang.String.valueOf(String.java:3388)
    at java.base/java.lang.StringBuilder.append(StringBuilder.java:167)
    at java.base/java.util.AbstractCollection.toString(AbstractCollection.java:457)

From the exception I realize that it has to do with toString() and when I have override toString() in the records as below code I don't see the Exception .

// code with implementation of toString()
public class Example {

    public record Course(String name, Student topper) {
    public String toString()
        {
            return name;
        }
   }
   public record Student(String name, List<Course> enrolled) {
   public String toString()
        {
             return this.name+" : "+enrolled.stream().map(s->s.toString()).collect(Collectors.joining(","));
        }
   }
   public static void main(String... args) {
       Student john = new Student("John", new ArrayList<>());
       john.enrolled().add(new Course("Enrolled for Math", john));
       john.enrolled().add(new Course("Enrolled for History", john));
       System.out.println(john);
   }
}

This code prints John : Enrolled for Math,Enrolled for History . Can someone please explain why if I don't override  toString() I get StackOverflow? Also I see StackOverflow when I print john.hashCode()


问:
What is the corresponding androix library for com.android.support:support-compat?
What is the corresponding androidx library for com.android.support:support-compat to implement push notifications?

They say here that it is part of androidx but as usual the documentation fails to provide the right directions.

答:
implementation 'androidx.appcompat:appcompat:1.0.0'

Refactoring using Android Studio


问:
Passing connection between two files - azure functions
I have a server.js file inside a connections folder that I'm trying to use and have all my azure functions reference so that it doesn't instantiate a connection after every API call. I'm having issues exporting the connection and importing it correctly in my azure functions. Is this not possible. If it is, what am I doing wrong? Appreciate the help!

server.js

```<code>const redis = require('redis');
var mongoose = require('mongoose');
const redis = require('redis');

const client = redis.createClient(6380, process.env.REDISCACHEHOSTNAME + '.redis.cache.windows.net', {
  auth_pass: process.env.REDISCACHEKEY,
  tls: { servername: process.env.REDISCACHEHOSTNAME + '.redis.cache.windows.net' }
});

module.exports = { client };
</code>```

top of azure function file importing connection

```<code>const redis = require('redis');

var redisConnection = require("../connections/server")

console.log("THE CLIENT IS " + redisConnection.client.connected);

</code>```

Error: client is not defined

答:
Yes, it is possible. I have tested this on Azure portal. I created two http trigger functions named HttpTrigger1 and HttpTrigger2.

HttpTrigger1 function

HttpTrigger2 function

It seems that your code is correct, please check your function project directory structure, mine is

You can test it locally, here are my code for your reference:

The server.js file

```<code>const redis = require('redis');

const client = redis.createClient(6380, 'test.redis.cache.windows.net',
        {auth_pass: 'XXXX=', tls: {servername: 'test.redis.cache.windows.net'}});

module.exports = { client };
</code>```

The function code

```<code>const redis = require('redis');

var redisConnection = require("../connections/server")

module.exports = async function (context, req) {
    context.log('JavaScript HTTP trigger function processed a request.');
    context.log("THE CLIENT IS " + redisConnection.client.connected);
    context.res = {
        // status: 200, /* Defaults to 200 */
        body: "THE CLIENT IS " + redisConnection.client.connected
    };

};
</code>```

Body:
I have a server.js file inside a connections folder that I'm trying to use and have all my azure functions reference so that it doesn't instantiate a connection after every API call. I'm having issues exporting the connection and importing it correctly in my azure functions. Is this not possible. If it is, what am I doing wrong? Appreciate the help!

server.js

const redis = require('redis');
var mongoose = require('mongoose');
const redis = require('redis');

const client = redis.createClient(6380, process.env.REDISCACHEHOSTNAME + '.redis.cache.windows.net', {
  auth_pass: process.env.REDISCACHEKEY,
  tls: { servername: process.env.REDISCACHEHOSTNAME + '.redis.cache.windows.net' }
});

module.exports = { client };

top of azure function file importing connection

const redis = require('redis');

var redisConnection = require("../connections/server")

console.log("THE CLIENT IS " + redisConnection.client.connected);

Error: client is not defined

Body:
Yes, it is possible. I have tested this on Azure portal. I created two http trigger functions named HttpTrigger1 and HttpTrigger2.

HttpTrigger1 function

HttpTrigger2 function

It seems that your code is correct, please check your function project directory structure, mine is

You can test it locally, here are my code for your reference:

The server.js file

const redis = require('redis');

const client = redis.createClient(6380, 'test.redis.cache.windows.net',
        {auth_pass: 'XXXX=', tls: {servername: 'test.redis.cache.windows.net'}});

module.exports = { client };

The function code

const redis = require('redis');

var redisConnection = require("../connections/server")

module.exports = async function (context, req) {
    context.log('JavaScript HTTP trigger function processed a request.');
    context.log("THE CLIENT IS " + redisConnection.client.connected);
    context.res = {
        // status: 200, /* Defaults to 200 */
        body: "THE CLIENT IS " + redisConnection.client.connected
    };

};


问:
Mongodb findoneandupdate with aggregation pipeline
I have a data in MongoDB like this

```<code>    {"_id":{"$oid":"5ec4ed0b94996124187b95ce"},
           "cid":"245345323",
     "dtl":[
          {"_id":{"$oid":"5ed5ab655df7930ec424be1e"},
              "sid":"test",
              "amt":{"$numberInt":"48"},
              "Name":"test"},
          {"_id":{"$oid":"5ed5ac9f79a75423d4bc0270"},
             "sid":"s",
             "amt":{"$numberInt":"14"},
             "Name":"sfds"},
          {"_id":{"$oid":"5ed5ace7d204ab144863ed7a"},
             "sid":"wesad",
             "amt":{"$numberInt":"6"},
             "Name":"2sdad"
          },
        "updated":{"$date":{"$numberLong":"1589964043787"}},
        "__v":{"$numberInt":"6"},
       "TotalAmt":{"$numberInt":"68"}}
</code>```

I need to update the TotalAmt field only if amt field in the array has value greater than 10. I have used the below 2 options

```<code>PM.findOneAndUpdate(
      {
        _id: MongoId,
      },
      [
        {
          $set: {
            //TotalAmt: { $sum: '$dtl.amt' },
            /*TotalAmt: {
              $cond: {
                if: { $gte: ['$dtl.amt', 10] },
                then: { $sum: '$dtl.amt' },
                else: 0,
              },
            },*/
          },
        },
      ],
      { new: true }
    )
</code>```

It works fine without amt > 10 condition (first option commented).  But not working if I add the condition. Any help would be appreciated. Thanks

答:
You need to use $filter operator:

```<code>PM.findOneAndUpdate(
  {
    _id: MongoId,
  },
  [
    {
      $set: {
        TotalAmt: {
          $sum: {
            $filter: {
              input: '$dtl.amt',
              cond: { $gte: ['$$this', 10] }
            }
          }
        }
      }
    }
  ]
  { new: true }
)
</code>```

---Output---

```<code>{
    "_id" : ObjectId("5ec4ed0b94996124187b95ce"),
    "cid" : "245345323",
    "dtl" : [
        {
            "_id" : ObjectId("5ed5ab655df7930ec424be1e"),
            "sid" : "test",
            "amt" : 48,
            "Name" : "test"
        },
        {
            "_id" : ObjectId("5ed5ac9f79a75423d4bc0270"),
            "sid" : "s",
            "amt" : 14,
            "Name" : "sfds"
        },
        {
            "_id" : ObjectId("5ed5ace7d204ab144863ed7a"),
            "sid" : "wesad",
            "amt" : 6,
            "Name" : "2sdad"
        }
    ],
    "updated" : ISODate("2020-05-20T08:40:43.787Z"),
    "__v" : 6,
    "TotalAmt" : 62
}
</code>```

Edit: If you want filter by other field, we need to add extra $map operator.

```<code>PM.findOneAndUpdate(
  {
    _id: MongoId,
  },
  [
    {
      $set: {
        TotalAmt: {
          $sum: {
            $map:{
                input: {
                  $filter: {
                    input: '$dtl',
                    cond: { $eq: ['$$this.Name', 'test'] }
                  }
                },
                in:"$$this.amt"
            }
          }
        }
      }
    }
  ],
  { new: true }
)
</code>```

Body:
I have a data in MongoDB like this

    {"_id":{"$oid":"5ec4ed0b94996124187b95ce"},
           "cid":"245345323",
     "dtl":[
          {"_id":{"$oid":"5ed5ab655df7930ec424be1e"},
              "sid":"test",
              "amt":{"$numberInt":"48"},
              "Name":"test"},
          {"_id":{"$oid":"5ed5ac9f79a75423d4bc0270"},
             "sid":"s",
             "amt":{"$numberInt":"14"},
             "Name":"sfds"},
          {"_id":{"$oid":"5ed5ace7d204ab144863ed7a"},
             "sid":"wesad",
             "amt":{"$numberInt":"6"},
             "Name":"2sdad"
          },
        "updated":{"$date":{"$numberLong":"1589964043787"}},
        "__v":{"$numberInt":"6"},
       "TotalAmt":{"$numberInt":"68"}}

I need to update the TotalAmt field only if amt field in the array has value greater than 10. I have used the below 2 options

PM.findOneAndUpdate(
      {
        _id: MongoId,
      },
      [
        {
          $set: {
            //TotalAmt: { $sum: '$dtl.amt' },
            /*TotalAmt: {
              $cond: {
                if: { $gte: ['$dtl.amt', 10] },
                then: { $sum: '$dtl.amt' },
                else: 0,
              },
            },*/
          },
        },
      ],
      { new: true }
    )

It works fine without amt > 10 condition (first option commented).  But not working if I add the condition. Any help would be appreciated. Thanks

Body:
You need to use $filter operator:

PM.findOneAndUpdate(
  {
    _id: MongoId,
  },
  [
    {
      $set: {
        TotalAmt: {
          $sum: {
            $filter: {
              input: '$dtl.amt',
              cond: { $gte: ['$$this', 10] }
            }
          }
        }
      }
    }
  ]
  { new: true }
)

---Output---

{
    "_id" : ObjectId("5ec4ed0b94996124187b95ce"),
    "cid" : "245345323",
    "dtl" : [
        {
            "_id" : ObjectId("5ed5ab655df7930ec424be1e"),
            "sid" : "test",
            "amt" : 48,
            "Name" : "test"
        },
        {
            "_id" : ObjectId("5ed5ac9f79a75423d4bc0270"),
            "sid" : "s",
            "amt" : 14,
            "Name" : "sfds"
        },
        {
            "_id" : ObjectId("5ed5ace7d204ab144863ed7a"),
            "sid" : "wesad",
            "amt" : 6,
            "Name" : "2sdad"
        }
    ],
    "updated" : ISODate("2020-05-20T08:40:43.787Z"),
    "__v" : 6,
    "TotalAmt" : 62
}

Edit: If you want filter by other field, we need to add extra $map operator.

PM.findOneAndUpdate(
  {
    _id: MongoId,
  },
  [
    {
      $set: {
        TotalAmt: {
          $sum: {
            $map:{
                input: {
                  $filter: {
                    input: '$dtl',
                    cond: { $eq: ['$$this.Name', 'test'] }
                  }
                },
                in:"$$this.amt"
            }
          }
        }
      }
    }
  ],
  { new: true }
)


问:
redirect to another page (setTimeout) won't stop loading
i use this script

```<code>setTimeout(function(){
        window.location.href = '/MyPage';
     }, 5000);
</code>```

it already redirect me ,but never stop loading each 5 second, so how to redirect to (/MyPage) but after reach want to stay without loading

答:
I suppose that this script should redirect to itself. Then you can set an entry in your local storage like:

```<code>if (!localStorage.getItem('foo')) {
    localStorage.setItem('foo', '1');
    setTimeout(function(){
        window.location.href = '/MyPage';
    }, 5000);
}
</code>```

If you want to reenable the redirect, you can delete the entry with:

```<code>localStorage.removeItem('foo');
</code>```

Alternatively you can also set a cookie.

Body:
i use this script

setTimeout(function(){
        window.location.href = '/MyPage';
     }, 5000);

it already redirect me ,but never stop loading each 5 second, so how to redirect to (/MyPage) but after reach want to stay without loading

Body:
I suppose that this script should redirect to itself. Then you can set an entry in your local storage like:

if (!localStorage.getItem('foo')) {
    localStorage.setItem('foo', '1');
    setTimeout(function(){
        window.location.href = '/MyPage';
    }, 5000);
}

If you want to reenable the redirect, you can delete the entry with:

localStorage.removeItem('foo');

Alternatively you can also set a cookie.


问:
Using MEF with asp.net web form application (SharePoint)
I'm trying to use MEF in my ASP.NET web form (SharePoint) application to load some controls from a directory at runtime. I'm not getting any error but the controls are not getting loaded.

Here is my code -

aspx.cs

```<code>    public partial class SampleMEF : System.Web.UI.Page
    {
        [ImportMany(typeof(IControlLoader))]
        IEnumerable<Lazy<IControlLoader, IControlLoaderMetaData>> controls;
        private CompositionContainer _partsContainer;
        private AggregateCatalog _catalog;
        private string _partsPath;

        /// <summary>
        /// default constructor
        /// </summary>
        public SampleMEF()
        {
        }

        /// <summary>
        /// Initialize the page
        /// </summary>
        /// <param name="e"></param>
        protected override void OnInit(EventArgs e)
        {
            _partsPath = SPUtility.GetGenericSetupPath(@"TEMPLATE\LAYOUTS\MEFProtoType\Parts");
            _catalog = new AggregateCatalog();
            DirectoryCatalog c = new DirectoryCatalog(_partsPath, "*.dll");
            _partsContainer = new CompositionContainer(c);
            _partsContainer.ComposeParts(this);
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            foreach(Lazy<IControlLoader, IControlLoaderMetaData> i in controls)
            {
                SPPControl ctrl = i.Value.LoadControl();
                lbxControls.Items.Add(new ListItem(ctrl.Name, ctrl.ControlID.ToString()));
            }
        }
    }
</code>```

Contracts

```<code>    /// <summary>
    /// Contract for Imports and Exports
    /// </summary>
    public interface IControlLoader
    {
        SPPControl LoadControl();
    }

    /// <summary>
    /// Exports metadata
    /// </summary>
    public interface IControlLoaderMetaData
    {
        string ControlID { get; }
    }
</code>```

Sample Export

```<code>    [Export(typeof(IControlLoader))]
    [ExportMetadata("ControlID", "7a6c6288-ab52-4010-8c56-79959843ec7c")]
    public class ctrlAccordion : IControlLoader
    {
        #region IControlLoader Members

        public SPPControl LoadControl()
        {
            SPPControl ctrl = new SPPControl("Accordion", new Guid("7a6c6288-ab52-4010-8c56-79959843ec7c"), 5);
            return ctrl;
        }

        #endregion
    }
</code>```

I'm able to see the DLLs copied in the parts directory. But I'm not able to load the parts. The import is not filled and it is empty.

I'm using .Net Framework 3.5 and downloaded the MEF dll from MEF Codeplex and signed the assembly myself.

Any ideas?

答:
Okay, I eventually found the issue. I'm able to load the part dlls only if I sign them and add the dlls to global assembly. But I don't understand what DirectoryCatalog does loading the folder.

Bottom line: If the dlls are just in the parts folder and not in the GAC they are not getting loaded.

Body:
I'm trying to use MEF in my ASP.NET web form (SharePoint) application to load some controls from a directory at runtime. I'm not getting any error but the controls are not getting loaded.

Here is my code -

aspx.cs

    public partial class SampleMEF : System.Web.UI.Page
    {
        [ImportMany(typeof(IControlLoader))]
        IEnumerable<Lazy<IControlLoader, IControlLoaderMetaData>> controls;
        private CompositionContainer _partsContainer;
        private AggregateCatalog _catalog;
        private string _partsPath;

        ///
        /// default constructor
        ///
        public SampleMEF()
        {
        }

        ///
        /// Initialize the page
        ///
        /// <param name="e"></param>
        protected override void OnInit(EventArgs e)
        {
            _partsPath = SPUtility.GetGenericSetupPath(@"TEMPLATE\LAYOUTS\MEFProtoType\Parts");
            _catalog = new AggregateCatalog();
            DirectoryCatalog c = new DirectoryCatalog(_partsPath, "*.dll");
            _partsContainer = new CompositionContainer(c);
            _partsContainer.ComposeParts(this);
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            foreach(Lazy<IControlLoader, IControlLoaderMetaData> i in controls)
            {
                SPPControl ctrl = i.Value.LoadControl();
                lbxControls.Items.Add(new ListItem(ctrl.Name, ctrl.ControlID.ToString()));
            }
        }
    }

Contracts

    ///
    /// Contract for Imports and Exports
    ///
    public interface IControlLoader
    {
        SPPControl LoadControl();
    }

    ///
    /// Exports metadata
    ///
    public interface IControlLoaderMetaData
    {
        string ControlID { get; }
    }

Sample Export

    [Export(typeof(IControlLoader))]
    [ExportMetadata("ControlID", "7a6c6288-ab52-4010-8c56-79959843ec7c")]
    public class ctrlAccordion : IControlLoader
    {
        #region IControlLoader Members

        public SPPControl LoadControl()
        {
            SPPControl ctrl = new SPPControl("Accordion", new Guid("7a6c6288-ab52-4010-8c56-79959843ec7c"), 5);
            return ctrl;
        }

        #endregion
    }

I'm able to see the DLLs copied in the parts directory. But I'm not able to load the parts. The import is not filled and it is empty.

I'm using .Net Framework 3.5 and downloaded the MEF dll from MEF Codeplex and signed the assembly myself.

Any ideas?


问:
I am having an error when run code in android studio
I dont know why it has error when run this code in emulator with android studio.

The detail error :  SA    Emulator: emulator: INFO: QtLogger.cpp:68:
  Critical: Uncaught TypeError: Cannot read property 'update' of
  undefined (qrc:/html/js/location-mock-web-channel.js:130, (null))

```<code>package com.example.zingmp3;

import androidx.appcompat.app.AppCompatActivity;

import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.widget.Button;
import android.widget.SeekBar;
import android.widget.TextView;

import java.util.ArrayList;

public class MainActivity extends AppCompatActivity {

    private Button nextButton, previousButton, playButton, pauseButton;
    private SeekBar seekBar;
    private TextView timeCurrent, timeTotal, nameSong;
    private int index;
    private int position = 3;
    private Handler handler;
    ArrayList<Song> songs;
    MediaPlayer mediaPlayer;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        findById();
        addSong();
        mediaPlayer = MediaPlayer.create(MainActivity.this, songs.get(position).getFile());

        playButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mediaPlayer.start();
            }
        });
    }

    public void findById() {
        this.nextButton = findViewById(R.id.playButton);
        this.previousButton = findViewById(R.id.previousButton);
        this.playButton = findViewById(R.id.playButton);
        this.timeCurrent = findViewById(R.id.timeCurrent);
        this.timeTotal = findViewById(R.id.totalTime);
        this.seekBar = findViewById(R.id.seekBar);
        this.nameSong = findViewById(R.id.nameSong);
    }

    private void addSong() {
        Song song1 = new Song("Mot Cu Lua", R.raw.song1);
        Song song2 = new Song("So rang anh con yeu em", R.raw.soranganhyeuem);
        Song song3 = new Song("Tinh sau thien thu muon loi", R.raw.tinhsauthienthu);

        songs.add(song1);
        songs.add(song2);
        songs.add(song3);
    }
}
</code>```

答:
try to change

```<code>    ArrayList<Song> songs;
</code>```

to this

```<code>    ArrayList<Song> songs= new ArrayList<>();
</code>```

or define it in onCreate ...

```<code>songs= new ArrayList<>();
</code>```

Body:
I dont know why it has error when run this code in emulator with android studio.

The detail error :  SA    Emulator: emulator: INFO: QtLogger.cpp:68:
  Critical: Uncaught TypeError: Cannot read property 'update' of
  undefined (qrc:/html/js/location-mock-web-channel.js:130, (null))

package com.example.zingmp3;

import androidx.appcompat.app.AppCompatActivity;

import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.widget.Button;
import android.widget.SeekBar;
import android.widget.TextView;

import java.util.ArrayList;

public class MainActivity extends AppCompatActivity {

    private Button nextButton, previousButton, playButton, pauseButton;
    private SeekBar seekBar;
    private TextView timeCurrent, timeTotal, nameSong;
    private int index;
    private int position = 3;
    private Handler handler;
    ArrayList<Song> songs;
    MediaPlayer mediaPlayer;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        findById();
        addSong();
        mediaPlayer = MediaPlayer.create(MainActivity.this, songs.get(position).getFile());

        playButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mediaPlayer.start();
            }
        });
    }

    public void findById() {
        this.nextButton = findViewById(R.id.playButton);
        this.previousButton = findViewById(R.id.previousButton);
        this.playButton = findViewById(R.id.playButton);
        this.timeCurrent = findViewById(R.id.timeCurrent);
        this.timeTotal = findViewById(R.id.totalTime);
        this.seekBar = findViewById(R.id.seekBar);
        this.nameSong = findViewById(R.id.nameSong);
    }

    private void addSong() {
        Song song1 = new Song("Mot Cu Lua", R.raw.song1);
        Song song2 = new Song("So rang anh con yeu em", R.raw.soranganhyeuem);
        Song song3 = new Song("Tinh sau thien thu muon loi", R.raw.tinhsauthienthu);

        songs.add(song1);
        songs.add(song2);
        songs.add(song3);
    }
}

Body:
try to change

    ArrayList<Song> songs;

to this

    ArrayList<Song> songs= new ArrayList<>();

or define it in onCreate ...

songs= new ArrayList<>();


问:
RuntimeError: one of the variables needed for gradient computation has been modified by an inplace operation?
I am using pytorch-1.5 to do some gan test. My code is very simple gan code which just fit the sin(x) function:

```<code>import torch
import torch.nn as nn
import numpy as np
import matplotlib.pyplot as plt

# Hyper Parameters
BATCH_SIZE = 64
LR_G = 0.0001
LR_D = 0.0001
N_IDEAS = 5
ART_COMPONENTS = 15
PAINT_POINTS = np.vstack([np.linspace(-1, 1, ART_COMPONENTS) for _ in range(BATCH_SIZE)])

def artist_works():  # painting from the famous artist (real target)
    r = 0.02 * np.random.randn(1, ART_COMPONENTS)
    paintings = np.sin(PAINT_POINTS * np.pi) + r
    paintings = torch.from_numpy(paintings).float()
    return paintings

G = nn.Sequential(  # Generator
    nn.Linear(N_IDEAS, 128),  # random ideas (could from normal distribution)
    nn.ReLU(),
    nn.Linear(128, ART_COMPONENTS),  # making a painting from these random ideas
)

D = nn.Sequential(  # Discriminator
    nn.Linear(ART_COMPONENTS, 128),  # receive art work either from the famous artist or a newbie like G
    nn.ReLU(),
    nn.Linear(128, 1),
    nn.Sigmoid(),  # tell the probability that the art work is made by artist
)

opt_D = torch.optim.Adam(D.parameters(), lr=LR_D)
opt_G = torch.optim.Adam(G.parameters(), lr=LR_G)

for step in range(10000):
    artist_paintings = artist_works()  # real painting from artist
    G_ideas = torch.randn(BATCH_SIZE, N_IDEAS)  # random ideas
    G_paintings = G(G_ideas)  # fake painting from G (random ideas)

    prob_artist0 = D(artist_paintings)  # D try to increase this prob
    prob_artist1 = D(G_paintings)  # D try to reduce this prob

    D_loss = - torch.mean(torch.log(prob_artist0) + torch.log(1. - prob_artist1))
    G_loss = torch.mean(torch.log(1. - prob_artist1))

    opt_D.zero_grad()
    D_loss.backward(retain_graph=True)  # reusing computational graph
    opt_D.step()

    opt_G.zero_grad()
    G_loss.backward()
    opt_G.step()
</code>```

But when i runing it got this error:

```<code>RuntimeError: one of the variables needed for gradient computation has been modified by an inplace operation: [torch.FloatTensor [128, 1]], which is output 0 of TBackward, is at version 2; expected version 1 instead. Hint: the backtrace further above shows the operation that failed to compute its gradient. The variable in question was changed in there or anywhere later. Good luck!
</code>```

Is there something wrong with my code?

答:
This happens because the opt_D.step() modifies the parameters of your discriminator inplace. But these parameters are required to compute the gradient for the generator. You can fix this by changing your code to:

```<code>for step in range(10000):
    artist_paintings = artist_works()  # real painting from artist
    G_ideas = torch.randn(BATCH_SIZE, N_IDEAS)  # random ideas
    G_paintings = G(G_ideas)  # fake painting from G (random ideas)

    prob_artist1 = D(G_paintings)  # G tries to fool D

    G_loss = torch.mean(torch.log(1. - prob_artist1))
    opt_G.zero_grad()
    G_loss.backward()
    opt_G.step()

    prob_artist0 = D(artist_paintings)  # D try to increase this prob
    # detach here to make sure we don't backprop in G that was already changed.
    prob_artist1 = D(G_paintings.detach())  # D try to reduce this prob

    D_loss = - torch.mean(torch.log(prob_artist0) + torch.log(1. - prob_artist1))
    opt_D.zero_grad()
    D_loss.backward(retain_graph=True)  # reusing computational graph
    opt_D.step()
</code>```

You can find more about this issue here https://github.com/pytorch/pytorch/issues/39141

Body:
I am using pytorch-1.5 to do some gan test. My code is very simple gan code which just fit the sin(x) function:

import torch
import torch.nn as nn
import numpy as np
import matplotlib.pyplot as plt

# Hyper Parameters
BATCH_SIZE = 64
LR_G = 0.0001
LR_D = 0.0001
N_IDEAS = 5
ART_COMPONENTS = 15
PAINT_POINTS = np.vstack([np.linspace(-1, 1, ART_COMPONENTS) for _ in range(BATCH_SIZE)])

def artist_works():  # painting from the famous artist (real target)
    r = 0.02 * np.random.randn(1, ART_COMPONENTS)
    paintings = np.sin(PAINT_POINTS * np.pi) + r
    paintings = torch.from_numpy(paintings).float()
    return paintings

G = nn.Sequential(  # Generator
    nn.Linear(N_IDEAS, 128),  # random ideas (could from normal distribution)
    nn.ReLU(),
    nn.Linear(128, ART_COMPONENTS),  # making a painting from these random ideas
)

D = nn.Sequential(  # Discriminator
    nn.Linear(ART_COMPONENTS, 128),  # receive art work either from the famous artist or a newbie like G
    nn.ReLU(),
    nn.Linear(128, 1),
    nn.Sigmoid(),  # tell the probability that the art work is made by artist
)

opt_D = torch.optim.Adam(D.parameters(), lr=LR_D)
opt_G = torch.optim.Adam(G.parameters(), lr=LR_G)

for step in range(10000):
    artist_paintings = artist_works()  # real painting from artist
    G_ideas = torch.randn(BATCH_SIZE, N_IDEAS)  # random ideas
    G_paintings = G(G_ideas)  # fake painting from G (random ideas)

    prob_artist0 = D(artist_paintings)  # D try to increase this prob
    prob_artist1 = D(G_paintings)  # D try to reduce this prob

    D_loss = - torch.mean(torch.log(prob_artist0) + torch.log(1. - prob_artist1))
    G_loss = torch.mean(torch.log(1. - prob_artist1))

    opt_D.zero_grad()
    D_loss.backward(retain_graph=True)  # reusing computational graph
    opt_D.step()

    opt_G.zero_grad()
    G_loss.backward()
    opt_G.step()

But when i runing it got this error:

RuntimeError: one of the variables needed for gradient computation has been modified by an inplace operation: [torch.FloatTensor [128, 1]], which is output 0 of TBackward, is at version 2; expected version 1 instead. Hint: the backtrace further above shows the operation that failed to compute its gradient. The variable in question was changed in there or anywhere later. Good luck!

Is there something wrong with my code?

Body:
This happens because the opt_D.step() modifies the parameters of your discriminator inplace. But these parameters are required to compute the gradient for the generator. You can fix this by changing your code to:

for step in range(10000):
    artist_paintings = artist_works()  # real painting from artist
    G_ideas = torch.randn(BATCH_SIZE, N_IDEAS)  # random ideas
    G_paintings = G(G_ideas)  # fake painting from G (random ideas)

    prob_artist1 = D(G_paintings)  # G tries to fool D

    G_loss = torch.mean(torch.log(1. - prob_artist1))
    opt_G.zero_grad()
    G_loss.backward()
    opt_G.step()

    prob_artist0 = D(artist_paintings)  # D try to increase this prob
    # detach here to make sure we don't backprop in G that was already changed.
    prob_artist1 = D(G_paintings.detach())  # D try to reduce this prob

    D_loss = - torch.mean(torch.log(prob_artist0) + torch.log(1. - prob_artist1))
    opt_D.zero_grad()
    D_loss.backward(retain_graph=True)  # reusing computational graph
    opt_D.step()

You can find more about this issue here https://github.com/pytorch/pytorch/issues/39141


问:
UI Bootstrap Datepicker for Angular - select all day in a month when clicking on month name
Is it somehow possible to make a function in ui.bootstrap.datepicker, that select all days in the shown month when clicking on the month name in the top?

https://angular-ui.github.io/bootstrap/#!#datepicker

答: The conclusion was that it isn't possible to do that using UI Bootstrap with out manually changing the source code</p>


问:
ERROR TypeError: Cannot read property 'call' of undefined
I finally got to start making the nouislider work in my angular 9 project. My issue now is that I want to update a field when the slider value changes (so when the user moves the slider, I want to display the new value on the screen). There is an issue with the events and I'm not sure what it is.

```<code>noUiSlider.create(this.theHtmlElement, {
  start: [3000],
  step: 1,
  connect: [true, false],
  range: {
      'min': [0],
      'max': [10000]
  }
});

this.theHtmlElement.noUiSlider.on('update', this.valueChanged());

...
valueChanged() {
console.log(this.theHtmlElement.noUiSlider.get());
</code>```

}

The error I get is:

```<code>ERROR TypeError: Cannot read property 'call' of undefined
at nouislider.js:2082
at Array.forEach (<anonymous>)
at nouislider.js:2081
at Array.forEach (<anonymous>)
at fireEvent (nouislider.js:2077)
at nouislider.js:2055
at Array.forEach (<anonymous>)
at Object.bindEvent [as on] (nouislider.js:2054)
at AddCreditPageComponent.ngAfterViewInit (add-credit-page.component.ts:65)
at callProviderLifecycles (core.js:33986)
</code>```

The event seems to work the first time, I get to see the initial value in console but then it's followed by the error! and then nothing else works. I had a walk through, there seem to be a second scope event which is undefined or something! not sure what it is and where it's coming from, it's probably that one thats causing the problem. I'm not sure how to fix it.

答:
To bind an event, you have to pass in an anonymous function (among other possibilities);

```<code>this.theHtmlElement.noUiSlider.on('update', () => this.valueChanged());
</code>```

or

```<code>this.theHtmlElement.noUiSlider.on('update', this.valueChanged.bind(this));
</code>```

or

```<code>this.theHtmlElement.noUiSlider.on('update', this.valueChanged);

readonly valueChanged = () => {
  console.log(this.theHtmlElement.noUiSlider.get());
};
</code>```

How you did it immediately executes the this.valueChanged() method, which returns undefined. It then tries to bind this undefined to the update event handler, which will result in the error you see

Body:
I finally got to start making the nouislider work in my angular 9 project. My issue now is that I want to update a field when the slider value changes (so when the user moves the slider, I want to display the new value on the screen). There is an issue with the events and I'm not sure what it is.

noUiSlider.create(this.theHtmlElement, {
  start: [3000],
  step: 1,
  connect: [true, false],
  range: {
      'min': [0],
      'max': [10000]
  }
});

this.theHtmlElement.noUiSlider.on('update', this.valueChanged());

...
valueChanged() {
console.log(this.theHtmlElement.noUiSlider.get());

}

The error I get is:

ERROR TypeError: Cannot read property 'call' of undefined
at nouislider.js:2082
at Array.forEach (<anonymous>)
at nouislider.js:2081
at Array.forEach (<anonymous>)
at fireEvent (nouislider.js:2077)
at nouislider.js:2055
at Array.forEach (<anonymous>)
at Object.bindEvent [as on] (nouislider.js:2054)
at AddCreditPageComponent.ngAfterViewInit (add-credit-page.component.ts:65)
at callProviderLifecycles (core.js:33986)

The event seems to work the first time, I get to see the initial value in console but then it's followed by the error! and then nothing else works. I had a walk through, there seem to be a second scope event which is undefined or something! not sure what it is and where it's coming from, it's probably that one thats causing the problem. I'm not sure how to fix it.

Body:
To bind an event, you have to pass in an anonymous function (among other possibilities);

this.theHtmlElement.noUiSlider.on('update', () => this.valueChanged());

or

this.theHtmlElement.noUiSlider.on('update', this.valueChanged.bind(this));

or

this.theHtmlElement.noUiSlider.on('update', this.valueChanged);

readonly valueChanged = () => {
  console.log(this.theHtmlElement.noUiSlider.get());
};

How you did it immediately executes the this.valueChanged() method, which returns undefined. It then tries to bind this undefined to the update event handler, which will result in the error you see


问:
How to decode and download base64 string(excel data) and download the file?
I'm getting excel data encoded as base64 string from backend. I want to decode this data and download the excel file in the browser. I'm using vuejs as my frontend. Also if I were to show this data in table format on the frontend, how can I go about doing that? Thanks in advance for the response.

This is what I have tried-

```<code>public downloadfile() {
    var data = window.atob("string");
    this.save("file", data, ".xls");
  }
  public save(name: any, data: any, type: any) {
    var bytes = new Array(data.length);
    console.log("here", bytes);
    for (var i = 0; i < data.length; i++) {
      bytes[i] = data.charCodeAt(i);
    }
    data = new Uint8Array(bytes);
    var blob = new Blob([data], { type: type });
    console.log(blob);
    let objectURL = window.URL.createObjectURL(blob);
    let anchor = document.createElement("a");

    anchor.href = objectURL;
    anchor.download = name;
    anchor.click();

    URL.revokeObjectURL(objectURL);
  }
</code>```

I have a run button on clicking that downloadfile runs. and a file.txt gets downloaded. What am I doing wrong here? If I rename the file format to xls, that file shows correct data.

答: You need a browser Javascript library that understands excel format. I have used sheetjs with good success in the past. </p>

Body:
I'm getting excel data encoded as base64 string from backend. I want to decode this data and download the excel file in the browser. I'm using vuejs as my frontend. Also if I were to show this data in table format on the frontend, how can I go about doing that? Thanks in advance for the response.

This is what I have tried-

public downloadfile() {
    var data = window.atob("string");
    this.save("file", data, ".xls");
  }
  public save(name: any, data: any, type: any) {
    var bytes = new Array(data.length);
    console.log("here", bytes);
    for (var i = 0; i < data.length; i++) {
      bytes[i] = data.charCodeAt(i);
    }
    data = new Uint8Array(bytes);
    var blob = new Blob([data], { type: type });
    console.log(blob);
    let objectURL = window.URL.createObjectURL(blob);
    let anchor = document.createElement("a");

    anchor.href = objectURL;
    anchor.download = name;
    anchor.click();

    URL.revokeObjectURL(objectURL);
  }

I have a run button on clicking that downloadfile runs. and a file.txt gets downloaded. What am I doing wrong here? If I rename the file format to xls, that file shows correct data.


问:
how to align left and right in border
```<code>Positioned(
                    left: 16,
                    right: 16,
                    child: CircleAvatar(
                      radius: 66,
                    child: response.users.photo != null
                        ? Image.network(Modal.url + response.users.photo, width: 120, height: 140,)
                        : Image.asset(
                            'assets/user-icon.png',
                          ),
                    ),
</code>```

i have a problem, i want image align right and left in the border, please help me!

答:
Use ClipOval to draw image inside CircleAvatar

     ClipOval(
              child: new CircleAvatar(
                radius: 66,
                child: new Image.asset('assets/images/image.jpg'),
              ),
            ),
```

Title: how to align left and right in border

Body:
Positioned(
                    left: 16,
                    right: 16,
                    child: CircleAvatar(
                      radius: 66,
                    child: response.users.photo != null
                        ? Image.network(Modal.url + response.users.photo, width: 120, height: 140,)
                        : Image.asset(
                            'assets/user-icon.png',
                          ),
                    ),

i have a problem, i want image align right and left in the border, please help me!


答:
Your structure is the following Student-> List<Course> and Course-> Student which builds a circular chain and the toString method runs in loop.

From the javadocs for records:

Object.toString() methods are derived from all of the component
  fields.

When you do System.out.println(john) toString is called for the Student john then it is delegated to all the enrolled Course instances for which toString is called and as a Course instance has a reference to a Student instance again...the whole chain runs until a StackOverflowException is thrown.

Title: Java Records StackOverflow RuntimeException