问:
how do i change an image if i click on a button in Swift?
I am new to swift. I have a button and 3 images that are saved in the array. What I want is to change the images by clicking on the button. </p>

```<code>let circleArray = ["circle-gray-big","circle-green-big","circle-red-big"]
@IBAction func carbsButton(_ sender: Any) {

}
</code>```

答:
Swift 3.0

Global declaration of the class,

```<code>let circleArray = ["circle-gray-big","circle-green-big","circle-red-big"]
var index = 0
</code>```

In UIImageView:

```<code>@IBOutlet var imageView: UIImageView! //Global

@IBAction func carbsButton(_ sender: Any) {

 self.index = (self.index >= self.circleArray.count-1) ? 0 : self.index+1
 self.imageView.image = UIImage(named:circleArray[index])
}
</code>```

In UIButton

Change Any in carbsButton(_ sender: Any) to carbsButton(_ sender: UIButton). After do like below code,

```<code>@IBAction func carbsButton(_ sender: UIButton) {
  self.index = (self.index >= self.circleArray.count-1) ? 0 : self.index+1
   sender.setImage(UIImage(named:circleArray[index]), for: .normal)//Button
}
</code>```

In UIImageView and UIButton:

```<code>let circleArray = ["circle-gray-big","circle-green-big","circle-red-big"]
var index = 0

@IBOutlet var imageView: UIImageView!
@IBAction func carbsButton(_ sender: UIButton) {

    self.index = (self.index >= self.circleArray.count-1) ? 0 : self.index+1

    self.imageView.image = UIImage(named:circleArray[index]) //imageView
    sender.setImage(UIImage(named:circleArray[index]), for: .normal)//Button
}
</code>```

Sample Output:

```<code>sender.setBackgroundImage(UIImage(named:circleArray[index]), for: .normal)
</code>```

Body:
I am new to swift. I have a button and 3 images that are saved in the array. What I want is to change the images by clicking on the button.

let circleArray = ["circle-gray-big","circle-green-big","circle-red-big"]
@IBAction func carbsButton(_ sender: Any) {

}

Body:
Swift 3.0

Global declaration of the class,

let circleArray = ["circle-gray-big","circle-green-big","circle-red-big"]
var index = 0

In UIImageView:

@IBOutlet var imageView: UIImageView! //Global

@IBAction func carbsButton(_ sender: Any) {

 self.index = (self.index >= self.circleArray.count-1) ? 0 : self.index+1
 self.imageView.image = UIImage(named:circleArray[index])
}

In UIButton

Change Any in carbsButton(_ sender: Any) to carbsButton(_ sender: UIButton). After do like below code,

@IBAction func carbsButton(_ sender: UIButton) {
  self.index = (self.index >= self.circleArray.count-1) ? 0 : self.index+1
   sender.setImage(UIImage(named:circleArray[index]), for: .normal)//Button
}

In UIImageView and UIButton:

let circleArray = ["circle-gray-big","circle-green-big","circle-red-big"]
var index = 0

@IBOutlet var imageView: UIImageView!
@IBAction func carbsButton(_ sender: UIButton) {

    self.index = (self.index >= self.circleArray.count-1) ? 0 : self.index+1

    self.imageView.image = UIImage(named:circleArray[index]) //imageView
    sender.setImage(UIImage(named:circleArray[index]), for: .normal)//Button
}

Sample Output:

sender.setBackgroundImage(UIImage(named:circleArray[index]), for: .normal)


来源: stackexchange

问:
Why the Python 2, 3 compatibility package is named `six`?
Six provides simple utilities for wrapping over differences between Python 2 and Python 3. It is intended to support codebases that work on both Python 2 and 3 without modification. six consists of only one Python file, so it is painless to copy into a project.

I was always wondering why it is named six.

答:
The name, “six”, comes from the fact that 2*3 equals 6. Why not
  addition? Multiplication is more powerful, and, anyway, “five” has
  already been snatched away by the (admittedly now moribund) Zope Five
  project.

Source

ContentLicense: CC BY-SA 4.0


问:
MongoError: Can't canonicalize query: BadValue unknown operator: $and
I have this query code but having problem making it work. I am using NodeJS and database is mongoDB.

```<code>  Transducer.find({$and: [{isNew:{$eq:true}}, {isPublished:{$eq:true}}]})
    .sort({"nominalDiameterin":1})
    .limit(50)
    .exec(function(err, allTransducers){
    if(err) {
        throw err;
    } else {
        if(req.xhr) {
            res.json(allTransducers);
        } else {
            var id = req.params.id;
            if(id === 'en'){
                res.render("products/transducers", {transducers: allTransducers, length: allTransducers.length});
            }else if(id === 'cn'){
                res.render("products/transducers-cn", {transducers: allTransducers, length: allTransducers.length});
            }

        }
</code>```

I want to display data that are new and published but I having no luck.

Any help, please?

答:
Dear @Vina Vanessa Compson u can no need to use $and and $eq operator for simple query and your syntax is also incorrect .

Please follow below answer

```<code>var query = {
        isNew:true,
        isPublished:true
  }

  var toSort = {
    nominalDiameterin:1
}
  Transducer.find(query).sort(toSort).limit(50).exec(function(err, allTransducers) {
    if (err) {
      throw err;
    } else {
      if(req.xhr) {
        res.json(allTransducers);
      } else {
        var id = req.params.id;
        if(id === 'en'){
          res.render("products/transducers", {transducers: allTransducers, length: allTransducers.length});
        }else if(id === 'cn'){
          res.render("products/transducers-cn", {transducers: allTransducers, length: allTransducers.length});
        }

      }
    }
  })
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have this query code but having problem making it work. I am using NodeJS and database is mongoDB.

  Transducer.find({$and: [{isNew:{$eq:true}}, {isPublished:{$eq:true}}]})
    .sort({"nominalDiameterin":1})
    .limit(50)
    .exec(function(err, allTransducers){
    if(err) {
        throw err;
    } else {
        if(req.xhr) {
            res.json(allTransducers);
        } else {
            var id = req.params.id;
            if(id === 'en'){
                res.render("products/transducers", {transducers: allTransducers, length: allTransducers.length});
            }else if(id === 'cn'){
                res.render("products/transducers-cn", {transducers: allTransducers, length: allTransducers.length});
            }

        }

I want to display data that are new and published but I having no luck.

Any help, please?

Body:
Dear @Vina Vanessa Compson u can no need to use $and and $eq operator for simple query and your syntax is also incorrect .

Please follow below answer

var query = {
        isNew:true,
        isPublished:true
  }

  var toSort = {
    nominalDiameterin:1
}
  Transducer.find(query).sort(toSort).limit(50).exec(function(err, allTransducers) {
    if (err) {
      throw err;
    } else {
      if(req.xhr) {
        res.json(allTransducers);
      } else {
        var id = req.params.id;
        if(id === 'en'){
          res.render("products/transducers", {transducers: allTransducers, length: allTransducers.length});
        }else if(id === 'cn'){
          res.render("products/transducers-cn", {transducers: allTransducers, length: allTransducers.length});
        }

      }
    }
  })


问:
What is the correct way to query MongoDB for _id using string by using Python?
I am using pymongo driver.  Supposedly, one can use a string to query the _id field of a document, like this:

```<code>thing = db.things.find_one({'_id':'4ea113d6b684853c8e000001'})
</code>```

But it doesn't work.  What am I doing wrong?

答:
To print it:

```<code>import pymongo
from bson.objectid import ObjectId
print(db.things.find_one({'_id': ObjectId('4ea113d6b684853c8e000001')}))
</code>```

if you don't want to print, store in other variable

Body:
I am using pymongo driver.  Supposedly, one can use a string to query the _id field of a document, like this:

thing = db.things.find_one({'_id':'4ea113d6b684853c8e000001'})

But it doesn't work.  What am I doing wrong?

Body:
To print it:

import pymongo
from bson.objectid import ObjectId
print(db.things.find_one({'_id': ObjectId('4ea113d6b684853c8e000001')}))

if you don't want to print, store in other variable


问:
Youtube api video auto playing when page scroll
How to play youtube video automatically when user scrolls page with several youtube videos (like on twitter and Facebook). When scrolling to video - autoplay youtube video. </p>

答:
https://github.com/olssonandreas/youtubeautoplay

Simple javascript project that shows how you can autoplay multiple videos on the same page. The autoplay starts when the video is in the viewport.


问:
How to use OR operator in Linq
I want to use OR function in my linq query.
Ex:
Sql:

```<code>select * from tblusers where userid=1 and status='a' or status='b';
</code>```

Linq:

```<code>var result= _Repository.selectAll().where(x=>x.UserID==1 && x.status=="a" OR x.status=="B");
</code>```

It's does work for linq query. so does anyone have any idea?

答:
So you are aware about the && operator for comparison, then why not make a try with || operator? Anyway here is the solution for your problem, Following code will get you the result with UserID is 1 and status is either a or B.

```<code> _Repository.selectAll().where(x=>x.UserID==1 && (x.status=="a" || x.status=="B"));
</code>```

Title: How to use OR operator in Linq

Body:
I want to use OR function in my linq query.
Ex:
Sql:

select * from tblusers where userid=1 and status='a' or status='b';

Linq:

var result= _Repository.selectAll().where(x=>x.UserID==1 && x.status=="a" OR x.status=="B");

It's does work for linq query. so does anyone have any idea?

Body:
So you are aware about the && operator for comparison, then why not make a try with || operator? Anyway here is the solution for your problem, Following code will get you the result with UserID is 1 and status is either a or B.

 _Repository.selectAll().where(x=>x.UserID==1 && (x.status=="a" || x.status=="B"));


问:
What is the conditional code to affect IE8 browser?
I don't mean conditional comments embedded into the html. I am refering to the conditional code that can be put directly into the css file. Like:

```<code>*+html .myClass {} is for IE7
* html .myClass {} is for IE 6
</code>```

what is the one for IE 8?

答:
What are you trying to achieve? You shouldn't have to hack up your CSS for IE8. I don't think there is a conditional code for IE8 so if you absolutely need to have a style sheet for IE8, you might have to turn to conditional comment.</p>

```<code><!--[if IE 8]>
    <link href="ie8css.css" rel="stylesheet" type="text/css" />
<![endif]-->
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I don't mean conditional comments embedded into the html. I am refering to the conditional code that can be put directly into the css file. Like:

*+html .myClass {} is for IE7
* html .myClass {} is for IE 6

what is the one for IE 8?

Body:
What are you trying to achieve? You shouldn't have to hack up your CSS for IE8. I don't think there is a conditional code for IE8 so if you absolutely need to have a style sheet for IE8, you might have to turn to conditional comment.

<!--[if IE 8]>
    <link href="ie8css.css" rel="stylesheet" type="text/css" />
<![endif]-->


问:
Prepare text to paste to MS Word with proper alignment
I am working on a C# application that calculates some values. They are placed into a DataGridView. When I select values from a column of the DataGridView and I paste them to a column of a table from a Word document, I want the values to be center aligned. Even if I set all cells of the DataGridView to be center aligned, when I copy and paste the text into the Word table, they show up left aligned.
The code used to copy the table into clipboard is

```<code>Clipboard.SetDataObject(this.dataGridView1.GetClipboardContent());
</code>```

How can I prepare the text so that when I paste it, it will show centered? If I copy and paste text from another column of Word, it maintains the original alignment. This indicates there are some special characters surrounding the cell values. I don't know how to view those characters (maybe I can add them to each value).

答:
I'm going to cheat and start with an incomplete answer.

This RTF text seems like it should work for a single value:

```<code>{\rtf1\ansi\qc
This is some centered text.}
</code>```

That's a "hard newline" after \qc or I think just a \n.  If I put that RTF into a file then open in WordPad it shows up centered.

I've been playing with System.Windows.Forms.ClipBoard.

```<code>Clipboard.SetData(DataFormats.Rtf, "{\\rtf1\\qc\n{\\b foo}}");
</code>```

If I run the above even in a console application, I can next ctrl-V paste into MS Word and the bold works, but unfortunately the centering doesn't.

In any case, I then looked at pasting into a MS Word table and clearly it's not just a matter of text with newlines, some delimiter or other is required to show cell boundaries.  So not only does the RTF I have not work, there's likely at least one more step / wrapper beyond the RTF to get a "column" not just a block of text.

Feel free to not vote, I just thought perhaps something here might be helpful to avoid both of us doing the same thing twice.

EDIT: DataFormats.Html may also work and seems it could even be the format normally used by your grid control.  (though it also supports CSV)

However there's an extra clipboard header for HTML I haven't figured out yet described here:  How to set HTML to clipboard in C#?

Body:
I am working on a C# application that calculates some values. They are placed into a DataGridView. When I select values from a column of the DataGridView and I paste them to a column of a table from a Word document, I want the values to be center aligned. Even if I set all cells of the DataGridView to be center aligned, when I copy and paste the text into the Word table, they show up left aligned.
The code used to copy the table into clipboard is

Clipboard.SetDataObject(this.dataGridView1.GetClipboardContent());

How can I prepare the text so that when I paste it, it will show centered? If I copy and paste text from another column of Word, it maintains the original alignment. This indicates there are some special characters surrounding the cell values. I don't know how to view those characters (maybe I can add them to each value).

Body:
I'm going to cheat and start with an incomplete answer.

This RTF text seems like it should work for a single value:

{\rtf1\ansi\qc
This is some centered text.}

That's a "hard newline" after \qc or I think just a \n.  If I put that RTF into a file then open in WordPad it shows up centered.

I've been playing with System.Windows.Forms.ClipBoard.

Clipboard.SetData(DataFormats.Rtf, "{\\rtf1\\qc\n{\\b foo}}");

If I run the above even in a console application, I can next ctrl-V paste into MS Word and the bold works, but unfortunately the centering doesn't.

In any case, I then looked at pasting into a MS Word table and clearly it's not just a matter of text with newlines, some delimiter or other is required to show cell boundaries.  So not only does the RTF I have not work, there's likely at least one more step / wrapper beyond the RTF to get a "column" not just a block of text.

Feel free to not vote, I just thought perhaps something here might be helpful to avoid both of us doing the same thing twice.

EDIT: DataFormats.Html may also work and seems it could even be the format normally used by your grid control.  (though it also supports CSV)

However there's an extra clipboard header for HTML I haven't figured out yet described here:  How to set HTML to clipboard in C#?


问:
Why is nothing appearing on my canvas?
I am such a noob and I have no idea why nothing is appearing on my canvas. Can someone help me out? I wanted to have a black box on my canvas, that was the intention anyway.   </p>

```<code>var canvas = document.createElement("canvas");
var ctx = canvas.getContext("2d");
canvas.width = 1040;
canvas.height = 400;
canvas.style.display='block';
canvas.style.marginLeft="auto";
canvas.style.marginRight="auto";

var mainFunction= function(){
ctx.fillStyle = "rgb(0, 0, 0)";
ctx.beginPath();
ctx.rect(0, 0, canvas.width, canvas.height);
ctx.closePath();
ctx.fill();
requestAnimationFrame(mainFunction);
};

mainFunction();
</code>```

答:
You have created a <canvas> element but have not attached it anywhere in the DOM. Perhaps you want something like

```<code>document.body.appendChild(canvas);
</code>```

or another suitable container.

Title: Why is nothing appearing on my canvas?

Body:
I am such a noob and I have no idea why nothing is appearing on my canvas. Can someone help me out? I wanted to have a black box on my canvas, that was the intention anyway.

var canvas = document.createElement("canvas");
var ctx = canvas.getContext("2d");
canvas.width = 1040;
canvas.height = 400;
canvas.style.display='block';
canvas.style.marginLeft="auto";
canvas.style.marginRight="auto";

var mainFunction= function(){
ctx.fillStyle = "rgb(0, 0, 0)";
ctx.beginPath();
ctx.rect(0, 0, canvas.width, canvas.height);
ctx.closePath();
ctx.fill();
requestAnimationFrame(mainFunction);
};

mainFunction();

Body:
You have created a <canvas> element but have not attached it anywhere in the DOM. Perhaps you want something like

document.body.appendChild(canvas);

or another suitable container.


问:
Is there any limit on the number of repositories in Gerrit?
I am trying to find out if there are any limits on the number of repositories we can create in Gerrit ?</p>

答: No, there is no limit for the number of repos in Gerrit. Maybe have a look at OpenStack's installation, they have a decent number of repos.</p>


问:
What's the best way to add a full screen background image in React Native
I wanted to add a full-screen image to the View so I write this code

```<code>return (
    <View style={styles.container}>
        <Image source={require('image!egg')}  style={styles.backgroundImage}/>
    </View>
)
</code>```

and defined the style as

```<code>var styles = StyleSheet.create({
container: {
     flex: 1,
     justifyContent: 'center',
     alignItems: 'center',
     backgroundColor: '#F5FCFF',
     flexDirection: 'column',
},
     backgroundImage:{
     width:320,
     height:480,
   }
...
</code>```

but in this way how am I supposed to find the actual iPhone screen size?

I've seen an API to access the Pixel Density but nothing about the screen size...

Any idea?

答:
If you want to use it as a background image, you will need to use the new <ImageBackground> component introduced at the end of June 2017 in v0.46. It supports nesting while <Image> soon won't.

Here is the commit summary:

We are removing support of nesting views inside  component. We decided to do this because having this feature makes supporting
  intrinsinc content size of the <Image> impossible; so when the
  transition process is complete, there will be no need to specify image
  size explicitly, it can be inferred from actual image bitmap.

And this is the step #0.

 is very simple drop-in replacement which implements
  this functionality via very simple styling. Please, use
   instead of  if you want to put something
  inside.

Body:
I wanted to add a full-screen image to the View so I write this code

return (
    <View style={styles.container}>
        <Image source={require('image!egg')}  style={styles.backgroundImage}/>
    </View>
)

and defined the style as

var styles = StyleSheet.create({
container: {
     flex: 1,
     justifyContent: 'center',
     alignItems: 'center',
     backgroundColor: '#F5FCFF',
     flexDirection: 'column',
},
     backgroundImage:{
     width:320,
     height:480,
   }
...

but in this way how am I supposed to find the actual iPhone screen size?

I've seen an API to access the Pixel Density but nothing about the screen size...

Any idea?


问:
Upload image to folder using ajax/jquery
I'm trying to upload an image to a folder using ajax, jquery and php but the problem is that I don't know how to send my file input value to my php file, when I run my code I get the following message:

undefined index archivo

This is my ajax call (PD. All the other parameters works properly, I only have problems with the file input value)

```<code>function Registrar() {
      var cat = $('#cat').val();
      var nom = $('#name').val();
      var desc = $('#description').val();
      var image = $('#archivo').val();
     //Also tried with this, to remove the fakepath string... $('input[type=file]').val().replace(/C:\\fakepath\\/i, '')

      $.ajax({
        url: '../../class/upload.php',
        method: 'POST',
        data: { categoria: cat, nombre: nom, descripcion: desc, archivo: image, activo: act, disponible: disp, precio: prec },
        success: function (data) {
          console.log(data);
        }
      });
    }
</code>```

PHP file:

```<code><?php

    $categoria = $_POST['categoria'];
    $nombre = $_POST['nombre'];
    $descripcion = $_POST['descripcion'];
    $img = $_POST['archivo'];
    $activo = $_POST['activo'];
    $disponible = $_POST['disponible'];
    $precio = $_POST['precio'];
    $IdCategoria = 0;
    $filepath = "";

    //Imagen

    if($categoria=="Piano") {
        $IdCategoria = 1;
        $filepath = "../Files/Productos/Piano/".$img;
    }

    $filetmp = $_FILES['archivo']['tmp_name'];
    move_uploaded_file($filetmp, $filepath);

    echo $IdCategoria.$nombre.$descripcion.$filepath.$activo.$disponible.$categoria.$precio;

?>
</code>```

And the important parts of my HTML:

```<code><form id="registerForm" method="post" role="form" enctype="multipart/form-data" >
<input name="archivo" id="archivo" style="width: 70%;" name="textinput" class="btn btn-block" type="file" onchange="showimagepreview(this)" />
</code>```

EDIT: showimagepreview

```<code>function showimagepreview(input) {

            if (input.files && input.files[0]) {
                var reader = new FileReader();
                reader.onload = function (e) {

                    document.getElementsByTagName("img")[0].setAttribute("src", e.target.result);
                }
                reader.readAsDataURL(input.files[0]);
            }
        }
</code>```

How can I solve this?

答:
Here is you solution

HTML

```<code><form id="registerForm" method="post" enctype="multipart/form-data">
    <input name="archivo" id="archivo" style="width: 70%;" class="btn btn-block" type="file" onchange="PreviewImage(this)" />
    <img id="uploadPreview" />
    <button type="submit">Submit</button>
</code>```

Java Script

```<code>function PreviewImage() {
    var oFReader = new FileReader();
    oFReader.readAsDataURL(document.getElementById("image").files[0]);
    oFReader.onload = function (oFREvent) {
        document.getElementById("uploadPreview").src = oFREvent.target.result;
   };
};

//ajax

$("#registerForm").submit(function(event) {
    var formData = new FormData($(this)[0]);
    if ($(this).valid()) {
        $.ajax({
            url         : '../../class/upload.php',
            type        : 'POST',
            data        : formData,
            contentType : false,
            cache       : false,
            processData : false,
            success: function(e) {alert(e)  },
            error       : function(x, t, m) {},
        });
    }
 });
</code>```

PHP

```<code><?php
    echo "```"; print_r($_FILES);echo "```"; die; //this will show you the file transfered by form.
    $categoria = $_POST['categoria'];
    $nombre = $_POST['nombre'];
    $descripcion = $_POST['descripcion'];
    $img = $_POST['archivo'];
    $activo = $_FILES['activo'];
    $disponible = $_POST['disponible'];
    $precio = $_POST['precio'];
    $IdCategoria = 0;
    $filepath = "";

    //Imagen

    if($categoria=="Piano") {
        $IdCategoria = 1;
        $filepath = "../Files/Productos/Piano/".$img;
    }

    $filetmp = $_FILES['archivo']['tmp_name'];
    move_uploaded_file($filetmp, $filepath);

    echo $IdCategoria.$nombre.$descripcion.$filepath.$activo.$disponible.$categoria.$precio;

?>
</code>```

Body:
I'm trying to upload an image to a folder using ajax, jquery and php but the problem is that I don't know how to send my file input value to my php file, when I run my code I get the following message:

undefined index archivo

This is my ajax call (PD. All the other parameters works properly, I only have problems with the file input value)

function Registrar() {
      var cat = $('#cat').val();
      var nom = $('#name').val();
      var desc = $('#description').val();
      var image = $('#archivo').val();
     //Also tried with this, to remove the fakepath string... $('input[type=file]').val().replace(/C:\\fakepath\\/i, '')

      $.ajax({
        url: '../../class/upload.php',
        method: 'POST',
        data: { categoria: cat, nombre: nom, descripcion: desc, archivo: image, activo: act, disponible: disp, precio: prec },
        success: function (data) {
          console.log(data);
        }
      });
    }

PHP file:

<?php

    $categoria = $_POST['categoria'];
    $nombre = $_POST['nombre'];
    $descripcion = $_POST['descripcion'];
    $img = $_POST['archivo'];
    $activo = $_POST['activo'];
    $disponible = $_POST['disponible'];
    $precio = $_POST['precio'];
    $IdCategoria = 0;
    $filepath = "";

    //Imagen

    if($categoria=="Piano") {
        $IdCategoria = 1;
        $filepath = "../Files/Productos/Piano/".$img;
    }

    $filetmp = $_FILES['archivo']['tmp_name'];
    move_uploaded_file($filetmp, $filepath);

    echo $IdCategoria.$nombre.$descripcion.$filepath.$activo.$disponible.$categoria.$precio;

?>

And the important parts of my HTML:

<form id="registerForm" method="post" role="form" enctype="multipart/form-data" >
<input name="archivo" id="archivo" style="width: 70%;" name="textinput" class="btn btn-block" type="file" onchange="showimagepreview(this)" />

EDIT: showimagepreview

function showimagepreview(input) {

            if (input.files && input.files[0]) {
                var reader = new FileReader();
                reader.onload = function (e) {

                    document.getElementsByTagName("img")[0].setAttribute("src", e.target.result);
                }
                reader.readAsDataURL(input.files[0]);
            }
        }

How can I solve this?

Body:
Here is you solution

HTML

<form id="registerForm" method="post" enctype="multipart/form-data">
    <input name="archivo" id="archivo" style="width: 70%;" class="btn btn-block" type="file" onchange="PreviewImage(this)" />
    <img id="uploadPreview" />
    <button type="submit">Submit</button>

Java Script

function PreviewImage() {
    var oFReader = new FileReader();
    oFReader.readAsDataURL(document.getElementById("image").files[0]);
    oFReader.onload = function (oFREvent) {
        document.getElementById("uploadPreview").src = oFREvent.target.result;
   };
};

//ajax

$("#registerForm").submit(function(event) {
    var formData = new FormData($(this)[0]);
    if ($(this).valid()) {
        $.ajax({
            url         : '../../class/upload.php',
            type        : 'POST',
            data        : formData,
            contentType : false,
            cache       : false,
            processData : false,
            success: function(e) {alert(e)  },
            error       : function(x, t, m) {},
        });
    }
 });

PHP

<?php
    echo "<pre>"; print_r($_FILES);echo "</pre>"; die; //this will show you the file transfered by form.
    $categoria = $_POST['categoria'];
    $nombre = $_POST['nombre'];
    $descripcion = $_POST['descripcion'];
    $img = $_POST['archivo'];
    $activo = $_FILES['activo'];
    $disponible = $_POST['disponible'];
    $precio = $_POST['precio'];
    $IdCategoria = 0;
    $filepath = "";

    //Imagen

    if($categoria=="Piano") {
        $IdCategoria = 1;
        $filepath = "../Files/Productos/Piano/".$img;
    }

    $filetmp = $_FILES['archivo']['tmp_name'];
    move_uploaded_file($filetmp, $filepath);

    echo $IdCategoria.$nombre.$descripcion.$filepath.$activo.$disponible.$categoria.$precio;

?>


问:
Python serial commands to send CTRL+ L
I have a customer display, that's connected to serial port. I am using a windows machine for this.

I want to send Ctrl+L to clear the display of customer display, but I cannot find a solution that helps me. Basically I wish to send Ctrl+'any commands' in future.

In command Prompt I can use "Ctrl+L " to clear the existing display and display the text. The following is the command that gets displayed in prompt

```<code>echo ^LDisplay me > COMX // ^L is actually CTRL + L
</code>```

The above will output as ,

Clears the display.

Displays "Display me"

Now I am trying to achieve the same thing using Python serial connector.

```<code>import serial
ser = Serial ('COM5',timeout=2)
ser.write("\x0C") # equivalent to ctrl+L
</code>```

This does not work at all. I get error as `

Exception in serial connection:  unicode strings are not supported, please encode to bytes:'\x03'

However if I try the following for normal texts, it works perfectly,

```<code>ser.write("Display me".encode()
</code>```

This displays "Display me" in the customer display.

I tried to use ser.write("\x0C".encode()) but I get no output.

I get error as

Exception in serial connection: unicode strings are not supported, please encode to bytes:'\x1fc\x00'

I would appreciate any suggestions, improvements and help to solve this. Thanks.

答:
To encode a Ctrl+L as bytes in Python3, you should use:

```<code>b'\x0c'
</code>```

Why?

Ascii control characters are encoded as their position in the alphabet, so Ctrl+C, since it is the third letter of the alphabet, encoded as a hex string, would be \x03. Similarly, Ctrl+L would \x0c (hex C is decimal 12).

In python 3 to get bytes, you can pre-pend the string with a b.

Title: Python serial commands to send CTRL+ L

Body:
I have a customer display, that's connected to serial port. I am using a windows machine for this.

I want to send Ctrl+L to clear the display of customer display, but I cannot find a solution that helps me. Basically I wish to send Ctrl+'any commands' in future.

In command Prompt I can use "Ctrl+L " to clear the existing display and display the text. The following is the command that gets displayed in prompt

echo ^LDisplay me > COMX // ^L is actually CTRL + L

The above will output as ,

Clears the display.

Displays "Display me"

Now I am trying to achieve the same thing using Python serial connector.

import serial
ser = Serial ('COM5',timeout=2)
ser.write("\x0C") # equivalent to ctrl+L

This does not work at all. I get error as `

Exception in serial connection:  unicode strings are not supported, please encode to bytes:'\x03'

However if I try the following for normal texts, it works perfectly,

ser.write("Display me".encode()

This displays "Display me" in the customer display.

I tried to use ser.write("\x0C".encode()) but I get no output.

I get error as

Exception in serial connection: unicode strings are not supported, please encode to bytes:'\x1fc\x00'

I would appreciate any suggestions, improvements and help to solve this. Thanks.

Body:
To encode a Ctrl+L as bytes in Python3, you should use:

b'\x0c'

Why?

Ascii control characters are encoded as their position in the alphabet, so Ctrl+C, since it is the third letter of the alphabet, encoded as a hex string, would be \x03. Similarly, Ctrl+L would \x0c (hex C is decimal 12).

In python 3 to get bytes, you can pre-pend the string with a b.


问:
Change directory with popen
I'm able to use popen to run just about any program, but apparently not cd:

```<code>#include <stdio.h>
void main() {
    FILE *fp = popen("cd", "w");
    pclose(fp);
}
</code>```

I'd expect that to change directory to home but nothing happens. Changing to "r", or changing to e.g. "cd ~", "cd /", does not help. Using system has about the same result, i.e. works for anything but cd. So how is it done? The answers here don't work for me. Thank you.

答:
cd is generally a shell internal command, NOT an executable.

Even if it were, in general no process can change another process's working directory, so it would change the cwd for the "cd" process and then upon exit it'd be gone.

Title: Change directory with popen

Body:
I'm able to use popen to run just about any program, but apparently not cd:

#include <stdio.h>
void main() {
    FILE *fp = popen("cd", "w");
    pclose(fp);
}

I'd expect that to change directory to home but nothing happens. Changing to "r", or changing to e.g. "cd ~", "cd /", does not help. Using system has about the same result, i.e. works for anything but cd. So how is it done? The answers here don't work for me. Thank you.


答:
first of all you need to give tag to UIButton

```<code>    @IBOutlet var btn: UIButton!
    let circleArray = ["circle-gray-big","circle-green-big","circle-red-big"]

    override func viewDidLoad() {
            super.viewDidLoad()
            see.btn.tag = 0
    }

    @IBAction func carbsButton(_ sender: Any) {
            button.setImage(UIImage(named: circleArray[btn.tag % 3]),forState:Normal)
            btn.tag = ban.tag + 1
    }
</code>```

Do in this manner you will definitely get what you want..If it solve the problem hit up arrow.

Title: how do i change an image if i click on a button in Swift?

Body:
I am new to swift. I have a button and 3 images that are saved in the array. What I want is to change the images by clicking on the button.

let circleArray = ["circle-gray-big","circle-green-big","circle-red-big"]
@IBAction func carbsButton(_ sender: Any) {

}

Body:
first of all you need to give tag to UIButton

    @IBOutlet var btn: UIButton!
    let circleArray = ["circle-gray-big","circle-green-big","circle-red-big"]

    override func viewDidLoad() {
            super.viewDidLoad()
            see.btn.tag = 0
    }

    @IBAction func carbsButton(_ sender: Any) {
            button.setImage(UIImage(named: circleArray[btn.tag % 3]),forState:Normal)
            btn.tag = ban.tag + 1
    }

Do in this manner you will definitely get what you want..If it solve the problem hit up arrow.


问:
Youtube video with hyphen not working in IOS
I am using Cordova YoutubeVideoPlayer Plugin in my ionic project. It works well in android.But in IOS, it is not working with video id having a hyphen(-) in it(eg: "6L-ZHjUhcQY"). It works fine with all other urls. How can I solve this. </p>

```<code>.controller('menuController', function () {
    var id = "6L-ZHjUhcQY";
    YoutubeVideoPlayer.openVideo(id);
});
</code>```

答:
Fixed the ios issue by updating some files
https://github.com/fingentffts/CordovaYoutubeVideoPlayer

Now I found some issue in android tabs.

Videos are playing even if the screen is locked. And also hyphen video are not playing in samsung tab.

Body:
I am using Cordova YoutubeVideoPlayer Plugin in my ionic project. It works well in android.But in IOS, it is not working with video id having a hyphen(-) in it(eg: "6L-ZHjUhcQY"). It works fine with all other urls. How can I solve this.

.controller('menuController', function () {
    var id = "6L-ZHjUhcQY";
    YoutubeVideoPlayer.openVideo(id);
});


问:
GitHub deleted my previous commits
Please! I lost all my day's work.

I created a github repository... I've been working all day doing git add -A and commit but I never did a push. I changed a readme directly on the page (not knowing I was going to have problems to merge those same branches).

When I tried to make git push after all day's rok the following happened:

```<code>To https://github.com/NEGU93/Steganography.git
 ! [rejected]        master -> master (fetch first)
error: failed to push some refs to 'https://github.com/NEGU93/Steganography.git'
hint: Updates were rejected because the remote contains work that you do
hint: not have locally. This is usually caused by another repository pushing
hint: to the same ref. You may want to first integrate the remote changes
hint: (e.g., 'git pull ...') before pushing again.
hint: See the 'Note about fast-forwards' in 'git push --help' for details.
</code>```

So I tried ta git pull --rebase but it started crashing some things I don't know what it is:

```<code>remote: Counting objects: 3, done.
remote: Compressing objects: 100% (3/3), done.
remote: Total 3 (delta 0), reused 0 (delta 0), pack-reused 0
Unpacking objects: 100% (3/3), done.
From https://github.com/NEGU93/Steganography
   6161279..44d1f0f  master     -> origin/master
      0 [main] expr 8516 open_stackdumpfile: Dumping stack trace to expr.exe.stackdump
      0 [main] cat 15632 open_stackdumpfile: Dumping stack trace to cat.exe.stackdump
      0 [main] rm 4660 open_stackdumpfile: Dumping stack trace to rm.exe.stackdump
^C
</code>```

I put ctrl+C to stop the crashin there. So I made a git fetch and then a git push of my work:

```<code>fatal: You are not currently on a branch.
To push the history leading to the current (detached HEAD)
state now, use

    git push origin HEAD:<name-of-remote-branch>
</code>```

So I did as suggested and made a git push to master:

```<code>git push origin HEAD:master
Counting objects: 6, done.
Delta compression using up to 4 threads.
Compressing objects: 100% (5/5), done.
Writing objects: 100% (5/5), 1.49 KiB | 0 bytes/s, done.
Total 5 (delta 1), reused 0 (delta 0)
remote: Resolving deltas: 100% (1/1), done.
To https://github.com/NEGU93/Steganography.git
   44d1f0f..c3b8393  HEAD -> master
</code>```

But now when I got back the work was not there... Help! I don't know what to do and I'm starting to panic. I think the problem is with git fetch. Is there a way to get all my work back???

答:
Use git reflog to see past commits, then use the commit's hash to reset hard e.g.:

```<code>git reset --hard e870e41
</code>```

See How can I recover a lost commit in Git?

Title: GitHub deleted my previous commits

Body:
Please! I lost all my day's work.

I created a github repository... I've been working all day doing git add -A and commit but I never did a push. I changed a readme directly on the page (not knowing I was going to have problems to merge those same branches).

When I tried to make git push after all day's rok the following happened:

To https://github.com/NEGU93/Steganography.git
 ! [rejected]        master -> master (fetch first)
error: failed to push some refs to 'https://github.com/NEGU93/Steganography.git'
hint: Updates were rejected because the remote contains work that you do
hint: not have locally. This is usually caused by another repository pushing
hint: to the same ref. You may want to first integrate the remote changes
hint: (e.g., 'git pull ...') before pushing again.
hint: See the 'Note about fast-forwards' in 'git push --help' for details.

So I tried ta git pull --rebase but it started crashing some things I don't know what it is:

remote: Counting objects: 3, done.
remote: Compressing objects: 100% (3/3), done.
remote: Total 3 (delta 0), reused 0 (delta 0), pack-reused 0
Unpacking objects: 100% (3/3), done.
From https://github.com/NEGU93/Steganography
   6161279..44d1f0f  master     -> origin/master
      0 [main] expr 8516 open_stackdumpfile: Dumping stack trace to expr.exe.stackdump
      0 [main] cat 15632 open_stackdumpfile: Dumping stack trace to cat.exe.stackdump
      0 [main] rm 4660 open_stackdumpfile: Dumping stack trace to rm.exe.stackdump
^C

I put ctrl+C to stop the crashin there. So I made a git fetch and then a git push of my work:

fatal: You are not currently on a branch.
To push the history leading to the current (detached HEAD)
state now, use

    git push origin HEAD:<name-of-remote-branch>

So I did as suggested and made a git push to master:

git push origin HEAD:master
Counting objects: 6, done.
Delta compression using up to 4 threads.
Compressing objects: 100% (5/5), done.
Writing objects: 100% (5/5), 1.49 KiB | 0 bytes/s, done.
Total 5 (delta 1), reused 0 (delta 0)
remote: Resolving deltas: 100% (1/1), done.
To https://github.com/NEGU93/Steganography.git
   44d1f0f..c3b8393  HEAD -> master

But now when I got back the work was not there... Help! I don't know what to do and I'm starting to panic. I think the problem is with git fetch. Is there a way to get all my work back???

Body:
Use git reflog to see past commits, then use the commit's hash to reset hard e.g.:

git reset --hard e870e41

See How can I recover a lost commit in Git?


问:
Angular: ng is not recognized as a command
C:\Users\Vivek Ghanchi>ng
'ng' is not recognized as an internal or external command,
operable program or batch file.

I have  installed  angular CLI but it is showing me the ng is not recognized  is there any solution

答:
I solved it few days ago, after having the same problem with other global modules, by adding to:

Environment Tables -> System variables -> Path:

C:\Users\Administrator\AppData\Roaming\npm\node_modules\angular-cli\bin;C:\Program Files\MongoDB\Server\3.2\bin

Note that it must not have any spaces after ;
That turned out to be my problem.


答:
Create an array of status you want to check and then use contains. something like this.   </p>

```<code>var statusList = new[] {"a", "b"};

.Where(x=> x.UserID == 1 &&  statusList.Contains(x.status));
</code>```

Title: How to use OR operator in Linq

Body:
I want to use OR function in my linq query.
Ex:
Sql:

select * from tblusers where userid=1 and status='a' or status='b';

Linq:

var result= _Repository.selectAll().where(x=>x.UserID==1 && x.status=="a" OR x.status=="B");

It's does work for linq query. so does anyone have any idea?

Body:
Create an array of status you want to check and then use contains. something like this.

var statusList = new[] {"a", "b"};

.Where(x=> x.UserID == 1 &&  statusList.Contains(x.status));


问:
how to make div to new line
i am beginner to css.

i want to make new div into new line like this,

i try my code like this

```<code><style>
div{
  display:inline-block;
  float:left;
  color:#fff;
  font-size:20px;
}

.one{
  width:100px;
  height:100px;
  background:red;
}
.three{
    width:100px;
  height:100px;
}

.four{
  width:150px;
  height:50px;
background:darkblue;
}
.five{
  width:150px;
  height:50px;
background:blue;
}
 </style>

<div class="one">image</div>

<div class="three">
  <div class="four">name</div>
  <div class="five">desc</div>
</div>

<div class="one">image</div>

<div class="three">
  <div class="four">name</div>
  <div class="five">desc</div>
</div>

<div class="one">image</div>

<div class="three">
  <div class="four">name</div>
  <div class="five">desc</div>
</div>
</code>```

but result like this

how to move, the second image to new line..
pls anybody help me. i ll appreciate your answer

答:
you can use something like this.

.box-wrapper {
        border: 1px solid #000;
        width: 100%;
        display: block;
        position: relative;
    }
    .box-wrapper:before, .box-wrapper:after{
      clear:both;
      display:table;
      content:"";
    }
    .box-tall {
        width: 50%;
        background:#ded9d9;
        height: 200px;
        float: left;
    }
    .box-left {
        width: 50%;
        float: left;
    }
    .box-1 {
        background: #8f8fde;
        height: 100px;
    }
    .box-2 {
        background: #d2c47a;
        height: 100px;
    }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="box-wrapper">
      <div class="box-tall">
         tall
      </div>
      <div class="box-left">
        <div class="box-1">top</div>
         <div class="box-2">bottom</div>
      </div>
    </div></code>```

Title: how to make div to new line

Body:
i am beginner to css.

i want to make new div into new line like this,

i try my code like this

image

name

desc

image

name

desc

image

name

desc

but result like this

how to move, the second image to new line..
pls anybody help me. i ll appreciate your answer

Body:
you can use something like this.

.box-wrapper {
        border: 1px solid #000;
        width: 100%;
        display: block;
        position: relative;
    }
    .box-wrapper:before, .box-wrapper:after{
      clear:both;
      display:table;
      content:"";
    }
    .box-tall {
        width: 50%;
        background:#ded9d9;
        height: 200px;
        float: left;
    }
    .box-left {
        width: 50%;
        float: left;
    }
    .box-1 {
        background: #8f8fde;
        height: 100px;
    }
    .box-2 {
        background: #d2c47a;
        height: 100px;
    }

<div class="box-wrapper">
      <div class="box-tall">
         tall
      </div>
      <div class="box-left">
        <div class="box-1">top</div>
         <div class="box-2">bottom</div>
      </div>
    </div>


问:
Android: Unable to insert data into SQLite using DbHelper and Contract class
```<code>public class Main2Activity extends AppCompatActivity {
    private EditText editText1, editText2, editText3, editText4;
    private Button button;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        editText1 = (EditText) findViewById(R.id.editText);
        editText2 = (EditText) findViewById(R.id.editText2);
        editText3 = (EditText) findViewById(R.id.editText3);
        editText4 = (EditText) findViewById(R.id.editText4);

        button = (Button) findViewById(R.id.button3);

        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String un, pw, cpw, ph;

                un = editText1.getText().toString();
                pw = editText2.getText().toString();
                cpw = editText3.getText().toString();
                ph = editText4.getText().toString();

                DbHelper dbHelpero = new DbHelper(Main2Activity.this);
                SQLiteDatabase db = dbHelpero.getWritableDatabase();

                ContentValues values = new ContentValues();
                values.put(Entry.C_UNAME, un);
                values.put(Entry.C_PASS, pw);
                values.put(Entry.C_CPASS, cpw);
                values.put(Entry.C_PNO, ph);

                long newRowId = db.insert(Entry.TABLE_NAME, null, values);

                if (newRowId == -1) {
                    Toast.makeText(getApplicationContext(), "Error while adding", Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(getApplicationContext(), "Yo Registration is complete", Toast.LENGTH_SHORT).show();
                }
            }
        });
    }
}
</code>```

Here is the Contract.java

```<code>public class Contract {

    private Contract() {

    }

    public static final class Entry implements BaseColumns {
        public final static String TABLE_NAME = "details";
        public final static String _ID = BaseColumns._ID;
        public final static String C_UNAME = "uname";
        public final static String C_PASS = "pw";
        public final static String C_CPASS = "cpw";
        public final static String C_PNO = "pno";

    }
}
</code>```

And the DbHelper.java

```<code>public class DbHelper extends SQLiteOpenHelper {
    public static final String LOG_TAG = DbHelper.class.getSimpleName();
    public final static String DATABASE_NAME = "contacts.db";
    private static final int DATABASE_VERSION = 1;

    public DbHelper(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        String CREATE_TABLE = "CREATE TABLE " + Entry.TABLE_NAME + " ("
                + Entry._ID + " TEXT PRIMARY KEY AUTOINCREMENT, "
                + Entry.C_UNAME + " TEXT, "
                + Entry.C_PASS + " TEXT, "
                + Entry.C_CPASS + " TEXT, "
                + Entry.C_PNO + " TEXT" + ")";

        db.execSQL(CREATE_TABLE);
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

    }
}
</code>```

There are no syntax errors but still, the app is crashing.

答:
Replace your CREATE_TABLE query with:

```<code>String CREATE_TABLE = "CREATE TABLE " + Entry.TABLE_NAME + " ("
                + Entry._ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
                + Entry.C_UNAME + " TEXT, "
                + Entry.C_PASS + " TEXT, "
                + Entry.C_CPASS + " TEXT, "
                + Entry.C_PNO + " TEXT" + ")";
</code>```

You can't have a TEXT type have an AUTOINCREMENT property as you currently have it on your _ID field. You need to change it to be an INTEGER so it can be used as PRIMARY KEY and then have it AUTOINCREMENT

Body:
public class Main2Activity extends AppCompatActivity {
    private EditText editText1, editText2, editText3, editText4;
    private Button button;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        editText1 = (EditText) findViewById(R.id.editText);
        editText2 = (EditText) findViewById(R.id.editText2);
        editText3 = (EditText) findViewById(R.id.editText3);
        editText4 = (EditText) findViewById(R.id.editText4);

        button = (Button) findViewById(R.id.button3);

        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String un, pw, cpw, ph;

                un = editText1.getText().toString();
                pw = editText2.getText().toString();
                cpw = editText3.getText().toString();
                ph = editText4.getText().toString();

                DbHelper dbHelpero = new DbHelper(Main2Activity.this);
                SQLiteDatabase db = dbHelpero.getWritableDatabase();

                ContentValues values = new ContentValues();
                values.put(Entry.C_UNAME, un);
                values.put(Entry.C_PASS, pw);
                values.put(Entry.C_CPASS, cpw);
                values.put(Entry.C_PNO, ph);

                long newRowId = db.insert(Entry.TABLE_NAME, null, values);

                if (newRowId == -1) {
                    Toast.makeText(getApplicationContext(), "Error while adding", Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(getApplicationContext(), "Yo Registration is complete", Toast.LENGTH_SHORT).show();
                }
            }
        });
    }
}

Here is the Contract.java

public class Contract {

    private Contract() {

    }

    public static final class Entry implements BaseColumns {
        public final static String TABLE_NAME = "details";
        public final static String _ID = BaseColumns._ID;
        public final static String C_UNAME = "uname";
        public final static String C_PASS = "pw";
        public final static String C_CPASS = "cpw";
        public final static String C_PNO = "pno";

    }
}

And the DbHelper.java

public class DbHelper extends SQLiteOpenHelper {
    public static final String LOG_TAG = DbHelper.class.getSimpleName();
    public final static String DATABASE_NAME = "contacts.db";
    private static final int DATABASE_VERSION = 1;

    public DbHelper(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        String CREATE_TABLE = "CREATE TABLE " + Entry.TABLE_NAME + " ("
                + Entry._ID + " TEXT PRIMARY KEY AUTOINCREMENT, "
                + Entry.C_UNAME + " TEXT, "
                + Entry.C_PASS + " TEXT, "
                + Entry.C_CPASS + " TEXT, "
                + Entry.C_PNO + " TEXT" + ")";

        db.execSQL(CREATE_TABLE);
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

    }
}

There are no syntax errors but still, the app is crashing.

Body:
Replace your CREATE_TABLE query with:

String CREATE_TABLE = "CREATE TABLE " + Entry.TABLE_NAME + " ("
                + Entry._ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
                + Entry.C_UNAME + " TEXT, "
                + Entry.C_PASS + " TEXT, "
                + Entry.C_CPASS + " TEXT, "
                + Entry.C_PNO + " TEXT" + ")";

You can't have a TEXT type have an AUTOINCREMENT property as you currently have it on your _ID field. You need to change it to be an INTEGER so it can be used as PRIMARY KEY and then have it AUTOINCREMENT


问:
syntax error:missing after property id mongo shell 4:5
I'm getting syntax error

missing after property id@shell:4:5

```<code>db.movieDetails.updateOne({
    title:"The Martian"
} , {
    $set {
        poster:"http://howle.jpg"
       }
})
</code>```

db.movieDetails.updateOne({
    title:"The Martian"
} , {
    $set {
        poster:"http://howle.jpg"
       }
})
```

答:
```<code>db.movieDetails.updateOne({
    title:"The Martian"
} , {
    $set:{
        poster:"http://howle.jpg"
       }
})
</code>```

Missing : at $set operator

$set_Operator_Reference

Body:
I'm getting syntax error

missing after property id@shell:4:5

db.movieDetails.updateOne({
    title:"The Martian"
} , {
    $set {
        poster:"http://howle.jpg"
       }
})

db.movieDetails.updateOne({
    title:"The Martian"
} , {
    $set {
        poster:"http://howle.jpg"
       }
})

Body:
db.movieDetails.updateOne({
    title:"The Martian"
} , {
    $set:{
        poster:"http://howle.jpg"
       }
})

Missing : at $set operator

$set_Operator_Reference


问:
what is the simplest way to check for occurrence of character/substring in dataframe values?
consider a pandas dataframe that has values such as 'a - b'. I would like to check for the occurrence of '-' anywhere across all values of the dataframe without looping through individual columns. Clearly a check such as the following won't work:

if '-' in df.values

Any suggestions on how to check for this? Thanks.

答:
Using NumPy: np.core.defchararray.find(a,s) returns an array of indices where the substring s appears in a;
 if it's not present, -1 is returned.

```<code>(np.core.defchararray.find(df.values.astype(str),'-') > -1).any()
</code>```

returns True if '-' is present anywhere in df.

Body:
Using NumPy: np.core.defchararray.find(a,s) returns an array of indices where the substring s appears in a;
 if it's not present, -1 is returned.

(np.core.defchararray.find(df.values.astype(str),'-') > -1).any()

returns True if '-' is present anywhere in df.


答:
Basically, you do not have an attached canvas to the DOM.

Create a html file with <canvas id="root"></canvas>;

var canvas = document.getElementById("root");

Title: Why is nothing appearing on my canvas?

Body:
I am such a noob and I have no idea why nothing is appearing on my canvas. Can someone help me out? I wanted to have a black box on my canvas, that was the intention anyway.

var canvas = document.createElement("canvas");
var ctx = canvas.getContext("2d");
canvas.width = 1040;
canvas.height = 400;
canvas.style.display='block';
canvas.style.marginLeft="auto";
canvas.style.marginRight="auto";

var mainFunction= function(){
ctx.fillStyle = "rgb(0, 0, 0)";
ctx.beginPath();
ctx.rect(0, 0, canvas.width, canvas.height);
ctx.closePath();
ctx.fill();
requestAnimationFrame(mainFunction);
};

mainFunction();


问:
How to change pixel color on the fly in iPhone camera preview window?
I am using UIImagePickerController to take photos on iPhone. I'd like to adjust the photo on the fly, it appears that I could use UIImagePickerController to adjust the shape of the photo on the fly, but I am not able to find a way to change the color on the fly. For example, change all the color to black/white. </p>

<p>Thanks. </p>

答:
The best way to do this is with an AVCaptureSession object. I'm doing exactly what you're talking about in my free app "Live Effects Cam"

There are several code examples on-line that a will help you implement this too. Here is a sample chunk of code that might help:

```<code>- (void) activateCameraFeed
    {
    videoSettings = nil;

#if USE_32BGRA
    pixelFormatCode = [[NSNumber alloc] initWithUnsignedInt:(unsigned int)kCVPixelFormatType_32BGRA];
    pixelFormatKey = [[NSString alloc] initWithString:(NSString *)kCVPixelBufferPixelFormatTypeKey];
    videoSettings = [[NSDictionary alloc] initWithObjectsAndKeys:pixelFormatCode, pixelFormatKey, nil];
#endif

    videoDataOutputQueue = dispatch_queue_create("com.jellyfilledstudios.ImageCaptureQueue", NULL);

    captureVideoOutput = [[AVCaptureVideoDataOutput alloc] init];
    [captureVideoOutput setAlwaysDiscardsLateVideoFrames:YES];
    [captureVideoOutput setSampleBufferDelegate:self queue:videoDataOutputQueue];
    [captureVideoOutput setVideoSettings:videoSettings];
    [captureVideoOutput setMinFrameDuration:kCMTimeZero];

    dispatch_release(videoDataOutputQueue); // AVCaptureVideoDataOutput uses dispatch_retain() & dispatch_release() so we can dispatch_release() our reference now

    if ( useFrontCamera )
        {
        currentCameraDeviceIndex = frontCameraDeviceIndex;
        cameraImageOrientation = UIImageOrientationLeftMirrored;
        }
    else
        {
        currentCameraDeviceIndex = backCameraDeviceIndex;
        cameraImageOrientation = UIImageOrientationRight;
        }

    selectedCamera = [[AVCaptureDevice devices] objectAtIndex:(NSUInteger)currentCameraDeviceIndex];

    captureVideoInput = [AVCaptureDeviceInput deviceInputWithDevice:selectedCamera error:nil];

    captureSession = [[AVCaptureSession alloc] init];

    [captureSession beginConfiguration];

    [self setCaptureConfiguration];

    [captureSession addInput:captureVideoInput];
    [captureSession addOutput:captureVideoOutput];
    [captureSession commitConfiguration];
    [captureSession startRunning];
    }

// AVCaptureVideoDataOutputSampleBufferDelegate
// AVCaptureAudioDataOutputSampleBufferDelegate
//
- (void)captureOutput:(AVCaptureOutput *)captureOutput didOutputSampleBuffer:(CMSampleBufferRef)sampleBuffer fromConnection:(AVCaptureConnection *)connection
    {
    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];

    if ( captureOutput==captureVideoOutput )
        {
        [self performImageCaptureFrom:sampleBuffer fromConnection:connection];
        }

    [pool drain];
    }

- (void) performImageCaptureFrom:(CMSampleBufferRef)sampleBuffer
    {
    CVImageBufferRef imageBuffer;

    if ( CMSampleBufferGetNumSamples(sampleBuffer) != 1 )
        return;
    if ( !CMSampleBufferIsValid(sampleBuffer) )
        return;
    if ( !CMSampleBufferDataIsReady(sampleBuffer) )
        return;

    imageBuffer = CMSampleBufferGetImageBuffer(sampleBuffer);

    if ( CVPixelBufferGetPixelFormatType(imageBuffer) != kCVPixelFormatType_32BGRA )
        return;

    CVPixelBufferLockBaseAddress(imageBuffer,0);

    uint8_t *baseAddress = (uint8_t *)CVPixelBufferGetBaseAddress(imageBuffer);
    size_t bytesPerRow = CVPixelBufferGetBytesPerRow(imageBuffer);
    size_t width = CVPixelBufferGetWidth(imageBuffer);
    size_t height = CVPixelBufferGetHeight(imageBuffer);
    int bufferSize = bytesPerRow * height;

    uint8_t *tempAddress = malloc( bufferSize );
    memcpy( tempAddress, baseAddress, bytesPerRow * height );

    baseAddress = tempAddress;

    //
    // Apply affects to the pixels stored in (uint32_t *)baseAddress
    //
    //
    // example: grayScale( (uint32_t *)baseAddress, width, height );
    // example: sepia( (uint32_t *)baseAddress, width, height );
    //

    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
    CGContextRef newContext = nil;

    if ( cameraDeviceSetting != CameraDeviceSetting640x480 )        // not an iPhone4 or iTouch 5th gen
        newContext = CGBitmapContextCreate(baseAddress, width, height, 8, bytesPerRow, colorSpace,  kCGBitmapByteOrder32Little | kCGImageAlphaNoneSkipFirst);
    else
        newContext = CGBitmapContextCreate(baseAddress, width, height, 8, bytesPerRow, colorSpace, kCGBitmapByteOrder32Little | kCGImageAlphaPremultipliedFirst);

    CGImageRef newImage = CGBitmapContextCreateImage( newContext );
    CGColorSpaceRelease( colorSpace );
    CGContextRelease( newContext );

    free( tempAddress );

    CVPixelBufferUnlockBaseAddress(imageBuffer,0);

    if ( newImage == nil )
        {
        return;
        }

    // To be able to display the CGImageRef newImage in your UI you will need to do it like this
    // because you are running on a different thread here…
    //
    [self performSelectorOnMainThread:@selector(newCameraImageNotification:) withObject:(id)newImage waitUntilDone:YES];
    }
</code>```

Body:
I am using UIImagePickerController to take photos on iPhone. I'd like to adjust the photo on the fly, it appears that I could use UIImagePickerController to adjust the shape of the photo on the fly, but I am not able to find a way to change the color on the fly. For example, change all the color to black/white.

Thanks.

Body:
The best way to do this is with an AVCaptureSession object. I'm doing exactly what you're talking about in my free app "Live Effects Cam"

There are several code examples on-line that a will help you implement this too. Here is a sample chunk of code that might help:

- (void) activateCameraFeed
    {
    videoSettings = nil;

#if USE_32BGRA
    pixelFormatCode = [[NSNumber alloc] initWithUnsignedInt:(unsigned int)kCVPixelFormatType_32BGRA];
    pixelFormatKey = [[NSString alloc] initWithString:(NSString *)kCVPixelBufferPixelFormatTypeKey];
    videoSettings = [[NSDictionary alloc] initWithObjectsAndKeys:pixelFormatCode, pixelFormatKey, nil];
#endif

    videoDataOutputQueue = dispatch_queue_create("com.jellyfilledstudios.ImageCaptureQueue", NULL);

    captureVideoOutput = [[AVCaptureVideoDataOutput alloc] init];
    [captureVideoOutput setAlwaysDiscardsLateVideoFrames:YES];
    [captureVideoOutput setSampleBufferDelegate:self queue:videoDataOutputQueue];
    [captureVideoOutput setVideoSettings:videoSettings];
    [captureVideoOutput setMinFrameDuration:kCMTimeZero];

    dispatch_release(videoDataOutputQueue); // AVCaptureVideoDataOutput uses dispatch_retain() & dispatch_release() so we can dispatch_release() our reference now

    if ( useFrontCamera )
        {
        currentCameraDeviceIndex = frontCameraDeviceIndex;
        cameraImageOrientation = UIImageOrientationLeftMirrored;
        }
    else
        {
        currentCameraDeviceIndex = backCameraDeviceIndex;
        cameraImageOrientation = UIImageOrientationRight;
        }

    selectedCamera = [[AVCaptureDevice devices] objectAtIndex:(NSUInteger)currentCameraDeviceIndex];

    captureVideoInput = [AVCaptureDeviceInput deviceInputWithDevice:selectedCamera error:nil];

    captureSession = [[AVCaptureSession alloc] init];

    [captureSession beginConfiguration];

    [self setCaptureConfiguration];

    [captureSession addInput:captureVideoInput];
    [captureSession addOutput:captureVideoOutput];
    [captureSession commitConfiguration];
    [captureSession startRunning];
    }

// AVCaptureVideoDataOutputSampleBufferDelegate
// AVCaptureAudioDataOutputSampleBufferDelegate
//
- (void)captureOutput:(AVCaptureOutput *)captureOutput didOutputSampleBuffer:(CMSampleBufferRef)sampleBuffer fromConnection:(AVCaptureConnection *)connection
    {
    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];

    if ( captureOutput==captureVideoOutput )
        {
        [self performImageCaptureFrom:sampleBuffer fromConnection:connection];
        }

    [pool drain];
    }

- (void) performImageCaptureFrom:(CMSampleBufferRef)sampleBuffer
    {
    CVImageBufferRef imageBuffer;

    if ( CMSampleBufferGetNumSamples(sampleBuffer) != 1 )
        return;
    if ( !CMSampleBufferIsValid(sampleBuffer) )
        return;
    if ( !CMSampleBufferDataIsReady(sampleBuffer) )
        return;

    imageBuffer = CMSampleBufferGetImageBuffer(sampleBuffer);

    if ( CVPixelBufferGetPixelFormatType(imageBuffer) != kCVPixelFormatType_32BGRA )
        return;

    CVPixelBufferLockBaseAddress(imageBuffer,0);

    uint8_t *baseAddress = (uint8_t *)CVPixelBufferGetBaseAddress(imageBuffer);
    size_t bytesPerRow = CVPixelBufferGetBytesPerRow(imageBuffer);
    size_t width = CVPixelBufferGetWidth(imageBuffer);
    size_t height = CVPixelBufferGetHeight(imageBuffer);
    int bufferSize = bytesPerRow * height;

    uint8_t *tempAddress = malloc( bufferSize );
    memcpy( tempAddress, baseAddress, bytesPerRow * height );

    baseAddress = tempAddress;

    //
    // Apply affects to the pixels stored in (uint32_t *)baseAddress
    //
    //
    // example: grayScale( (uint32_t *)baseAddress, width, height );
    // example: sepia( (uint32_t *)baseAddress, width, height );
    //

    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
    CGContextRef newContext = nil;

    if ( cameraDeviceSetting != CameraDeviceSetting640x480 )        // not an iPhone4 or iTouch 5th gen
        newContext = CGBitmapContextCreate(baseAddress, width, height, 8, bytesPerRow, colorSpace,  kCGBitmapByteOrder32Little | kCGImageAlphaNoneSkipFirst);
    else
        newContext = CGBitmapContextCreate(baseAddress, width, height, 8, bytesPerRow, colorSpace, kCGBitmapByteOrder32Little | kCGImageAlphaPremultipliedFirst);

    CGImageRef newImage = CGBitmapContextCreateImage( newContext );
    CGColorSpaceRelease( colorSpace );
    CGContextRelease( newContext );

    free( tempAddress );

    CVPixelBufferUnlockBaseAddress(imageBuffer,0);

    if ( newImage == nil )
        {
        return;
        }

    // To be able to display the CGImageRef newImage in your UI you will need to do it like this
    // because you are running on a different thread here…
    //
    [self performSelectorOnMainThread:@selector(newCameraImageNotification:) withObject:(id)newImage waitUntilDone:YES];
    }


问:
How does one React component call a method in another React component?
My page contains two completely separate React components (different files, different classes, no parent-child relationship).

How can one component call an instance method in another component? The problem seems to be obtaining the instance of the target component.

EDIT: Both components share the same parent (i.e. they are rendered in the same render() method) but I still don't know how to pass the reference of the target component to the calling component.

答:
The short answer is: they don't.

It's not clear what you're trying to accomplish, so I can't speak to the specifics of your case, but the way React components "communicate" with one another is via state and props. For example, consider a Page component that has two child components, CompA and CompB, rendered something like this:

```<code><Page>
    <CompA />
    <CompB />
</Page>
</code>```

If CompA needs to pass something to CompB, this is done through state on the Page component, with that state exposed as props on CompA and CompB, something like this:

```<code>class Page extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            sharedValue: 42,
        };
    }

    onChangeSharedValue(newValue) {
        this.setState({ sharedValue: newValue });
    }

    render() {
        return (
            <div>
                <CompA
                    sharedValue={this.state.sharedValue}
                    onChange={this.onChangeSharedValue}
                />
                <CompB
                    sharedValue={this.state.sharedValue}
                    onChange={this.onChangeSharedValue}
                />
            </div>
        );
    }
}
</code>```

If CompA needs to change the shared value, it calls the onChange handler, which will change the state on the Page component. That value will then be propagated down to the CompB component.

There is no direct communication between components like you're describing; it is all done via state and props.

Body:
The short answer is: they don't.

It's not clear what you're trying to accomplish, so I can't speak to the specifics of your case, but the way React components "communicate" with one another is via state and props. For example, consider a Page component that has two child components, CompA and CompB, rendered something like this:

<Page>
    <CompA />
    <CompB />
</Page>

If CompA needs to pass something to CompB, this is done through state on the Page component, with that state exposed as props on CompA and CompB, something like this:

class Page extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            sharedValue: 42,
        };
    }

    onChangeSharedValue(newValue) {
        this.setState({ sharedValue: newValue });
    }

    render() {
        return (
            <div>
                <CompA
                    sharedValue={this.state.sharedValue}
                    onChange={this.onChangeSharedValue}
                />
                <CompB
                    sharedValue={this.state.sharedValue}
                    onChange={this.onChangeSharedValue}
                />
            </div>
        );
    }
}

If CompA needs to change the shared value, it calls the onChange handler, which will change the state on the Page component. That value will then be propagated down to the CompB component.

There is no direct communication between components like you're describing; it is all done via state and props.


问:
Angular 2 ui-router: inject a service to onEnter
I'm using ui-router in my Angular 2 project. When entering a state I need to call a function in a service to do some updates. My codes are like this:

```<code>import { dataService } from '../data.service';
export const stateA = {
    name: 'stateA',
    url: '',
    onEnter: function(trans, state, dataService) {
        dataService.update();
    }
}
</code>```

However, it seems I can't inject dataService to onEnter this way. Anyone knows the correct way to do it? Thanks!

答:
Angular 2 doesn't use the same style of injection as Angular 1.  Only services registered with DI can be injected automatically (using Typescript)

To inject manually, get the injector from the transition and fetch the Data Service (by whatever token it is registered using in DI).

```<code>export const stateA = {
    name: 'stateA',
    url: '',
    onEnter: function(trans, state) {
        const dataService = trans.injector().get('dataService');
        dataService.update();
    }
}
</code>```

However, I see that you are importing dataService using ES6 module import/export.  Perhaps you don't need to use DI at all because you already have a reference to it?

```<code>import { dataService } from '../data.service';
export const stateA = {
    name: 'stateA',
    url: '',
    onEnter: function(trans, state) {
        dataService.update();
    }
}
</code>```

Body:
I'm using ui-router in my Angular 2 project. When entering a state I need to call a function in a service to do some updates. My codes are like this:

import { dataService } from '../data.service';
export const stateA = {
    name: 'stateA',
    url: '',
    onEnter: function(trans, state, dataService) {
        dataService.update();
    }
}

However, it seems I can't inject dataService to onEnter this way. Anyone knows the correct way to do it? Thanks!

Body:
Angular 2 doesn't use the same style of injection as Angular 1.  Only services registered with DI can be injected automatically (using Typescript)

To inject manually, get the injector from the transition and fetch the Data Service (by whatever token it is registered using in DI).

export const stateA = {
    name: 'stateA',
    url: '',
    onEnter: function(trans, state) {
        const dataService = trans.injector().get('dataService');
        dataService.update();
    }
}

However, I see that you are importing dataService using ES6 module import/export.  Perhaps you don't need to use DI at all because you already have a reference to it?

import { dataService } from '../data.service';
export const stateA = {
    name: 'stateA',
    url: '',
    onEnter: function(trans, state) {
        dataService.update();
    }
}


答:
"Props down, Events up."

If you provide us a specific example of what you're looking for, I can update this post with a more specific response.

But in general, there are a couple of strategies that you can take.  Some of them are presented here.

The preferred approach is to simply move your calling method to the parent component.  It's a common strategy in React.

If you're not able to, then the next step would be to write an event handler for the parent, and then pass this event down to the first child component.

Use this event to pass information up to the parent, so that when it gets triggered, data can be passed as props down to the second component.

Title: How does one React component call a method in another React component?

Body:
My page contains two completely separate React components (different files, different classes, no parent-child relationship).

How can one component call an instance method in another component? The problem seems to be obtaining the instance of the target component.

EDIT: Both components share the same parent (i.e. they are rendered in the same render() method) but I still don't know how to pass the reference of the target component to the calling component.


问:
where clause not working in cakephp 3.4
I want to use category listing in subcategory controller. I am trying following methods to get categories which status are 1.

```<code>$this->loadModel('Categories');
$query = $this->Categories->find();
$query->where(['cat_status' => 1]);
</code>```

This is returning following output

'SELECT Categories.id AS Categories__id, Categories.cat_name AS
      Categories__cat_name, Categories.cat_status AS Categories__cat_status
      FROM categories Categories WHERE cat_status = :c0'

I don't know where it is getting:c0. Then I used another code which is giving all the list but where clause is not working.

```<code>$this->loadModel('Categories');
$categories = $this->Categories->find('all',[
                                            'where' => (['cat_status'=>1]),
                                            'limit' => 5,
                                            'order' => 'Categories.id DESC'
    ]);
debug($categories);
</code>```

The output is

SELECT Categories.id AS Categories__id, Categories.cat_name AS
  Categories__cat_name, Categories.cat_status AS
  Categories__cat_status FROM categories Categories ORDER BY
  Categories.id DESC LIMIT 5

Please suggest a suitable way.

答:
You need to add ->first()
to your where clause, like so :

```<code>$query->where(['cat_status' => 1])->first();
</code>```

Title: where clause not working in cakephp 3.4

Body:
I want to use category listing in subcategory controller. I am trying following methods to get categories which status are 1.

$this->loadModel('Categories');
$query = $this->Categories->find();
$query->where(['cat_status' => 1]);

This is returning following output

'SELECT Categories.id AS Categories__id, Categories.cat_name AS
      Categories__cat_name, Categories.cat_status AS Categories__cat_status
      FROM categories Categories WHERE cat_status = :c0'

I don't know where it is getting:c0. Then I used another code which is giving all the list but where clause is not working.

$this->loadModel('Categories');
$categories = $this->Categories->find('all',[
                                            'where' => (['cat_status'=>1]),
                                            'limit' => 5,
                                            'order' => 'Categories.id DESC'
    ]);
debug($categories);

The output is

SELECT Categories.id AS Categories__id, Categories.cat_name AS
  Categories__cat_name, Categories.cat_status AS
  Categories__cat_status FROM categories Categories ORDER BY
  Categories.id DESC LIMIT 5

Please suggest a suitable way.

Body:
You need to add ->first()
to your where clause, like so :

$query->where(['cat_status' => 1])->first();


问:
Insert Image and set to circle in canvas
This is my code to insert image to canvas..

```<code><script src="https://rawgit.com/kangax/fabric.js/master/dist/fabric.min.js"></script>
<button onclick="addTexttitle()" type="button" class="text-left btn-block btn white">Set Image To Circle</button>
<input type="file" id="file">
        <canvas id="canvas" width="750" height="550"></canvas>
        <a href='' id='txt' target="_blank">Click Me!</a>
        <br />
        <img id="preview" />
</code>```

https://jsfiddle.net/javasalden/yn04k565/

how to complete button:

```<code><button onclick="addTexttitle()" type="button" class="text-left btn-block btn white">Set Image To Circle</button>
</code>```

when I click and image/element will be CIRCLE

答:
Hi I have created one example, please have a look at it, this is definatley be useful for you.

var createCache = function(requestFunction) {
    var cache = {};
    return function(key, callback) {
        if (!cache[key]) {
            cache[key] = $.Deferred(function(defer) {
                requestFunction(defer, key);
            }).promise();
        }
        return cache[key].done(drawImg);
    };
};

var loadImage = createCache(function(defer, url) {
    var image = new Image();
    function cleanUp() {
       image.onload = image.onerror = null;
    }

    defer.then(cleanUp, cleanUp);
    image.onload = function() {
        defer.resolve(url);
    };
    image.onerror = defer.reject;
    image.src = url;
});

var drawImg = function(img) {
    var tmpCanvas = document.createElement('canvas'),
        tmpCtx = tmpCanvas.getContext('2d'),
        image = new Image();

    image.src = img;
    tmpCanvas.width = image.width*2;
    tmpCanvas.height = image.height*2;

    // draw the cached images to temporary canvas and return the context
    tmpCtx.save();
        tmpCtx.beginPath();
            tmpCtx.arc(2*24, 2*24, 2*24, 0, Math.PI*2, true);
        tmpCtx.closePath();
        tmpCtx.clip();

    tmpCtx.drawImage(image, 0, 0, 4*24+2, 4*24+2);

        tmpCtx.beginPath();
            tmpCtx.arc(0, 0, 2, 0, Math.PI*2, true);
            tmpCtx.clip();
        tmpCtx.closePath();
    tmpCtx.restore();

    $('body').append(tmpCanvas);
};

var cacheImgs = function() {
    var imgs = [

        'https://cdn.pixabay.com/photo/2017/01/06/19/15/soap-bubble-1958650_960_720.jpg'
    ];

    for (var i = 0; i < imgs.length; i++) {
        var img = loadImage(imgs[i])/*.done(drawImg(imgs[i]))*/;
        // .done callback is what sends the canvases to where they need to go
    }
}
cacheImgs();```
<pre class="snippet-code-css lang-css prettyprint-override"><code>canvas { float: left; }</code>```

```

Body:
This is my code to insert image to canvas..

<button onclick="addTexttitle()" type="button" class="text-left btn-block btn white">Set Image To Circle</button>
<input type="file" id="file">
        <canvas id="canvas" width="750" height="550"></canvas>
        Click Me!

https://jsfiddle.net/javasalden/yn04k565/

how to complete button:

<button onclick="addTexttitle()" type="button" class="text-left btn-block btn white">Set Image To Circle</button>

when I click and image/element will be CIRCLE

Body:
Hi I have created one example, please have a look at it, this is definatley be useful for you.

var createCache = function(requestFunction) {
    var cache = {};
    return function(key, callback) {
        if (!cache[key]) {
            cache[key] = $.Deferred(function(defer) {
                requestFunction(defer, key);
            }).promise();
        }
        return cache[key].done(drawImg);
    };
};

var loadImage = createCache(function(defer, url) {
    var image = new Image();
    function cleanUp() {
       image.onload = image.onerror = null;
    }

    defer.then(cleanUp, cleanUp);
    image.onload = function() {
        defer.resolve(url);
    };
    image.onerror = defer.reject;
    image.src = url;
});

var drawImg = function(img) {
    var tmpCanvas = document.createElement('canvas'),
        tmpCtx = tmpCanvas.getContext('2d'),
        image = new Image();

    image.src = img;
    tmpCanvas.width = image.width*2;
    tmpCanvas.height = image.height*2;

    // draw the cached images to temporary canvas and return the context
    tmpCtx.save();
        tmpCtx.beginPath();
            tmpCtx.arc(2*24, 2*24, 2*24, 0, Math.PI*2, true);
        tmpCtx.closePath();
        tmpCtx.clip();

    tmpCtx.drawImage(image, 0, 0, 4*24+2, 4*24+2);

        tmpCtx.beginPath();
            tmpCtx.arc(0, 0, 2, 0, Math.PI*2, true);
            tmpCtx.clip();
        tmpCtx.closePath();
    tmpCtx.restore();

    $('body').append(tmpCanvas);
};

var cacheImgs = function() {
    var imgs = [

        'https://cdn.pixabay.com/photo/2017/01/06/19/15/soap-bubble-1958650_960_720.jpg'
    ];

    for (var i = 0; i < imgs.length; i++) {
        var img = loadImage(imgs[i])/*.done(drawImg(imgs[i]))*/;
        // .done callback is what sends the canvases to where they need to go
    }
}
cacheImgs();

canvas { float: left; }

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.2/jquery.min.js"></script>
<body></body>


问:
random numbers after a ? on an image is this for far expires headers?
I was pooking around a random site on the internet and noticed that on the images they have numbers prefixing it: icons-16.png?1292032550

I've heard of people optimising websites with far expires headers. If someone changes the content that doesn't change very often, the cache won't get refreshed. Ergo this new image won't get re-downloaded to someones cache. Because the filename has to change.

答:
Yes, the intent is probably to force a refresh of the browser cache.  However, I do not recommend this approach:

Many proxies (and possibly some browsers) simply will not cache anything with a query string, regardless of Cache-Control headers.  You're shooting yourself in the foot if you include a superfluous query string – you'll needlessly consume your own bandwidth sending images that should be cached, but aren't.

Depending on how you configure your server, user agents will periodically make a request for cached resources, with a If-Modified-Since and/or If-None-Match header.  If the client's cache is up to date, the server responds with 304 Not Modified and stops; otherwise it responds with a normal 200 OK and sends the new content.  You do not have to change a resource's file name in order for client caches to be updated when the resource changes. Trying to get clever with a query string only serves to defeat caching mechanisms.

That said, if you do optimize caching by setting an Expires date a year out (and if the Last Modified date of the resource is long ago), user agents may check for updates infrequently.  If this is unacceptable to you, you have two options: either reduce the amount of time before the resource expires (so that the browser will issue a GET request and you can respond with 304 or 200 as appropriate), or use "URL fingerprinting," where a random token is included in the path, instead of in the query string.  For example:

```<code>/img/a03f/image.png
</code>```

instead of

```<code>/img/image.png?a03f
</code>```

This way, your resources are still cached by proxies.  You'll probably want to look in to using mod_rewrite to allow you to include a token in the path.  Of course, you need to be able to change all references to this URL whenever you change the resource.

For further reading, I highly recommend Google's page speed best practices, specifically the section on optimizing caching.

Body:
Yes, the intent is probably to force a refresh of the browser cache.  However, I do not recommend this approach:

Many proxies (and possibly some browsers) simply will not cache anything with a query string, regardless of Cache-Control headers.  You're shooting yourself in the foot if you include a superfluous query string – you'll needlessly consume your own bandwidth sending images that should be cached, but aren't.

Depending on how you configure your server, user agents will periodically make a request for cached resources, with a If-Modified-Since and/or If-None-Match header.  If the client's cache is up to date, the server responds with 304 Not Modified and stops; otherwise it responds with a normal 200 OK and sends the new content.  You do not have to change a resource's file name in order for client caches to be updated when the resource changes. Trying to get clever with a query string only serves to defeat caching mechanisms.

That said, if you do optimize caching by setting an Expires date a year out (and if the Last Modified date of the resource is long ago), user agents may check for updates infrequently.  If this is unacceptable to you, you have two options: either reduce the amount of time before the resource expires (so that the browser will issue a GET request and you can respond with 304 or 200 as appropriate), or use "URL fingerprinting," where a random token is included in the path, instead of in the query string.  For example:

/img/a03f/image.png

instead of

/img/image.png?a03f

This way, your resources are still cached by proxies.  You'll probably want to look in to using mod_rewrite to allow you to include a token in the path.  Of course, you need to be able to change all references to this URL whenever you change the resource.

For further reading, I highly recommend Google's page speed best practices, specifically the section on optimizing caching.


问:
HTML 5 Canvas and QR Code
I'm using this repository qrcode to generate QR codes

This is my Jquery

```<code>    $(".generatetext").click(function() {
        var x = document.getElementById("textdata").value;
        $('#output').qrcode(x);
    });
</code>```

so this gets the input value of the user and generates the QR code on click on a button.
but every time I click "Generate Button" it generates a new QR code in a new line, doesn't replace the existing one.

```<code><canvas width="256" height="256"></canvas>-> on first click
<canvas width="256" height="256"></canvas>-> on second click
<canvas width="256" height="256"></canvas>-> on third click
</code>```

DEMO -<- generate 2 or 3 qr codes

it creates a list of QR codes. how do I solve this problem?
I want just one QR code to be shown every time I click on Generate button

答:
Please check working solution below.

$(".generatetext").click(function(e) {
    e.preventDefault();
    var x = $("#textdata").val();
    $('#output').html('').qrcode(x);
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#output{border:1px solid #eee;min-height:200px;width:200px;}</code>```

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>

  <form class="form-inline">

      <button class="btn btn-primary generatetext">Generate QR Code</button>
      <input type="text" class="form-control" id="textdata" placeholder="Enter text for QR Code" />

  </form>

```
</div>
</div>
</p>

<p>Please check below mentioned solution.</p>

```$(".generatetext").click(function() {
    var x = document.getElementById("textdata").value;
     $('#output').html('').qrcode(x);
});
```

Let me know if it not works

Title: HTML 5 Canvas and QR Code

Body:
I'm using this repository qrcode to generate QR codes

This is my Jquery

    $(".generatetext").click(function() {
        var x = document.getElementById("textdata").value;
        $('#output').qrcode(x);
    });

so this gets the input value of the user and generates the QR code on click on a button.
but every time I click "Generate Button" it generates a new QR code in a new line, doesn't replace the existing one.

<canvas width="256" height="256"></canvas>-> on first click
<canvas width="256" height="256"></canvas>-> on second click
<canvas width="256" height="256"></canvas>-> on third click

DEMO -<- generate 2 or 3 qr codes

it creates a list of QR codes. how do I solve this problem?
I want just one QR code to be shown every time I click on Generate button

Body:
Please check working solution below.

$(".generatetext").click(function(e) {
    e.preventDefault();
    var x = $("#textdata").val();
    $('#output').html('').qrcode(x);
});

#output{border:1px solid #eee;min-height:200px;width:200px;}

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.qrcode/1.0/jquery.qrcode.min.js"></script>
<div class="container">
  <form class="form-inline">
    <div class="form-group">
      <button class="btn btn-primary generatetext">Generate QR Code</button>
      <input type="text" class="form-control" id="textdata" placeholder="Enter text for QR Code" />
    </div>
  </form>
  <div class="container">
    <div id="output" class="text-center"></div>
  </div>
</div>

Please check below mentioned solution.

$(".generatetext").click(function() {
    var x = document.getElementById("textdata").value;
     $('#output').html('').qrcode(x);
});

Let me know if it not works


问:
RecyclerView: how to clear cached/recycled views?
I use a RecyclerView to display a list of items with a list layout. I switch from a list layout to a grid layout, showing just a subset of all the data when in grid layout. This switch uses a different layout XML than when list layout is presented.

All this works well, except that when I scroll, recycled (cached?) list layout views populate the grid, mixed in with proper grid layout view items. In other words, instead of using my layout_grid.xml for each item's layout in the RecyclerView, I get items using the layout_list.xml layout, but in a grid format.

This tells me the LayoutManager is working correctly, switching from a list to grid layout. But not all item view items are recreated using the grid xml layout, but rather recycled list layout views are used.

I tried RecyclerView.removeAllViews(), RecyclerView.removeAllViewInLayout(), RecyclerView.swapAdapter() (to force adapter reload), all to no avail.

Update:

If I scroll two positions down in the list, and then switch from list to grid, the first two positions do not go through onCreateViewHolder(), but straight to onBindViewHolder() and are therefore not forced to use the grid layout xml. Instead those first two position items are recycled (I think) and displayed in their list layout format.

答:
Just do this
Simple !!</p>

```<code>adapter.notifyItemRangeRemoved(0,adapter.getItemCount());

  adapter.notifyItemRangeRemoved(0,adapter.getItemCount());
                   for (int i = 0; i < array.length(); i++) {
                        JSONObject object = array.getJSONObject(i);
                         ////
                        data_List.add(data);
                    }
</code>```

Body:
Just do this
Simple !!

adapter.notifyItemRangeRemoved(0,adapter.getItemCount());

  adapter.notifyItemRangeRemoved(0,adapter.getItemCount());
                   for (int i = 0; i < array.length(); i++) {
                        JSONObject object = array.getJSONObject(i);
                         ////
                        data_List.add(data);
                    }


问:
Textbox mandatory on clicking radio button
I have a view where add to electronic has 2 radiobuttons yes & no. And a submit button.When yes radiobutton is clicked. the quantity textbox should not be empty.but it can be empty if no radiobutton is clicked.This functionality should work when submit button is clicked with yes radiobutton is selected.any ideas?
MY VIEW:

```<code> <HTML>
    <head>
    radio
    </head>
    <body>
    <form id=radio>
     Add to electronic  <input type="radio" name="yes"onclick="validate(_this)"id="yes"/>Yes<input type="radio" name="yes" id="no" />No<br />
    <label>Quantity</label><input type="text"size="25"name="dir"id="dir" required/>
<button type=submit name=insert>insert</button>
</body>
<div>
<script src="~/Scripts/radiobuttonvalidation.js"></script>
</div>
</html>
</code>```

im new to mvc and javascript help me with javascript code too.and the way i should link it with my view.
Javascript:

```<code>    function validate(_this) {
    if ($(_this).attr('id') == "yes") {
        $('#dir').attr('required');
        alert("Text Box required");
    }
    else {
        $('#dir').removeAttr('required');
        alert("Text Box not required");
    }
}
</code>```

答:
$(function() {
  $("#radio").submit(function() {
    if ($('#yes').is(':checked') && !$.trim($('#quantity').val())) {
      alert("Please input the quantity.");
      return false;
    }
  });
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code>    <html>
        <head>
            <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
        </head>
        <body>
            <form id=radio>
                Add to electronic <input type="radio" name="yes" id="yes" />Yes<input type="radio" name="yes" id="no" />No<br />
                <label>Quantity</label><input type="text" size="25" name="quantity" id="quantity" />
                <button type=submit name=insert>insert</button>
            </form>
        </body>
    </html></code>```

Body:
I have a view where add to electronic has 2 radiobuttons yes & no. And a submit button.When yes radiobutton is clicked. the quantity textbox should not be empty.but it can be empty if no radiobutton is clicked.This functionality should work when submit button is clicked with yes radiobutton is selected.any ideas?
MY VIEW:

    radio

    <form id=radio>
     Add to electronic  <input type="radio" name="yes"onclick="validate(_this)"id="yes"/>Yes<input type="radio" name="yes" id="no" />No

    Quantity<input type="text"size="25"name="dir"id="dir" required/>
<button type=submit name=insert>insert</button>

im new to mvc and javascript help me with javascript code too.and the way i should link it with my view.
Javascript:

    function validate(_this) {
    if ($(_this).attr('id') == "yes") {
        $('#dir').attr('required');
        alert("Text Box required");
    }
    else {
        $('#dir').removeAttr('required');
        alert("Text Box not required");
    }
}

Body:
$(function() {
  $("#radio").submit(function() {
    if ($('#yes').is(':checked') && !$.trim($('#quantity').val())) {
      alert("Please input the quantity.");
      return false;
    }
  });
});

    <html>
        <head>
            <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
        </head>
        <body>
            <form id=radio>
                Add to electronic <input type="radio" name="yes" id="yes" />Yes<input type="radio" name="yes" id="no" />No<br />
                <label>Quantity</label><input type="text" size="25" name="quantity" id="quantity" />
                <button type=submit name=insert>insert</button>
            </form>
        </body>
    </html>


问:
Eslint version automatically downgrading on init
I'm installing ESLint on a project with the following command:

```<code>npm install --save-dev eslint@latest
</code>```

which gets me the 4.1.1 version of the package.

After i init it with the command:

```<code>./node_modules/.bin/eslint --init
</code>```

I follow the instructions to use Airbnb codestyle and i get downgraded to version 3.19.0.

How can i get it to use version 4.0.0 atleast?

答:
Working as intended.

Quoting @kaicataldo on github:

"A number of breaking changes were introduced on the plugin authoring side of things in ESLint v4. Installing ESLint v4 with a plugin that has not been updated yet could result in a broken installation, so the behavior you're seeing is intentional to ensure that everything works together."

Body:
I'm installing ESLint on a project with the following command:

npm install --save-dev eslint@latest

which gets me the 4.1.1 version of the package.

After i init it with the command:

./node_modules/.bin/eslint --init

I follow the instructions to use Airbnb codestyle and i get downgraded to version 3.19.0.

How can i get it to use version 4.0.0 atleast?


问:
How to animate child components in angular 2?
I tried to add animation on the parent component so when child components :enter or :leave, a sliding effect would show. Here is my parent @component:

```<code>  @component({
   selector: 'plan',
   templateUrl: '../templates/plan.tpl.html',
   styleUrls: ['../../../../assets/css/plan.scss'],
   animations: [
     trigger('stepAnimation', [
       transition(':enter', [
         style({transform: 'translateX(100%)'}),
         animate('0.5s ease-in-out', style({transform: 'translateX(0%)'}))
       ]),
    transition(':leave', [  // before 2.1: transition('* => void', [
      style({transform: 'translateX(0%)'}),
      animate('0.5s ease-in-out', style({transform: 'translateX(-100%)'}))
    ])
  ])]

})
</code>```

Then I added the animation selector to the child component in the template as follow:

```<code><start *ngIf="currentPage == 'start'" @stepAnimation></start>
<about *ngIf="currentPage == 'about'" @stepAnimation></about>
<family *ngIf="currentPage == 'family'" @stepAnimation></family>
</code>```

The animation doesn't work. Then I add the animation code inside each component and add @stepAnimation to the parent tag of each template. This way, I get the enter animation but not leave. I guess that's because of the ngIf on the parent but regardless, there are a lot of repeat animation code with this. Would there be anyway to handle the animation on the parent level?

答:
The problem is that the custom elements, <start>, <family>, and <about> have no styling and therefore display defaults to inline, which can't be translated. Simply add this to your parent stylesheet:

```<code>about, start, family {
    display: block;
    /*Any other layout code, e.g. position:absolute */
}
</code>```

And it should work.

Body:
I tried to add animation on the parent component so when child components :enter or :leave, a sliding effect would show. Here is my parent @component:

  @component({
   selector: 'plan',
   templateUrl: '../templates/plan.tpl.html',
   styleUrls: ['../../../../assets/css/plan.scss'],
   animations: [
     trigger('stepAnimation', [
       transition(':enter', [
         style({transform: 'translateX(100%)'}),
         animate('0.5s ease-in-out', style({transform: 'translateX(0%)'}))
       ]),
    transition(':leave', [  // before 2.1: transition('* => void', [
      style({transform: 'translateX(0%)'}),
      animate('0.5s ease-in-out', style({transform: 'translateX(-100%)'}))
    ])
  ])]

})

Then I added the animation selector to the child component in the template as follow:

<start *ngIf="currentPage == 'start'" @stepAnimation></start>
<about *ngIf="currentPage == 'about'" @stepAnimation></about>
<family *ngIf="currentPage == 'family'" @stepAnimation></family>

The animation doesn't work. Then I add the animation code inside each component and add @stepAnimation to the parent tag of each template. This way, I get the enter animation but not leave. I guess that's because of the ngIf on the parent but regardless, there are a lot of repeat animation code with this. Would there be anyway to handle the animation on the parent level?

Body:
The problem is that the custom elements, <start>, <family>, and <about> have no styling and therefore display defaults to inline, which can't be translated. Simply add this to your parent stylesheet:

about, start, family {
    display: block;
    /*Any other layout code, e.g. position:absolute */
}

And it should work.