问:
How do to make a stopwatch thread?
```<code>        //make timer
        min = 0;
        sec = 0;
        final TextView timer1 = (TextView) findViewById(R.id.timer1);
        timer1.setText(min + ":" + sec);
        Thread t = new Thread() {
            public void run() {
                sec+=1;
                if (sec>59) {
                    min+=1;
                    sec=0;
                }
                timer1.setText(min + ":" + sec);
                Log.d("Timer", "run: "+min+":"+sec);
                try
                {
                    sleep(1000);
                }
                catch (InterruptedException e)
                {}
            }
        };
        t.start();
</code>```

i tried to create this thread which supposed to count number each second and update it in the textview,
but it just freeze when i run the activty.

答:
You don't have a loop, adding a while loop is what makes the Thread keep running the code over and over and over.

Also you will not be able to update a TextView's text from a background thread.

i.e. timer1.setText(min + ":" + sec);

You will need to post the update, like so:

```<code>private boolean running = false;

@Override
public void onResume() {
    super.onResume()
    final Handler mainThreadHandler = new Handler()
    running = true;
        // make timer
        min = 0;
        sec = 0;
        final TextView timer1 = (TextView) findViewById(R.id.timer1);
        timer1.setText(min + ":" + sec);
        Thread t = new Thread() {
            public void run() {
               while(running) {
                  sec += 1;
                  if (sec > 59) {
                     min += 1;
                     sec = 0;
                  }
                  mainThreadHandler.post(new Runnable(){
                      @Override
                      public void run() {
                           timer1.setText(min + ":" + sec);
                      }
                  }
                  Log.d("Timer", "run: "+min+":"+sec);
                  try{ Thread.sleep(1000);}
                  catch (InterruptedException e) {Log.e("TUT", "error! don't ignore me", e}
               }
            }
        };
        t.start();
}

@Override
public void onPause() {
    running = false;
    super.onPause()
}
</code>```

Title: How do to make a stopwatch thread?

Body:
        //make timer
        min = 0;
        sec = 0;
        final TextView timer1 = (TextView) findViewById(R.id.timer1);
        timer1.setText(min + ":" + sec);
        Thread t = new Thread() {
            public void run() {
                sec+=1;
                if (sec>59) {
                    min+=1;
                    sec=0;
                }
                timer1.setText(min + ":" + sec);
                Log.d("Timer", "run: "+min+":"+sec);
                try
                {
                    sleep(1000);
                }
                catch (InterruptedException e)
                {}
            }
        };
        t.start();

i tried to create this thread which supposed to count number each second and update it in the textview,
but it just freeze when i run the activty.

Body:
You don't have a loop, adding a while loop is what makes the Thread keep running the code over and over and over.

Also you will not be able to update a TextView's text from a background thread.

i.e. timer1.setText(min + ":" + sec);

You will need to post the update, like so:

private boolean running = false;

@Override
public void onResume() {
    super.onResume()
    final Handler mainThreadHandler = new Handler()
    running = true;
        // make timer
        min = 0;
        sec = 0;
        final TextView timer1 = (TextView) findViewById(R.id.timer1);
        timer1.setText(min + ":" + sec);
        Thread t = new Thread() {
            public void run() {
               while(running) {
                  sec += 1;
                  if (sec > 59) {
                     min += 1;
                     sec = 0;
                  }
                  mainThreadHandler.post(new Runnable(){
                      @Override
                      public void run() {
                           timer1.setText(min + ":" + sec);
                      }
                  }
                  Log.d("Timer", "run: "+min+":"+sec);
                  try{ Thread.sleep(1000);}
                  catch (InterruptedException e) {Log.e("TUT", "error! don't ignore me", e}
               }
            }
        };
        t.start();
}

@Override
public void onPause() {
    running = false;
    super.onPause()
}


来源: stackexchange

问:
Is there a security risk in exposing the MongoDB url to the public?
When I create a connection to MongoDB, I do something like this:

```<code>mongoose.connect(uri, options).then(
  () => { console.log("Successfully connected to", uri },
  err => { console.log("Could not connect to database" }
);
</code>```

Is it dangerous to expose this information on the console? Could someone trying to hack into my site/database use this maliciously and if so, how?

答:
One claims a system is secure if it cares about the Confidentiality, Integrity and Accessibility (so called CIA triad) of the information in transport, at rest and in processing. So, to judge whether a system is secure or insecure – we need to know what information it deals with.

If you put sensitive data into the database and expose it to the public, it is insecure, as Confidentiality is not provided.

You could argue that the DB holds only public information and that the Confidentiality is not an issue here. Ok, then what about the Integrity? Can everyone change the information in the database? Probably you could make the information read-only which would be a nice workaround over the Integrity issues, else the system is considered not secure.

Last thing last – Availability. It is an uncommon thing to expose the database to the public. One of many issues to deal with are Denial-of-Service (DoS) attacks. Exposed database raises the risk of someone running self-made queries intended to put big load on CPU/memory/bandwidth and leading to an outage. If this is not an issue here than yes, the system is secure.

ContentLicense: CC BY-SA 4.0

Body:
When I create a connection to MongoDB, I do something like this:

mongoose.connect(uri, options).then(
  () => { console.log("Successfully connected to", uri },
  err => { console.log("Could not connect to database" }
);

Is it dangerous to expose this information on the console? Could someone trying to hack into my site/database use this maliciously and if so, how?


问:
How to count IMG tags within DIV using Xpath
I want to count how many IMG tags there are under the surface div tag and echo the amount.

```<code><div id="surface" style="width: 4567px; height: 4137px; left: -1850px; top: -1152px; cursor: default;">

<img src="https://media.memories.png" data-seat="L:106|EE:5" data-pl="1" style="position: absolute; cursor: pointer; width: 14px; height: 14px; left: 2221px; top: 1561px; display: block;">

<img src="https://media.memories.png" data-seat="L:106|EE:6" data-pl="1" style="position: absolute; cursor: pointer; width: 14px; height: 14px; left: 2237px; top: 1561px; display: block;">

<img src="https://media.memories.png" data-seat="L:106|EE:7" data-pl="1" style="position: absolute; cursor: pointer; width: 14px; height: 14px; left: 2253px; top: 1561px; display: block;">

<img src="https://media.memories.png" data-seat="L:106|EE:8" data-pl="1" style="position: absolute; cursor: pointer; width: 14px; height: 14px; left: 2269px; top: 1561px; display: block;">

</div>
</code>```

Here is my non working attempt to get the count however its not returning the count to run my test in selenium IDE.

```<code>"//div[@surface='data-seat']/img"
</code>```

答:
You can use the XPath-1.0 expression

```<code>count(//div[@id='surface']/img)
</code>```

It counts all img children of all div elements.

Body:
I want to count how many IMG tags there are under the surface div tag and echo the amount.

Here is my non working attempt to get the count however its not returning the count to run my test in selenium IDE.

"//div[@surface='data-seat']/img"

Body:
You can use the XPath-1.0 expression

count(//div[@id='surface']/img)

It counts all img children of all div elements.


问:
How to order Lucid Models results based on relation?
What I want is to order all Service model results based on a relation (that belongsTo the same ServiceCategory) like Laravel does, something like this:

const services = await Service
  .query()
  .orderBy('categories.id', 'desc')
  .fetch()
```

<p>The problem is that Lucid doesn't understand it and gives the following error:</p>

<blockquote>
  <p>select * from <code>services</code> order
  by <code>categories</code>.<code>id</code> asc - ER_BAD_FIELD_ERROR: Unknown column
  'categories.id' in 'order clause'</p>
</blockquote>

<p>This is the Service model:</p>

<pre class="lang-js prettyprint-override"><code>const Model = use('Model')

class Service extends Model {
  categories() {
    return this
      .belongsToMany('App/Models/ServiceCategory')
      .withTimestamps()
  }
}

module.exports = Service
</code>```

This is the ServiceCategory model:

const Model = use('Model')

class ServiceCategory extends Model {
  services() {
    return this
      .belongsToMany('App/Models/Service')
      .withTimestamps()
  }
}

module.exports = ServiceCategory
```

How can I make it work?

答:
Try to use with()

```<code>const services = await Service
  .query()
  .with('categories')
  .orderBy('categories.id', 'desc')
  .fetch()
</code>```

if don't work, use innerJoin

Body:
What I want is to order all Service model results based on a relation (that belongsTo the same ServiceCategory) like Laravel does, something like this:

const services = await Service
  .query()
  .orderBy('categories.id', 'desc')
  .fetch()

The problem is that Lucid doesn't understand it and gives the following error:

select * from services order
  by categories.id asc - ER_BAD_FIELD_ERROR: Unknown column
  'categories.id' in 'order clause'

This is the Service model:

const Model = use('Model')

class Service extends Model {
  categories() {
    return this
      .belongsToMany('App/Models/ServiceCategory')
      .withTimestamps()
  }
}

module.exports = Service

This is the ServiceCategory model:

const Model = use('Model')

class ServiceCategory extends Model {
  services() {
    return this
      .belongsToMany('App/Models/Service')
      .withTimestamps()
  }
}

module.exports = ServiceCategory

How can I make it work?

Body:
Try to use with()

const services = await Service
  .query()
  .with('categories')
  .orderBy('categories.id', 'desc')
  .fetch()

if don't work, use innerJoin


问:
Cannot make a secured connection from Celery to Redis
I'm following this tutorial, and adjusting the Celery-background related code to my project.

In my case I am operating in a Docker environment, and I have a secured site (i.e. https://localhost).

I adjusted the code for secure connection as follows:

```<code>key_file = '/etc/nginx/ssl/localhost.key'
cert_file = '/etc/nginx/ssl/localhost.crt'
ca_file = '/etc/nginx/ssl/localhost.ca.crt'

app.config['CELERY_BROKER_URL'] = 'rediss://redis:6380/0'
app.config['CELERY_RESULT_BACKEND'] = 'rediss://redis:6380/0'

def make_celery(app):
    """Setup celery."""
    celery = Celery(app.import_name,
                    backend=app.config['CELERY_RESULT_BACKEND'],
                    broker=app.config['CELERY_BROKER_URL'],
                    broker_use_ssl = {
                        'ssl_keyfile': key_file,
                        'ssl_certfile': cert_file,
                        'ssl_ca_certs': ca_file,
                        'ssl_cert_reqs': ssl.CERT_REQUIRED
                    },
                    redis_backend_use_ssl = {
                        'ssl_keyfile': key_file,
                        'ssl_certfile': cert_file,
                        'ssl_ca_certs': ca_file,
                        'ssl_cert_reqs': ssl.CERT_REQUIRED
                    })
</code>```

My docker-compose file look like this:

```<code>version: '3'

services:
  web:
    restart: always
    build:
      context: ./web
      dockerfile: Dockerfile
    expose:
      - "8000"
    volumes:
      - /home/avner/avner/constructionOverlay/code/meshlabjs/branches/meshlabjs_avnerV1/webServer/web:/home/flask/app/web
      - data2:/home/flask/app/web/project/avner/img
    command: /usr/local/bin/gunicorn -w 2 -t 3600 -b :8000 project:app
    depends_on:
      - postgres
    stdin_open: true
    tty: true

  nginx:
    restart: always
    build:
      context: ./nginx
      dockerfile: Dockerfile
    ports:
      - "80:80"
      - "443:443"
    volumes:
      - /home/avner/avner/constructionOverlay/code/meshlabjs/branches/meshlabjs_avnerV1/webServer/web:/home/flask/app/web
      - data2:/home/flask/app/web/project/avner/img
    depends_on:
      - web

  postgres:
    restart: always
    build:
      context: ./postgresql
      dockerfile: Dockerfile
    volumes:
      - data1:/var/lib/postgresql/data
    expose:
      - "5432"

  redis:
    container_name: redis
    hostname: redis
    image: "redis:alpine"
    command: --port 6380
    restart: always
    expose:
      - '6380'
    ports:
     - "6380:6380"
    volumes:
     - /home/avner/avner/constructionOverlay/code/meshlabjs/branches/meshlabjs_avnerV1/webServer/redis/redis.conf:/usr/local/etc/redis/redis.conf

  celery:
    build:
      context: ./web
    command: watchmedo auto-restart --directory=./ --pattern=*.py --recursive -- celery worker -A project.celery  --loglevel=info
    volumes:
      - /home/avner/avner/constructionOverlay/code/meshlabjs/branches/meshlabjs_avnerV1/webServer/web:/home/flask/app/web
      - /home/avner/avner/constructionOverlay/code/meshlabjs/branches/meshlabjs_avnerV1/webServer/nginx/ssl:/etc/nginx/ssl
      - data2:/home/flask/app/web/project/avner/img
    depends_on:
      - redis

volumes:
  data1:
  data2:
</code>```

The files: key_file, cert_file, and ca_file are generated using a self-CA with the following steps, similar to the steps here:

create a self CA

sign a certificate to my localhost, outside of Docker

mount the files to Docker

After doing this change, I don't see connection errors. The containers start ok, and the log file is quite!

But at run time, when calling a Celery task from my web container I get an error, in my web container.

From my javascript I have a POST call:

```<code>let queryUrl = 'http://localhost/api/v1_2/create_zip_file3';
let fetchData = {
    method: 'POST',
};
let response = await fetch(queryUrl, fetchData);
</code>```

Here is the code in Flask web container:

```<code>@sites_api_blueprint.route('/api/v1_2/create_zip_file', methods=['POST'])
def create_zip_file():
    print( 'BEG create_zip_file' )
    task = create_zip_file_task.delay(current_user_id=current_user.id)
    return jsonify({}), 202, {'Location': url_for('create_zip_file_taskstatus', task_id=task.id)}

@celery.task(bind=True)
def create_zip_file_task(self, current_user_id):
    print( 'BEG create_zip_file_task' )
    # do some stuff
    # ...

# taskstatus -> create_zip_file_taskstatus
@app.route('/status/<task_id>')
def create_zip_file_taskstatus(task_id):
    # return the progress status
    # ...
</code>```

The error in the web container:

```<code>docker logs -f webserver_web_1
...
BEG create_zip_file
172.20.0.5 - - [14/Feb/2020 05:48:32] "POST /api/v1_2/create_zip_file HTTP/1.0" 500 -
Traceback (most recent call last):
  File "/usr/local/lib/python3.7/site-packages/redis/connection.py", line 492, in connect
    sock = self._connect()
  File "/usr/local/lib/python3.7/site-packages/redis/connection.py", line 742, in _connect
    keyfile=self.keyfile)
FileNotFoundError: [Errno 2] No such file or directory
</code>```

What am I doing wrong?

Thanks
Avner

答:
The problem with secure connection was because the ssl keys were not available to the web container.

I fixed it by changing docker-compose.yml

```<code>cat docker-compose.yml
...
services:
  web:
    volumes:
      - /home/webServer/nginx/ssl:/etc/nginx/ssl
...
</code>```

After doing the change, there are no errors in the log file.

But there still seems to be problems with the connection, and when triggering the task, there is no activity on the celery container.

This is a different problem and I track it separately in here.

Body:
I'm following this tutorial, and adjusting the Celery-background related code to my project.

In my case I am operating in a Docker environment, and I have a secured site (i.e. https://localhost).

I adjusted the code for secure connection as follows:

key_file = '/etc/nginx/ssl/localhost.key'
cert_file = '/etc/nginx/ssl/localhost.crt'
ca_file = '/etc/nginx/ssl/localhost.ca.crt'

app.config['CELERY_BROKER_URL'] = 'rediss://redis:6380/0'
app.config['CELERY_RESULT_BACKEND'] = 'rediss://redis:6380/0'

def make_celery(app):
    """Setup celery."""
    celery = Celery(app.import_name,
                    backend=app.config['CELERY_RESULT_BACKEND'],
                    broker=app.config['CELERY_BROKER_URL'],
                    broker_use_ssl = {
                        'ssl_keyfile': key_file,
                        'ssl_certfile': cert_file,
                        'ssl_ca_certs': ca_file,
                        'ssl_cert_reqs': ssl.CERT_REQUIRED
                    },
                    redis_backend_use_ssl = {
                        'ssl_keyfile': key_file,
                        'ssl_certfile': cert_file,
                        'ssl_ca_certs': ca_file,
                        'ssl_cert_reqs': ssl.CERT_REQUIRED
                    })

My docker-compose file look like this:

version: '3'

services:
  web:
    restart: always
    build:
      context: ./web
      dockerfile: Dockerfile
    expose:
      - "8000"
    volumes:
      - /home/avner/avner/constructionOverlay/code/meshlabjs/branches/meshlabjs_avnerV1/webServer/web:/home/flask/app/web
      - data2:/home/flask/app/web/project/avner/img
    command: /usr/local/bin/gunicorn -w 2 -t 3600 -b :8000 project:app
    depends_on:
      - postgres
    stdin_open: true
    tty: true

  nginx:
    restart: always
    build:
      context: ./nginx
      dockerfile: Dockerfile
    ports:
      - "80:80"
      - "443:443"
    volumes:
      - /home/avner/avner/constructionOverlay/code/meshlabjs/branches/meshlabjs_avnerV1/webServer/web:/home/flask/app/web
      - data2:/home/flask/app/web/project/avner/img
    depends_on:
      - web

  postgres:
    restart: always
    build:
      context: ./postgresql
      dockerfile: Dockerfile
    volumes:
      - data1:/var/lib/postgresql/data
    expose:
      - "5432"

  redis:
    container_name: redis
    hostname: redis
    image: "redis:alpine"
    command: --port 6380
    restart: always
    expose:
      - '6380'
    ports:
     - "6380:6380"
    volumes:
     - /home/avner/avner/constructionOverlay/code/meshlabjs/branches/meshlabjs_avnerV1/webServer/redis/redis.conf:/usr/local/etc/redis/redis.conf

  celery:
    build:
      context: ./web
    command: watchmedo auto-restart --directory=./ --pattern=*.py --recursive -- celery worker -A project.celery  --loglevel=info
    volumes:
      - /home/avner/avner/constructionOverlay/code/meshlabjs/branches/meshlabjs_avnerV1/webServer/web:/home/flask/app/web
      - /home/avner/avner/constructionOverlay/code/meshlabjs/branches/meshlabjs_avnerV1/webServer/nginx/ssl:/etc/nginx/ssl
      - data2:/home/flask/app/web/project/avner/img
    depends_on:
      - redis

volumes:
  data1:
  data2:

The files: key_file, cert_file, and ca_file are generated using a self-CA with the following steps, similar to the steps here:

create a self CA

sign a certificate to my localhost, outside of Docker

mount the files to Docker

After doing this change, I don't see connection errors. The containers start ok, and the log file is quite!

But at run time, when calling a Celery task from my web container I get an error, in my web container.

From my javascript I have a POST call:

let queryUrl = 'http://localhost/api/v1_2/create_zip_file3';
let fetchData = {
    method: 'POST',
};
let response = await fetch(queryUrl, fetchData);

Here is the code in Flask web container:

@sites_api_blueprint.route('/api/v1_2/create_zip_file', methods=['POST'])
def create_zip_file():
    print( 'BEG create_zip_file' )
    task = create_zip_file_task.delay(current_user_id=current_user.id)
    return jsonify({}), 202, {'Location': url_for('create_zip_file_taskstatus', task_id=task.id)}

@celery.task(bind=True)
def create_zip_file_task(self, current_user_id):
    print( 'BEG create_zip_file_task' )
    # do some stuff
    # ...

# taskstatus -> create_zip_file_taskstatus
@app.route('/status/<task_id>')
def create_zip_file_taskstatus(task_id):
    # return the progress status
    # ...

The error in the web container:

docker logs -f webserver_web_1
...
BEG create_zip_file
172.20.0.5 - - [14/Feb/2020 05:48:32] "POST /api/v1_2/create_zip_file HTTP/1.0" 500 -
Traceback (most recent call last):
  File "/usr/local/lib/python3.7/site-packages/redis/connection.py", line 492, in connect
    sock = self._connect()
  File "/usr/local/lib/python3.7/site-packages/redis/connection.py", line 742, in _connect
    keyfile=self.keyfile)
FileNotFoundError: [Errno 2] No such file or directory

What am I doing wrong?

Thanks
Avner

Body:
The problem with secure connection was because the ssl keys were not available to the web container.

I fixed it by changing docker-compose.yml

cat docker-compose.yml
...
services:
  web:
    volumes:
      - /home/webServer/nginx/ssl:/etc/nginx/ssl
...

After doing the change, there are no errors in the log file.

But there still seems to be problems with the connection, and when triggering the task, there is no activity on the celery container.

This is a different problem and I track it separately in here.


问:
Host a Slim microsite in a subdirectory
Is there a nice and supported way to define routes like this:

```<code>$app->get('/', function (Request $request, Response $response) {
});
$app->get('/hello/{name}', function (Request $request, Response $response) {
});
</code>```

... and get them work as expected no matter the location of the index.php routing file?

E.g. if DOCUMENT_ROOT is C:\Projects\Playground (http://playground.example.com) and my router file is located at C:\Projects\Playground\PHP\Slim\foo\bar\index.php (http://playground.example.com/PHP/Slim/foo/bar) I'd like http://playground.example.com/PHP/Slim/foo/bar/hello/world! to match '/hello/{name}'.

(Every other file belonging to Slim would be somewhere else, let's say C:\Libraries\Slim, and should be irrelevant to this question.)

With nice and supported I mean not this:

```<code>$uri_prefix = complex_function_to_calculate_it($_SERVER['DOCUMENT_ROOT'], __DIR__);
$app->get($uri_prefix . '/hello/{name}', function (Request $request, Response $response) {
});
</code>```

Slim 3 uses nikic/fast-route but I couldn't find any hint.

答:
You could nest all of your routes inside of a wrapper group in Slim, for which the path pattern is determined based on the $_SERVER variable:

$app = Slim\Factory\AppFactory::create();
$app->group(dirname($_SERVER['SCRIPT_NAME']), function($subdirectory) {
    $subdirectory->group('/api/v1', $function($api) {
        // define routes as usual, e.g...
        $api->get('/foo/{foo:[0-9]+}', function($req, $res) {
            // ...
        });
    });
});
```

A little pre-processing of the $_SERVER['SCRIPT_NAME'] variable lets you do other things -- detect that your API is nested inside a directory named API and don't append another API to the route pattern, for example.

ContentLicense: CC BY-SA 3.0

Title: Host a Slim microsite in a subdirectory

Body:
Is there a nice and supported way to define routes like this:

$app->get('/', function (Request $request, Response $response) {
});
$app->get('/hello/{name}', function (Request $request, Response $response) {
});

... and get them work as expected no matter the location of the index.php routing file?

E.g. if DOCUMENT_ROOT is C:\Projects\Playground (http://playground.example.com) and my router file is located at C:\Projects\Playground\PHP\Slim\foo\bar\index.php (http://playground.example.com/PHP/Slim/foo/bar) I'd like http://playground.example.com/PHP/Slim/foo/bar/hello/world! to match '/hello/{name}'.

(Every other file belonging to Slim would be somewhere else, let's say C:\Libraries\Slim, and should be irrelevant to this question.)

With nice and supported I mean not this:

$uri_prefix = complex_function_to_calculate_it($_SERVER['DOCUMENT_ROOT'], __DIR__);
$app->get($uri_prefix . '/hello/{name}', function (Request $request, Response $response) {
});

Slim 3 uses nikic/fast-route but I couldn't find any hint.

Body:
You could nest all of your routes inside of a wrapper group in Slim, for which the path pattern is determined based on the $_SERVER variable:

$app = Slim\Factory\AppFactory::create();
$app->group(dirname($_SERVER['SCRIPT_NAME']), function($subdirectory) {
    $subdirectory->group('/api/v1', $function($api) {
        // define routes as usual, e.g...
        $api->get('/foo/{foo:[0-9]+}', function($req, $res) {
            // ...
        });
    });
});

A little pre-processing of the $_SERVER['SCRIPT_NAME'] variable lets you do other things -- detect that your API is nested inside a directory named API and don't append another API to the route pattern, for example.


问:
Syntax error in binary search tree in ocaml
```<code>type (ty1,ty2) btree = Empty
  | Node of (ty1,ty2) * (ty1,ty2) btree * (ty1,ty2) btree;;
</code>```

Here is my code to write a constructor. write down OCaml expressions of type (ty1,ty2) tree, for suitable types ty1 and ty2, that represent trees of the kind we are interested in.

```<code>When I run that
7 | type (ty1,ty2) btree = Empty
          ^^^
Error: Syntax error
</code>```

答:
Type variables need to be prefixed with an apostrophe, ', to distinguish them from concrete types.

The syntax for the first parameter of Node is also not valid. I assume you mean for it to be a tuple:

```<code>type ('ty1, 'ty2) btree = Empty
  | Node of ('ty1 * 'ty2) * ('ty1, 'ty2) btree * ('ty1, 'ty2) btree;;
</code>```

Body:
type (ty1,ty2) btree = Empty
  | Node of (ty1,ty2) * (ty1,ty2) btree * (ty1,ty2) btree;;

Here is my code to write a constructor. write down OCaml expressions of type (ty1,ty2) tree, for suitable types ty1 and ty2, that represent trees of the kind we are interested in.

When I run that
7 | type (ty1,ty2) btree = Empty
          ^^^
Error: Syntax error

Body:
Type variables need to be prefixed with an apostrophe, ', to distinguish them from concrete types.

The syntax for the first parameter of Node is also not valid. I assume you mean for it to be a tuple:

type ('ty1, 'ty2) btree = Empty
  | Node of ('ty1 * 'ty2) * ('ty1, 'ty2) btree * ('ty1, 'ty2) btree;;


问:
How do I remove duplicate words in a string in JavaScript?
I've been trying to remove duplicate words from a string, and it's not working.

I have the current string:

```<code>const categories = 'mexican, restaurant, mexican, food, restaurant'
</code>```

and I want this outcome:

```<code>const x = 'mexican restaurant food'
</code>```

I have tried the following:

```<code>const x = categories.replace(/,/g, '');

    const uniqueList = x
      .split()
      .filter((currentItem, i, allItems) => {
        return i === allItems.indexOf(currentItem);
      })
      .join();
</code>```

Which is giving me:

```<code>uniqueList = 'chinese restaurant chinese food restaurant'
</code>```

What is wrong with the code above?

答:
const categories = 'mexican, restaurant, mexican, food, restaurant';

    const uniqueList = categories
      .split(', ') // split the string when a comma + space is found
      .filter((currentItem, i, allItems) => {
        return i === allItems.indexOf(currentItem);
      }) // filter out duplicates
      .join(' '); // rejoin array to string

 console.log( uniqueList );```

Body:
I've been trying to remove duplicate words from a string, and it's not working.

I have the current string:

const categories = 'mexican, restaurant, mexican, food, restaurant'

and I want this outcome:

const x = 'mexican restaurant food'

I have tried the following:

const x = categories.replace(/,/g, '');

    const uniqueList = x
      .split()
      .filter((currentItem, i, allItems) => {
        return i === allItems.indexOf(currentItem);
      })
      .join();

Which is giving me:

uniqueList = 'chinese restaurant chinese food restaurant'

What is wrong with the code above?


问:
How to know exactly when a UIScrollView's scrolling has stopped?
In short, I need to know exactly when the scrollview stopped scrolling. By 'stopped scrolling', I mean the moment at which it is no longer moving and not being touched.

I've been working on a horizontal UIScrollView subclass (for iOS 4) with selection tabs in it. One of its requirements is that it stops scrolling below a certain speed to allow user interaction more quickly. It should also snap to the start of a tab. In other words, when the user releases the scrollview and its speed is low, it snaps to a position. I've implemented this and it works, but there's a bug in it.

What I have now:

The scrollview is its own delegate. at every call to scrollViewDidScroll:, it refreshes its speed-related variables:

```<code>-(void)refreshCurrentSpeed
{
    float currentOffset = self.contentOffset.x;
    NSTimeInterval currentTime = [[NSDate date] timeIntervalSince1970];

    deltaOffset = (currentOffset - prevOffset);
    deltaTime = (currentTime - prevTime);
    currentSpeed = deltaOffset/deltaTime;
    prevOffset = currentOffset;
    prevTime = currentTime;

    NSLog(@"deltaOffset is now %f, deltaTime is now %f and speed is %f",deltaOffset,deltaTime,currentSpeed);
}
</code>```

Then proceeds to snap if needed:

```<code>-(void)snapIfNeeded
{
    if(canStopScrolling && currentSpeed <70.0f && currentSpeed>-70.0f)
    {
        NSLog(@"Stopping with a speed of %f points per second", currentSpeed);
        [self stopMoving];

        float scrollDistancePastTabStart = fmodf(self.contentOffset.x, (self.frame.size.width/3));
        float scrollSnapX = self.contentOffset.x - scrollDistancePastTabStart;
        if(scrollDistancePastTabStart > self.frame.size.width/6)
        {
            scrollSnapX += self.frame.size.width/3;
        }
        float maxSnapX = self.contentSize.width-self.frame.size.width;
        if(scrollSnapX>maxSnapX)
        {
            scrollSnapX = maxSnapX;
        }
        [UIView animateWithDuration:0.3
                         animations:^{self.contentOffset=CGPointMake(scrollSnapX, self.contentOffset.y);}
                         completion:^(BOOL finished){[self stopMoving];}
        ];
    }
    else
    {
        NSLog(@"Did not stop with a speed of %f points per second", currentSpeed);
    }
}

-(void)stopMoving
{
    if(self.dragging)
    {
        [self setContentOffset:CGPointMake(self.contentOffset.x, self.contentOffset.y) animated:NO];
    }
    canStopScrolling = NO;
}
</code>```

Here are the delegate methods:

```<code>-(void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
    canStopScrolling = NO;
    [self refreshCurrentSpeed];
}

-(void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate
{
    canStopScrolling = YES;
    NSLog(@"Did end dragging");
    [self snapIfNeeded];
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    [self refreshCurrentSpeed];
    [self snapIfNeeded];
}
</code>```

This works well most of the time, except in two scenarios:
1. When the user scrolls without releasing his/her finger and lets go at a near stationary timing right after moving, it often snaps to its position as it's supposed to, but a lot of times, does not. It usually takes a few attempts to get it to happen. Odd values for time (very low) and/or distance (rather high) appear at the release, causing a high speed value while the scrollView is, in reality, nearly or entirely stationary.
2. When the user taps the scrollview to stop its movement, it seems the scrollview sets the contentOffset to its previous spot. This teleportation results in a very high speed value. This could be fixed by checking if the previous delta is currentDelta*-1, but I'd prefer a more stable solution.

I've tried using didEndDecelerating, but when the glitch occurs, it does not get called. This probably confirms that it's stationary already. There seems to be no delegate method that gets called when the scrollview stopped moving completely.

If you'd like to see the glitch yourself, here's some code to fill the scrollview with tabs:

```<code>@interface  UIScrollView <UIScrollViewDelegate>
{
    bool canStopScrolling;
    float prevOffset;
    float deltaOffset; //remembered for debug purposes
    NSTimeInterval prevTime;
    NSTimeInterval deltaTime; //remembered for debug purposes
    float currentSpeed;
}

-(void)stopMoving;
-(void)snapIfNeeded;
-(void)refreshCurrentSpeed;

@end

@implementation TabScrollView

-(id) init
{
    self = [super init];
    if(self)
    {
        self.delegate = self;
        self.frame = CGRectMake(0.0f,0.0f,320.0f,40.0f);
        self.backgroundColor = [UIColor grayColor];
        float tabWidth = self.frame.size.width/3;
        self.contentSize = CGSizeMake(100*tabWidth, 40.0f);
        for(int i=0; i<100;i++)
        {
            UIView *view = [[UIView alloc] init];
            view.frame = CGRectMake(i*tabWidth,0.0f,tabWidth,40.0f);
            view.backgroundColor = [UIColor colorWithWhite:(float)(i%2) alpha:1.0f];
            [self addSubview:view];
        }
    }
    return self;
}

@end
</code>```

A shorter version of this question: how to know when the scrollview stopped scrolling? didEndDecelerating: does not get called when you release it stationary, didEndDragging: happens a lot during the scrolling and checking for speed is unreliable due to this odd 'jump' which sets the speed to something random.

答:
It is important to understand, that the when UIScrollView is stopping to move it triggers two different functions of the UIScrollViewDelegate depending on how strong the user has pushed.

stopDragging is triggered, when the user stops his drag gesture on the screen. When this was very slowly no more movement will happen after that.

stopDecelerating is triggered, when the user has pushed the scroll view in a way, so that it is still moving after the user touches up his finger and then comes to an end. This function is not always triggered, it is not triggered, when there is no movement after the user touches up his finger. Then only the function above "stopDragging" is triggered.

So in conclusion it is necessary to combine the two functions like @WayneBurkett already pointed out in his answer.

In Swift 5.X:

```<code>func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
    myFunction()
}

func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {
    if decelerate == false {
        myFunction()
    }
}

private func myFunction() {
    // scrollView did stop moving -> do what ever
    // ...
}
</code>```

Body:
In short, I need to know exactly when the scrollview stopped scrolling. By 'stopped scrolling', I mean the moment at which it is no longer moving and not being touched.

I've been working on a horizontal UIScrollView subclass (for iOS 4) with selection tabs in it. One of its requirements is that it stops scrolling below a certain speed to allow user interaction more quickly. It should also snap to the start of a tab. In other words, when the user releases the scrollview and its speed is low, it snaps to a position. I've implemented this and it works, but there's a bug in it.

What I have now:

The scrollview is its own delegate. at every call to scrollViewDidScroll:, it refreshes its speed-related variables:

-(void)refreshCurrentSpeed
{
    float currentOffset = self.contentOffset.x;
    NSTimeInterval currentTime = [[NSDate date] timeIntervalSince1970];

    deltaOffset = (currentOffset - prevOffset);
    deltaTime = (currentTime - prevTime);
    currentSpeed = deltaOffset/deltaTime;
    prevOffset = currentOffset;
    prevTime = currentTime;

    NSLog(@"deltaOffset is now %f, deltaTime is now %f and speed is %f",deltaOffset,deltaTime,currentSpeed);
}

Then proceeds to snap if needed:

-(void)snapIfNeeded
{
    if(canStopScrolling && currentSpeed <70.0f && currentSpeed>-70.0f)
    {
        NSLog(@"Stopping with a speed of %f points per second", currentSpeed);
        [self stopMoving];

        float scrollDistancePastTabStart = fmodf(self.contentOffset.x, (self.frame.size.width/3));
        float scrollSnapX = self.contentOffset.x - scrollDistancePastTabStart;
        if(scrollDistancePastTabStart > self.frame.size.width/6)
        {
            scrollSnapX += self.frame.size.width/3;
        }
        float maxSnapX = self.contentSize.width-self.frame.size.width;
        if(scrollSnapX>maxSnapX)
        {
            scrollSnapX = maxSnapX;
        }
        [UIView animateWithDuration:0.3
                         animations:^{self.contentOffset=CGPointMake(scrollSnapX, self.contentOffset.y);}
                         completion:^(BOOL finished){[self stopMoving];}
        ];
    }
    else
    {
        NSLog(@"Did not stop with a speed of %f points per second", currentSpeed);
    }
}

-(void)stopMoving
{
    if(self.dragging)
    {
        [self setContentOffset:CGPointMake(self.contentOffset.x, self.contentOffset.y) animated:NO];
    }
    canStopScrolling = NO;
}

Here are the delegate methods:

-(void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
    canStopScrolling = NO;
    [self refreshCurrentSpeed];
}

-(void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate
{
    canStopScrolling = YES;
    NSLog(@"Did end dragging");
    [self snapIfNeeded];
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    [self refreshCurrentSpeed];
    [self snapIfNeeded];
}

This works well most of the time, except in two scenarios:
1. When the user scrolls without releasing his/her finger and lets go at a near stationary timing right after moving, it often snaps to its position as it's supposed to, but a lot of times, does not. It usually takes a few attempts to get it to happen. Odd values for time (very low) and/or distance (rather high) appear at the release, causing a high speed value while the scrollView is, in reality, nearly or entirely stationary.
2. When the user taps the scrollview to stop its movement, it seems the scrollview sets the contentOffset to its previous spot. This teleportation results in a very high speed value. This could be fixed by checking if the previous delta is currentDelta*-1, but I'd prefer a more stable solution.

I've tried using didEndDecelerating, but when the glitch occurs, it does not get called. This probably confirms that it's stationary already. There seems to be no delegate method that gets called when the scrollview stopped moving completely.

If you'd like to see the glitch yourself, here's some code to fill the scrollview with tabs:

@interface  UIScrollView <UIScrollViewDelegate>
{
    bool canStopScrolling;
    float prevOffset;
    float deltaOffset; //remembered for debug purposes
    NSTimeInterval prevTime;
    NSTimeInterval deltaTime; //remembered for debug purposes
    float currentSpeed;
}

-(void)stopMoving;
-(void)snapIfNeeded;
-(void)refreshCurrentSpeed;

@end

@implementation TabScrollView

-(id) init
{
    self = [super init];
    if(self)
    {
        self.delegate = self;
        self.frame = CGRectMake(0.0f,0.0f,320.0f,40.0f);
        self.backgroundColor = [UIColor grayColor];
        float tabWidth = self.frame.size.width/3;
        self.contentSize = CGSizeMake(100*tabWidth, 40.0f);
        for(int i=0; i<100;i++)
        {
            UIView *view = [[UIView alloc] init];
            view.frame = CGRectMake(i*tabWidth,0.0f,tabWidth,40.0f);
            view.backgroundColor = [UIColor colorWithWhite:(float)(i%2) alpha:1.0f];
            [self addSubview:view];
        }
    }
    return self;
}

@end

A shorter version of this question: how to know when the scrollview stopped scrolling? didEndDecelerating: does not get called when you release it stationary, didEndDragging: happens a lot during the scrolling and checking for speed is unreliable due to this odd 'jump' which sets the speed to something random.

Body:
It is important to understand, that the when UIScrollView is stopping to move it triggers two different functions of the UIScrollViewDelegate depending on how strong the user has pushed.

stopDragging is triggered, when the user stops his drag gesture on the screen. When this was very slowly no more movement will happen after that.

stopDecelerating is triggered, when the user has pushed the scroll view in a way, so that it is still moving after the user touches up his finger and then comes to an end. This function is not always triggered, it is not triggered, when there is no movement after the user touches up his finger. Then only the function above "stopDragging" is triggered.

So in conclusion it is necessary to combine the two functions like @WayneBurkett already pointed out in his answer.

In Swift 5.X:

func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
    myFunction()
}

func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {
    if decelerate == false {
        myFunction()
    }
}

private func myFunction() {
    // scrollView did stop moving -> do what ever
    // ...
}


问:
How can I add a gltf model to Aframe & AR.js with an alpha channel?
--Update-- I have added this code and it seems to have helped. I can see that the glass is now clear, but it's still incredibly dark.

Warning: I'm a newbie to WebAR (and coding in general).... but rest assured I have scoured the internet for days trying to figure this out.

I am trying to use a gltf model with AR.js and Aframe to make a WebAR experience. Here is a portion of my code:

```<code><script src="https://aframe.io/releases/0.8.2/aframe.min.js"></script>
<script src="build/aframe-ar.js"></script>
<script src="https://rawgit.com/donmccurdy/aframe-extras/master/dist/aframe-extras.loaders.min.js"></script>

<!-- marker -->
<a-marker type='pattern' url='https://raw.githubusercontent.com/merowell/Evidence-Collection-Procedures/master/assets/markers/patt/pattern-biological-1.patt'>

<!-- add .gltf model-->
    <a-entity gltf-model="https://raw.githubusercontent.com/merowell/Evidence-Collection-Procedures/master/assets/models/biological/biological.gltf" position="0 0 0" crossOrigin="anonymous" rotation="0 0 0" scale=".3 .3 .3">
    </a-entity>
</code>```

I have figured out how to get the gltf model to work with textures, but I still cannot seem to get the exact look I'm going for. Mostly, the glass on the bottles are supposed to be clear and not opaque. I imported and edited the model in Blender 2.82. I am using the Principled BSDF node and have set the Blend mode to "alpha blend"

Here is a screenshot:

After exporting the model, I tested it in the gltf validator and it looks like I want it to. Here is a screenshot:

Unfortunately, the active marker does not display it in the same way. Maybe there is something else I need to do to make the alpha channels work? Or perhaps it's an error in my code?
Here is a screenshot of the active marker:

Finally, I have tried adding the model as a glb file instead, listed as an asset. But when I list assets within the a-scene tag, the webcam won't deploy. However, I have read other people use this method.

答:
EDITED-- problem still persists.... the models are only transparent in relation to other models. But you can not see the real world environment through the transparent material (as you can with a wavefront obj)

This solved the issue... and I just had to go to the blender file and re-export the model with a lighter color in order to get it to look the way I want.

Body:
--Update-- I have added this code and it seems to have helped. I can see that the glass is now clear, but it's still incredibly dark.

Warning: I'm a newbie to WebAR (and coding in general).... but rest assured I have scoured the internet for days trying to figure this out.

I am trying to use a gltf model with AR.js and Aframe to make a WebAR experience. Here is a portion of my code:

I have figured out how to get the gltf model to work with textures, but I still cannot seem to get the exact look I'm going for. Mostly, the glass on the bottles are supposed to be clear and not opaque. I imported and edited the model in Blender 2.82. I am using the Principled BSDF node and have set the Blend mode to "alpha blend"

Here is a screenshot:

After exporting the model, I tested it in the gltf validator and it looks like I want it to. Here is a screenshot:

Unfortunately, the active marker does not display it in the same way. Maybe there is something else I need to do to make the alpha channels work? Or perhaps it's an error in my code?
Here is a screenshot of the active marker:

Finally, I have tried adding the model as a glb file instead, listed as an asset. But when I list assets within the a-scene tag, the webcam won't deploy. However, I have read other people use this method.


问:
How to print file contents with filename before each line?
I have several files, say, a,b,c, I would like to something like

```<code> > cat a b c
</code>```

but with "a,"  in the beginning lines of a. "b," in the beginning of the lines of b and "c," in the beginning of the lines of c.
I can do this using python:

```<code>#!/bin/env python

files = 'a b c'

all_lines = []
for f in files.split():
  lines = open(f, 'r').readlines()
  for line in lines:
    all_lines.append(f + ',' + line.strip())

fout = open('out.csv', 'w')
fout.write('\n'.join(all_lines))
fout.close()
</code>```

but I would prefer to do it in the command line, combining some simple commands with the pipe | operator.

Is there a easy way of accomplishing this?

Thanks.

答:
```<code>perl -pe 'print "$ARGV,"' a b c
</code>```

will do it.

Body:
I have several files, say, a,b,c, I would like to something like

 > cat a b c

but with "a,"  in the beginning lines of a. "b," in the beginning of the lines of b and "c," in the beginning of the lines of c.
I can do this using python:

#!/bin/env python

files = 'a b c'

all_lines = []
for f in files.split():
  lines = open(f, 'r').readlines()
  for line in lines:
    all_lines.append(f + ',' + line.strip())

fout = open('out.csv', 'w')
fout.write('\n'.join(all_lines))
fout.close()

but I would prefer to do it in the command line, combining some simple commands with the pipe | operator.

Is there a easy way of accomplishing this?

Thanks.

Body:
perl -pe 'print "$ARGV,"' a b c

will do it.


问:
Is Byte Really The Minimum Addressable Unit?
Section 3.6 of C11 standard defines "byte" as "addressable unit of data storage ... to hold ... character".

Section 1.7 of C++11 standard defines "byte" as "the fundamental storage unit in the C++ memory model ... to contain ... character".

Both definitions does not say that "byte" is the minimum addressable unit. Is this because standards intentionally want to abstract from a specific machine ? Can you provide a real example of machine where C/C++ compiler were decided to have "byte" longer/shorter than the minimum addressable unit ?

答:
I programmed both the TMS34010 and its successor TMS34020 graphics chips back in the early 1990's and they had a flat address space and were bit addressable i.e. addresses indexed each bit. This was very useful for computer graphics of the time and back when memory was a lot more precious.

The embedded C-compiler didn't really have away to access individual bits directly, since from a (standard) C language point of view the byte was still the smallest unit as pointed out in a previous post.

Thus if you want to read/write a stream of bits in C, you need to read/write (at least) a byte at a time and buffer (for example when writing a Arithmetic or Huffman Coder).


问:
Unable to direct Route53 records to new server
I am trying to point a domain from a website (radicalxchange.org) currently hosted by Firebase to a new version hosted in a Digital Ocean droplet. The name servers are managed by AWS Route53. When I change the A record in Route53 to my D.O. droplet IP address (167.99.59.52), the site immediately stops loading. I've tried to wait a few hours but it never connects.

I should note that Route53 contains a lot of other stuff related to our site (CNAME, MX & TXT records) however I've been under the impression that the only thing necessary to route website traffic to the new IP is the A record. What am I doing wrong?

答:
Well, your Digital Ocean droplet is kind of misconfigured:

1) from current hosting, you have permanent redirect to https (and if your browser have that already cached, it will immediately go to https://radicalxchange.org), and you don't have https configured in your new hosting

2)  Even if you use clean browser, your new http://radicalxchange.org will redirect you to http://167.99.59.52/, which is quite strange.

I suggest you hardcode 167.99.59.52 radicalxchange.org entry in your hosts file, and test thoroughly, and only then make DNS changes.


问:
Attempted import error: 'react-table' does not contain a default export (imported as 'ReactTable')
React Table Import error

Code import style below :

```<code>import ReactTable from 'react-table'
import 'react-table/react-table.css'
</code>```

While its running, its showing error message like this

Attempted import error: 'react-table' does not contain a default export (imported as 'ReactTable').

What to do now?

答:
The error talks about there is no named default export like ReactTable. You might need to import objects differently.

Maybe you can try as the following:

```<code>import * as ReactTable from 'react-table'
</code>```

Additionally I checked react-table on the official npmjs page and I see there are examples like the following:

```<code>import { useTable, useFilters, useGlobalFilter } from 'react-table';
</code>```

I guess you might want to use just few specific things from the library thus I suggest to go with importing only the required features like import { } from 'react-table' where between { } you list what you need.

Body:
React Table Import error

Code import style below :

import ReactTable from 'react-table'
import 'react-table/react-table.css'

While its running, its showing error message like this

Attempted import error: 'react-table' does not contain a default export (imported as 'ReactTable').

What to do now?

Body:
The error talks about there is no named default export like ReactTable. You might need to import objects differently.

Maybe you can try as the following:

import * as ReactTable from 'react-table'

Additionally I checked react-table on the official npmjs page and I see there are examples like the following:

import { useTable, useFilters, useGlobalFilter } from 'react-table';

I guess you might want to use just few specific things from the library thus I suggest to go with importing only the required features like import { } from 'react-table' where between { } you list what you need.


问:
Google Apps Script Calendar Service: Get the start date of a recurring (all day) event
I'm referring to this question. Is it still not possible to retrieve the start date of a recurring (all day) event in standard mode (without enabling "Advanced Google services")?</p>

答:
Does this do it:</p>

```<code>function findFirstEvent() {
  var cal=CalendarApp.getCalendarById("Calendar Id");
  var startTime=new Date(1850,0,1);
  var endTime=new Date();
  var events=cal.getEvents(startTime, endTime,{search:'Keywords contained in the event or just the title'});
  Logger.log('StartTime: %s, Id: %s',events[0].getStartTime(),events[0].getId());
}
</code>```

Body:
Does this do it:

function findFirstEvent() {
  var cal=CalendarApp.getCalendarById("Calendar Id");
  var startTime=new Date(1850,0,1);
  var endTime=new Date();
  var events=cal.getEvents(startTime, endTime,{search:'Keywords contained in the event or just the title'});
  Logger.log('StartTime: %s, Id: %s',events[0].getStartTime(),events[0].getId());
}


问:
CDN links in php include files
I am working a site project with Bootstrap 4.4.1. I use the CDN links to place them right before closing the . In order to avoid lots of coding in all pages, I want to use a php include file which contains all the scripts below/ This file I named "js-remote.php". This is inside a folder called "js".

I inserted the code on every content page (I am doing all php pages) and the path is:

<?php include '../js/js-remote.php'>

But doesn't work. I have navigation bar also as included file, the menu is shown but the dropdowns don't work properly. Even when I paste the full scripts codes of the CDN (without using any php include) don't work either.

ONLY works when I don't use the include files, just when pasting the complete code as a regular html file.Get below the code I wanna use in a php include file. Observations, please.

```<code><script src="https://code.jquery.com/jquery-3.4.1.slim.min.js" integrity="sha384-J6qa4849blE2+poT4WnyKhv5vZF5SrPo0iEjwBvKU7imGFAV0wwj1yYfoRSJoZ+n" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js" integrity="sha384-wfSDF2E50Y2D1uUdj0O3uMBJnjuUD4Ih7YwaYd1iqfktj0Uod8GCExl3Og8ifwB6" crossorigin="anonymous"></script>
</body>
</code>```

But instead of pasting the whole scripts I just want to put one single line:

```<code><?php include '../js/js-remote.php' ?>
</body>
<--! Could it work?-->
</code>```

Where "js-remote.php" is a page which contains all the cdn scripts above and more coming in the future.

Sorry for the redundance but it's necessary. The "js-remote.php" file contains:

```<code><script src="https://code.jquery.com/jquery-3.4.1.slim.min.js" integrity="sha384-J6qa4849blE2+poT4WnyKhv5vZF5SrPo0iEjwBvKU7imGFAV0wwj1yYfoRSJoZ+n" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js" integrity="sha384-wfSDF2E50Y2D1uUdj0O3uMBJnjuUD4Ih7YwaYd1iqfktj0Uod8GCExl3Og8ifwB6" crossorigin="anonymous"></script>
</code>```

答:
This is because you need to place the scripts near the end of the document.

According to the docs:

Many of our components require the use of JavaScript to function.
  Specifically, they require jQuery, Popper.js, and our own JavaScript
  plugins. Place the following s near the end of your pages,
  right before the closing  tag, to enable them. jQuery must come
  first, then Popper.js, and then our JavaScript plugins.

Title: CDN links in php include files

Body:
I am working a site project with Bootstrap 4.4.1. I use the CDN links to place them right before closing the . In order to avoid lots of coding in all pages, I want to use a php include file which contains all the scripts below/ This file I named "js-remote.php". This is inside a folder called "js".

I inserted the code on every content page (I am doing all php pages) and the path is:

<?php include '../js/js-remote.php'>

But doesn't work. I have navigation bar also as included file, the menu is shown but the dropdowns don't work properly. Even when I paste the full scripts codes of the CDN (without using any php include) don't work either.

ONLY works when I don't use the include files, just when pasting the complete code as a regular html file.Get below the code I wanna use in a php include file. Observations, please.

But instead of pasting the whole scripts I just want to put one single line:

<?php include '../js/js-remote.php' ?>

<--! Could it work?-->

Where "js-remote.php" is a page which contains all the cdn scripts above and more coming in the future.

Sorry for the redundance but it's necessary. The "js-remote.php" file contains:


问:
SD card initialization using SPI
I saw a lot of information about MMC/SD cards and I tried to make a library to read this (modifying the Procyon AVRlib).

But I have some problems here. I don't change the original code and tried here. My problem is about the initialization of an SD card. I have two here, a 256 MB and another 1 GB.

I send the init commands in this order: CMD0, CMD55, ACMD41, and CMD1.

But the 256 MB SD card only returns a 0x01 response for each command. I send the CMD1 a lot of times and the 256 MB SD card always returns only 0x01, never 0x00.

The 1 GB SD is more crazy... CMD0 returns with 0x01. Nice, but the CMD55 command responds with 0x05. At other times it responds with 0xC1 and also sometimes responds with 0xF0 with a 0x5F in the next interation...

Around the Internet there is information and examples, but it is a bit confused. Here in my project, I must use a 1 GB card and I'm trying with a microSD card with an SD adapter (I think that this is not the problem).

How do I fix this problem?

PS: My problem is like the problem in Stack Overflow question Initializing SD card in SPI issues, but the solution didn't solve my problem. The 1 GB SD card only returns 0x01 ever...  :cry:

答:
However, the solution may not work for some makes of cards. For such cards, you may have to edit the procedure/library. That may be why your 1 GB card acts differently -- it may be a different make of card. The SPI mode of certain cards may not be that popular for commercial equipment, and thus may be more deviated in specification by some card manufacturers.

If you bit bang the commands and clocks, you may have more control and confidence that those procedures are correct. That is useful because you need some solid ground to build on to progress bit by bit. I found that the <400 kHz 80 clocks was critical on one card, but could run at more than 2 MHz on another.

Try to progress one command at a time that is reliable for both cards.

Title: SD card initialization using SPI


问:
Why am I obtaining this exception trying to configure DB connection on a Spring Boot application? Error creating bean with name 'dataSource'
I am pretty new in Spring Boot and I have some problem trying to set the connection with a Maria DB.

I am working on a Spring Boot 1.5.9.RELEASE project, I see the version into the pom.xml file containing this information:

```<code><parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>1.5.9.RELEASE</version>
    <relativePath/> <!-- lookup parent from repository -->
</parent>
</code>```

Into the pom.xml file I set also these dependencies:

```<code><dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>

<dependency>
  <groupId>org.mariadb.jdbc</groupId>
  <artifactId>mariadb-java-client</artifactId>
  <version>1.5.7</version>
</dependency>
</code>```

Then I have the application.yml file that should contains the database configuration. Following some tutorial I configured it in this way:

```<code>spring:
    application:
            name: Spring Boot Excel API
            datasource:
                platform: mariadb
                driverClassName: org.mariadb.jdbc.Driver
                url: mysql://localhost:3306/energydb
                username: root
                password: password
                timeBetweenEvictionRunsMillis: 1000
                testWhileIdle: true
                validationQuery: SELECT 1
debug: true
</code>```

The problem is that when I start my application by this command:

```<code>mvn spring-boot:run
</code>```

I obtain the following errors into the stacktrace:

```<code>***************************
APPLICATION FAILED TO START
***************************

Description:

Cannot determine embedded database driver class for database type NONE

Action:

If you want an embedded database please put a supported one on the classpath. If you have database settings to be loaded from a particular profile you may need to active it (no profiles are currently active).

[WARNING]
java.lang.reflect.InvocationTargetException
    at jdk.internal.reflect.NativeMethodAccessorImpl.invoke0 (Native Method)
    at jdk.internal.reflect.NativeMethodAccessorImpl.invoke (NativeMethodAccessorImpl.java:62)
    at jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke (DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke (Method.java:567)
    at org.springframework.boot.maven.AbstractRunMojo$LaunchRunner.run (AbstractRunMojo.java:527)
    at java.lang.Thread.run (Thread.java:830)
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'dataSource' defined in class path resource [org/springframework/boot/autoconfigure/jdbc/DataSourceConfiguration$Tomcat.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.apache.tomcat.jdbc.pool.DataSource]: Factory method 'dataSource' threw exception; nested exception is org.springframework.boot.autoconfigure.jdbc.DataSourceProperties$DataSourceBeanCreationException: Cannot determine embedded database driver class for database type NONE. If you want an embedded database please put a supported one on the classpath. If you have database settings to be loaded from a particular profile you may need to active it (no profiles are currently active).
    at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod (ConstructorResolver.java:599)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod (AbstractAutowireCapableBeanFactory.java:1173)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance (AbstractAutowireCapableBeanFactory.java:1067)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean (AbstractAutowireCapableBeanFactory.java:513)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean (AbstractAutowireCapableBeanFactory.java:483)
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject (AbstractBeanFactory.java:306)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton (DefaultSingletonBeanRegistry.java:230)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean (AbstractBeanFactory.java:302)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean (AbstractBeanFactory.java:197)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons (DefaultListableBeanFactory.java:761)
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization (AbstractApplicationContext.java:867)
    at org.springframework.context.support.AbstractApplicationContext.refresh (AbstractApplicationContext.java:543)
    at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.refresh (EmbeddedWebApplicationContext.java:122)
    at org.springframework.boot.SpringApplication.refresh (SpringApplication.java:693)
    at org.springframework.boot.SpringApplication.refreshContext (SpringApplication.java:360)
    at org.springframework.boot.SpringApplication.run (SpringApplication.java:303)
    at org.springframework.boot.SpringApplication.run (SpringApplication.java:1118)
    at org.springframework.boot.SpringApplication.run (SpringApplication.java:1107)
    at com.springboot.excelapi.Application.main (Application.java:12)
    at jdk.internal.reflect.NativeMethodAccessorImpl.invoke0 (Native Method)
    at jdk.internal.reflect.NativeMethodAccessorImpl.invoke (NativeMethodAccessorImpl.java:62)
    at jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke (DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke (Method.java:567)
    at org.springframework.boot.maven.AbstractRunMojo$LaunchRunner.run (AbstractRunMojo.java:527)
    at java.lang.Thread.run (Thread.java:830)
Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.apache.tomcat.jdbc.pool.DataSource]: Factory method 'dataSource' threw exception; nested exception is org.springframework.boot.autoconfigure.jdbc.DataSourceProperties$DataSourceBeanCreationException: Cannot determine embedded database driver class for database type NONE. If you want an embedded database please put a supported one on the classpath. If you have database settings to be loaded from a particular profile you may need to active it (no profiles are currently active).
    at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate (SimpleInstantiationStrategy.java:189)
    at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod (ConstructorResolver.java:588)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod (AbstractAutowireCapableBeanFactory.java:1173)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance (AbstractAutowireCapableBeanFactory.java:1067)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean (AbstractAutowireCapableBeanFactory.java:513)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean (AbstractAutowireCapableBeanFactory.java:483)
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject (AbstractBeanFactory.java:306)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton (DefaultSingletonBeanRegistry.java:230)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean (AbstractBeanFactory.java:302)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean (AbstractBeanFactory.java:197)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons (DefaultListableBeanFactory.java:761)
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization (AbstractApplicationContext.java:867)
    at org.springframework.context.support.AbstractApplicationContext.refresh (AbstractApplicationContext.java:543)
    at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.refresh (EmbeddedWebApplicationContext.java:122)
    at org.springframework.boot.SpringApplication.refresh (SpringApplication.java:693)
    at org.springframework.boot.SpringApplication.refreshContext (SpringApplication.java:360)
    at org.springframework.boot.SpringApplication.run (SpringApplication.java:303)
    at org.springframework.boot.SpringApplication.run (SpringApplication.java:1118)
    at org.springframework.boot.SpringApplication.run (SpringApplication.java:1107)
    at com.springboot.excelapi.Application.main (Application.java:12)
    at jdk.internal.reflect.NativeMethodAccessorImpl.invoke0 (Native Method)
    at jdk.internal.reflect.NativeMethodAccessorImpl.invoke (NativeMethodAccessorImpl.java:62)
    at jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke (DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke (Method.java:567)
    at org.springframework.boot.maven.AbstractRunMojo$LaunchRunner.run (AbstractRunMojo.java:527)
    at java.lang.Thread.run (Thread.java:830)
Caused by: org.springframework.boot.autoconfigure.jdbc.DataSourceProperties$DataSourceBeanCreationException: Cannot determine embedded database driver class for database type NONE. If you want an embedded database please put a supported one on the classpath. If you have database settings to be loaded from a particular profile you may need to active it (no profiles are currently active).
    at org.springframework.boot.autoconfigure.jdbc.DataSourceProperties.determineDriverClassName (DataSourceProperties.java:247)
    at org.springframework.boot.autoconfigure.jdbc.DataSourceProperties.initializeDataSourceBuilder (DataSourceProperties.java:184)
    at org.springframework.boot.autoconfigure.jdbc.DataSourceConfiguration.createDataSource (DataSourceConfiguration.java:42)
    at org.springframework.boot.autoconfigure.jdbc.DataSourceConfiguration$Tomcat.dataSource (DataSourceConfiguration.java:56)
    at jdk.internal.reflect.NativeMethodAccessorImpl.invoke0 (Native Method)
    at jdk.internal.reflect.NativeMethodAccessorImpl.invoke (NativeMethodAccessorImpl.java:62)
    at jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke (DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke (Method.java:567)
    at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate (SimpleInstantiationStrategy.java:162)
    at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod (ConstructorResolver.java:588)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod (AbstractAutowireCapableBeanFactory.java:1173)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance (AbstractAutowireCapableBeanFactory.java:1067)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean (AbstractAutowireCapableBeanFactory.java:513)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean (AbstractAutowireCapableBeanFactory.java:483)
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject (AbstractBeanFactory.java:306)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton (DefaultSingletonBeanRegistry.java:230)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean (AbstractBeanFactory.java:302)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean (AbstractBeanFactory.java:197)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons (DefaultListableBeanFactory.java:761)
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization (AbstractApplicationContext.java:867)
    at org.springframework.context.support.AbstractApplicationContext.refresh (AbstractApplicationContext.java:543)
    at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.refresh (EmbeddedWebApplicationContext.java:122)
    at org.springframework.boot.SpringApplication.refresh (SpringApplication.java:693)
    at org.springframework.boot.SpringApplication.refreshContext (SpringApplication.java:360)
    at org.springframework.boot.SpringApplication.run (SpringApplication.java:303)
    at org.springframework.boot.SpringApplication.run (SpringApplication.java:1118)
    at org.springframework.boot.SpringApplication.run (SpringApplication.java:1107)
    at com.springboot.excelapi.Application.main (Application.java:12)
    at jdk.internal.reflect.NativeMethodAccessorImpl.invoke0 (Native Method)
    at jdk.internal.reflect.NativeMethodAccessorImpl.invoke (NativeMethodAccessorImpl.java:62)
    at jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke (DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke (Method.java:567)
    at org.springframework.boot.maven.AbstractRunMojo$LaunchRunner.run (AbstractRunMojo.java:527)
    at java.lang.Thread.run (Thread.java:830)
[INFO] ------------------------------------------------------------------------
[INFO] BUILD FAILURE
[INFO] ------------------------------------------------------------------------
[INFO] Total time:  4.316 s
[INFO] Finished at: 2020-02-15T22:01:40+01:00
[INFO] ------------------------------------------------------------------------
[ERROR] Failed to execute goal org.springframework.boot:spring-boot-maven-plugin:1.5.9.RELEASE:run (default-cli) on project excel-api: An exception occurred while running. null: InvocationTargetException: Error creating bean with name 'dataSource' defined in class path resource [org/springframework/boot/autoconfigure/jdbc/DataSourceConfiguration$Tomcat.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.apache.tomcat.jdbc.pool.DataSource]: Factory method 'dataSource' threw exception; nested exception is org.springframework.boot.autoconfigure.jdbc.DataSourceProperties$DataSourceBeanCreationException: Cannot determine embedded database driver class for database type NONE. If you want an embedded database please put a supported one on the classpath. If you have database settings to be loaded from a particular profile you may need to active it (no profiles are currently active). -> [Help 1]
[ERROR]
[ERROR] To see the full stack trace of the errors, re-run Maven with the -e switch.
[ERROR] Re-run Maven using the -X switch to enable full debug logging.
[ERROR]
[ERROR] For more information about the errors and possible solutions, please read the following articles:
[ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/MojoExecutionException
</code>```

Why? What is wrong? What am I missing? How can I try to fix this issue?

答: I am new to YAML but you may need to escape the JDBC URL as it contains a colon which is used by YAML for a property value. </p>

Body:
I am pretty new in Spring Boot and I have some problem trying to set the connection with a Maria DB.

I am working on a Spring Boot 1.5.9.RELEASE project, I see the version into the pom.xml file containing this information:

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>1.5.9.RELEASE</version>
    <relativePath/>
</parent>

Into the pom.xml file I set also these dependencies:

<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>

<dependency>
  <groupId>org.mariadb.jdbc</groupId>
  <artifactId>mariadb-java-client</artifactId>
  <version>1.5.7</version>
</dependency>

Then I have the application.yml file that should contains the database configuration. Following some tutorial I configured it in this way:

spring:
    application:
            name: Spring Boot Excel API
            datasource:
                platform: mariadb
                driverClassName: org.mariadb.jdbc.Driver
                url: mysql://localhost:3306/energydb
                username: root
                password: password
                timeBetweenEvictionRunsMillis: 1000
                testWhileIdle: true
                validationQuery: SELECT 1
debug: true

The problem is that when I start my application by this command:

mvn spring-boot:run

I obtain the following errors into the stacktrace:

***************************
APPLICATION FAILED TO START
***************************

Description:

Cannot determine embedded database driver class for database type NONE

Action:

If you want an embedded database please put a supported one on the classpath. If you have database settings to be loaded from a particular profile you may need to active it (no profiles are currently active).

[WARNING]
java.lang.reflect.InvocationTargetException
    at jdk.internal.reflect.NativeMethodAccessorImpl.invoke0 (Native Method)
    at jdk.internal.reflect.NativeMethodAccessorImpl.invoke (NativeMethodAccessorImpl.java:62)
    at jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke (DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke (Method.java:567)
    at org.springframework.boot.maven.AbstractRunMojo$LaunchRunner.run (AbstractRunMojo.java:527)
    at java.lang.Thread.run (Thread.java:830)
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'dataSource' defined in class path resource [org/springframework/boot/autoconfigure/jdbc/DataSourceConfiguration$Tomcat.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.apache.tomcat.jdbc.pool.DataSource]: Factory method 'dataSource' threw exception; nested exception is org.springframework.boot.autoconfigure.jdbc.DataSourceProperties$DataSourceBeanCreationException: Cannot determine embedded database driver class for database type NONE. If you want an embedded database please put a supported one on the classpath. If you have database settings to be loaded from a particular profile you may need to active it (no profiles are currently active).
    at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod (ConstructorResolver.java:599)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod (AbstractAutowireCapableBeanFactory.java:1173)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance (AbstractAutowireCapableBeanFactory.java:1067)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean (AbstractAutowireCapableBeanFactory.java:513)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean (AbstractAutowireCapableBeanFactory.java:483)
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject (AbstractBeanFactory.java:306)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton (DefaultSingletonBeanRegistry.java:230)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean (AbstractBeanFactory.java:302)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean (AbstractBeanFactory.java:197)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons (DefaultListableBeanFactory.java:761)
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization (AbstractApplicationContext.java:867)
    at org.springframework.context.support.AbstractApplicationContext.refresh (AbstractApplicationContext.java:543)
    at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.refresh (EmbeddedWebApplicationContext.java:122)
    at org.springframework.boot.SpringApplication.refresh (SpringApplication.java:693)
    at org.springframework.boot.SpringApplication.refreshContext (SpringApplication.java:360)
    at org.springframework.boot.SpringApplication.run (SpringApplication.java:303)
    at org.springframework.boot.SpringApplication.run (SpringApplication.java:1118)
    at org.springframework.boot.SpringApplication.run (SpringApplication.java:1107)
    at com.springboot.excelapi.Application.main (Application.java:12)
    at jdk.internal.reflect.NativeMethodAccessorImpl.invoke0 (Native Method)
    at jdk.internal.reflect.NativeMethodAccessorImpl.invoke (NativeMethodAccessorImpl.java:62)
    at jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke (DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke (Method.java:567)
    at org.springframework.boot.maven.AbstractRunMojo$LaunchRunner.run (AbstractRunMojo.java:527)
    at java.lang.Thread.run (Thread.java:830)
Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.apache.tomcat.jdbc.pool.DataSource]: Factory method 'dataSource' threw exception; nested exception is org.springframework.boot.autoconfigure.jdbc.DataSourceProperties$DataSourceBeanCreationException: Cannot determine embedded database driver class for database type NONE. If you want an embedded database please put a supported one on the classpath. If you have database settings to be loaded from a particular profile you may need to active it (no profiles are currently active).
    at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate (SimpleInstantiationStrategy.java:189)
    at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod (ConstructorResolver.java:588)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod (AbstractAutowireCapableBeanFactory.java:1173)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance (AbstractAutowireCapableBeanFactory.java:1067)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean (AbstractAutowireCapableBeanFactory.java:513)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean (AbstractAutowireCapableBeanFactory.java:483)
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject (AbstractBeanFactory.java:306)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton (DefaultSingletonBeanRegistry.java:230)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean (AbstractBeanFactory.java:302)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean (AbstractBeanFactory.java:197)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons (DefaultListableBeanFactory.java:761)
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization (AbstractApplicationContext.java:867)
    at org.springframework.context.support.AbstractApplicationContext.refresh (AbstractApplicationContext.java:543)
    at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.refresh (EmbeddedWebApplicationContext.java:122)
    at org.springframework.boot.SpringApplication.refresh (SpringApplication.java:693)
    at org.springframework.boot.SpringApplication.refreshContext (SpringApplication.java:360)
    at org.springframework.boot.SpringApplication.run (SpringApplication.java:303)
    at org.springframework.boot.SpringApplication.run (SpringApplication.java:1118)
    at org.springframework.boot.SpringApplication.run (SpringApplication.java:1107)
    at com.springboot.excelapi.Application.main (Application.java:12)
    at jdk.internal.reflect.NativeMethodAccessorImpl.invoke0 (Native Method)
    at jdk.internal.reflect.NativeMethodAccessorImpl.invoke (NativeMethodAccessorImpl.java:62)
    at jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke (DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke (Method.java:567)
    at org.springframework.boot.maven.AbstractRunMojo$LaunchRunner.run (AbstractRunMojo.java:527)
    at java.lang.Thread.run (Thread.java:830)
Caused by: org.springframework.boot.autoconfigure.jdbc.DataSourceProperties$DataSourceBeanCreationException: Cannot determine embedded database driver class for database type NONE. If you want an embedded database please put a supported one on the classpath. If you have database settings to be loaded from a particular profile you may need to active it (no profiles are currently active).
    at org.springframework.boot.autoconfigure.jdbc.DataSourceProperties.determineDriverClassName (DataSourceProperties.java:247)
    at org.springframework.boot.autoconfigure.jdbc.DataSourceProperties.initializeDataSourceBuilder (DataSourceProperties.java:184)
    at org.springframework.boot.autoconfigure.jdbc.DataSourceConfiguration.createDataSource (DataSourceConfiguration.java:42)
    at org.springframework.boot.autoconfigure.jdbc.DataSourceConfiguration$Tomcat.dataSource (DataSourceConfiguration.java:56)
    at jdk.internal.reflect.NativeMethodAccessorImpl.invoke0 (Native Method)
    at jdk.internal.reflect.NativeMethodAccessorImpl.invoke (NativeMethodAccessorImpl.java:62)
    at jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke (DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke (Method.java:567)
    at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate (SimpleInstantiationStrategy.java:162)
    at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod (ConstructorResolver.java:588)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod (AbstractAutowireCapableBeanFactory.java:1173)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance (AbstractAutowireCapableBeanFactory.java:1067)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean (AbstractAutowireCapableBeanFactory.java:513)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean (AbstractAutowireCapableBeanFactory.java:483)
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject (AbstractBeanFactory.java:306)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton (DefaultSingletonBeanRegistry.java:230)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean (AbstractBeanFactory.java:302)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean (AbstractBeanFactory.java:197)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons (DefaultListableBeanFactory.java:761)
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization (AbstractApplicationContext.java:867)
    at org.springframework.context.support.AbstractApplicationContext.refresh (AbstractApplicationContext.java:543)
    at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.refresh (EmbeddedWebApplicationContext.java:122)
    at org.springframework.boot.SpringApplication.refresh (SpringApplication.java:693)
    at org.springframework.boot.SpringApplication.refreshContext (SpringApplication.java:360)
    at org.springframework.boot.SpringApplication.run (SpringApplication.java:303)
    at org.springframework.boot.SpringApplication.run (SpringApplication.java:1118)
    at org.springframework.boot.SpringApplication.run (SpringApplication.java:1107)
    at com.springboot.excelapi.Application.main (Application.java:12)
    at jdk.internal.reflect.NativeMethodAccessorImpl.invoke0 (Native Method)
    at jdk.internal.reflect.NativeMethodAccessorImpl.invoke (NativeMethodAccessorImpl.java:62)
    at jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke (DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke (Method.java:567)
    at org.springframework.boot.maven.AbstractRunMojo$LaunchRunner.run (AbstractRunMojo.java:527)
    at java.lang.Thread.run (Thread.java:830)
[INFO] ------------------------------------------------------------------------
[INFO] BUILD FAILURE
[INFO] ------------------------------------------------------------------------
[INFO] Total time:  4.316 s
[INFO] Finished at: 2020-02-15T22:01:40+01:00
[INFO] ------------------------------------------------------------------------
[ERROR] Failed to execute goal org.springframework.boot:spring-boot-maven-plugin:1.5.9.RELEASE:run (default-cli) on project excel-api: An exception occurred while running. null: InvocationTargetException: Error creating bean with name 'dataSource' defined in class path resource [org/springframework/boot/autoconfigure/jdbc/DataSourceConfiguration$Tomcat.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.apache.tomcat.jdbc.pool.DataSource]: Factory method 'dataSource' threw exception; nested exception is org.springframework.boot.autoconfigure.jdbc.DataSourceProperties$DataSourceBeanCreationException: Cannot determine embedded database driver class for database type NONE. If you want an embedded database please put a supported one on the classpath. If you have database settings to be loaded from a particular profile you may need to active it (no profiles are currently active). -> [Help 1]
[ERROR]
[ERROR] To see the full stack trace of the errors, re-run Maven with the -e switch.
[ERROR] Re-run Maven using the -X switch to enable full debug logging.
[ERROR]
[ERROR] For more information about the errors and possible solutions, please read the following articles:
[ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/MojoExecutionException

Why? What is wrong? What am I missing? How can I try to fix this issue?


问:
CSV file with Arabic characters is displayed as symbols in Excel
I am using python to extract Arabic tweets from twitter and save it as a CSV file, but when I open the saved file in excel the Arabic language displays as symbols. However, inside python, notepad, or word, it looks good.

May I know where is the problem?

答:
This is a problem I face frequently with Microsoft Excel when opening CSV files that contain Arabic characters. Try the following workaround that I tested on latest versions of Microsoft Excel on both Windows and MacOS:

Open Excel on a blank workbook

Within the Data tab, click on From Text button (if not
    activated, make  sure an empty cell is selected)

Browse and select the CSV file

In the Text Import Wizard, change the File_origin to "Unicode (UTF-8)"

Go next and from the Delimiters, select the delimiter used in your file e.g. comma

Finish and select where to import the data

The Arabic characters should show correctly.


问:
Cannot get just the second list on a page with PHP Simple DOM
I have this code to try and extract a list on a page:

```<code>$websiteURL = "https://waset.org/conferences-in-january-2022-in-tokyo";
$html = file_get_html($websiteURL);

foreach ( $html->find( 'ul') as $ul ) {
     foreach($ul->find('li') as $li) {
        echo "LI: " . $li . "<br>";
    }
}
</code>```

This does what I expect it to do (that is display every
 for ALL
's on the page.

However, If I replace the second foreach with (as I only want to get first list):

```<code>foreach ( $html->find( 'ul', 1) as $ul ) {
</code>```

I get:

"Call to a member function find() on int"

... which suggests that find('ul', 1) did not return anything, but I don't know why?

Note: There are more than two lists on this page.

Anybody know what I am doing wrong?

答:
To answer your question "I suppose my bottom line question is how do I access all the
's from the second  on a web page?" using an API that is relatively modern, well-supported, and built into PHP:

```<code><?php
$url = "https://waset.org/conferences-in-january-2022-in-tokyo";

libxml_use_internal_errors(true);
$dom = new DomDocument();
$dom->loadHtmlFile($url);
$lists = $dom->getElementsByTagName("ul");
$items = $lists[1]->getElementsByTagName("li");
foreach ($items as $item) {
    // clean up extra whitespace
    $text = preg_replace("/\s+/", " ", trim($item->textContent));
    echo "$text\n------\n";
}
</code>```

Output:

ICA 2022: Aeroponics Conference, Tokyo (Jan 07-08, 2022)
------
ICAA 2022: Agroforestry and Applications Conference, Tokyo (Jan 07-08, 2022)
------
ICAAAA 2022: Applied Aerodynamics, Aeronautics and Astronautics Conference, Tokyo (Jan 07-08, 2022)
------
ICAAAE 2022: Aquatic Animals and Aquaculture Engineering Conference, Tokyo (Jan 07-08, 2022)
------
ICAAC 2022: Advances in Astronomical Computing Conference, Tokyo (Jan 07-08, 2022)
------
...
```

<p>Also worth noting that the conference name is in an <code><a></code> element, the location is in a <code><span></code> within it, and the date follows it. Using this, you could fairly simply extract the data:</p>

```function getNodeText(\DomNode $node): string
{
    $return = "";
    foreach($node->childNodes as $child) {
        if ($child->nodeName === "#text") {
            $return .= trim($child->nodeValue);
        }
    }
    return $return;
}

foreach ($items as $item) {
    $conference = getNodeText($item->getElementsByTagName("a")[0]);
    $location = getNodeText($item->getElementsByTagName("span")[0]);
    $date = getNodeText($item);
    echo "------\n$conference | $location | $date\n";
}
```

<p>Output:</p>

<pre class="lang-none prettyprint-override"><code>------
ICA 2022: Aeroponics Conference, | Tokyo | (Jan 07-08, 2022)
------
ICAA 2022: Agroforestry and Applications Conference, | Tokyo | (Jan 07-08, 2022)
------
ICAAAA 2022: Applied Aerodynamics, Aeronautics and Astronautics Conference, | Tokyo | (Jan 07-08, 2022)
------
ICAAAE 2022: Aquatic Animals and Aquaculture Engineering Conference, | Tokyo | (Jan 07-08, 2022)
------
ICAAC 2022: Advances in Astronomical Computing Conference, | Tokyo | (Jan 07-08, 2022)
...
</code>```

Body:
I have this code to try and extract a list on a page:

$websiteURL = "https://waset.org/conferences-in-january-2022-in-tokyo";
$html = file_get_html($websiteURL);

foreach ( $html->find( 'ul') as $ul ) {
     foreach($ul->find('li') as $li) {
        echo "LI: " . $li . "
";
    }
}

This does what I expect it to do (that is display every
 for ALL
's on the page.

However, If I replace the second foreach with (as I only want to get first list):

foreach ( $html->find( 'ul', 1) as $ul ) {

I get:

"Call to a member function find() on int"

... which suggests that find('ul', 1) did not return anything, but I don't know why?

Note: There are more than two lists on this page.

Anybody know what I am doing wrong?

Body:
To answer your question "I suppose my bottom line question is how do I access all the <li>'s from the second  on a web page?" using an API that is relatively modern, well-supported, and built into PHP:

<?php
$url = "https://waset.org/conferences-in-january-2022-in-tokyo";

libxml_use_internal_errors(true);
$dom = new DomDocument();
$dom->loadHtmlFile($url);
$lists = $dom->getElementsByTagName("ul");
$items = $lists[1]->getElementsByTagName("li");
foreach ($items as $item) {
    // clean up extra whitespace
    $text = preg_replace("/\s+/", " ", trim($item->textContent));
    echo "$text\n------\n";
}

Output:

ICA 2022: Aeroponics Conference, Tokyo (Jan 07-08, 2022)
------
ICAA 2022: Agroforestry and Applications Conference, Tokyo (Jan 07-08, 2022)
------
ICAAAA 2022: Applied Aerodynamics, Aeronautics and Astronautics Conference, Tokyo (Jan 07-08, 2022)
------
ICAAAE 2022: Aquatic Animals and Aquaculture Engineering Conference, Tokyo (Jan 07-08, 2022)
------
ICAAC 2022: Advances in Astronomical Computing Conference, Tokyo (Jan 07-08, 2022)
------
...

Also worth noting that the conference name is in an <a> element, the location is in a <span> within it, and the date follows it. Using this, you could fairly simply extract the data:

function getNodeText(\DomNode $node): string
{
    $return = "";
    foreach($node->childNodes as $child) {
        if ($child->nodeName === "#text") {
            $return .= trim($child->nodeValue);
        }
    }
    return $return;
}

foreach ($items as $item) {
    $conference = getNodeText($item->getElementsByTagName("a")[0]);
    $location = getNodeText($item->getElementsByTagName("span")[0]);
    $date = getNodeText($item);
    echo "------\n$conference | $location | $date\n";
}

Output:

------
ICA 2022: Aeroponics Conference, | Tokyo | (Jan 07-08, 2022)
------
ICAA 2022: Agroforestry and Applications Conference, | Tokyo | (Jan 07-08, 2022)
------
ICAAAA 2022: Applied Aerodynamics, Aeronautics and Astronautics Conference, | Tokyo | (Jan 07-08, 2022)
------
ICAAAE 2022: Aquatic Animals and Aquaculture Engineering Conference, | Tokyo | (Jan 07-08, 2022)
------
ICAAC 2022: Advances in Astronomical Computing Conference, | Tokyo | (Jan 07-08, 2022)
...


问:
Email expiration tokens without usage of database and crontab deletion
I have API server with Auth (registration, login, forgotten password, etc..) based on JWT token session.

When user forgot password, he gets email with unique token and link where he can reset his password.

At this moment, I am generating UUID token which is saved into database with expiration field.

After user reset his password or token expires, this token is invalidated. Invalidated tokens are deleted every midnight by crontab to keep database clean.

Is there any other way to do this? Maybe without usage of database?

I was thinking about bundling token UUID into JWT string. This way I do not need database row.
But then I realized, that this token will be valid until it expires, so user can change his password infinitely. Only fix I see is add this token into revoked list (in database) until it expires, but then I again used database :D

Any ideas?

答:
Auth is a complex domain, I would use an existing solution like Auth0 to handle this, as there are too many flows to consider.

That said, you can send a JWT token in the reset password link. It will have the expiry date and user id. Signed JWT tokens cannot be manipulated by users, so we can trust them on when they expire. This way you do not need a DB entry at all to track this.