问:
What am I doing wrong when trying to run the this java test command for LWJGL?
I'm attempting to use the lwjgl library and I'm starting from scratch on a new Windows 7 install.

I downloaded the latest JDK 6 from the Oracle website.  After installing it, I found that commands like "java" or "javac" weren't being recognized from a windows cmd prompt.  So, I edited my path variable and appended the jdk's bin folder to it.

Now the java commands work.

So, I download the latest lwjgl, extract it and read the installation instructions on their website:

Download the distribution Unpack the
  archive, file contents (in sub
  folders) should include (amongst other
  things):

lwjgl.dll lwjglaudio.dll lwjgl.jar
  lwjgl_util.jar lwjgl_test.jar

  Test
  LWJGL by opening a command prompt, and
  navigating to the folder where the
  archive was extracted. Once navigated,
  issue the following command: (all in
  one line, space before each -option)

java -cp .;res;jar\lwjgl.jar;jar\lwjgl_test.jar;jar\lwjgl_util.jar;jar\lwjgl_fmod3.jar;jar\lwjgl_devil.jar;jar\jinput.jar;-Djava.library.path=native\windows org.lwjgl.test.WindowCreationTest

A window should appear and you should
  see the following output:

Found  display modes 240, 320,
  WindowCreationTest Display created
  Moving to 100, 100 Window created 600,
  800, Game

So, I extracted it and navigated to the extracted folder in a cmd prompt.

I then executed the test command specified above and I get the following error:

C:\Users\Nestor\Downloads\lwjgl-2.6\lwjgl-2.6>java
  -cp .;res;jar\lwjgl.jar;jar\ lwjgl_test.jar;jar\lwjgl_util.jar;jar\lwjgl_fmod3.jar;jar\lwjgl_devil.jar;jar\ji
  nput.jar;-Djava.library.path=native\windows
  org.lwjgl.test.WindowCreationTest

  The
  following keys are available: ESCAPE:
  Exit test ARROW Keys:     Move window
  when in non-fullscreen mode L:

  List selectable display modes 0-8:

  Selection of display modes F:

  Toggle fullscreen SHIFT-F:

  Toggle fullscreen with
  Display.destroy()/create() cycle
  Exception in thread "main"
  java.lang.UnsatisfiedLinkError: no
  lwjgl in java.libr ary.path
          at java.lang.ClassLoader.loadLibrary(ClassLoader.java:1734)
          at java.lang.Runtime.loadLibrary0(Runtime.java:823)
          at java.lang.System.loadLibrary(System.java:1028)
          at org.lwjgl.Sys$1.run(Sys.java:73)
          at java.security.AccessController.doPrivileged(Native
  Method)
          at org.lwjgl.Sys.doLoadLibrary(Sys.java:66)
          at org.lwjgl.Sys.loadLibrary(Sys.java:82)
          at org.lwjgl.Sys.(Sys.java:99)
          at org.lwjgl.opengl.Display.(Display.java:130)
          at org.lwjgl.test.WindowCreationTest.initialize(WindowCreationTest.java:
  82)
          at org.lwjgl.test.WindowCreationTest.main(WindowCreationTest.java:286)

C:\Users\Nestor\Downloads\lwjgl-2.6\lwjgl-2.6>

Why am I getting that error?  I don't understand why there should be linking errors.  In the command that I attempted to execute it clearly spells out the path to those native dll's it needs:

C:\Users\Nestor\Downloads\lwjgl-2.6\lwjgl-2.6>java
  -cp .;res;jar\lwjgl.jar;jar\ lwjgl_test.jar;jar\lwjgl_util.jar;jar\lwjgl_fmod3.jar;jar\lwjgl_devil.jar;jar\ji
  nput.jar;-Djava.library.path=native\windows
  org.lwjgl.test.WindowCreationTest

I've confirmed that the relative path "native\windows" contains those dependencies:

C:\Users\Nestor\Downloads\lwjgl-2.6\lwjgl-2.6\native\windows>dir

  Volume in drive C has no label.

  Volume Serial Number is 2061-75F6

Directory of C:\Users\Nestor\Downloads\lwjgl-2.6\lwjgl-2.6\native\windows

11/24/2010  12:35 AM              .

  11/24/2010  12:35 AM              ..

  10/18/2010  08:44 PM            31,232 jinput-dx8.dll

  10/18/2010  08:44 PM            65,024 jinput-dx8_64.dll

  10/18/2010  08:44 PM            29,696 jinput-raw.dll

  10/18/2010  08:44 PM            62,464 jinput-raw_64.dll

  10/18/2010  08:44 PM           197,120 lwjgl.dll

  10/18/2010  08:44 PM           305,664 lwjgl64.dll

  10/18/2010  08:44 PM            56,832 OpenAL32.dll

  10/18/2010  08:44 PM           157,184 OpenAL64.dll

                8 File(s)        905,216 bytes

                2 Dir(s)  155,163,058,176 bytes free

Can anyone help point out what I'm doing wrong? Can anyone reproduce this by downloading the LWJGL library and attempting to run the test command given in the installation instructions?

答: Just throwing this out there, because Ive had some issues related to this. Go to your Java/JRE/BIN folder. Right click on Java, and go to properties. Under Privilege Level, check the box by run as an administrator.</p>


来源: stackexchange

问:
How to retrieve user avatar from a Trello API?
trello API gives only hashes, such as avatarHash, gravatarHash, uploadedAvatarHash etc. Is there any way to retrieve an image url from these hashes?

答: Using this hash you can retrieve an image by url: http://trello-avatars.s3.amazonaws.com/${avatarHash}/50.png</p>

ContentLicense: CC BY-SA 3.0


问:
Conditional update Dynamodb on nested object
I am trying to learn to use DynamoDB with C#
I have Partial updates, Put, Delete working.
Conditional update works (If the Attributes is part of root object).

I have the following model created.

Person with a lot of attributes.
The following works:

```<code>Expression expr = new Expression();
expr.ExpressionStatement = "Age = :age";
expr.ExpressionAttributeValues[":age"] = 26;

UpdateItemOperationConfig config = new UpdateItemOperationConfig
{
    ConditionalExpression = expr,
    ReturnValues = ReturnValues.AllNewAttributes
};

Document updatedPerson2 = personCatalog.UpdateItem(doc, config);
</code>```

But what if my condition was on the Pet Name?

I have tried a couple of approaches with no luck eg:

```<code>expr.ExpressionStatement = "Pet.Name = :name";
expr.ExpressionAttributeValues[":name"] = "Lilleper";
</code>```

Hope someone can help :) Or just nudge me in the right direction.

答:
Try externalizing the Name sub-attribute name to ExpressionAttributeNames.</p>

```<code>Expression expr = new Expression();
expr.ExpressionStatement = "Pet.#name = :name";
expr.ExpressionAttributeNames["#name"] = "Name";
expr.ExpressionAttributeValues[":name"] = "Lilleper";
</code>```

Body:
I am trying to learn to use DynamoDB with C#
I have Partial updates, Put, Delete working.
Conditional update works (If the Attributes is part of root object).

I have the following model created.

Person with a lot of attributes.
The following works:

Expression expr = new Expression();
expr.ExpressionStatement = "Age = :age";
expr.ExpressionAttributeValues[":age"] = 26;

UpdateItemOperationConfig config = new UpdateItemOperationConfig
{
    ConditionalExpression = expr,
    ReturnValues = ReturnValues.AllNewAttributes
};

Document updatedPerson2 = personCatalog.UpdateItem(doc, config);

But what if my condition was on the Pet Name?

I have tried a couple of approaches with no luck eg:

expr.ExpressionStatement = "Pet.Name = :name";
expr.ExpressionAttributeValues[":name"] = "Lilleper";

Hope someone can help :) Or just nudge me in the right direction.

Body:
Try externalizing the Name sub-attribute name to ExpressionAttributeNames.

Expression expr = new Expression();
expr.ExpressionStatement = "Pet.#name = :name";
expr.ExpressionAttributeNames["#name"] = "Name";
expr.ExpressionAttributeValues[":name"] = "Lilleper";


问:
HTML thumbnail size issue
enter image description here

I have an issue with thumbnail size. In the picture, there should have been another picture in white area in the left-middle, but the space is skipped because an image above has a long title. Everytime a picture with a long title is showed up, the size becomes larger. Is there any way I can fix thumbnail size even though the title gets longer?

Here is my HTML code and CSS i don't write anything.

```<code><div class="panel-body">
  <div id="recipeResults" class="row">
    <!-- templates/BasicImages/imageTemplates.js -->
  </div>
</div>
</code>```

Here is actual code. Sorry :)

```<code><div class="col-sm-6 col-md-4">
  <div class="thumbnail">
    <div class="hovereffect">
      <img class="img-responsive center-block" src="{{json.url}}" alt="{{json.alt_name}}">
        <div class="overlay">
           <h3> {{json.hoverDescription}}</h3>
           <a class="info" href="#"><i class="fa fa-clock-o fa-fw" aria-hidden="true"></i>{{json.cookTime}}</a>
        </div>
    </div>
        <div class="caption">
      <p style="font-size: 1pt;"> </p>
      <h4>{{json.name}}</h4>
      <p>{{json.description}}</p>
      <p><button type="button" class="btn btn-default btn-sm" aria-label="Left Align">
        <span class="glyphicon glyphicon-star" aria-hidden="true"></span> Save
        </button></p>
    </div>
  </div>
</div>
</code>```

答:
Using Flex you can align children of different height vertically without leaving gaps.

```<code><div id="outer-wrap">
  <div class="child"></div>
  <div class="child"></div>
  <div class="child"></div>
  <div class="child"></div>
  <div class="child"></div>
</div>
</code>```

And the CSS

```<code>div#outer-wrap {
  display: -ms-flexbox;
  -ms-flex-direction: column;
  -ms-flex-wrap: wrap;
  display: flex;
  flex-direction: column;
  flex-wrap: wrap;
  height: 100 vw;
}
div#outer-wrap .child {
  width: 33.3%;
}
</code>```

Title: HTML thumbnail size issue

Body:
enter image description here

I have an issue with thumbnail size. In the picture, there should have been another picture in white area in the left-middle, but the space is skipped because an image above has a long title. Everytime a picture with a long title is showed up, the size becomes larger. Is there any way I can fix thumbnail size even though the title gets longer?

Here is my HTML code and CSS i don't write anything.

Here is actual code. Sorry :)

 {{json.hoverDescription}}

           {{json.cookTime}}

{{json.name}}

{{json.description}}

<button type="button" class="btn btn-default btn-sm" aria-label="Left Align">
         Save
        </button>

Body:
Using Flex you can align children of different height vertically without leaving gaps.

<div id="outer-wrap">
  <div class="child"></div>
  <div class="child"></div>
  <div class="child"></div>
  <div class="child"></div>
  <div class="child"></div>
</div>

And the CSS

div#outer-wrap {
  display: -ms-flexbox;
  -ms-flex-direction: column;
  -ms-flex-wrap: wrap;
  display: flex;
  flex-direction: column;
  flex-wrap: wrap;
  height: 100 vw;
}
div#outer-wrap .child {
  width: 33.3%;
}


问:
Codeigniter jQuery file upload not working
PHP Code:

```<code>$files = json_decode($this->input->post('Image'));
echo "```";
print_r($files);
echo "```";
</code>```

jQuery code:

```<code>var image = [];
for(var i = 1; i <= $("#removeimagefield").attr('data-id'); i++){
    image.push($("#imageupload"+i).val());
}
console.log(JSON.stringify(image));
</code>```

HTML code:

```<code><form role="form" enctype="multipart/form-data" accept-charset="utf-8" name="formname" id="formname"  method="post" action="">
    <input type="file" class="default" id="imageupload1">
</form>
</code>```

AJAX Function:

```<code>  addproperty = {Image: JSON.stringify(image)}
  $.ajax({
    method: "POST",
    url: formsubmission,
    data: addproperty,
    async : false,
    cache : false,
    contentType : false,
    processData : false,
    success: function(response){
      console.log(response);
    }
  });
</code>```

Console message:

```<code>["C:\\fakepath\\abhishek.jpg","C:\\fakepath\\krunal.jpg","C:\\fakepath\\nitin.jpg"]
</code>```

I am trying to uploading image file to Codeigniter Controller. but when I am printing value of $files. than it displaying empty array.

答:
Try this code and get your file in controller using simple $_FILES['img_file']['file_name']          </p>

```<code>   $(document).ready(function (e) {
                    var file_name = $('#id_file_input').prop('files')[0];
                    var form_data = new FormData();
                    form_data.append('img_file', file_data);
                    $('#vid_file').prop('disabled', true);
                    $.ajax({
                    url: '<?php echo base_url(); ?>Controller/function_name',
                        dataType: 'text',
                        cache: false,
                        contentType: false,
                        processData: false,
                        data: form_data,
                        type: 'post',
                          success: function (response) {

                        }
                    });
                    });
</code>```

Body:
PHP Code:

$files = json_decode($this->input->post('Image'));
echo "
";
print_r($files);
echo "
";

jQuery code:

var image = [];
for(var i = 1; i <= $("#removeimagefield").attr('data-id'); i++){
    image.push($("#imageupload"+i).val());
}
console.log(JSON.stringify(image));

HTML code:

<form role="form" enctype="multipart/form-data" accept-charset="utf-8" name="formname" id="formname"  method="post" action="">
    <input type="file" class="default" id="imageupload1">
</form>

AJAX Function:

  addproperty = {Image: JSON.stringify(image)}
  $.ajax({
    method: "POST",
    url: formsubmission,
    data: addproperty,
    async : false,
    cache : false,
    contentType : false,
    processData : false,
    success: function(response){
      console.log(response);
    }
  });

Console message:

["C:\\fakepath\\abhishek.jpg","C:\\fakepath\\krunal.jpg","C:\\fakepath\\nitin.jpg"]

I am trying to uploading image file to Codeigniter Controller. but when I am printing value of $files. than it displaying empty array.

Body:
Try this code and get your file in controller using simple $_FILES['img_file']['file_name']

   $(document).ready(function (e) {
                    var file_name = $('#id_file_input').prop('files')[0];
                    var form_data = new FormData();
                    form_data.append('img_file', file_data);
                    $('#vid_file').prop('disabled', true);
                    $.ajax({
                    url: '<?php echo base_url(); ?>Controller/function_name',
                        dataType: 'text',
                        cache: false,
                        contentType: false,
                        processData: false,
                        data: form_data,
                        type: 'post',
                          success: function (response) {

                        }
                    });
                    });


问:
mkdir doesn't do path expansion
So I have folder aa

```<code>$ mkdir aa
</code>```

and path expansion for ls command works like this:

```<code>$ ls -la a*
total 0
drwxr-xr-x 1 a a 0 Mar 29 08:41 ./
drwxr-xr-x 1 a a 0 Dec 31  1979 ../
$ ls -la a?
total 0
drwxr-xr-x 1 a a 0 Mar 29 08:41 ./
drwxr-xr-x 1 a a 0 Dec 31  1979 ../
</code>```

But "the same" for mkdir shows an error:

```<code>$ mkdir a*/bb
mkdir: cannot create directory 'a*/bb': No such file or directory
$ mkdir a?/bb
mkdir: cannot create directory 'a?/bb': No such file or directory
</code>```

Where can I read why this difference in behavior happens and is there simple trick to let mkdir be "smarter" for behavior like in ls?

答:
Try:</p>

```<code>mkdir -p a*/aa
mkdir -p a?/aa
</code>```

Title: mkdir doesn't do path expansion

Body:
So I have folder aa

$ mkdir aa

and path expansion for ls command works like this:

$ ls -la a*
total 0
drwxr-xr-x 1 a a 0 Mar 29 08:41 ./
drwxr-xr-x 1 a a 0 Dec 31  1979 ../
$ ls -la a?
total 0
drwxr-xr-x 1 a a 0 Mar 29 08:41 ./
drwxr-xr-x 1 a a 0 Dec 31  1979 ../

But "the same" for mkdir shows an error:

$ mkdir a*/bb
mkdir: cannot create directory 'a*/bb': No such file or directory
$ mkdir a?/bb
mkdir: cannot create directory 'a?/bb': No such file or directory

Where can I read why this difference in behavior happens and is there simple trick to let mkdir be "smarter" for behavior like in ls?

Body:
Try:

mkdir -p a*/aa
mkdir -p a?/aa


问:
Loading/Downloading image from URL on Swift
I'd like to load an image from a URL in my application, so I first tried with Objective-C and it worked, however, with Swift, I've a compilation error:

'imageWithData' is unavailable: use object construction 'UIImage(data:)'

My function:

```<code>@IBOutlet var imageView : UIImageView

override func viewDidLoad() {
    super.viewDidLoad()

    var url:NSURL = NSURL.URLWithString("http://myURL/ios8.png")
    var data:NSData = NSData.dataWithContentsOfURL(url, options: nil, error: nil)

    imageView.image = UIImage.imageWithData(data)// Error here
}
</code>```

In Objective-C:

```<code>- (void)viewDidLoad {
    [super viewDidLoad];

    NSURL *url = [NSURL URLWithString:(@"http://myURL/ios8.png")];
    NSData *data = [NSData dataWithContentsOfURL:url];

    _imageView.image = [UIImage imageWithData: data];
    _labelURL.text = @"http://www.quentinroussat.fr/assets/img/iOS%20icon's%20Style/ios8.png";
 }
</code>```

Can someone please explain me why the imageWithData: doesn't work with Swift, and how can I solve the problem.

答:
swift 3 with error handling

```<code>let url = URL(string: arr[indexPath.row] as! String)
if url != nil {
    DispatchQueue.global().async {
        let data = try? Data(contentsOf: url!) //make sure your image in this url does exist, otherwise unwrap in a if let check / try-catch
        DispatchQueue.main.async {
            if data != nil {
                cell.imgView.image = UIImage(data:data!)
            }else{
                cell.imgView.image = UIImage(named: "default.png")
            }
        }
    }
}
</code>```

With Extension

```<code>extension UIImageView {

    func setCustomImage(_ imgURLString: String?) {
        guard let imageURLString = imgURLString else {
            self.image = UIImage(named: "default.png")
            return
        }
        DispatchQueue.global().async { [weak self] in
            let data = try? Data(contentsOf: URL(string: imageURLString)!)
            DispatchQueue.main.async {
                self?.image = data != nil ? UIImage(data: data!) : UIImage(named: "default.png")
            }
        }
    }
}
</code>```

Extension Usage

```<code>myImageView. setCustomImage("url")
</code>```

With Cache support

```<code>let imageCache = NSCache<NSString, UIImage>()

extension UIImageView {

    func loadImageUsingCacheWithURLString(_ URLString: String, placeHolder: UIImage?) {

        self.image = nil
        if let cachedImage = imageCache.object(forKey: NSString(string: URLString)) {
            self.image = cachedImage
            return
        }

        if let url = URL(string: URLString) {
            URLSession.shared.dataTask(with: url, completionHandler: { (data, response, error) in

                //print("RESPONSE FROM API: \(response)")
                if error != nil {
                    print("ERROR LOADING IMAGES FROM URL: \(String(describing: error))")
                    DispatchQueue.main.async { [weak self] in
                        self?.image = placeHolder
                    }
                    return
                }
                DispatchQueue.main.async { [weak self] in
                    if let data = data {
                        if let downloadedImage = UIImage(data: data) {
                            imageCache.setObject(downloadedImage, forKey: NSString(string: URLString))
                            self?.image = downloadedImage
                        }
                    }
                }
            }).resume()
        }
    }
}
</code>```

Body:
I'd like to load an image from a URL in my application, so I first tried with Objective-C and it worked, however, with Swift, I've a compilation error:

'imageWithData' is unavailable: use object construction 'UIImage(data:)'

My function:

@IBOutlet var imageView : UIImageView

override func viewDidLoad() {
    super.viewDidLoad()

    var url:NSURL = NSURL.URLWithString("http://myURL/ios8.png")
    var data:NSData = NSData.dataWithContentsOfURL(url, options: nil, error: nil)

    imageView.image = UIImage.imageWithData(data)// Error here
}

In Objective-C:

- (void)viewDidLoad {
    [super viewDidLoad];

    NSURL *url = [NSURL URLWithString:(@"http://myURL/ios8.png")];
    NSData *data = [NSData dataWithContentsOfURL:url];

    _imageView.image = [UIImage imageWithData: data];
    _labelURL.text = @"http://www.quentinroussat.fr/assets/img/iOS%20icon's%20Style/ios8.png";
 }

Can someone please explain me why the imageWithData: doesn't work with Swift, and how can I solve the problem.

Body:
swift 3 with error handling

let url = URL(string: arr[indexPath.row] as! String)
if url != nil {
    DispatchQueue.global().async {
        let data = try? Data(contentsOf: url!) //make sure your image in this url does exist, otherwise unwrap in a if let check / try-catch
        DispatchQueue.main.async {
            if data != nil {
                cell.imgView.image = UIImage(data:data!)
            }else{
                cell.imgView.image = UIImage(named: "default.png")
            }
        }
    }
}

With Extension

extension UIImageView {

    func setCustomImage(_ imgURLString: String?) {
        guard let imageURLString = imgURLString else {
            self.image = UIImage(named: "default.png")
            return
        }
        DispatchQueue.global().async { [weak self] in
            let data = try? Data(contentsOf: URL(string: imageURLString)!)
            DispatchQueue.main.async {
                self?.image = data != nil ? UIImage(data: data!) : UIImage(named: "default.png")
            }
        }
    }
}

Extension Usage

myImageView. setCustomImage("url")

With Cache support

let imageCache = NSCache<NSString, UIImage>()

extension UIImageView {

    func loadImageUsingCacheWithURLString(_ URLString: String, placeHolder: UIImage?) {

        self.image = nil
        if let cachedImage = imageCache.object(forKey: NSString(string: URLString)) {
            self.image = cachedImage
            return
        }

        if let url = URL(string: URLString) {
            URLSession.shared.dataTask(with: url, completionHandler: { (data, response, error) in

                //print("RESPONSE FROM API: \(response)")
                if error != nil {
                    print("ERROR LOADING IMAGES FROM URL: \(String(describing: error))")
                    DispatchQueue.main.async { [weak self] in
                        self?.image = placeHolder
                    }
                    return
                }
                DispatchQueue.main.async { [weak self] in
                    if let data = data {
                        if let downloadedImage = UIImage(data: data) {
                            imageCache.setObject(downloadedImage, forKey: NSString(string: URLString))
                            self?.image = downloadedImage
                        }
                    }
                }
            }).resume()
        }
    }
}

ContentLicense: CC BY-SA 4.0


答:
It looks like the values are already in a tuple, so you don't need to split the string. Is

```<code>val data = joinDataRdd.map(x=>(x._1,x._2._1._4))
</code>```

what you are looking for?

Body:
Given is data by joining two tables.

joinDataRdd.take(5).foreach(println)
(41234,((102921,249,2,109.94,54.97),(2014-04-04 00:00:00.0,3182,PENDING_PAYMENT)))
(65722,((164249,365,2,119.98,59.99),(2014-05-23 00:00:00.0,4077,COMPLETE)))
(65722,((164250,730,5,400.0,80.0),(2014-05-23 00:00:00.0,4077,COMPLETE)))
(65722,((164251,1004,1,399.98,399.98),(2014-05-23 00:00:00.0,4077,COMPLETE)))
(65722,((164252,627,5,199.95,39.99),(2014-05-23 00:00:00.0,4077,COMPLETE)))

When I am trying to get following
 val data = joinDataRdd.map(x=>(x._1,x._2._1.split(",")(3)))

It's is throwing an error :
value split is not a member of (String, String, String, String, String)

Body:
It looks like the values are already in a tuple, so you don't need to split the string. Is

val data = joinDataRdd.map(x=>(x._1,x._2._1._4))

what you are looking for?


问:
sending html and inline images using php Mail/mime
I am using php/Mail_mime to send styled html content using the code below.

```<code>$headers = array ('From' => $sender,
          'To' => implode(',',$to),
          'Subject' => $subject,
          'Reply-To'=>'myemail@mydomain.com',
          'MIME-Version'=>'1.0',
          'Content-Type'=>'text/html'
    );
    /*end header*/

    $this->mime = new Mail_mime();
    $tt=$this->mime;
    $tt->addBcc(implode(',',$bcc));
    $tt->addCc(implode(',',$cc));
    $tt->setTXTBody($text);
    $tt->setHTMLBody($body);
    $tt->addHTMLImage('../images/delete.gif');
//  $tt->addAttachment('../images/delete.gif','image/gif');
    $mime_body = $tt->get();
    $mime_hdrs = $tt->headers($headers);

    $smtp = Mail::factory('smtp',
    array ('host' => $this->host,
            'port' => $this->port,
            'auth' => false,
            'username' => $this->username,
            'password' => $this->password));
    $recipients=array_merge($to,$cc,$bcc);
    $mail = $smtp->send($recipients, $mime_hdrs, $mime_body);
</code>```

This is all a class code, so initialization is done on the constructor, which is not posted here.

Now my question is, while the above code works fine, i didnt see the correct style on the email sent.

for example if i have this as a message body of my email:

```<code><div style="background-color:silver;">
</code>```

MY Header

On my email, I can only see the My Header. The background didnt showup as silver.

What did i miss on my code above. Any help ?

答:
Its quite possible that the email provider you are using doesn't allow HTML code in the emails, or it restricts CSS styling in the allowed HTML code. Which email provider are you using?

You might want to test this by sending an email to a gmail.com email address, which does allow html code, and see if it makes any difference.

Another thing to test would be to do a view source, or inspect element if you're using google chrome or firebug in firefox, and see if the html code is being placed where it should be.

ContentLicense: CC BY-SA 2.5

Body:
I am using php/Mail_mime to send styled html content using the code below.

$headers = array ('From' => $sender,
          'To' => implode(',',$to),
          'Subject' => $subject,
          'Reply-To'=>'myemail@mydomain.com',
          'MIME-Version'=>'1.0',
          'Content-Type'=>'text/html'
    );
    /*end header*/

    $this->mime = new Mail_mime();
    $tt=$this->mime;
    $tt->addBcc(implode(',',$bcc));
    $tt->addCc(implode(',',$cc));
    $tt->setTXTBody($text);
    $tt->setHTMLBody($body);
    $tt->addHTMLImage('../images/delete.gif');
//  $tt->addAttachment('../images/delete.gif','image/gif');
    $mime_body = $tt->get();
    $mime_hdrs = $tt->headers($headers);

    $smtp = Mail::factory('smtp',
    array ('host' => $this->host,
            'port' => $this->port,
            'auth' => false,
            'username' => $this->username,
            'password' => $this->password));
    $recipients=array_merge($to,$cc,$bcc);
    $mail = $smtp->send($recipients, $mime_hdrs, $mime_body);

This is all a class code, so initialization is done on the constructor, which is not posted here.

Now my question is, while the above code works fine, i didnt see the correct style on the email sent.

for example if i have this as a message body of my email:

MY Header

On my email, I can only see the My Header. The background didnt showup as silver.

What did i miss on my code above. Any help ?


问:
Select2 autocomplete by option value
I have tried to integrate tag/autocomplete for my site. Its working through option text. I am almost close to result but still hanging.

Now when you try to select option text there will appear related text. But now i want to appear kathmandu or related option text searching via option value also.

Ex:
when we will search value a001 kathmandu will appear and select same as a002 it will appear pokhara

$("select").select2({
  tags: "true",
  placeholder: "Select an option",
  allowClear: true,
  width: '100%',
  createTag: function (params) {
    var term = $.trim(params.term);

    if (term === '') {
      return null;
    }

    return {
     id: term,
     text: term,
     value: true // add additional parameters
    }
  }
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.select2-container {
  max-width: 400px;
}</code>```

<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/css/select2.min.css" rel="stylesheet"/>
<select class="custom-select"  multiple="multiple">
  <option value="a001">Kathmandu</option>
  <option value="a002">Pokhara</option>
  <option value="a003">Lalitpur</option>
</select>```

I think i am close after searching via value and click on it it will show relevant option with id. But i want only option text like pokhara kathmandu not an ID on select area.

答:
To remove the double-ups of the Id and the Text showing when entering just the Id check whether the entered term matches an existing Id, and if it does simply return the Text of the matching option:

options = [];

// create an array of select options for a lookup
$('.custom-select option').each(function(idx) {
    options.push({id: $(this).val(), text: $(this).text()});
});

$("select").select2({
  tags: "true",
  placeholder: "Select an option",
  allowClear: true,
  width: '100%',
  createTag: function (params) {
    var term = $.trim(params.term);

    if (term === '') {
      return null;
    }

    // check whether the term matches an id
    var search = $.grep(options, function( n, i ) {
      return ( n.id === term || n.text === term); // check against id and text
    });

    // if a match is found replace the term with the options' text
    if (search.length)
      term = search[0].text;
    else
      return null; // didn't match id or text value so don't add it to selection

    return {
     id: term,
     text: term,
     value: true // add additional parameters
    }
  }
});

$('select').on('select2:select', function (evt) {
  //console.log(evt);
  //return false;
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.select2-container {
  max-width: 400px;
}</code>```

<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/css/select2.min.css" rel="stylesheet"/>
<select class="custom-select"  multiple="multiple">
  <option value="a001">Kathmandu</option>
  <option value="a002">Pokhara</option>
  <option value="a003">Lalitpur</option>
</select>```

Title: Select2 autocomplete by option value

Body:
I have tried to integrate tag/autocomplete for my site. Its working through option text. I am almost close to result but still hanging.

Now when you try to select option text there will appear related text. But now i want to appear kathmandu or related option text searching via option value also.

Ex:
when we will search value a001 kathmandu will appear and select same as a002 it will appear pokhara

$("select").select2({
  tags: "true",
  placeholder: "Select an option",
  allowClear: true,
  width: '100%',
  createTag: function (params) {
    var term = $.trim(params.term);

    if (term === '') {
      return null;
    }

    return {
     id: term,
     text: term,
     value: true // add additional parameters
    }
  }
});

.select2-container {
  max-width: 400px;
}

<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/css/select2.min.css" rel="stylesheet"/>
<select class="custom-select"  multiple="multiple">
  <option value="a001">Kathmandu</option>
  <option value="a002">Pokhara</option>
  <option value="a003">Lalitpur</option>
</select>

I think i am close after searching via value and click on it it will show relevant option with id. But i want only option text like pokhara kathmandu not an ID on select area.

Body:
To remove the double-ups of the Id and the Text showing when entering just the Id check whether the entered term matches an existing Id, and if it does simply return the Text of the matching option:

options = [];

// create an array of select options for a lookup
$('.custom-select option').each(function(idx) {
    options.push({id: $(this).val(), text: $(this).text()});
});

$("select").select2({
  tags: "true",
  placeholder: "Select an option",
  allowClear: true,
  width: '100%',
  createTag: function (params) {
    var term = $.trim(params.term);

    if (term === '') {
      return null;
    }

    // check whether the term matches an id
    var search = $.grep(options, function( n, i ) {
      return ( n.id === term || n.text === term); // check against id and text
    });

    // if a match is found replace the term with the options' text
    if (search.length)
      term = search[0].text;
    else
      return null; // didn't match id or text value so don't add it to selection

    return {
     id: term,
     text: term,
     value: true // add additional parameters
    }
  }
});

$('select').on('select2:select', function (evt) {
  //console.log(evt);
  //return false;
});

.select2-container {
  max-width: 400px;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/js/select2.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/css/select2.min.css" rel="stylesheet"/>
<select class="custom-select"  multiple="multiple">
  <option value="a001">Kathmandu</option>
  <option value="a002">Pokhara</option>
  <option value="a003">Lalitpur</option>
</select>


问:
How to get previous EndTime to calculate in new rows?
I have below formatted table data values. I would like to get last operation completed status start time and end time duration need to show in next ready operation.

E.g: Original table format:

```<code>     Sno    Operation      Status               StartTime               EndTime
    ------ -----------  -----------------     ---------------------  ---------------
    1        OP10       Complete              2017-03-01 07:00:00    2017-03-01 07:10:00
    1        OP20       Complete              2017-03-01 07:10:00    2017-03-01 07:30:00
    1        OP30       Ready                      Null                    Null
    2        OP10       Complete              2017-03-01 08:00:00    2017-03-01 08:10:00
    2        OP20       Ready                      Null                    Null
    3        OP10       Complete              2017-03-01 09:00:00    2017-03-01 09:10:00
    3        OP20       Complete              2017-03-01 10:00:00    2017-03-01 10:10:00
    3        OP30       Ready                 2017-03-01 10:00:00    2017-03-01 10:10:00
</code>```

I need output like this:

```<code>  Sno     Operation     Status          TotalDurationCountInMins
------  ------------  ------------  ---------------------------------
    1        OP30       Ready                      20
    2        OP20       Ready                      10
    3        OP30       Ready                      10
</code>```

答:
Use a subquery to get the last operation complete times.

Note: If your Operation column contains data that can't be sorted (like 'start', 'middle', 'end') this query will produce wrong results.

Create and populate sample table (Please save us this step in your future questions)

```<code>DECLARE @T AS TABLE
(
    Sno int,
    Operation char(5),
    [Status] varchar(8),
    StartTime datetime,
    EndTime datetime
)

INSERT INTO @T VALUES
(1, 'OP10', 'Complete', '2017-03-01 07:00:00', '2017-03-01 07:10:00'),
(1, 'OP20', 'Complete', '2017-03-01 07:10:00', '2017-03-01 07:30:00'),
(1, 'OP30', 'Ready', Null, Null),
(2, 'OP10', 'Complete', '2017-03-01 08:00:00', '2017-03-01 08:10:00'),
(2, 'OP20', 'Ready', Null, Null),
(3, 'OP10', 'Complete', '2017-03-01 09:00:00', '2017-03-01 09:10:00'),
(3, 'OP20', 'Complete', '2017-03-01 10:00:00', '2017-03-01 10:10:00'),
(3, 'OP30', 'Ready', '2017-03-01 10:00:00', '2017-03-01 10:10:00')
</code>```

The Query:

```<code>SELECT  Sno,
        Operation,
        [Status],
        (SELECT TOP 1 DATEDIFF(MINUTE, StartTime, EndTime)
         FROM @T t2
         WHERE t2.Sno = t1.Sno
         AND t2.Operation < t1.Operation
         AND t2.[Status] = 'Complete'
         ORDER BY StartTime DESC
         ) AS TotalDurationCountInMins
FROM @T t1
WHERE [Status] = 'Ready'
</code>```

Results:

```<code>Sno     Operation   Status  TotalDurationCountInMins
1       OP30        Ready   20
2       OP20        Ready   10
3       OP30        Ready   10
</code>```

See a live demo on rextester

Body:
I have below formatted table data values. I would like to get last operation completed status start time and end time duration need to show in next ready operation.

E.g: Original table format:

     Sno    Operation      Status               StartTime               EndTime
    ------ -----------  -----------------     ---------------------  ---------------
    1        OP10       Complete              2017-03-01 07:00:00    2017-03-01 07:10:00
    1        OP20       Complete              2017-03-01 07:10:00    2017-03-01 07:30:00
    1        OP30       Ready                      Null                    Null
    2        OP10       Complete              2017-03-01 08:00:00    2017-03-01 08:10:00
    2        OP20       Ready                      Null                    Null
    3        OP10       Complete              2017-03-01 09:00:00    2017-03-01 09:10:00
    3        OP20       Complete              2017-03-01 10:00:00    2017-03-01 10:10:00
    3        OP30       Ready                 2017-03-01 10:00:00    2017-03-01 10:10:00

I need output like this:

  Sno     Operation     Status          TotalDurationCountInMins
------  ------------  ------------  ---------------------------------
    1        OP30       Ready                      20
    2        OP20       Ready                      10
    3        OP30       Ready                      10

Body:
Use a subquery to get the last operation complete times.

Note: If your Operation column contains data that can't be sorted (like 'start', 'middle', 'end') this query will produce wrong results.

Create and populate sample table (Please save us this step in your future questions)

DECLARE @T AS TABLE
(
    Sno int,
    Operation char(5),
    [Status] varchar(8),
    StartTime datetime,
    EndTime datetime
)

INSERT INTO @T VALUES
(1, 'OP10', 'Complete', '2017-03-01 07:00:00', '2017-03-01 07:10:00'),
(1, 'OP20', 'Complete', '2017-03-01 07:10:00', '2017-03-01 07:30:00'),
(1, 'OP30', 'Ready', Null, Null),
(2, 'OP10', 'Complete', '2017-03-01 08:00:00', '2017-03-01 08:10:00'),
(2, 'OP20', 'Ready', Null, Null),
(3, 'OP10', 'Complete', '2017-03-01 09:00:00', '2017-03-01 09:10:00'),
(3, 'OP20', 'Complete', '2017-03-01 10:00:00', '2017-03-01 10:10:00'),
(3, 'OP30', 'Ready', '2017-03-01 10:00:00', '2017-03-01 10:10:00')

The Query:

SELECT  Sno,
        Operation,
        [Status],
        (SELECT TOP 1 DATEDIFF(MINUTE, StartTime, EndTime)
         FROM @T t2
         WHERE t2.Sno = t1.Sno
         AND t2.Operation < t1.Operation
         AND t2.[Status] = 'Complete'
         ORDER BY StartTime DESC
         ) AS TotalDurationCountInMins
FROM @T t1
WHERE [Status] = 'Ready'

Results:

Sno     Operation   Status  TotalDurationCountInMins
1       OP30        Ready   20
2       OP20        Ready   10
3       OP30        Ready   10

See a live demo on rextester


问:
Image stretched when I capture image and save to SD card in Android
```<code>BitmapFactory.Options opts = new BitmapFactory.Options();
Bitmap bitmap = BitmapFactory.decodeByteArray(data, 0, data.length, opts);
bitmap = Bitmap.createScaledBitmap(bitmap, 150, 50, false);
int width = bitmap.getWidth();
int height = bitmap.getHeight();
int newWidth = 150;
int newHeight = 50;

// calculate the scale - in this case = 0.4f
float scaleWidth = ((float) newWidth) / width;
float scaleHeight = ((float) newHeight) / height;

// createa matrix for the manipulation
Matrix matrix = new Matrix();
// resize the bit map
matrix.postScale(scaleWidth, scaleHeight);
// rotate the Bitmap
matrix.postRotate(-90);
Bitmap resizedBitmap = Bitmap.createBitmap(bitmap, 0, 0,
        width, height, matrix, true);
//      HomePage.image.setImageBitmap(resizedBitmap);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
resizedBitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] byteArray = stream.toByteArray();

Intent in1 = new Intent(CameraView.this, ImageDisplay.class);
in1.putExtra("picture",byteArray);
startActivity(in1);
</code>```

This is my code. I am unable to set image because image becomes stretched. It's not coming clear image full screen. Where am I doing wrong?

My image come like this we have fix it it should not stretched.

答:
It can be due to 'createScaledBitmap' as may be the image size is small and when you try to resize it it gets streched

You can use this:

```<code>   public Bitmap compressImage(String imageUri) {

        String filePath = getRealPathFromURI(imageUri);
        Bitmap scaledBitmap = null;
        BitmapFactory.Options options = new BitmapFactory.Options();

//      by setting this field as true, the actual bitmap pixels are not loaded in the memory. Just the bounds are loaded. If
//      you try the use the bitmap here, you will get null.
        options.inJustDecodeBounds = true;
        Bitmap bmp = BitmapFactory.decodeFile(filePath, options);

        int actualHeight = options.outHeight;
        int actualWidth = options.outWidth;

//      max Height and width values of the compressed image is taken as 816x612

        float maxHeight = 816.0f;
        float maxWidth = 612.0f;
        float imgRatio = actualWidth / actualHeight;
        float maxRatio = maxWidth / maxHeight;

//      width and height values are set maintaining the aspect ratio of the image

        if (actualHeight > maxHeight || actualWidth > maxWidth) {
            if (imgRatio < maxRatio) {
                imgRatio = maxHeight / actualHeight;
                actualWidth = (int) (imgRatio * actualWidth);
                actualHeight = (int) maxHeight;
            } else if (imgRatio > maxRatio) {
                imgRatio = maxWidth / actualWidth;
                actualHeight = (int) (imgRatio * actualHeight);
                actualWidth = (int) maxWidth;
            } else {
                actualHeight = (int) maxHeight;
                actualWidth = (int) maxWidth;

            }
        }

//      setting inSampleSize value allows to load a scaled down version of the original image

        options.inSampleSize = calculateInSampleSize(options, actualWidth, actualHeight);

//      inJustDecodeBounds set to false to load the actual bitmap
        options.inJustDecodeBounds = false;

//      this options allow android to claim the bitmap memory if it runs low on memory
        options.inPurgeable = true;
        options.inInputShareable = true;
        options.inTempStorage = new byte[16 * 1024];

        try {
//          load the bitmap from its path
            bmp = BitmapFactory.decodeFile(filePath, options);
        } catch (OutOfMemoryError exception) {
            exception.printStackTrace();

        }
        try {
            scaledBitmap = Bitmap.createBitmap(actualWidth, actualHeight, Bitmap.Config.ARGB_8888);
        } catch (OutOfMemoryError exception) {
            exception.printStackTrace();
        }

        float ratioX = actualWidth / (float) options.outWidth;
        float ratioY = actualHeight / (float) options.outHeight;
        float middleX = actualWidth / 2.0f;
        float middleY = actualHeight / 2.0f;

        Matrix scaleMatrix = new Matrix();
        scaleMatrix.setScale(ratioX, ratioY, middleX, middleY);

        Canvas canvas = new Canvas(scaledBitmap);
        canvas.setMatrix(scaleMatrix);
        canvas.drawBitmap(bmp, middleX - bmp.getWidth() / 2, middleY - bmp.getHeight() / 2, new Paint(Paint.FILTER_BITMAP_FLAG));

//      check the rotation of the image and display it properly
        ExifInterface exif;
        try {
            exif = new ExifInterface(filePath);

            int orientation = exif.getAttributeInt(
                    ExifInterface.TAG_ORIENTATION, 0);
            Log.d("EXIF", "Exif: " + orientation);
            Matrix matrix = new Matrix();
            if (orientation == 6) {
                matrix.postRotate(90);
                Log.d("EXIF", "Exif: " + orientation);
            } else if (orientation == 3) {
                matrix.postRotate(180);
                Log.d("EXIF", "Exif: " + orientation);
            } else if (orientation == 8) {
                matrix.postRotate(270);
                Log.d("EXIF", "Exif: " + orientation);
            }
            scaledBitmap = Bitmap.createBitmap(scaledBitmap, 0, 0,
                    scaledBitmap.getWidth(), scaledBitmap.getHeight(), matrix,
                    true);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return scaledBitmap;

    }
</code>```

Body:
BitmapFactory.Options opts = new BitmapFactory.Options();
Bitmap bitmap = BitmapFactory.decodeByteArray(data, 0, data.length, opts);
bitmap = Bitmap.createScaledBitmap(bitmap, 150, 50, false);
int width = bitmap.getWidth();
int height = bitmap.getHeight();
int newWidth = 150;
int newHeight = 50;

// calculate the scale - in this case = 0.4f
float scaleWidth = ((float) newWidth) / width;
float scaleHeight = ((float) newHeight) / height;

// createa matrix for the manipulation
Matrix matrix = new Matrix();
// resize the bit map
matrix.postScale(scaleWidth, scaleHeight);
// rotate the Bitmap
matrix.postRotate(-90);
Bitmap resizedBitmap = Bitmap.createBitmap(bitmap, 0, 0,
        width, height, matrix, true);
//      HomePage.image.setImageBitmap(resizedBitmap);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
resizedBitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] byteArray = stream.toByteArray();

Intent in1 = new Intent(CameraView.this, ImageDisplay.class);
in1.putExtra("picture",byteArray);
startActivity(in1);

This is my code. I am unable to set image because image becomes stretched. It's not coming clear image full screen. Where am I doing wrong?

My image come like this we have fix it it should not stretched.

Body:
It can be due to 'createScaledBitmap' as may be the image size is small and when you try to resize it it gets streched

You can use this:

   public Bitmap compressImage(String imageUri) {

        String filePath = getRealPathFromURI(imageUri);
        Bitmap scaledBitmap = null;
        BitmapFactory.Options options = new BitmapFactory.Options();

//      by setting this field as true, the actual bitmap pixels are not loaded in the memory. Just the bounds are loaded. If
//      you try the use the bitmap here, you will get null.
        options.inJustDecodeBounds = true;
        Bitmap bmp = BitmapFactory.decodeFile(filePath, options);

        int actualHeight = options.outHeight;
        int actualWidth = options.outWidth;

//      max Height and width values of the compressed image is taken as 816x612

        float maxHeight = 816.0f;
        float maxWidth = 612.0f;
        float imgRatio = actualWidth / actualHeight;
        float maxRatio = maxWidth / maxHeight;

//      width and height values are set maintaining the aspect ratio of the image

        if (actualHeight > maxHeight || actualWidth > maxWidth) {
            if (imgRatio < maxRatio) {
                imgRatio = maxHeight / actualHeight;
                actualWidth = (int) (imgRatio * actualWidth);
                actualHeight = (int) maxHeight;
            } else if (imgRatio > maxRatio) {
                imgRatio = maxWidth / actualWidth;
                actualHeight = (int) (imgRatio * actualHeight);
                actualWidth = (int) maxWidth;
            } else {
                actualHeight = (int) maxHeight;
                actualWidth = (int) maxWidth;

            }
        }

//      setting inSampleSize value allows to load a scaled down version of the original image

        options.inSampleSize = calculateInSampleSize(options, actualWidth, actualHeight);

//      inJustDecodeBounds set to false to load the actual bitmap
        options.inJustDecodeBounds = false;

//      this options allow android to claim the bitmap memory if it runs low on memory
        options.inPurgeable = true;
        options.inInputShareable = true;
        options.inTempStorage = new byte[16 * 1024];

        try {
//          load the bitmap from its path
            bmp = BitmapFactory.decodeFile(filePath, options);
        } catch (OutOfMemoryError exception) {
            exception.printStackTrace();

        }
        try {
            scaledBitmap = Bitmap.createBitmap(actualWidth, actualHeight, Bitmap.Config.ARGB_8888);
        } catch (OutOfMemoryError exception) {
            exception.printStackTrace();
        }

        float ratioX = actualWidth / (float) options.outWidth;
        float ratioY = actualHeight / (float) options.outHeight;
        float middleX = actualWidth / 2.0f;
        float middleY = actualHeight / 2.0f;

        Matrix scaleMatrix = new Matrix();
        scaleMatrix.setScale(ratioX, ratioY, middleX, middleY);

        Canvas canvas = new Canvas(scaledBitmap);
        canvas.setMatrix(scaleMatrix);
        canvas.drawBitmap(bmp, middleX - bmp.getWidth() / 2, middleY - bmp.getHeight() / 2, new Paint(Paint.FILTER_BITMAP_FLAG));

//      check the rotation of the image and display it properly
        ExifInterface exif;
        try {
            exif = new ExifInterface(filePath);

            int orientation = exif.getAttributeInt(
                    ExifInterface.TAG_ORIENTATION, 0);
            Log.d("EXIF", "Exif: " + orientation);
            Matrix matrix = new Matrix();
            if (orientation == 6) {
                matrix.postRotate(90);
                Log.d("EXIF", "Exif: " + orientation);
            } else if (orientation == 3) {
                matrix.postRotate(180);
                Log.d("EXIF", "Exif: " + orientation);
            } else if (orientation == 8) {
                matrix.postRotate(270);
                Log.d("EXIF", "Exif: " + orientation);
            }
            scaledBitmap = Bitmap.createBitmap(scaledBitmap, 0, 0,
                    scaledBitmap.getWidth(), scaledBitmap.getHeight(), matrix,
                    true);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return scaledBitmap;

    }


问:
android notify a textview to be updated from the server side
I have a textView, i need to display in this text a message returned by the web service, my problem is every some time this message can be changed , i need to know whether it is changed ..so the target is to create a notifier or something that tell the android app to change the displayed message in textview when it is changed.

how to do this from server and android sides??

答:
There are some ways to do this. I think first and best way, when you want to change text, you may send notification application then it fire text change webservice.

Another solution is swipe refresh. This is generally using in applications and simple way.


问:
Filtering out noise from gpx data
I have a Pandas dataframe with column speed in which I have occasional noise (data are from a Garmin and represent data captured during a run).

I am trying to find a way to average over adjacent points, but when I hit something like this

```<code>9.112273445
164.5779550738
84.4553498412
4.231089359
4.3740439706
</code>```

I get caught in an infinite loop.

My algorithm is rather naive:

```<code># Get list of indices in which value is great than 6:
idx = z[(z['speed']>=6)].index
while list(idx) != []:
    for i in idx:
        # check if out of bounds
        if i + 1 >= len(z):
            z.iloc[i, z.columns.get_indexer(['speed'])] = (z['speed'].ix[i-2] + z['speed'].ix[i-1])/2
        elif i - 1 < 0:
            z.iloc[i, z.columns.get_indexer(['speed'])] = (z['speed'].ix[i+1] + z['speed'].ix[i+2])/2
        else:
            z.iloc[i, z.columns.get_indexer(['speed'])] = (z['speed'].ix[i-1] + z['speed'].ix[i+1])/2
    idx = z[(z['speed']>=6)].index
</code>```

The problem, of course, is when I have two adjacent values that are very large, this gets stuck in an infinite loop.

I am applying this filter (using a Hanning window) to eliminate random noise: SciPy Cookbook SignalSmooth, but it is not dealing with these large spikes in the data.

Short of discarding them, or setting them to a constant value, is there any other simple method of dealing with them?

EDIT

The values I am testing this over are:

```<code>0           NaN
1      3.508394
2      5.097879
3      7.743824
4      9.138245
5     13.315918
6     12.836310
7     12.001393
8     15.815223
9      0.000000
10    16.622944
11     9.061864
12     2.089729
13     2.710874
Name: speed, dtype: float64
</code>```

答:
If you want to "bridge" values greater than six you can do that like so:</p>

```<code>import numpy as np

# locate outliers and adjacent values
outliers = np.r_[False, (~np.isfinite(data)) | (data > 6), False]
if np.any(outliers):
    boundaries = np.where(outliers[:-1] != outliers[1:])[0]
    lb = boundaries[::2]
    rb = boundaries[1::2]
    # special case if leftmost and/or rightmost values are outliers
    lv = data[lb-1]
    if lb[0] == 0:
        lv[0] = data[rb[0]]
    rv = data[rb % len(data)]
    if rb[-1] == len(data):
        rv[-1] = data[lb[-1]-1]
    # create fill values; use a bit of trickery to keep it vectorised
    lengths = rb-lb
    fv = np.repeat((rv-lv)/(lengths+1), lengths)
    sw = np.cumsum(lengths[:-1])
    fv[sw] += fv[sw-1] - rv[:-1] + lv[1:]
    fv[0] += lv[0]
    fv = np.cumsum(fv)
    # place them
    out = data.copy()
    out[outliers[1:-1]] = fv
else:
    out = data.copy()
</code>```

Title: Filtering out noise from gpx data

Body:
I have a Pandas dataframe with column speed in which I have occasional noise (data are from a Garmin and represent data captured during a run).

I am trying to find a way to average over adjacent points, but when I hit something like this

9.112273445
164.5779550738
84.4553498412
4.231089359
4.3740439706

I get caught in an infinite loop.

My algorithm is rather naive:

# Get list of indices in which value is great than 6:
idx = z[(z['speed']>=6)].index
while list(idx) != []:
    for i in idx:
        # check if out of bounds
        if i + 1 >= len(z):
            z.iloc[i, z.columns.get_indexer(['speed'])] = (z['speed'].ix[i-2] + z['speed'].ix[i-1])/2
        elif i - 1 < 0:
            z.iloc[i, z.columns.get_indexer(['speed'])] = (z['speed'].ix[i+1] + z['speed'].ix[i+2])/2
        else:
            z.iloc[i, z.columns.get_indexer(['speed'])] = (z['speed'].ix[i-1] + z['speed'].ix[i+1])/2
    idx = z[(z['speed']>=6)].index

The problem, of course, is when I have two adjacent values that are very large, this gets stuck in an infinite loop.

I am applying this filter (using a Hanning window) to eliminate random noise: SciPy Cookbook SignalSmooth, but it is not dealing with these large spikes in the data.

Short of discarding them, or setting them to a constant value, is there any other simple method of dealing with them?

EDIT

The values I am testing this over are:

0           NaN
1      3.508394
2      5.097879
3      7.743824
4      9.138245
5     13.315918
6     12.836310
7     12.001393
8     15.815223
9      0.000000
10    16.622944
11     9.061864
12     2.089729
13     2.710874
Name: speed, dtype: float64

Body:
If you want to "bridge" values greater than six you can do that like so:

import numpy as np

# locate outliers and adjacent values
outliers = np.r_[False, (~np.isfinite(data)) | (data > 6), False]
if np.any(outliers):
    boundaries = np.where(outliers[:-1] != outliers[1:])[0]
    lb = boundaries[::2]
    rb = boundaries[1::2]
    # special case if leftmost and/or rightmost values are outliers
    lv = data[lb-1]
    if lb[0] == 0:
        lv[0] = data[rb[0]]
    rv = data[rb % len(data)]
    if rb[-1] == len(data):
        rv[-1] = data[lb[-1]-1]
    # create fill values; use a bit of trickery to keep it vectorised
    lengths = rb-lb
    fv = np.repeat((rv-lv)/(lengths+1), lengths)
    sw = np.cumsum(lengths[:-1])
    fv[sw] += fv[sw-1] - rv[:-1] + lv[1:]
    fv[0] += lv[0]
    fv = np.cumsum(fv)
    # place them
    out = data.copy()
    out[outliers[1:-1]] = fv
else:
    out = data.copy()


问:
Using getSimpleName() vs getName() for acquiring logger
I've seen code that uses log4j, which acquires logger for a given Logger using

```<code>static public Logger getLogger(String name)
</code>```

and

```<code>static public Logger getLogger(Class clazz)
</code>```

with the former api passed explicitly with getSimpleName(), while the latter uses getName() on the passed Class. Is there a difference between these two? Would it affect if I configure various packages to log at different level in log4j.properties file?

答: You might get confused if you have many classes with the same simpleName in different packages.  Having many loggers with the same name should not be a problem otherwise - just could be confusing.

Body:
I've seen code that uses log4j, which acquires logger for a given Logger using

static public Logger getLogger(String name)

and

static public Logger getLogger(Class clazz)

with the former api passed explicitly with getSimpleName(), while the latter uses getName() on the passed Class. Is there a difference between these two? Would it affect if I configure various packages to log at different level in log4j.properties file?


问:
using ipdb to debug python code in one cell (jupyter or Ipython)
I'm using jupyter (or Ipython) notebook with firefox, and want to debug some python code in the cell. I am using 'import ipdb; ipdb.set_trace()' as kind of breakpoint, for example my cell has the following code:

```<code>a=4
import ipdb; ipdb.set_trace()
b=5
print a
print b
</code>```

which after execution with Shift+Enter gives me this error:

```<code>--------------------------------------------------------------------------
MultipleInstanceError                     Traceback (most recent call last)
<ipython-input-1-f2b356251c56> in <module>()
      1 a=4
----> 2 import ipdb; ipdb.set_trace()
      3 b=5
      4 print a
      5 print b

/home/nnn/anaconda/lib/python2.7/site-packages/ipdb/__init__.py in <module>()
     14 # You should have received a copy of the GNU General Public License along with this program. If not, see http://www.gnu.org/licenses/.
     15
---> 16 from ipdb.__main__ import set_trace, post_mortem, pm, run, runcall, runeval, launch_ipdb_on_exception
     17
     18 pm                       # please pyflakes

/home/nnn/anaconda/lib/python2.7/site-packages/ipdb/__main__.py in <module>()
     71         # the instance method will create a new one without loading the config.
     72         # i.e: if we are in an embed instance we do not want to load the config.
---> 73         ipapp = TerminalIPythonApp.instance()
     74         shell = get_ipython()
     75         def_colors = shell.colors

/home/nnn/anaconda/lib/python2.7/site-packages/traitlets/config/configurable.pyc in instance(cls, *args, **kwargs)
    413             raise MultipleInstanceError(
    414                 'Multiple incompatible subclass instances of '
--> 415                 '%s are being created.' % cls.__name__
    416             )
    417

MultipleInstanceError: Multiple incompatible subclass instances of TerminalIPythonApp are being created.
</code>```

The same error appears if I use this code not in the jupyter notebook in the browser, but in jupyter qtconsole.
What does this error mean and what to do to avoid it?
Is it possible to debug code in the cell step-by-step, using next, continue, etc commands of pdb debugger?

答:
If using Jupyter Notebook
begin your cell with magic command "%%debug".
Then a ipdb line will be shown at the bottom of the cell which will help you navigate through the debugging session. Following commands should get you started:

n- execute current line and go to next line.

c- continue execution until next break point.

Make sure you restart the kernel each time you decide on debugging, so that all variables are freshly assigned.You can check the value of each variable through the ipdb line and you will see that the variable is undefined until you execute the line that assigns a value to that variable.

```<code>%%debug
import pdb
from pdb import set_trace as bp
def function_xyz():
    print('before breakpoint')
    bp() # This is a breakpoint.
    print('after breakpoint')
</code>```

Body:
I'm using jupyter (or Ipython) notebook with firefox, and want to debug some python code in the cell. I am using 'import ipdb; ipdb.set_trace()' as kind of breakpoint, for example my cell has the following code:

a=4
import ipdb; ipdb.set_trace()
b=5
print a
print b

which after execution with Shift+Enter gives me this error:

--------------------------------------------------------------------------
MultipleInstanceError                     Traceback (most recent call last)
<ipython-input-1-f2b356251c56> in <module>()
      1 a=4
----> 2 import ipdb; ipdb.set_trace()
      3 b=5
      4 print a
      5 print b

/home/nnn/anaconda/lib/python2.7/site-packages/ipdb/__init__.py in <module>()
     14 # You should have received a copy of the GNU General Public License along with this program. If not, see http://www.gnu.org/licenses/.
     15
---> 16 from ipdb.__main__ import set_trace, post_mortem, pm, run, runcall, runeval, launch_ipdb_on_exception
     17
     18 pm                       # please pyflakes

/home/nnn/anaconda/lib/python2.7/site-packages/ipdb/__main__.py in <module>()
     71         # the instance method will create a new one without loading the config.
     72         # i.e: if we are in an embed instance we do not want to load the config.
---> 73         ipapp = TerminalIPythonApp.instance()
     74         shell = get_ipython()
     75         def_colors = shell.colors

/home/nnn/anaconda/lib/python2.7/site-packages/traitlets/config/configurable.pyc in instance(cls, *args, **kwargs)
    413             raise MultipleInstanceError(
    414                 'Multiple incompatible subclass instances of '
--> 415                 '%s are being created.' % cls.__name__
    416             )
    417

MultipleInstanceError: Multiple incompatible subclass instances of TerminalIPythonApp are being created.

The same error appears if I use this code not in the jupyter notebook in the browser, but in jupyter qtconsole.
What does this error mean and what to do to avoid it?
Is it possible to debug code in the cell step-by-step, using next, continue, etc commands of pdb debugger?

Body:
If using Jupyter Notebook
begin your cell with magic command "%%debug".
Then a ipdb line will be shown at the bottom of the cell which will help you navigate through the debugging session. Following commands should get you started:

n- execute current line and go to next line.

c- continue execution until next break point.

Make sure you restart the kernel each time you decide on debugging, so that all variables are freshly assigned.You can check the value of each variable through the ipdb line and you will see that the variable is undefined until you execute the line that assigns a value to that variable.

%%debug
import pdb
from pdb import set_trace as bp
def function_xyz():
    print('before breakpoint')
    bp() # This is a breakpoint.
    print('after breakpoint')


问:
How to check whether any particular partition exist or not in HIVE
How to check whether any particular partition exist or not in HIVE:

I have partitions in my hive table as below:

country=india/state=MH
  country=US/state=NY

i want to check whether country = "something and state="something" exist or not in HIVE  or using shell script.Please help

答:
desc mytable partition (...)

show table extended like mytable partition (...)

Execute from shell using hive -e '...'

Demo

```<code>create table mytable (i int)
partitioned by (year int,month tinyint,day tinyint)
;

insert into mytable partition(year,month,day) values (1,2017,3,29)
;

hive> desc mytable partition (year=2017,month=3,day=29);
OK
i                       int
year                    int
month                   tinyint
day                     tinyint

# Partition Information
# col_name              data_type               comment

year                    int
month                   tinyint
day                     tinyint

hive> desc mytable partition (year=2017,month=4,day=1);
FAILED: SemanticException [Error 10006]: Partition not found {year=2017, month=4, day=1}

hive> show table extended like mytable partition (year=2017,month=3,day=29);
OK
tableName:mytable
owner:cloudera
location:hdfs://quickstart.cloudera:8020/user/hive/warehouse/mytable/year=2017/month=3/day=29
inputformat:org.apache.hadoop.mapred.TextInputFormat
outputformat:org.apache.hadoop.hive.ql.io.HiveIgnoreKeyTextOutputFormat
columns:struct columns { i32 i}
partitioned:true
partitionColumns:struct partition_columns { i32 year, byte month, byte day}
totalNumberFiles:1
totalFileSize:2
maxFileSize:2
minFileSize:2
lastAccessTime:1490770378864
lastUpdateTime:1490770379748

hive> show table extended like mytable partition (year=2017,month=4,day=1);
FAILED: SemanticException [Error 10006]: Partition not found {year=2017, month=4, day=1}
</code>```

Body:
desc mytable partition (...)

show table extended like mytable partition (...)

Execute from shell using hive -e '...'

Demo

create table mytable (i int)
partitioned by (year int,month tinyint,day tinyint)
;

insert into mytable partition(year,month,day) values (1,2017,3,29)
;

hive> desc mytable partition (year=2017,month=3,day=29);
OK
i                       int
year                    int
month                   tinyint
day                     tinyint

# Partition Information
# col_name              data_type               comment

year                    int
month                   tinyint
day                     tinyint

hive> desc mytable partition (year=2017,month=4,day=1);
FAILED: SemanticException [Error 10006]: Partition not found {year=2017, month=4, day=1}

hive> show table extended like mytable partition (year=2017,month=3,day=29);
OK
tableName:mytable
owner:cloudera
location:hdfs://quickstart.cloudera:8020/user/hive/warehouse/mytable/year=2017/month=3/day=29
inputformat:org.apache.hadoop.mapred.TextInputFormat
outputformat:org.apache.hadoop.hive.ql.io.HiveIgnoreKeyTextOutputFormat
columns:struct columns { i32 i}
partitioned:true
partitionColumns:struct partition_columns { i32 year, byte month, byte day}
totalNumberFiles:1
totalFileSize:2
maxFileSize:2
minFileSize:2
lastAccessTime:1490770378864
lastUpdateTime:1490770379748

hive> show table extended like mytable partition (year=2017,month=4,day=1);
FAILED: SemanticException [Error 10006]: Partition not found {year=2017, month=4, day=1}


问:
How to validate user input in shiny
I'm working on a very simple Shiny app that takes in a DNA codon and returns the corresponding amino acid. My issue is that I want to validate the user input so that it can only accept 3 letter (a single codon), must be capital letters, and only accept the DNA bases ( A, C, T, or G). I've had a look at Shiny's validation article, but keep on running into errors.
Here is the code I have so far:

ui.R

```<code>library(shiny)
library(shinythemes)

shinyUI(fluidPage(

  theme = shinytheme("slate"),

  # Application title
  titlePanel("Codon lookup"),

  #
  sidebarLayout(
    sidebarPanel(
      textInput(
        inputId = "codon",
        label = "Enter a codon",
        value = ""),
      actionButton(inputId = "go", label = "Search")
    ),

    #
    mainPanel(
      verbatimTextOutput("aminoacid")
    )
  )
))
</code>```

server.R

```<code>library(shiny)
library(Biostrings)

shinyServer(function(input, output) {

  data <- eventReactive(input$go, {

    #validate somehow
      input$codon

  })

  output$aminoacid <- renderText({

    GENETIC_CODE[[as.character(data())]]

  })

})
</code>```

Also, if anyone know of an easy way to retrieve the amino acid's full name, rather than just the single letter notation, that would be helpful. Any other suggestions are welcomed.

答:
That reactive is not really the right place to do the validation in this case since you are not using GENETIC_CODE there. So I moved it into the renderText output node. If you had a reactive doing the lookup you could do it there.

I looked at GENETIC_CODE, and it seems to make more sense to do this as a dropdown anyway and use that as validation. So I went ahead and put a selectInput in there using renderUI, as you have more flexibility if you create the input control in the server usually.

I also moved the Search button to above the codon select control as it was getting covered up by the selection.

```<code>library(shiny)
library(shinythemes)

u <- shinyUI(fluidPage(

  theme = shinytheme("slate"),

  # Application title
  titlePanel("Codon lookup"),

  #
  sidebarLayout(
    sidebarPanel(
      actionButton(inputId = "go", label = "Search"),
      uiOutput("codonselection")
    ),

    #
    mainPanel(
      verbatimTextOutput("aminoacid")
    )
  )
))

library(Biostrings)

s <- shinyServer(function(input, output) {

  data <- eventReactive(input$go, {
    input$codon
  })
  output$codonselection <- renderUI({
    choices <- names(GENETIC_CODE)
    default <- "TTC"
    selectInput("codon",label="Select Codon",choices=choices,selected=default)
  })

  output$aminoacid <- renderText({
    lookupcodon <-as.character(data())
    if (lookupcodon %in% names(GENETIC_CODE)){
      return(GENETIC_CODE[[ lookupcodon  ]])
    } else {
      return("Name not in GENETIC_CODE")
    }
  })

})
shinyApp(u,s)
</code>```

Screen shot of it working:

Title: How to validate user input in shiny

Body:
I'm working on a very simple Shiny app that takes in a DNA codon and returns the corresponding amino acid. My issue is that I want to validate the user input so that it can only accept 3 letter (a single codon), must be capital letters, and only accept the DNA bases ( A, C, T, or G). I've had a look at Shiny's validation article, but keep on running into errors.
Here is the code I have so far:

ui.R

library(shiny)
library(shinythemes)

shinyUI(fluidPage(

  theme = shinytheme("slate"),

  # Application title
  titlePanel("Codon lookup"),

  #
  sidebarLayout(
    sidebarPanel(
      textInput(
        inputId = "codon",
        label = "Enter a codon",
        value = ""),
      actionButton(inputId = "go", label = "Search")
    ),

    #
    mainPanel(
      verbatimTextOutput("aminoacid")
    )
  )
))

server.R

library(shiny)
library(Biostrings)

shinyServer(function(input, output) {

  data <- eventReactive(input$go, {

    #validate somehow
      input$codon

  })

  output$aminoacid <- renderText({

    GENETIC_CODE[[as.character(data())]]

  })

})

Also, if anyone know of an easy way to retrieve the amino acid's full name, rather than just the single letter notation, that would be helpful. Any other suggestions are welcomed.

Body:
That reactive is not really the right place to do the validation in this case since you are not using GENETIC_CODE there. So I moved it into the renderText output node. If you had a reactive doing the lookup you could do it there.

I looked at GENETIC_CODE, and it seems to make more sense to do this as a dropdown anyway and use that as validation. So I went ahead and put a selectInput in there using renderUI, as you have more flexibility if you create the input control in the server usually.

I also moved the Search button to above the codon select control as it was getting covered up by the selection.

library(shiny)
library(shinythemes)

u <- shinyUI(fluidPage(

  theme = shinytheme("slate"),

  # Application title
  titlePanel("Codon lookup"),

  #
  sidebarLayout(
    sidebarPanel(
      actionButton(inputId = "go", label = "Search"),
      uiOutput("codonselection")
    ),

    #
    mainPanel(
      verbatimTextOutput("aminoacid")
    )
  )
))

library(Biostrings)

s <- shinyServer(function(input, output) {

  data <- eventReactive(input$go, {
    input$codon
  })
  output$codonselection <- renderUI({
    choices <- names(GENETIC_CODE)
    default <- "TTC"
    selectInput("codon",label="Select Codon",choices=choices,selected=default)
  })

  output$aminoacid <- renderText({
    lookupcodon <-as.character(data())
    if (lookupcodon %in% names(GENETIC_CODE)){
      return(GENETIC_CODE[[ lookupcodon  ]])
    } else {
      return("Name not in GENETIC_CODE")
    }
  })

})
shinyApp(u,s)

Screen shot of it working:


问:
ADB server didn't ACK on macOS
I am getting this error since two days ago when I updated my Android Studio to the latest stable version 2.3; the full error message I am getting from Gradle Console is:

```<code>07:59:59 E/adb: error: could not install *smartsocket* listener: Address already in use
07:59:59 E/adb: ADB server didn't ACK
07:59:59 E/adb: * failed to start daemon *
07:59:59 E/adb: error: cannot connect to daemon
07:59:59 E/ddms: '/Users/USER_NAME/Library/Android/sdk/platform-tools/adb start
server' failed -- run manually if necessary
</code>```

My attempts to solve the issue:

kill all adb processes and make sure no process is holding port 5037, adb kill-server (says * server not running * even in cases when adb is running), close Android Studio, delete ~/.android directory, run adb start-server (says * daemon not running. starting it now at tcp:5037 *; * daemon started successfully *, start Android Studio and run application, MAC throws error adb quit unexpectedly and gradle console shows same the error I posted above.

uninstalled and deleted all Android Studio stuff (except for projects directory), restarted MAC, installed fresh and latest android studio.

increased gradle vm ram org.gradle.jvmargs=-Xmx1536M in project gradle.properties

uninstalled antivirus and restarted the mac

Environment:

OS: MacOS Sierra 10.12.3

Android Studio: 2.3

buildToolsVersion: '25.0.0'

Android Debug Bridge version: 1.0.39

答:
I read that you killed the adb, but as this answer says How to resolve the "ADB server didn't ACK" error? did you do that from the platform-tools folder? If your answer is yes, update the Android SDK to the lastest version via the SDK manager and update the $ANDROID_HOME

I hope it helps!

Title: ADB server didn't ACK on macOS

Body:
I am getting this error since two days ago when I updated my Android Studio to the latest stable version 2.3; the full error message I am getting from Gradle Console is:

07:59:59 E/adb: error: could not install *smartsocket* listener: Address already in use
07:59:59 E/adb: ADB server didn't ACK
07:59:59 E/adb: * failed to start daemon *
07:59:59 E/adb: error: cannot connect to daemon
07:59:59 E/ddms: '/Users/USER_NAME/Library/Android/sdk/platform-tools/adb start
server' failed -- run manually if necessary

My attempts to solve the issue:

kill all adb processes and make sure no process is holding port 5037, adb kill-server (says * server not running * even in cases when adb is running), close Android Studio, delete ~/.android directory, run adb start-server (says * daemon not running. starting it now at tcp:5037 *; * daemon started successfully *, start Android Studio and run application, MAC throws error adb quit unexpectedly and gradle console shows same the error I posted above.

uninstalled and deleted all Android Studio stuff (except for projects directory), restarted MAC, installed fresh and latest android studio.

increased gradle vm ram org.gradle.jvmargs=-Xmx1536M in project gradle.properties

uninstalled antivirus and restarted the mac

Environment:

OS: MacOS Sierra 10.12.3

Android Studio: 2.3

buildToolsVersion: '25.0.0'

Android Debug Bridge version: 1.0.39


问:
How to pass form values as FormData in reactjs on submit function
I have a dynamic form generated using json data and I need to pass the form input values on submit. I'm planning to send the values as formdata. I have created submit function but i don't know how to append the values in formdata and need to pass through post method using Axios. I'm new to react can anyone tell me how to do this. Below is my code.</p>
```<code>var DATA = {
  "indexList": [{
    "Label": "Name",
    "Type": "text",
    "Regex": "",
    "Default_Val": "",
    "Values": {
      "Key": "",
      "Value": ""
    },
    "Validtion Msg": "",
    "Script": "",
    "Mandatory": "Y",
    "maxLength":"16",
    "minLength":"7",
    "format":"Alphanumeric",
    "cssClassName": "form-control",
    "Placeholder": ""
  },
  {
    "Label": "Select Language",
    "Type": "dropdown",
    "Regex": "",
    "Default_Val": "English",
    "Values": [{
      "Key": "option1",
      "Value": "English"
    },{
      "Key": "option2",
      "Value": "Spanish"
    }],
    "Validtion Msg": "",
    "Script": "",
    "Mandatory": "Y",
    "maxLength":"",
    "minLength":"",
    "format":"",
    "cssClassName": "form-control",
    "Placeholder": ""
  },
  {
    "Label": "Type",
    "Type": "radio",
    "Regex": "",
    "Default_Val": "",
    "Values": [{
      "Key": "option1",
      "Value": "Form1"
    }, {
      "Key": "option2",
      "Value": "Form2"
    }, {
      "Key": "option3",
      "Value": "Form3"
    },{
      "Key": "option4",
      "Value": "Form4"
    },{
      "Key": "option5",
      "Value": "Form5"
    }],
    "Validtion Msg": "",
    "Script": "",
    "Mandatory": "Y",
    "maxLength":"",
    "minLength":"",
    "format":"",
    "cssClassName": "form-control",
    "Placeholder": ""
  }
  ]
};

var Menu = React.createClass({

  getInitialState() {
    return {
    }
  },

  _renderElement: function(group){
    switch(group.Type){
      case 'text':
        return (
          <input
            className={group.cssClassName}
            id={group.Label}
            placeholder={group.Placeholder}
            required={group.Mandatory == 'Y' ? true : false}
          />
        );

      case 'dropdown':
        return (
          <select className={group.cssClassName}>
            <option value="">{group.Placeholder}</option>
            {group.Values.map(el => <option>{el.Value}</option>)}
          </select>
        );

      case 'radio':
        return (
          <div className={group.Type}>
            <div for="let value of group.Values">
              {group.Values.map(el=> (
                <label><input name="radios"/>{el.Value}</label>
              ))}
            </div>
          </div>
        );
    }
  },

  renderForm: function () {
    var data = DATA.indexList;
    return data.map(group => {
      return (
        <div>
          <label for={group.Label}>{group.Label}</label>
          <div>
            {this._renderElement(group)}
          </div>
        </div>
      )
    });
  },

  _onSubmit: function () {
    let formData = new FormData();
    var data1 = DATA.indexList;
    data1.map(group => {
      formData.append(group.Label); // How to get the input value here as a second parameter, so than i can pass the label name and corresponding value to form data.
    });

    const config = {
      headers: { 'content-type': 'multipart/form-data' }
    }

    Axios.post('',formData, config)
      .then(response => {
        console.log(response);
      })
      .catch(error => {
          console.log(error);
      });
  },

  render: function() {
    return (
      <div className="container">
        <br/>
        <div className="panel panel-primary">
          <div className="panel-heading">Form</div>
          <div className="panel-body">
            <form>
              <div className="form-group">
                <div className="col-xs-5">
                  {this.renderForm()}
                  <button type="submit" className="btn btn-primary" onSubmit={this._onSubmit()}>Submit</button>
                </div>
              </div>
            </form>
          </div>
        </div>
      </div>
    )
  }
});

ReactDOM.render(<Menu/>, document.getElementById('app'));
</code>```

答:
You can update your changes to your state dynamically. See the example Here

```<code>constructor(props) {
    super(props);
    this.state = {value: ''};

    this.handleChange = this.handleChange.bind(this);
    this.handleSubmit = this.handleSubmit.bind(this);
  }
</code>```

bind all your fields to your state. Exampkle

```<code>this.sate = { name: '', username: '', select: '' }
</code>```

and then

```<code>_renderElement: function(group){
    switch(group.Type){
      case 'text':
      return <input className={group.cssClassName}
      id={group.Label}
      placeholder={group.Placeholder}
      value={this.state[group.name]}
      onChange={this.handleUsernameChange}
      required={group.Mandatory == 'Y'? true:   false}/>

      case 'dropdown':
      return <select className={group.cssClassName}>
      onChange={this.handleDropDropDownChange}
      <option value="">{group.Placeholder} </option>
      {group.Values.map(el => <option>{el.Value}</option>)}
      </select>

      </div>
    }
  }
</code>```

note group.name can be username, name or what ever you name your control.

```<code>handleUsernameChange(event) {
    this.setState({username: event.target.value});
  }

handleDropDownChange(event) {
    this.setState({select: event.target.value});
  }
</code>```

and then when posting

```<code>axios.post(url, this.state, config)
    .then(response => {
        console.log(response);
    })
    .catch(error => {
        console.log(error);
    });
</code>```

Don't forget to update your render to

```<code>render: function() {
    return (
      <div className="container">
      <br/>
      <div className="panel panel-primary">
      <div className="panel-heading">Form</div>
      <div className="panel-body">
      <form onSubmit={this.handleSubmit}>
      <div className="form-group">
      <div className="col-xs-5">

      {this.renderForm()}

             <input type="submit" value="Submit" />
      </div>
      </div>
      </form>
      </div>
      </div>
      </div>
      )}
  });
</code>```

Have a look at the doc here https://facebook.github.io/react/docs/forms.html

Body:
I have a dynamic form generated using json data and I need to pass the form input values on submit. I'm planning to send the values as formdata. I have created submit function but i don't know how to append the values in formdata and need to pass through post method using Axios. I'm new to react can anyone tell me how to do this. Below is my code.

var DATA = {
  "indexList": [{
    "Label": "Name",
    "Type": "text",
    "Regex": "",
    "Default_Val": "",
    "Values": {
      "Key": "",
      "Value": ""
    },
    "Validtion Msg": "",
    "Script": "",
    "Mandatory": "Y",
    "maxLength":"16",
    "minLength":"7",
    "format":"Alphanumeric",
    "cssClassName": "form-control",
    "Placeholder": ""
  },
  {
    "Label": "Select Language",
    "Type": "dropdown",
    "Regex": "",
    "Default_Val": "English",
    "Values": [{
      "Key": "option1",
      "Value": "English"
    },{
      "Key": "option2",
      "Value": "Spanish"
    }],
    "Validtion Msg": "",
    "Script": "",
    "Mandatory": "Y",
    "maxLength":"",
    "minLength":"",
    "format":"",
    "cssClassName": "form-control",
    "Placeholder": ""
  },
  {
    "Label": "Type",
    "Type": "radio",
    "Regex": "",
    "Default_Val": "",
    "Values": [{
      "Key": "option1",
      "Value": "Form1"
    }, {
      "Key": "option2",
      "Value": "Form2"
    }, {
      "Key": "option3",
      "Value": "Form3"
    },{
      "Key": "option4",
      "Value": "Form4"
    },{
      "Key": "option5",
      "Value": "Form5"
    }],
    "Validtion Msg": "",
    "Script": "",
    "Mandatory": "Y",
    "maxLength":"",
    "minLength":"",
    "format":"",
    "cssClassName": "form-control",
    "Placeholder": ""
  }
  ]
};

var Menu = React.createClass({

  getInitialState() {
    return {
    }
  },

  _renderElement: function(group){
    switch(group.Type){
      case 'text':
        return (
          <input
            className={group.cssClassName}
            id={group.Label}
            placeholder={group.Placeholder}
            required={group.Mandatory == 'Y' ? true : false}
          />
        );

      case 'dropdown':
        return (
          <select className={group.cssClassName}>
            <option value="">{group.Placeholder}</option>
            {group.Values.map(el => <option>{el.Value}</option>)}
          </select>
        );

      case 'radio':
        return (

              {group.Values.map(el=> (
                <input name="radios"/>{el.Value}
              ))}

        );
    }
  },

  renderForm: function () {
    var data = DATA.indexList;
    return data.map(group => {
      return (

          {group.Label}

            {this._renderElement(group)}

      )
    });
  },

  _onSubmit: function () {
    let formData = new FormData();
    var data1 = DATA.indexList;
    data1.map(group => {
      formData.append(group.Label); // How to get the input value here as a second parameter, so than i can pass the label name and corresponding value to form data.
    });

    const config = {
      headers: { 'content-type': 'multipart/form-data' }
    }

    Axios.post('',formData, config)
      .then(response => {
        console.log(response);
      })
      .catch(error => {
          console.log(error);
      });
  },

  render: function() {
    return (

Form

            <form>

                  {this.renderForm()}
                  <button type="submit" className="btn btn-primary" onSubmit={this._onSubmit()}>Submit</button>

            </form>

    )
  }
});

ReactDOM.render(<Menu/>, document.getElementById('app'));

Body:
You can update your changes to your state dynamically. See the example Here

constructor(props) {
    super(props);
    this.state = {value: ''};

    this.handleChange = this.handleChange.bind(this);
    this.handleSubmit = this.handleSubmit.bind(this);
  }

bind all your fields to your state. Exampkle

this.sate = { name: '', username: '', select: '' }

and then

_renderElement: function(group){
    switch(group.Type){
      case 'text':
      return <input className={group.cssClassName}
      id={group.Label}
      placeholder={group.Placeholder}
      value={this.state[group.name]}
      onChange={this.handleUsernameChange}
      required={group.Mandatory == 'Y'? true:   false}/>

      case 'dropdown':
      return <select className={group.cssClassName}>
      onChange={this.handleDropDropDownChange}
      <option value="">{group.Placeholder} </option>
      {group.Values.map(el => <option>{el.Value}</option>)}
      </select>

      </div>
    }
  }

note group.name can be username, name or what ever you name your control.

handleUsernameChange(event) {
    this.setState({username: event.target.value});
  }

handleDropDownChange(event) {
    this.setState({select: event.target.value});
  }

and then when posting

axios.post(url, this.state, config)
    .then(response => {
        console.log(response);
    })
    .catch(error => {
        console.log(error);
    });

Don't forget to update your render to

render: function() {
    return (
      <div className="container">
      <br/>
      <div className="panel panel-primary">
      <div className="panel-heading">Form</div>
      <div className="panel-body">
      <form onSubmit={this.handleSubmit}>
      <div className="form-group">
      <div className="col-xs-5">

      {this.renderForm()}

             <input type="submit" value="Submit" />
      </div>
      </div>
      </form>
      </div>
      </div>
      </div>
      )}
  });

Have a look at the doc here https://facebook.github.io/react/docs/forms.html


问:
Calculate value based on amount of green against blue and red
A bit stuck on this one.

Here is my predicament:

A colour has 3 elements Red, Green and Blue (RGB).

All colours have a value from 0-255.

for example:

```<code>var red:int = 53;
var green:int = 150;
var blue:int = 28;
</code>```

My scoring system works that the greener the colour the higher score it will get out of 10.

so:

```<code>var red:int = 0;
var green:int = 255;
var blue:int = 0;
</code>```

Would receive the highest score(10) and:

```<code>var red:int = 255;
var green:int = 0;
var blue:int = 255;
</code>```

would receive the lowest score (0).

I need to produce an equation of some sort. Is Bayes' Theorum where I am meant to be?

really dont have a clue.

答:
Your problem is selecting the correct function of (r,g,b) that would return values from 0 to 10. You state that (0,255,0) should return 10.0, while other values should return less, and (255,0,255) should return 0. So, you need to select at least two parameters for that function. One is value at (x,x,x) (if you desire that one to be equal, or else the parameter would be a function of X), and another is a rule of interpolation for non-extreme values. So, your function should look like this:

```<code>function score(r,g,b:int):Number {
    var rc:int=Math.max(0,Math.min(255,r)); // clamp
    var gc:int=Math.max(0,Math.min(255,g));
    var bc:int=Math.max(0,Math.min(255,b));
    const GRAY:Number=5.0; // value at (x,x,x)
    if ((rc==rg) and (rc==rb)) return GRAY;
    return ir(r,g,b); // interpolation rule
}
</code>```

In fact, you can specify values at all 8 corners and plain interpolate them by any law you can imagine. For example, by relative distance. Like this:

```<code>const SCORES:Array=[
    0, // black, (0,0,0)
    0, // red, (255,0,0)
    10, // green, (0,255,0)
    6.66666, // yellow, (255,255,0)
    0, // blue, (0,0,255)
    0, // magenta, (255,0,255)
    6.66666, // cyan, (0,255,255)
    5.0 // white, (255,255,255)
];
const POINTS:Array=[
    {r:0;g:0;b:0},
    {r:255;g:0;b:0},
    {r:0;g:255;b:0},
    {r:255;g:255;b:0},
    {r:0;g:0;b:255},
    {r:255;g:0;b:255},
    {r:0;g:255;b:255},
    {r:255;g:255;b:255}
]; // respective points

function score(r,g,b:int):Number {
    var rc:int=Math.max(0,Math.min(255,r)); // clamp
    var gc:int=Math.max(0,Math.min(255,g));
    var bc:int=Math.max(0,Math.min(255,b));
    var dists:Array=new Array();
    var td:Number=0;
    for (var i:int=POINTS.length-1;i>=0;i--)
        var dist:Number=distance({r=rc;g=gc;b=bc},POINTS[i]); // TODO
        if (dist<1e-6) return SCORES[i]; // we're at the corner
        dists.unshift(1.0/dist);
        td+=1.0/dist;
    }
    var result:Number=0;
    for (i=POINTS.length-1;i>=0;i--)
        result+=SCORES[i]*dists[i]/td;
    return result;
}
</code>```

Body:
A bit stuck on this one.

Here is my predicament:

A colour has 3 elements Red, Green and Blue (RGB).

All colours have a value from 0-255.

for example:

var red:int = 53;
var green:int = 150;
var blue:int = 28;

My scoring system works that the greener the colour the higher score it will get out of 10.

so:

var red:int = 0;
var green:int = 255;
var blue:int = 0;

Would receive the highest score(10) and:

var red:int = 255;
var green:int = 0;
var blue:int = 255;

would receive the lowest score (0).

I need to produce an equation of some sort. Is Bayes' Theorum where I am meant to be?

really dont have a clue.

Body:
Your problem is selecting the correct function of (r,g,b) that would return values from 0 to 10. You state that (0,255,0) should return 10.0, while other values should return less, and (255,0,255) should return 0. So, you need to select at least two parameters for that function. One is value at (x,x,x) (if you desire that one to be equal, or else the parameter would be a function of X), and another is a rule of interpolation for non-extreme values. So, your function should look like this:

function score(r,g,b:int):Number {
    var rc:int=Math.max(0,Math.min(255,r)); // clamp
    var gc:int=Math.max(0,Math.min(255,g));
    var bc:int=Math.max(0,Math.min(255,b));
    const GRAY:Number=5.0; // value at (x,x,x)
    if ((rc==rg) and (rc==rb)) return GRAY;
    return ir(r,g,b); // interpolation rule
}

In fact, you can specify values at all 8 corners and plain interpolate them by any law you can imagine. For example, by relative distance. Like this:

const SCORES:Array=[
    0, // black, (0,0,0)
    0, // red, (255,0,0)
    10, // green, (0,255,0)
    6.66666, // yellow, (255,255,0)
    0, // blue, (0,0,255)
    0, // magenta, (255,0,255)
    6.66666, // cyan, (0,255,255)
    5.0 // white, (255,255,255)
];
const POINTS:Array=[
    {r:0;g:0;b:0},
    {r:255;g:0;b:0},
    {r:0;g:255;b:0},
    {r:255;g:255;b:0},
    {r:0;g:0;b:255},
    {r:255;g:0;b:255},
    {r:0;g:255;b:255},
    {r:255;g:255;b:255}
]; // respective points

function score(r,g,b:int):Number {
    var rc:int=Math.max(0,Math.min(255,r)); // clamp
    var gc:int=Math.max(0,Math.min(255,g));
    var bc:int=Math.max(0,Math.min(255,b));
    var dists:Array=new Array();
    var td:Number=0;
    for (var i:int=POINTS.length-1;i>=0;i--)
        var dist:Number=distance({r=rc;g=gc;b=bc},POINTS[i]); // TODO
        if (dist<1e-6) return SCORES[i]; // we're at the corner
        dists.unshift(1.0/dist);
        td+=1.0/dist;
    }
    var result:Number=0;
    for (i=POINTS.length-1;i>=0;i--)
        result+=SCORES[i]*dists[i]/td;
    return result;
}


问:
Adding months to a date in access based on a number in another field
I have a database of documents with a "last reviewed" date field, another field has a number which states how many months until this document expires (6, 12, 18, 24)
I would like to display all the document which expire each month based on the review dates X the months till expire.

for example
if 3 documents have a date of 28/03/2017 and a 6 month review i would like a box on a menu which states 3 documents need to be reviewed in September.

any help would be great, thanks in advance

答:
First find the future month to check, then calculate the expire date for the documents, and finally compare these.

Then you can use DCount in an expression for your textbox counting the documents:

```<code>=DCount("*","YourTable","DateDiff('m',DateAdd('m'," & [YourMonthsForwardTextbox] & ", Date()),DateAdd('m',[Expires],[Last Reviewed]))=0")
</code>```

Body:
First find the future month to check, then calculate the expire date for the documents, and finally compare these.

Then you can use DCount in an expression for your textbox counting the documents:

=DCount("*","YourTable","DateDiff('m',DateAdd('m'," & [YourMonthsForwardTextbox] & ", Date()),DateAdd('m',[Expires],[Last Reviewed]))=0")