问:
How to upload image using javascript fetch api and express multer
I am working in a reactjs application where i have to upload user image. I am getting file on onChange event of file input and passing it parent component and parent component will make a post request using the data

Server side I am using express and multer for file upload and client side using fetch api to upload the image.

Thanks in advance :)

答:
I figure it out
To upload an file/image to multer we need a form enctype="multipart/form-data" without that it wont work with multer

I am getting file from a child component then
1) i have created a empty form with the encType="mutipart/form-data"
2) when i received the file i create a new FormData(with ref to myform)
3) then append key and value in the formData
4) create fetch.post() and it works :)

for ref submitting the code

React Parent component Upload.js

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

import { ImageWithoutForm } from "../app/components/ImageUpload";

export default class UploadFile extends Component {
    onImageLoad(e){
        console.log('onImageLoad', e.target.files[0]);
        this.uploadForm(e.target.files[0]);
    }

    uploadForm(file){
        let form = new FormData(this.refs.myForm);
        form.append('myImage', file);
        fetch('/upload-image', {
          method: 'POST',
          body: form
        }).then(res => console.log('res of fetch', res));
    }

  render() {
    return (
      <div>
        <h4>Upload Image</h4>
        <ImageWithoutForm onImageLoad={(e)=>this.onImageLoad(e)} />
        <form id="upload_form" ref="myForm"  encType="multipart/form-data">
        </form>
      </div>
    )
  }
}
</code>```

React Child Component with input to load the file ImageWithoutForm.js

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

export  class ImageWithoutForm extends Component {

    handleSubmit(e){
        this.props.onImageLoad(e);
    }

  render() {
    return (
      <div>
            <input type="file" onChange={(e)=>this.handleSubmit(e)}/>
      </div>
    )
  }
}
</code>```

Express Route file taken from someone github repo and customized UploadImage.js

```<code>const express = require('express');
const multer = require('multer');
const path = require('path');

// Set Storage Engine
const storage = multer.diskStorage({
  destination: './public/uploads/',
  filename: function(req, file, cb){
    cb(null,file.fieldname + '-' + Date.now() + path.extname(file.originalname));
  }
});

// Init Upload
const upload = multer({
  storage: storage,
  limits:{fileSize: 1000000},
  fileFilter: function(req, file, cb){
    checkFileType(file, cb);
  }
}).single('myImage');

// Check File Type
function checkFileType(file, cb){
  // Allowed ext
  const filetypes = /jpeg|jpg|png|gif/;
  // Check ext
  const extname = filetypes.test(path.extname(file.originalname).toLowerCase());
  // Check mime
  const mimetype = filetypes.test(file.mimetype);

  if(mimetype && extname){
    return cb(null,true);
  } else {
    cb('Error: Images Only!');
  }
}

// Init app
const app = express.Router();

// Public Folder
app.use(express.static('./public'));

app.post('/', (req, res) => {
    console.log('handling upload image');
  upload(req, res, (err) => {
    if(err){
      console.log('first err', err);
      res.send({
        msg: err
      });
    } else {
      if(req.file == undefined){
        console.log('Error: No File Selected!')
        res.send({
          msg: 'Error: No File Selected!'
        });
      } else {
        console.log('File Uploaded!')
        res.send({
          msg: 'File Uploaded!',
          file: `uploads/${req.file.filename}`
        });
      }
    }
  });
});

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

and in my express app.js just require the route file ImageUpload.js

and map to the route like this

```<code>var uploadImage = require('./routes/UploadImage');
server.use('/upload-image', uploadImage);
</code>```

Body:
I figure it out
To upload an file/image to multer we need a form enctype="multipart/form-data" without that it wont work with multer

I am getting file from a child component then
1) i have created a empty form with the encType="mutipart/form-data"
2) when i received the file i create a new FormData(with ref to myform)
3) then append key and value in the formData
4) create fetch.post() and it works :)

for ref submitting the code

React Parent component Upload.js

import React, { Component } from 'react'

import { ImageWithoutForm } from "../app/components/ImageUpload";

export default class UploadFile extends Component {
    onImageLoad(e){
        console.log('onImageLoad', e.target.files[0]);
        this.uploadForm(e.target.files[0]);
    }

    uploadForm(file){
        let form = new FormData(this.refs.myForm);
        form.append('myImage', file);
        fetch('/upload-image', {
          method: 'POST',
          body: form
        }).then(res => console.log('res of fetch', res));
    }

  render() {
    return (
      <div>
        <h4>Upload Image</h4>
        <ImageWithoutForm onImageLoad={(e)=>this.onImageLoad(e)} />
        <form id="upload_form" ref="myForm"  encType="multipart/form-data">
        </form>
      </div>
    )
  }
}

React Child Component with input to load the file ImageWithoutForm.js

import React, { Component } from 'react'

export  class ImageWithoutForm extends Component {

    handleSubmit(e){
        this.props.onImageLoad(e);
    }

  render() {
    return (
      <div>
            <input type="file" onChange={(e)=>this.handleSubmit(e)}/>
      </div>
    )
  }
}

Express Route file taken from someone github repo and customized UploadImage.js

const express = require('express');
const multer = require('multer');
const path = require('path');

// Set Storage Engine
const storage = multer.diskStorage({
  destination: './public/uploads/',
  filename: function(req, file, cb){
    cb(null,file.fieldname + '-' + Date.now() + path.extname(file.originalname));
  }
});

// Init Upload
const upload = multer({
  storage: storage,
  limits:{fileSize: 1000000},
  fileFilter: function(req, file, cb){
    checkFileType(file, cb);
  }
}).single('myImage');

// Check File Type
function checkFileType(file, cb){
  // Allowed ext
  const filetypes = /jpeg|jpg|png|gif/;
  // Check ext
  const extname = filetypes.test(path.extname(file.originalname).toLowerCase());
  // Check mime
  const mimetype = filetypes.test(file.mimetype);

  if(mimetype && extname){
    return cb(null,true);
  } else {
    cb('Error: Images Only!');
  }
}

// Init app
const app = express.Router();

// Public Folder
app.use(express.static('./public'));

app.post('/', (req, res) => {
    console.log('handling upload image');
  upload(req, res, (err) => {
    if(err){
      console.log('first err', err);
      res.send({
        msg: err
      });
    } else {
      if(req.file == undefined){
        console.log('Error: No File Selected!')
        res.send({
          msg: 'Error: No File Selected!'
        });
      } else {
        console.log('File Uploaded!')
        res.send({
          msg: 'File Uploaded!',
          file: `uploads/${req.file.filename}`
        });
      }
    }
  });
});

module.exports = app;

and in my express app.js just require the route file ImageUpload.js

and map to the route like this

var uploadImage = require('./routes/UploadImage');
server.use('/upload-image', uploadImage);


来源: stackexchange

问:
python -m cannot find my modules
I wrote a package, which lives in /home/michael/python/mcdb-mail-parser/

The file structure in there is:

```<code> .
 ├── __init__.py
 ├── mcdb_mail_parser
 │   ├── __init__.py
 │   ├── MCDBAttachment.py
 │   ├── MCDBEmail.py
 │   ├── Options.py
 ├── mcdb-mail-parser.conf.sample
 ├── mcdb-mail-parser.py
 ├── README.md
</code>```

mcdb-mail-parser.py imports from the mcdb_mail_parser subdirectory.

if I run the scripts from the source directory (/home/michael/python/src/mcdb_mail_parser) it works fine because the mcdb_mail_parser directory is immediately available in the current directory. However, I need to run it from the home directory of another user (via a cronjob, or from another script via subprocess), python complains it cannot find the module:

I tried to execute it with python3 -m /home/michael/python/src/mcdb_mail_parser, but it complains:

```<code>michael@d8:~$ python3 -m /home/michael/python/mcdb-mail-parser/
/usr/bin/python3: No module named /home/michael/python/mcdb-mail-parser/
</code>```

I am not sure where to go from here. I think that it's a path issue. I could add /home/michael/python/src/mcdb_mail_parser to the system path, or perhaps python path, but that seems like the wrong solution. I certainly don't want to hard code paths into any scripts either.

How do I tell python: "Run the mcdb-mail-parser.py script from /home/michael/python/src/mcdb_mail_parser directory?

Closing notes
The accepted answer was useful, and so was the link they provided. Here's what I eventually did:
 1. I moved the contents of mcdb_mail_parser from the subdirectory into the same directory as README.md, thus removing one level of complexity.
 2. I added the import statements to __init__.py as suggested.
 3. Python complained it couldn't find __main__.py, so I renamed mcdb-mail-parser.py to __main__.py

答:
List the modules in the __init__.py that's in the sub directory and then have the Import in mcdb-mail-parser.py reference that directory

Very similar to this previous StackOverflow Post ->
Loading all modules in a folder in Python

ContentLicense: CC BY-SA 3.0

Title: python -m cannot find my modules

Body:
I wrote a package, which lives in /home/michael/python/mcdb-mail-parser/

The file structure in there is:

 .
 ├── __init__.py
 ├── mcdb_mail_parser
 │   ├── __init__.py
 │   ├── MCDBAttachment.py
 │   ├── MCDBEmail.py
 │   ├── Options.py
 ├── mcdb-mail-parser.conf.sample
 ├── mcdb-mail-parser.py
 ├── README.md

mcdb-mail-parser.py imports from the mcdb_mail_parser subdirectory.

if I run the scripts from the source directory (/home/michael/python/src/mcdb_mail_parser) it works fine because the mcdb_mail_parser directory is immediately available in the current directory. However, I need to run it from the home directory of another user (via a cronjob, or from another script via subprocess), python complains it cannot find the module:

I tried to execute it with python3 -m /home/michael/python/src/mcdb_mail_parser, but it complains:

michael@d8:~$ python3 -m /home/michael/python/mcdb-mail-parser/
/usr/bin/python3: No module named /home/michael/python/mcdb-mail-parser/

I am not sure where to go from here. I think that it's a path issue. I could add /home/michael/python/src/mcdb_mail_parser to the system path, or perhaps python path, but that seems like the wrong solution. I certainly don't want to hard code paths into any scripts either.

How do I tell python: "Run the mcdb-mail-parser.py script from /home/michael/python/src/mcdb_mail_parser directory?

Closing notes
The accepted answer was useful, and so was the link they provided. Here's what I eventually did:
 1. I moved the contents of mcdb_mail_parser from the subdirectory into the same directory as README.md, thus removing one level of complexity.
 2. I added the import statements to __init__.py as suggested.
 3. Python complained it couldn't find __main__.py, so I renamed mcdb-mail-parser.py to __main__.py


问:
Structure for monitoring lots of system variables of varying type
I am in need of some advice for a solution to a data storage problem we have at the place were I work.

The problem is as follows:

We have an embedded application which must monitor data from some equipment. The data is simple, such as status flags, single integer/floating variables indicating a setting/temperature/whatever, but we have hundreds of them.

What we are discussing now, is a simple way to store these variables in the application. Some parts of the system will read the equipment, and write their state to these variables. Other parts of the system will need to be notified when any of these variables change.

So basically a < Consumer > <-----> < Data Store > <-----> < Producer > structure.

As I have never worked on any professional software like this before (fresh out of university :) ) I was hoping there would be some brilliant people on these forums who could lend me their wisdom on how to aproach this problem.

What I have looked into so far, is:

SQLite: Very simple database, and easy to use. But perhaps it is overkill when the data to be stored doesnt really lend itself to a tabular structure?

Hashmaps: Simply store each data-lump with some key as index, then subscribe to changes on certain indices.

I hope I am making sense, and sorry for the wall of text :) Thanks in advance for the help.

答:
With limited data, I'd say try the HashMap implementation using an Observer pattern like you mentioned.  I think this may be a good approach because of two things:

It seems that you're learning.  Thus, it's important to be able to quickly churn something out just to see if it will work.

It seems to be more simple (in terms of dependencies) than using SQLLite.  In a fight in which theres a simple solution and a complex solution (and both accomplish the same thing), I'd bet on the simple solution.

ContentLicense: CC BY-SA 2.5


问:
How to force www, SSL and trailing slash in SilverStripe 4?
With the latest versions of SilverStripe they encourage you to use server side rules for URL re-writing and not Director::forceSSL(); and/or Director::forceWWW(); in your _config.php file as it is considered unreliable.

On an Apache server this would logically seem to suggest that it should be managed via an .htaccess file. Unfortunately the snippets shown below can fire a rewrite independently however chaining or combining in a single file seems to skip either the www or https case.

```<code>### SILVERSTRIPE START ###
### TRIMMED ROBOT/ERROR CODE ###

<IfModule mod_rewrite.c>

    # Turn off index.php handling requests to the homepage fixes issue in apache >=2.4
    <IfModule mod_dir.c>
        DirectoryIndex disabled
        DirectorySlash On
    </IfModule>

    SetEnv HTTP_MOD_REWRITE On
    RewriteEngine On
    RewriteBase '/'

    RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]

    # Deny access to potentially sensitive files and folders
    RewriteRule ^vendor(/|$) - [F,L,NC]
    RewriteRule ^\.env - [F,L,NC]
    RewriteRule silverstripe-cache(/|$) - [F,L,NC]
    RewriteRule composer\.(json|lock) - [F,L,NC]
    RewriteRule (error|silverstripe|debug)\.log - [F,L,NC]

    # Process through SilverStripe if no file with the requested name exists.
    # Pass through the original path as a query parameter, and retain the existing parameters.
    # Try finding framework in the vendor folder first
    RewriteCond %{REQUEST_URI} ^(.*)$
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule .* index.php

</IfModule>
### SILVERSTRIPE END ###

<IfModule mod_rewrite.c>
    ### FORCE TRAILING SLASH ###
    ### Source - https://paulund.co.uk/using-htaccess-to-force-trailing-slash ###
    RewriteCond %{REQUEST_URI} /+[^\.]+$
    RewriteRule ^(.+[^/])$ %{REQUEST_URI}/ [R=301,L]

    ### FORCE WWW ###
    #### Modified from source https://paulund.co.uk/add-www-subdomain-to-all-urls-using-htaccess ###
    RewriteCond %{HTTP_HOST} !^$
    RewriteCond %{HTTP_HOST} !^www\. [NC]
    RewriteCond %{HTTPS} off
    RewriteRule ^ https://www.example.com%{REQUEST_URI} [R=301,L]

    ### FORCE SSL ###
    RewriteCond %{HTTPS} off
    RewriteRule ^ https://www.example.com/$1 [R=301,L]

</IfModule>
</code>```

答:
Our approach is to enforce www and https in the Apache virtual host file:

```<code><VirtualHost *:80>
  ServerName www.myexampledomain.com
  Redirect permanent / https://www.myexampledomain.com/
</VirtualHost>
<VirtualHost *:443>
  ServerName myexampledomain.com
  Redirect permanent / https://www.myexampledomain.com/
</VirtualHost>
<VirtualHost *:443>
  ServerName www.myexampledomain.com
  DocumentRoot etc etc
</VirtualHost>
</code>```

Then finally we use this module to enforce trailing slashes: https://github.com/axllent/silverstripe-trailing-slash . There is a chance of a double redirect with this approach.

Body:
With the latest versions of SilverStripe they encourage you to use server side rules for URL re-writing and not Director::forceSSL(); and/or Director::forceWWW(); in your _config.php file as it is considered unreliable.

On an Apache server this would logically seem to suggest that it should be managed via an .htaccess file. Unfortunately the snippets shown below can fire a rewrite independently however chaining or combining in a single file seems to skip either the www or https case.

### SILVERSTRIPE START ###
### TRIMMED ROBOT/ERROR CODE ###

<IfModule mod_rewrite.c>

    # Turn off index.php handling requests to the homepage fixes issue in apache >=2.4
    <IfModule mod_dir.c>
        DirectoryIndex disabled
        DirectorySlash On
    </IfModule>

    SetEnv HTTP_MOD_REWRITE On
    RewriteEngine On
    RewriteBase '/'

    RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]

    # Deny access to potentially sensitive files and folders
    RewriteRule ^vendor(/|$) - [F,L,NC]
    RewriteRule ^\.env - [F,L,NC]
    RewriteRule silverstripe-cache(/|$) - [F,L,NC]
    RewriteRule composer\.(json|lock) - [F,L,NC]
    RewriteRule (error|silverstripe|debug)\.log - [F,L,NC]

    # Process through SilverStripe if no file with the requested name exists.
    # Pass through the original path as a query parameter, and retain the existing parameters.
    # Try finding framework in the vendor folder first
    RewriteCond %{REQUEST_URI} ^(.*)$
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule .* index.php

</IfModule>
### SILVERSTRIPE END ###

<IfModule mod_rewrite.c>
    ### FORCE TRAILING SLASH ###
    ### Source - https://paulund.co.uk/using-htaccess-to-force-trailing-slash ###
    RewriteCond %{REQUEST_URI} /+[^\.]+$
    RewriteRule ^(.+[^/])$ %{REQUEST_URI}/ [R=301,L]

    ### FORCE WWW ###
    #### Modified from source https://paulund.co.uk/add-www-subdomain-to-all-urls-using-htaccess ###
    RewriteCond %{HTTP_HOST} !^$
    RewriteCond %{HTTP_HOST} !^www\. [NC]
    RewriteCond %{HTTPS} off
    RewriteRule ^ https://www.example.com%{REQUEST_URI} [R=301,L]

    ### FORCE SSL ###
    RewriteCond %{HTTPS} off
    RewriteRule ^ https://www.example.com/$1 [R=301,L]

</IfModule>

Body:
Our approach is to enforce www and https in the Apache virtual host file:

<VirtualHost *:80>
  ServerName www.myexampledomain.com
  Redirect permanent / https://www.myexampledomain.com/
</VirtualHost>
<VirtualHost *:443>
  ServerName myexampledomain.com
  Redirect permanent / https://www.myexampledomain.com/
</VirtualHost>
<VirtualHost *:443>
  ServerName www.myexampledomain.com
  DocumentRoot etc etc
</VirtualHost>

Then finally we use this module to enforce trailing slashes: https://github.com/axllent/silverstripe-trailing-slash . There is a chance of a double redirect with this approach.


问:
how to upload sub-folder which is empty to S3 using python
The following code works fine except if there is a subfolder, which does not have any file inside, then the subfolder will not appear in S3. e.g.
if /home/temp/subfolder has no file, then subfolder will not show in S3. how to change the code so that the empty folder is also uploaded in S3?
I tried to write sth. (see note below), but do not know how to call put_object() to the empty subfolder.

```<code>#!/usr/bin/env python
import os
from boto3.session import Session

path = "/home/temp"
session = Session(aws_access_key_id='XXX', aws_secret_access_key='XXX')
s3 = session.resource('s3')

for subdir, dirs, files in os.walk(path):
    # note: if not files ......
    for file in files:
        full_path = os.path.join(subdir, file)
        with open(full_path, 'rb') as data:

s3.Bucket('my_bucket').put_object(Key=full_path[len(path)+1:],
Body=data)
</code>```

besides, I tried to call this function to check if a subfolder or file exist or not. it works for file, but not subfolder. how to check if a subfolder exists or not? (if a subfolder exists, I will not upload)

```<code>def check_exist(s3, bucket, key):
    try:
        s3.Object(bucket, key).load()
    except botocore.exceptions.ClientError as e:
        return False
    return True
</code>```

BTW, I refer the above code from

check if a key exists in a bucket in s3 using boto3

and

http://www.developerfiles.com/upload-files-to-s3-with-python-keeping-the-original-folder-structure/

thanks them for sharing the code.

答:
Directories (folders, subfolders, etc.) do not exist in S3.

When you copy this file to an empty S3 bucket /mydir/myfile.txt, only the file myfile.txt is copied to S3. The directory mydir is not created as that string is part of the file name mydir/myfile.txt. The actual file name is the full path, no subdirectories exist or are created.

S3 simulates directories by using a prefix when listing files in the bucket. If you specify mydir/, then all of the S3 objects that start with mydir/ will be returned including objects such as mydir/anotherfolder/myotherfile.txt. S3 supports a delimitor such as / so that the appearance of subdirectories can be created.

Note: There is no / at the beginning of a file name for S3 objects.

Listing Keys Hierarchically Using a Prefix and Delimiter

Body:
The following code works fine except if there is a subfolder, which does not have any file inside, then the subfolder will not appear in S3. e.g.
if /home/temp/subfolder has no file, then subfolder will not show in S3. how to change the code so that the empty folder is also uploaded in S3?
I tried to write sth. (see note below), but do not know how to call put_object() to the empty subfolder.

#!/usr/bin/env python
import os
from boto3.session import Session

path = "/home/temp"
session = Session(aws_access_key_id='XXX', aws_secret_access_key='XXX')
s3 = session.resource('s3')

for subdir, dirs, files in os.walk(path):
    # note: if not files ......
    for file in files:
        full_path = os.path.join(subdir, file)
        with open(full_path, 'rb') as data:

s3.Bucket('my_bucket').put_object(Key=full_path[len(path)+1:],
Body=data)

besides, I tried to call this function to check if a subfolder or file exist or not. it works for file, but not subfolder. how to check if a subfolder exists or not? (if a subfolder exists, I will not upload)

def check_exist(s3, bucket, key):
    try:
        s3.Object(bucket, key).load()
    except botocore.exceptions.ClientError as e:
        return False
    return True

BTW, I refer the above code from

check if a key exists in a bucket in s3 using boto3

and

http://www.developerfiles.com/upload-files-to-s3-with-python-keeping-the-original-folder-structure/

thanks them for sharing the code.


问:
akka actor current receive function name
i have a simple actor with 2 behavior

```<code>package com.hello

import akka.actor.{Actor, ActorLogging}

case object Ping

class Hello extends Actor with ActorLogging {

  import context._

  def receive: Receive = behaviorFoo

  self ! Ping

  def behaviorFoo: Receive = {
    case _ =>
      log.info(this.receive.getClass.getSimpleName)
      become(behaviorBar)
      self ! Ping
  }

  def behaviorBar: Receive = {
    case _ =>
      log.info(this.receive.getClass.getSimpleName)
  }
}
</code>```

this thing do those:

ping self

logging current receive function

change behavior to behaviorBar

ping self

logging current receive function

in both cases it logs "$anonfun$behaviorFoo$1"

why it is not "$anonfun$behaviorBar$1" in second log?

if i change code to

```<code>  self ! Ping

  def receive: Receive = {
    case _ =>
      log.info(this.receive.getClass.getSimpleName)
      become(behaviorFoo)
      self ! Ping
  }

  def behaviorFoo: Receive = {
    case _ =>
      log.info(this.receive.getClass.getSimpleName)
      become(behaviorBar)
      self ! Ping
  }

  def behaviorBar: Receive = {
    case _ =>
      log.info(this.receive.getClass.getSimpleName)
  }
</code>```

it logs 3 times "$anonfun$receive$1"

is exist any way to get current behavior (Receive) function name?
or i need to hardwrite like log.info("behaviorFoo") any time?

update:

for logging issues, i added

```<code>trait MyLogging extends ActorLogging {
  this: Actor ⇒

  private[this] val actorClassName = this.getClass.getSimpleName

  private[this] var receiveName: String = {
    val receiveClassName = s"${this.receive.getClass.getSimpleName}"
    val left = receiveClassName.substring(0, receiveClassName.lastIndexOf("$"))
    left.substring(left.lastIndexOf("$") + 1)
  }

  def become(behavior: Actor.Receive): Unit = {
    val behaviorClassName = behavior.getClass.getSimpleName
    val left = behaviorClassName.substring(0, behaviorClassName.lastIndexOf("$"))

    receiveName = left.substring(left.lastIndexOf("$") + 1)

    context.become(behavior)
  }

  def info(message: Any): Unit = log.info(s"$actorClassName : $receiveName got $message")
}
</code>```

then, my actor code become

```<code>class Hello extends Actor with MyLogging {

  def receive: Receive = behaviorFoo

  self ! Ping

  def behaviorFoo: Receive = {
    case any =>
      info(any)
      become(behaviorBar)
      self ! Ping
  }

  def behaviorBar: Receive = {
    case any => info(any)
  }
}
</code>```

now logs looks like

... Hello : behaviorFoo got Ping

... Hello : behaviorBar got Ping

答:
Maybe this is why those are called anonymous functions. The behaviorFoo, behaviorBar, ... names have no influence on those anonymous functions. To illustrate this point, consider this:

```<code>// this is a val!
val behaviorFoo: Receive = {
  case _ =>
    log.info(this.receive.getClass.getSimpleName)
    become(behaviorBar)
    self ! Ping
}
// this returns the same anonymous function
def behaviorFoo2 = behaviorFoo
</code>```

With the above, you should see that the name under which you store the anonymous function has nothing to do with the anonymous function itself...

Now, if you realize what those anonymous functions are (they are partial functions, aliased with type Actor.Receive) you could do something like below:

```<code>// not an anonymous function anymore
class BehaviourFoo extends Actor.Receive {
  val anonymousFun: Actor.Receive = {
    case _ =>
      log.info(this.receive.getClass.getSimpleName)
      become(behaviorBar)
      self ! Ping
  }
  override def isDefinedAt(x: Any) = anonymousFun.isDefinedAt(x)

  override def apply(x: Any) = anonymousFun(x)
}
// again, the name behaviorFoo doesn't matter
def behaviorFoo: Receive = new BehaviourFoo
</code>```

It is certainly NOT worth the hassle, but it should help you understand what is happening.

Body:
i have a simple actor with 2 behavior

package com.hello

import akka.actor.{Actor, ActorLogging}

case object Ping

class Hello extends Actor with ActorLogging {

  import context._

  def receive: Receive = behaviorFoo

  self ! Ping

  def behaviorFoo: Receive = {
    case _ =>
      log.info(this.receive.getClass.getSimpleName)
      become(behaviorBar)
      self ! Ping
  }

  def behaviorBar: Receive = {
    case _ =>
      log.info(this.receive.getClass.getSimpleName)
  }
}

this thing do those:

ping self

logging current receive function

change behavior to behaviorBar

ping self

logging current receive function

in both cases it logs "$anonfun$behaviorFoo$1"

why it is not "$anonfun$behaviorBar$1" in second log?

if i change code to

  self ! Ping

  def receive: Receive = {
    case _ =>
      log.info(this.receive.getClass.getSimpleName)
      become(behaviorFoo)
      self ! Ping
  }

  def behaviorFoo: Receive = {
    case _ =>
      log.info(this.receive.getClass.getSimpleName)
      become(behaviorBar)
      self ! Ping
  }

  def behaviorBar: Receive = {
    case _ =>
      log.info(this.receive.getClass.getSimpleName)
  }

it logs 3 times "$anonfun$receive$1"

is exist any way to get current behavior (Receive) function name?
or i need to hardwrite like log.info("behaviorFoo") any time?

update:

for logging issues, i added

trait MyLogging extends ActorLogging {
  this: Actor ⇒

  private[this] val actorClassName = this.getClass.getSimpleName

  private[this] var receiveName: String = {
    val receiveClassName = s"${this.receive.getClass.getSimpleName}"
    val left = receiveClassName.substring(0, receiveClassName.lastIndexOf("$"))
    left.substring(left.lastIndexOf("$") + 1)
  }

  def become(behavior: Actor.Receive): Unit = {
    val behaviorClassName = behavior.getClass.getSimpleName
    val left = behaviorClassName.substring(0, behaviorClassName.lastIndexOf("$"))

    receiveName = left.substring(left.lastIndexOf("$") + 1)

    context.become(behavior)
  }

  def info(message: Any): Unit = log.info(s"$actorClassName : $receiveName got $message")
}

then, my actor code become

class Hello extends Actor with MyLogging {

  def receive: Receive = behaviorFoo

  self ! Ping

  def behaviorFoo: Receive = {
    case any =>
      info(any)
      become(behaviorBar)
      self ! Ping
  }

  def behaviorBar: Receive = {
    case any => info(any)
  }
}

now logs looks like

... Hello : behaviorFoo got Ping

... Hello : behaviorBar got Ping

Body:
Maybe this is why those are called anonymous functions. The behaviorFoo, behaviorBar, ... names have no influence on those anonymous functions. To illustrate this point, consider this:

// this is a val!
val behaviorFoo: Receive = {
  case _ =>
    log.info(this.receive.getClass.getSimpleName)
    become(behaviorBar)
    self ! Ping
}
// this returns the same anonymous function
def behaviorFoo2 = behaviorFoo

With the above, you should see that the name under which you store the anonymous function has nothing to do with the anonymous function itself...

Now, if you realize what those anonymous functions are (they are partial functions, aliased with type Actor.Receive) you could do something like below:

// not an anonymous function anymore
class BehaviourFoo extends Actor.Receive {
  val anonymousFun: Actor.Receive = {
    case _ =>
      log.info(this.receive.getClass.getSimpleName)
      become(behaviorBar)
      self ! Ping
  }
  override def isDefinedAt(x: Any) = anonymousFun.isDefinedAt(x)

  override def apply(x: Any) = anonymousFun(x)
}
// again, the name behaviorFoo doesn't matter
def behaviorFoo: Receive = new BehaviourFoo

It is certainly NOT worth the hassle, but it should help you understand what is happening.


问:
Creating a Christmas Tree using for loops
I am trying to make a christmas tree using for loops and nested for loops. For me to do that I need to be able to make a pyramids with *. I have tried countless times and I am having problems making one. Here is my code:

```<code>for(int i=1;i<=10;i++){
    for(int j=10;j>i;j--){
        System.out.println(" ");
    }

    for(int k=1;k<=i;k++){
        System.out.print("*");
    }

    for(int l=10;l<=1;l++){
        for(int h=1;h<=10;h++){
            System.out.print(" ");
        }
    }

    System.out.println();
}
</code>```

What I am trying to do is:

```<code>     *
    ***
   *****
  *******
</code>```

答:
```<code>import java.util.Scanner;

public class cmastree{

    public static void main (String[]args){
        Scanner keyboard=new Scanner (System.in);

        int j;
        System.out.println ("Enter a number");
        j=keyboard.nextInt();
        /*take the above part out and change the j variable if you want to set
        the size*/
        for(int i=1; i<=j; i+=2){
            int numSpaces = (j-i)/2;
        for (int k=0; k<numSpaces; k++){
            System.out.print(" ");
            }
        for(int k=0; k<numSpaces; k++){
            System.out.print("*");
            }
            System.out.println();
        }
    }
}
</code>```

Body:
I am trying to make a christmas tree using for loops and nested for loops. For me to do that I need to be able to make a pyramids with *. I have tried countless times and I am having problems making one. Here is my code:

for(int i=1;i<=10;i++){
    for(int j=10;j>i;j--){
        System.out.println(" ");
    }

    for(int k=1;k<=i;k++){
        System.out.print("*");
    }

    for(int l=10;l<=1;l++){
        for(int h=1;h<=10;h++){
            System.out.print(" ");
        }
    }

    System.out.println();
}

What I am trying to do is:

     *
    ***
   *****
  *******


问:
Swift - Avoiding strong reference cycles in closure-based configuration
Please note: I have read many of the (very many) answers and articles on the subject of avoiding strong reference cycles. However, I'm looking for guidance on how to handle a specific by-product of avoiding these cycles.

In the following example, the class Foo is designed to be configured using a closure. A reference to the closure is cached for later use.

The closure will be called whenever the Model data is needed. In order for Foo to work properly, the data must exist.

```<code>class Foo
{
    typealias ModelGetter = (() -> Model)
    fileprivate var _modelGetter: ModelGetter!

    ...

    func configure(with modelGetter: @escaping ModalGetter)
    {
        _modelGetter = modelGetter
    }

    func printLastestModel()
    {
        // Get the latest model, do something with it.
        precondition(_modelGetter != nil)
        let model = _modelGetter()
        print(model)
    }
}
</code>```

In the above code, _modelGetter is implicitly unwrapped. Although I could define it as an Optional, and unwrap it as needed, Foo always needs the closure to be set in order to work properly, hence the implicit unwrapping.

Making an instance of Foo, and configuring it:

```<code>let foo = Foo()
foo.configure(with: { self.makeModel() })
foo.printLatestModel()
</code>```

But, this creates a retain cycle.

So, [weak self] is used, and we check for self's optionality:

```<code>foo.configure(with: { [weak self] in
    guard let strongSelf = self else { return **WHAT** }
    return strongSelf.makeModel()
})
</code>```

Problem

This requires that even though self may be nil, the closure still needs to return a Model (i.e. WHAT?) to the caller of the closure (the Foo instance.) But, since self is nil, I don't have a Model to hand over.

Question

Can someone recommend a pattern to use in this situation? Preferably, I don't want Foo to be checking if the modelGetter is valid or not, or left wondering if the Model is valid. For Foo's purposes, if Foo exists, then it must always be able to get the Model it needs.

Or, should I just redesign Foo's needs, to take in to account the possibility of not being able to procure a Model? Thankyou for any help.

答: If Class is the owner of Foo, it's recommended to set [unowned self] instead of [weak self]. It will solve the problem. If one class is the owner of another it will never appear as a problem, but if the logic is wrong it will appear a crash. This is not bad because it signals to you that you broke something in the project.

Body:
Please note: I have read many of the (very many) answers and articles on the subject of avoiding strong reference cycles. However, I'm looking for guidance on how to handle a specific by-product of avoiding these cycles.

In the following example, the class Foo is designed to be configured using a closure. A reference to the closure is cached for later use.

The closure will be called whenever the Model data is needed. In order for Foo to work properly, the data must exist.

class Foo
{
    typealias ModelGetter = (() -> Model)
    fileprivate var _modelGetter: ModelGetter!

    ...

    func configure(with modelGetter: @escaping ModalGetter)
    {
        _modelGetter = modelGetter
    }

    func printLastestModel()
    {
        // Get the latest model, do something with it.
        precondition(_modelGetter != nil)
        let model = _modelGetter()
        print(model)
    }
}

In the above code, _modelGetter is implicitly unwrapped. Although I could define it as an Optional, and unwrap it as needed, Foo always needs the closure to be set in order to work properly, hence the implicit unwrapping.

Making an instance of Foo, and configuring it:

let foo = Foo()
foo.configure(with: { self.makeModel() })
foo.printLatestModel()

But, this creates a retain cycle.

So, [weak self] is used, and we check for self's optionality:

foo.configure(with: { [weak self] in
    guard let strongSelf = self else { return **WHAT** }
    return strongSelf.makeModel()
})

Problem

This requires that even though self may be nil, the closure still needs to return a Model (i.e. WHAT?) to the caller of the closure (the Foo instance.) But, since self is nil, I don't have a Model to hand over.

Question

Can someone recommend a pattern to use in this situation? Preferably, I don't want Foo to be checking if the modelGetter is valid or not, or left wondering if the Model is valid. For Foo's purposes, if Foo exists, then it must always be able to get the Model it needs.

Or, should I just redesign Foo's needs, to take in to account the possibility of not being able to procure a Model? Thankyou for any help.

ContentLicense: CC BY-SA 4.0


问:
Rijndael support in Java
We have a requirement to do some Rijndael development in Java.

Any recommendations for articles, libraries etc. that would help us?

Any pointers to keystore maintenance and how store the keys securely?

Edit:

It would need to be open source. Essentially, it's just standard encrypt / decrypt of data using Rijndael.

答:
As my company recently found out, AES is not quite Rijndael.  AES has the restriction that keys MUST be 128, 192, or 256 bit - however, Rijndael allows for keys that are 160 and 224 as well.

As indicated by erickson above, BouncyCastle provides a Rijndael object that DOES support the additional key lengths: 128/160/192/224/256 bits.  Specifically, take a look at the lightweight API.

Gnu-crypto is another open source library - however, it also does NOT provide support for 160 and 224 bit keys.

So, if you are specifically looking for full Rijndael support, then BouncyCastle is the only one I've found so far.

OwnerDisplayName: nzpcmad

Title: Rijndael support in Java

LastEditorDisplayName: nzpcmad


问:
spread operator giving issue with typescript
I am trying to implement a redux store for my react-typescript app. I am having a problem in my reducer. In native react-apps I did the following

```<code>  reminders = [...state, reminder(action)];
  return reminders;
</code>```

the spread operator works perfectly. and the new object is added to array immutably.

with typescript this is not happening.(get an empty object instead of an array) I tried object.assign

```<code>  return (<any>Object).assign({}, state, reminder(action));
</code>```

This replaces the current object rather then adding it to the array and I dont think its doing it in an immutable way.

I tried uisng immutable.js and the reducer was not being called at all.

```<code> return map([state,reminder(action)])
</code>```

no idea what is wrong. also after using objext.assign the nextprops and currents props always come same. even if it is changed in the shouldContainerUpdate() method

答:
the spread operator works perfectly. and the new object is added to array immutably.

Use the exact same in TypeScript and it will work perfectly:

```<code>reminders = [...state, reminder(action)];
return reminders;
</code>```

Why

Because TypeScript follows the same semantics as JavaScript for JavaScript syntax

Body:
I am trying to implement a redux store for my react-typescript app. I am having a problem in my reducer. In native react-apps I did the following

  reminders = [...state, reminder(action)];
  return reminders;

the spread operator works perfectly. and the new object is added to array immutably.

with typescript this is not happening.(get an empty object instead of an array) I tried object.assign

  return (<any>Object).assign({}, state, reminder(action));

This replaces the current object rather then adding it to the array and I dont think its doing it in an immutable way.

I tried uisng immutable.js and the reducer was not being called at all.

 return map([state,reminder(action)])

no idea what is wrong. also after using objext.assign the nextprops and currents props always come same. even if it is changed in the shouldContainerUpdate() method

Body:
the spread operator works perfectly. and the new object is added to array immutably.

Use the exact same in TypeScript and it will work perfectly:

reminders = [...state, reminder(action)];
return reminders;

Why

Because TypeScript follows the same semantics as JavaScript for JavaScript syntax


问:
Laravel show more button
I do have two laravel collections

```<code>$posts = collect($instagramService->fetchPosts('username'))->take(10);
</code>```

and some more posts

```<code>$morePosts =  collect($instagramService->fetchPosts('username'))->slice(10);
</code>```

I am displaying first collection on a blade:

```<code>@foreach($posts as $post)
   {{$post->url}}
   {{$post->likes}}
@endforeach

<button type="submit">Show More</button>
</code>```

I am trying to research an ajax pagination but no luck so far, so if someone could help me here would be highly appreciated.

Question: when I click "Show More" I want to load the second collection?

答:
button

```<code><button type="submit" class="clickMe">Show More</button>
</code>```

ajax

```<code>       $(".clickMe").click(function(){
    $.ajax({
            dataType: 'json',
            type:'GET',
            url: "{{ url('morePosts') }}",
          }).done(function(data){
             var len=data.length
console.log(len);
    //Perform ANy action after successfuly post data
      var rows = '';
for(i=0;i<data.length;i++){
      rows = rows + 'data[i].url'
}
 $("#morePosts").html(rows);
        });
</code>```

Route

```<code> Route::get('/morePosts', 'PostController@morePosts');
</code>```

method in controller

```<code>public function morePosts(){
   $data=  collect($instagramService->fetchPosts('username'))->slice(10);
return response()->json($data);
}
</code>```

html

```<code><div id="morePosts">
</div>
</code>```

Title: Laravel show more button

Body:
I do have two laravel collections

$posts = collect($instagramService->fetchPosts('username'))->take(10);

and some more posts

$morePosts =  collect($instagramService->fetchPosts('username'))->slice(10);

I am displaying first collection on a blade:

@foreach($posts as $post)
   {{$post->url}}
   {{$post->likes}}
@endforeach

<button type="submit">Show More</button>

I am trying to research an ajax pagination but no luck so far, so if someone could help me here would be highly appreciated.

Question: when I click "Show More" I want to load the second collection?

Body:
button

<button type="submit" class="clickMe">Show More</button>

ajax

       $(".clickMe").click(function(){
    $.ajax({
            dataType: 'json',
            type:'GET',
            url: "{{ url('morePosts') }}",
          }).done(function(data){
             var len=data.length
console.log(len);
    //Perform ANy action after successfuly post data
      var rows = '';
for(i=0;i<data.length;i++){
      rows = rows + 'data[i].url'
}
 $("#morePosts").html(rows);
        });

Route

 Route::get('/morePosts', 'PostController@morePosts');

method in controller

public function morePosts(){
   $data=  collect($instagramService->fetchPosts('username'))->slice(10);
return response()->json($data);
}

html

<div id="morePosts">
</div>


问:
Handling Enter Key on EditText (Kotlin, Android)
How to handle Enter Key on EditText in Android Kotlin Language?</p>

答:
Bellow is the simplest solution for above question</p>

```<code>    editText.setOnKeyListener(View.OnKeyListener { v, keyCode, event ->
                if (keyCode == KeyEvent.KEYCODE_ENTER && event.action == KeyEvent.ACTION_UP) {
                    //Perform Code
                    return@OnKeyListener true
                }
                false
            })
</code>```

Body:
Bellow is the simplest solution for above question

    editText.setOnKeyListener(View.OnKeyListener { v, keyCode, event ->
                if (keyCode == KeyEvent.KEYCODE_ENTER && event.action == KeyEvent.ACTION_UP) {
                    //Perform Code
                    return@OnKeyListener true
                }
                false
            })


问:
Link a domain to Amazon lightsail, ubuntu
I'm unable to ping domain name or amazon static ip from the lightsail instance (attached to that static ip)

Bought a domain name (say, test.com) from Google.

Created an Amazon Lightsail ubuntu 16.04 instance & attached a static IP

Enabled firewall on lightsail instance & allowed ports ssh/http/https

DNS settings added on google domain as below

Using google domain name servers

Registered host: www.test.com -> Amazon static ip

Custom resource records: @ -> A -> Amazon static ip

Custom resource records: www -> A -> Amazon static ip

After all the above steps, am able to access test.com from web-browser

Now the issue is, am unable to ping test.com from lightsail instance (the same created in step-2).
To add, am able to ping google.com from the same instance. I'm doubting if any route missed.

Can someone guide me here. Many thanks.

答: Ping is uses the ICMP protocol, and the Lightsail firewall rules do not have a way to allow that protocol so that instances to be pinged from the Internet -- they only allow TCP and UDP.  All outbound traffic is allowed, and the firewall is stateful, so you can ping out but not in.</p>


问:
HTML Table formatting for three column layout
I have a HTML table i'm making that I want to display data with a three column layout.  I have something close here: https://jsfiddle.net/j89cttva/1/

But I'd like for the gaps to be erased up top to condense all of the empty whitespace.  Could anyone assist?

```<code>  <table>
  <table style="width: 30%; margin-bottom: 5px;font-size:12px;float: left;">
    <tr>
      <td style="width: 10%; vertical-align: top;">
        <div class="accent-color2" style="width: 100px; padding: 0px 10px;"><b>Comfort_Features:</b></div>
      </td>
    </tr>
    <td style="width: 30%; padding-right: 5px; vertical-align: top;">
      <ul style="padding-left: 10px;">
        <li>Rear Center Folding With Storage and Pass-Thru Armrests</li>
        <li>Carpet Floor Mats</li>
        <li>Carpet Floors</li>
        <li>Front Floor Mats</li>
        <li>Chrome Interior Accents</li>
        <li>Simulated Alloy Shift Knob Trim</li>
        <li>Urethane Steering Wheel Trim</li>
      </ul>
    </td>
  </table>
  <table style="width: 30%; margin-bottom: 5px;font-size:12px;float: left;display: inline-block;">
    <tr>
      <td style="width: 10%; vertical-align: top;">
        <div class="accent-color2" style="width: 100px; padding: 0px 10px;"><b>Drivetrain:</b></div>
      </td>
    </tr>
    <td style="width: 30%; padding-right: 5px; vertical-align: top;">
      <ul style="padding-left: 10px;">
        <li>4.11 Axle Ratio</li>
      </ul>
    </td>
  </table>
  <table style="width: 30%; margin-bottom: 5px;font-size:12px;float: left;display: inline-block;">
    <tr>
      <td style="width: 10%; vertical-align: top;">
        <div class="accent-color2" style="width: 100px; padding: 0px 10px;"><b>Engine:</b></div>
      </td>
    </tr>
    <td style="width: 30%; padding-right: 5px; vertical-align: top;">
      <ul style="padding-left: 10px;">
        <li>140 Amps Alternator</li>
        <li>600 Cca Battery Rating</li>
        <li>Battery Saver</li>
        <li>Maintenance-Free Battery</li>
        <li>50 State Emissions</li>
        <li>Auxiliary Oil Cooler</li>
      </ul>
    </td>
  </table>
  <table style="width: 30%; margin-bottom: 5px;font-size:12px;float: left;display: inline-block;">
    <tr>
      <td style="width: 10%; vertical-align: top;">
        <div class="accent-color2" style="width: 100px; padding: 0px 10px;"><b>In_Car_Entertainment:</b></div>
      </td>
    </tr>
    <td style="width: 30%; padding-right: 5px; vertical-align: top;">
      <ul style="padding-left: 10px;">
        <li>Uconnect Infotainment</li>
      </ul>
    </td>
  </table>
  <table style="width: 30%; margin-bottom: 5px;font-size:12px;float: left;display: inline-block;">
    <tr>
      <td style="width: 10%; vertical-align: top;">
        <div class="accent-color2" style="width: 100px; padding: 0px 10px;"><b>Instrumentation:</b></div>
      </td>
    </tr>
    <td style="width: 30%; padding-right: 5px; vertical-align: top;">
      <ul style="padding-left: 10px;">
        <li>Clock</li>
        <li>Digital Odometer</li>
        <li>Driver Information System</li>
        <li>External Temperature Display</li>
        <li>Tachometer Gauge</li>
        <li>Multi-Function Display</li>
        <li>Trip Computer</li>
        <li>2 Trip Odometer</li>
        <li>Low Fuel Level Warnings and Reminders</li>
      </ul>
    </td>
  </table>
  <table style="width: 30%; margin-bottom: 5px;font-size:12px;float: up;display: inline-block;">
    <tr>
      <td style="width: 10%; vertical-align: top;">
        <div class="accent-color2" style="width: 100px; padding: 0px 10px;"><b>Lights:</b></div>
      </td>
    </tr>
    <td style="width: 30%; padding-right: 5px; vertical-align: top;">
      <ul style="padding-left: 10px;">
        <li>Daytime Running Lights</li>
        <li>Auto Delay Off Headlights</li>
        <li>Led Taillights</li>
      </ul>
    </td>
  </table>
</table>
</code>```

答:
Is this for an assignment where you have to use tables? If not, tables are not the right tool here.

I wanted to practice flexbox so I put this together. The height on the flex container is a hack to make it wrap but I don't know your surrounding code, maybe you are already height constrained.

https://jsfiddle.net/dgrogan/ua4cn5d8/

And I wanted to practice multicol -- https://jsfiddle.net/dgrogan/jLsgpxy1/

This code is flex:

body {
  font-size: 12px;
}

#container {
  outline: 1px solid pink;
  display: flex;
  flex-direction: column;
  flex-wrap: wrap;
  height:300px; /* otherwise this container can grow down indefinitely*/
}

.section {
  outline: 1px solid lightblue;
  width: 30%;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="container">
  <div class="section">
    <b>Comfort_Features:</b>
    <br>
    <ul style="padding-left: 10px;">
      <li>Rear Center Folding With Storage and Pass-Thru Armrests</li>
      <li>Carpet Floor Mats</li>
      <li>Carpet Floors</li>
      <li>Front Floor Mats</li>
      <li>Chrome Interior Accents</li>
      <li>Simulated Alloy Shift Knob Trim</li>
      <li>Urethane Steering Wheel Trim</li>
    </ul>
  </div>
  <div class="section">
    <b>Drivetrain:</b>
    <br>
    <ul style="padding-left: 10px;">
      <li>4.11 Axle Ratio</li>
    </ul>
  </div>
  <div class="section">
    <b>Engine:</b>
    <br>
    <ul style="padding-left: 10px;">
      <li>140 Amps Alternator</li>
      <li>600 Cca Battery Rating</li>
      <li>Battery Saver</li>
      <li>Maintenance-Free Battery</li>
      <li>50 State Emissions</li>
      <li>Auxiliary Oil Cooler</li>
    </ul>
  </div>
  <div class="section">
    <b>In_Car_Entertainment:</b>
    <br>
    <ul style="padding-left: 10px;">
      <li>Uconnect Infotainment</li>
    </ul>
  </div>
  <div class="section">
    <b>Instrumentation:</b>
    <br>
    <ul style="padding-left: 10px;">
      <li>Clock</li>
      <li>Digital Odometer</li>
      <li>Driver Information System</li>
      <li>External Temperature Display</li>
      <li>Tachometer Gauge</li>
      <li>Multi-Function Display</li>
      <li>Trip Computer</li>
      <li>2 Trip Odometer</li>
      <li>Low Fuel Level Warnings and Reminders</li>
    </ul>
  </div>
  <div class="section">
    <b>Lights:</b>
    <br>
    <ul style="padding-left: 10px;">
      <li>Daytime Running Lights</li>
      <li>Auto Delay Off Headlights</li>
      <li>Led Taillights</li>
    </ul>
  </div>
</div></code>```

Body:
I have a HTML table i'm making that I want to display data with a three column layout.  I have something close here: https://jsfiddle.net/j89cttva/1/

But I'd like for the gaps to be erased up top to condense all of the empty whitespace.  Could anyone assist?

Comfort_Features:

Rear Center Folding With Storage and Pass-Thru Armrests

Carpet Floor Mats

Carpet Floors

Front Floor Mats

Chrome Interior Accents

Simulated Alloy Shift Knob Trim

Urethane Steering Wheel Trim

Drivetrain:

4.11 Axle Ratio

Engine:

140 Amps Alternator

600 Cca Battery Rating

Battery Saver

Maintenance-Free Battery

50 State Emissions

Auxiliary Oil Cooler

In_Car_Entertainment:

Uconnect Infotainment

Instrumentation:

Clock

Digital Odometer

Driver Information System

External Temperature Display

Tachometer Gauge

Multi-Function Display

Trip Computer

2 Trip Odometer

Low Fuel Level Warnings and Reminders

Lights:

Daytime Running Lights

Auto Delay Off Headlights

Led Taillights

Body:
Is this for an assignment where you have to use tables? If not, tables are not the right tool here.

I wanted to practice flexbox so I put this together. The height on the flex container is a hack to make it wrap but I don't know your surrounding code, maybe you are already height constrained.

https://jsfiddle.net/dgrogan/ua4cn5d8/

And I wanted to practice multicol -- https://jsfiddle.net/dgrogan/jLsgpxy1/

This code is flex:

body {
  font-size: 12px;
}

#container {
  outline: 1px solid pink;
  display: flex;
  flex-direction: column;
  flex-wrap: wrap;
  height:300px; /* otherwise this container can grow down indefinitely*/
}

.section {
  outline: 1px solid lightblue;
  width: 30%;
}

<div id="container">
  <div class="section">
    <b>Comfort_Features:</b>
    <br>
    <ul style="padding-left: 10px;">
      <li>Rear Center Folding With Storage and Pass-Thru Armrests</li>
      <li>Carpet Floor Mats</li>
      <li>Carpet Floors</li>
      <li>Front Floor Mats</li>
      <li>Chrome Interior Accents</li>
      <li>Simulated Alloy Shift Knob Trim</li>
      <li>Urethane Steering Wheel Trim</li>
    </ul>
  </div>
  <div class="section">
    <b>Drivetrain:</b>
    <br>
    <ul style="padding-left: 10px;">
      <li>4.11 Axle Ratio</li>
    </ul>
  </div>
  <div class="section">
    <b>Engine:</b>
    <br>
    <ul style="padding-left: 10px;">
      <li>140 Amps Alternator</li>
      <li>600 Cca Battery Rating</li>
      <li>Battery Saver</li>
      <li>Maintenance-Free Battery</li>
      <li>50 State Emissions</li>
      <li>Auxiliary Oil Cooler</li>
    </ul>
  </div>
  <div class="section">
    <b>In_Car_Entertainment:</b>
    <br>
    <ul style="padding-left: 10px;">
      <li>Uconnect Infotainment</li>
    </ul>
  </div>
  <div class="section">
    <b>Instrumentation:</b>
    <br>
    <ul style="padding-left: 10px;">
      <li>Clock</li>
      <li>Digital Odometer</li>
      <li>Driver Information System</li>
      <li>External Temperature Display</li>
      <li>Tachometer Gauge</li>
      <li>Multi-Function Display</li>
      <li>Trip Computer</li>
      <li>2 Trip Odometer</li>
      <li>Low Fuel Level Warnings and Reminders</li>
    </ul>
  </div>
  <div class="section">
    <b>Lights:</b>
    <br>
    <ul style="padding-left: 10px;">
      <li>Daytime Running Lights</li>
      <li>Auto Delay Off Headlights</li>
      <li>Led Taillights</li>
    </ul>
  </div>
</div>


问:
SQL - Select *, but add in another column as the nth column?
This is probably a stupid question, but if I select tableA.*, but in the results I want a column from tableB as say the third column slotted in the middle of tableA's columns, is there a way to do this without manually selecting every single column from tableA and rearranging as required? This is in SSMS2016.

答:
You can use the following query

```<code>-- store column list of table1 in @cols1 with ',' delimited using sys tables.

declare @cols1 varchar(max) =  stuff((SELECT ',' + sys.columns.name FROM sys.columns
                        JOIN sys.tables ON sys.columns.object_id = sys.tables.object_id
                        WHERE sys.tables.name ='table1'
                for xml path('')),1,1,'')

-- find second occurance of ',' and replace it with ',columnNameFromTable2'
declare @pos int =  (SELECT CHARINDEX(',',LTRIM(RTRIM(@cols1)), (CHARINDEX(',', LTRIM(RTRIM(@cols1)) )+1)) secondpos)
declare @finalCols varchar(max) = stuff(@cols1,@pos,1,',columnNamefromTable2')

-- execute dynamic query to get expected result
exec('select '+@finalCols+' from table1 t join table2 t2 on (condition)')
</code>```

hope this query helps you :)

Body:
You can use the following query

-- store column list of table1 in @cols1 with ',' delimited using sys tables.

declare @cols1 varchar(max) =  stuff((SELECT ',' + sys.columns.name FROM sys.columns
                        JOIN sys.tables ON sys.columns.object_id = sys.tables.object_id
                        WHERE sys.tables.name ='table1'
                for xml path('')),1,1,'')

-- find second occurance of ',' and replace it with ',columnNameFromTable2'
declare @pos int =  (SELECT CHARINDEX(',',LTRIM(RTRIM(@cols1)), (CHARINDEX(',', LTRIM(RTRIM(@cols1)) )+1)) secondpos)
declare @finalCols varchar(max) = stuff(@cols1,@pos,1,',columnNamefromTable2')

-- execute dynamic query to get expected result
exec('select '+@finalCols+' from table1 t join table2 t2 on (condition)')

hope this query helps you :)


问:
The procedure to matching words from a list to words in a line
The following are two examples of many lines that I need to analyze and extract specific words from.

```<code>[40.748330000000003, -73.878609999999995] 6 2011-08-28 19:52:47 Sometimes I wish my life was a movie; #unreal I hate the fact I feel lonely surrounded by so many ppl

[37.786221300000001, -122.1965002] 6 2011-08-28 19:55:26 I wish I could lay up with the love of my life And watch cartoons all day.
</code>```

The coordinates and numbers are ignored

The case is to find how many of the words in each tweet line are present in this keywords list:

```<code>['hate', 1]
['hurt', 1]
['hurting', 1]
['like', 5]
['lonely', 1]
['love', 10]
</code>```

And also, find the sum of the values (e.g ['love', 10]) of the keywords found in each tweet line.

For example, for the sentence

```<code>'I hate to feel lonely at times'
</code>```

The sum of sentiments values for hate=1 and lonely=1 is equal to 2.
And the no. of words in the line is 7.

I've tried to use list into lists method and even trying to go through each sentence and keywords, but those haven't worked because the no. of tweets and keywords are several and I need to use loop format to find the values.

What I want to find out is the sum of sentiment values of the keywords found in each line and how many words there were in each line

Appreciate your insight in advance!! :)

My Code:

```<code>try:
    KeywordFileName=input('Input keyword file name: ')
    KeywordFile = open(KeywordFileName, 'r')
except FileNotFoundError:
    print('The file you entered does not exist or is not in the directory')
    exit()
KeyLine = KeywordFile.readline()
while KeyLine != '':
    if list != []:
        KeyLine = KeywordFile.readline()
        KeyLine = KeyLine.rstrip()
        list = KeyLine.split(',')
        list[1] = int(list[1])
        print(list)
    else:
        break

try:
    TweetFileName = input('Input Tweet file name: ')
    TweetFile = open(TweetFileName, 'r')
except FileNotFoundError:
    print('The file you entered does not exist or is not in the directory')
    exit()

TweetLine = TweetFile.readline()
while TweetLine != '':
    TweetLine = TweetFile.readline()
    TweetLine = TweetLine.rstrip()
</code>```

答:
The simplest approach is to use word_tokenize from nltk library on a per tweet basis.

```<code>from nltk.tokenize import word_tokenize
import collections
import re

# Sample text from above
s = '[40.748330000000003, -73.878609999999995] 6 2011-08-28 19:52:47 Sometimes I wish my life was a movie; #unreal I hate the fact I feel lonely surrounded by so many ppl'
num_regex = re.compile(r"[+-]?\d+(?:\.\d+)?")
# Removing the numbers from the text
s = num_regex.sub('',s)
# Tokenization
tokens = word_tokenize(s)
# Counting the words
fdist = collections.Counter(tokens)
print fdist
</code>```

`

Body:
The following are two examples of many lines that I need to analyze and extract specific words from.

[40.748330000000003, -73.878609999999995] 6 2011-08-28 19:52:47 Sometimes I wish my life was a movie; #unreal I hate the fact I feel lonely surrounded by so many ppl

[37.786221300000001, -122.1965002] 6 2011-08-28 19:55:26 I wish I could lay up with the love of my life And watch cartoons all day.

The coordinates and numbers are ignored

The case is to find how many of the words in each tweet line are present in this keywords list:

['hate', 1]
['hurt', 1]
['hurting', 1]
['like', 5]
['lonely', 1]
['love', 10]

And also, find the sum of the values (e.g ['love', 10]) of the keywords found in each tweet line.

For example, for the sentence

'I hate to feel lonely at times'

The sum of sentiments values for hate=1 and lonely=1 is equal to 2.
And the no. of words in the line is 7.

I've tried to use list into lists method and even trying to go through each sentence and keywords, but those haven't worked because the no. of tweets and keywords are several and I need to use loop format to find the values.

What I want to find out is the sum of sentiment values of the keywords found in each line and how many words there were in each line

Appreciate your insight in advance!! :)

My Code:

try:
    KeywordFileName=input('Input keyword file name: ')
    KeywordFile = open(KeywordFileName, 'r')
except FileNotFoundError:
    print('The file you entered does not exist or is not in the directory')
    exit()
KeyLine = KeywordFile.readline()
while KeyLine != '':
    if list != []:
        KeyLine = KeywordFile.readline()
        KeyLine = KeyLine.rstrip()
        list = KeyLine.split(',')
        list[1] = int(list[1])
        print(list)
    else:
        break

try:
    TweetFileName = input('Input Tweet file name: ')
    TweetFile = open(TweetFileName, 'r')
except FileNotFoundError:
    print('The file you entered does not exist or is not in the directory')
    exit()

TweetLine = TweetFile.readline()
while TweetLine != '':
    TweetLine = TweetFile.readline()
    TweetLine = TweetLine.rstrip()

Body:
The simplest approach is to use word_tokenize from nltk library on a per tweet basis.

from nltk.tokenize import word_tokenize
import collections
import re

# Sample text from above
s = '[40.748330000000003, -73.878609999999995] 6 2011-08-28 19:52:47 Sometimes I wish my life was a movie; #unreal I hate the fact I feel lonely surrounded by so many ppl'
num_regex = re.compile(r"[+-]?\d+(?:\.\d+)?")
# Removing the numbers from the text
s = num_regex.sub('',s)
# Tokenization
tokens = word_tokenize(s)
# Counting the words
fdist = collections.Counter(tokens)
print fdist

`


问:
Forward Kinematics for Baxter
I've put together this Forward Kinematics function for Baxter arm robot based on its hardware specs and the following joints axis:
The joint positions for the following forward kinematics are not matching the corresponding Cartesian coordinates, what am I doing wrong here?

```<code>def FK_function_2(joints):
    def yaw(theta): #(rotation around z)
        y = np.array([[np.cos(theta), -np.sin(theta), 0],
                      [np.sin(theta), np.cos(theta), 0],
                      [0, 0, 1] ])
        return y

    R01 = yaw(joints[0]).dot(np.array([[-1,     0,   0],
                                       [0,      0,   1],
                                       [0,      1,   0]]))
    R12 = yaw(joints[1]).dot(np.array([[0,      0,   -1],
                                       [-1,     0,   0],
                                       [0,      1,   0]]))
    R23 = yaw(joints[2]).dot(np.array([[-1,     0,   0],
                                       [0,      0,   1],
                                       [0,      1,   0]]))
    R34 = yaw(joints[3]).dot(np.array([[-1,     0,   0],
                                       [0,      0,   1],
                                       [0,      1,   0]]))
    R45 = yaw(joints[4]).dot(np.array([[-1,     0,   0],
                                       [0,      0,   1],
                                       [0,      1,   0]]))
    R56 = yaw(joints[5]).dot(np.array([[-1,     0,   0],
                                       [0,      0,   1],
                                       [0,      1,   0]]))
    R67 = yaw(joints[6]).dot(np.array([[1,      0,   0],
                                       [0,      1,   0],
                                       [0,      0,   1]]))

    d = np.array([0.27035, 0, 0.36435, 0, 0.37429, 0, 0.229525])
    a = np.array([0.069, 0, 0.069, 0, 0.010, 0, 0])

    l1 = np.array([a[0]*np.cos(joints[0]), a[0]*np.sin(joints[0]), d[0]]);
    l2 = np.array([a[1]*np.cos(joints[1]), a[1]*np.sin(joints[1]), d[1]]);
    l3 = np.array([a[2]*np.cos(joints[2]), a[2]*np.sin(joints[2]), d[2]]);
    l4 = np.array([a[3]*np.cos(joints[3]), a[3]*np.sin(joints[3]), d[3]]);
    l5 = np.array([a[4]*np.cos(joints[4]), a[4]*np.sin(joints[4]), d[4]]);
    l6 = np.array([a[5]*np.cos(joints[5]), a[5]*np.sin(joints[5]), d[5]]);
    l7 = np.array([a[6]*np.cos(joints[6]), a[6]*np.sin(joints[6]), d[6]]);

    unit = np.array([0, 0, 0, 1])
    H0 = np.concatenate((np.concatenate((R01, l1.reshape(3, 1)), axis=1), unit.reshape(1,4)), axis=0)
    H1 = np.concatenate((np.concatenate((R12, l2.reshape(3, 1)), axis=1), unit.reshape(1,4)), axis=0)
    H2 = np.concatenate((np.concatenate((R23, l3.reshape(3, 1)), axis=1), unit.reshape(1,4)), axis=0)
    H3 = np.concatenate((np.concatenate((R34, l4.reshape(3, 1)), axis=1), unit.reshape(1,4)), axis=0)
    H4 = np.concatenate((np.concatenate((R45, l5.reshape(3, 1)), axis=1), unit.reshape(1,4)), axis=0)
    H5 = np.concatenate((np.concatenate((R56, l6.reshape(3, 1)), axis=1), unit.reshape(1,4)), axis=0)
    H6 = np.concatenate((np.concatenate((R67, l7.reshape(3, 1)), axis=1), unit.reshape(1,4)), axis=0)

    T = H0.dot(H1).dot(H2).dot(H3).dot(H4).dot(H5).dot(H6)

    return T[0:3, 3]
</code>```

答:
Ok, so I have been looking at this and checked your code. The code is good and works with your defined kinematic chain with transformations from the base to the end of the robotic arm.

(H0 * H1 * H2 * H3 * H4 * H5 * H6)  is the correct kinematic chain where each represents a transformation from one joint to the next in the chain starting at the base of the arm.

The problem is your transformations are wrong. Your representation of H0 through H6 is not right and it is the numbers in these matrices that cause your transformations to not match the real transformations that take place. You need to from up the correct transformations from the base all the way to the end of the arm. Other than that, your approach is correct.

It looks like you are using normal DH parameters for your transformation matrices. Your values for a and d (and alpha which isn't shown in your code) are off and causing the transformations to be expressed incorrectly. The DH parameters are seen in https://en.wikipedia.org/wiki/Denavit%E2%80%93Hartenberg_parameters.

I found an exact guide for Baxter's forward kinematics to help after going through the modified DH table to set up the transformations. I would look at the modified DH parameters at the end of the wiki article above since the guide uses that.

Baxter Forward Kinematic Guide: https://www.ohio.edu/mechanical-faculty/williams/html/pdf/BaxterKinematics.pdf

In this paper, the author, Robert Williams, sets up the DH parameters for the Baxter robotic arm and gets values different than what you have (I know you are using the normal DH parameters, but I would look at using the modified ones). His table is:

With lengths of:

And using the modified DH matrix:

Now you can calculate matrices H0 through H6 and if you want you can also add the end effector geometry if you have that for an additional H7. Once you multiple them all together you should get the proper forward kinematic transformation (see the paper for additional resource). Both the left and right arms have the same kinematics.

When you multiply it all together then you get the expressions for the coordinates of x7, y7, and z7 from the base of the arm that are functions of the rotations of the joints and the geometry of the robot arm. See the paper on page 17 for the expressions for x7,y7, and z7. Also see page 14 for the individual transformations.

Also don't forget to express the angles in radians since your code uses regular trig functions.

One last update:
I just remembered that it is easier for me to think of the intermediate translation and rotational steps one-by-one (instead of jumping straight to the DH matrix). The two approaches will be equivalent, but I like to think of each individual step that it takes to get from one rotation frame to the next.

For this you can use these building blocks.

Pure Translation:

```<code>[1   0   0   u;
0    1   0   v;
0    0   1   w;
0    0   0    1]
</code>```

Where u is the distance from the previous frame to the new frame measured from the previous x frame axis.

Where v is the distance from the previous frame to the new frame measured from the previous y frame axis.

Where w is the distance from the previous frame to the new frame measured from the previous z frame axis.

Rotation about the z-axis by arbitrary theta:
This represent the robot joint rotation to an arbitrary theta.

```<code>[cos(theta)    -sin(theta)        0 0;
sin(theta)     cos(theta)         0 0;
0                   0             1 0;
0                   0             0 1]
</code>```

Combination of rotations around intermediate frames to get to final frame position: (these angles will usually be in increments of pi/2 or pi to be able to get to the final orientation)
Can use a rotation about the intermediate x axis, y axis, or z axis shown below.

(Rotation about x axis by alpha)

```<code>R_x(alpha) =         [1             0           0              0;
                      0         cos(alpha)  -sin(alpha)        0;
                      0         sin(alpha)  cos(alpha)         0;
                      0            0            0              1];
</code>```

(Rotation about y axis by beta)

```<code>R_y(beta) =   [  cos(beta)     0      sin(beta)    0;
                     0         1          0        0;
                 -sin(beta)    0      cos(beta)    0;
                     0         0          0        1];
</code>```

(Rotation about z axis by gamma):

```<code>[cos(gamma)  -sin(gamma)     0      0;
sin(gamma)    cos(gamma)     0      0;
       0          0          1      0;
       0          0          0      1]
</code>```

So with these building blocks you can build the sequence of steps to go from one frame to another (essentially any H matrix can be decomposed into these steps). The chain would be something like:

[H](transformation from previous frame to the next frame) = [Pure Translation from previous joint to new joint expressed in the previous joint's frame] * [Rotation about previous frame's z-axis by theta (for the joint) (since the joint has many positions, theta is left as symbolic)] * [All other intermediate rotations to arrive at the new joint frame orientation expressed as rotations about intermediate axis frames]

That is essentially what the DH parameters helps you do, but I like to think of the individual steps to get from one frame to the next instead of jumping there with the DH parameters.

With the corrected H0 through H6 transformations, your approach is correct. Just change the definitions of H0 through H6 in your code.

Title: Forward Kinematics for Baxter

Body:
I've put together this Forward Kinematics function for Baxter arm robot based on its hardware specs and the following joints axis:
The joint positions for the following forward kinematics are not matching the corresponding Cartesian coordinates, what am I doing wrong here?

def FK_function_2(joints):
    def yaw(theta): #(rotation around z)
        y = np.array([[np.cos(theta), -np.sin(theta), 0],
                      [np.sin(theta), np.cos(theta), 0],
                      [0, 0, 1] ])
        return y

    R01 = yaw(joints[0]).dot(np.array([[-1,     0,   0],
                                       [0,      0,   1],
                                       [0,      1,   0]]))
    R12 = yaw(joints[1]).dot(np.array([[0,      0,   -1],
                                       [-1,     0,   0],
                                       [0,      1,   0]]))
    R23 = yaw(joints[2]).dot(np.array([[-1,     0,   0],
                                       [0,      0,   1],
                                       [0,      1,   0]]))
    R34 = yaw(joints[3]).dot(np.array([[-1,     0,   0],
                                       [0,      0,   1],
                                       [0,      1,   0]]))
    R45 = yaw(joints[4]).dot(np.array([[-1,     0,   0],
                                       [0,      0,   1],
                                       [0,      1,   0]]))
    R56 = yaw(joints[5]).dot(np.array([[-1,     0,   0],
                                       [0,      0,   1],
                                       [0,      1,   0]]))
    R67 = yaw(joints[6]).dot(np.array([[1,      0,   0],
                                       [0,      1,   0],
                                       [0,      0,   1]]))

    d = np.array([0.27035, 0, 0.36435, 0, 0.37429, 0, 0.229525])
    a = np.array([0.069, 0, 0.069, 0, 0.010, 0, 0])

    l1 = np.array([a[0]*np.cos(joints[0]), a[0]*np.sin(joints[0]), d[0]]);
    l2 = np.array([a[1]*np.cos(joints[1]), a[1]*np.sin(joints[1]), d[1]]);
    l3 = np.array([a[2]*np.cos(joints[2]), a[2]*np.sin(joints[2]), d[2]]);
    l4 = np.array([a[3]*np.cos(joints[3]), a[3]*np.sin(joints[3]), d[3]]);
    l5 = np.array([a[4]*np.cos(joints[4]), a[4]*np.sin(joints[4]), d[4]]);
    l6 = np.array([a[5]*np.cos(joints[5]), a[5]*np.sin(joints[5]), d[5]]);
    l7 = np.array([a[6]*np.cos(joints[6]), a[6]*np.sin(joints[6]), d[6]]);

    unit = np.array([0, 0, 0, 1])
    H0 = np.concatenate((np.concatenate((R01, l1.reshape(3, 1)), axis=1), unit.reshape(1,4)), axis=0)
    H1 = np.concatenate((np.concatenate((R12, l2.reshape(3, 1)), axis=1), unit.reshape(1,4)), axis=0)
    H2 = np.concatenate((np.concatenate((R23, l3.reshape(3, 1)), axis=1), unit.reshape(1,4)), axis=0)
    H3 = np.concatenate((np.concatenate((R34, l4.reshape(3, 1)), axis=1), unit.reshape(1,4)), axis=0)
    H4 = np.concatenate((np.concatenate((R45, l5.reshape(3, 1)), axis=1), unit.reshape(1,4)), axis=0)
    H5 = np.concatenate((np.concatenate((R56, l6.reshape(3, 1)), axis=1), unit.reshape(1,4)), axis=0)
    H6 = np.concatenate((np.concatenate((R67, l7.reshape(3, 1)), axis=1), unit.reshape(1,4)), axis=0)

    T = H0.dot(H1).dot(H2).dot(H3).dot(H4).dot(H5).dot(H6)

    return T[0:3, 3]

Body:
Ok, so I have been looking at this and checked your code. The code is good and works with your defined kinematic chain with transformations from the base to the end of the robotic arm.

(H0 * H1 * H2 * H3 * H4 * H5 * H6)  is the correct kinematic chain where each represents a transformation from one joint to the next in the chain starting at the base of the arm.

The problem is your transformations are wrong. Your representation of H0 through H6 is not right and it is the numbers in these matrices that cause your transformations to not match the real transformations that take place. You need to from up the correct transformations from the base all the way to the end of the arm. Other than that, your approach is correct.

It looks like you are using normal DH parameters for your transformation matrices. Your values for a and d (and alpha which isn't shown in your code) are off and causing the transformations to be expressed incorrectly. The DH parameters are seen in https://en.wikipedia.org/wiki/Denavit%E2%80%93Hartenberg_parameters.

I found an exact guide for Baxter's forward kinematics to help after going through the modified DH table to set up the transformations. I would look at the modified DH parameters at the end of the wiki article above since the guide uses that.

Baxter Forward Kinematic Guide: https://www.ohio.edu/mechanical-faculty/williams/html/pdf/BaxterKinematics.pdf

In this paper, the author, Robert Williams, sets up the DH parameters for the Baxter robotic arm and gets values different than what you have (I know you are using the normal DH parameters, but I would look at using the modified ones). His table is:

With lengths of:

And using the modified DH matrix:

Now you can calculate matrices H0 through H6 and if you want you can also add the end effector geometry if you have that for an additional H7. Once you multiple them all together you should get the proper forward kinematic transformation (see the paper for additional resource). Both the left and right arms have the same kinematics.

When you multiply it all together then you get the expressions for the coordinates of x7, y7, and z7 from the base of the arm that are functions of the rotations of the joints and the geometry of the robot arm. See the paper on page 17 for the expressions for x7,y7, and z7. Also see page 14 for the individual transformations.

Also don't forget to express the angles in radians since your code uses regular trig functions.

One last update:
I just remembered that it is easier for me to think of the intermediate translation and rotational steps one-by-one (instead of jumping straight to the DH matrix). The two approaches will be equivalent, but I like to think of each individual step that it takes to get from one rotation frame to the next.

For this you can use these building blocks.

Pure Translation:

[1   0   0   u;
0    1   0   v;
0    0   1   w;
0    0   0    1]

Where u is the distance from the previous frame to the new frame measured from the previous x frame axis.

Where v is the distance from the previous frame to the new frame measured from the previous y frame axis.

Where w is the distance from the previous frame to the new frame measured from the previous z frame axis.

Rotation about the z-axis by arbitrary theta:
This represent the robot joint rotation to an arbitrary theta.

[cos(theta)    -sin(theta)        0 0;
sin(theta)     cos(theta)         0 0;
0                   0             1 0;
0                   0             0 1]

Combination of rotations around intermediate frames to get to final frame position: (these angles will usually be in increments of pi/2 or pi to be able to get to the final orientation)
Can use a rotation about the intermediate x axis, y axis, or z axis shown below.

(Rotation about x axis by alpha)

R_x(alpha) =         [1             0           0              0;
                      0         cos(alpha)  -sin(alpha)        0;
                      0         sin(alpha)  cos(alpha)         0;
                      0            0            0              1];

(Rotation about y axis by beta)

R_y(beta) =   [  cos(beta)     0      sin(beta)    0;
                     0         1          0        0;
                 -sin(beta)    0      cos(beta)    0;
                     0         0          0        1];

(Rotation about z axis by gamma):

[cos(gamma)  -sin(gamma)     0      0;
sin(gamma)    cos(gamma)     0      0;
       0          0          1      0;
       0          0          0      1]

So with these building blocks you can build the sequence of steps to go from one frame to another (essentially any H matrix can be decomposed into these steps). The chain would be something like:

[H](transformation from previous frame to the next frame) = [Pure Translation from previous joint to new joint expressed in the previous joint's frame] * [Rotation about previous frame's z-axis by theta (for the joint) (since the joint has many positions, theta is left as symbolic)] * [All other intermediate rotations to arrive at the new joint frame orientation expressed as rotations about intermediate axis frames]

That is essentially what the DH parameters helps you do, but I like to think of the individual steps to get from one frame to the next instead of jumping there with the DH parameters.

With the corrected H0 through H6 transformations, your approach is correct. Just change the definitions of H0 through H6 in your code.


问:
What is the possible setting for Codeigniter connecting to a SSH server with centOS and mariadb as database management?
The server I'm using is an ssh connection, which is ran by centOS, it uses LAMP as platform.

Because it is centOS, mariadb is the only available database management for it. I cannot install mysql via sudo yum install mysql-server command.

I've created a project using codeigniter in my local.

I'm having trouble connecting to the database. The error gives like:

```<code>A PHP Error was encountered

Severity: Warning

Message: mysqli::real_connect(): (HY000/2002): A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond.

Filename: mysqli/mysqli_driver.php
</code>```

The db setting in my codeigniter is:

```<code>$active_group = 'default';
$query_builder = TRUE;

$db['default'] = array(
    'dsn'   => '',
    'hostname' => '*server-ip-address*',
    'port' => '*server-port-number*',
    'username' => 'root',
    'password' => 'root@999',
    'database' => 'listingapp_db',
    'dbdriver' => 'mysqli',
    'dbprefix' => '',
    'pconnect' => FALSE,
    'db_debug' => (ENVIRONMENT !== 'production'),
    'cache_on' => FALSE,
    'cachedir' => '',
    'char_set' => 'utf8',
    'dbcollat' => 'utf8_general_ci',
    'swap_pre' => '',
    'encrypt' => FALSE,
    'compress' => FALSE,
    'stricton' => FALSE,
    'failover' => array(),
    'save_queries' => TRUE
);
</code>```

I just thought that maybe my database setting is wrong.

Has it something to matter with the dbdriver setting?
I tried changing mysqli to mariadb, still no progress.

What could possibly be the valid setting that could co-inside with the server's centOS, mariadb?

I tried sudo iptables -vnL to check firewall and this is the result:

```<code>Chain INPUT (policy DROP 10924 packets, 630K bytes)
 pkts bytes target     prot opt in     out     source               destination
40905 5353K ACCEPT     tcp  --  *      *       0.0.0.0/0            0.0.0.0/0            tcp dpt:80
1860K 2702M ACCEPT     all  --  *      *       0.0.0.0/0            0.0.0.0/0            state RELATED,ESTABLISHED
    0     0 DROP       tcp  --  *      *       0.0.0.0/0            0.0.0.0/0            tcp flags:0x3F/0x00
    4   172 DROP       tcp  --  *      *       0.0.0.0/0            0.0.0.0/0            tcp flags:!0x17/0x02 state NEW
    0     0 DROP       tcp  --  *      *       0.0.0.0/0            0.0.0.0/0            tcp flags:0x3F/0x3F
  158  9480 ACCEPT     all  --  lo     *       0.0.0.0/0            0.0.0.0/0
  445 28059 ACCEPT     icmp --  *      *       0.0.0.0/0            0.0.0.0/0
   57  2800 ACCEPT     tcp  --  *      *       0.0.0.0/0            0.0.0.0/0            tcp dpt:2202

Chain FORWARD (policy ACCEPT 0 packets, 0 bytes)
 pkts bytes target     prot opt in     out     source               destination

Chain OUTPUT (policy ACCEPT 1133K packets, 103M bytes)
 pkts bytes target     prot opt in     out     source               destination
</code>```

答: I have now fixed my issue. It's a matter of opening the port I used then granting privilege to the root user in mysql.</p>

Body:
The server I'm using is an ssh connection, which is ran by centOS, it uses LAMP as platform.

Because it is centOS, mariadb is the only available database management for it. I cannot install mysql via sudo yum install mysql-server command.

I've created a project using codeigniter in my local.

I'm having trouble connecting to the database. The error gives like:

A PHP Error was encountered

Severity: Warning

Message: mysqli::real_connect(): (HY000/2002): A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond.

Filename: mysqli/mysqli_driver.php

The db setting in my codeigniter is:

$active_group = 'default';
$query_builder = TRUE;

$db['default'] = array(
    'dsn'   => '',
    'hostname' => '*server-ip-address*',
    'port' => '*server-port-number*',
    'username' => 'root',
    'password' => 'root@999',
    'database' => 'listingapp_db',
    'dbdriver' => 'mysqli',
    'dbprefix' => '',
    'pconnect' => FALSE,
    'db_debug' => (ENVIRONMENT !== 'production'),
    'cache_on' => FALSE,
    'cachedir' => '',
    'char_set' => 'utf8',
    'dbcollat' => 'utf8_general_ci',
    'swap_pre' => '',
    'encrypt' => FALSE,
    'compress' => FALSE,
    'stricton' => FALSE,
    'failover' => array(),
    'save_queries' => TRUE
);

I just thought that maybe my database setting is wrong.

Has it something to matter with the dbdriver setting?
I tried changing mysqli to mariadb, still no progress.

What could possibly be the valid setting that could co-inside with the server's centOS, mariadb?

I tried sudo iptables -vnL to check firewall and this is the result:

Chain INPUT (policy DROP 10924 packets, 630K bytes)
 pkts bytes target     prot opt in     out     source               destination
40905 5353K ACCEPT     tcp  --  *      *       0.0.0.0/0            0.0.0.0/0            tcp dpt:80
1860K 2702M ACCEPT     all  --  *      *       0.0.0.0/0            0.0.0.0/0            state RELATED,ESTABLISHED
    0     0 DROP       tcp  --  *      *       0.0.0.0/0            0.0.0.0/0            tcp flags:0x3F/0x00
    4   172 DROP       tcp  --  *      *       0.0.0.0/0            0.0.0.0/0            tcp flags:!0x17/0x02 state NEW
    0     0 DROP       tcp  --  *      *       0.0.0.0/0            0.0.0.0/0            tcp flags:0x3F/0x3F
  158  9480 ACCEPT     all  --  lo     *       0.0.0.0/0            0.0.0.0/0
  445 28059 ACCEPT     icmp --  *      *       0.0.0.0/0            0.0.0.0/0
   57  2800 ACCEPT     tcp  --  *      *       0.0.0.0/0            0.0.0.0/0            tcp dpt:2202

Chain FORWARD (policy ACCEPT 0 packets, 0 bytes)
 pkts bytes target     prot opt in     out     source               destination

Chain OUTPUT (policy ACCEPT 1133K packets, 103M bytes)
 pkts bytes target     prot opt in     out     source               destination


问:
How can i enter only one data per Item in Grid
Here i have small requirement like  in my dropdown  i have Piza,Burger option When i select any one only once should be enter in Grid not more than one

```<code> <select id="Drp_Bake">
    <option value="1">Pizza</option>
    <option value="2">Burger</option>

</select>
<input type="button" value="Submit" id="Bake_Items" />

<div id="DisplayItems"></div>
</code>```

JqueryCode

```<code> $(document).ready(function () {
var key = [];
$('#Bake_Items').click(function () {
    var Menus= $('#Drp_Bake').val();
    var Bake_Items= key.push(Menus);
 $('#DisplayItems').append(Bake_Items);
})
</code>```

The Items Stored in Key Array but its should be Inserted only not more-than once

答:
HTML Code

```<code><select id="Drp_Bake">
  <option Value="0">-Select-</option>
  <option value="1">Pizza</option>
  <option value="2">Burger</option>
</select>
<input type="button" value="Submit" id="Bake_Items" />

<div id="DisplayItems"></div>
</code>```

JQUERY

```<code> $(document).ready(function () {
            var key = [];
            var selected;
            $('#Bake_Items').click(function () {
                selected = $('#Drp_Bake option:selected').text();

                if (selected == '-Select-') {
                    alert('Please Select any Value...');
                }
                else if (jQuery.inArray(selected, key) == -1) {
                    key.push(selected);
                    $('#DisplayItems').append(selected);
                    $('#DisplayItems').append('</br>');
                }
                else {
                    alert('already selected choose another one...');
                }
            });
        });
</code>```

here, i used "jQuery.inArray()" method to check existence of the value in the array...
if value not exists in the array method returns -1....

Body:
Here i have small requirement like  in my dropdown  i have Piza,Burger option When i select any one only once should be enter in Grid not more than one

 <select id="Drp_Bake">
    <option value="1">Pizza</option>
    <option value="2">Burger</option>

</select>
<input type="button" value="Submit" id="Bake_Items" />

JqueryCode

 $(document).ready(function () {
var key = [];
$('#Bake_Items').click(function () {
    var Menus= $('#Drp_Bake').val();
    var Bake_Items= key.push(Menus);
 $('#DisplayItems').append(Bake_Items);
})

The Items Stored in Key Array but its should be Inserted only not more-than once

Body:
HTML Code

<select id="Drp_Bake">
  <option Value="0">-Select-</option>
  <option value="1">Pizza</option>
  <option value="2">Burger</option>
</select>
<input type="button" value="Submit" id="Bake_Items" />

<div id="DisplayItems"></div>

JQUERY

 $(document).ready(function () {
            var key = [];
            var selected;
            $('#Bake_Items').click(function () {
                selected = $('#Drp_Bake option:selected').text();

                if (selected == '-Select-') {
                    alert('Please Select any Value...');
                }
                else if (jQuery.inArray(selected, key) == -1) {
                    key.push(selected);
                    $('#DisplayItems').append(selected);
                    $('#DisplayItems').append('</br>');
                }
                else {
                    alert('already selected choose another one...');
                }
            });
        });

here, i used "jQuery.inArray()" method to check existence of the value in the array...
if value not exists in the array method returns -1....


问:
How to disable auto hide the solution explorer (Visual Studio 2017)
How to disable auto hide solution explorer (Visual Studio 2017)?

Every time after launching the project, the solution explorer does autohide.

How disable it?

答:
I resolve it problem.

Solution:

Delete the following directories:

```<code>%userfolder%\AppData\Local\Microsoft\VisualStudio
%userfolder%\AppData\Local\Microsoft\Visual Studio
%userfolder%\AppData\Local\Microsoft\VisualStudio Services
%userfolder%\AppData\Roaming\Microsoft\VisualStudio
</code>```

Microsoft Visual Studio Enterprise 2017 (15.4.4)

P.S. devenv /Resetsettings does not help.

Body:
I resolve it problem.

Solution:

Delete the following directories:

%userfolder%\AppData\Local\Microsoft\VisualStudio
%userfolder%\AppData\Local\Microsoft\Visual Studio
%userfolder%\AppData\Local\Microsoft\VisualStudio Services
%userfolder%\AppData\Roaming\Microsoft\VisualStudio

Microsoft Visual Studio Enterprise 2017 (15.4.4)

P.S. devenv /Resetsettings does not help.


问:
MySQL Query to list users who have recently messaged
I'm building a chat application and I want to list the users who have recently messaged, with their id, name, pic, and last message (id, timestamp, content)

My two tables look like this:

```<code>users:
------
id
name
pic

messages:
---------
id
content
timestamp
user_id (foreign key of user's id)
</code>```

Here is the query that I've tried:

```<code>SELECT U.*,
    MAX(M.id) as lastmessage_id
FROM users U, messages M
WHERE M.user_id=U.id
GROUP BY user_id
ORDER BY lastmessage_id DESC
</code>```

It will list the users who have messaged recently but it doesn't contain the last message's 'content'

Current output:

```<code>id, name, pic, lastmessage_id
</code>```

Required output:

```<code>id, name, pic, lastmessage_id, lastmessage_content, lastmessage_timestamp
</code>```

答:
Try this...</p>

```<code>select t1.id,t1.name,t1.pic,t1.lastmessage_id from (SELECT U.id,U.name,U.pic,(M.id) as lastmessage_id FROM users U, messages M WHERE M.user_id=U.id ORDER BY lastmessage_id DESC) t1
GROUP BY t1.id
</code>```

Body:
I'm building a chat application and I want to list the users who have recently messaged, with their id, name, pic, and last message (id, timestamp, content)

My two tables look like this:

users:
------
id
name
pic

messages:
---------
id
content
timestamp
user_id (foreign key of user's id)

Here is the query that I've tried:

SELECT U.*,
    MAX(M.id) as lastmessage_id
FROM users U, messages M
WHERE M.user_id=U.id
GROUP BY user_id
ORDER BY lastmessage_id DESC

It will list the users who have messaged recently but it doesn't contain the last message's 'content'

Current output:

id, name, pic, lastmessage_id

Required output:

id, name, pic, lastmessage_id, lastmessage_content, lastmessage_timestamp

Body:
Try this...

select t1.id,t1.name,t1.pic,t1.lastmessage_id from (SELECT U.id,U.name,U.pic,(M.id) as lastmessage_id FROM users U, messages M WHERE M.user_id=U.id ORDER BY lastmessage_id DESC) t1
GROUP BY t1.id


问:
How do I calculate the area of a projection created by the command "view"?
How do I calculate the area of a projection? For example, using the following code, I get a projection on the X-Z plane.

```<code>[x,y,z]=peaks;
surf(x,y,z);
xlabel('x');ylabel('y');zlabel('z')
view([0,0])
</code>```

X-Z Plane Projection

I want to be able to determine the area of the projection of any surf plot that I create. Is there a command or function for this?

答:
Short answer

```<code>polyarea(x(1,:),max(z))+polyarea(x(1,:),min(z))
</code>```

Explanation

The plot you want to calculate its area is,

In area calculation you need only the borders of the projection,

```<code>plot(x(1,:),max(z))
hold on
plot(x(1,:),min(z),'r')
</code>```

and the output is,

The total area is the summation of both areas (upper border to x axis and lower border to x axis),

```<code>>> polyarea(x(1,:),max(z))+polyarea(x(1,:),min(z))
>> 28.5947
</code>```

Body:
How do I calculate the area of a projection? For example, using the following code, I get a projection on the X-Z plane.

[x,y,z]=peaks;
surf(x,y,z);
xlabel('x');ylabel('y');zlabel('z')
view([0,0])

X-Z Plane Projection

I want to be able to determine the area of the projection of any surf plot that I create. Is there a command or function for this?

Body:
Short answer

polyarea(x(1,:),max(z))+polyarea(x(1,:),min(z))

Explanation

The plot you want to calculate its area is,

In area calculation you need only the borders of the projection,

plot(x(1,:),max(z))
hold on
plot(x(1,:),min(z),'r')

and the output is,

The total area is the summation of both areas (upper border to x axis and lower border to x axis),

>> polyarea(x(1,:),max(z))+polyarea(x(1,:),min(z))
>> 28.5947


答:
First find all the latest message id for each user and then join it with messages table to get the corresponding rows:

```<code>select u.*,
    m.*
from users u
join messages m on u.id = m.user_id
join (
    select user_id,
        max(id) as id
    from messages
    group by user_id
    ) t on m.id = t.id
        and m.user_id = t.user_id
order by m.id desc;
</code>```

Also, always use explicit modern join syntax instead of old comma based syntax.

Title: MySQL Query to list users who have recently messaged

Body:
First find all the latest message id for each user and then join it with messages table to get the corresponding rows:

select u.*,
    m.*
from users u
join messages m on u.id = m.user_id
join (
    select user_id,
        max(id) as id
    from messages
    group by user_id
    ) t on m.id = t.id
        and m.user_id = t.user_id
order by m.id desc;

Also, always use explicit modern join syntax instead of old comma based syntax.


问:
Calculate the softmax of an array column-wise using numpy
Following https://classroom.udacity.com/courses/ud730/lessons/6370362152/concepts/63815621490923, I'm trying to write a "softmax" function which, when given a 2-dimensional array as input, calculates the softmax of each column. I wrote the following script to test it:

```<code>import numpy as np

#scores=np.array([1.0,2.0,3.0])

scores=np.array([[1,2,3,6],
                [2,4,5,6],
                [3,8,7,6]])

def softmax(x):
    if x.ndim==1:
        S=np.sum(np.exp(x))
        return np.exp(x)/S
    elif x.ndim==2:
        result=np.zeros_like(x)
        M,N=x.shape
        for n in range(N):
            S=np.sum(np.exp(x[:,n]))
            result[:,n]=np.exp(x[:,n])/S
        return result
    else:
        print("The input array is not 1- or 2-dimensional.")

s=softmax(scores)
print(s)
</code>```

However, the result "s" turns out to be an array of zeros:

```<code>[[0 0 0 0]
 [0 0 0 0]
 [0 0 0 0]]
</code>```

If I remove the "/S" in the for-loop, the 'un-normalized' result is as I would expect it to be; somehow the "/S" division appears to make all the elements zero instead dividing each element by S as I would expect it to. What is wrong with the code?

答:
Numpy has some nifty matrix operations that makes this problem a lot easier and simpler to solve.

Calculating the exponential works on a matrix of any dimension

the sum() method takes an argument axis which allows us to restrict the sum to a given axis - columns maps to axis 0 in our case.

```<code>def softmax(x):
    exp = np.exp(x) # exp just calculates exp for all elements in the matrix
    return exp / exp.sum(0) # sum axis = 0 argument sums over axis representing columns
</code>```

Body:
Following https://classroom.udacity.com/courses/ud730/lessons/6370362152/concepts/63815621490923, I'm trying to write a "softmax" function which, when given a 2-dimensional array as input, calculates the softmax of each column. I wrote the following script to test it:

import numpy as np

#scores=np.array([1.0,2.0,3.0])

scores=np.array([[1,2,3,6],
                [2,4,5,6],
                [3,8,7,6]])

def softmax(x):
    if x.ndim==1:
        S=np.sum(np.exp(x))
        return np.exp(x)/S
    elif x.ndim==2:
        result=np.zeros_like(x)
        M,N=x.shape
        for n in range(N):
            S=np.sum(np.exp(x[:,n]))
            result[:,n]=np.exp(x[:,n])/S
        return result
    else:
        print("The input array is not 1- or 2-dimensional.")

s=softmax(scores)
print(s)

However, the result "s" turns out to be an array of zeros:

[[0 0 0 0]
 [0 0 0 0]
 [0 0 0 0]]

If I remove the "/S" in the for-loop, the 'un-normalized' result is as I would expect it to be; somehow the "/S" division appears to make all the elements zero instead dividing each element by S as I would expect it to. What is wrong with the code?

Body:
Numpy has some nifty matrix operations that makes this problem a lot easier and simpler to solve.

Calculating the exponential works on a matrix of any dimension

the sum() method takes an argument axis which allows us to restrict the sum to a given axis - columns maps to axis 0 in our case.

def softmax(x):
    exp = np.exp(x) # exp just calculates exp for all elements in the matrix
    return exp / exp.sum(0) # sum axis = 0 argument sums over axis representing columns