问:
Problem generating image with different text
I'm creating a student ID card system, where each student will have his/her own.

For this I am using the intervention image, to pick up the student data and put in the standard ID card template.

The basic code for this I did was:

```<code><?php

[...]

$card = Image::make('card_id-model.png');

$card->text('CARD ID', 20, 40, function($font) {
    $font->file('arial.ttf');
    $font->size(24);
    $font->color('#fdf6e3');
    $font->align('center');
    $font->valign('top');
    $font->angle(45);
});

$card->text('NAME: STUDENT\'S NAME', 20, 60, function($font) {
    $font->file('arial.ttf');
    $font->size(24);
    $font->color('#fdf6e3');
    $font->align('center');
    $font->valign('top');
    $font->angle(45);
});

$card->text('CODE: STUDENT\'S CODE', 20, 80, function($font) {
    $font->file('arial.ttf');
    $font->size(24);
    $font->color('#fdf6e3');
    $font->align('center');
    $font->valign('top');
    $font->angle(45);
});

$card->save('card_id - student\'s code.png');
</code>```

This way is slower, considering that I will call the function every time I create the image.
So I decided to instantiate the image first, since it will be used for all card id. Well, but I'm experiencing problems applying it in a loop to generate several at the same time since the texts are overwriting.

```<code><?php

[...]

$card = Image::make('card_id-model.png');

$card->text('CARD ID', 20, 40, function($font) {
    $font->file('arial.ttf');
    $font->size(24);
    $font->color('#fdf6e3');
    $font->align('center');
    $font->valign('top');
    $font->angle(45);
});

for ($students as $student) {
    $card->text('NAME: ' . $student->name, 20, 60, function($font) {
        $font->file('arial.ttf');
        $font->size(24);
        $font->color('#fdf6e3');
        $font->align('center');
        $font->valign('top');
        $font->angle(45);
    });

    $card->text('CODE: ' . $student->code, 20, 80, function($font) {
        $font->file('arial.ttf');
        $font->size(24);
        $font->color('#fdf6e3');
        $font->align('center');
        $font->valign('top');
        $font->angle(45);
    });

    $card->save('card_id - ' . $student->code . '.png');
}
</code>```

That was the best and quickest way I found to mass-generate. Anybody got any tips?

答:
i usually do a design first in AI, then get the SVG out of it, then fill in with CSS+HTML. Since PHP can help filling it in, i use it to generate the HTML only.

Then the HTML will be transformed to PDF and then i just print it from there.

In any case, PHP is not ideal to generate images eventhough there's a way to do it. Use Browser's power to do it. Google Chrome is robust, but if you need it to be runable on server, you can use wkhtmltopdf.

Body:
I'm creating a student ID card system, where each student will have his/her own.

For this I am using the intervention image, to pick up the student data and put in the standard ID card template.

The basic code for this I did was:

<?php

[...]

$card = Image::make('card_id-model.png');

$card->text('CARD ID', 20, 40, function($font) {
    $font->file('arial.ttf');
    $font->size(24);
    $font->color('#fdf6e3');
    $font->align('center');
    $font->valign('top');
    $font->angle(45);
});

$card->text('NAME: STUDENT\'S NAME', 20, 60, function($font) {
    $font->file('arial.ttf');
    $font->size(24);
    $font->color('#fdf6e3');
    $font->align('center');
    $font->valign('top');
    $font->angle(45);
});

$card->text('CODE: STUDENT\'S CODE', 20, 80, function($font) {
    $font->file('arial.ttf');
    $font->size(24);
    $font->color('#fdf6e3');
    $font->align('center');
    $font->valign('top');
    $font->angle(45);
});

$card->save('card_id - student\'s code.png');

This way is slower, considering that I will call the function every time I create the image.
So I decided to instantiate the image first, since it will be used for all card id. Well, but I'm experiencing problems applying it in a loop to generate several at the same time since the texts are overwriting.

<?php

[...]

$card = Image::make('card_id-model.png');

$card->text('CARD ID', 20, 40, function($font) {
    $font->file('arial.ttf');
    $font->size(24);
    $font->color('#fdf6e3');
    $font->align('center');
    $font->valign('top');
    $font->angle(45);
});

for ($students as $student) {
    $card->text('NAME: ' . $student->name, 20, 60, function($font) {
        $font->file('arial.ttf');
        $font->size(24);
        $font->color('#fdf6e3');
        $font->align('center');
        $font->valign('top');
        $font->angle(45);
    });

    $card->text('CODE: ' . $student->code, 20, 80, function($font) {
        $font->file('arial.ttf');
        $font->size(24);
        $font->color('#fdf6e3');
        $font->align('center');
        $font->valign('top');
        $font->angle(45);
    });

    $card->save('card_id - ' . $student->code . '.png');
}

That was the best and quickest way I found to mass-generate. Anybody got any tips?


来源: stackexchange

问:
Laravel Eager Load Multiple Polymorphic Relationships - some soft deletes, some not
I have several models that contain a polymorphic field. These poly fields contain four or five relationships each, some are soft deleteable, some are not. I'm running into a 'damned if you do, damned if you don't' problem and not sure how to solve.

If I load with a call to eager loading without including trashed on the models that have softdeletes:

```<code>$deptRisks = \App\DeptRisk::with(['owner', 'riskable']);
</code>```

I will get the following error on those models that have been soft-deleted:

Trying to get property of non-object

If I load WITH the withTrashed for the softdeletes:

```<code>$deptRisks = \App\DeptRisk::with(['owner', 'riskable' => function ($query) {
        $query->withTrashed();
}]);
</code>```

I will get the following error on those models that have NOT been set up as soft-deletes:

Call to undefined method
  Illuminate\Database\Query\Builder::withTrashed()

I'm sure I'm missing something obvious, but I'm spinning in circles. Please help.

答:
I too tried the suggested solution

```<code>public function riskable() {
    $builder = $this->morphTo();

    if (method_exists($builder, 'withTrashed')) {
        $builder->withTrashed();
    }

    return $builder;
}
</code>```

Unfortunately, $builder, wasn't the actual model, so I couldn't check for the withTrashed method.

On 5.4, php 7.1 the most elegant solution I found was to wrap the attempt at ->withTrashed in a try catch.

```<code>public function riskable() {
    $morphTo = $this->morphTo();

    try {
        return $morphTo->withTrashed();
    } catch (\Throwable $e) {
        return $morphTo;
    }

}
</code>```

I ran into this when loading a polymorphic relationship when appending data to the model.

This worked very well for me.

ContentLicense: CC BY-SA 3.0

Body:
I have several models that contain a polymorphic field. These poly fields contain four or five relationships each, some are soft deleteable, some are not. I'm running into a 'damned if you do, damned if you don't' problem and not sure how to solve.

If I load with a call to eager loading without including trashed on the models that have softdeletes:

$deptRisks = \App\DeptRisk::with(['owner', 'riskable']);

I will get the following error on those models that have been soft-deleted:

Trying to get property of non-object

If I load WITH the withTrashed for the softdeletes:

$deptRisks = \App\DeptRisk::with(['owner', 'riskable' => function ($query) {
        $query->withTrashed();
}]);

I will get the following error on those models that have NOT been set up as soft-deletes:

Call to undefined method
  Illuminate\Database\Query\Builder::withTrashed()

I'm sure I'm missing something obvious, but I'm spinning in circles. Please help.

Body:
I too tried the suggested solution

public function riskable() {
    $builder = $this->morphTo();

    if (method_exists($builder, 'withTrashed')) {
        $builder->withTrashed();
    }

    return $builder;
}

Unfortunately, $builder, wasn't the actual model, so I couldn't check for the withTrashed method.

On 5.4, php 7.1 the most elegant solution I found was to wrap the attempt at ->withTrashed in a try catch.

public function riskable() {
    $morphTo = $this->morphTo();

    try {
        return $morphTo->withTrashed();
    } catch (\Throwable $e) {
        return $morphTo;
    }

}

I ran into this when loading a polymorphic relationship when appending data to the model.

This worked very well for me.

ContentLicense: CC BY-SA 4.0


问:
How to fix this NullPointerException on executeQuery?
I Have a NullPointerException on the executeQuery of my simple sql statement; I think the problem come from the connection to sqlite but i cant figure it out...

My java method :

```<code>    public Connection connect() throws SQLException {
    Connection conn = null;
    try {
        try {
            Class.forName("org.sqlite.JDBC");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        String url = "jdbc:sqlite:sakila.db.sqlite3";
        conn = DriverManager.getConnection(url);
        System.out.println("Connection to SQLite has been established.");
    } catch (SQLException e) {
        System.out.println(e.getMessage());
    }

    Statement stmt = conn.createStatement();
    String sql = "SELECT * FROM FILM LIMIT 10";
    stmt.executeQuery(sql);
    return conn;
}
</code>```

And this is the result from the console

```<code>Connection to SQLite has been established.
Exception in thread "main" java.lang.NullPointerException
at org.sqlite.Stmt.executeQuery(Stmt.java:121)
at Connect.connect(Connect.java:33)
at Main.main(Main.java:10)
</code>```

Thanks in advance

答:
Your finally block, closes the connection, so when the statement

```<code>Statement stmt = conn.createStatement();
</code>```

is reached, it will throw a NullPointerException. To fix the problem, your code should look like this:

```<code>public Connection connect() throws SQLException {

        Connection conn = null;
        try {
            try {
                Class.forName("org.sqlite.JDBC");
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            }
            String url = "jdbc:sqlite:sakila.db.sqlite3";
            conn = DriverManager.getConnection(url);
            System.out.println("Connection to SQLite has been established.");
            Statement stmt = conn.createStatement();
            String sql = "SELECT * FROM FILM LIMIT 10";
            stmt.executeQuery(sql);
            return conn;
        } catch (SQLException e) {
            System.out.println(e.getMessage());
        } finally {
            try {
                if (conn != null) {
                    conn.close();
                }
            } catch (SQLException ex) {
                System.out.println(ex.getMessage());
            }
        }
    }
</code>```

Body:
I Have a NullPointerException on the executeQuery of my simple sql statement; I think the problem come from the connection to sqlite but i cant figure it out...

My java method :

    public Connection connect() throws SQLException {
    Connection conn = null;
    try {
        try {
            Class.forName("org.sqlite.JDBC");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        String url = "jdbc:sqlite:sakila.db.sqlite3";
        conn = DriverManager.getConnection(url);
        System.out.println("Connection to SQLite has been established.");
    } catch (SQLException e) {
        System.out.println(e.getMessage());
    }

    Statement stmt = conn.createStatement();
    String sql = "SELECT * FROM FILM LIMIT 10";
    stmt.executeQuery(sql);
    return conn;
}

And this is the result from the console

Connection to SQLite has been established.
Exception in thread "main" java.lang.NullPointerException
at org.sqlite.Stmt.executeQuery(Stmt.java:121)
at Connect.connect(Connect.java:33)
at Main.main(Main.java:10)

Thanks in advance

Body:
Your finally block, closes the connection, so when the statement

Statement stmt = conn.createStatement();

is reached, it will throw a NullPointerException. To fix the problem, your code should look like this:

public Connection connect() throws SQLException {

        Connection conn = null;
        try {
            try {
                Class.forName("org.sqlite.JDBC");
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            }
            String url = "jdbc:sqlite:sakila.db.sqlite3";
            conn = DriverManager.getConnection(url);
            System.out.println("Connection to SQLite has been established.");
            Statement stmt = conn.createStatement();
            String sql = "SELECT * FROM FILM LIMIT 10";
            stmt.executeQuery(sql);
            return conn;
        } catch (SQLException e) {
            System.out.println(e.getMessage());
        } finally {
            try {
                if (conn != null) {
                    conn.close();
                }
            } catch (SQLException ex) {
                System.out.println(ex.getMessage());
            }
        }
    }


问:
How to Get WebAuthn to Work with a Roaming Authenticator?
The W3C recently approved Web Authentication: An API for accessing Public Key Credentials, commonly referred to as WebAuthn.

In section 6.2.1 the recommendation states, "For example, a platform authenticator integrated into a mobile device could make itself available as a roaming authenticator via Bluetooth. In this case the client would recognize it only as a roaming authenticator, and not as a platform authenticator."

Are there any code examples available anywhere for creating a WebAuthn roaming authenticator on a mobile device and making it available by Bluetooth Low Energy?

The article, The ultimate account security is now in your pocket, promised that your Android phone could be used as a roaming authenticator to sign into your Google account (just your Google account; a modest but good start).

I was able to associate my new Pixel 3A phone as a security key to my Google account:

When I go to authenticate I get the following screen on my web authentication page in the Chrome browser:

however, nothing happens on my phone.  The process just times out.

Has anyone gotten even this basic example to work?

Yes, Bluetooth is turned on in both my workstation (running the latest version of Windows 10) and my Pixel 3A (running Android Pie); I can pair the devices.

答:
OK. The good news is that after a complete uninstall of Chrome and then a fresh reinstall, the WebAuthn process for Google accounts now works with my new Pixel 3A phone.
https://blog.google/technology/safety-security/your-android-phone-is-a-security-key/

I had used a Yubico security key previously. I suspect there was an association to that key that was married to my Google account.

The major issue still remains: The lack of a clear reference implementation implementation for roaming authenticators.
https://github.com/w3c/webauthn/issues/1221


问:
SpriteKit Tileset Memory Leak
I am trying to create 2d platform game using SpriteKit. The game contains 21 levels, this means 21 scenes and 21 tilesets as well.
Each scene contains several tilenodes, all of which uses only 1 tileset.
At some point I found that my game consume almost 2GB of memory and sometimes being terminated due to memory issue.

I started investigation of reasons for this memory leaks using instruments. I found 4 leaks which shown on attached screenshot.
Responsible library is JavaScriptCore, I have no idea what the hell that means.

So, I continue investigation and try to remove blocks of code and assets from project in order to understand what going on.

At the end my project contained:

GameViewController which is looks exactly like GameViewController from XCode template.

Empty subclass of SKScene

1 Scene

21 Tilesets

Code of the GameViewController:

```<code>class GameViewController: UIViewController {

override func viewDidLoad() {
    super.viewDidLoad()
    if let scene = GKScene(fileNamed: "GameScene") {
        if let sceneNode = scene.rootNode as! SKScene? {
            sceneNode.scaleMode = .aspectFill
            if let view = self.view as! SKView? {
                view.presentScene(sceneNode)
                view.ignoresSiblingOrder = true
            }
        }
    }
}

override var shouldAutorotate: Bool {
    return true
}

override var supportedInterfaceOrientations: UIInterfaceOrientationMask {
    if UIDevice.current.userInterfaceIdiom == .phone {
        return .allButUpsideDown
    } else {
        return .all
    }
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Release any cached data, images, etc that aren't in use.
}

override var prefersStatusBarHidden: Bool {
    return true
}
</code>```

}

So, no code which can cause leaks and the game still consume 2GB in peaks.
And only when I remove all tilesets from project except one which is required for level - the memory consumption became normal, like ~200mb.

My guess that the SpriteKit load all tilesets into memory despite all tilenodes of the scene using only 1 tileset.

Also, game works well if I put tilesets back to the project and remove all tilenodes from scene.

My questition is how to properly manage this situation?

Thank you!

Update1: Memory Graph is attached
Update2: GameViewController code is provided

答:
Try this:

open Info.plist file, add a new row,

key: "PrefersOpenGL"
type: "Boolean"
value: "YES"

Title: SpriteKit Tileset Memory Leak

Body:
I am trying to create 2d platform game using SpriteKit. The game contains 21 levels, this means 21 scenes and 21 tilesets as well.
Each scene contains several tilenodes, all of which uses only 1 tileset.
At some point I found that my game consume almost 2GB of memory and sometimes being terminated due to memory issue.

I started investigation of reasons for this memory leaks using instruments. I found 4 leaks which shown on attached screenshot.
Responsible library is JavaScriptCore, I have no idea what the hell that means.

So, I continue investigation and try to remove blocks of code and assets from project in order to understand what going on.

At the end my project contained:

GameViewController which is looks exactly like GameViewController from XCode template.

Empty subclass of SKScene

1 Scene

21 Tilesets

Code of the GameViewController:

class GameViewController: UIViewController {

override func viewDidLoad() {
    super.viewDidLoad()
    if let scene = GKScene(fileNamed: "GameScene") {
        if let sceneNode = scene.rootNode as! SKScene? {
            sceneNode.scaleMode = .aspectFill
            if let view = self.view as! SKView? {
                view.presentScene(sceneNode)
                view.ignoresSiblingOrder = true
            }
        }
    }
}

override var shouldAutorotate: Bool {
    return true
}

override var supportedInterfaceOrientations: UIInterfaceOrientationMask {
    if UIDevice.current.userInterfaceIdiom == .phone {
        return .allButUpsideDown
    } else {
        return .all
    }
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Release any cached data, images, etc that aren't in use.
}

override var prefersStatusBarHidden: Bool {
    return true
}

}

So, no code which can cause leaks and the game still consume 2GB in peaks.
And only when I remove all tilesets from project except one which is required for level - the memory consumption became normal, like ~200mb.

My guess that the SpriteKit load all tilesets into memory despite all tilenodes of the scene using only 1 tileset.

Also, game works well if I put tilesets back to the project and remove all tilenodes from scene.

My questition is how to properly manage this situation?

Thank you!

Update1: Memory Graph is attached
Update2: GameViewController code is provided


问:
How to check the date is empty using python?
The startdate and enddate values are coming from jenkin to lambda.
In this code I am trying to get value using event["start_date"] and event["end_date"] and it's working fine, but if startdate and enddate are not available then the code should automatically take today's and yesterday's date.

I am new to python, can someone help here?

I tried as below but I am getting error.
If I will mention 'startdate and enddate is none' and set both values as none then it's working but I need to implement mentioned in code as I am using AWS lambda with python.

```<code>import datetime
from datetime import timedelta

dateformat = "%Y-%m-%d"
startdate = datetime.datetime.strptime("", dateformat)
enddate = datetime.datetime.strptime("", dateformat)
# Both startdate and enddate values come from Jenkin to lambda  -
event["start_date"] and event["end_date"]
if (startdate and enddate) == "":
    startdate = datetime.date.today()
    enddate = startdate - datetime.timedelta(days = 1)
    print('yesterday : ', enddate)
    print('Today : ', startdate)
</code>```

Current Error Output:

```<code>Traceback (most recent call last):
  File "variable_value_change.py", line 10, in <module>
    startdate = datetime.datetime.strptime("", dateformat)
  File "C:\Users\336635743\AppData\Local\Programs\Python\Python37-32\lib\_strptime.py", line 577, in _strptime_datetime
    tt, fraction, gmtoff_fraction = _strptime(data_string, format)
  File "C:\Users\336635743\AppData\Local\Programs\Python\Python37-32\lib\_strptime.py", line 359, in _strptime
   (data_string, format))
ValueError: time data '' does not match format '%Y-%m-%d'
</code>```

答:
Change this line

```<code>if (startdate and enddate) == "":
</code>```

to

```<code>if startdate == "" and enddate == "":
</code>```

Another way:

```<code>if not startdate and not enddate: # PEP 8 recommended
</code>```

Body:
The startdate and enddate values are coming from jenkin to lambda.
In this code I am trying to get value using event["start_date"] and event["end_date"] and it's working fine, but if startdate and enddate are not available then the code should automatically take today's and yesterday's date.

I am new to python, can someone help here?

I tried as below but I am getting error.
If I will mention 'startdate and enddate is none' and set both values as none then it's working but I need to implement mentioned in code as I am using AWS lambda with python.

import datetime
from datetime import timedelta

dateformat = "%Y-%m-%d"
startdate = datetime.datetime.strptime("", dateformat)
enddate = datetime.datetime.strptime("", dateformat)
# Both startdate and enddate values come from Jenkin to lambda  -
event["start_date"] and event["end_date"]
if (startdate and enddate) == "":
    startdate = datetime.date.today()
    enddate = startdate - datetime.timedelta(days = 1)
    print('yesterday : ', enddate)
    print('Today : ', startdate)

Current Error Output:

Traceback (most recent call last):
  File "variable_value_change.py", line 10, in <module>
    startdate = datetime.datetime.strptime("", dateformat)
  File "C:\Users\336635743\AppData\Local\Programs\Python\Python37-32\lib\_strptime.py", line 577, in _strptime_datetime
    tt, fraction, gmtoff_fraction = _strptime(data_string, format)
  File "C:\Users\336635743\AppData\Local\Programs\Python\Python37-32\lib\_strptime.py", line 359, in _strptime
   (data_string, format))
ValueError: time data '' does not match format '%Y-%m-%d'

Body:
Change this line

if (startdate and enddate) == "":

to

if startdate == "" and enddate == "":

Another way:

if not startdate and not enddate: # PEP 8 recommended


问:
Double Click vs Single Click - are these mutually exclusive
Can anyone name an instance of an application where clicking an entity (say image) does one thing, but if you double-click it it does something different?

The only example I've been able to find is in double-clicking a track in iTunes but then that selects it (single click function) and then plays it (double-click function) which implies (logically) that double click is the superset (containing single-click).

Basically, I am being asked to implement (in WPF) an image single-click doing one thing and an image double-click doing another thing and I'm not sure if this is even conceptually correct.

If someone has an example of anyone sensibly doing this that would be appreciated?

答:
```<code>private void OnItemMouseDown(object sender, MouseButtonEventArgs e) {
    if(e.ClickCount==2) {
        // DoubleClick Function
    }

    if(e.ClickCount==1) {
        // Click Function
    }
}
</code>```

ContentLicense: CC BY-SA 2.5


问:
Azure APIM custom domain SSL let's encrypt
I want to create a SSL certificate for a custom domain I owned and I then need to use this certificate with an Azure APIM instance.
I found the steps to assign a custom domain in APIM but I missed 2 pre-requisities:
  - The SSL certificat that needs to be uploaded first to a key vault --> I'm looking for the how to guid to use let's encrypt to generate this certificate
  - The DNS configuration that is required for APIM (only a CNAME?)</p>

答:
There are quite a few ways/tools that you can use to generate SSL certificates using Let's Encrypt.

acme.sh is a personal favorite which is bash compatible and supports DNS-01 challenges with lots of providers (Azure DNS is one of them).

Once you generate the cert (you can find them under ~/.acme.sh/), convert it to .pfx using this command

openssl pkcs12 -export -out domain.name.pfx -inkey domain.name.key -in domain.name.crt
```

Now you could either upload this file to Key Vault and reference it in APIM or directly upload it as well.

Note that LE certs expire in 90 days which acme.sh renews every 60 days and can be done manually as well.

Also, you will have to convert and reupload the new certs into Key Vault as well

As for the DNS entry, yes, you just need a CNAME record.

Body:
There are quite a few ways/tools that you can use to generate SSL certificates using Let's Encrypt.

acme.sh is a personal favorite which is bash compatible and supports DNS-01 challenges with lots of providers (Azure DNS is one of them).

Once you generate the cert (you can find them under ~/.acme.sh/), convert it to .pfx using this command

openssl pkcs12 -export -out domain.name.pfx -inkey domain.name.key -in domain.name.crt

Now you could either upload this file to Key Vault and reference it in APIM or directly upload it as well.

Note that LE certs expire in 90 days which acme.sh renews every 60 days and can be done manually as well.

Also, you will have to convert and reupload the new certs into Key Vault as well

As for the DNS entry, yes, you just need a CNAME record.


问:
How to edit "Reference Resolution" by script in Unity?
I want to change Reference Resolutuion with C# script in real time game, how can I make it?

Because I want to scale my controls with easiest way

答:
Like all the other properties of CanvasScaler you can simply use the CanvasScaler.referenceResolution property in a script like

```<code>GetComponent<CanvasScaler>().referenceResolution = new Vector2(xSize, ySize);
</code>```

Body:
Like all the other properties of CanvasScaler you can simply use the CanvasScaler.referenceResolution property in a script like

GetComponent<CanvasScaler>().referenceResolution = new Vector2(xSize, ySize);


问:
Unresolved reference: setLifecycleOwner in AndroidX

MainActivity.kt: (41, 16): Unresolved reference: setLifecycleOwner

Task :app:buildInfoGeneratorDebug

My app uses AndroidX, in my gradle.properties:

```<code>android.useAndroidX=true
android.enableJetifier=true
</code>```

My Code in onCreate function in MainActivity.tk:

```<code>val camera = findViewById<View>(R.id.camera)
    camera.setLifecycleOwner(this)
</code>```

Trying to implment the CameraView.

答:
You cast your library view type to android basic View which hasn't such method.

You should change your findViewById<View> to findViewById<CameraView>

Body:
MainActivity.kt: (41, 16): Unresolved reference: setLifecycleOwner

Task :app:buildInfoGeneratorDebug

My app uses AndroidX, in my gradle.properties:

android.useAndroidX=true
android.enableJetifier=true

My Code in onCreate function in MainActivity.tk:

val camera = findViewById<View>(R.id.camera)
    camera.setLifecycleOwner(this)

Trying to implment the CameraView.


问:
What's wrong with my delete link?
```<code><%= link_to "Delete Party", party_path(@party.id), :method => :delete %>
</code>```

a GET is always called according to the logs. I just get redirected to the same show page when I click the delete link.

答:
The solution worked for me..
I was using jQuery 1.4.4 and facing issues with the delete link, I read somewhere about the jQuery version issue and switched to jQuery 1.4.2 and delete link worked fine for me.

Title: What's wrong with my delete link?

Body:
<%= link_to "Delete Party", party_path(@party.id), :method => :delete %>

a GET is always called according to the logs. I just get redirected to the same show page when I click the delete link.


答:
This is probably not what you want:

```<code> if (startdate and enddate) == "":
</code>```

How about:

```<code>if startdate == '':
    startdate = datetime.date.today()
if enddate == '':
    enddate = startdate - datetime.timedelta(days = 1)
</code>```

Title: How to check the date is empty using python?

Body:
This is probably not what you want:

 if (startdate and enddate) == "":

How about:

if startdate == '':
    startdate = datetime.date.today()
if enddate == '':
    enddate = startdate - datetime.timedelta(days = 1)


问:
How can I export the 'result' returned from a mysql query?
I am trying to use node js to place MySql data eventually in an HTML( really an ejs) page.

I have been using the code below from W3's node js examples. https://www.w3schools.com/nodejs/nodejs_mysql_select.asp

What I eventually would like to do is use module.exports on 'result', and be able to access the array in another file. I have been finding this difficult to accomplish.

```<code>var mysql = require('mysql');

var con = mysql.createConnection({
    host: "localhost",
    user: "username",
    password: "password",
    database: "testdb"
});

con.connect(function(err) {
    if (err) throw err;
    con.query("SELECT * FROM customers", function (err, result, fields) {
    if (err) throw err;
    console.log(result);
});

// This is what is logged to the console.

// [ RowDataPacket { name: 'Company Inc', address: 'Highway 37' },
  RowDataPacket { name: 'Sanitation', address: 'Highway 27' },
  RowDataPacket { name: 'Ice Cream', address: 'Highway 11' } ]

// Above works but it doesn't do what I need it to.
// Below is explained what I need to happen.

var mysql = require('mysql');

var x; // x is undefined

var con = mysql.createConnection({
    host: "localhost",
    user: "username",
    password: "password",
    database: "testdb"
});

con.connect(function(err) {
    if (err) throw err;
    con.query("SELECT * FROM customers",
    function (err, result, fields) {
    if (err) throw err;
    x = result; // If I do a 'console.log(x);' here I get the array above.
    // If try to 'module.exports = result;' here, it is
    // undefined in the receiving file. });
});

console.log(x); // x is undefined, even though result was stored in x.
</code>```

I would expect for the 'console.log(x);' at the bottom of the code to return the array, but it is undefined. This makes me think that anything in the 'con.query' is local. If that is the case, I considered using 'module. exports = result' in the function, but that also returns an undefined variable in the receiving file. If anyone knows why this happens, or if there is a solution, I would be very appreciative of your advice : )

答:
Maybe what you need to do is export your function, and use it whenever you want

What I suggest is that you export the database connection variable, so you can use it whenever you want, something like:

config.js

```<code>var con = mysql.createConnection({
    host: "localhost",
    user: "username",
    password: "password",
    database: "testdb"
});
exports.default = con
</code>```

fileThatUsesResult.js

```<code>const db = ./config.js
db.con.connect(function(err) {
    if (err) throw err;
    con.query("SELECT * FROM customers",
    function (err, result, fields) {
    if (err) throw err;
    //here you use your results, maybe res.json or whatever you want to do
});
</code>```

This way you can split your code and call the dabatase connection object whenever you need it. Remember the DRY principle.

By the way, I recommend you use promise instead of callbacks functions, that way you can manage your asynchronous calls

Hope I helped!

Body:
I am trying to use node js to place MySql data eventually in an HTML( really an ejs) page.

I have been using the code below from W3's node js examples. https://www.w3schools.com/nodejs/nodejs_mysql_select.asp

What I eventually would like to do is use module.exports on 'result', and be able to access the array in another file. I have been finding this difficult to accomplish.

var mysql = require('mysql');

var con = mysql.createConnection({
    host: "localhost",
    user: "username",
    password: "password",
    database: "testdb"
});

con.connect(function(err) {
    if (err) throw err;
    con.query("SELECT * FROM customers", function (err, result, fields) {
    if (err) throw err;
    console.log(result);
});

// This is what is logged to the console.

// [ RowDataPacket { name: 'Company Inc', address: 'Highway 37' },
  RowDataPacket { name: 'Sanitation', address: 'Highway 27' },
  RowDataPacket { name: 'Ice Cream', address: 'Highway 11' } ]

// Above works but it doesn't do what I need it to.
// Below is explained what I need to happen.

var mysql = require('mysql');

var x; // x is undefined

var con = mysql.createConnection({
    host: "localhost",
    user: "username",
    password: "password",
    database: "testdb"
});

con.connect(function(err) {
    if (err) throw err;
    con.query("SELECT * FROM customers",
    function (err, result, fields) {
    if (err) throw err;
    x = result; // If I do a 'console.log(x);' here I get the array above.
    // If try to 'module.exports = result;' here, it is
    // undefined in the receiving file. });
});

console.log(x); // x is undefined, even though result was stored in x.

I would expect for the 'console.log(x);' at the bottom of the code to return the array, but it is undefined. This makes me think that anything in the 'con.query' is local. If that is the case, I considered using 'module. exports = result' in the function, but that also returns an undefined variable in the receiving file. If anyone knows why this happens, or if there is a solution, I would be very appreciative of your advice : )

Body:
Maybe what you need to do is export your function, and use it whenever you want

What I suggest is that you export the database connection variable, so you can use it whenever you want, something like:

config.js

var con = mysql.createConnection({
    host: "localhost",
    user: "username",
    password: "password",
    database: "testdb"
});
exports.default = con

fileThatUsesResult.js

const db = ./config.js
db.con.connect(function(err) {
    if (err) throw err;
    con.query("SELECT * FROM customers",
    function (err, result, fields) {
    if (err) throw err;
    //here you use your results, maybe res.json or whatever you want to do
});

This way you can split your code and call the dabatase connection object whenever you need it. Remember the DRY principle.

By the way, I recommend you use promise instead of callbacks functions, that way you can manage your asynchronous calls

Hope I helped!


问:
Using charAt with number in Javascript
I want to set some index to my statement and check it's found or not i found this method charAt but it's work just with strings so how to handle these with numbers

```<code>if (mobileNumber) {
        let j = mobileNumber.charAt(2);
        let w = mobileNumber.charAt(0);
        alert("@", w, j)
        if (j === 9) { //Not work quz it's a number
          alert("FoundJ", j)
          return;
        } else if (w === 6) { //Not work quz it's a number
          alert("FoundW", w)
          return
        } else{
           alert("sorry, App does not work in your city right now")
           return
          }
</code>```

Update

now I handle the index but I have some issue with them here is my Statements
if I write the number and it contains 9 || 6 in the (2)index I see the alert when calling the function I don't know why?

```<code> let j = mobileNumber.toString().charAt(2);
      if (mobileNumber.length <= 0) {
        this.setState(
          Object.assign(validations, {
            mobileNumberValid: "• Please, write your Mobile Number"
          })
        );
        return;
      } else if (mobileNumber.length < 10) {
        this.setState(
          Object.assign(validations, {
            mobileNumberValid:
              "• Your Mobile Number must be exactly 10 characters!"
          })
        );
        return;
      } else if (regNumber.test(mobileNumber) === false) {
        this.setState(
          Object.assign(validations, {
            mobileNumberValid: "• Please, Your mobile must be a number"
          })
        );
        return;
      }
      else if (j != 9 || j != 6) { // i think the issue with **OR**
        alert("sorry not work in your city yet!")
        return;
      }
 else {
        this.setState(
          Object.assign(validations, {
            mobileNumberValid: ""
          })
        );
      }
</code>```

答:
=== performs exact comparison without casting type (as far as I know)

If you have a numeric expression, you can convert it into string, then use charAt() to do your comparison

function findJW(mobileNumber) {
    console.log("Checking "+ mobileNumber)
    let str = mobileNumber.toString();
    let j = str.charAt(2);
    let w = str.charAt(0);

    if (j == '9') {
       console.log("FoundJ", j)
    } else if (w == '6') {
      console.log("FoundW", w)
    } else{
      console.log("sorry, App does not work in your city right now")
    }
}

findJW(12954678)
findJW(62354678)
findJW(11111111)```

Title: Using charAt with number in Javascript

Body:
I want to set some index to my statement and check it's found or not i found this method charAt but it's work just with strings so how to handle these with numbers

if (mobileNumber) {
        let j = mobileNumber.charAt(2);
        let w = mobileNumber.charAt(0);
        alert("@", w, j)
        if (j === 9) { //Not work quz it's a number
          alert("FoundJ", j)
          return;
        } else if (w === 6) { //Not work quz it's a number
          alert("FoundW", w)
          return
        } else{
           alert("sorry, App does not work in your city right now")
           return
          }

Update

now I handle the index but I have some issue with them here is my Statements
if I write the number and it contains 9 || 6 in the (2)index I see the alert when calling the function I don't know why?

 let j = mobileNumber.toString().charAt(2);
      if (mobileNumber.length <= 0) {
        this.setState(
          Object.assign(validations, {
            mobileNumberValid: "• Please, write your Mobile Number"
          })
        );
        return;
      } else if (mobileNumber.length < 10) {
        this.setState(
          Object.assign(validations, {
            mobileNumberValid:
              "• Your Mobile Number must be exactly 10 characters!"
          })
        );
        return;
      } else if (regNumber.test(mobileNumber) === false) {
        this.setState(
          Object.assign(validations, {
            mobileNumberValid: "• Please, Your mobile must be a number"
          })
        );
        return;
      }
      else if (j != 9 || j != 6) { // i think the issue with **OR**
        alert("sorry not work in your city yet!")
        return;
      }
 else {
        this.setState(
          Object.assign(validations, {
            mobileNumberValid: ""
          })
        );
      }


问:
Webpack not working for simple project with npm start
This is my package file and webpack configuration.  I'm learning the technology but this isn't working.  I receive the following error for a blank canvas project.  Is there something I'm doing wrong?

Many thanks,

Error message

```<code>ERROR in ./src/index.js 6:16
Module parse failed: Unexpected token (6:16)
You may need an appropriate loader to handle this file type.
| import App from './App';
|
> ReactDOM.render(<App />, document.getElementById('root'));
</code>```

package.json

```<code>{
  "name": "boilerplate",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "start": "webpack --mode development --watch",
    "build": "webpack --mode production"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "babel-core": "^6.26.3",
    "babel-loader": "^8.0.6",
    "babel-preset-env": "^1.7.0",
    "babel-preset-react": "^6.24.1",
    "css-loader": "^2.1.1",
    "html-webpack-plugin": "^3.2.0",
    "style-loader": "^0.23.1",
    "webpack": "^4.32.2",
    "webpack-cli": "^3.3.2"
  },
  "dependencies": {
    "react": "^16.8.6",
    "react-dom": "^16.8.6"
  }
}
</code>```

webpack.config.js

```<code>var HtmlWebpackPlugin = require('html-webpack-plugin');
var path = require('path');

module.exports = {
  entry: './src/index.js',
  output: {
    path: path.join(__dirname, './dist'),
    filename: 'index_bundle.js'
  },
  plugins: [new HtmlWebpackPlugin()]
};
</code>```

App.js

```<code>import React, { Component } from 'react';

class App extends Component {
    render() {
        return (
            <div>
                <h1>hello</h1>
            </div>
        )
    }
}
</code>```

I now have the following webpack.config.js

Update - complete file

```<code>var HtmlWebpackPlugin = require('html-webpack-plugin');
var path = require('path');

module.exports = {
  entry: './src/index.js',
  output: {
    path: path.join(__dirname, './dist'),
    filename: 'index_bundle.js'
  },
  resolve: {
    extensions: ['', '.js', '.jsx']
  },
  module: {
    loaders: [
      {
        test: /\.jsx?$/,
        loader: 'babel',
        exclude: /node_modules/,
        query: {
          cacheDirectory: true,
          presets: ['react', 'es2015']
        }
      }
    ]
  },
  plugins: [new HtmlWebpackPlugin()]
};
</code>```

After this change and after running npm install I get the following error when running npm start

```<code>Invalid configuration object. Webpack has been initialised using a configuration object that does not match the API schema.
 - configuration.module has an unknown property 'loaders'. These properties are valid:
   object { defaultRules?, exprContextCritical?, exprContextRecursive?, exprContextRegExp?, exprContextRequest?, noParse?, rules?, strictExportPrese
nce?, strictThisContextOnImports?, unknownContextCritical?, unknownContextRecursive?, unknownContextRegExp?, unknownContextRequest?, unsafeCache?, w
rappedContextCritical?, wrappedContextRecursive?, wrappedContextRegExp? }
   -> Options affecting the normal modules (`NormalModuleFactory`).
 - configuration.resolve.extensions[0] should be an non-empty string.
   -> A non-empty string
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! boilerplate@1.0.0 start: `webpack --mode development --watch`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the boilerplate@1.0.0 start script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.
</code>```

Update 2

```<code>var HtmlWebpackPlugin = require('html-webpack-plugin');
var path = require('path');

module.exports = {
  entry: './src/index.js',
  output: {
    path: path.join(__dirname, './dist'),
    filename: 'index_bundle.js'
  },
  resolve: {
    extensions: ['.js', '.jsx']
  },
  module: {
    rules: [
      {
        test: /\.js$/,
        exclude: /node_modules/,
        use: {
            loader: "babel-loader"
        }
      }
    ]
  },
  plugins: [new HtmlWebpackPlugin()]
};
</code>```

Error received with this version of the file

```<code>[./src/index.js] 3.16 KiB {main} [not cacheable] [built] [failed] [1 error]

ERROR in ./src/index.js
Module build failed (from ./node_modules/babel-loader/lib/index.js):
Error: Cannot find module '@babel/core'
 babel-loader@8 requires Babel 7.x (the package '@babel/core'). If you'd like to use Babel 6.x ('babel-core'), you should install 'babel-loader@7'.
    at Function.Module._resolveFilename (internal/modules/cjs/loader.js:613:15)
</code>```

答:
Firstly, your property

module:{
loaders

is not correct, it should be modules->rules. Secondly, you do not have any JSX in folders, You have App.js, so your rules, should test it and load appropriate loaders for it, which would we be babel-loader with presets set to react

```<code> module: {
        rules: [
            {
                test: /\.js$/,
                exclude: /node_modules/,
                use: {
                    loader: "babel-loader"
                }
            }
</code>```

To tell babel to use react as its presets, either you specify in above config or create a .babelrc file with below content in it.

```<code>{
    "presets": ["@babel/preset-env", "@babel/preset-react"]
  }
</code>```

After this, you should be good to go

Body:
This is my package file and webpack configuration.  I'm learning the technology but this isn't working.  I receive the following error for a blank canvas project.  Is there something I'm doing wrong?

Many thanks,

Error message

ERROR in ./src/index.js 6:16
Module parse failed: Unexpected token (6:16)
You may need an appropriate loader to handle this file type.
| import App from './App';
|
> ReactDOM.render(<App />, document.getElementById('root'));

package.json

{
  "name": "boilerplate",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "start": "webpack --mode development --watch",
    "build": "webpack --mode production"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "babel-core": "^6.26.3",
    "babel-loader": "^8.0.6",
    "babel-preset-env": "^1.7.0",
    "babel-preset-react": "^6.24.1",
    "css-loader": "^2.1.1",
    "html-webpack-plugin": "^3.2.0",
    "style-loader": "^0.23.1",
    "webpack": "^4.32.2",
    "webpack-cli": "^3.3.2"
  },
  "dependencies": {
    "react": "^16.8.6",
    "react-dom": "^16.8.6"
  }
}

webpack.config.js

var HtmlWebpackPlugin = require('html-webpack-plugin');
var path = require('path');

module.exports = {
  entry: './src/index.js',
  output: {
    path: path.join(__dirname, './dist'),
    filename: 'index_bundle.js'
  },
  plugins: [new HtmlWebpackPlugin()]
};

App.js

import React, { Component } from 'react';

class App extends Component {
    render() {
        return (

hello

        )
    }
}

I now have the following webpack.config.js

Update - complete file

var HtmlWebpackPlugin = require('html-webpack-plugin');
var path = require('path');

module.exports = {
  entry: './src/index.js',
  output: {
    path: path.join(__dirname, './dist'),
    filename: 'index_bundle.js'
  },
  resolve: {
    extensions: ['', '.js', '.jsx']
  },
  module: {
    loaders: [
      {
        test: /\.jsx?$/,
        loader: 'babel',
        exclude: /node_modules/,
        query: {
          cacheDirectory: true,
          presets: ['react', 'es2015']
        }
      }
    ]
  },
  plugins: [new HtmlWebpackPlugin()]
};

After this change and after running npm install I get the following error when running npm start

Invalid configuration object. Webpack has been initialised using a configuration object that does not match the API schema.
 - configuration.module has an unknown property 'loaders'. These properties are valid:
   object { defaultRules?, exprContextCritical?, exprContextRecursive?, exprContextRegExp?, exprContextRequest?, noParse?, rules?, strictExportPrese
nce?, strictThisContextOnImports?, unknownContextCritical?, unknownContextRecursive?, unknownContextRegExp?, unknownContextRequest?, unsafeCache?, w
rappedContextCritical?, wrappedContextRecursive?, wrappedContextRegExp? }
   -> Options affecting the normal modules (`NormalModuleFactory`).
 - configuration.resolve.extensions[0] should be an non-empty string.
   -> A non-empty string
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! boilerplate@1.0.0 start: `webpack --mode development --watch`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the boilerplate@1.0.0 start script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

Update 2

var HtmlWebpackPlugin = require('html-webpack-plugin');
var path = require('path');

module.exports = {
  entry: './src/index.js',
  output: {
    path: path.join(__dirname, './dist'),
    filename: 'index_bundle.js'
  },
  resolve: {
    extensions: ['.js', '.jsx']
  },
  module: {
    rules: [
      {
        test: /\.js$/,
        exclude: /node_modules/,
        use: {
            loader: "babel-loader"
        }
      }
    ]
  },
  plugins: [new HtmlWebpackPlugin()]
};

Error received with this version of the file

[./src/index.js] 3.16 KiB {main} [not cacheable] [built] [failed] [1 error]

ERROR in ./src/index.js
Module build failed (from ./node_modules/babel-loader/lib/index.js):
Error: Cannot find module '@babel/core'
 babel-loader@8 requires Babel 7.x (the package '@babel/core'). If you'd like to use Babel 6.x ('babel-core'), you should install 'babel-loader@7'.
    at Function.Module._resolveFilename (internal/modules/cjs/loader.js:613:15)

Body:
Firstly, your property

module:{
loaders

is not correct, it should be modules->rules. Secondly, you do not have any JSX in folders, You have App.js, so your rules, should test it and load appropriate loaders for it, which would we be babel-loader with presets set to react

 module: {
        rules: [
            {
                test: /\.js$/,
                exclude: /node_modules/,
                use: {
                    loader: "babel-loader"
                }
            }

To tell babel to use react as its presets, either you specify in above config or create a .babelrc file with below content in it.

{
    "presets": ["@babel/preset-env", "@babel/preset-react"]
  }

After this, you should be good to go


问:
Fitting a Logistic Curve to Data
I would like to fit a logaritmic function to some data with scipy.

Unfortunatley I get the following error: Covariance of the parameters could not be estimated

How can I prevent this?

import numpy as np
import scipy.optimize as opt
import matplotlib.pyplot as plt

x = [0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0, 11.0, 12.0, 13.0, 14.0]
y = [0.073, 2.521, 15.879, 48.365, 72.68, 90.298, 92.111, 93.44, 93.439, 93.389, 93.381, 93.367, 93.94, 93.269, 96.376]

def f(x, a, b, c, d):
    return a / (1. + np.exp(-c * (x - d))) + b

(a_, b_, c_, d_), _ = opt.curve_fit(f, x, y)

y_fit = f(x, a_, b_, c_, d_)
fig, ax = plt.subplots(1, 1, figsize=(6, 4))
ax.plot(x, y, 'o')
ax.plot(x, y_fit, '-')
```

答:
After several tries, I saw that there is an issue in the computation of the covariance with your data. I tried to remove the 0.0 in case this is the reason but not.

The only alternative I found is to change the method of computation from lm to trf :

```<code>x = np.array(x)
y = np.array(y)

popt, pcov = opt.curve_fit(f, x, y, method="trf")
y_fit = f(x, *popt)
fig, ax = plt.subplots(1, 1, figsize=(6, 4))
ax.plot(x, y, 'o')
ax.plot(x, y_fit, '-')
plt.show()
</code>```

and the curve is properly fit with those parameters [96.2823169  -2.38876852  1.39927921  2.98341838]

Title: Fitting a Logistic Curve to Data

Body:
After several tries, I saw that there is an issue in the computation of the covariance with your data. I tried to remove the 0.0 in case this is the reason but not.

The only alternative I found is to change the method of computation from lm to trf :

x = np.array(x)
y = np.array(y)

popt, pcov = opt.curve_fit(f, x, y, method="trf")
y_fit = f(x, *popt)
fig, ax = plt.subplots(1, 1, figsize=(6, 4))
ax.plot(x, y, 'o')
ax.plot(x, y_fit, '-')
plt.show()

and the curve is properly fit with those parameters [96.2823169  -2.38876852  1.39927921  2.98341838]


问:
How to add social share links to DetailView?
How do I add social sharing feature to my website build in Django. I saw a similar question in SO but that didn't help (below I explained why?), it was asked 6 years ago and I thought probably there must be better ways of doing it after these years.

I tried using addthis ,it is elegant and easy to use, but this is the problem when I share a post in Facebook.

And also it didn't keep counts number of sharing a post.

I also tried other ways either I didn't understand or it didn't work fine.
Please help me do this. Thank you very much.

edit:
I am getting this error. after adding Share on Facebook

答:
use this for Facebook:

{% with base_url="http://example.com" %}
Share on Facebook
{% endwith %}

for Twitter:

{% with base_url="http://example.com" %}
Share on Twitter
{% endwith %}

for Linkedin: use this

Body:
use this for Facebook:

{% with base_url="http://example.com" %}
<a href="https://www.facebook.com/sharer/sharer.php?u={{ base_url|urlencode }}{{ request.get_full_path|urlencode }}&t={{ object.title }}">Share on Facebook</a>
{% endwith %}

for Twitter:

{% with base_url="http://example.com" %}
<a href="https://twitter.com/share?text={{ user.username }}&url={{ base_url|urlencode }}{{ request.get_full_path|urlencode}}">Share on Twitter</a>
{% endwith %}

for Linkedin: use this


问:
How to uniquely display SQL
Task 9
What is the total cost of medications prescribed by each vet each day? Only display the vet’s id, date of visit and the total cost. Sort the report by the vet’s id and the date of visit.

This is the output I got:

```<code>VET_ID  VISIT_DATE  TOTAL_COST
V01     21-Apr-2004 36.49
V01     21-Apr-2004 38.49
V01     21-Apr-2004 41.88
V01     21-Apr-2004 40.24
V01     21-Apr-2004 35.99
V01     21-Apr-2004 35.99
V01     27-Apr-2004 32.5
V01     27-Apr-2004 37.89
V01     27-Apr-2004 32
V01     27-Apr-2004 34.5

SELECT Visit.Vet_id, Visit.Visit_Date, (Basic_Cost + Cost) AS Total_Cost
FROM Visit
INNER JOIN Medication ON Visit.Vet_id = Medication.Vet_id
ORDER BY Vet_ID, Visit_Date;
</code>```

This is the expected output:

```<code>Vet Date      Total Cost
--- --------- ------------
V01 21-APR-04 12
V01 27-APR-04 16.25
V01 03-MAY-04 26.5
V01 22-JUN-04 30.39
V02 21-APR-04 38.5
V02 28-APR-04 12.5
V02 16-MAY-04 27.5
V03 28-APR-04 7.99
V03 08-MAY-04 7.99
V03 13-MAY-04 28.25
V04 03-MAY-04 10.49
V04 07-MAY-04 16.75
V04 12-MAY-04 46.05
V04 13-MAY-04 22.5
V04 17-MAY-04 32.85
V04 19-MAY-04 17.5
</code>```

答:
You can use a subquery in your own query.  Sounds like it.</p>

```<code>with grouped as (
    SELECT
            Visit.Vet_id,
            Visit.Visit_Date,
            (Basic_Cost + Cost) AS Total_Cost
    FROM Visit
    INNER JOIN
        Medication ON Visit.Vet_id = Medication.Vet_id
    ORDER BY Vet_ID, Visit_Date;
)
    select
        Vet_id,
        Visit_Date,
        sum(Total_Cost)
    from grouped
    group by
        Vet_id,Visit_Date
</code>```

Title: How to uniquely display SQL

Body:
Task 9
What is the total cost of medications prescribed by each vet each day? Only display the vet’s id, date of visit and the total cost. Sort the report by the vet’s id and the date of visit.

This is the output I got:

VET_ID  VISIT_DATE  TOTAL_COST
V01     21-Apr-2004 36.49
V01     21-Apr-2004 38.49
V01     21-Apr-2004 41.88
V01     21-Apr-2004 40.24
V01     21-Apr-2004 35.99
V01     21-Apr-2004 35.99
V01     27-Apr-2004 32.5
V01     27-Apr-2004 37.89
V01     27-Apr-2004 32
V01     27-Apr-2004 34.5

SELECT Visit.Vet_id, Visit.Visit_Date, (Basic_Cost + Cost) AS Total_Cost
FROM Visit
INNER JOIN Medication ON Visit.Vet_id = Medication.Vet_id
ORDER BY Vet_ID, Visit_Date;

This is the expected output:

Vet Date      Total Cost
--- --------- ------------
V01 21-APR-04 12
V01 27-APR-04 16.25
V01 03-MAY-04 26.5
V01 22-JUN-04 30.39
V02 21-APR-04 38.5
V02 28-APR-04 12.5
V02 16-MAY-04 27.5
V03 28-APR-04 7.99
V03 08-MAY-04 7.99
V03 13-MAY-04 28.25
V04 03-MAY-04 10.49
V04 07-MAY-04 16.75
V04 12-MAY-04 46.05
V04 13-MAY-04 22.5
V04 17-MAY-04 32.85
V04 19-MAY-04 17.5

Body:
You can use a subquery in your own query.  Sounds like it.

with grouped as (
    SELECT
            Visit.Vet_id,
            Visit.Visit_Date,
            (Basic_Cost + Cost) AS Total_Cost
    FROM Visit
    INNER JOIN
        Medication ON Visit.Vet_id = Medication.Vet_id
    ORDER BY Vet_ID, Visit_Date;
)
    select
        Vet_id,
        Visit_Date,
        sum(Total_Cost)
    from grouped
    group by
        Vet_id,Visit_Date


问:
Sweet Alert Syntax
I am failing to get sweet alert going and i think it has something to do with the syntax. Can someone show me what i should be doing</p>

```<code><!DOCTYPE html>
<html>
 <head>
  <title>Testing</title>
  <script src="dist/sweetalert.min.js"></script>
  <link rel="stylesheet" type="text/css" href="dist/sweetalert.css">
 </head>
<body>
<script>
   swal({
     title: 'Confirm',
     text: 'Are you sure to delete this message?',
     type: 'warning',
     showCancelButton: true,
     confirmButtonText: 'Yes, sir',
     cancelButtonText: 'Not at all'
 });
</script>
</body>
</html>
</code>```

答:
Just change your code as per below:</p>

```<code><!DOCTYPE html>
<html>
    <head>
        <title>Testing</title>

        <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/limonte-sweetalert2/7.33.1/sweetalert2.css">
        <script type="text/javascript" src="https://code.jquery.com/jquery-3.4.1.js"></script>
        <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/limonte-sweetalert2/7.33.1/sweetalert2.js"></script>

        <script>
            $(document).ready(function(){

                    Swal.fire({
                        title: 'Success',
                        text: "Your sweet alert successfully worked",
                        type: 'success',
                    });

                });
        </script>

    </head>
    <body>

    </body>
</html>

</code>```

Title: Sweet Alert Syntax

Body:
I am failing to get sweet alert going and i think it has something to do with the syntax. Can someone show me what i should be doing

<!DOCTYPE html>

  <title>Testing</title>

  <link rel="stylesheet" type="text/css" href="dist/sweetalert.css">

Body:
Just change your code as per below:

<!DOCTYPE html>
<html>
    <head>
        <title>Testing</title>

        <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/limonte-sweetalert2/7.33.1/sweetalert2.css">
        <script type="text/javascript" src="https://code.jquery.com/jquery-3.4.1.js"></script>
        <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/limonte-sweetalert2/7.33.1/sweetalert2.js"></script>

        <script>
            $(document).ready(function(){

                    Swal.fire({
                        title: 'Success',
                        text: "Your sweet alert successfully worked",
                        type: 'success',
                    });

                });
        </script>

    </head>
    <body>

    </body>
</html>


问:
MySQL root password reset -bash: syntax error near unexpected token `('
I am just starting to learn MySQL, im running 5.7.20 on Mac os 10.12 when i tried to use the following command in Terminal to reset password

```<code>mysql> UPDATE mysql.user SET authentication_string = PASSWORD('password')
</code>```

i am keep getting

-bash: syntax error near unexpected token `('

Can anyone assist me with that error message? i have tried many different website no one seems to have an answer to that.

```<code>Last login: Tue May 28 02:07:04 on ttys001
192-168-1-5:~ Betty$ mysql> UPDATE mysql.user SET authentication_string = PASSWORD('password')
-bash: syntax error near unexpected token `('
</code>```

答: When you see mysql> something, it doesn't mean to type mysql> something at the Bash prompt. It means to type something at the MySQL prompt. Run the command properly from inside MySQL and it will work.

Body:
I am just starting to learn MySQL, im running 5.7.20 on Mac os 10.12 when i tried to use the following command in Terminal to reset password

mysql> UPDATE mysql.user SET authentication_string = PASSWORD('password')

i am keep getting

-bash: syntax error near unexpected token `('

Can anyone assist me with that error message? i have tried many different website no one seems to have an answer to that.

Last login: Tue May 28 02:07:04 on ttys001
192-168-1-5:~ Betty$ mysql> UPDATE mysql.user SET authentication_string = PASSWORD('password')
-bash: syntax error near unexpected token `('


问:
Problem generating image with different text
I'm creating a student ID card system, where each student will have his/her own.

For this I am using the intervention image, to pick up the student data and put in the standard ID card template.

The basic code for this I did was:

```<code><?php

[...]

$card = Image::make('card_id-model.png');

$card->text('CARD ID', 20, 40, function($font) {
    $font->file('arial.ttf');
    $font->size(24);
    $font->color('#fdf6e3');
    $font->align('center');
    $font->valign('top');
    $font->angle(45);
});

$card->text('NAME: STUDENT\'S NAME', 20, 60, function($font) {
    $font->file('arial.ttf');
    $font->size(24);
    $font->color('#fdf6e3');
    $font->align('center');
    $font->valign('top');
    $font->angle(45);
});

$card->text('CODE: STUDENT\'S CODE', 20, 80, function($font) {
    $font->file('arial.ttf');
    $font->size(24);
    $font->color('#fdf6e3');
    $font->align('center');
    $font->valign('top');
    $font->angle(45);
});

$card->save('card_id - student\'s code.png');
</code>```

This way is slower, considering that I will call the function every time I create the image.
So I decided to instantiate the image first, since it will be used for all card id. Well, but I'm experiencing problems applying it in a loop to generate several at the same time since the texts are overwriting.

```<code><?php

[...]

$card = Image::make('card_id-model.png');

$card->text('CARD ID', 20, 40, function($font) {
    $font->file('arial.ttf');
    $font->size(24);
    $font->color('#fdf6e3');
    $font->align('center');
    $font->valign('top');
    $font->angle(45);
});

for ($students as $student) {
    $card->text('NAME: ' . $student->name, 20, 60, function($font) {
        $font->file('arial.ttf');
        $font->size(24);
        $font->color('#fdf6e3');
        $font->align('center');
        $font->valign('top');
        $font->angle(45);
    });

    $card->text('CODE: ' . $student->code, 20, 80, function($font) {
        $font->file('arial.ttf');
        $font->size(24);
        $font->color('#fdf6e3');
        $font->align('center');
        $font->valign('top');
        $font->angle(45);
    });

    $card->save('card_id - ' . $student->code . '.png');
}
</code>```

That was the best and quickest way I found to mass-generate. Anybody got any tips?

答:
You are having the issue with text overwriting, because you are calling the text function on original object. Instead you need to do modifications on copy of element, and then save it in array.

See example.

```<code>$generatedCards = [];

foreach ($students as $student) {
    $generatedCard = clone $card;
    $generatedCard->text('...');
    $generatedCards[] = $generatedCard;
}
</code>```

Body:
I'm creating a student ID card system, where each student will have his/her own.

For this I am using the intervention image, to pick up the student data and put in the standard ID card template.

The basic code for this I did was:

<?php

[...]

$card = Image::make('card_id-model.png');

$card->text('CARD ID', 20, 40, function($font) {
    $font->file('arial.ttf');
    $font->size(24);
    $font->color('#fdf6e3');
    $font->align('center');
    $font->valign('top');
    $font->angle(45);
});

$card->text('NAME: STUDENT\'S NAME', 20, 60, function($font) {
    $font->file('arial.ttf');
    $font->size(24);
    $font->color('#fdf6e3');
    $font->align('center');
    $font->valign('top');
    $font->angle(45);
});

$card->text('CODE: STUDENT\'S CODE', 20, 80, function($font) {
    $font->file('arial.ttf');
    $font->size(24);
    $font->color('#fdf6e3');
    $font->align('center');
    $font->valign('top');
    $font->angle(45);
});

$card->save('card_id - student\'s code.png');

This way is slower, considering that I will call the function every time I create the image.
So I decided to instantiate the image first, since it will be used for all card id. Well, but I'm experiencing problems applying it in a loop to generate several at the same time since the texts are overwriting.

<?php

[...]

$card = Image::make('card_id-model.png');

$card->text('CARD ID', 20, 40, function($font) {
    $font->file('arial.ttf');
    $font->size(24);
    $font->color('#fdf6e3');
    $font->align('center');
    $font->valign('top');
    $font->angle(45);
});

for ($students as $student) {
    $card->text('NAME: ' . $student->name, 20, 60, function($font) {
        $font->file('arial.ttf');
        $font->size(24);
        $font->color('#fdf6e3');
        $font->align('center');
        $font->valign('top');
        $font->angle(45);
    });

    $card->text('CODE: ' . $student->code, 20, 80, function($font) {
        $font->file('arial.ttf');
        $font->size(24);
        $font->color('#fdf6e3');
        $font->align('center');
        $font->valign('top');
        $font->angle(45);
    });

    $card->save('card_id - ' . $student->code . '.png');
}

That was the best and quickest way I found to mass-generate. Anybody got any tips?

Body:
You are having the issue with text overwriting, because you are calling the text function on original object. Instead you need to do modifications on copy of element, and then save it in array.

See example.

$generatedCards = [];

foreach ($students as $student) {
    $generatedCard = clone $card;
    $generatedCard->text('...');
    $generatedCards[] = $generatedCard;
}


问:
"Cannot GET" error when doing href to file in parent folder
I am trying to link to another html file which is located in a different folder. The files are in the following folders:

Wevdev/DigitalMedia/image1.html

and the other is in:

Webdev/Labs/Directory.html

Hyperlinks are working when linking between files in the same folder but getting an error when trying to link to a file in a different folder.

```<code><img src="arrow-3D-green-left.jpg">
<a href="http://wikipedia.com"><img src="rome1.jpg"></a>
<img src="arrow-3D-green-right.jpg"><br>

<h1>Image 1</h1>

<a href="=../Labs/Directory.html">Link to directory</a>
</code>```

The page opens in chrome with the following error message:

Cannot GET /Labs/Directory.html

答:
You are using extra = after href=" .I think just a type mistake:

```<code><a href="../Labs/Directory.html">Link to directory</a>
</code>```

Body:
I am trying to link to another html file which is located in a different folder. The files are in the following folders:

Wevdev/DigitalMedia/image1.html

and the other is in:

Webdev/Labs/Directory.html

Hyperlinks are working when linking between files in the same folder but getting an error when trying to link to a file in a different folder.

Image 1

Link to directory

The page opens in chrome with the following error message:

Cannot GET /Labs/Directory.html

Body:
You are using extra = after href=" .I think just a type mistake:

<a href="../Labs/Directory.html">Link to directory</a>


问:
jquery/javascript wait for a function to complete
I have script that performs from DOM manipulation to change the way a div looks. The way the application is, when the page loads, the div is rendered in its original state, the function manipulates the DIV. The problem is it renders the original div before rendering the changed div.

I tried:

```<code>//Make div invisible

//Call function to change the DIV

//Make div visible
</code>```

This does not work

答:
```<code>$('div').hide(function(){
 $(this).css('font-size', '5em');
 $(this).find('h1').css('color','red');
 $(this).show();
})
</code>```

This MUST work ;)

OwnerDisplayName: Bob Smith

Body:
I have script that performs from DOM manipulation to change the way a div looks. The way the application is, when the page loads, the div is rendered in its original state, the function manipulates the DIV. The problem is it renders the original div before rendering the changed div.

I tried:

//Make div invisible

//Call function to change the DIV

//Make div visible

This does not work

Body:
$('div').hide(function(){
 $(this).css('font-size', '5em');
 $(this).find('h1').css('color','red');
 $(this).show();
})

This MUST work ;)

OwnerDisplayName: Ionut Staicu


问:
Conditional "or" in Thinking Sphinx search
Using RoR 2.3.8.

Here's my controller code:

```<code>class CitiesController < ApplicationController
  def show
    @city = City.find(params[:id])
    @shops = Shop.search @city.name, {
      :conditions => {:country => @city.country && (:city => @city.name || :state => @city.state)},
      :page => params[:page],
      :per_page => 100
      }
  end
end
</code>```

The :conditions => {:country => @city.country && (:city => @city.name || :state => @city.state)} obviously doesn't work because I am just trying to explain what I wanna achieve.

:city and :state will be columns from Spots table, not Cities table. I want results to return either one of them fulfills the condition. But have no clue how to do it.

Thanks.

答:
Place your raw search to Sphinx - you should find the correct method in the TS docu. A reference for raw search. You probably want something like

```<code>"@city_country #{@city.country} (@city_name #{@city.name} | @city_state #{@city.state})"
</code>```

(I'm not sure how TS names the indexes. Check that.)

Body:
Using RoR 2.3.8.

Here's my controller code:

class CitiesController < ApplicationController
  def show
    @city = City.find(params[:id])
    @shops = Shop.search @city.name, {
      :conditions => {:country => @city.country && (:city => @city.name || :state => @city.state)},
      :page => params[:page],
      :per_page => 100
      }
  end
end

The :conditions => {:country => @city.country && (:city => @city.name || :state => @city.state)} obviously doesn't work because I am just trying to explain what I wanna achieve.

:city and :state will be columns from Spots table, not Cities table. I want results to return either one of them fulfills the condition. But have no clue how to do it.

Thanks.

Body:
Place your raw search to Sphinx - you should find the correct method in the TS docu. A reference for raw search. You probably want something like

"@city_country #{@city.country} (@city_name #{@city.name} | @city_state #{@city.state})"

(I'm not sure how TS names the indexes. Check that.)


问:
Halting at 95% emitting index-html-webpack-plugin (Angular ver. 7)
Solution for Halting Problem at "ng build --prod 95% emitting index-html-webpack-plugin" (Angular version 7) when set "sourceMap": true in angular.json

Thanks!

答:
```<code>node --max_old_space_size=8000 ./node_modules/@angular/cli/bin/ng build -e=prod --prod --sourcemap --vendor-chunk=true --build-optimizer
</code>```

For me resizing the max_old_space_size for 8000 worked, the comand is above

Body:
node --max_old_space_size=8000 ./node_modules/@angular/cli/bin/ng build -e=prod --prod --sourcemap --vendor-chunk=true --build-optimizer

For me resizing the max_old_space_size for 8000 worked, the comand is above


问:
mktemp on macOS random file generation fails: file exists
When I create a random file on macOS with mktemp I get:

```<code>mktemp /tmp/test.XXXXXXX.json
mktemp: mkstemp failed on /tmp/test.XXXXXXX.json: File exists
</code>```

It does not replace XXXXXXX with random string. Works fine on Linux but not on macOS.

答:
This is the documented behaviour, from man mktemp:

The template may be any file name with some number of `Xs'
       appended to it, for example /tmp/temp.XXXXXX

Body:
When I create a random file on macOS with mktemp I get:

mktemp /tmp/test.XXXXXXX.json
mktemp: mkstemp failed on /tmp/test.XXXXXXX.json: File exists

It does not replace XXXXXXX with random string. Works fine on Linux but not on macOS.


问:
Issue in setting the background color in pyqtgraph
I've  got an issue when using the pyqtgraph module in python.
When I put a white background color to a glscatterplot, the scatter dots just vanish. It is like if the color of background was added to the color of the scatterplot therefore everything is white.
Here is a piece of the code I use:

```<code>w = gl.GLViewWidget()
w.setBackgroundColor('w')
w.show()
sp3 = gl.GLScatterPlotItem(pos=np.transpose(pos3), color=rgba_img, size=1, pxMode=False)
w.addItem(sp3)
</code>```

If I replace ('w') by ('k') in the setBackgroundColor method the color of scatter is fine and the background is black. Did anyone else ever get this issue?

答:
I had the same problem and I found the solution here: https://github.com/pyqtgraph/pyqtgraph/issues/193. I think is the same question so probably you already know the solution but I report it here simplified because.

The problem is that there is an option for GLScatterPlotItem called glOptions. By default, 'additive' is used (see pyqtgraph.opengl.GLGraphicsItem.GLOptions). You can change it to 'translucent' like so:

```<code>sp3.setGLOptions('translucent')
</code>```

In this way you won't have any problem changing the background color to white, nor the scatter color to black (I had both problems).

Body:
I've  got an issue when using the pyqtgraph module in python.
When I put a white background color to a glscatterplot, the scatter dots just vanish. It is like if the color of background was added to the color of the scatterplot therefore everything is white.
Here is a piece of the code I use:

w = gl.GLViewWidget()
w.setBackgroundColor('w')
w.show()
sp3 = gl.GLScatterPlotItem(pos=np.transpose(pos3), color=rgba_img, size=1, pxMode=False)
w.addItem(sp3)

If I replace ('w') by ('k') in the setBackgroundColor method the color of scatter is fine and the background is black. Did anyone else ever get this issue?

Body:
I had the same problem and I found the solution here: https://github.com/pyqtgraph/pyqtgraph/issues/193. I think is the same question so probably you already know the solution but I report it here simplified because.

The problem is that there is an option for GLScatterPlotItem called glOptions. By default, 'additive' is used (see pyqtgraph.opengl.GLGraphicsItem.GLOptions). You can change it to 'translucent' like so:

sp3.setGLOptions('translucent')

In this way you won't have any problem changing the background color to white, nor the scatter color to black (I had both problems).


问:
Good books and web resources for JOGL and JMonkeyEngine?
I am currently trying to decide between using JOGL and JMonkeyEngine on a project so I would like to learn a bit about the basics of each and decide which one I prefer.  Does anyone have any books or web resources to recommend for learning how to use each one?  I really prefer stuff that gives a lot of detailed information and examples that use good style over brief online tutorials with poor quality code examples.  Official documentation is always good, but I haven't yet found it for either.  JMonkeyEngine says that it has complete documentation but I haven't yet located it on their website.  Any information would be appreciated.

I should probably mention that I have never used OpenGL before.  If I go with JOGL I will need to learn all of the OpenGL basics, so I also need good resources on OpenGL if the JOGL resources don't go into full detail on it.

答:
Updated:

jMonkeyEngine 3 Beginner's Guide

jMonkeyEngine 3 Cookbook

I am in the jMonkey Core Team, albeit not as a programmer.

For starters, if you're considering JOGL, I hope you're looking at JOGL2 by JogAmp, and not the old abandoned one over at Java.net. In terms of use, JOGL and jME are two different things. JOGL, like LWJGL that jME (and Minecraft, to name one) is based on, only eases you into the bare essentials, mainly OpenGL. It means even more freedom, but you will be spending a large amount of time making the "bare bones" of your game before you get to flesh it out with real gameplay features.

jMonkeyEngine, the latest jME3 especially, is designed with intermediate developers in mind, not by means of limitations but with a gradual learning curve and a whole lot of game-specific features built in.

/takes salesman hat off

Our wiki is located at jmonkeyengine.org/wiki/doku.php. Even if you're more used to Eclipse, I strongly recommend using jMonkeyPlatform (the jME3 SDK) for all your jMonkey development, as it comes with a lot of tools that we just couldn't put into the engine core.

As for books, I don't believe there is one, for either. Our main doc writer is working on a contract with Packt though. The final "jMonkeyEngine 3 Beginner's Guide" book is expected late 2011 or early 2012.

I can't speak for JOGL (though I figure they'd say the same), but if you have any more questions regarding jMonkeyEngine I suggest you come visit our forum.


问:
Generate a pdf with images on header and footer with iText
I am looking forward to create a pdf using iText.
The pdf will have a header and a footer. Both the header and footer will have a image (company logo) in it.

I am looking forward to an example similar to that. I will be using the iText library for the first time so I am not sure where to start off from.

答:
To add headers and footers to a PDF you generate using iText 7.x, you will generally create event listeners for page starts and/or page ends and add the header and footer contents there-in.

For example you can do it like in this sample on the iText site. Here two event listeners are defined:

//Header event handler
protected class Header implements IEventHandler {
    String header;
    public Header(String header) {
        this.header = header;
    }
    @Override
    public void handleEvent(Event event) {
        //Retrieve document and
        PdfDocumentEvent docEvent = (PdfDocumentEvent) event;
        PdfDocument pdf = docEvent.getDocument();
        PdfPage page = docEvent.getPage();
        Rectangle pageSize = page.getPageSize();
        PdfCanvas pdfCanvas = new PdfCanvas(
                page.getLastContentStream(), page.getResources(), pdf);
        Canvas canvas = new Canvas(pdfCanvas, pdf, pageSize);
        canvas.setFontSize(18f);
        //Write text at position
        canvas.showTextAligned(header,
                pageSize.getWidth() / 2,
                pageSize.getTop() - 30, TextAlignment.CENTER);
    }
}
```

<p>This event handler adds a simple constant string as header to the current page. Similarly you can also add an image.</p>

<pre class="lang-java prettyprint-override"><code>//page X of Y
protected class PageXofY implements IEventHandler {
    protected PdfFormXObject placeholder;
    protected float side = 20;
    protected float x = 300;
    protected float y = 25;
    protected float space = 4.5f;
    protected float descent = 3;
    public PageXofY(PdfDocument pdf) {
        placeholder =
                new PdfFormXObject(new Rectangle(0, 0, side, side));
    }
    @Override
    public void handleEvent(Event event) {
        PdfDocumentEvent docEvent = (PdfDocumentEvent) event;
        PdfDocument pdf = docEvent.getDocument();
        PdfPage page = docEvent.getPage();
        int pageNumber = pdf.getPageNumber(page);
        Rectangle pageSize = page.getPageSize();
        PdfCanvas pdfCanvas = new PdfCanvas(
                page.getLastContentStream(), page.getResources(), pdf);
        Canvas canvas = new Canvas(pdfCanvas, pdf, pageSize);
        Paragraph p = new Paragraph()
                .add("Page ").add(String.valueOf(pageNumber)).add(" of");
        canvas.showTextAligned(p, x, y, TextAlignment.RIGHT);
        pdfCanvas.addXObject(placeholder, x + space, y - descent);
        pdfCanvas.release();
    }
    public void writeTotal(PdfDocument pdf) {
        Canvas canvas = new Canvas(placeholder, pdf);
        canvas.showTextAligned(String.valueOf(pdf.getNumberOfPages()),
                0, descent, TextAlignment.LEFT);
    }
}
</code>```

This event handler is a bit more complex, it adds a Page x of y footer to the current page. As the total number of pages y is unknown at the time, a reference to a placeholder XObject is added instead, and as soon as you know all the pages are created, you can call writeTotal to have this method write the current number of document pages into the placeholder XObject.

You register these event listeners as following:

PdfWriter writer= new PdfWriter(pdfDest);
PdfDocument pdfDocument = new PdfDocument(writer);

//Create event-handlers
String header = "pdfHtml Header and footer example using page-events";
Header headerHandler = new Header(header);
PageXofY footerHandler = new PageXofY(pdfDocument);

//Assign event-handlers
pdfDocument.addEventHandler(PdfDocumentEvent.START_PAGE,headerHandler);
pdfDocument.addEventHandler(PdfDocumentEvent.END_PAGE,footerHandler);

//Add content
[... here you add the regular page content to the PdfDocument ...]

//Write the total number of pages to the placeholder and close the document
footerHandler.writeTotal(pdfDocument);
pdfDocument.close();
```

(The actual example adds the regular page content based on HTML using pdfHTML. You may do so, too, or you may generate the content directly using Document, Paragraph, Text, and other layout classes.)

Body:
To add headers and footers to a PDF you generate using iText 7.x, you will generally create event listeners for page starts and/or page ends and add the header and footer contents there-in.

For example you can do it like in this sample on the iText site. Here two event listeners are defined:

//Header event handler
protected class Header implements IEventHandler {
    String header;
    public Header(String header) {
        this.header = header;
    }
    @Override
    public void handleEvent(Event event) {
        //Retrieve document and
        PdfDocumentEvent docEvent = (PdfDocumentEvent) event;
        PdfDocument pdf = docEvent.getDocument();
        PdfPage page = docEvent.getPage();
        Rectangle pageSize = page.getPageSize();
        PdfCanvas pdfCanvas = new PdfCanvas(
                page.getLastContentStream(), page.getResources(), pdf);
        Canvas canvas = new Canvas(pdfCanvas, pdf, pageSize);
        canvas.setFontSize(18f);
        //Write text at position
        canvas.showTextAligned(header,
                pageSize.getWidth() / 2,
                pageSize.getTop() - 30, TextAlignment.CENTER);
    }
}

This event handler adds a simple constant string as header to the current page. Similarly you can also add an image.

//page X of Y
protected class PageXofY implements IEventHandler {
    protected PdfFormXObject placeholder;
    protected float side = 20;
    protected float x = 300;
    protected float y = 25;
    protected float space = 4.5f;
    protected float descent = 3;
    public PageXofY(PdfDocument pdf) {
        placeholder =
                new PdfFormXObject(new Rectangle(0, 0, side, side));
    }
    @Override
    public void handleEvent(Event event) {
        PdfDocumentEvent docEvent = (PdfDocumentEvent) event;
        PdfDocument pdf = docEvent.getDocument();
        PdfPage page = docEvent.getPage();
        int pageNumber = pdf.getPageNumber(page);
        Rectangle pageSize = page.getPageSize();
        PdfCanvas pdfCanvas = new PdfCanvas(
                page.getLastContentStream(), page.getResources(), pdf);
        Canvas canvas = new Canvas(pdfCanvas, pdf, pageSize);
        Paragraph p = new Paragraph()
                .add("Page ").add(String.valueOf(pageNumber)).add(" of");
        canvas.showTextAligned(p, x, y, TextAlignment.RIGHT);
        pdfCanvas.addXObject(placeholder, x + space, y - descent);
        pdfCanvas.release();
    }
    public void writeTotal(PdfDocument pdf) {
        Canvas canvas = new Canvas(placeholder, pdf);
        canvas.showTextAligned(String.valueOf(pdf.getNumberOfPages()),
                0, descent, TextAlignment.LEFT);
    }
}

This event handler is a bit more complex, it adds a Page x of y footer to the current page. As the total number of pages y is unknown at the time, a reference to a placeholder XObject is added instead, and as soon as you know all the pages are created, you can call writeTotal to have this method write the current number of document pages into the placeholder XObject.

You register these event listeners as following:

PdfWriter writer= new PdfWriter(pdfDest);
PdfDocument pdfDocument = new PdfDocument(writer);

//Create event-handlers
String header = "pdfHtml Header and footer example using page-events";
Header headerHandler = new Header(header);
PageXofY footerHandler = new PageXofY(pdfDocument);

//Assign event-handlers
pdfDocument.addEventHandler(PdfDocumentEvent.START_PAGE,headerHandler);
pdfDocument.addEventHandler(PdfDocumentEvent.END_PAGE,footerHandler);

//Add content
[... here you add the regular page content to the PdfDocument ...]

//Write the total number of pages to the placeholder and close the document
footerHandler.writeTotal(pdfDocument);
pdfDocument.close();

(The actual example adds the regular page content based on HTML using pdfHTML. You may do so, too, or you may generate the content directly using Document, Paragraph, Text, and other layout classes.)


问:
Connection Refused error when Mongo is connected to application
I am writing some tests in Mocha and my first test always passes:

```<code>const assert = require('assert');
const request = require('supertest');
const app = require('../app');

describe('The express app', () => {
  it('handles a GET request to /api', done => {
    request(app)
      .get('/api')
      .end((err, response) => {
        assert(response.body.hi === 'there');
        done();
      });
  });
});
</code>```

But this second test always fails since its inception:

```<code>const assert = require("assert");
const request = require("supertest");
const mongoose = require("mongoose");
const app = require("../../app");

const Driver = mongoose.model("driver");

describe("Drivers controller", () => {
  it("Post to /api/drivers create a new driver", () => {
    let oldCount;
    return Driver.count()
      .then(count => {
        oldCount = count;
        return new Promise((resolve, reject) => {
          request(app)
            .post("api/drivers")
            .send({ email: "test@test.com" })
            .end((err, res) => {
              if (err) {
                reject(err);
              } else {
                resolve(res);
              }
            });
        });
      })
      .then(() => {
        return Driver.count();
      })
      .then(newCount => {
        assert(oldCount + 1 === newCount);
      });
  });
});
</code>```

The above is the third refactor of it and I am testing this controller:

```<code>const Driver = require("../models/driver");

module.exports = {
  greeting(req, res) {
    res.send({ hi: "there" });
  },

  create(req, res) {
    console.log(req.body);
    const driverProps = req.body;

    Driver.create(driverProps).then(driver => res.send(driver));
  }
};
</code>```

With the original refactor I was getting that the assert(oldCount + 1 === newCount); was returning falsy instead of truthy which was not expected and with the refactor of my test I get a connection refused, but the db is connected I checked with this configuration:

```<code>const express = require("express");
const bodyParser = require("body-parser");
const mongoose = require("mongoose");
const routes = require("./routes/routes");
const app = express();

mongoose.Promise = global.Promise;
mongoose.connect("mongodb://localhost/muber", { useMongoClient: true });

const connection = mongoose.connection;

connection.on("connected", function() {
  console.log("connected to db");
});

app.use(bodyParser.json());
routes(app);

module.exports = app;
</code>```

results in:

[nodemon] starting mocha --recursive -R min   connected to db

1 passing (43ms)   1 failing

1) Drivers controller Post to /api/drivers create a new driver:
       Error: ECONNREFUSED: Connection refused
        at Test.assert (node_modules/supertest/lib/test.js:164:13)
        at Server.assert (node_modules/supertest/lib/test.js:131:12)
        at emitCloseNT (net.js:1600:8)
        at processTicksAndRejections (internal/process/next_tick.js:76:17)

[nodemon] app crashed - waiting for file changes before starting...

Not sure what is going on.

答:
Holy cow, I had to stop the test and stop the mongo database server and restart it then run the test and everything is passing and working as expected:

```<code>  connected to db
{ email: 'test@test.com' }

  2 passing (132ms)

[nodemon] clean exit - waiting for changes before restart
</code>```

The refactor was actually not necessary but I did tweak it a bit when I put it back to:

```<code>describe("Drivers controller", () => {
  it("Post to /api/drivers create a new driver", done => {
    Driver.count().then(count => {
      request(app)
        .post("/api/drivers")
        .send({ email: "test@test.com" })
        .set("Accept", "application/json")
        .expect("Content-Type", /json/)
        .expect(200)
        .end(() => {
          Driver.count().then(newCount => {
            assert(count + 1 === newCount);
            done();
          });
        });
    });
  });
});
</code>```

Body:
I am writing some tests in Mocha and my first test always passes:

const assert = require('assert');
const request = require('supertest');
const app = require('../app');

describe('The express app', () => {
  it('handles a GET request to /api', done => {
    request(app)
      .get('/api')
      .end((err, response) => {
        assert(response.body.hi === 'there');
        done();
      });
  });
});

But this second test always fails since its inception:

const assert = require("assert");
const request = require("supertest");
const mongoose = require("mongoose");
const app = require("../../app");

const Driver = mongoose.model("driver");

describe("Drivers controller", () => {
  it("Post to /api/drivers create a new driver", () => {
    let oldCount;
    return Driver.count()
      .then(count => {
        oldCount = count;
        return new Promise((resolve, reject) => {
          request(app)
            .post("api/drivers")
            .send({ email: "test@test.com" })
            .end((err, res) => {
              if (err) {
                reject(err);
              } else {
                resolve(res);
              }
            });
        });
      })
      .then(() => {
        return Driver.count();
      })
      .then(newCount => {
        assert(oldCount + 1 === newCount);
      });
  });
});

The above is the third refactor of it and I am testing this controller:

const Driver = require("../models/driver");

module.exports = {
  greeting(req, res) {
    res.send({ hi: "there" });
  },

  create(req, res) {
    console.log(req.body);
    const driverProps = req.body;

    Driver.create(driverProps).then(driver => res.send(driver));
  }
};

With the original refactor I was getting that the assert(oldCount + 1 === newCount); was returning falsy instead of truthy which was not expected and with the refactor of my test I get a connection refused, but the db is connected I checked with this configuration:

const express = require("express");
const bodyParser = require("body-parser");
const mongoose = require("mongoose");
const routes = require("./routes/routes");
const app = express();

mongoose.Promise = global.Promise;
mongoose.connect("mongodb://localhost/muber", { useMongoClient: true });

const connection = mongoose.connection;

connection.on("connected", function() {
  console.log("connected to db");
});

app.use(bodyParser.json());
routes(app);

module.exports = app;

results in:

[nodemon] starting mocha --recursive -R min   connected to db

1 passing (43ms)   1 failing

1) Drivers controller Post to /api/drivers create a new driver:
       Error: ECONNREFUSED: Connection refused
        at Test.assert (node_modules/supertest/lib/test.js:164:13)
        at Server.assert (node_modules/supertest/lib/test.js:131:12)
        at emitCloseNT (net.js:1600:8)
        at processTicksAndRejections (internal/process/next_tick.js:76:17)

[nodemon] app crashed - waiting for file changes before starting...

Not sure what is going on.

Body:
Holy cow, I had to stop the test and stop the mongo database server and restart it then run the test and everything is passing and working as expected:

  connected to db
{ email: 'test@test.com' }

  2 passing (132ms)

[nodemon] clean exit - waiting for changes before restart

The refactor was actually not necessary but I did tweak it a bit when I put it back to:

describe("Drivers controller", () => {
  it("Post to /api/drivers create a new driver", done => {
    Driver.count().then(count => {
      request(app)
        .post("/api/drivers")
        .send({ email: "test@test.com" })
        .set("Accept", "application/json")
        .expect("Content-Type", /json/)
        .expect(200)
        .end(() => {
          Driver.count().then(newCount => {
            assert(count + 1 === newCount);
            done();
          });
        });
    });
  });
});


问:
New shell/window in Prism/WPF shows wrong view
Inspired by this answer, I created a general purpose Shell (Prism, WPF) like this:

```<code><Window x:Class="VRMDataLogger.UI.Shell" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:prism="http://prismlibrary.com/" Title="My App" Height="450" Width="800">
    <Grid>
        <ContentControl prism:RegionManager.RegionManager="{Binding RegionManager}" prism:RegionManager.RegionName="MainShellRegion" />
    </Grid>
</Window>
</code>```

```<code>public partial class Shell : Window
{
    public Shell(IRegionManager regionManager, Type contentType)
    {
        RegionManager = regionManager;
        InitializeComponent();
        RegionManager.RegisterViewWithRegion("MainShellRegion", contentType);
    }

    public IRegionManager RegionManager { get; }
}

</code>```

The initial shell gets created in App.CreateShell():

```<code>protected override Window CreateShell()
{
    return new Shell(Container.Resolve<IRegionManager>(), typeof(StartScreen));
}
</code>```

This works fine and the correct view is shown in that initial shell.

I then try to create a second Shell from StartScreenViewModel which shows a different view:

```<code>var shell = new Shell(RegionManager.CreateRegionManager(), typeof(MainScreen));
shell.Show();
</code>```

This opens a new window, but it shows the same view like the first window (StartScreen) instead of MainScreen. What am I doing wrong here?

答:
So I was thinking about getting rid of the region stuff too. But I think what I'll lose by doing so is the nice feature of dependency injection into my view models

Not at all. In fact, you get more control over how your view models are created.

When going view-first, your view model is typically created by the ViewModelLocator upon navigation and then passed NavigationParameters, if any.

If you create your view model manually and bind the view via data templating, you have full control over the creation of the view model. The simplest option is to inject a factory for the view models (like Func<MainScreenViewModel>) and you get full dependency injection from the container.

```<code>internal class StartScreenViewModel
{
    public StartScreenViewModel( Func<MainScreenViewModel> mainScreenViewModelFactory )
    {
        GoToMainScreenCommand = new DelegateCommand( () => new Shell( mainScreenViewModelFactory() ).Show() );
    }

    public DelegateCommand GoToMainScreenCommand { get; }
}
</code>```

Of course, you can use a more sophisticated, hand-crafted factory if need be (see this answer).

Body:
Inspired by this answer, I created a general purpose Shell (Prism, WPF) like this:

<Window x:Class="VRMDataLogger.UI.Shell" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:prism="http://prismlibrary.com/" Title="My App" Height="450" Width="800">
    <Grid>
        <ContentControl prism:RegionManager.RegionManager="{Binding RegionManager}" prism:RegionManager.RegionName="MainShellRegion" />
    </Grid>
</Window>

public partial class Shell : Window
{
    public Shell(IRegionManager regionManager, Type contentType)
    {
        RegionManager = regionManager;
        InitializeComponent();
        RegionManager.RegisterViewWithRegion("MainShellRegion", contentType);
    }

    public IRegionManager RegionManager { get; }
}

The initial shell gets created in App.CreateShell():

protected override Window CreateShell()
{
    return new Shell(Container.Resolve<IRegionManager>(), typeof(StartScreen));
}

This works fine and the correct view is shown in that initial shell.

I then try to create a second Shell from StartScreenViewModel which shows a different view:

var shell = new Shell(RegionManager.CreateRegionManager(), typeof(MainScreen));
shell.Show();

This opens a new window, but it shows the same view like the first window (StartScreen) instead of MainScreen. What am I doing wrong here?

Body:
So I was thinking about getting rid of the region stuff too. But I think what I'll lose by doing so is the nice feature of dependency injection into my view models

Not at all. In fact, you get more control over how your view models are created.

When going view-first, your view model is typically created by the ViewModelLocator upon navigation and then passed NavigationParameters, if any.

If you create your view model manually and bind the view via data templating, you have full control over the creation of the view model. The simplest option is to inject a factory for the view models (like Func<MainScreenViewModel>) and you get full dependency injection from the container.

internal class StartScreenViewModel
{
    public StartScreenViewModel( Func<MainScreenViewModel> mainScreenViewModelFactory )
    {
        GoToMainScreenCommand = new DelegateCommand( () => new Shell( mainScreenViewModelFactory() ).Show() );
    }

    public DelegateCommand GoToMainScreenCommand { get; }
}

Of course, you can use a more sophisticated, hand-crafted factory if need be (see this answer).