问:
Trying to automate data entry on a sap webapp using IE and excel vba
I am able to log in however, I am not able to select any options from there.

Tried reading on UI Automation however couldn' follow, can someone help to code for click

```<code>Dim IE As Object
Dim doc As HTMLDocument

Set IE = CreateObject("InternetExplorer.Application")
IE.Visible = True

IE.navigate "https://website.com/"

Do While IE.Busy
Application.Wait DateAdd("s", 1, Now)
Loop

Set doc = IE.document

IE.document.getElementById("j_username").Value = "user"
doc.getElementById("j_password").Value = "pass"
doc.getElementById("logOnFormSubmit").Click

Do While IE.Busy
Application.Wait DateAdd("s", 10, Now)
Loop

Dim NewTicketBtn As Object
Set NewTicketBtn = doc.getElementById("__tile0-__component0---landingDetail--aboPanel-2")
NewTicketBtn.Click
</code>```

答:
Try this. Read my comments in the macro:</p>

```<code>Sub test()

  Dim IE As Object
  Dim doc As HTMLDocument
  Dim NewTicketBtn As Object

  Set IE = CreateObject("InternetExplorer.Application")
  IE.Visible = True
  IE.navigate "https://website.com/"
  Do While IE.Busy: DoEvents:  Loop

  Set doc = IE.document

  doc.getElementById("j_username").Value = "user"
  doc.getElementById("j_password").Value = "pass"
  doc.getElementById("logOnFormSubmit").Click

  'This don't work here because the ready state of the IE is allready 'complete'
  'Do While IE.Busy
  'Application.Wait DateAdd("s", 10, Now)
  'Loop
  '
  'You must set a manual break for a few seconds to load the page after the login
  'If 3 seconds not enough go higher
  Application.Wait (Now + TimeValue("0:00:03"))

  'Here you can't work anymore with 'doc' because the document in the IE has changed
  Set NewTicketBtn = IE.document.getElementById("__tile0-__component0---landingDetail--aboPanel-2")
  NewTicketBtn.Click
End Sub
</code>```

Body:
I am able to log in however, I am not able to select any options from there.

Tried reading on UI Automation however couldn' follow, can someone help to code for click

Dim IE As Object
Dim doc As HTMLDocument

Set IE = CreateObject("InternetExplorer.Application")
IE.Visible = True

IE.navigate "https://website.com/"

Do While IE.Busy
Application.Wait DateAdd("s", 1, Now)
Loop

Set doc = IE.document

IE.document.getElementById("j_username").Value = "user"
doc.getElementById("j_password").Value = "pass"
doc.getElementById("logOnFormSubmit").Click

Do While IE.Busy
Application.Wait DateAdd("s", 10, Now)
Loop

Dim NewTicketBtn As Object
Set NewTicketBtn = doc.getElementById("__tile0-__component0---landingDetail--aboPanel-2")
NewTicketBtn.Click

Body:
Try this. Read my comments in the macro:

Sub test()

  Dim IE As Object
  Dim doc As HTMLDocument
  Dim NewTicketBtn As Object

  Set IE = CreateObject("InternetExplorer.Application")
  IE.Visible = True
  IE.navigate "https://website.com/"
  Do While IE.Busy: DoEvents:  Loop

  Set doc = IE.document

  doc.getElementById("j_username").Value = "user"
  doc.getElementById("j_password").Value = "pass"
  doc.getElementById("logOnFormSubmit").Click

  'This don't work here because the ready state of the IE is allready 'complete'
  'Do While IE.Busy
  'Application.Wait DateAdd("s", 10, Now)
  'Loop
  '
  'You must set a manual break for a few seconds to load the page after the login
  'If 3 seconds not enough go higher
  Application.Wait (Now + TimeValue("0:00:03"))

  'Here you can't work anymore with 'doc' because the document in the IE has changed
  Set NewTicketBtn = IE.document.getElementById("__tile0-__component0---landingDetail--aboPanel-2")
  NewTicketBtn.Click
End Sub


来源: stackexchange

问:
Find between two string date ranges in spring mongodb
I have Document Person like

```<code>{
  "_id": {
    "$oid": "5e44659dcd"
  },
  "record": {
    "Date_Of_Birth": "9/25/2018"
  },
  "_class": "com.example.entities.Birth"
}
</code>```

Record is of type object, Date_Of_Birth is of type String but Date has been stored in it and I want to execute query to use $gte and $lte operations on that. I am using spring data mongodb. It seems first I have to use $dateFromString to convert it to date, But this seems to be aggregation which I don't think I require.

Below is the code which I have created so far

```<code>Pageable pageable = PageRequest.of(page, size);
Query query = new Query(
        Criteria
                .where("record.Date_Of_Birth").gte(DateOperators.dateFromString(startDate).withFormat("mm/dd/yyyy"))
                .andOperator(Criteria.where("record.Date_Of_Birth").lte(DateOperators.dateFromString(endDate).withFormat("mm/dd/yyyy"))
)).with(pageable);
</code>```

which generates this query

```<code>{ "record.Date_Of_Birth" : { "$gte" : { "value" : { "dateString" : "9/25/2018", "format" : "mm/dd/yyyy"}}}, "$and" : [{ "record.Date_Of_Birth" : { "$lte" : { "value" : { "dateString" : "9/25/2018", "format" : "mm/dd/yyyy"}}}}]}
</code>```

and is not working at all. Any idea?

答:
Since the date format for the document field Date_Of_Birth and the input from-to dates are in string data and are formatted as "MM/dd/yyyy" the comparison will not be correct if used as they are.  There are different ways to handle this issue.

Convert both the date formats to "yyyy/MM/dd" strings and compare or convert both dates to Date objects and compare. Note the sample code shows usage of date values converted to Date objects.

To convert the dates for the find query, the filter will use the Aggregation date or string conversion operators. The find query filter can use Aggregation operators only with the $exproperator.

I could not figure clearly to use $expr with MongoDB Spring-Data APIs (I suspect there is no such API for handling the $expr, but there may be a workaround for that).

The way to run the query clearly is to use an Aggregation. The following are the Mongo Shell and the Spring Data versions.

```<code>db.persons.aggregate( [
  {
      $addFields: {
          matches: {
              $and: [
                  { $gte: [
                      { $dateFromString: { dateString: "$record.Date_Of_Birth", format: "%m/%d/%Y" } },
                       ISODate("2018-09-24T00:00:00.00Z") // input from date
                   ] },
                 { $lte: [
                     { $dateFromString: { dateString: "$record.Date_Of_Birth", format: "%m/%d/%Y" } },
                      ISODate("2018-11-10T00:00:00.00Z") // input to date
                 ] }
              ]
          }
      }
  },
  {
      $match: { matches: true }
  }
] )
</code>```

The Spring-Data Java code:

```<code>// Convert the String input dates to Date objects to be used in the query
String from = "9/24/2018";
String to = "11/10/2018";
DateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy");
Date fromDt = dateFormat.parse(from);
Date toDt = dateFormat.parse(to);

// Build and run the query
MongoOperations mongoOps = new MongoTemplate(MongoClients.create(), "test");
Aggregation agg = newAggregation(
    project("record.Date_Of_Birth")
        .and(Gte.valueOf(DateOperators.DateFromString.fromStringOf("record.Date_Of_Birth").withFormat("%m/%d/%Y"))
            .greaterThanEqualToValue(fromDt))
                .as("matches1")
        .and(Lte.valueOf(DateOperators.DateFromString.fromStringOf("record.Date_Of_Birth").withFormat("%m/%d/%Y"))
            .lessThanEqualToValue(toDt))
              .as("matches2"),
    match(where("matches1").is(true)),
    match(where("matches2").is(true))
);

AggregationResults<Person> results = mongoOps.aggregate(agg, "persons", Person.class);
results.forEach(System.out::println);
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have Document Person like

{
  "_id": {
    "$oid": "5e44659dcd"
  },
  "record": {
    "Date_Of_Birth": "9/25/2018"
  },
  "_class": "com.example.entities.Birth"
}

Record is of type object, Date_Of_Birth is of type String but Date has been stored in it and I want to execute query to use $gte and $lte operations on that. I am using spring data mongodb. It seems first I have to use $dateFromString to convert it to date, But this seems to be aggregation which I don't think I require.

Below is the code which I have created so far

Pageable pageable = PageRequest.of(page, size);
Query query = new Query(
        Criteria
                .where("record.Date_Of_Birth").gte(DateOperators.dateFromString(startDate).withFormat("mm/dd/yyyy"))
                .andOperator(Criteria.where("record.Date_Of_Birth").lte(DateOperators.dateFromString(endDate).withFormat("mm/dd/yyyy"))
)).with(pageable);

which generates this query

{ "record.Date_Of_Birth" : { "$gte" : { "value" : { "dateString" : "9/25/2018", "format" : "mm/dd/yyyy"}}}, "$and" : [{ "record.Date_Of_Birth" : { "$lte" : { "value" : { "dateString" : "9/25/2018", "format" : "mm/dd/yyyy"}}}}]}

and is not working at all. Any idea?

Body:
Since the date format for the document field Date_Of_Birth and the input from-to dates are in string data and are formatted as "MM/dd/yyyy" the comparison will not be correct if used as they are.  There are different ways to handle this issue.

Convert both the date formats to "yyyy/MM/dd" strings and compare or convert both dates to Date objects and compare. Note the sample code shows usage of date values converted to Date objects.

To convert the dates for the find query, the filter will use the Aggregation date or string conversion operators. The find query filter can use Aggregation operators only with the $exproperator.

I could not figure clearly to use $expr with MongoDB Spring-Data APIs (I suspect there is no such API for handling the $expr, but there may be a workaround for that).

The way to run the query clearly is to use an Aggregation. The following are the Mongo Shell and the Spring Data versions.

db.persons.aggregate( [
  {
      $addFields: {
          matches: {
              $and: [
                  { $gte: [
                      { $dateFromString: { dateString: "$record.Date_Of_Birth", format: "%m/%d/%Y" } },
                       ISODate("2018-09-24T00:00:00.00Z") // input from date
                   ] },
                 { $lte: [
                     { $dateFromString: { dateString: "$record.Date_Of_Birth", format: "%m/%d/%Y" } },
                      ISODate("2018-11-10T00:00:00.00Z") // input to date
                 ] }
              ]
          }
      }
  },
  {
      $match: { matches: true }
  }
] )

The Spring-Data Java code:

// Convert the String input dates to Date objects to be used in the query
String from = "9/24/2018";
String to = "11/10/2018";
DateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy");
Date fromDt = dateFormat.parse(from);
Date toDt = dateFormat.parse(to);

// Build and run the query
MongoOperations mongoOps = new MongoTemplate(MongoClients.create(), "test");
Aggregation agg = newAggregation(
    project("record.Date_Of_Birth")
        .and(Gte.valueOf(DateOperators.DateFromString.fromStringOf("record.Date_Of_Birth").withFormat("%m/%d/%Y"))
            .greaterThanEqualToValue(fromDt))
                .as("matches1")
        .and(Lte.valueOf(DateOperators.DateFromString.fromStringOf("record.Date_Of_Birth").withFormat("%m/%d/%Y"))
            .lessThanEqualToValue(toDt))
              .as("matches2"),
    match(where("matches1").is(true)),
    match(where("matches2").is(true))
);

AggregationResults<Person> results = mongoOps.aggregate(agg, "persons", Person.class);
results.forEach(System.out::println);


问:
I don't have access to '/public/assets' using Codeigniter 4 when removing index.php from url using a .htaccess file
I just started using Codeigniter 4 and uploaded the project to a shared hosting. I defined a new sub domain with the local path of /application/public.

I used the default .htaccess to remove index.php from url and it's working but I don't have access to /public/assets. How can I fix this?

This is my .htaccess file:

```<code># Disable directory browsing
Options All -Indexes

# ----------------------------------------------------------------------
# Rewrite engine
# ----------------------------------------------------------------------

# Turning on the rewrite engine is necessary for the following rules and features.
# FollowSymLinks must be enabled for this to work.
<IfModule mod_rewrite.c>
    Options +FollowSymlinks
    RewriteEngine On

    # If you installed CodeIgniter in a subfolder, you will need to
    # change the following line to match the subfolder you need.
    # http://httpd.apache.org/docs/current/mod/mod_rewrite.html#rewritebase
    # RewriteBase /

    # Redirect Trailing Slashes...
    RewriteRule ^(.*)/$ /$1 [L,R=301]

    # Rewrite "www.example.com -> example.com"
    RewriteCond %{HTTPS} !=on
    RewriteCond %{HTTP_HOST} ^www\.(.+)$ [NC]
    RewriteRule ^ http://%1%{REQUEST_URI} [R=301,L]

    # Checks to see if the user is attempting to access a valid file,
    # such as an image or css document, if this isn't true it sends the
    # request to the front controller, index.php
    RewriteCond $1 !^(index\.php|assets|robots\.txt)
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule ^(.*)$ index.php/$1 [L]

    # Ensure Authorization header is passed along
    RewriteCond %{HTTP:Authorization} .
    RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]
</IfModule>

<IfModule !mod_rewrite.c>
    # If we don't have mod_rewrite installed, all 404's
    # can be sent to index.php, and everything works as normal.
    ErrorDocument 404 index.php
</IfModule>

# Disable server signature start
    ServerSignature Off
# Disable server signature end
</code>```

答:
In /public/.htaccess , change:

RewriteRule ^(.*)$ index.php/$1 [L]

to

RewriteRule ^(.*)$ index.php?/$1 [L,QSA]

In app/Config/App.php:

$indexPage = ''; //instead of 'index.php'

$baseUrl ='https://mysubdomain.mydomain.com/'; //slash at the end was important before, not sure now

After that all files and directories in /public/ are actually accessible through web. You may want to limit that with the .htaccess file or just put only stuff that needs to be public.

Body:
I just started using Codeigniter 4 and uploaded the project to a shared hosting. I defined a new sub domain with the local path of /application/public.

I used the default .htaccess to remove index.php from url and it's working but I don't have access to /public/assets. How can I fix this?

This is my .htaccess file:

# Disable directory browsing
Options All -Indexes

# ----------------------------------------------------------------------
# Rewrite engine
# ----------------------------------------------------------------------

# Turning on the rewrite engine is necessary for the following rules and features.
# FollowSymLinks must be enabled for this to work.
<IfModule mod_rewrite.c>
    Options +FollowSymlinks
    RewriteEngine On

    # If you installed CodeIgniter in a subfolder, you will need to
    # change the following line to match the subfolder you need.
    # http://httpd.apache.org/docs/current/mod/mod_rewrite.html#rewritebase
    # RewriteBase /

    # Redirect Trailing Slashes...
    RewriteRule ^(.*)/$ /$1 [L,R=301]

    # Rewrite "www.example.com -> example.com"
    RewriteCond %{HTTPS} !=on
    RewriteCond %{HTTP_HOST} ^www\.(.+)$ [NC]
    RewriteRule ^ http://%1%{REQUEST_URI} [R=301,L]

    # Checks to see if the user is attempting to access a valid file,
    # such as an image or css document, if this isn't true it sends the
    # request to the front controller, index.php
    RewriteCond $1 !^(index\.php|assets|robots\.txt)
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule ^(.*)$ index.php/$1 [L]

    # Ensure Authorization header is passed along
    RewriteCond %{HTTP:Authorization} .
    RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]
</IfModule>

<IfModule !mod_rewrite.c>
    # If we don't have mod_rewrite installed, all 404's
    # can be sent to index.php, and everything works as normal.
    ErrorDocument 404 index.php
</IfModule>

# Disable server signature start
    ServerSignature Off
# Disable server signature end


问:
ES2015 import doesn't work (even at top-level) in Firefox
These are my sample files:

```<code><!DOCTYPE html>
<html>
<head>
  <title>Test</title>
  <script src="t1.js"></script>
</head>
<body></body>
</html>
</code>```

t1.js:

```<code>import Test from 't2.js';
</code>```

t2.js:

```<code>export const Test = console.log("Hello world");
</code>```

When I load the page in Firefox 46, it returns

SyntaxError: import declarations may only appear at top level of a module
```

but I'm not sure how much more top-level the import statement can get here. Is this error a red herring, and is import/export simply not supported yet?

答:
Just using .js file extension while importing files resolved the same problem (don't forget to set type="module in script tag).

Simply write:

```<code>import foo from 'foo.js';
</code>```

instead of

```<code>import foo from 'foo';
</code>```

Body:
These are my sample files:

<!DOCTYPE html>

  <title>Test</title>

t1.js:

import Test from 't2.js';

t2.js:

export const Test = console.log("Hello world");

When I load the page in Firefox 46, it returns

SyntaxError: import declarations may only appear at top level of a module

but I'm not sure how much more top-level the import statement can get here. Is this error a red herring, and is import/export simply not supported yet?

Body:
Just using .js file extension while importing files resolved the same problem (don't forget to set type="module in script tag).

Simply write:

import foo from 'foo.js';

instead of

import foo from 'foo';


问:
Laravel 5.8 check record in the database if exists not working
I got a schedules table and i want it to have any duplicates. If the user puts same datas in the form that has already in the database it will not go to dd('exists') does anyone know what seems to be the problem?

Here is my update

```<code>$schedule = Schedule::findOrFail($id);

$validate = Schedule::where('subject_code_id',$request->subject)
                    ->where('teacher_id',$request->teacher)
                    ->where('room_id',$request->room)
                    ->where('start_time',$request->start_time)
                    ->where('end_time',$request->end_time)
                    ->where('school_year',$request->schoolyr)
                    ->where('day',$request->days)
                    ->where('term',$request->term)
                    ->where('semester',$request->sem)
                    ->count();

if($validate == 1){
          dd('exist');
} else{
            $schedule->update($request->all());
}
</code>```

tried
dd($request->all());
I got

```<code>array:11 [
  "id" => 9
  "term" => "2"
  "semester" => "2"
  "start_time" => "10:30 PM"
  "end_time" => "12:30 AM"
  "scid" => 10
  "teacher_id" => 5
  "room_id" => 6
  "subject_code_id" => 9
  "day" => "SAT"
  "school_year" => "2020"
]
</code>```

答:
Instead of using the count method to determine if any records exist that match your query's constraints, you may use the exists and doesntExist methods:

```<code>$schedule = Schedule::findOrFail($id);

$validate = Schedule::where('subject_code_id',$request->subject)
                ->where('teacher_id',$request->teacher)
                ->where('room_id',$request->room)
                ->where('start_time',$request->start_time)
                ->where('end_time',$request->end_time)
                ->where('school_year',$request->schoolyr)
                ->where('day',$request->days)
                ->where('term',$request->term)
                ->where('semester',$request->sem)
                ->exists();

if($validate){
      dd('exist');
} else{
        $schedule->update($request->all());
}
</code>```

Please visit to see details - aggregates

Body:
I got a schedules table and i want it to have any duplicates. If the user puts same datas in the form that has already in the database it will not go to dd('exists') does anyone know what seems to be the problem?

Here is my update

$schedule = Schedule::findOrFail($id);

$validate = Schedule::where('subject_code_id',$request->subject)
                    ->where('teacher_id',$request->teacher)
                    ->where('room_id',$request->room)
                    ->where('start_time',$request->start_time)
                    ->where('end_time',$request->end_time)
                    ->where('school_year',$request->schoolyr)
                    ->where('day',$request->days)
                    ->where('term',$request->term)
                    ->where('semester',$request->sem)
                    ->count();

if($validate == 1){
          dd('exist');
} else{
            $schedule->update($request->all());
}

tried
dd($request->all());
I got

array:11 [
  "id" => 9
  "term" => "2"
  "semester" => "2"
  "start_time" => "10:30 PM"
  "end_time" => "12:30 AM"
  "scid" => 10
  "teacher_id" => 5
  "room_id" => 6
  "subject_code_id" => 9
  "day" => "SAT"
  "school_year" => "2020"
]

Body:
Instead of using the count method to determine if any records exist that match your query's constraints, you may use the exists and doesntExist methods:

$schedule = Schedule::findOrFail($id);

$validate = Schedule::where('subject_code_id',$request->subject)
                ->where('teacher_id',$request->teacher)
                ->where('room_id',$request->room)
                ->where('start_time',$request->start_time)
                ->where('end_time',$request->end_time)
                ->where('school_year',$request->schoolyr)
                ->where('day',$request->days)
                ->where('term',$request->term)
                ->where('semester',$request->sem)
                ->exists();

if($validate){
      dd('exist');
} else{
        $schedule->update($request->all());
}

Please visit to see details - aggregates


问:
Yarn - remove package best practices
If you want to remove a package using Yarn should you:

run yarn remove [package]

or

delete it from package.json and run yarn install

Do both work the same? Will #2 update yarn.lock?

答:
Best way to remove any package is

```<code>yarn remove "your package name"
</code>```

Your package name should be same as your package.json file

ContentLicense: CC BY-SA 3.0

Title: Yarn - remove package best practices

Body:
Best way to remove any package is

yarn remove "your package name"

Your package name should be same as your package.json file


问:
Android file management
i use the code below to write a file to the sd card and read the content of it:

```<code>try {
        if (root.canWrite())
        {
                File rootdir = Environment.getExternalStorageDirectory();
                File yourFile = new File(rootdir, "tomato50.txt");
                FileWriter filewriter = new FileWriter(file,true);
                BufferedWriter out = new BufferedWriter(filewriter);
            for (int k=0; k<assignArr.size(); k++)
            {
               out.write(assignArr.get(k) + "\n");
               Toast.makeText(MainActivity.this, "out: " + assignArr.get(k), Toast.LENGTH_LONG).show();
            }
            out.close();
          }
          } catch (IOException e) {
          Log.e("TAG", "Could not write file " + e.getMessage());

try {
       File rootdir = Environment.getExternalStorageDirectory();
       File yourFile = new File(rootdir, "tomato50.txt");
       FileReader filereader = new FileReader(yourFile);
       BufferedReader br = new BufferedReader(filereader);
       String line;
       while((line = br.readLine()) != null)
       {
           assignArrBe.add(line);
           Toast.makeText(MainActivity.this, "Read from file: " + line, Toast.LENGTH_LONG).show();
        }
      br.close();
       }
      catch (IOException e)
     {
        e.printStackTrace();
     }
</code>```

Question is: how can i write to the phone memory and read from it?

答:
You will need to root your phone in order to get write access to any phone folder.

If what you want is to write in the app-specific internal storage, then you can follow this guide: http://developer.android.com/guide/topics/data/data-storage.html#filesInternal

Title: Android file management

Body:
i use the code below to write a file to the sd card and read the content of it:

try {
        if (root.canWrite())
        {
                File rootdir = Environment.getExternalStorageDirectory();
                File yourFile = new File(rootdir, "tomato50.txt");
                FileWriter filewriter = new FileWriter(file,true);
                BufferedWriter out = new BufferedWriter(filewriter);
            for (int k=0; k<assignArr.size(); k++)
            {
               out.write(assignArr.get(k) + "\n");
               Toast.makeText(MainActivity.this, "out: " + assignArr.get(k), Toast.LENGTH_LONG).show();
            }
            out.close();
          }
          } catch (IOException e) {
          Log.e("TAG", "Could not write file " + e.getMessage());

try {
       File rootdir = Environment.getExternalStorageDirectory();
       File yourFile = new File(rootdir, "tomato50.txt");
       FileReader filereader = new FileReader(yourFile);
       BufferedReader br = new BufferedReader(filereader);
       String line;
       while((line = br.readLine()) != null)
       {
           assignArrBe.add(line);
           Toast.makeText(MainActivity.this, "Read from file: " + line, Toast.LENGTH_LONG).show();
        }
      br.close();
       }
      catch (IOException e)
     {
        e.printStackTrace();
     }

Question is: how can i write to the phone memory and read from it?


问:
Compiled vs. Interpreted Languages
I'm trying to get a better understanding of the difference. I've found a lot of explanations online, but they tend towards the abstract differences rather than the practical implications.

Most of my programming experiences has been with CPython (dynamic, interpreted), and Java (static, compiled). However, I understand that there are other kinds of interpreted and compiled languages. Aside from the fact that executable files can be distributed from programs written in compiled languages, are there any advantages/disadvantages to each type? Oftentimes, I hear people arguing that interpreted languages can be used interactively, but I believe that compiled languages can have interactive implementations as well, correct?

答:
Short (un-precise) definition:

Compiled language: Entire program is translated to machine code at once, then the machine code is run by the CPU.

Interpreted language: Program is read line-by-line and as soon as a line is read the machine instructions for that line are executed by the CPU.

But really, few languages these days are purely compiled or purely interpreted, it often is a mix. For a more detailed description with pictures, see this thread:

What is the difference between compilation and interpretation?

Or my later blog post:

https://orangejuiceliberationfront.com/the-difference-between-compiler-and-interpreter/

ContentLicense: CC BY-SA 2.5

Title: Compiled vs. Interpreted Languages


问:
Visual Studio 2017 Angular 6 shows "Cannot Get /" First Try Only
I am using Visual Studio 2017 15.8.3 with .Net Core 2.1 and Angular 6. I used the template to create the project and upgraded it from Angular 5 to 6. It ran as expected. I removed the template code and added my own. As I added more code I started getting the Cannot GET/ message; however, if I go into any .ts file and save it, refresh the browser everything reloads and comes up as expected. No errors  ever show. I can't see any issues.

I have this in Startup

```<code>    app.UseSpa(spa =>
    {
        // To learn more about options for serving an Angular SPA from ASP.NET Core,
        // see https://go.microsoft.com/fwlink/?linkid=864501

        spa.Options.SourcePath = "ClientApp";

        if (env.IsDevelopment())
        {
            spa.Options.StartupTimeout = new TimeSpan(0, 0, 360);
            spa.UseAngularCliServer(npmScript: "start");
            spa.UseProxyToSpaDevelopmentServer("https://localhost:4200");
        }
    });
</code>```

I'm stumped.

Thanks,
Paul

答:
In my case, I had "C#" in my folder path</p>

```<code>D:\dev\C#\test_project
</code>```

Body:
I am using Visual Studio 2017 15.8.3 with .Net Core 2.1 and Angular 6. I used the template to create the project and upgraded it from Angular 5 to 6. It ran as expected. I removed the template code and added my own. As I added more code I started getting the Cannot GET/ message; however, if I go into any .ts file and save it, refresh the browser everything reloads and comes up as expected. No errors  ever show. I can't see any issues.

I have this in Startup

    app.UseSpa(spa =>
    {
        // To learn more about options for serving an Angular SPA from ASP.NET Core,
        // see https://go.microsoft.com/fwlink/?linkid=864501

        spa.Options.SourcePath = "ClientApp";

        if (env.IsDevelopment())
        {
            spa.Options.StartupTimeout = new TimeSpan(0, 0, 360);
            spa.UseAngularCliServer(npmScript: "start");
            spa.UseProxyToSpaDevelopmentServer("https://localhost:4200");
        }
    });

I'm stumped.

Thanks,
Paul

Body:
In my case, I had "C#" in my folder path

D:\dev\C#\test_project


问:
Handle concurrent async updates to local state
I have a series of asynchronous calls that read from a local state S, perform some computation based on its current value, and return a new, update value of the local state S'

All this happens at runtime, so I have very little control over the order of these operations. This is a simplified version of what I have.

type State = {
  state: number
}

let localState: State = {
  state: 1000
}

const promiseTimeout = (time: number, value: number) => () => new Promise(
    (resolve: (n: number) => void) => setTimeout(resolve, time, value + time)
  );

const post: (n: number, currentState: State) => Promise<void> = (n, c) => promiseTimeout(n, c.state)()
  .then(res => {
    localState.state = res
    console.log(localState)
  })

post(1000, localState); // localState at call time is 1000
post(3000, localState); // localState at call time is still 1000
// when both promises resolve, the final value of localState will be 4000 instead of 5000
```

<p>Playground link</p>

<p>This model is clearly broken, as both calls to <code>post</code> will read the same value of <code>localState</code>, while instead they should be performed sequentially.</p>

<p>If all calls were already determined at compile time, I could simply have something like</p>

<pre class="lang-js prettyprint-override"><code>post(1000, localState)
  .then(() => post(3000, localState)) // localState at call time is now 2000
</code>```

How would I go about solving this?

答:
One approach is to have post hook into a promise rather than working directly on the state object. That promise could be stored in the state object itself. It starts out fulfilled with the state object. post updates it like this:

```<code>const post = (n, state) => {
    return state.promise = state.promise
        .then(state => {
            // ...do stuff here that updates (or replaces) `state`...
            return state;
        }));
};
</code>```

Here's an example (in JavaScript, but you can add back the type annotations) using asyncAction (it's like your promiseTimeout, but without making it return a function we call immediately; not

"use strict";

let localState = {
    state: 1000
};
localState.promise = Promise.resolve(localState);

// I'm not sure why this *returns* a function that we
// have to call, but...
const promiseTimeout = (time, value) => () => new Promise((resolve) => setTimeout(resolve, time, value + time));

const post = (n, state) => {
    return state.promise = state.promise
        .then(state => promiseTimeout(n, state.state)().then(newValue => {
            state.state = newValue;
            console.log(state.state);
            return state;
        }));
};

console.log("Running...");
post(1000, localState); // localState at call time is 1000
post(3000, localState); // localState at call time is still 1000```
</div>
</div>
</p>

<p>Since each call to <code>post</code> synchronously replaces the promise with a new promise, the chain is built by the calls to <code>post</code>.</p>

<p>Here's that in TypeScript (with a bit of a hack in one place, you can probably improve that); link to the playground.</p>

```type State = {
  state: number,
  promise: Promise<State>
};

let localState: State = (() => {
    const s: Partial<State> = {
        state: 1000
    };
    // There's probably a better way to handle this than type assertions, but...
    s.promise = Promise.resolve(s as State);
    return s as State;
})();

// I'm not sure why this *returns* a function that we
// have to call, but...
const promiseTimeout = (time: number, value: number) => () => new Promise(
    (resolve: (n: number) => void) => setTimeout(resolve, time, value + time)
);

const post = (n: number, state: State): Promise<State> => {
    return state.promise = state.promise
        .then(state => promiseTimeout(n, state.state)().then(newValue => {
            state.state = newValue;
            console.log(state.state);
            return state;
        }));
};

console.log("Running...");
post(1000, localState); // localState at call time is 1000
post(3000, localState); // localState at call time is still 1000
```

It's worth noting that in situations like this where the state can be changed asynchronously like this, it's often worth producing a new state object when changing it rather than modifying the existing one — e.g., treat the state aspects as immutable.

Body:
I have a series of asynchronous calls that read from a local state S, perform some computation based on its current value, and return a new, update value of the local state S'

All this happens at runtime, so I have very little control over the order of these operations. This is a simplified version of what I have.

type State = {
  state: number
}

let localState: State = {
  state: 1000
}

const promiseTimeout = (time: number, value: number) => () => new Promise(
    (resolve: (n: number) => void) => setTimeout(resolve, time, value + time)
  );

const post: (n: number, currentState: State) => Promise<void> = (n, c) => promiseTimeout(n, c.state)()
  .then(res => {
    localState.state = res
    console.log(localState)
  })

post(1000, localState); // localState at call time is 1000
post(3000, localState); // localState at call time is still 1000
// when both promises resolve, the final value of localState will be 4000 instead of 5000

<a href="https://www.typescriptlang.org/play/index.html?ssl=1&ssc=1&pln=23&pc=1#code/C4TwDgpgBAysCGxoF4oG8BQUoGcFIC4oA7AVwFsAjCAJwwF8MMAbCYKZgewGN5m5EEIgKRRUmbHkFEAjAAYFDJt07E8UMDU7kAljggAVHeQidS7VAApgxoSQrUaAGigA3PqTtkqtAJRiAPihLf2Qg4ggAdygABS1dfUssbGCaCBxOZlc7S2Iib0dQoNdOHQATItw2IxMzYEs0jKyIFxsTF3dmTygAaig2iF9k3wBuJgwVNXYwTjwiXPyHWhduUho04mARO23KuO09CAAeEvKgq2IVys0D-RrTc1yVgDopJF8Q5OfgAAsIYga6UC6GS2C4vH4+AgryhYigjVBUEmTWhXAA5pZwXxdsl6EMMDM8JZ5AoXFjIYJRgTZvUAMwKORknjYqFUjBAA" rel="nofollow noreferrer">Playground link

This model is clearly broken, as both calls to post will read the same value of localState, while instead they should be performed sequentially.

If all calls were already determined at compile time, I could simply have something like

post(1000, localState)
  .then(() => post(3000, localState)) // localState at call time is now 2000

How would I go about solving this?

Body:
One approach is to have post hook into a promise rather than working directly on the state object. That promise could be stored in the state object itself. It starts out fulfilled with the state object. post updates it like this:

const post = (n, state) => {
    return state.promise = state.promise
        .then(state => {
            // ...do stuff here that updates (or replaces) `state`...
            return state;
        }));
};

Here's an example (in JavaScript, but you can add back the type annotations) using asyncAction (it's like your promiseTimeout, but without making it return a function we call immediately; not

"use strict";

let localState = {
    state: 1000
};
localState.promise = Promise.resolve(localState);

// I'm not sure why this *returns* a function that we
// have to call, but...
const promiseTimeout = (time, value) => () => new Promise((resolve) => setTimeout(resolve, time, value + time));

const post = (n, state) => {
    return state.promise = state.promise
        .then(state => promiseTimeout(n, state.state)().then(newValue => {
            state.state = newValue;
            console.log(state.state);
            return state;
        }));
};

console.log("Running...");
post(1000, localState); // localState at call time is 1000
post(3000, localState); // localState at call time is still 1000

Since each call to post synchronously replaces the promise with a new promise, the chain is built by the calls to post.

Here's that in TypeScript (with a bit of a hack in one place, you can probably improve that); <a href="https://www.typescriptlang.org/play/index.html?ssl=1&ssc=1&pln=3&pc=1#code/C4TwDgpgBAysCGxoF4oG8BQUoGcFIC4oA7AVwFsAjCAJwBosowaB7cgSxwiIAVWOuAHjiIIAPgwBfANwYMAGwjAo8lgGN48kYVj4UUABQGAlFGRj0jbGpbE8uXvBrB2m4XoupM2Hz7yiiAEYABlCrKBlwgHooqAAVAAtaCAByHCZWSnhKeRAoeChqYCQaKAB3eDzgFigE+GIAE0UoYATOFrriFvBoeBwuZ3ZbHDpC0mAAOinwnAnmNk59PgWuCZoIHBZ5ADcIA3S+3VFjWV914FIaLoP07QhZSWMTWQwYqABJFPISFmUcS+gZQSVTa6QAVOdLnYwfkoAAzUjENQuWwdRDlCCvWJ1XYtGoaeTyUaUcZTCYYGx2ZTzAQQOLscgQFjjMyGFyMohkKi0UbbTSkbgkCjUGimcyGMUWYgQMpQZa0gzhAzrTY7QUGYic4W0SVQbYsdgNXVcYD0xnM4DKjZbXajdkQXn86AAahaDIgxgwJ0YFOG1JY9lQGq13PouD0RDuxl4-EW7lEngs3h8kKu4dEc1jXFZ-iQmZWmN8vgmrQgxH2ejMFhpizNTPGGtGuYgE2bT2MJaS5elZQAak6q5Yi8P03nm6ye-35ALTiPfJTVS3VABzCsZtuzufYVPXPSbouPb2RX12LZLlirgBEACVEcR2MRl2TL96wAHLSFQqNVASo9IoG8P6aHc+TKAS8huoyUDtJ+wQYG+eAGAAzKEwTfuowF6CcAGxEBWiVui4GQdA7R4OwhJQLBGBAA" rel="nofollow noreferrer">link to the playground.

type State = {
  state: number,
  promise: Promise<State>
};

let localState: State = (() => {
    const s: Partial<State> = {
        state: 1000
    };
    // There's probably a better way to handle this than type assertions, but...
    s.promise = Promise.resolve(s as State);
    return s as State;
})();

// I'm not sure why this *returns* a function that we
// have to call, but...
const promiseTimeout = (time: number, value: number) => () => new Promise(
    (resolve: (n: number) => void) => setTimeout(resolve, time, value + time)
);

const post = (n: number, state: State): Promise<State> => {
    return state.promise = state.promise
        .then(state => promiseTimeout(n, state.state)().then(newValue => {
            state.state = newValue;
            console.log(state.state);
            return state;
        }));
};

console.log("Running...");
post(1000, localState); // localState at call time is 1000
post(3000, localState); // localState at call time is still 1000

It's worth noting that in situations like this where the state can be changed asynchronously like this, it's often worth producing a new state object when changing it rather than modifying the existing one — e.g., treat the state aspects as immutable.


问:
How do I setup the dotenv file in Node.js?
I am trying to use the dotenv NPM package and it is not working for me. I have a file config/config.js with the following content:

'use strict';

var dotenv = require('dotenv');
dotenv.load();
console.log('config');
```
<p>I have another file <code>.env</code> at the root of my application folder. I also have an environment variable <code>TWILIO_ACCOUNT_SID</code>.</p>
<p>This is the process I go through while trying to use the environment variables in a certain function:</p>
```$ node
> require('./config/config.js');
config
{}
> process.env.TWILIO_ACCOUNT_SID
undefined
```

I defined the TWILIO_ACCOUNT_SID in my .env file but as soon as I try to output the value in my console, I get an error stating that the variable is undefined.

I will be very grateful for any support in troubleshooting this issue.

答:
I am using NodeJS on windows 10. I used process.env.var-name to access the variables but failed because it gives me windows path variables as a JSON object, so I installed dotenv ( npm install dotenv ). dotenv  gets process envirnoment variables from your project's .evn file

npm install dotenv or yarn add dotenv

const dotenv = require('dotenv');
dotenv.config();

process.env.variable_name

output

Body:
I am trying to use the dotenv NPM package and it is not working for me. I have a file config/config.js with the following content:

'use strict';

var dotenv = require('dotenv');
dotenv.load();
console.log('config');

I have another file .env at the root of my application folder. I also have an environment variable TWILIO_ACCOUNT_SID.

This is the process I go through while trying to use the environment variables in a certain function:

$ node
> require('./config/config.js');
config
{}
> process.env.TWILIO_ACCOUNT_SID
undefined

I defined the TWILIO_ACCOUNT_SID in my .env file but as soon as I try to output the value in my console, I get an error stating that the variable is undefined.

I will be very grateful for any support in troubleshooting this issue.


问:
Having problem while using docker-compose on mysql
I'm having a problem while trying to connect MySQL database using Docker-compose. My app starts until trying to connect to DB through docker while I can connect to the same DB from my IDE.
While I run it from IDE with MySQL running  form Docker I can connect to it, add, delete etc using spring.datasource.url=jdbc:mysql://localhost:3306/exchanger.
But starting my app from docker-compose seem to cause connection errors. I tryied different datasource.url and nothing helps.

Here's my files:

Dockerfile:

```<code>FROM openjdk:8u201-jdk-alpine3.9
ADD target/exchanger-0.0.1-SNAPSHOT.jar .
EXPOSE 8080
CMD java -jar exchanger-0.0.1-SNAPSHOT.jar
</code>```

Docker-compose.yml

```<code>version: '3'
services:

  db:
    container_name: db
    image: mysql
    environment:
      MYSQL_PASSWORD: password
      MYSQL_ROOT_PASSWORD: password
      MYSQL_DATABASE: exchanger
      MYSQL_USER: user
    ports:
      - "3306:3306"
      - "33060:33060"
    restart : always
    volumes:
      - ./mysql-data:/var/lib/mysql

  exchanger:
    build: ./
    ports:
      - "8080:8080"
    depends_on:
      - db

</code>```

application.properties:

```<code>server.port=8080
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL57Dialect
spring.datasource.username=root
spring.datasource.password=password
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://db:3306/exchanger
spring.jpa.show-sql=true
spring.jpa.hibernate.ddl-auto=create-drop
logging.level.org.hibernate.SQL=info
</code>```

console log

```<code>Starting db ... done
Starting exchanger_exchanger_1 ... done
Attaching to db, exchanger_exchanger_1
db           | 2020-02-13 23:28:02+00:00 [Note] [Entrypoint]: Entrypoint script for MySQL Server 8.0.19-1debian9 started.
db           | 2020-02-13 23:28:02+00:00 [Note] [Entrypoint]: Switching to dedicated user 'mysql'
db           | 2020-02-13 23:28:02+00:00 [Note] [Entrypoint]: Entrypoint script for MySQL Server 8.0.19-1debian9 started.
db           | 2020-02-13T23:28:02.638670Z 0 [Warning] [MY-010139] [Server] Changed limits: max_open_files: 1024 (requested 8161)
db           | 2020-02-13T23:28:02.638684Z 0 [Warning] [MY-010142] [Server] Changed limits: table_open_cache: 431 (requested 4000)
db           | 2020-02-13T23:28:02.968321Z 0 [Warning] [MY-011070] [Server] 'Disabling symbolic links using --skip-symbolic-links (or equivalent) is the default. Consider not using this option as it' is deprecated and will be removed in a future release.
db           | 2020-02-13T23:28:02.968508Z 0 [System] [MY-010116] [Server] /usr/sbin/mysqld (mysqld 8.0.19) starting as process 1
db           | 2020-02-13T23:28:05.415554Z 0 [Warning] [MY-010068] [Server] CA certificate ca.pem is self signed.
db           | 2020-02-13T23:28:05.461398Z 0 [Warning] [MY-011810] [Server] Insecure configuration for --pid-file: Location '/var/run/mysqld' in the path is accessible to all OS users. Consider choosing a different directory.
db           | 2020-02-13T23:28:05.504622Z 0 [System] [MY-010931] [Server] /usr/sbin/mysqld: ready for connections. Version: '8.0.19'  socket: '/var/run/mysqld/mysqld.sock'  port: 3306  MySQL Community Server - GPL.
db           | 2020-02-13T23:28:05.777882Z 0 [System] [MY-011323] [Server] X Plugin ready for connections. Socket: '/var/run/mysqld/mysqlx.sock' bind-address: '::' port: 33060
exchanger_1  |
exchanger_1  |   .   ____          _            __ _ _
exchanger_1  |  /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
exchanger_1  | ( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
exchanger_1  |  \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
exchanger_1  |   '  |____| .__|_| |_|_| |_\__, | / / / /
exchanger_1  |  =========|_|==============|___/=/_/_/_/
exchanger_1  |  :: Spring Boot ::        (v2.2.4.RELEASE)
exchanger_1  |
exchanger_1  | 2020-02-13 23:28:06.865  INFO 1 --- [           main] p.e.exchanger.ExchangerApplication       : Starting ExchangerApplication v0.0.1-SNAPSHOT on f2c5f2d1f4c1 with PID 1 (/exchanger-0.0.1-SNAPSHOT.jar started by root in /)
exchanger_1  | 2020-02-13 23:28:06.873  INFO 1 --- [           main] p.e.exchanger.ExchangerApplication       : No active profile set, falling back to default profiles: default
exchanger_1  | 2020-02-13 23:28:09.180  INFO 1 --- [           main] .s.d.r.c.RepositoryConfigurationDelegate : Bootstrapping Spring Data JPA repositories in DEFAULT mode.
exchanger_1  | 2020-02-13 23:28:09.341  INFO 1 --- [           main] .s.d.r.c.RepositoryConfigurationDelegate : Finished Spring Data repository scanning in 138ms. Found 3 JPA repository interfaces.
exchanger_1  | 2020-02-13 23:28:10.311  INFO 1 --- [           main] trationDelegate$BeanPostProcessorChecker : Bean 'org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration' of type [org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
exchanger_1  | 2020-02-13 23:28:10.944  INFO 1 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat initialized with port(s): 8080 (http)
exchanger_1  | 2020-02-13 23:28:10.976  INFO 1 --- [           main] o.apache.catalina.core.StandardService   : Starting service [Tomcat]
exchanger_1  | 2020-02-13 23:28:10.976  INFO 1 --- [           main] org.apache.catalina.core.StandardEngine  : Starting Servlet engine: [Apache Tomcat/9.0.30]
exchanger_1  | 2020-02-13 23:28:11.128  INFO 1 --- [           main] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring embedded WebApplicationContext
exchanger_1  | 2020-02-13 23:28:11.128  INFO 1 --- [           main] o.s.web.context.ContextLoader            : Root WebApplicationContext: initialization completed in 4140 ms
exchanger_1  | 2020-02-13 23:28:11.752  INFO 1 --- [           main] o.hibernate.jpa.internal.util.LogHelper  : HHH000204: Processing PersistenceUnitInfo [name: default]
exchanger_1  | 2020-02-13 23:28:11.911  INFO 1 --- [           main] org.hibernate.Version                    : HHH000412: Hibernate Core {5.4.10.Final}
exchanger_1  | 2020-02-13 23:28:12.181  INFO 1 --- [           main] o.hibernate.annotations.common.Version   : HCANN000001: Hibernate Commons Annotations {5.1.0.Final}
exchanger_1  | 2020-02-13 23:28:12.410  INFO 1 --- [           main] com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Starting...
exchanger_1  | 2020-02-13 23:28:13.660 ERROR 1 --- [           main] com.zaxxer.hikari.pool.HikariPool        : HikariPool-1 - Exception during pool initialization.
exchanger_1  |
exchanger_1  | com.mysql.cj.jdbc.exceptions.CommunicationsException: Communications link failure
exchanger_1  |
exchanger_1  | The last packet sent successfully to the server was 0 milliseconds ago. The driver has not received any packets from the server.
exchanger_1  |  at com.mysql.cj.jdbc.exceptions.SQLError.createCommunicationsException(SQLError.java:174) ~[mysql-connector-java-8.0.19.jar!/:8.0.19]
exchanger_1  |  at com.mysql.cj.jdbc.exceptions.SQLExceptionsMapping.translateException(SQLExceptionsMapping.java:64) ~[mysql-connector-java-8.0.19.jar!/:8.0.19]
exchanger_1  |  at com.mysql.cj.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:836) ~[mysql-connector-java-8.0.19.jar!/:8.0.19]
exchanger_1  |  at com.mysql.cj.jdbc.ConnectionImpl.<init>(ConnectionImpl.java:456) ~[mysql-connector-java-8.0.19.jar!/:8.0.19]
exchanger_1  |  at com.mysql.cj.jdbc.ConnectionImpl.getInstance(ConnectionImpl.java:246) ~[mysql-connector-java-8.0.19.jar!/:8.0.19]
exchanger_1  |  at com.mysql.cj.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:197) ~[mysql-connector-java-8.0.19.jar!/:8.0.19]
exchanger_1  |  at com.zaxxer.hikari.util.DriverDataSource.getConnection(DriverDataSource.java:138) ~[HikariCP-3.4.2.jar!/:na]
exchanger_1  |  at com.zaxxer.hikari.pool.PoolBase.newConnection(PoolBase.java:354) ~[HikariCP-3.4.2.jar!/:na]
exchanger_1  |  at com.zaxxer.hikari.pool.PoolBase.newPoolEntry(PoolBase.java:202) ~[HikariCP-3.4.2.jar!/:na]
exchanger_1  |  at com.zaxxer.hikari.pool.HikariPool.createPoolEntry(HikariPool.java:473) [HikariCP-3.4.2.jar!/:na]
exchanger_1  |  at com.zaxxer.hikari.pool.HikariPool.checkFailFast(HikariPool.java:554) [HikariCP-3.4.2.jar!/:na]
exchanger_1  |  at com.zaxxer.hikari.pool.HikariPool.<init>(HikariPool.java:115) [HikariCP-3.4.2.jar!/:na]
exchanger_1  |  at com.zaxxer.hikari.HikariDataSource.getConnection(HikariDataSource.java:112) [HikariCP-3.4.2.jar!/:na]
exchanger_1  |  at org.hibernate.engine.jdbc.connections.internal.DatasourceConnectionProviderImpl.getConnection(DatasourceConnectionProviderImpl.java:122) [hibernate-core-5.4.10.Final.jar!/:5.4.10.Final]
exchanger_1  |  at org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator$ConnectionProviderJdbcConnectionAccess.obtainConnection(JdbcEnvironmentInitiator.java:180) [hibernate-core-5.4.10.Final.jar!/:5.4.10.Final]
...
</code>```

答:
I've solved the problem,

The problem occured during setting up database for first time. I thikn something went wrong while creating MySQL database and the whole volume ./myslq-data was wrong.

I've just deleted catalog mysql-data and created run docker-compose again. It created volume again and working great.

Body:
I'm having a problem while trying to connect MySQL database using Docker-compose. My app starts until trying to connect to DB through docker while I can connect to the same DB from my IDE.
While I run it from IDE with MySQL running  form Docker I can connect to it, add, delete etc using spring.datasource.url=jdbc:mysql://localhost:3306/exchanger.
But starting my app from docker-compose seem to cause connection errors. I tryied different datasource.url and nothing helps.

Here's my files:

Dockerfile:

FROM openjdk:8u201-jdk-alpine3.9
ADD target/exchanger-0.0.1-SNAPSHOT.jar .
EXPOSE 8080
CMD java -jar exchanger-0.0.1-SNAPSHOT.jar

Docker-compose.yml

version: '3'
services:

  db:
    container_name: db
    image: mysql
    environment:
      MYSQL_PASSWORD: password
      MYSQL_ROOT_PASSWORD: password
      MYSQL_DATABASE: exchanger
      MYSQL_USER: user
    ports:
      - "3306:3306"
      - "33060:33060"
    restart : always
    volumes:
      - ./mysql-data:/var/lib/mysql

  exchanger:
    build: ./
    ports:
      - "8080:8080"
    depends_on:
      - db

application.properties:

server.port=8080
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL57Dialect
spring.datasource.username=root
spring.datasource.password=password
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://db:3306/exchanger
spring.jpa.show-sql=true
spring.jpa.hibernate.ddl-auto=create-drop
logging.level.org.hibernate.SQL=info

console log

Starting db ... done
Starting exchanger_exchanger_1 ... done
Attaching to db, exchanger_exchanger_1
db           | 2020-02-13 23:28:02+00:00 [Note] [Entrypoint]: Entrypoint script for MySQL Server 8.0.19-1debian9 started.
db           | 2020-02-13 23:28:02+00:00 [Note] [Entrypoint]: Switching to dedicated user 'mysql'
db           | 2020-02-13 23:28:02+00:00 [Note] [Entrypoint]: Entrypoint script for MySQL Server 8.0.19-1debian9 started.
db           | 2020-02-13T23:28:02.638670Z 0 [Warning] [MY-010139] [Server] Changed limits: max_open_files: 1024 (requested 8161)
db           | 2020-02-13T23:28:02.638684Z 0 [Warning] [MY-010142] [Server] Changed limits: table_open_cache: 431 (requested 4000)
db           | 2020-02-13T23:28:02.968321Z 0 [Warning] [MY-011070] [Server] 'Disabling symbolic links using --skip-symbolic-links (or equivalent) is the default. Consider not using this option as it' is deprecated and will be removed in a future release.
db           | 2020-02-13T23:28:02.968508Z 0 [System] [MY-010116] [Server] /usr/sbin/mysqld (mysqld 8.0.19) starting as process 1
db           | 2020-02-13T23:28:05.415554Z 0 [Warning] [MY-010068] [Server] CA certificate ca.pem is self signed.
db           | 2020-02-13T23:28:05.461398Z 0 [Warning] [MY-011810] [Server] Insecure configuration for --pid-file: Location '/var/run/mysqld' in the path is accessible to all OS users. Consider choosing a different directory.
db           | 2020-02-13T23:28:05.504622Z 0 [System] [MY-010931] [Server] /usr/sbin/mysqld: ready for connections. Version: '8.0.19'  socket: '/var/run/mysqld/mysqld.sock'  port: 3306  MySQL Community Server - GPL.
db           | 2020-02-13T23:28:05.777882Z 0 [System] [MY-011323] [Server] X Plugin ready for connections. Socket: '/var/run/mysqld/mysqlx.sock' bind-address: '::' port: 33060
exchanger_1  |
exchanger_1  |   .   ____          _            __ _ _
exchanger_1  |  /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
exchanger_1  | ( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
exchanger_1  |  \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
exchanger_1  |   '  |____| .__|_| |_|_| |_\__, | / / / /
exchanger_1  |  =========|_|==============|___/=/_/_/_/
exchanger_1  |  :: Spring Boot ::        (v2.2.4.RELEASE)
exchanger_1  |
exchanger_1  | 2020-02-13 23:28:06.865  INFO 1 --- [           main] p.e.exchanger.ExchangerApplication       : Starting ExchangerApplication v0.0.1-SNAPSHOT on f2c5f2d1f4c1 with PID 1 (/exchanger-0.0.1-SNAPSHOT.jar started by root in /)
exchanger_1  | 2020-02-13 23:28:06.873  INFO 1 --- [           main] p.e.exchanger.ExchangerApplication       : No active profile set, falling back to default profiles: default
exchanger_1  | 2020-02-13 23:28:09.180  INFO 1 --- [           main] .s.d.r.c.RepositoryConfigurationDelegate : Bootstrapping Spring Data JPA repositories in DEFAULT mode.
exchanger_1  | 2020-02-13 23:28:09.341  INFO 1 --- [           main] .s.d.r.c.RepositoryConfigurationDelegate : Finished Spring Data repository scanning in 138ms. Found 3 JPA repository interfaces.
exchanger_1  | 2020-02-13 23:28:10.311  INFO 1 --- [           main] trationDelegate$BeanPostProcessorChecker : Bean 'org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration' of type [org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
exchanger_1  | 2020-02-13 23:28:10.944  INFO 1 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat initialized with port(s): 8080 (http)
exchanger_1  | 2020-02-13 23:28:10.976  INFO 1 --- [           main] o.apache.catalina.core.StandardService   : Starting service [Tomcat]
exchanger_1  | 2020-02-13 23:28:10.976  INFO 1 --- [           main] org.apache.catalina.core.StandardEngine  : Starting Servlet engine: [Apache Tomcat/9.0.30]
exchanger_1  | 2020-02-13 23:28:11.128  INFO 1 --- [           main] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring embedded WebApplicationContext
exchanger_1  | 2020-02-13 23:28:11.128  INFO 1 --- [           main] o.s.web.context.ContextLoader            : Root WebApplicationContext: initialization completed in 4140 ms
exchanger_1  | 2020-02-13 23:28:11.752  INFO 1 --- [           main] o.hibernate.jpa.internal.util.LogHelper  : HHH000204: Processing PersistenceUnitInfo [name: default]
exchanger_1  | 2020-02-13 23:28:11.911  INFO 1 --- [           main] org.hibernate.Version                    : HHH000412: Hibernate Core {5.4.10.Final}
exchanger_1  | 2020-02-13 23:28:12.181  INFO 1 --- [           main] o.hibernate.annotations.common.Version   : HCANN000001: Hibernate Commons Annotations {5.1.0.Final}
exchanger_1  | 2020-02-13 23:28:12.410  INFO 1 --- [           main] com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Starting...
exchanger_1  | 2020-02-13 23:28:13.660 ERROR 1 --- [           main] com.zaxxer.hikari.pool.HikariPool        : HikariPool-1 - Exception during pool initialization.
exchanger_1  |
exchanger_1  | com.mysql.cj.jdbc.exceptions.CommunicationsException: Communications link failure
exchanger_1  |
exchanger_1  | The last packet sent successfully to the server was 0 milliseconds ago. The driver has not received any packets from the server.
exchanger_1  |  at com.mysql.cj.jdbc.exceptions.SQLError.createCommunicationsException(SQLError.java:174) ~[mysql-connector-java-8.0.19.jar!/:8.0.19]
exchanger_1  |  at com.mysql.cj.jdbc.exceptions.SQLExceptionsMapping.translateException(SQLExceptionsMapping.java:64) ~[mysql-connector-java-8.0.19.jar!/:8.0.19]
exchanger_1  |  at com.mysql.cj.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:836) ~[mysql-connector-java-8.0.19.jar!/:8.0.19]
exchanger_1  |  at com.mysql.cj.jdbc.ConnectionImpl.<init>(ConnectionImpl.java:456) ~[mysql-connector-java-8.0.19.jar!/:8.0.19]
exchanger_1  |  at com.mysql.cj.jdbc.ConnectionImpl.getInstance(ConnectionImpl.java:246) ~[mysql-connector-java-8.0.19.jar!/:8.0.19]
exchanger_1  |  at com.mysql.cj.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:197) ~[mysql-connector-java-8.0.19.jar!/:8.0.19]
exchanger_1  |  at com.zaxxer.hikari.util.DriverDataSource.getConnection(DriverDataSource.java:138) ~[HikariCP-3.4.2.jar!/:na]
exchanger_1  |  at com.zaxxer.hikari.pool.PoolBase.newConnection(PoolBase.java:354) ~[HikariCP-3.4.2.jar!/:na]
exchanger_1  |  at com.zaxxer.hikari.pool.PoolBase.newPoolEntry(PoolBase.java:202) ~[HikariCP-3.4.2.jar!/:na]
exchanger_1  |  at com.zaxxer.hikari.pool.HikariPool.createPoolEntry(HikariPool.java:473) [HikariCP-3.4.2.jar!/:na]
exchanger_1  |  at com.zaxxer.hikari.pool.HikariPool.checkFailFast(HikariPool.java:554) [HikariCP-3.4.2.jar!/:na]
exchanger_1  |  at com.zaxxer.hikari.pool.HikariPool.<init>(HikariPool.java:115) [HikariCP-3.4.2.jar!/:na]
exchanger_1  |  at com.zaxxer.hikari.HikariDataSource.getConnection(HikariDataSource.java:112) [HikariCP-3.4.2.jar!/:na]
exchanger_1  |  at org.hibernate.engine.jdbc.connections.internal.DatasourceConnectionProviderImpl.getConnection(DatasourceConnectionProviderImpl.java:122) [hibernate-core-5.4.10.Final.jar!/:5.4.10.Final]
exchanger_1  |  at org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator$ConnectionProviderJdbcConnectionAccess.obtainConnection(JdbcEnvironmentInitiator.java:180) [hibernate-core-5.4.10.Final.jar!/:5.4.10.Final]
...


问:
checking if a database exists
The code below works fine except it throws a warning when connecting to a database that does not exist. This works fine in product where errors are off, but I would rather not have errors if I don't need to.</p>

```<code>function cpanel_db_connect($dbname) {
    // normalize
    $dbname = convert_to_slug($dbname);
    $dbname = CPANEL_USER . '_' . $dbname;

    $dbuser = CPANEL_USER . '_' . CPANEL_DB_USER;

    // connnect database
    $mysqli = new mysqli(CPANEL_DB_HOST, $dbuser, CPANEL_DB_PASS, $dbname);

    if ($mysqli->connect_error) {
        return false;
    }

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

答:
```<code>$mysqli = @new mysqli(CPANEL_DB_HOST, $dbuser, CPANEL_DB_PASS, $dbname);
</code>```

The above works!

Title: checking if a database exists

Body:
The code below works fine except it throws a warning when connecting to a database that does not exist. This works fine in product where errors are off, but I would rather not have errors if I don't need to.

function cpanel_db_connect($dbname) {
    // normalize
    $dbname = convert_to_slug($dbname);
    $dbname = CPANEL_USER . '_' . $dbname;

    $dbuser = CPANEL_USER . '_' . CPANEL_DB_USER;

    // connnect database
    $mysqli = new mysqli(CPANEL_DB_HOST, $dbuser, CPANEL_DB_PASS, $dbname);

    if ($mysqli->connect_error) {
        return false;
    }

    return $mysqli;
}

Body:
$mysqli = @new mysqli(CPANEL_DB_HOST, $dbuser, CPANEL_DB_PASS, $dbname);

The above works!


问:
troubles connecting to a (remote) PostgreSQL database using FireDAC & Delphi 10.3.3
Using Delphi 10.3.3 I need to access a Postgress database on a remote server. I am trying using FireDac. I am not able to connect to the remote database, so I thought to create a testprog and a local PostgreSQL-database first. So I installed PostgreSQL 32 bit on my machine. Copied the libpq.dll to the same location as my exe, copied the libpq.dll to Windows\System32 as well. Checked the PATH, System32 is there. But still I get "Cannot load vendor library (libpq.dll). The specified module could not be found"

I tried 64 bit versions as well, I found different versions of the libpq.dll which I tried without success.

Do you have any experience in how to solve this ?
If you have the latest libpq.dll, does the remote database version matter ? I am new to PostgreSQL, how can I find the version ?

答: Just libpq.dll is not enough, you need other DLLs. You will find the full list here.</p>


问:
pdfLaTeX epstopdf converts all text to monotype font
When including .eps files with \includegraphics and compiling with pdfLaTeX, I get all fonts in monotype font even though the original .eps file has another font specified, e.g. Helvetica or Arial. I've tested both Helvetica and Arial (the latter of which is installed on my Windows 10 system) to make sure it wasn't an issue of whether the font is installed.

Here are the two example eps files I'm using to test it:

https://github.com/skhiggins/test_epstopdf/blob/master/sample_eps_arial.eps

https://github.com/skhiggins/test_epstopdf/blob/master/sample_eps_helvetica.eps

Opening the .eps files in a text editor, I confirmed they declare the fonts as Helvetica and Arial, respectively, using e.g. %%DocumentNeededResources: font Arial. If I open the .eps files using gsview they appear correctly. However, when I compile a pdf in LaTeX the font of the graphs is monotype. (If I run epstopdf in the command line, I also get monotype font.) Here is the LaTeX code that I compile with pdflatex.exe:

```<code>\documentclass[12pt]{article}
\usepackage{graphicx}
\usepackage{epstopdf}

\begin{document}

\includegraphics[width=\textwidth]{sample_eps_helvetica.eps}
\includegraphics[width=\textwidth]{sample_eps_arial.eps}

\end{document}
</code>```

Both graphics appear in the pdf as follows, with a monotype font :

I already tried the obvious things like uninstalling and reinstalling MiKTeX. Here is the log:

```<code>This is pdfTeX, Version 3.14159265-2.6-1.40.20 (MiKTeX 2.9.7250 64-bit) (preloaded format=pdflatex 2020.1.10)  10 JAN 2020 10:12
entering extended mode
**C:/Dropbox/Latex_code/test_epstopdf/epstopdf_MWE.tex
(C:/Dropbox/Latex_code/test_epstopdf/epstopdf_MWE.tex
LaTeX2e <2019-10-01> patch level 3
("C:\Dropbox\Programs\MiKTeX 2.9\tex/latex/base\article.cls"
Document Class: article 2019/10/25 v1.4k Standard LaTeX document class
("C:\Dropbox\Programs\MiKTeX 2.9\tex/latex/base\size12.clo"
File: size12.clo 2019/10/25 v1.4k Standard LaTeX file (size option)
)
\c@part=\count80
\c@section=\count81
\c@subsection=\count82
\c@subsubsection=\count83
\c@paragraph=\count84
\c@subparagraph=\count85
\c@figure=\count86
\c@table=\count87
\abovecaptionskip=\skip41
\belowcaptionskip=\skip42
\bibindent=\dimen102
) ("C:\Dropbox\Programs\MiKTeX 2.9\tex/latex/graphics\graphicx.sty"
Package: graphicx 2017/06/01 v1.1a Enhanced LaTeX Graphics (DPC,SPQR)
("C:\Dropbox\Programs\MiKTeX 2.9\tex/latex/graphics\keyval.sty"
Package: keyval 2014/10/28 v1.15 key=value parser (DPC)
\KV@toks@=\toks14
) ("C:\Dropbox\Programs\MiKTeX 2.9\tex/latex/graphics\graphics.sty"
Package: graphics 2019/11/01 v1.3d Standard LaTeX Graphics (DPC,SPQR)
("C:\Dropbox\Programs\MiKTeX 2.9\tex/latex/graphics\trig.sty"
Package: trig 2016/01/03 v1.10 sin cos tan (DPC)
) ("C:\Dropbox\Programs\MiKTeX 2.9\tex/latex/graphics-cfg\graphics.cfg"
File: graphics.cfg 2016/06/04 v1.11 sample graphics configuration
)
Package graphics Info: Driver file: pdftex.def on input line 105.
("C:\Dropbox\Programs\MiKTeX 2.9\tex/latex/graphics-def\pdftex.def"
File: pdftex.def 2018/01/08 v1.0l Graphics/color driver for pdftex
))
\Gin@req@height=\dimen103
\Gin@req@width=\dimen104
) ("C:\Dropbox\Programs\MiKTeX 2.9\tex/latex/epstopdf-pkg\epstopdf.sty"
Package: epstopdf 2019/11/24 v2.7 Conversion with epstopdf on the fly (HO)
("C:\Dropbox\Programs\MiKTeX 2.9\tex/latex/epstopdf-pkg\epstopdf-base.sty"
Package: epstopdf-base 2019/11/24 v2.7 Base part for package epstopdf
("C:\Dropbox\Programs\MiKTeX 2.9\tex/generic/oberdiek\infwarerr.sty"
Package: infwarerr 2016/05/16 v1.4 Providing info/warning/error messages (HO)
) ("C:\Dropbox\Programs\MiKTeX 2.9\tex/latex/oberdiek\grfext.sty"
Package: grfext 2016/05/16 v1.2 Manage graphics extensions (HO)
("C:\Dropbox\Programs\MiKTeX 2.9\tex/generic/oberdiek\kvdefinekeys.sty"
Package: kvdefinekeys 2016/05/16 v1.4 Define keys (HO)
("C:\Dropbox\Programs\MiKTeX 2.9\tex/generic/oberdiek\ltxcmds.sty"
Package: ltxcmds 2016/05/16 v1.23 LaTeX kernel commands for general use (HO)
))) ("C:\Dropbox\Programs\MiKTeX 2.9\tex/latex/oberdiek\kvoptions.sty"
Package: kvoptions 2016/05/16 v3.12 Key value format for package options (HO)
("C:\Dropbox\Programs\MiKTeX 2.9\tex/generic/oberdiek\kvsetkeys.sty"
Package: kvsetkeys 2016/05/16 v1.17 Key value parser (HO)
("C:\Dropbox\Programs\MiKTeX 2.9\tex/generic/oberdiek\etexcmds.sty"
Package: etexcmds 2016/05/16 v1.6 Avoid name clashes with e-TeX commands (HO)
("C:\Dropbox\Programs\MiKTeX 2.9\tex/generic/iftex\ifluatex.sty"
Package: ifluatex 2019/10/25 v1.5 ifluatex legacy package. Use iftex instead.
("C:\Dropbox\Programs\MiKTeX 2.9\tex/generic/iftex\iftex.sty"
Package: iftex 2019/11/07 v1.0c TeX engine tests
))))) ("C:\Dropbox\Programs\MiKTeX 2.9\tex/latex/pdftexcmds\pdftexcmds.sty"
Package: pdftexcmds 2019/11/24 v0.31 Utility functions of pdfTeX for LuaTeX (HO
)
Package pdftexcmds Info: \pdf@primitive is available.
Package pdftexcmds Info: \pdf@ifprimitive is available.
Package pdftexcmds Info: \pdfdraftmode found.
)
Package epstopdf-base Info: Redefining graphics rule for `.eps' on input line 4
42.
Package grfext Info: Graphics extension search list:
(grfext)             [.pdf,.png,.jpg,.mps,.jpeg,.jbig2,.jb2,.PDF,.PNG,.JPG,.JPE
G,.JBIG2,.JB2,.eps]
(grfext)             \AppendGraphicsExtensions on input line 460.
)) (C:\Dropbox\Latex_code\test_epstopdf\build\epstopdf_MWE.aux)
\openout1 = `epstopdf_MWE.aux'.

LaTeX Font Info:    Checking defaults for OML/cmm/m/it on input line 7.
LaTeX Font Info:    ... okay on input line 7.
LaTeX Font Info:    Checking defaults for T1/cmr/m/n on input line 7.
LaTeX Font Info:    ... okay on input line 7.
LaTeX Font Info:    Checking defaults for OT1/cmr/m/n on input line 7.
LaTeX Font Info:    ... okay on input line 7.
LaTeX Font Info:    Checking defaults for OMS/cmsy/m/n on input line 7.
LaTeX Font Info:    ... okay on input line 7.
LaTeX Font Info:    Checking defaults for OMX/cmex/m/n on input line 7.
LaTeX Font Info:    ... okay on input line 7.
LaTeX Font Info:    Checking defaults for U/cmr/m/n on input line 7.
LaTeX Font Info:    ... okay on input line 7.
("C:\Dropbox\Programs\MiKTeX 2.9\tex/context/base/mkii\supp-pdf.mkii"
[Loading MPS to PDF converter (version 2006.09.02).]
\scratchcounter=\count88
\scratchdimen=\dimen105
\scratchbox=\box27
\nofMPsegments=\count89
\nofMParguments=\count90
\everyMPshowfont=\toks15
\MPscratchCnt=\count91
\MPscratchDim=\dimen106
\MPnumerator=\count92
\makeMPintoPDFobject=\count93
\everyMPtoPDFconversion=\toks16
)
Package epstopdf Info: Source file: <sample_eps_helvetica.eps>
(epstopdf)                    date: 2020-01-10 10:10:40
(epstopdf)                    size: 13204 bytes
(epstopdf)             Output file: <sample_eps_helvetica-eps-converted-to.pdf>

(epstopdf)                    date: 2020-01-10 10:12:32
(epstopdf)                    size: 11003 bytes
(epstopdf)             Command: <epstopdf --outfile=sample_eps_helvetica-eps-co
nverted-to.pdf sample_eps_helvetica.eps>
(epstopdf)             \includegraphics on input line 9.
Package epstopdf Info: Output file is already uptodate.

pdfTeX warning: pdflatex.exe (file ./sample_eps_helvetica-eps-converted-to.pdf)
: PDF inclusion: found PDF version <1.7>, but at most version <1.5> allowed
<sample_eps_helvetica-eps-converted-to.pdf, id=1, 397.485pt x 289.08pt>
File: sample_eps_helvetica-eps-converted-to.pdf Graphic file (type pdf)
<use sample_eps_helvetica-eps-converted-to.pdf>
Package pdftex.def Info: sample_eps_helvetica-eps-converted-to.pdf  used on inp
ut line 9.
(pdftex.def)             Requested size: 390.0pt x 283.64493pt.
Package epstopdf Info: Source file: <sample_eps_arial.eps>
(epstopdf)                    date: 2020-01-10 10:10:40
(epstopdf)                    size: 13200 bytes
(epstopdf)             Output file: <sample_eps_arial-eps-converted-to.pdf>
(epstopdf)                    date: 2020-01-10 10:12:33
(epstopdf)                    size: 11003 bytes
(epstopdf)             Command: <epstopdf --outfile=sample_eps_arial-eps-conver
ted-to.pdf sample_eps_arial.eps>
(epstopdf)             \includegraphics on input line 10.
Package epstopdf Info: Output file is already uptodate.

pdfTeX warning: pdflatex.exe (file ./sample_eps_arial-eps-converted-to.pdf): PD
F inclusion: found PDF version <1.7>, but at most version <1.5> allowed
<sample_eps_arial-eps-converted-to.pdf, id=2, 397.485pt x 289.08pt>
File: sample_eps_arial-eps-converted-to.pdf Graphic file (type pdf)
<use sample_eps_arial-eps-converted-to.pdf>
Package pdftex.def Info: sample_eps_arial-eps-converted-to.pdf  used on input l
ine 10.
(pdftex.def)             Requested size: 390.0pt x 283.64493pt.

Overfull \hbox (17.62482pt too wide) in paragraph at lines 9--11
[][]
 []

[1

{C:/Users/Sean Higgins/AppData/Local/MiKTeX/2.9/pdftex/config/pdftex.map} <./sa
mple_eps_helvetica-eps-converted-to.pdf>] [2 <./sample_eps_arial-eps-converted-
to.pdf>] (C:\Dropbox\Latex_code\test_epstopdf\build\epstopdf_MWE.aux) )
Here is how much of TeX's memory you used:
 1503 strings out of 492484
 22174 string characters out of 3129678
 82863 words of memory out of 3000000
 5860 multiletter control sequences out of 15000+200000
 3938 words of font info for 15 fonts, out of 3000000 for 9000
 1141 hyphenation exceptions out of 8191
 57i,4n,32p,365b,115s stack positions out of 5000i,500n,10000p,200000b,50000s
<C:/Drop
box/Programs/MiKTeX 2.9/fonts/type1/public/amsfonts/cm/cmr12.pfb>
Output written on C:\Dropbox\Latex_code\test_epstopdf\build\epstopdf_MWE.pdf (2
 pages, 27497 bytes).
PDF statistics:
 25 PDF objects out of 1000 (max. 8388607)
 0 named destinations out of 1000 (max. 500000)
 11 words of extra memory for PDF output out of 10000 (max. 10000000)
</code>```

答: I had the same problem, I don't know the reason, but the solution for me was to reinstall Miktex to the previous version (basic-miktex-2.9.6850-x64).</p>

Body:
When including .eps files with \includegraphics and compiling with pdfLaTeX, I get all fonts in monotype font even though the original .eps file has another font specified, e.g. Helvetica or Arial. I've tested both Helvetica and Arial (the latter of which is installed on my Windows 10 system) to make sure it wasn't an issue of whether the font is installed.

Here are the two example eps files I'm using to test it:

https://github.com/skhiggins/test_epstopdf/blob/master/sample_eps_arial.eps

https://github.com/skhiggins/test_epstopdf/blob/master/sample_eps_helvetica.eps

Opening the .eps files in a text editor, I confirmed they declare the fonts as Helvetica and Arial, respectively, using e.g. %%DocumentNeededResources: font Arial. If I open the .eps files using gsview they appear correctly. However, when I compile a pdf in LaTeX the font of the graphs is monotype. (If I run epstopdf in the command line, I also get monotype font.) Here is the LaTeX code that I compile with pdflatex.exe:

\documentclass[12pt]{article}
\usepackage{graphicx}
\usepackage{epstopdf}

\begin{document}

\includegraphics[width=\textwidth]{sample_eps_helvetica.eps}
\includegraphics[width=\textwidth]{sample_eps_arial.eps}

\end{document}

Both graphics appear in the pdf as follows, with a monotype font :

I already tried the obvious things like uninstalling and reinstalling MiKTeX. Here is the log:

This is pdfTeX, Version 3.14159265-2.6-1.40.20 (MiKTeX 2.9.7250 64-bit) (preloaded format=pdflatex 2020.1.10)  10 JAN 2020 10:12
entering extended mode
**C:/Dropbox/Latex_code/test_epstopdf/epstopdf_MWE.tex
(C:/Dropbox/Latex_code/test_epstopdf/epstopdf_MWE.tex
LaTeX2e <2019-10-01> patch level 3
("C:\Dropbox\Programs\MiKTeX 2.9\tex/latex/base\article.cls"
Document Class: article 2019/10/25 v1.4k Standard LaTeX document class
("C:\Dropbox\Programs\MiKTeX 2.9\tex/latex/base\size12.clo"
File: size12.clo 2019/10/25 v1.4k Standard LaTeX file (size option)
)
\c@part=\count80
\c@section=\count81
\c@subsection=\count82
\c@subsubsection=\count83
\c@paragraph=\count84
\c@subparagraph=\count85
\c@figure=\count86
\c@table=\count87
\abovecaptionskip=\skip41
\belowcaptionskip=\skip42
\bibindent=\dimen102
) ("C:\Dropbox\Programs\MiKTeX 2.9\tex/latex/graphics\graphicx.sty"
Package: graphicx 2017/06/01 v1.1a Enhanced LaTeX Graphics (DPC,SPQR)
("C:\Dropbox\Programs\MiKTeX 2.9\tex/latex/graphics\keyval.sty"
Package: keyval 2014/10/28 v1.15 key=value parser (DPC)
\KV@toks@=\toks14
) ("C:\Dropbox\Programs\MiKTeX 2.9\tex/latex/graphics\graphics.sty"
Package: graphics 2019/11/01 v1.3d Standard LaTeX Graphics (DPC,SPQR)
("C:\Dropbox\Programs\MiKTeX 2.9\tex/latex/graphics\trig.sty"
Package: trig 2016/01/03 v1.10 sin cos tan (DPC)
) ("C:\Dropbox\Programs\MiKTeX 2.9\tex/latex/graphics-cfg\graphics.cfg"
File: graphics.cfg 2016/06/04 v1.11 sample graphics configuration
)
Package graphics Info: Driver file: pdftex.def on input line 105.
("C:\Dropbox\Programs\MiKTeX 2.9\tex/latex/graphics-def\pdftex.def"
File: pdftex.def 2018/01/08 v1.0l Graphics/color driver for pdftex
))
\Gin@req@height=\dimen103
\Gin@req@width=\dimen104
) ("C:\Dropbox\Programs\MiKTeX 2.9\tex/latex/epstopdf-pkg\epstopdf.sty"
Package: epstopdf 2019/11/24 v2.7 Conversion with epstopdf on the fly (HO)
("C:\Dropbox\Programs\MiKTeX 2.9\tex/latex/epstopdf-pkg\epstopdf-base.sty"
Package: epstopdf-base 2019/11/24 v2.7 Base part for package epstopdf
("C:\Dropbox\Programs\MiKTeX 2.9\tex/generic/oberdiek\infwarerr.sty"
Package: infwarerr 2016/05/16 v1.4 Providing info/warning/error messages (HO)
) ("C:\Dropbox\Programs\MiKTeX 2.9\tex/latex/oberdiek\grfext.sty"
Package: grfext 2016/05/16 v1.2 Manage graphics extensions (HO)
("C:\Dropbox\Programs\MiKTeX 2.9\tex/generic/oberdiek\kvdefinekeys.sty"
Package: kvdefinekeys 2016/05/16 v1.4 Define keys (HO)
("C:\Dropbox\Programs\MiKTeX 2.9\tex/generic/oberdiek\ltxcmds.sty"
Package: ltxcmds 2016/05/16 v1.23 LaTeX kernel commands for general use (HO)
))) ("C:\Dropbox\Programs\MiKTeX 2.9\tex/latex/oberdiek\kvoptions.sty"
Package: kvoptions 2016/05/16 v3.12 Key value format for package options (HO)
("C:\Dropbox\Programs\MiKTeX 2.9\tex/generic/oberdiek\kvsetkeys.sty"
Package: kvsetkeys 2016/05/16 v1.17 Key value parser (HO)
("C:\Dropbox\Programs\MiKTeX 2.9\tex/generic/oberdiek\etexcmds.sty"
Package: etexcmds 2016/05/16 v1.6 Avoid name clashes with e-TeX commands (HO)
("C:\Dropbox\Programs\MiKTeX 2.9\tex/generic/iftex\ifluatex.sty"
Package: ifluatex 2019/10/25 v1.5 ifluatex legacy package. Use iftex instead.
("C:\Dropbox\Programs\MiKTeX 2.9\tex/generic/iftex\iftex.sty"
Package: iftex 2019/11/07 v1.0c TeX engine tests
))))) ("C:\Dropbox\Programs\MiKTeX 2.9\tex/latex/pdftexcmds\pdftexcmds.sty"
Package: pdftexcmds 2019/11/24 v0.31 Utility functions of pdfTeX for LuaTeX (HO
)
Package pdftexcmds Info: \pdf@primitive is available.
Package pdftexcmds Info: \pdf@ifprimitive is available.
Package pdftexcmds Info: \pdfdraftmode found.
)
Package epstopdf-base Info: Redefining graphics rule for `.eps' on input line 4
42.
Package grfext Info: Graphics extension search list:
(grfext)             [.pdf,.png,.jpg,.mps,.jpeg,.jbig2,.jb2,.PDF,.PNG,.JPG,.JPE
G,.JBIG2,.JB2,.eps]
(grfext)             \AppendGraphicsExtensions on input line 460.
)) (C:\Dropbox\Latex_code\test_epstopdf\build\epstopdf_MWE.aux)
\openout1 = `epstopdf_MWE.aux'.

LaTeX Font Info:    Checking defaults for OML/cmm/m/it on input line 7.
LaTeX Font Info:    ... okay on input line 7.
LaTeX Font Info:    Checking defaults for T1/cmr/m/n on input line 7.
LaTeX Font Info:    ... okay on input line 7.
LaTeX Font Info:    Checking defaults for OT1/cmr/m/n on input line 7.
LaTeX Font Info:    ... okay on input line 7.
LaTeX Font Info:    Checking defaults for OMS/cmsy/m/n on input line 7.
LaTeX Font Info:    ... okay on input line 7.
LaTeX Font Info:    Checking defaults for OMX/cmex/m/n on input line 7.
LaTeX Font Info:    ... okay on input line 7.
LaTeX Font Info:    Checking defaults for U/cmr/m/n on input line 7.
LaTeX Font Info:    ... okay on input line 7.
("C:\Dropbox\Programs\MiKTeX 2.9\tex/context/base/mkii\supp-pdf.mkii"
[Loading MPS to PDF converter (version 2006.09.02).]
\scratchcounter=\count88
\scratchdimen=\dimen105
\scratchbox=\box27
\nofMPsegments=\count89
\nofMParguments=\count90
\everyMPshowfont=\toks15
\MPscratchCnt=\count91
\MPscratchDim=\dimen106
\MPnumerator=\count92
\makeMPintoPDFobject=\count93
\everyMPtoPDFconversion=\toks16
)
Package epstopdf Info: Source file: <sample_eps_helvetica.eps>
(epstopdf)                    date: 2020-01-10 10:10:40
(epstopdf)                    size: 13204 bytes
(epstopdf)             Output file: <sample_eps_helvetica-eps-converted-to.pdf>

(epstopdf)                    date: 2020-01-10 10:12:32
(epstopdf)                    size: 11003 bytes
(epstopdf)             Command: <epstopdf --outfile=sample_eps_helvetica-eps-co
nverted-to.pdf sample_eps_helvetica.eps>
(epstopdf)             \includegraphics on input line 9.
Package epstopdf Info: Output file is already uptodate.

pdfTeX warning: pdflatex.exe (file ./sample_eps_helvetica-eps-converted-to.pdf)
: PDF inclusion: found PDF version <1.7>, but at most version <1.5> allowed
<sample_eps_helvetica-eps-converted-to.pdf, id=1, 397.485pt x 289.08pt>
File: sample_eps_helvetica-eps-converted-to.pdf Graphic file (type pdf)
<use sample_eps_helvetica-eps-converted-to.pdf>
Package pdftex.def Info: sample_eps_helvetica-eps-converted-to.pdf  used on inp
ut line 9.
(pdftex.def)             Requested size: 390.0pt x 283.64493pt.
Package epstopdf Info: Source file: <sample_eps_arial.eps>
(epstopdf)                    date: 2020-01-10 10:10:40
(epstopdf)                    size: 13200 bytes
(epstopdf)             Output file: <sample_eps_arial-eps-converted-to.pdf>
(epstopdf)                    date: 2020-01-10 10:12:33
(epstopdf)                    size: 11003 bytes
(epstopdf)             Command: <epstopdf --outfile=sample_eps_arial-eps-conver
ted-to.pdf sample_eps_arial.eps>
(epstopdf)             \includegraphics on input line 10.
Package epstopdf Info: Output file is already uptodate.

pdfTeX warning: pdflatex.exe (file ./sample_eps_arial-eps-converted-to.pdf): PD
F inclusion: found PDF version <1.7>, but at most version <1.5> allowed
<sample_eps_arial-eps-converted-to.pdf, id=2, 397.485pt x 289.08pt>
File: sample_eps_arial-eps-converted-to.pdf Graphic file (type pdf)
<use sample_eps_arial-eps-converted-to.pdf>
Package pdftex.def Info: sample_eps_arial-eps-converted-to.pdf  used on input l
ine 10.
(pdftex.def)             Requested size: 390.0pt x 283.64493pt.

Overfull \hbox (17.62482pt too wide) in paragraph at lines 9--11
[][]
 []

[1

{C:/Users/Sean Higgins/AppData/Local/MiKTeX/2.9/pdftex/config/pdftex.map} <./sa
mple_eps_helvetica-eps-converted-to.pdf>] [2 <./sample_eps_arial-eps-converted-
to.pdf>] (C:\Dropbox\Latex_code\test_epstopdf\build\epstopdf_MWE.aux) )
Here is how much of TeX's memory you used:
 1503 strings out of 492484
 22174 string characters out of 3129678
 82863 words of memory out of 3000000
 5860 multiletter control sequences out of 15000+200000
 3938 words of font info for 15 fonts, out of 3000000 for 9000
 1141 hyphenation exceptions out of 8191
 57i,4n,32p,365b,115s stack positions out of 5000i,500n,10000p,200000b,50000s
<C:/Drop
box/Programs/MiKTeX 2.9/fonts/type1/public/amsfonts/cm/cmr12.pfb>
Output written on C:\Dropbox\Latex_code\test_epstopdf\build\epstopdf_MWE.pdf (2
 pages, 27497 bytes).
PDF statistics:
 25 PDF objects out of 1000 (max. 8388607)
 0 named destinations out of 1000 (max. 500000)
 11 words of extra memory for PDF output out of 10000 (max. 10000000)


问:
How can I check a Java library's dependencies against the appengine whitelist?
I want to use the SIFWorks ADK, a java library, with my appengine project.  It's a complex library with 700 classes.  I can get a sample application to run on the appengine development environment.  I don't want a surprise later in development that some class I need to use, but failed to test, has a dependency not on the whitelist.

I used DependencyFinder to generate a list of dependencies, and it produces a huge list of classes, and also things like java.util.*, which I can't check against the whitelist directly.

What's the best way to ensure a complex library will be fully compatible with appengine?

答:
Check out this project:
http://www.ltech.com/cloud/google-app-engine/java-compatibility-analyzer
It will scan your class files and check for dependencies against the whitelist.</p>


问:
Time zone issue in Java
I am using this simple code to fetch the time zone ids of the current time zone that has been set in the system.

```<code>public class Main {

    public static void main(String[] args)
    {   TimeZone timezone = TimeZone.getDefault();
        System.out.println(timezone.getID());
    }
}
</code>```

I use the tzutil /g to determine the time zone and tzutil /s to set the timezone.
I have observed when time zone is set to Eastern Standard Time the above code returns id as America/New_York but when it is set to Eastern Standard Time_dstoff then I get id as GMT-05:00 which is undesirable. I want the output in the form of continent/city.

How would I get that?

答:
To find time zones that are and were always GMT-05:00, aka Eastern Standard Time_dstoff, check all ZoneId rules to find one with:

Offset of -5 hours

No transitions (past time zone changes)

No transition rules (current and future time zone changes)

```<code>for (String id : ZoneId.getAvailableZoneIds()) {
    ZoneRules rules = ZoneId.of(id).getRules();
    if (rules.getTransitions().isEmpty() && rules.getTransitionRules().isEmpty()
                && rules.getOffset(Instant.now()).getTotalSeconds() == 5 * -3600) {
        System.out.println(id);
    }
}
</code>```

Output (OpenJDK 13.0.2 on Windows)

Etc/GMT+5
SystemV/EST5
```

<p>So if you need to change the time zone from <code>GMT-05:00</code> to a zone with a <code>/</code> in it, use one of those two. <code>Etc/GMT+5</code> seems appropriate.</p>

<p>If you want to automate that, so it tries to fix it if the default time zone doesn't contain a <code>/</code>, then something like this might work:</p>

```if (! ZoneId.systemDefault().getId().contains("/")) {
    int offset = ZoneId.systemDefault().getRules().getOffset(Instant.now()).getTotalSeconds();
    String candidate = null;
    for (String id : ZoneId.getAvailableZoneIds()) {
        ZoneRules rules = ZoneId.of(id).getRules();
        if (rules.getTransitions().isEmpty() && rules.getTransitionRules().isEmpty()
                       && rules.getOffset(Instant.now()).getTotalSeconds() == offset) {
            if (id.startsWith("Etc/GMT")) {
                candidate = id;
                break;
            }
            if (candidate == null)
                candidate = id;
        }
    }
    if (candidate != null)
        TimeZone.setDefault(TimeZone.getTimeZone(ZoneId.of(candidate)));
}
```

Title: Time zone issue in Java

Body:
I am using this simple code to fetch the time zone ids of the current time zone that has been set in the system.

public class Main {

    public static void main(String[] args)
    {   TimeZone timezone = TimeZone.getDefault();
        System.out.println(timezone.getID());
    }
}

I use the tzutil /g to determine the time zone and tzutil /s to set the timezone.
I have observed when time zone is set to Eastern Standard Time the above code returns id as America/New_York but when it is set to Eastern Standard Time_dstoff then I get id as GMT-05:00 which is undesirable. I want the output in the form of continent/city.

How would I get that?

Body:
To find time zones that are and were always GMT-05:00, aka Eastern Standard Time_dstoff, check all ZoneId rules to find one with:

Offset of -5 hours

No transitions (past time zone changes)

No transition rules (current and future time zone changes)

for (String id : ZoneId.getAvailableZoneIds()) {
    ZoneRules rules = ZoneId.of(id).getRules();
    if (rules.getTransitions().isEmpty() && rules.getTransitionRules().isEmpty()
                && rules.getOffset(Instant.now()).getTotalSeconds() == 5 * -3600) {
        System.out.println(id);
    }
}

Output (OpenJDK 13.0.2 on Windows)

Etc/GMT+5
SystemV/EST5

So if you need to change the time zone from GMT-05:00 to a zone with a / in it, use one of those two. Etc/GMT+5 seems appropriate.

If you want to automate that, so it tries to fix it if the default time zone doesn't contain a /, then something like this might work:

if (! ZoneId.systemDefault().getId().contains("/")) {
    int offset = ZoneId.systemDefault().getRules().getOffset(Instant.now()).getTotalSeconds();
    String candidate = null;
    for (String id : ZoneId.getAvailableZoneIds()) {
        ZoneRules rules = ZoneId.of(id).getRules();
        if (rules.getTransitions().isEmpty() && rules.getTransitionRules().isEmpty()
                       && rules.getOffset(Instant.now()).getTotalSeconds() == offset) {
            if (id.startsWith("Etc/GMT")) {
                candidate = id;
                break;
            }
            if (candidate == null)
                candidate = id;
        }
    }
    if (candidate != null)
        TimeZone.setDefault(TimeZone.getTimeZone(ZoneId.of(candidate)));
}


问:
If player doesn't move for x seconds, do something in pygame
I'm trying to execute an action if player is not moved in certain amount of time.

I tried something like this:

```<code>        while True:
        dt = self.clock.tick(30)
        time_since_last_action += dt
        moved = False

        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                sys.exit()
            if event.type == pygame.KEYDOWN:
                moved = True
                if event.key == pygame.K_LEFT:
                    player_position -= player_size
                elif event.key == pygame.K_RIGHT:
                    player_position += player_size

        if time_since_last_action > 1000 and not moved:
            #----action----
            time_since_last_action = 0
</code>```

It doesn't work and I understand why but I have no other idea how to code what I want. It would be very helpful to see an example of what my code should look like. Thank you!

答:
Minimal working example.

When player doesn't move then it start shaking (make random moves up and down)

I use do_something = True/False to control if it should shake or not.

When I press key LEFT or RIGH then I set do_something = False and reset timer time_since_last_action.

When I don't press keys and it does nothing then timer change value.

When timer > 1000 and it doesn't move and doesn't do something then I set  do_something = True

```<code># https://github.com/furas/python-examples/

import pygame
import random

# --- constants --- (UPPER_CASE_NAMES)

SCREEN_WIDTH = 800
SCREEN_HEIGHT = 600

FPS = 25 # for more than 220 it has no time to update screen

BLACK = (0, 0, 0)
WHITE = (255, 255, 255)

# --- classes --- (CamelCaseNames)

class Player(pygame.sprite.Sprite):

    def __init__(self, x=SCREEN_WIDTH//2, y=SCREEN_HEIGHT//2):
        super().__init__()
        self.image = pygame.Surface((100,100))
        self.image.fill(WHITE)
        self.rect = self.image.get_rect(centerx=x, centery=y)

    def update(self):
        #move_x = random.randint(-5, 5)
        #move_y = random.randint(-5, 5)
        #self.rect.move_ip(move_x,move_y)
        pass

    def draw(self, surface):
        surface.blit(self.image, self.rect)

# --- functions --- (lower_case_names)

# --- main ---

pygame.init()

screen = pygame.display.set_mode( (SCREEN_WIDTH, SCREEN_HEIGHT) )

player = Player()

# --- mainloop ---

clock = pygame.time.Clock()

# default values at start
do_something = False
time_since_last_action = 0

running = True
while running:
    # --- FPS ---

    dt = clock.tick(30)
    time_since_last_action += dt

    # --- events ---

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False

        elif event.type == pygame.KEYUP:
            if event.key == pygame.K_ESCAPE:
                running = False

    keys = pygame.key.get_pressed()

    moved = False

    if keys[pygame.K_LEFT]:
        player.rect.x -= 10 # player.rect.width
        moved = True
        # reset other values
        do_something = False
        time_since_last_action = 0
    elif keys[pygame.K_RIGHT]:
        player.rect.x += 10 # player.rect.width
        moved = True
        # reset other values
        do_something = False
        time_since_last_action = 0

    if not do_something and not moved and time_since_last_action > 1000:
        do_something = True
        # reset other values
        time_since_last_action = 0

    if do_something:
        # - action -
        # shaking
        player.rect.y -= random.randint(-5, 5)

    # --- changes/moves/updates ---

    # empty

    # --- draws ---

    screen.fill(BLACK)

    player.draw(screen)

    pygame.display.flip()

# --- end ---

pygame.quit()
</code>```

I put more complex version on Github. It saves position, changes image and start shaking. When you press LEFT or RIGHT then it restore original position and image.

Body:
I'm trying to execute an action if player is not moved in certain amount of time.

I tried something like this:

        while True:
        dt = self.clock.tick(30)
        time_since_last_action += dt
        moved = False

        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                sys.exit()
            if event.type == pygame.KEYDOWN:
                moved = True
                if event.key == pygame.K_LEFT:
                    player_position -= player_size
                elif event.key == pygame.K_RIGHT:
                    player_position += player_size

        if time_since_last_action > 1000 and not moved:
            #----action----
            time_since_last_action = 0

It doesn't work and I understand why but I have no other idea how to code what I want. It would be very helpful to see an example of what my code should look like. Thank you!

Body:
Minimal working example.

When player doesn't move then it start shaking (make random moves up and down)

I use do_something = True/False to control if it should shake or not.

When I press key LEFT or RIGH then I set do_something = False and reset timer time_since_last_action.

When I don't press keys and it does nothing then timer change value.

When timer > 1000 and it doesn't move and doesn't do something then I set  do_something = True

# https://github.com/furas/python-examples/

import pygame
import random

# --- constants --- (UPPER_CASE_NAMES)

SCREEN_WIDTH = 800
SCREEN_HEIGHT = 600

FPS = 25 # for more than 220 it has no time to update screen

BLACK = (0, 0, 0)
WHITE = (255, 255, 255)

# --- classes --- (CamelCaseNames)

class Player(pygame.sprite.Sprite):

    def __init__(self, x=SCREEN_WIDTH//2, y=SCREEN_HEIGHT//2):
        super().__init__()
        self.image = pygame.Surface((100,100))
        self.image.fill(WHITE)
        self.rect = self.image.get_rect(centerx=x, centery=y)

    def update(self):
        #move_x = random.randint(-5, 5)
        #move_y = random.randint(-5, 5)
        #self.rect.move_ip(move_x,move_y)
        pass

    def draw(self, surface):
        surface.blit(self.image, self.rect)

# --- functions --- (lower_case_names)

# --- main ---

pygame.init()

screen = pygame.display.set_mode( (SCREEN_WIDTH, SCREEN_HEIGHT) )

player = Player()

# --- mainloop ---

clock = pygame.time.Clock()

# default values at start
do_something = False
time_since_last_action = 0

running = True
while running:
    # --- FPS ---

    dt = clock.tick(30)
    time_since_last_action += dt

    # --- events ---

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False

        elif event.type == pygame.KEYUP:
            if event.key == pygame.K_ESCAPE:
                running = False

    keys = pygame.key.get_pressed()

    moved = False

    if keys[pygame.K_LEFT]:
        player.rect.x -= 10 # player.rect.width
        moved = True
        # reset other values
        do_something = False
        time_since_last_action = 0
    elif keys[pygame.K_RIGHT]:
        player.rect.x += 10 # player.rect.width
        moved = True
        # reset other values
        do_something = False
        time_since_last_action = 0

    if not do_something and not moved and time_since_last_action > 1000:
        do_something = True
        # reset other values
        time_since_last_action = 0

    if do_something:
        # - action -
        # shaking
        player.rect.y -= random.randint(-5, 5)

    # --- changes/moves/updates ---

    # empty

    # --- draws ---

    screen.fill(BLACK)

    player.draw(screen)

    pygame.display.flip()

# --- end ---

pygame.quit()

I put more complex version on Github. It saves position, changes image and start shaking. When you press LEFT or RIGHT then it restore original position and image.


问:
Remove all packages that do not come with R
How can I remove all installed packages except base and recommended?

答:
WARNING, YOU WILL DELETE A LOT OF STUFF

Sometimes uninstalling packages does not work, in which case you may want to delete the folder of the packages. This can be done from R assuming you have permissions.

```<code>sapply(paste(installed.packages( priority = "NA" )[, 2], installed.packages( priority = "NA" )[, 1], sep = "/"), unlink, recursive = T)
</code>```

You can preview the paths to be delete by:

```<code>sapply(paste(installed.packages( priority = "NA" )[, 2], installed.packages( priority = "NA" )[, 1], sep = "/"), identity)
</code>```

This call:

Gets the list of installed non-base packages

Makes a vector of their installed paths

Loops over the paths

Deletes each folder recursively

Body:
WARNING, YOU WILL DELETE A LOT OF STUFF

Sometimes uninstalling packages does not work, in which case you may want to delete the folder of the packages. This can be done from R assuming you have permissions.

sapply(paste(installed.packages( priority = "NA" )[, 2], installed.packages( priority = "NA" )[, 1], sep = "/"), unlink, recursive = T)

You can preview the paths to be delete by:

sapply(paste(installed.packages( priority = "NA" )[, 2], installed.packages( priority = "NA" )[, 1], sep = "/"), identity)

This call:

Gets the list of installed non-base packages

Makes a vector of their installed paths

Loops over the paths

Deletes each folder recursively


问:
check how many dominant numbers there are in a 2D array
in this program i'm supposed to find how many dominant numbers the matrix has. a dominant number is a number that is bigger than whatever is below to the right onwards(bear with my english please).

i entered this :

```<code>5 (9) 2  4  1 (7)  2  4///
3  5  6  2  5 (6)  1  2///
1  3  4  7  8 (8) (3) 0///
1  3  5  6  7  8   2  1///
</code>```

the ones i circled are supposed to be the dominant ones but it gave me back 6, what went wrong?

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

#define NR 4
#define NC 8

int dominants(int a[NR][NC]);
int main(int argc, char * argv[]){
int array[NR][NC];
int ndom;
int i,j;

for(i=0;i<NR;i++){
        for(j=0;j<NC;j++){

        scanf("%d", &array[i][j]);
        }
}
printf("array entered:\n\n");
for(i=0;i<NR;i++){
        printf("\n");
        for(j=0;j<NC;j++){

        printf("%d  ", array[i][j]);
        }
}

ndom=dominants(array);

printf("amount of dominant numbers:%d", ndom);
return 0;
}
int dominants(int a[NR][NC]){
int domflag;
int i,j, l, m;
int numdom=0;
for(i=0;i<NR-1;i++){
    for(j=0;j<NC-1;j++){
        for(l=i+1;l<NR;l++){
                domflag=1;
                for(m=j+1;m<NC;m++){
                if(a[i][j]<=a[l][m]){
                    domflag=0;
                                    }
                                   }
                           }
            if(domflag==1){
                numdom++;
                          }
        }

    }
    return numdom;
}
</code>```

答:
domflag = 1; is inside the loop for (l = i + 1; l < NR; l++) but should be outside it.

A good way to reduce errors like this is to only define identifiers where they are needed. If the definition int domflag; at the top of the routine were removed and the statement domflag = 1; were changed to int domflag = 1;, then the compiler would have given an error later where domflag == 1 is tested, because that would be outside the scope of the definition.

Body:
in this program i'm supposed to find how many dominant numbers the matrix has. a dominant number is a number that is bigger than whatever is below to the right onwards(bear with my english please).

i entered this :

5 (9) 2  4  1 (7)  2  4///
3  5  6  2  5 (6)  1  2///
1  3  4  7  8 (8) (3) 0///
1  3  5  6  7  8   2  1///

the ones i circled are supposed to be the dominant ones but it gave me back 6, what went wrong?

#include <stdio.h>
#include <stdlib.h>

#define NR 4
#define NC 8

int dominants(int a[NR][NC]);
int main(int argc, char * argv[]){
int array[NR][NC];
int ndom;
int i,j;

for(i=0;i<NR;i++){
        for(j=0;j<NC;j++){

        scanf("%d", &array[i][j]);
        }
}
printf("array entered:\n\n");
for(i=0;i<NR;i++){
        printf("\n");
        for(j=0;j<NC;j++){

        printf("%d  ", array[i][j]);
        }
}

ndom=dominants(array);

printf("amount of dominant numbers:%d", ndom);
return 0;
}
int dominants(int a[NR][NC]){
int domflag;
int i,j, l, m;
int numdom=0;
for(i=0;i<NR-1;i++){
    for(j=0;j<NC-1;j++){
        for(l=i+1;l<NR;l++){
                domflag=1;
                for(m=j+1;m<NC;m++){
                if(a[i][j]<=a[l][m]){
                    domflag=0;
                                    }
                                   }
                           }
            if(domflag==1){
                numdom++;
                          }
        }

    }
    return numdom;
}