问:
How can I do a countdown timer with html?
I'm helping my I.T teacher to create easter eggs for some tasks, and I would like to create a countdown timer with html.
Explanation:
Everytime you enter into a website, the countdown timer starts.
Example:
I have a html code with a countdown timer at 30 min, if I go into the website, the countdown timer starts going down, but if I refresh the website, it reset.
I hope you will understand, thanks!</p>

答:
html code:

```<code><h1>Countdown Clock</h1>
<div id="clockdiv">
  <div>
    <span class="days"></span>
    <div class="text">Days</div>
  </div>
  <div>
    <span class="hours"></span>
    <div class="text">Hours</div>
  </div>
  <div>
    <span class="minutes"></span>
    <div class="text">Minutes</div>
  </div>
  <div>
    <span class="seconds"></span>
    <div class="text">Seconds</div>
  </div>
</div>
</code>```

css code:

```<code>#clockdiv{
    font-family: sans-serif;
    color: #fff;
    display: inline-block;
    font-weight: 100;
    text-align: center;
    font-size: 30px;
}

#clockdiv > div{
    padding: 10px;
    border-radius: 3px;
    background: #00BF96;
    display: inline-block;
}

#clockdiv div > span{
    padding: 15px;
    border-radius: 3px;
    background: #00816A;
    display: inline-block;
}

.text{
    padding-top: 5px;
    font-size: 16px;
}
</code>```

javascript code:

```<code>function getTimeRemaining(endtime) {
  var t = Date.parse("June 31,2017") - Date.parse(new Date());
  var seconds = Math.floor((t / 1000) % 60);
  var minutes = Math.floor((t / 1000 / 60) % 60);
  var hours = Math.floor((t / (1000 * 60 * 60)) % 24);
  var days = Math.floor(t / (1000 * 60 * 60 * 24));
  return {
    'total': t,
    'days': days,
    'hours': hours,
    'minutes': minutes,
    'seconds': seconds
  };
}

function initializeClock(id, endtime) {
  var clock = document.getElementById(id);
  var daysSpan = clock.querySelector('.days');
  var hoursSpan = clock.querySelector('.hours');
  var minutesSpan = clock.querySelector('.minutes');
  var secondsSpan = clock.querySelector('.seconds');

  function updateClock() {
    var t = getTimeRemaining(endtime);

    daysSpan.innerHTML = t.days;
    hoursSpan.innerHTML = ('0' + t.hours).slice(-2);
    minutesSpan.innerHTML = ('0' + t.minutes).slice(-2);
    secondsSpan.innerHTML = ('0' + t.seconds).slice(-2);

    if (t.total <= 0) {
      clearInterval(timeinterval);
    }
  }

  updateClock();
  var timeinterval = setInterval(updateClock, 1000);
}

var deadline = new Date(Date.parse(new Date()) + 15 * 24 * 60 * 60 * 1000);
initializeClock('clockdiv', deadline);
</code>```

in the html documnet,include the new files:

```<code><script type="text/javascript" src="assets/js/count.js"></script>

<link rel="stylesheet" type="text/css" href="assets/css/flipclock.css">
</code>```

hope it works...

Body:
html code:

<h1>Countdown Clock</h1>
<div id="clockdiv">
  <div>
    <span class="days"></span>
    <div class="text">Days</div>
  </div>
  <div>
    <span class="hours"></span>
    <div class="text">Hours</div>
  </div>
  <div>
    <span class="minutes"></span>
    <div class="text">Minutes</div>
  </div>
  <div>
    <span class="seconds"></span>
    <div class="text">Seconds</div>
  </div>
</div>

css code:

#clockdiv{
    font-family: sans-serif;
    color: #fff;
    display: inline-block;
    font-weight: 100;
    text-align: center;
    font-size: 30px;
}

#clockdiv > div{
    padding: 10px;
    border-radius: 3px;
    background: #00BF96;
    display: inline-block;
}

#clockdiv div > span{
    padding: 15px;
    border-radius: 3px;
    background: #00816A;
    display: inline-block;
}

.text{
    padding-top: 5px;
    font-size: 16px;
}

javascript code:

function getTimeRemaining(endtime) {
  var t = Date.parse("June 31,2017") - Date.parse(new Date());
  var seconds = Math.floor((t / 1000) % 60);
  var minutes = Math.floor((t / 1000 / 60) % 60);
  var hours = Math.floor((t / (1000 * 60 * 60)) % 24);
  var days = Math.floor(t / (1000 * 60 * 60 * 24));
  return {
    'total': t,
    'days': days,
    'hours': hours,
    'minutes': minutes,
    'seconds': seconds
  };
}

function initializeClock(id, endtime) {
  var clock = document.getElementById(id);
  var daysSpan = clock.querySelector('.days');
  var hoursSpan = clock.querySelector('.hours');
  var minutesSpan = clock.querySelector('.minutes');
  var secondsSpan = clock.querySelector('.seconds');

  function updateClock() {
    var t = getTimeRemaining(endtime);

    daysSpan.innerHTML = t.days;
    hoursSpan.innerHTML = ('0' + t.hours).slice(-2);
    minutesSpan.innerHTML = ('0' + t.minutes).slice(-2);
    secondsSpan.innerHTML = ('0' + t.seconds).slice(-2);

    if (t.total <= 0) {
      clearInterval(timeinterval);
    }
  }

  updateClock();
  var timeinterval = setInterval(updateClock, 1000);
}

var deadline = new Date(Date.parse(new Date()) + 15 * 24 * 60 * 60 * 1000);
initializeClock('clockdiv', deadline);

in the html documnet,include the new files:

<script type="text/javascript" src="assets/js/count.js"></script>

<link rel="stylesheet" type="text/css" href="assets/css/flipclock.css">

hope it works...


来源: stackexchange

问:
What does const means in auto return declaration with trailing return type?
I need to return a const reference from the function. This code does the thing:

```<code>auto test()->add_lvalue_reference<const int>::type
{
    static int i{50};
    return i;
}

int & i{test()}; // doesn't compile
</code>```

But this snippet, that looks painfully similar, gives an incorrect result:

```<code>auto const test()->add_lvalue_reference<int>::type
{
    static int i{50};
    return i;
}

int & i{test()}; // compiles thougth test() returned a const
</code>```

I moved keyword const from the type declaration to the return declaration.

At first, I thought, that after deduction the function signature became in the second case:

```<code>int & const test(); // not valid - const qualifiers cannot be applied to int&
</code>```

This is not a valid c++. But with auto specifier it compiles.

So my question is what does const means in function return type with auto trailing return? Or maybe it's discarded?

答:
```<code>auto const test()->add_lvalue_reference<int>::type
</code>```

This is ill-formed, see [dcl.fct]/2 (in the case where a trailing-return-type is used, "T shall be the single type-specifier auto").

ContentLicense: CC BY-SA 3.0

Body:
I need to return a const reference from the function. This code does the thing:

auto test()->add_lvalue_reference<const int>::type
{
    static int i{50};
    return i;
}

int & i{test()}; // doesn't compile

But this snippet, that looks painfully similar, gives an incorrect result:

auto const test()->add_lvalue_reference<int>::type
{
    static int i{50};
    return i;
}

int & i{test()}; // compiles thougth test() returned a const

I moved keyword const from the type declaration to the return declaration.

At first, I thought, that after deduction the function signature became in the second case:

int & const test(); // not valid - const qualifiers cannot be applied to int&

This is not a valid c++. But with auto specifier it compiles.

So my question is what does const means in function return type with auto trailing return? Or maybe it's discarded?

Body:
auto const test()->add_lvalue_reference<int>::type

This is ill-formed, see [dcl.fct]/2 (in the case where a trailing-return-type is used, "T shall be the single type-specifier auto").


问:
Node Express - multer causing controller call failure and vice versa
Routes.js

The below code worked.

```<code>var upload= multer({ storage: storage})
app.post('/upload', [ upload.any(), function(req, res) {
     console.log(req.body) // form fields
     console.log(req.files) // form files
     res.status(204).end()
   }]);
</code>```

However, I wanted to call a controller method as well which is located in my file uploadController.js

So I did this, down below.

```<code> app.post('/upload', controllers.uploadFiles.upload, [ upload.any(), function(req, res) {
                    console.log(req.body) // form fields
                    console.log(req.files) // form files
                    res.status(204).end()
                }]);
</code>```

However, what happened was that my controller was called but then uploading part failed, i.e the below part wasn't called.

```<code>console.log(req.body) // form fields
 console.log(req.files) // form files
 res.status(204).end()
</code>```

In conclusion, either one of them (multer or controller) work, both of them don't.
   What could be wrong with this?

UPDATE

Tried the below. Only controller gets called. No file uploading done.

```<code>  app.post('/upload', controllers.dataUpload.upload, [ upload.any(), function(req, res, next) {
                    console.log(req.body) // form fields
                    console.log(req.files) // form files
                    next()
                }]);
</code>```

答:
Credits to @squgeim for helping me out with the conceptual part. According to his guidance, I figured out the issue. Below is the working code.

Routes.js

```<code>var uploadStorage = multer({ storage: storage})
app.post('/upload', controllers.uploadController.uploadFile, [uploadStorage.any(), function(req, res, next) {
    console.log(req.body) // form fields
    console.log(req.files) // form files
    res.status(204).end()
}]);
</code>```

uploadController.js

```<code>module.exports = {
    uploadFile: (req, res, next) => {

        //Do whatever you want over here.
        next()
    },
}
</code>```

So basically, inside app.post argument #2, I call the controller, do whatever I want and then call next() to proceed forward to app.post arguments #3 which is calling multer and uploading file.

Body:
Routes.js

The below code worked.

var upload= multer({ storage: storage})
app.post('/upload', [ upload.any(), function(req, res) {
     console.log(req.body) // form fields
     console.log(req.files) // form files
     res.status(204).end()
   }]);

However, I wanted to call a controller method as well which is located in my file uploadController.js

So I did this, down below.

 app.post('/upload', controllers.uploadFiles.upload, [ upload.any(), function(req, res) {
                    console.log(req.body) // form fields
                    console.log(req.files) // form files
                    res.status(204).end()
                }]);

However, what happened was that my controller was called but then uploading part failed, i.e the below part wasn't called.

console.log(req.body) // form fields
 console.log(req.files) // form files
 res.status(204).end()

In conclusion, either one of them (multer or controller) work, both of them don't.
   What could be wrong with this?

UPDATE

Tried the below. Only controller gets called. No file uploading done.

  app.post('/upload', controllers.dataUpload.upload, [ upload.any(), function(req, res, next) {
                    console.log(req.body) // form fields
                    console.log(req.files) // form files
                    next()
                }]);

Body:
Credits to @squgeim for helping me out with the conceptual part. According to his guidance, I figured out the issue. Below is the working code.

Routes.js

var uploadStorage = multer({ storage: storage})
app.post('/upload', controllers.uploadController.uploadFile, [uploadStorage.any(), function(req, res, next) {
    console.log(req.body) // form fields
    console.log(req.files) // form files
    res.status(204).end()
}]);

uploadController.js

module.exports = {
    uploadFile: (req, res, next) => {

        //Do whatever you want over here.
        next()
    },
}

So basically, inside app.post argument #2, I call the controller, do whatever I want and then call next() to proceed forward to app.post arguments #3 which is calling multer and uploading file.


问:
Show Matplotlib Xaxis labels only at half and full hour
I have a matplotlib chart that has a time x axis (timestamps converted by matplotlib.dates.date2num()).

I want to show a grid with labels that mark each half and full hour, like this: 10:00, 10:30, 11:00,...

To format the labels intervals I use these code lines:

```<code>import matplotlib.dates as mdates
ax.xaxis.set_major_locator(mdates.MinuteLocator(interval=30))
</code>```

The problem is - the data does not start at a full or half full hour. So what I get instead are just the correct intervals, but shifted away from each half and full hour. I.e. 10:17, 10:47, 11:17,... depending on when the data starts. How can this be fixed?

答:
Using the byminute argument as pointed out by languitar is the right way to go.

This code works:

```<code>ax.xaxis.set_major_locator(mdates.MinuteLocator(byminute=[0,30])
</code>```

Now only half and full hours will show a label.

I initially tested byminute, but did not remove interval=30, which results in the error:

ValueError: Invalid rrule byxxx generates an empty set.

So using the arguments byminute and interval at the same time does not work and is not necessary anyways.

Body:
I have a matplotlib chart that has a time x axis (timestamps converted by matplotlib.dates.date2num()).

I want to show a grid with labels that mark each half and full hour, like this: 10:00, 10:30, 11:00,...

To format the labels intervals I use these code lines:

import matplotlib.dates as mdates
ax.xaxis.set_major_locator(mdates.MinuteLocator(interval=30))

The problem is - the data does not start at a full or half full hour. So what I get instead are just the correct intervals, but shifted away from each half and full hour. I.e. 10:17, 10:47, 11:17,... depending on when the data starts. How can this be fixed?

Body:
Using the byminute argument as pointed out by languitar is the right way to go.

This code works:

ax.xaxis.set_major_locator(mdates.MinuteLocator(byminute=[0,30])

Now only half and full hours will show a label.

I initially tested byminute, but did not remove interval=30, which results in the error:

ValueError: Invalid rrule byxxx generates an empty set.

So using the arguments byminute and interval at the same time does not work and is not necessary anyways.


问:
Python Pandas Error tokenizing data
I'm trying to use pandas to manipulate a .csv file but I get this error:

pandas.parser.CParserError: Error tokenizing data. C error: Expected 2 fields in line 3,  saw 12

I have tried to read the pandas docs, but found nothing.

My code is simple:

```<code>path = 'GOOG Key Ratios.csv'
#print(open(path).read())
data = pd.read_csv(path)
</code>```

How can I resolve this? Should I use the csv module or another language ?

File is from Morningstar

答:
Your CSV file might have variable number of columns and read_csv inferred the number of columns from the first few rows. Two ways to solve it in this case:

1) Change the CSV file to have a dummy first line with max number of columns (and specify header=[0])

2) Or use names = list(range(0,N)) where N is the max number of columns.

Title: Python Pandas Error tokenizing data

Body:
I'm trying to use pandas to manipulate a .csv file but I get this error:

pandas.parser.CParserError: Error tokenizing data. C error: Expected 2 fields in line 3,  saw 12

I have tried to read the pandas docs, but found nothing.

My code is simple:

path = 'GOOG Key Ratios.csv'
#print(open(path).read())
data = pd.read_csv(path)

How can I resolve this? Should I use the csv module or another language ?

File is from Morningstar


问:
Odoo 10 - Form view opened in edit mode
I'm developing on Odoo 10.

I created a dynamic form view which search and display a product from its barcode, but I've got a problem.

Since the view has no initial record to display it is opened in edit mode, and that's ok, because I want to type the 'barcode' field.

But, after the product is displayed, when I exit from that view the 'can_be_discarded' function is fired, opening the confirm dialog.

Have I to create a new view type inheriting from FormView or is there a way to workaround this problem?

The view is a classic form view, with nothing special.

Here's the server code instead.

class ProductFromBarcode(models.TransientModel):
    _name = 'levelprime_product_general_status.product_from_barcode'
    _inherits = { 'product.product': 'product_id' }

    product_id      = fields.Many2one(
                            comodel_name='product.product',
                            store=False)
    product_barcode = fields.Integer(help='Insert the barcode to search '
                                          'the correspondent product',
                                     store=False)

    @api.onchange('product_barcode')
    def on_barcode_changed(self):
        if self.product_barcode != 0:
            self.product_id = self.get_product_from_barcode(self.product_barcode)

    @api.model
    def get_product_from_barcode(self, barcode):
        r = self.env['product.product'].search([('barcode', '=', barcode)])
        if r:
            return r
```

答:
You have used  _inherits = { 'product.product': 'product_id' } in your wizard.

When using _inherits you will do a kind of polymorphic model in the database way.

For example product.product inherits product.template or res.users inherits res.partner.

This mean we create a model that gets the know how of a Model but adds aditional data/columns in a new database table. So when you create a user, all partner data is stored in res_partner table (and a partner is created) and all user related info is stored in res_users table.

In your code when wizard (levelprime_product_general_status.product_from_barcode) record will create then all product.product/product.template fields are required,due to that reason you are getting this type of error.

You can check difference between _inherit & _inherits from following link.

https://www.odoo.com/forum/how-to/developers-13/the-different-openerp-model-inheritance-mechanisms-what-s-the-difference-between-them-and-when-should-they-be-used-46

You need to follow following code.

```<code>class ProductFromBarcode(models.TransientModel):
    _name = 'levelprime_product_general_status.product_from_barcode'

    product_id= fields.Many2one(comodel_name='product.product',string="Product")
    product_barcode = fields.Char(help='Insert the barcode to search '
                                          'the correspondent product',
                                     "Barcode")

    @api.onchange('product_barcode')
    def on_barcode_changed(self):
        if self.product_barcode:
            self.product_id = self.get_product_from_barcode(self.product_barcode)

    @api.model
    def get_product_from_barcode(self,barcode):
        r = self.env['product.product'].search([('barcode', '=', barcode)])
        if r:
            return r
        else:
            return False
</code>```

In above code just create wizard & add two fields.
This may help you.

Title: Odoo 10 - Form view opened in edit mode

Body:
You have used  _inherits = { 'product.product': 'product_id' } in your wizard.

When using _inherits you will do a kind of polymorphic model in the database way.

For example product.product inherits product.template or res.users inherits res.partner.

This mean we create a model that gets the know how of a Model but adds aditional data/columns in a new database table. So when you create a user, all partner data is stored in res_partner table (and a partner is created) and all user related info is stored in res_users table.

In your code when wizard (levelprime_product_general_status.product_from_barcode) record will create then all product.product/product.template fields are required,due to that reason you are getting this type of error.

You can check difference between _inherit & _inherits from following link.

https://www.odoo.com/forum/how-to/developers-13/the-different-openerp-model-inheritance-mechanisms-what-s-the-difference-between-them-and-when-should-they-be-used-46

You need to follow following code.

class ProductFromBarcode(models.TransientModel):
    _name = 'levelprime_product_general_status.product_from_barcode'

    product_id= fields.Many2one(comodel_name='product.product',string="Product")
    product_barcode = fields.Char(help='Insert the barcode to search '
                                          'the correspondent product',
                                     "Barcode")

    @api.onchange('product_barcode')
    def on_barcode_changed(self):
        if self.product_barcode:
            self.product_id = self.get_product_from_barcode(self.product_barcode)

    @api.model
    def get_product_from_barcode(self,barcode):
        r = self.env['product.product'].search([('barcode', '=', barcode)])
        if r:
            return r
        else:
            return False

In above code just create wizard & add two fields.
This may help you.


问:
Failed to load user control at design time
I am having problems with a user control. I cannot placed it on a form.

To make a test, I have created now a new UserControl. I have added just a button on it. Then, I have created a new Form. Then compiled.

After that, I loaded the form design view. I can see in toolbox the "UserControl1" I have created. Then, I drag that user control from the toolbox and drop into the form and the following error occurs:

After I cick OK button, the user control is removed from the toolbox.

What may be happening here?

I am using Visual Studio 2012 and building against .NET Framework 4.5.2.

答: Finally, the problem was that I was building for x64 platform and my VS2012 is x86. At development time, I will use x86 and use x64 only for deployment.</p>


问:
am charts labeltext fonsize can't change
I need to show my percentage value in my bar chart within the cylinder but some of the value is missing.
    So how can I show the missing values in my chart?Attached Screenshot.
    # am trying fontSize also.

答:
By default, the chart will not show labels if they can't fit within the chart. In your particular case, you'll want to set showAllValueLabels to true in your graph objects:

```<code>"graphs": [{
  // ...
  "showAllValueLabels": true,
  // ...
},
 // repeat for each graph in the array
]
</code>```

Body:
By default, the chart will not show labels if they can't fit within the chart. In your particular case, you'll want to set showAllValueLabels to true in your graph objects:

"graphs": [{
  // ...
  "showAllValueLabels": true,
  // ...
},
 // repeat for each graph in the array
]


问:
Read 'n' lines from file and assign each line to distinct variable
I generate a text file based on nodes in the cluster.

```<code>cat primary_nodes.txt
clusterNodea
clusterNodeb
..
....
clusterNoden
</code>```

While I try to generate variable for each line, it gives me following output

```<code>while read PRIMARY_NODE$((i++)); do
echo $PRIMARY_NODE1
echo $PRIMARY_NODE2
done < primary_node.txt

clusterNodea
clusterNodea
clusterNodeb
</code>```

What I want is:

It should return total no.of nodes

Each line should be assigned to PRIMARY_NODE1...n variable incrementally

Return all variable with its value.

答:
Arrays are your friend here:

```<code>readarray -t MYARRAY <primary_nodes.txt
$ echo ${MYARRAY[0]}
clusterNodea
$ echo ${MYARRAY[1]}
clusterNodeb
</code>```

Note that it's possible to also use the following:

```<code>$ MYARRAY=($(cat primary_nodes.txt))
</code>```

however this should be avoided for as file globbing and literal whitespaces can give unexpected results as Charles Duffy points out below

Body:
I generate a text file based on nodes in the cluster.

cat primary_nodes.txt
clusterNodea
clusterNodeb
..
....
clusterNoden

While I try to generate variable for each line, it gives me following output

while read PRIMARY_NODE$((i++)); do
echo $PRIMARY_NODE1
echo $PRIMARY_NODE2
done < primary_node.txt

clusterNodea
clusterNodea
clusterNodeb

What I want is:

It should return total no.of nodes

Each line should be assigned to PRIMARY_NODE1...n variable incrementally

Return all variable with its value.

Body:
Arrays are your friend here:

readarray -t MYARRAY <primary_nodes.txt
$ echo ${MYARRAY[0]}
clusterNodea
$ echo ${MYARRAY[1]}
clusterNodeb

Note that it's possible to also use the following:

$ MYARRAY=($(cat primary_nodes.txt))

however this should be avoided for as file globbing and literal whitespaces can give unexpected results as Charles Duffy points out below


问:
How to read nextline of textfile in Java?
```<code>import java.io.*;
import java.util.*;
public class stringstore
{
    public static void main(String[] args)
    {
        File file = new File("C:\\a.txt");
        try
        {
            String strIP="";
            Scanner sc = new Scanner(file);
            while(sc.hasNext())
            {
                String line = sc.nextLine();
                String str[] = line.split(", ");
                strIP = str[0];
            }
            System.out.println(strIP);
        }
        catch(IOException e)
        {
        // work with the errors here
        }
    }
}
</code>```

How do I read a nextline from a textfile and display it.

答:
There is only slight mistake in your code.
Try this.

```<code>import java.io.*;
   import java.util.*;
   public class stringstore
 {
   public static void main(String[] args)
{
    File file = new File("C:\\a.txt");
 try
{
String strIP="";
Scanner sc = new Scanner(file);
while(sc.hasNext())
{
    String line = sc.nextLine();
    String str[] = line.split(", ");
    strIP = str[0];
System.out.println(strIP);
}

}
catch(IOException e)
{
  // work with the errors here
}
  }
}
</code>```

place the print statement inside the loop

Body:
import java.io.*;
import java.util.*;
public class stringstore
{
    public static void main(String[] args)
    {
        File file = new File("C:\\a.txt");
        try
        {
            String strIP="";
            Scanner sc = new Scanner(file);
            while(sc.hasNext())
            {
                String line = sc.nextLine();
                String str[] = line.split(", ");
                strIP = str[0];
            }
            System.out.println(strIP);
        }
        catch(IOException e)
        {
        // work with the errors here
        }
    }
}

How do I read a nextline from a textfile and display it.

Body:
There is only slight mistake in your code.
Try this.

import java.io.*;
   import java.util.*;
   public class stringstore
 {
   public static void main(String[] args)
{
    File file = new File("C:\\a.txt");
 try
{
String strIP="";
Scanner sc = new Scanner(file);
while(sc.hasNext())
{
    String line = sc.nextLine();
    String str[] = line.split(", ");
    strIP = str[0];
System.out.println(strIP);
}

}
catch(IOException e)
{
  // work with the errors here
}
  }
}

place the print statement inside the loop


问:
Google Sign In Failed - Firebase
I followed this tutorial and in this part of the code:

```<code>@Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        // Result returned from launching the Intent from GoogleSignInApi.getSignInIntent(...);
        if (requestCode == RC_SIGN_IN) {
            GoogleSignInResult result = Auth.GoogleSignInApi.getSignInResultFromIntent(data);
            if (result.isSuccess()) {
                // Google Sign In was successful, authenticate with Firebase
                GoogleSignInAccount account = result.getSignInAccount();
                firebaseAuthWithGoogle(account);
            } else {
                // Google Sign In failed
                Log.e(TAG, "Google Sign In failed.");
                Toast.makeText(SignInActivity.this,"Google Sign In Failed.",Toast.LENGTH_SHORT).show();
            }
        }
    }
</code>```

I am getting a google sign in failed. I do not know what is wrong how to fix?

I actually got in working when I tried running app-released.apk instead of running in directly on my phone.

答:
Perhaps you messed up/haven't configured your debug certificate (might happen if you switch to another development machine with different keystore set).
Make sure you have added the SHA1 certificate fingerprint in the Firebase Console Settings section of your project, as described here: https://firebase.google.com/docs/auth/android/google-signin#before_you_begin

Title: Google Sign In Failed - Firebase

Body:
I followed this tutorial and in this part of the code:

@Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        // Result returned from launching the Intent from GoogleSignInApi.getSignInIntent(...);
        if (requestCode == RC_SIGN_IN) {
            GoogleSignInResult result = Auth.GoogleSignInApi.getSignInResultFromIntent(data);
            if (result.isSuccess()) {
                // Google Sign In was successful, authenticate with Firebase
                GoogleSignInAccount account = result.getSignInAccount();
                firebaseAuthWithGoogle(account);
            } else {
                // Google Sign In failed
                Log.e(TAG, "Google Sign In failed.");
                Toast.makeText(SignInActivity.this,"Google Sign In Failed.",Toast.LENGTH_SHORT).show();
            }
        }
    }

I am getting a google sign in failed. I do not know what is wrong how to fix?

I actually got in working when I tried running app-released.apk instead of running in directly on my phone.


问:
Asp.net redirect to page based Azure AD user
Hello,
I have asp.net web forms project with Azure AD authentication,
now in this project i have two forms "webfrom1.aspx" and "webform2.aspx"
now i need that, if user "it" is login then redirect to "web form 1.aspx" or if user "finance" login then redirect to "web form 2.aspx".
please help me!
Thanks

答: As part of your authentication configuration, you could specify a RedirectUri to a page that could make the decision on where to redirect (webform1.aspx or webform2.aspx) based on the user.</p>


问:
F# instead of multiple lets , can I pipe the intermediate results
Given:

```<code>let json = """
{
    "KeyValuePairs": "[{\"Key\" : \"one\", \"Value\" : \"1\"},{\"Key\" : \"two\", \"Value\" : \"2\"}]"
}
"""
let dict = JsonConvert.DeserializeObject<Dictionary<System.String, System.String>>(json)
let kvpairs = dict.["KeyValuePairs"]
let kvlist = JsonConvert.DeserializeObject<KeyValuePair<System.String, System.String> List>(kvpairs)
let kvmap = [for kv  in kvlist -> (kv.Key, kv.Value)] |> Map.ofList
</code>```

Can I use one expression with pipes instead of intermediate variables?  If so, what would that look like?

FWIW I tried:

```<code>let kvpairs = JsonConvert.DeserializeObject<Dictionary<System.String, System.String>>(json)
    |> (fun d -> d.["KeyValuePairs"])
</code>```

but that gave me the error:

```<code>error FS0010: Unexpected infix operator in binding. Expected incomplete structured construct at or before this point or other
</code>```

token.

Update:  What about the other way around: piping into JsonConvert?

```<code>let kvpairs =
    json
    |> JsonConvert.DeserializeObject<Dictionary<System.String, System.String>>
    |> (fun d -> d.["KeyValuePairs"])
</code>```

This gives me:

error FS0717: Unexpected type arguments

答:
In your code

```<code>let kvpairs = JsonConvert.DeserializeObject<Dictionary<System.String, System.String>>(json)
    |> (fun d -> d.["KeyValuePairs"])
</code>```

The pipe is not indented far enough.

```<code>let kvpairs = JsonConvert.DeserializeObject<Dictionary<System.String, System.String>>(json)
              |> (fun d -> d.["KeyValuePairs"])
</code>```

or

```<code>let kvpairs = JsonConvert.DeserializeObject<Dictionary<System.String, System.String>>(json)
           |> (fun d -> d.["KeyValuePairs"])
</code>```

or

```<code>let kvpairs =
    JsonConvert.DeserializeObject<Dictionary<System.String, System.String>>(json)
    |> (fun d -> d.["KeyValuePairs"])
</code>```

will work.

Body:
Given:

let json = """
{
    "KeyValuePairs": "[{\"Key\" : \"one\", \"Value\" : \"1\"},{\"Key\" : \"two\", \"Value\" : \"2\"}]"
}
"""
let dict = JsonConvert.DeserializeObject<Dictionary<System.String, System.String>>(json)
let kvpairs = dict.["KeyValuePairs"]
let kvlist = JsonConvert.DeserializeObject<KeyValuePair<System.String, System.String> List>(kvpairs)
let kvmap = [for kv  in kvlist -> (kv.Key, kv.Value)] |> Map.ofList

Can I use one expression with pipes instead of intermediate variables?  If so, what would that look like?

FWIW I tried:

let kvpairs = JsonConvert.DeserializeObject<Dictionary<System.String, System.String>>(json)
    |> (fun d -> d.["KeyValuePairs"])

but that gave me the error:

error FS0010: Unexpected infix operator in binding. Expected incomplete structured construct at or before this point or other

token.

Update:  What about the other way around: piping into JsonConvert?

let kvpairs =
    json
    |> JsonConvert.DeserializeObject<Dictionary<System.String, System.String>>
    |> (fun d -> d.["KeyValuePairs"])

This gives me:

error FS0717: Unexpected type arguments

Body:
In your code

let kvpairs = JsonConvert.DeserializeObject<Dictionary<System.String, System.String>>(json)
    |> (fun d -> d.["KeyValuePairs"])

The pipe is not indented far enough.

let kvpairs = JsonConvert.DeserializeObject<Dictionary<System.String, System.String>>(json)
              |> (fun d -> d.["KeyValuePairs"])

or

let kvpairs = JsonConvert.DeserializeObject<Dictionary<System.String, System.String>>(json)
           |> (fun d -> d.["KeyValuePairs"])

or

let kvpairs =
    JsonConvert.DeserializeObject<Dictionary<System.String, System.String>>(json)
    |> (fun d -> d.["KeyValuePairs"])

will work.


问:
Build Error: Jack requires Build Tools 24.0.0 or later
I am using RX library in my android project and due to some reasons I need to have my build.gradle as:

```<code>apply plugin: 'com.android.application'

android {
compileSdkVersion 23
buildToolsVersion "23.0.3"

defaultConfig {
    applicationId "com.urjapawar.bevyotp"
    minSdkVersion 18
    targetSdkVersion 23
    versionCode 1
    versionName "1.0"
    jackOptions {
        enabled true
    }
}
buildTypes {
    release {
        minifyEnabled false
        proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
    }
}
compileOptions {
    sourceCompatibility JavaVersion.VERSION_1_8
    targetCompatibility JavaVersion.VERSION_1_8
}
}

dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
testCompile 'junit:junit:4.12'
compile 'com.android.support:appcompat-v7:23.4.0'
compile 'com.android.support:support-v4:23.4.0'
compile 'com.android.support:recyclerview-v7:23.4.0'
compile 'io.reactivex:rxandroid:0.24.0'
}
</code>```

I have visited this and this too but cannot fix it. My project code is
RegisterActivity.java

```<code>public class RegisterActivity extends AppCompatActivity {

EditText name,email,phonenumber,city;
Button button;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_register);
    name = (EditText) findViewById(R.id.nameinput);
    email = (EditText) findViewById(R.id.emailinput);
    phonenumber = (EditText) findViewById(R.id.phonenumber);
    city = (EditText) findViewById(R.id.cityName);
    final Pattern emailPattern = Pattern.compile(
            "^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*@"
                    + "[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$");

    Observable<Boolean> userNameValid = WidgetObservable.text(name) //  [2]
            .map(e -> e.text())
            .map(t -> t.length() != 0);

    Observable<Boolean> emailValid = WidgetObservable.text(email)
            .map(e -> e.text())
            .map(t -> emailPattern.matcher(t).matches());

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

    Observable<Boolean> registerEnabled =
            Observable.combineLatest(userNameValid, emailValid, (a, b) -> a && b);
    // registerEnabled.subscribe(enabled -> registerButton.setEnabled(enabled));
    emailValid.distinctUntilChanged()
            .doOnNext(b -> Log.d("[Rx]", "Email " + (b ? "Valid" : "Invalid")))
            .map(b -> b ? Color.BLACK : Color.RED)
            .subscribe(color -> email.setTextColor(color));

    userNameValid.distinctUntilChanged()
            .doOnNext(b -> Log.d("[Rx]", "Uname " + (b ? "Valid" : "Invalid")))
            .map(b -> b ? Color.BLACK : Color.RED)
            .subscribe(color -> name.setTextColor(color));

 // and registerEnabled

    registerEnabled.distinctUntilChanged()
            .doOnNext(b -> Log.d("[Rx]", "Button " + (b ? "Enabled" : "Disabled")))
            .subscribe(enabled -> registerButton.setEnabled(enabled));

}
public void OTPbutton(View view){
    startActivity(new Intent(RegisterActivity.this, ChooseActivity.class));
}

}
</code>```

Here is the log

Thanks in advance

答:
now you better use</p>

```<code>buildToolsVersion = "24.0.0"
</code>```

Body:
I am using RX library in my android project and due to some reasons I need to have my build.gradle as:

apply plugin: 'com.android.application'

android {
compileSdkVersion 23
buildToolsVersion "23.0.3"

defaultConfig {
    applicationId "com.urjapawar.bevyotp"
    minSdkVersion 18
    targetSdkVersion 23
    versionCode 1
    versionName "1.0"
    jackOptions {
        enabled true
    }
}
buildTypes {
    release {
        minifyEnabled false
        proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
    }
}
compileOptions {
    sourceCompatibility JavaVersion.VERSION_1_8
    targetCompatibility JavaVersion.VERSION_1_8
}
}

dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
testCompile 'junit:junit:4.12'
compile 'com.android.support:appcompat-v7:23.4.0'
compile 'com.android.support:support-v4:23.4.0'
compile 'com.android.support:recyclerview-v7:23.4.0'
compile 'io.reactivex:rxandroid:0.24.0'
}

I have visited this and this too but cannot fix it. My project code is
RegisterActivity.java

public class RegisterActivity extends AppCompatActivity {

EditText name,email,phonenumber,city;
Button button;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_register);
    name = (EditText) findViewById(R.id.nameinput);
    email = (EditText) findViewById(R.id.emailinput);
    phonenumber = (EditText) findViewById(R.id.phonenumber);
    city = (EditText) findViewById(R.id.cityName);
    final Pattern emailPattern = Pattern.compile(
            "^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*@"
                    + "[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$");

    Observable<Boolean> userNameValid = WidgetObservable.text(name) //  [2]
            .map(e -> e.text())
            .map(t -> t.length() != 0);

    Observable<Boolean> emailValid = WidgetObservable.text(email)
            .map(e -> e.text())
            .map(t -> emailPattern.matcher(t).matches());

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

    Observable<Boolean> registerEnabled =
            Observable.combineLatest(userNameValid, emailValid, (a, b) -> a && b);
    // registerEnabled.subscribe(enabled -> registerButton.setEnabled(enabled));
    emailValid.distinctUntilChanged()
            .doOnNext(b -> Log.d("[Rx]", "Email " + (b ? "Valid" : "Invalid")))
            .map(b -> b ? Color.BLACK : Color.RED)
            .subscribe(color -> email.setTextColor(color));

    userNameValid.distinctUntilChanged()
            .doOnNext(b -> Log.d("[Rx]", "Uname " + (b ? "Valid" : "Invalid")))
            .map(b -> b ? Color.BLACK : Color.RED)
            .subscribe(color -> name.setTextColor(color));

 // and registerEnabled

    registerEnabled.distinctUntilChanged()
            .doOnNext(b -> Log.d("[Rx]", "Button " + (b ? "Enabled" : "Disabled")))
            .subscribe(enabled -> registerButton.setEnabled(enabled));

}
public void OTPbutton(View view){
    startActivity(new Intent(RegisterActivity.this, ChooseActivity.class));
}

}

Here is the log

Thanks in advance

Body:
now you better use

buildToolsVersion = "24.0.0"


问:
Convert GET HTML response into document
I am developing a page that reads the source of another page and I need to extract certain information out of that page. I currently have the project snagging the live source with the data however I cannot for the life of me figure out how to convert this string into a document.

My rationale for using a document is that I need to use getElementById etc to get the value of these items.

What have I tried?

Assigning the HTML to an invisible div on my page. This kind of works though it doesn't render the entire HTML string and provides a "shorter" rendition of this page.

Manually finding the substrings. As you can imagine this is a crappy way to do things and provides very unreliable results.

DOM parser to convert the doc and then query it but that fails miserably.

Any assistance at all would be seriously appreciated.

pertinent code:

```<code>$.ajax({
  method: "GET",
  dataType: '',
  crossDomain: true,
  xhrFields: {
    withCredentials: true
  },
  success: function(res) {
    //shows the entire source just fine.
    console.log("Value of RES: " + res);
    bootbox.hideAll();
    //shows a "truncated" copy of the source
    alert(res);
    $("#hiddendiv").html(x);
    var name = document.findElementById("myitem");
    alert(name);
  },
</code>```

答: Create a hidden IFRAME on your document. Then set the contents of that IFRAME to the HTML that you want to query. Target that IFRAME with your javascript when you do your querying. See How can I access iframe elements with Javascript? to understand how.</p>

Title: Convert GET HTML response into document

Body:
I am developing a page that reads the source of another page and I need to extract certain information out of that page. I currently have the project snagging the live source with the data however I cannot for the life of me figure out how to convert this string into a document.

My rationale for using a document is that I need to use getElementById etc to get the value of these items.

What have I tried?

Assigning the HTML to an invisible div on my page. This kind of works though it doesn't render the entire HTML string and provides a "shorter" rendition of this page.

Manually finding the substrings. As you can imagine this is a crappy way to do things and provides very unreliable results.

DOM parser to convert the doc and then query it but that fails miserably.

Any assistance at all would be seriously appreciated.

pertinent code:

$.ajax({
  method: "GET",
  dataType: '',
  crossDomain: true,
  xhrFields: {
    withCredentials: true
  },
  success: function(res) {
    //shows the entire source just fine.
    console.log("Value of RES: " + res);
    bootbox.hideAll();
    //shows a "truncated" copy of the source
    alert(res);
    $("#hiddendiv").html(x);
    var name = document.findElementById("myitem");
    alert(name);
  },


答:
A bit of dynamic variable assignment using declare and indirect expansion as

```<code>#!/bin/bash

i=1
while IFS= read -r line; do
    # The 'declare' syntax creates variables on the fly with the values
    # read from the file
    declare primaryNode$((i++))="$line"
done <file

count="$((i-1))"

# Now the variables are created; those can be individually accessed as
# '$primaryNode1'..'$primaryNoden'; but to print it on a loop, use
# indirect expansion using ${!var} syntax

for ((idx=1; idx<=count; idx++)); do
    temp=primaryNode$idx
    printf "PRIMARY NODE%s=%s\n" "$idx" "${!temp}"
done
</code>```

Title: Read 'n' lines from file and assign each line to distinct variable

Body:
A bit of dynamic variable assignment using declare and indirect expansion as

#!/bin/bash

i=1
while IFS= read -r line; do
    # The 'declare' syntax creates variables on the fly with the values
    # read from the file
    declare primaryNode$((i++))="$line"
done <file

count="$((i-1))"

# Now the variables are created; those can be individually accessed as
# '$primaryNode1'..'$primaryNoden'; but to print it on a loop, use
# indirect expansion using ${!var} syntax

for ((idx=1; idx<=count; idx++)); do
    temp=primaryNode$idx
    printf "PRIMARY NODE%s=%s\n" "$idx" "${!temp}"
done


问:
Replace HTML tags or retrieve text within them
I am using a platform that generates an HTML script. I cannot change its format. The reason is that it is a private platform and that generates the data in a specific way. I create a query (let's say Month and Number) and that shows the data in an HTML format as shown below:

```<code><table>
<tbody>
    <tr>
        <td>
    <table>
    <tbody>
      <tr><td>Jan</td></tr>
      <tr><td>Feb</td></tr>
      <tr><td>Mar</td></tr>
    </tbody>
    </table>
    </td>
        <td>
    <table>
    <tbody>
      <tr><td>1</td></tr>
      <tr><td>2</td></tr>
      <tr><td>3</td></tr>
    </tbody>
    </table>
    </td>
    </tr>
</tbody>
</table>
</code>```

and I want to convert this to :

```<code><table>
    <tr>
        <td>Jan</td>
        <td>Feb</td>
        <td>Mar</td>
    </tr>
    <tr>
        <td>1</td>
        <td>2</td>
        <td>3</td>
    </tr>
</table>
</code>```

I want to use a replace function but that will apply for tags and not text as the one below :

$(document).ready(function(){
    $("button").click(function(){
        $("p:first").replaceWith("I HAVE REPLACED IT");
    });
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>

<p>REPLACE THAT.</p>
<p>Leave it as is.</p>

<button>Replace the first sentence</button></code>```

So, then I tried replacing the tags :

$('li').replaceWith(function () {
    return $('', {
        html: $(this).html()
    });
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>td {
    text-align: center;
    vertical-align: middle;
    line-height: 90px;
    background-color: #ccc;
}</code>```

Jan 2017

Feb 2017

Jun 2017

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

<p>Then I tried replacing the tags from scratch but then I do not how to redistribute the values into the new table tags : </p>

<p><div class="snippet" data-lang="js" data-hide="true" data-console="true" data-babel="false">
<div class="snippet-code snippet-currently-hidden">
<pre class="snippet-code-js lang-js prettyprint-override"><code>var regex = /<\/?([a-z])+\>/g;

var str =  '<table><tr><td>Jan</td><td>Feb</td><td>Mar</td></tr><tr><td>1</td><td>2</td><td>3</td></tr></table>';
var result = str.replace( regex, "");

document.write(result);</code>```

I think the ideal would be to edit the last snippet and make it replace the tags and then output (not in the console) the results. But I am not sure how to make this work.

Another idea is to get the text instead of the html tags using regex and for each match, allocate the results in a new table.

Please give me your thoughts. I might update the question. I have spent hours on this with no success.

UPD

I updated the snipped according to the first answer :

function myFunction() {
let htmlFromService = '

Jan

Feb

Mar

1

2

3

'

let fragment = window.HtmlFragment(htmlFromService);

let newTable = document.createElement('table');

Array
  .from(fragment.querySelectorAll('tbody tbody'))
  .forEach(tbody => {
    let tr = newTable.appendChild(document.createElement('tr'));
    Array
      .from(tbody.querySelectorAll('td'))
      .forEach(td => {
        tr.appendChild(td);
      });

  });

document.write(newTable.outerHTML);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://npmcdn.com/html-fragment@1.1.0/lib/html-fragment.min.js"></script>
<head>

</head>

<body>

<script>

</script>

</body></code>```

答:
When doing DOM manipulations, always try to use the DOM query API's instead of regular expressions. In this solution, I use DocumentFragments to make query-able DOM.

I did this by converting the string of HTML returned from the service into a DocumentFragment. From there, I was able to query into the element, and  get the elements I wanted, and added them to a new table.

let htmlFromService = `

Jan

Feb

Mar

1

2

3

`

let fragment = window.HtmlFragment(htmlFromService);

let newTable = document.createElement('table');

Array
  .from(fragment.querySelectorAll('tbody tbody'))
  .forEach(tbody => {
    let tr = newTable.appendChild(document.createElement('tr'));
    Array
      .from(tbody.querySelectorAll('td'))
      .forEach(td => {
        tr.appendChild(td);
      });

  });

console.log(newTable.outerHTML);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://npmcdn.com/html-fragment@1.1.0/lib/html-fragment.min.js"></script></code>```

Disclaimer: I used an npm package I wrote myself a while back to convert the HTML to a document fragment called html-fragment.

Body:
I am using a platform that generates an HTML script. I cannot change its format. The reason is that it is a private platform and that generates the data in a specific way. I create a query (let's say Month and Number) and that shows the data in an HTML format as shown below:

Jan

Feb

Mar

1

2

3

and I want to convert this to :

        Jan
        Feb
        Mar

        1
        2
        3

I want to use a replace function but that will apply for tags and not text as the one below :

$(document).ready(function(){
    $("button").click(function(){
        $("p:first").replaceWith("I HAVE REPLACED IT");
    });
});

REPLACE THAT.

Leave it as is.

<button>Replace the first sentence</button>

So, then I tried replacing the tags :

$('li').replaceWith(function () {
    return $('', {
        html: $(this).html()
    });
});

td {
    text-align: center;
    vertical-align: middle;
    line-height: 90px;
    background-color: #ccc;
}

Jan 2017

Feb 2017

Jun 2017

Then I tried replacing the tags from scratch but then I do not how to redistribute the values into the new table tags :

var regex = /<\/?([a-z])+\>/g;

var str =  '

Jan	Feb	Mar

1	2	3

';
var result = str.replace( regex, "");

document.write(result);

I think the ideal would be to edit the last snippet and make it replace the tags and then output (not in the console) the results. But I am not sure how to make this work.

Another idea is to get the text instead of the html tags using regex and for each match, allocate the results in a new table.

Please give me your thoughts. I might update the question. I have spent hours on this with no success.

UPD

I updated the snipped according to the first answer :

function myFunction() {
let htmlFromService = '

Jan

Feb

Mar

1

2

3

'

let fragment = window.HtmlFragment(htmlFromService);

let newTable = document.createElement('table');

Array
  .from(fragment.querySelectorAll('tbody tbody'))
  .forEach(tbody => {
    let tr = newTable.appendChild(document.createElement('tr'));
    Array
      .from(tbody.querySelectorAll('td'))
      .forEach(td => {
        tr.appendChild(td);
      });

  });

document.write(newTable.outerHTML);
}

Body:
When doing DOM manipulations, always try to use the DOM query API's instead of regular expressions. In this solution, I use DocumentFragments to make query-able DOM.

I did this by converting the string of HTML returned from the service into a DocumentFragment. From there, I was able to query into the element, and  get the elements I wanted, and added them to a new table.

let htmlFromService = `<table><tbody><tr><td><table><tbody><tr><td>Jan</td></tr><tr><td>Feb</td></tr><tr><td>Mar</td></tr></tbody></table></td><td><table><tbody><tr><td>1</td></tr><tr><td>2</td></tr><tr><td>3</td></tr></tbody></table></td></tr></tbody></table>`

let fragment = window.HtmlFragment(htmlFromService);

let newTable = document.createElement('table');

Array
  .from(fragment.querySelectorAll('tbody tbody'))
  .forEach(tbody => {
    let tr = newTable.appendChild(document.createElement('tr'));
    Array
      .from(tbody.querySelectorAll('td'))
      .forEach(td => {
        tr.appendChild(td);
      });

  });

console.log(newTable.outerHTML);

<script src="https://npmcdn.com/html-fragment@1.1.0/lib/html-fragment.min.js"></script>

Disclaimer: I used an npm package I wrote myself a while back to convert the HTML to a document fragment called html-fragment.


问:
Expression type '[Card]' is ambiguous without more context with an array passed into function
So I have this function remoteDrawCards, which takes an array of cards that is supposed to come from a remote computer, draw the same number of cards, and if they're the same allocate those cards to the remote player. I've taken out code that doesn't pertain to my issue and left a comment in it's place:

```<code>func remoteDrawCards(player: GKPlayer, remoteCards : [Card]) {
    //guard to check if the card count is the same remote and locally
    remoteCards.enumerated().map({(i, card) in
        // guard to check if each card is the same remote and locally
        let playerStruct = players![player.playerID!]!
        // give the cards to the player
    })
    undoHistory.append(play: Play(action: .Draw(cards: remoteCards, player: player)))
}
</code>```

Anyhow, I get an error on the remoteCards variable in the undoHistory.append line of code that says:

Expression type '[Card]' is ambiguous without more context

I don't understand why swift thinks this is ambiguous, and I'm not seeing any of the other times this has been asked that it occurs when a parameter is used.

答:
What it is is that my .Draw was incorrectly formatted. My original issue was with a

```<code>for card in remoteCards{

}
</code>```

giving the error, which I factored out before I asked this question with a .map(), but I thought the error came back when I used the variable in undoHistory. My proper use of .Draw is without the player, which is a variable in Play.

Body:
So I have this function remoteDrawCards, which takes an array of cards that is supposed to come from a remote computer, draw the same number of cards, and if they're the same allocate those cards to the remote player. I've taken out code that doesn't pertain to my issue and left a comment in it's place:

func remoteDrawCards(player: GKPlayer, remoteCards : [Card]) {
    //guard to check if the card count is the same remote and locally
    remoteCards.enumerated().map({(i, card) in
        // guard to check if each card is the same remote and locally
        let playerStruct = players![player.playerID!]!
        // give the cards to the player
    })
    undoHistory.append(play: Play(action: .Draw(cards: remoteCards, player: player)))
}

Anyhow, I get an error on the remoteCards variable in the undoHistory.append line of code that says:

Expression type '[Card]' is ambiguous without more context

I don't understand why swift thinks this is ambiguous, and I'm not seeing any of the other times this has been asked that it occurs when a parameter is used.

Body:
What it is is that my .Draw was incorrectly formatted. My original issue was with a

for card in remoteCards{

}

giving the error, which I factored out before I asked this question with a .map(), but I thought the error came back when I used the variable in undoHistory. My proper use of .Draw is without the player, which is a variable in Play.


问:
How can I put an icon and an input text on the same line?
I want to put an icon on the left and an input type text on the right occupying all the remaining space.

```<code>----------------------------------------------------
| [ico]  ----------------------------------------  |
|        |   input type="text"                  |  |
|        ----------------------------------------  |
----------------------------------------------------
</code>```

If I set both with display: inline-block and set the input's width to 100% it jumps the line, because 100% is not considering the space - icosize...

I want to expand the input to the remaining available space (I don't care for vertical align). Is there a way to achieve this behavior without using tables?

An example of the problem on jsFiddle.

答:
A bit less complicated that ianaré's version and works in IE6:

http://jsfiddle.net/sUYBS/23/

ContentLicense: CC BY-SA 2.5

Body:
I want to put an icon on the left and an input type text on the right occupying all the remaining space.

----------------------------------------------------
| [ico]  ----------------------------------------  |
|        |   input type="text"                  |  |
|        ----------------------------------------  |
----------------------------------------------------

If I set both with display: inline-block and set the input's width to 100% it jumps the line, because 100% is not considering the space - icosize...

I want to expand the input to the remaining available space (I don't care for vertical align). Is there a way to achieve this behavior without using tables?

An example of the problem on jsFiddle.


问:
How to expand a column in a dataframe following another column's formatting?
I have a huge dataframe consisting of 10 mio objects with the following format in RStudio.

```<code>       ID      DATE        reading
    100845 2014-08-17 0,0,0,0,3,0,0,0,0,1,1,0,0,0,0,0,2,0,0,1,0,0,2,0
    100845 2014-08-18 0,0,4,0,0,0,0,1,0,0,0,0,1,1,1,1,0,1,1,2,1,1,0,1
    100845 2014-08-19 0,1,0,1,0,1,1,1,2,0,1,0,1,0,1,0,1,0,1,0,2,1,1,0
    100918 2015-07-02 1,0,0,1,0,1,3,1,1,0,1,0,1,0,1,0,0,1,0,1,0,0,1,1
    100920 2013-02-07 0,1,0,0,1,0,1,1,1,0,0,1,0,0,1,0,0,5,6,4,2,1,0,1
    100920 2013-02-08 0,1,0,0,1,3,5,4,2,1,0,1,0,1,0,0,1,3,7,5,1,1,1,0
</code>```

The 24 readings per row refer to hourly meter readings during a day. I would like to convert the daily dates to hourly and convert the strings of readings to a column format instead. The IDs should follow this format.
For example, I have implemented the following:

```<code>hourly <- data.frame(Hourly=seq(min(as.POSIXct(paste0(df$date, "00:00"),tz="")),max(as.POSIXct(paste0(df$date, "23:00"),tz="")),by="hour"))
</code>```

How can I fill in the new fields that are created due to the hourly setting with the same IDs as in the daily format? As the full dataset I have is extremely big, I would appreciate a solution that can run very fast.

答:
I can't speak to the speed of this approach on a data set as large as yours, but I think this code does the steps you want:

```<code>library(dplyr)
library(tidyr)

df2 <- df %>%
  # use separate to spread the readings across separate columns
  separate(reading, into = paste0("hour.", seq(24)), sep = ",") %>%
  # use gather to convert that wide data frame into a long one
  gather(key = hour, value = reading, hour.1:hour.24) %>%
  # make the hour marker into a number
  mutate(hour = as.numeric(gsub("hour.", "", hour)) - 1) %>%
  # order the data
  arrange(ID, DATE, hour) %>%
  # create a new column that combines the date and time stamp
  mutate(datetime = as.POSIXct(paste(DATE, hour), format = "%Y-%m-%d %H")) %>%
  # shed unneeded columns
  select(ID, datetime, reading)
</code>```

Result:

```<code>> head(df2)
      ID            datetime reading
1 100845 2014-08-17 00:00:00       0
2 100845 2014-08-17 01:00:00       0
3 100845 2014-08-17 02:00:00       0
4 100845 2014-08-17 03:00:00       0
5 100845 2014-08-17 04:00:00       3
6 100845 2014-08-17 05:00:00       0
</code>```

Body:
I have a huge dataframe consisting of 10 mio objects with the following format in RStudio.

       ID      DATE        reading
    100845 2014-08-17 0,0,0,0,3,0,0,0,0,1,1,0,0,0,0,0,2,0,0,1,0,0,2,0
    100845 2014-08-18 0,0,4,0,0,0,0,1,0,0,0,0,1,1,1,1,0,1,1,2,1,1,0,1
    100845 2014-08-19 0,1,0,1,0,1,1,1,2,0,1,0,1,0,1,0,1,0,1,0,2,1,1,0
    100918 2015-07-02 1,0,0,1,0,1,3,1,1,0,1,0,1,0,1,0,0,1,0,1,0,0,1,1
    100920 2013-02-07 0,1,0,0,1,0,1,1,1,0,0,1,0,0,1,0,0,5,6,4,2,1,0,1
    100920 2013-02-08 0,1,0,0,1,3,5,4,2,1,0,1,0,1,0,0,1,3,7,5,1,1,1,0

The 24 readings per row refer to hourly meter readings during a day. I would like to convert the daily dates to hourly and convert the strings of readings to a column format instead. The IDs should follow this format.
For example, I have implemented the following:

hourly <- data.frame(Hourly=seq(min(as.POSIXct(paste0(df$date, "00:00"),tz="")),max(as.POSIXct(paste0(df$date, "23:00"),tz="")),by="hour"))

How can I fill in the new fields that are created due to the hourly setting with the same IDs as in the daily format? As the full dataset I have is extremely big, I would appreciate a solution that can run very fast.

Body:
I can't speak to the speed of this approach on a data set as large as yours, but I think this code does the steps you want:

library(dplyr)
library(tidyr)

df2 <- df %>%
  # use separate to spread the readings across separate columns
  separate(reading, into = paste0("hour.", seq(24)), sep = ",") %>%
  # use gather to convert that wide data frame into a long one
  gather(key = hour, value = reading, hour.1:hour.24) %>%
  # make the hour marker into a number
  mutate(hour = as.numeric(gsub("hour.", "", hour)) - 1) %>%
  # order the data
  arrange(ID, DATE, hour) %>%
  # create a new column that combines the date and time stamp
  mutate(datetime = as.POSIXct(paste(DATE, hour), format = "%Y-%m-%d %H")) %>%
  # shed unneeded columns
  select(ID, datetime, reading)

Result:

> head(df2)
      ID            datetime reading
1 100845 2014-08-17 00:00:00       0
2 100845 2014-08-17 01:00:00       0
3 100845 2014-08-17 02:00:00       0
4 100845 2014-08-17 03:00:00       0
5 100845 2014-08-17 04:00:00       3
6 100845 2014-08-17 05:00:00       0


问:
JSP form input maxlength not working on number type
I'm using jsp <form:input> tag for input the data on jsp form. The requirement is to limit length of input field and be able to input only numbers.

The following tag works for limiting length of the input string, however I'm able to input any symbols here:

```<code><form:input path="somePath" code="someCode" maxlength="3"/>
</code>```

And when I use type number, maxlength attribute doesn't work and there is no limit on input field, however I'm limited to number only:

<form:input path="somePath" code="someCode" maxlength="3" type="number"/>

Is there a way to have input field limited in maximum length and to numbers only? Can't figure out why the line above doesn't work.

答:
Spring <form:input /> tag doesnt have any attribute named type and the type=number used in your code belongs to html5 input tag

The best way I can think of is to have this validation using Javascript.

Spring form tld lists the valid attributes of form:input element here

Body:
I'm using jsp <form:input> tag for input the data on jsp form. The requirement is to limit length of input field and be able to input only numbers.

The following tag works for limiting length of the input string, however I'm able to input any symbols here:

<form:input path="somePath" code="someCode" maxlength="3"/>

And when I use type number, maxlength attribute doesn't work and there is no limit on input field, however I'm limited to number only:

<form:input path="somePath" code="someCode" maxlength="3" type="number"/>

Is there a way to have input field limited in maximum length and to numbers only? Can't figure out why the line above doesn't work.


问:
php & mysql: Proper handling of all types of queries
I would like to make one universal function for database queries.
The function I have below works perfectly for SELECT queries.
However I would like to have it working properly for INSERT, UPDATE,
DROP and other queries not returning anything. Can someone tell me
why using mysqli_fetch_all for such queries prints warning? How
to properly handle it? How to obtain status of such queries?</p>

```<code>function cms_query($sql_query)
{
    // Object returned by mysqli_connect
    global $cms_db;

    // Perform query
    $result = mysqli_query($cms_db, $sql_query);
    if(!$result) {
        print("ERROR\nFAILED_TO_QUERY\n");
        return;
    }

    // Obtain results
    $rows = mysqli_fetch_all($result, MYSQL_ASSOC);
    if(!$rows) {
        print("OK\n0\n0\n");
        return;
    }

    // Print result array keys
    $keys = array_keys($rows[0]);
    print("OK\n" . count($keys) . "\n");
    foreach($keys as $key)
        print($key . "\n");

    // Print result rows
    print(count($rows) . "\n");
    foreach($rows as $row)
        foreach($row as $value)
            print($value . "\n");
}
</code>```

答:
Well, it's a good idea per se to have such a function, but there is one thing that your function desperately lacking - the support for prepared statements.

So, to make your function work in its current form, it's not a big deal:

```<code>function cms_query($sql_query)
{
    // Object returned by mysqli_connect
    global $cms_db;

    // Perform query
    $result = mysqli_query($cms_db, $sql_query);
    if(!$result) {
        trigger_error(mysqli_error($cms_db));
    }

    // if it was a DML query
    if (if $result === true)
    {
        return;
    }

    // Obtain results
    return mysqli_fetch_all($result, MYSQL_ASSOC);
}
</code>```

but you have to understand that such a function should support prepared statements. And for sake of such a support it's better to use PDO. I wrote such a function, or rather, a PDO wrapper which I strongly recommend for you to consider. Note the Examples part of the article - as you can see, this function can run any kind of query.

Body:
I would like to make one universal function for database queries.
The function I have below works perfectly for SELECT queries.
However I would like to have it working properly for INSERT, UPDATE,
DROP and other queries not returning anything. Can someone tell me
why using mysqli_fetch_all for such queries prints warning? How
to properly handle it? How to obtain status of such queries?

function cms_query($sql_query)
{
    // Object returned by mysqli_connect
    global $cms_db;

    // Perform query
    $result = mysqli_query($cms_db, $sql_query);
    if(!$result) {
        print("ERROR\nFAILED_TO_QUERY\n");
        return;
    }

    // Obtain results
    $rows = mysqli_fetch_all($result, MYSQL_ASSOC);
    if(!$rows) {
        print("OK\n0\n0\n");
        return;
    }

    // Print result array keys
    $keys = array_keys($rows[0]);
    print("OK\n" . count($keys) . "\n");
    foreach($keys as $key)
        print($key . "\n");

    // Print result rows
    print(count($rows) . "\n");
    foreach($rows as $row)
        foreach($row as $value)
            print($value . "\n");
}

Body:
Well, it's a good idea per se to have such a function, but there is one thing that your function desperately lacking - the support for prepared statements.

So, to make your function work in its current form, it's not a big deal:

function cms_query($sql_query)
{
    // Object returned by mysqli_connect
    global $cms_db;

    // Perform query
    $result = mysqli_query($cms_db, $sql_query);
    if(!$result) {
        trigger_error(mysqli_error($cms_db));
    }

    // if it was a DML query
    if (if $result === true)
    {
        return;
    }

    // Obtain results
    return mysqli_fetch_all($result, MYSQL_ASSOC);
}

but you have to understand that such a function should support prepared statements. And for sake of such a support it's better to use PDO. I wrote such a function, or rather, a PDO wrapper which I strongly recommend for you to consider. Note the Examples part of the article - as you can see, this function can run any kind of query.


问:
how to prevent escaping when using newlines in text interpolation (Ruby)
The following three lines of code:

```<code>array = ["line 2", "line 3"]
foo = array.join("\n")
bar = "line 1\n#{foo}\nline4"
</code>```

result in

```<code>"line 1\nline 2\nline 3\nline4"
</code>```

is it possible to combine the 2nd and 3rd line using interpolation?  The following doesn't work:

```<code>bar = "line 1\n#{array.join('\n')}\nline4"
</code>```

because it adds an extra backslash:

```<code>"line 1\nline 2\\nline 3\nline4"
</code>```

答:
You need to use double-quotes around "\n" if you want Ruby to treat it as a newline character instead of two separate characters:

```<code>bar = "line 1\n#{array.join("\n")}\nline4"
                            ^^^^
</code>```

Body:
The following three lines of code:

array = ["line 2", "line 3"]
foo = array.join("\n")
bar = "line 1\n#{foo}\nline4"

result in

"line 1\nline 2\nline 3\nline4"

is it possible to combine the 2nd and 3rd line using interpolation?  The following doesn't work:

bar = "line 1\n#{array.join('\n')}\nline4"

because it adds an extra backslash:

"line 1\nline 2\\nline 3\nline4"

Body:
You need to use double-quotes around "\n" if you want Ruby to treat it as a newline character instead of two separate characters:

bar = "line 1\n#{array.join("\n")}\nline4"
                            ^^^^


问:
How to add EventSource to a web application
We finally got EventSource and ElasticSearch correctly configured in our service fabric cluster.  Now that we have that we want to add EventSources to our web applications that interact with our service fabric applications so that we can view all events (application logs) in one location and filter / query via Kibana.

Our issue seems to be related to the differences between a service fabric app which is an exe and a .NET 4.6 (not .net CORE) web app which is stateless.  In service Fabric we place the using statement that instantiates the pipeline in Program.cs and set an infinite sleep.

```<code>private static void Main()
{
        try
        {
            using (var diagnosticsPipeline = ServiceFabricDiagnosticPipelineFactory.CreatePipeline("CacheApp-CacheAPI-DiagnosticsPipeline"))
            {
                ServiceEventSource.Current.ServiceTypeRegistered(Process.GetCurrentProcess().Id, typeof(Endpoint).Name);
                // Prevents this host process from terminating so services keeps running.
                Thread.Sleep(Timeout.Infinite);
            }
</code>```

How do I do this in a web app?  This is the pipeline code we are using for a non ServiceFabric implementation of the EventSource.  This is what we are using:

```<code>using (var pipeline = DiagnosticPipelineFactory.CreatePipeline("eventFlowConfig.json"))
    {
        IEnumerable ie = System.Diagnostics.Tracing.EventSource.GetSources();

        ServiceEventSource.Current.Message("initialize eventsource");

    }
</code>```

We are able to see the pipeline and send events to ElasticSearch from within the using statement but not outside of it.  So the question is:

how/where do we place our pipeline using statement for a web app?

Do we need to instantiate and destroy the pipeline that every time we log or is there a way to reuse that pipeline across the stateless web events?  It would seem like that would be very expensive and hurt performance.  Maybe we can we cache a pipeline?

That’s the jist, let me know if you need clarification.  I see lots of doco out there for client apps but not much for web apps.

Thanks,
Greg

UPDATE WITH SOLUTION CODE

DiagnosticPipeline pipeline;

```<code>protected void Application_Start(Object sender, EventArgs e)
{
    try
    {
        pipeline = DiagnosticPipelineFactory.CreatePipeline("eventFlowConfig.json");
        IEnumerable ie = System.Diagnostics.Tracing.EventSource.GetSources();
        AppEventSource.Current.Message("initialize eventsource");

    }
}

protected void Application_End(Object sender, EventArgs e)
{
    pipeline.Dispose();
}
</code>```

答:
Assuming ASP.NET Core the simplest way to initialize EventFlow pipeline would be in the Program.cs Main() method, for example:

```<code>public static void Main(string[] args)
{
    using (var pipeline = DiagnosticPipelineFactory.CreatePipeline("eventFlowConfig.json"))
    {
        var host = new WebHostBuilder()
            .UseKestrel()
            .UseContentRoot(Directory.GetCurrentDirectory())
            .UseIISIntegration()
            .UseStartup<Startup>()
            .UseApplicationInsights()
            .Build();

            host.Run();
    }
}
</code>```

This takes advantage of the fact that host.Run() will block until the server is shut down, and so the pipeline will exist during the time when requests are received and served.

Depending on the web framework you use things might vary. E.g. if the one you use offers "setup" and "cleanup" hooks, you could create a diagnostic pipeline during setup phase (and store a reference to it in some member variable), then dispose of it during cleanup phase. For example, in ASP.NET classic you'd put the code in global.asax.cs and leverage Application_OnStart and Application_OnEnd methods. See Application Instances, Application Events, and Application State in ASP.NET for details.

Creating a pipeline instance every time a request is served is quite inefficient, like you said. There is really no good reason to do that.

Body:
We finally got EventSource and ElasticSearch correctly configured in our service fabric cluster.  Now that we have that we want to add EventSources to our web applications that interact with our service fabric applications so that we can view all events (application logs) in one location and filter / query via Kibana.

Our issue seems to be related to the differences between a service fabric app which is an exe and a .NET 4.6 (not .net CORE) web app which is stateless.  In service Fabric we place the using statement that instantiates the pipeline in Program.cs and set an infinite sleep.

private static void Main()
{
        try
        {
            using (var diagnosticsPipeline = ServiceFabricDiagnosticPipelineFactory.CreatePipeline("CacheApp-CacheAPI-DiagnosticsPipeline"))
            {
                ServiceEventSource.Current.ServiceTypeRegistered(Process.GetCurrentProcess().Id, typeof(Endpoint).Name);
                // Prevents this host process from terminating so services keeps running.
                Thread.Sleep(Timeout.Infinite);
            }

How do I do this in a web app?  This is the pipeline code we are using for a non ServiceFabric implementation of the EventSource.  This is what we are using:

using (var pipeline = DiagnosticPipelineFactory.CreatePipeline("eventFlowConfig.json"))
    {
        IEnumerable ie = System.Diagnostics.Tracing.EventSource.GetSources();

        ServiceEventSource.Current.Message("initialize eventsource");

    }

We are able to see the pipeline and send events to ElasticSearch from within the using statement but not outside of it.  So the question is:

how/where do we place our pipeline using statement for a web app?

Do we need to instantiate and destroy the pipeline that every time we log or is there a way to reuse that pipeline across the stateless web events?  It would seem like that would be very expensive and hurt performance.  Maybe we can we cache a pipeline?

That’s the jist, let me know if you need clarification.  I see lots of doco out there for client apps but not much for web apps.

Thanks,
Greg

UPDATE WITH SOLUTION CODE

DiagnosticPipeline pipeline;

protected void Application_Start(Object sender, EventArgs e)
{
    try
    {
        pipeline = DiagnosticPipelineFactory.CreatePipeline("eventFlowConfig.json");
        IEnumerable ie = System.Diagnostics.Tracing.EventSource.GetSources();
        AppEventSource.Current.Message("initialize eventsource");

    }
}

protected void Application_End(Object sender, EventArgs e)
{
    pipeline.Dispose();
}

Body:
Assuming ASP.NET Core the simplest way to initialize EventFlow pipeline would be in the Program.cs Main() method, for example:

public static void Main(string[] args)
{
    using (var pipeline = DiagnosticPipelineFactory.CreatePipeline("eventFlowConfig.json"))
    {
        var host = new WebHostBuilder()
            .UseKestrel()
            .UseContentRoot(Directory.GetCurrentDirectory())
            .UseIISIntegration()
            .UseStartup<Startup>()
            .UseApplicationInsights()
            .Build();

            host.Run();
    }
}

This takes advantage of the fact that host.Run() will block until the server is shut down, and so the pipeline will exist during the time when requests are received and served.

Depending on the web framework you use things might vary. E.g. if the one you use offers "setup" and "cleanup" hooks, you could create a diagnostic pipeline during setup phase (and store a reference to it in some member variable), then dispose of it during cleanup phase. For example, in ASP.NET classic you'd put the code in global.asax.cs and leverage Application_OnStart and Application_OnEnd methods. See Application Instances, Application Events, and Application State in ASP.NET for details.

Creating a pipeline instance every time a request is served is quite inefficient, like you said. There is really no good reason to do that.


问:
Double versus float
I have a constant for pi in my code:

const float PI = acos(-1);

Would it be better to declare it as a double?  An answer to another question on this site said floating point operations aren't exactly precise, and I'd like the constant to be accurate.

答:
It depends exactly how precise you need to be. I've never had to you doubles because floats are not precise enough.

The most accurate representation of pi is M_PI from math.h

Title: Double versus float


问:
How to make correct revert to specific version in django-reversion?
I have 2 question cause little bit comfused with django-reversion app. I have page where users can see list all of reversions. Every version has button to revert.

1 Question: How to show only some fields of changes. Right now it shows me all fields. I use version.field_dict.items.

2 Question: How to make correct revert to specific version?

Here below you can see code but it raise Error in views.py when I try to click to revert link. What I did wrong?

template.html

```<code>{% for version in versions %}
       {% for field_name, field_value in version.field_dict.items %}
             {{ field_name }}
             {{ field_value }}
       {% endfor %}
       <a href="{% url 'project:group_task_revert' project_code=project.code group_task_code=group_task.code group_task_reversion_id=version.revision.id%}">REVERT</a>
{% endfor %}
</code>```

urls.py:

```<code> url(r'^(?P<project_code>[0-9a-f-]+)/(?P<group_code>[0-9a-f-]+)/(?P<group_reversion_id>\d+)/$',
        group_revert,
        name='group_revert'),
</code>```

views.py:

```<code>def group_revert(request, project_code, group_code, group_reversion_id):
    project = get_object_or_404(Project, pk=project_code, status='open')
    group = get_object_or_404(Group, pk=group_code)

    versions = Version.objects.get_for_object(group)
    versions[group_reversion_id].revision.revert()

    return redirect('project:project_detail', project_code=project.code)
</code>```

ERROR:

```<code>Internal Server Error: /ru/account/dashboard/projects/42442299-97dd-4d92-9ef1-880f9cdd1612/4d3d3422-2618-4d66-96f5-8f0a0b5d9bf3/21/
Traceback (most recent call last):
  File "C:\Users\Nurzhan\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\core\handlers\exception.py", line 39, in inner
    response = get_response(request)
  File "C:\Users\Nurzhan\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\core\handlers\base.py", line 187, in _get_response
    response = self.process_exception_by_middleware(e, request)
  File "C:\Users\Nurzhan\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\core\handlers\base.py", line 185, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "C:\Users\Nurzhan\PycharmProjects\RMS\project\views.py", line 198, in group_revert
    versions[group_reversion_id].revision.revert()
  File "C:\Users\Nurzhan\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\db\models\query.py", line 271, in __getitem__
    raise TypeError
TypeError
</code>```

答: I found the answer to this question: dhango-reversion</p>

Body:
I have 2 question cause little bit comfused with django-reversion app. I have page where users can see list all of reversions. Every version has button to revert.

1 Question: How to show only some fields of changes. Right now it shows me all fields. I use version.field_dict.items.

2 Question: How to make correct revert to specific version?

Here below you can see code but it raise Error in views.py when I try to click to revert link. What I did wrong?

template.html

{% for version in versions %}
       {% for field_name, field_value in version.field_dict.items %}
             {{ field_name }}
             {{ field_value }}
       {% endfor %}
       REVERT
{% endfor %}

urls.py:

 url(r'^(?P<project_code>[0-9a-f-]+)/(?P<group_code>[0-9a-f-]+)/(?P<group_reversion_id>\d+)/$',
        group_revert,
        name='group_revert'),

views.py:

def group_revert(request, project_code, group_code, group_reversion_id):
    project = get_object_or_404(Project, pk=project_code, status='open')
    group = get_object_or_404(Group, pk=group_code)

    versions = Version.objects.get_for_object(group)
    versions[group_reversion_id].revision.revert()

    return redirect('project:project_detail', project_code=project.code)

ERROR:

Internal Server Error: /ru/account/dashboard/projects/42442299-97dd-4d92-9ef1-880f9cdd1612/4d3d3422-2618-4d66-96f5-8f0a0b5d9bf3/21/
Traceback (most recent call last):
  File "C:\Users\Nurzhan\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\core\handlers\exception.py", line 39, in inner
    response = get_response(request)
  File "C:\Users\Nurzhan\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\core\handlers\base.py", line 187, in _get_response
    response = self.process_exception_by_middleware(e, request)
  File "C:\Users\Nurzhan\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\core\handlers\base.py", line 185, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "C:\Users\Nurzhan\PycharmProjects\RMS\project\views.py", line 198, in group_revert
    versions[group_reversion_id].revision.revert()
  File "C:\Users\Nurzhan\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\db\models\query.py", line 271, in __getitem__
    raise TypeError
TypeError


问:
javax.mail.MessagingException: Could not convert socket to TLS exception in JAVA
I want to send a mail from my email address to another email address via clicking a button in JFrame netbeans.Here is the code,

```<code>import java.awt.HeadlessException;
import java.util.Properties;
import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import javax.swing.JOptionPane;
import com.sun.mail.util.MailSSLSocketFactory;
import java.io.File;
import javax.mail.PasswordAuthentication;
import javax.mail.*;
import javax.swing.JFileChooser;

    private void btn_sendActionPerformed(java.awt.event.ActionEvent evt) {
    final String From = txt_from.getText();
    final String password = txt_password.getText();
    String To = txt_to.getText();
    String subject = txt_sub.getText();
    String txtmessage = txt_body.getText();

    Properties props = new Properties();

    props.put("mail.smtp.host", "smtp.gmail.com");
    props.put("mail.smtp.socketFactory.port", "587");
    props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLsocketFactory");
    props.put("mail.smtp.auth", "true");
    props.put("mail.smtp.port", "587");
    props.put("mail.smtp.starttls.enable", "true");
    props.put("mail.smtp.ssl.trust", "smtp.gmail.com");
    props.put("mail.smtp.socketFactory.fallback", "true");
    props.put("mail.smtp.ssl.socketFactory", "true");
    props.put("mail.smtp.EnableSSL.enable","true");

    Session session = Session.getDefaultInstance(props,
            new javax.mail.Authenticator() {

                protected PasswordAuthentication getPasswordAuthentication() {
                    return new PasswordAuthentication(From, password);
                }
            }
    );

    try {
        Message message = new MimeMessage(session);
        message.setFrom(new InternetAddress(From));
        message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(To));
        message.setSubject(subject);

        MimeBodyPart messageBodyPart = new MimeBodyPart();
        messageBodyPart.setText(txtmessage);
        Multipart multiPart = new MimeMultipart();
        multiPart.addBodyPart(messageBodyPart);

        messageBodyPart = new MimeBodyPart();
        DataSource source = new FileDataSource(attachment_path);
        messageBodyPart.setDataHandler(new DataHandler(source));
        messageBodyPart.setFileName(txt_DocAttach.getText());
        multiPart.addBodyPart(messageBodyPart);

        message.setContent(multiPart);

        Transport.send(message);
        JOptionPane.showMessageDialog(rootPane, "Message is sent");
    } catch (MessagingException | HeadlessException e) {
        JOptionPane.showMessageDialog(rootPane, e);
    }

}
</code>```

But it is giving me following error,

javax.mail.MessagingException: Could not convert socket to TLS; nested exception is: java.io.lOException: Exception in startTLS using SSL socket factory class null: host, port smtp.gmail.com, 587; Exception: java.lang.ClassNotFoundException: javax.netssl.SSLsocketFactory

Tried a lot but can't figure out what to do to solve it? Help please.

答:
Try to change the value of the property mail.smtp.socketFactory.class
to javax.net.ssl.SSLSocketFactory instead of javax.net.ssl.SSLsocketFactory,
The class name is case sensitive.

For more infromations about connection properties you can look at:
Where to find all available Java mail properties?

Body:
I want to send a mail from my email address to another email address via clicking a button in JFrame netbeans.Here is the code,

import java.awt.HeadlessException;
import java.util.Properties;
import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import javax.swing.JOptionPane;
import com.sun.mail.util.MailSSLSocketFactory;
import java.io.File;
import javax.mail.PasswordAuthentication;
import javax.mail.*;
import javax.swing.JFileChooser;

    private void btn_sendActionPerformed(java.awt.event.ActionEvent evt) {
    final String From = txt_from.getText();
    final String password = txt_password.getText();
    String To = txt_to.getText();
    String subject = txt_sub.getText();
    String txtmessage = txt_body.getText();

    Properties props = new Properties();

    props.put("mail.smtp.host", "smtp.gmail.com");
    props.put("mail.smtp.socketFactory.port", "587");
    props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLsocketFactory");
    props.put("mail.smtp.auth", "true");
    props.put("mail.smtp.port", "587");
    props.put("mail.smtp.starttls.enable", "true");
    props.put("mail.smtp.ssl.trust", "smtp.gmail.com");
    props.put("mail.smtp.socketFactory.fallback", "true");
    props.put("mail.smtp.ssl.socketFactory", "true");
    props.put("mail.smtp.EnableSSL.enable","true");

    Session session = Session.getDefaultInstance(props,
            new javax.mail.Authenticator() {

                protected PasswordAuthentication getPasswordAuthentication() {
                    return new PasswordAuthentication(From, password);
                }
            }
    );

    try {
        Message message = new MimeMessage(session);
        message.setFrom(new InternetAddress(From));
        message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(To));
        message.setSubject(subject);

        MimeBodyPart messageBodyPart = new MimeBodyPart();
        messageBodyPart.setText(txtmessage);
        Multipart multiPart = new MimeMultipart();
        multiPart.addBodyPart(messageBodyPart);

        messageBodyPart = new MimeBodyPart();
        DataSource source = new FileDataSource(attachment_path);
        messageBodyPart.setDataHandler(new DataHandler(source));
        messageBodyPart.setFileName(txt_DocAttach.getText());
        multiPart.addBodyPart(messageBodyPart);

        message.setContent(multiPart);

        Transport.send(message);
        JOptionPane.showMessageDialog(rootPane, "Message is sent");
    } catch (MessagingException | HeadlessException e) {
        JOptionPane.showMessageDialog(rootPane, e);
    }

}

But it is giving me following error,

javax.mail.MessagingException: Could not convert socket to TLS; nested exception is: java.io.lOException: Exception in startTLS using SSL socket factory class null: host, port smtp.gmail.com, 587; Exception: java.lang.ClassNotFoundException: javax.netssl.SSLsocketFactory

Tried a lot but can't figure out what to do to solve it? Help please.


问:
Sending email alert from excel to Outlook
I am trying to send a test mail from excel to Outlook, However I am getting error message : Run Time Error 287 in the following line :

```<code>OutMail.Send
</code>```

Please find below my code:

```<code>Sub sendds()

    Dim OutMail As MailItem
    Dim outlookapp As Outlook.Application
     Dim myInspector As Outlook.Inspector

Set outlookapp = CreateObject("Outlook.application")
Set OutMail = outlookapp.CreateItem(olMailItem)

With OutMail

    .To = "email address"
    .Subject = "test mail"
    .Body = "Hi this is test email"

    OutMail.Send 'Getting error on this line

    End With

 Set outlookapp = Nothing
Set OutMail = Nothing

End Sub
</code>```

答:
Based on the comment "when I am using outMail.display it displays the email which I want to send but I actually want to send the email" the code is too fast. It would likely as well work if you stepped through with F8.

You could use Excel's Wait to delay the send.

This should as well work for all applications and it would be the minimum waiting period.

```<code>Sub sendds_ErrorHandlerWait()

    Dim OutMail As MailItem
    Dim outlookapp As Outlook.Application
    Dim myInspector As Outlook.Inspector

    Set outlookapp = CreateObject("Outlook.application")
    Set OutMail = outlookapp.CreateItem(olMailItem)

    With OutMail

        .To = "email address"
        .Subject = "test mail"
        .body = "Hi this is test email"

        On Error GoTo ErrorHandler
        ' Err.Raise 287 ' for testing
        ' Err.Raise 1   ' for testing
        .Send
        On Error GoTo 0

    End With

ExitRoutine:
    Set outlookapp = Nothing
    Set OutMail = Nothing

    Exit Sub

ErrorHandler:

    Select Case Err

    Case 287
        DoEvents ' To accept clicks and to allow escaping if Outlook never opens
        Debug.Print " <Ctrl> + <Break> to escape"
        Resume

    Case Else
        On Error GoTo 0
        ' Break on other lines with an error
        Resume

End Select

End Sub
</code>```

It appears your Outlook setup requires a display. If there is no fix for that situation, you may be able to use an invisible display.

```<code>Sub sendds_InspectorRatherThanDisplay()

    Dim OutMail As mailItem
    Dim outlookapp As Outlook.Application
    Dim myInspector As Outlook.Inspector

    Set outlookapp = CreateObject("Outlook.application")
    Set OutMail = outlookapp.CreateItem(olMailItem)

    With OutMail

        .To = "email address"
        .Subject = "test mail"
        .body = "Hi this is test email"

        Set myInspector = .GetInspector
        .Send

    End With

ExitRoutine:
    Set outlookapp = Nothing
    Set OutMail = Nothing
    Set myInspector = Nothing

End Sub
</code>```

Body:
I am trying to send a test mail from excel to Outlook, However I am getting error message : Run Time Error 287 in the following line :

OutMail.Send

Please find below my code:

Sub sendds()

    Dim OutMail As MailItem
    Dim outlookapp As Outlook.Application
     Dim myInspector As Outlook.Inspector

Set outlookapp = CreateObject("Outlook.application")
Set OutMail = outlookapp.CreateItem(olMailItem)

With OutMail

    .To = "email address"
    .Subject = "test mail"
    .Body = "Hi this is test email"

    OutMail.Send 'Getting error on this line

    End With

 Set outlookapp = Nothing
Set OutMail = Nothing

End Sub

Body:
Based on the comment "when I am using outMail.display it displays the email which I want to send but I actually want to send the email" the code is too fast. It would likely as well work if you stepped through with F8.

You could use Excel's Wait to delay the send.

This should as well work for all applications and it would be the minimum waiting period.

Sub sendds_ErrorHandlerWait()

    Dim OutMail As MailItem
    Dim outlookapp As Outlook.Application
    Dim myInspector As Outlook.Inspector

    Set outlookapp = CreateObject("Outlook.application")
    Set OutMail = outlookapp.CreateItem(olMailItem)

    With OutMail

        .To = "email address"
        .Subject = "test mail"
        .body = "Hi this is test email"

        On Error GoTo ErrorHandler
        ' Err.Raise 287 ' for testing
        ' Err.Raise 1   ' for testing
        .Send
        On Error GoTo 0

    End With

ExitRoutine:
    Set outlookapp = Nothing
    Set OutMail = Nothing

    Exit Sub

ErrorHandler:

    Select Case Err

    Case 287
        DoEvents ' To accept clicks and to allow escaping if Outlook never opens
        Debug.Print " <Ctrl> + <Break> to escape"
        Resume

    Case Else
        On Error GoTo 0
        ' Break on other lines with an error
        Resume

End Select

End Sub

It appears your Outlook setup requires a display. If there is no fix for that situation, you may be able to use an invisible display.

Sub sendds_InspectorRatherThanDisplay()

    Dim OutMail As mailItem
    Dim outlookapp As Outlook.Application
    Dim myInspector As Outlook.Inspector

    Set outlookapp = CreateObject("Outlook.application")
    Set OutMail = outlookapp.CreateItem(olMailItem)

    With OutMail

        .To = "email address"
        .Subject = "test mail"
        .body = "Hi this is test email"

        Set myInspector = .GetInspector
        .Send

    End With

ExitRoutine:
    Set outlookapp = Nothing
    Set OutMail = Nothing
    Set myInspector = Nothing

End Sub


问:
Timer in VC++ for Non-GUI Applications
I want to test a code which is designed for running on a Microcontroller and it is platform independent.

Problem is I currently don't have any Embedded simulator (due to some damn reason!) and I want to test it... I am using Visual Studio 2008 (What a Pity!!).... Code is entirely in C but as VS 2008 doesn't support C, I have stored files as .cpp.... But No C++ concept is used!!

What all I require is a Timer which would generate Interrupt after every 1 millisecond!

And One more thing.... Can I configure something so that an Interrupt will be generated if I press certain key on Keyboard....

I don't want to make GUI. I searched for Timers and all were for MFC application.... If there isn't any option, I will make a rough MFC...

Regards!!

答:
For high precision timers the your best bet is probably CreateTimerQueueTimer (not used personally).

Personally I used to use timeSetEvent but that was way back years and years ago.

Title: Timer in VC++ for Non-GUI Applications