问:
php allow access to pages to only logged in users
I have 3 pages have html code similar to just example

<!DOCTYPE html>

html code

html code

html code

```

and have 2 php files login.php and logout.php , is it possible to strict access to the 3 pages only to login users

答:
You need to use session to do it in PHP, it will be like this.

```<code>$_SESSION(id)
</code>```

You can see some tutorial in google.

Refer the below link http://www.makeitsimple.co.in/PHP_loginexmp.php

Body:
I have 3 pages have html code similar to just example

<!DOCTYPE html>

html code

html code

html code

and have 2 php files login.php and logout.php , is it possible to strict access to the 3 pages only to login users

Body:
You need to use session to do it in PHP, it will be like this.

$_SESSION(id)

You can see some tutorial in google.

Refer the below link http://www.makeitsimple.co.in/PHP_loginexmp.php


来源: stackexchange

问:
Fill Pdf Form in Ruby using pdf-form gem
I want to programmatically fill a pdf using pdf-form gem

I was able to read the fields using the following code:

```<code>require 'pdf_forms'
pdftk = PdfForms.new('/usr/local/bin/pdftk')
fields = pdftk.get_fields('*/Desktop/sample_pdf.pdf')
for f in fields
  print f.to_s
end
</code>```

But when I tried to fill the Pdf with the provide synthax, I created only an empty, not openable pdf.

```<code>pdftk.fill_form '/path/to/form.pdf', 'target.pdf', ['Value Name'] => 'Value to be inserted'
</code>```

Does anybody know a working solution?

Thanks in advance!!!

Additional Information:

the fields of the pdf are the following: Name, Address, Dropdown1, Dropdown2, Dropdown3, Check Box4, Check Box1, Check Box3, Check Box2, Text5, Button7, Text6, Group6, %

I tried it with filling just one field:

pdftk.fill_form 'sample_pdf.pdf', 'sample_pdf_filled.pdf', {["Name"]=>"Value to be inserted"}

The result: I have an pdf "sample_pdf_filled.pdf", which I cannot open, because it's empty. I thought my problem is the form-filling, but it seems, that the pdf is not created correctly.

Note: I am working on a mac (unix)

Has anybody a solution?

答:
I found a solution - for all MAC OS X 10.11 El Capitan User:

PDFtk Server on OS X 10.11

ContentLicense: CC BY-SA 3.0

Body:
I want to programmatically fill a pdf using pdf-form gem

I was able to read the fields using the following code:

require 'pdf_forms'
pdftk = PdfForms.new('/usr/local/bin/pdftk')
fields = pdftk.get_fields('*/Desktop/sample_pdf.pdf')
for f in fields
  print f.to_s
end

But when I tried to fill the Pdf with the provide synthax, I created only an empty, not openable pdf.

pdftk.fill_form '/path/to/form.pdf', 'target.pdf', ['Value Name'] => 'Value to be inserted'

Does anybody know a working solution?

Thanks in advance!!!

Additional Information:

the fields of the pdf are the following: Name, Address, Dropdown1, Dropdown2, Dropdown3, Check Box4, Check Box1, Check Box3, Check Box2, Text5, Button7, Text6, Group6, %

I tried it with filling just one field:

pdftk.fill_form 'sample_pdf.pdf', 'sample_pdf_filled.pdf', {["Name"]=>"Value to be inserted"}

The result: I have an pdf "sample_pdf_filled.pdf", which I cannot open, because it's empty. I thought my problem is the form-filling, but it seems, that the pdf is not created correctly.

Note: I am working on a mac (unix)

Has anybody a solution?


问:
How to sort a HashMap by it amount of value in Java
I have declared a HashMap like this:

```<code>Map<Integer,ArrayList<Integer>> numbers = new HashMap<Integer,ArrayList<Integer>>();
</code>```

It has an output like this:

{64=[61, 68, 77], 65=[63, 66, 66, 70], 66=[69, 75, 2], 2=[4], 67=[65, 77], 4=[2]}

How do I count an value amount of its key?

So for 64 will be 3, 65 will be 4 and 66 will be 3

And then get a keys which has top 3 value amount
So the output in this case be like 65 64 66

答: Iterrate Map and get Key after that get value based on key those return list and take list size and hold in new map if iteration done after that iterated your new map.</p>

Body:
I have declared a HashMap like this:

Map<Integer,ArrayList<Integer>> numbers = new HashMap<Integer,ArrayList<Integer>>();

It has an output like this:

{64=[61, 68, 77], 65=[63, 66, 66, 70], 66=[69, 75, 2], 2=[4], 67=[65, 77], 4=[2]}

How do I count an value amount of its key?

So for 64 will be 3, 65 will be 4 and 66 will be 3

And then get a keys which has top 3 value amount
So the output in this case be like 65 64 66


问:
Swift 3 found nil when Firebase DB persistence is enabled
In my app I am using Firebase db to store my data, I have everything working as it should, with my tableview populating with the data from the db.  However I have found that on initial start it is quite slow to download the data, so I enable persistence in AppDelegate.  When I did this and ran the app it crashes on load with an unexpectedly found nil error.

```<code>FIRDatabase.database().persistenceEnabled = true
</code>```

is the line I added to AppDelegate under didFinishLaunching section.

The error occurs in this class on the line I have marked

```<code>import Foundation
import FirebaseDatabase
import CoreLocation

struct newTracks {

//Declerations
var locationManager = CLLocationManager()
let name: String!
let lat: Double!
let lon: Double!
let countryImage: String!
let link: String!
let ref: FIRDatabaseReference?
let distance: Double

//Initialize
init(name: String, trackId: Int, postcode: String, trackType: String, trackURL: String, locID: Int, lat: Double, lon: Double, phoneNumber: String, email: String, rating: Double, numrating: Double, totalrating: Double, countryImage: String, link: String, distance: Double) {
    self.name = name
    self.ref = nil
    self.lat = lat
    self.lon = lon
    self.countryImage = countryImage
    self.link = link
    self.distance = distance
 }

//Initialize data from Firebase
init(snapshot: FIRDataSnapshot) {

    let snapshotValue = snapshot.value as! [String: AnyObject]
    name = snapshotValue["name"] as! String
    lat = snapshotValue["lat"]as! Double
    lon = snapshotValue["long"]as! Double
    ref = snapshot.ref
    countryImage = snapshotValue["country"] as! String   <--  Unexpectedly found nil
    link = snapshotValue["link"] as! String

    let currentLat = self.locationManager.location!.coordinate.latitude
    let currentLon = self.locationManager.location!.coordinate.longitude
    let myLocation = CLLocation(latitude: currentLat, longitude: currentLon)
    let loc = CLLocation(latitude: lat, longitude: lon)
    let distanceInMiles = round(myLocation.distance(from: loc) / 1609.34)
    distance = distanceInMiles

}

func toAnyObject() -> Any {
    return [
        "name": name,
        "lat": lat,
        "lon": lon,
        "countryImage": countryImage,
        "link": link,
        "distance": distance
    ]

 }

}
</code>```

I don't get why this works ok when persistence isn't switched on, but when I enable it it crashes.  Any help is much appreciated.

答: I have resolved this by uninstalling the app from my phone, this cleared away the old cached data, seems to load ok now</p>

Body:
In my app I am using Firebase db to store my data, I have everything working as it should, with my tableview populating with the data from the db.  However I have found that on initial start it is quite slow to download the data, so I enable persistence in AppDelegate.  When I did this and ran the app it crashes on load with an unexpectedly found nil error.

FIRDatabase.database().persistenceEnabled = true

is the line I added to AppDelegate under didFinishLaunching section.

The error occurs in this class on the line I have marked

import Foundation
import FirebaseDatabase
import CoreLocation

struct newTracks {

//Declerations
var locationManager = CLLocationManager()
let name: String!
let lat: Double!
let lon: Double!
let countryImage: String!
let link: String!
let ref: FIRDatabaseReference?
let distance: Double

//Initialize
init(name: String, trackId: Int, postcode: String, trackType: String, trackURL: String, locID: Int, lat: Double, lon: Double, phoneNumber: String, email: String, rating: Double, numrating: Double, totalrating: Double, countryImage: String, link: String, distance: Double) {
    self.name = name
    self.ref = nil
    self.lat = lat
    self.lon = lon
    self.countryImage = countryImage
    self.link = link
    self.distance = distance
 }

//Initialize data from Firebase
init(snapshot: FIRDataSnapshot) {

    let snapshotValue = snapshot.value as! [String: AnyObject]
    name = snapshotValue["name"] as! String
    lat = snapshotValue["lat"]as! Double
    lon = snapshotValue["long"]as! Double
    ref = snapshot.ref
    countryImage = snapshotValue["country"] as! String   <--  Unexpectedly found nil
    link = snapshotValue["link"] as! String

    let currentLat = self.locationManager.location!.coordinate.latitude
    let currentLon = self.locationManager.location!.coordinate.longitude
    let myLocation = CLLocation(latitude: currentLat, longitude: currentLon)
    let loc = CLLocation(latitude: lat, longitude: lon)
    let distanceInMiles = round(myLocation.distance(from: loc) / 1609.34)
    distance = distanceInMiles

}

func toAnyObject() -> Any {
    return [
        "name": name,
        "lat": lat,
        "lon": lon,
        "countryImage": countryImage,
        "link": link,
        "distance": distance
    ]

 }

}

I don't get why this works ok when persistence isn't switched on, but when I enable it it crashes.  Any help is much appreciated.


问:
Text contents in :before/:after of <select>
I need to add custom text to :before and :after <select> element.
But it does not seem to be working.

Please help.

Fiddle link : https://jsfiddle.net/cpwkg0vu/2/

答:
Select tags doesn't allow :after or :before pseudos that's why you have to wrap it with any element assigning it pseudos  elements

#count {
  margin: 20px;
}

.wrapper:before {
  content: 'Show ';
}

.wrapper:after {
  content: ' rows';
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="wrapper">
  <select id="count">
    <option value=5>5</option>
    <option value=10>10</option>
    <option value=50>50</option>
    <option value="All">All</option>
  </select>
</div></code>```

```<code><div class="wrapper">
  <select id="count">
    <option value=5>5</option>
    <option value=10>10</option>
    <option value=50>50</option>
    <option value="All">All</option>
  </select>
</div>

#count {
  margin: 20px;
}

    .wrapper:before {
      content: 'Show ';
    }

.wrapper:after {
  content: ' rows';
}
</code>```

Body:
Select tags doesn't allow :after or :before pseudos that's why you have to wrap it with any element assigning it pseudos  elements

#count {
  margin: 20px;
}

.wrapper:before {
  content: 'Show ';
}

.wrapper:after {
  content: ' rows';
}

<div class="wrapper">
  <select id="count">
    <option value=5>5</option>
    <option value=10>10</option>
    <option value=50>50</option>
    <option value="All">All</option>
  </select>
</div>

<div class="wrapper">
  <select id="count">
    <option value=5>5</option>
    <option value=10>10</option>
    <option value=50>50</option>
    <option value="All">All</option>
  </select>
</div>

#count {
  margin: 20px;
}

    .wrapper:before {
      content: 'Show ';
    }

.wrapper:after {
  content: ' rows';
}


问:
Difference between ArrayList<String>() and mutableListOf<String>() in Kotlin
```<code>private val repositories = mutableListOf<String>()

private val repositories = ArrayList<String>()
</code>```

Both are mutable list, then what is the point of two keywords mutableListOf or ArrayList?

or is there any major difference?

答:
The only difference between the two is communicating your intent.

When you write val a = mutableListOf(), you're saying "I want a mutable list, and I don't particularly care about the implementation". When you write, instead, val a = ArrayList(), you're saying "I specifically want an ArrayList".

In practice, in the current implementation of Kotlin compiling to the JVM, calling mutableListOf will produce an ArrayList, and there's no difference in behaviour: once the list is built, everything will behave the same.

Now, let's say that a future version of Kotlin changes mutableListOf to return a different type of list.

Likelier than not, the Kotlin team would only make that change if they figure the new implementation works better for most use cases. mutableListOf would then have you using that new list implementation transparently, and you'd get that better behaviour for free. Go with mutableListOf if that sounds like your case.

On the other hand, maybe you spent a bunch of time thinking about your problem, and figured that ArrayList really is the best fit for your problem, and you don't want to risk getting moved to something sub-optimal. Then you probably want to either use ArrayList directly, or use the arrayListOf factory function (an ArrayList-specific analogue to mutableListOf).

Body:
private val repositories = mutableListOf<String>()

private val repositories = ArrayList<String>()

Both are mutable list, then what is the point of two keywords mutableListOf or ArrayList?

or is there any major difference?

ContentLicense: CC BY-SA 4.0


问:
Resolve promises one after another (i.e. in sequence)?
Consider the following code that reads an array of files in a serial/sequential manner. readFiles returns a promise, which is resolved only once all files have been read in sequence.

```<code>var readFile = function(file) {
  ... // Returns a promise.
};

var readFiles = function(files) {
  return new Promise((resolve, reject) => {
    var readSequential = function(index) {
      if (index >= files.length) {
        resolve();
      } else {
        readFile(files[index]).then(function() {
          readSequential(index + 1);
        }).catch(reject);
      }
    };

    readSequential(0); // Start with the first file!
  });
};
</code>```

The above code works, but I don't like having to do recursion for things to occur sequentially. Is there a simpler way that this code can be re-written so that I don't have to use my weird readSequential function?

Originally I tried to use Promise.all, but that caused all of the readFile calls to happen concurrently, which is not what I want:

```<code>var readFiles = function(files) {
  return Promise.all(files.map(function(file) {
    return readFile(file);
  }));
};
</code>```

答:
Your approach is not bad, but it does have two issues: it swallows errors and it employs the Explicit Promise Construction Antipattern.

You can solve both of these issues, and make the code cleaner, while still employing the same general strategy:

```<code>var Q = require("q");

var readFile = function(file) {
  ... // Returns a promise.
};

var readFiles = function(files) {
  var readSequential = function(index) {
    if (index < files.length) {
      return readFile(files[index]).then(function() {
        return readSequential(index + 1);
      });
    }
  };

  // using Promise.resolve() here in case files.length is 0
  return Promise.resolve(readSequential(0)); // Start!
};
</code>```

Body:
Consider the following code that reads an array of files in a serial/sequential manner. readFiles returns a promise, which is resolved only once all files have been read in sequence.

var readFile = function(file) {
  ... // Returns a promise.
};

var readFiles = function(files) {
  return new Promise((resolve, reject) => {
    var readSequential = function(index) {
      if (index >= files.length) {
        resolve();
      } else {
        readFile(files[index]).then(function() {
          readSequential(index + 1);
        }).catch(reject);
      }
    };

    readSequential(0); // Start with the first file!
  });
};

The above code works, but I don't like having to do recursion for things to occur sequentially. Is there a simpler way that this code can be re-written so that I don't have to use my weird readSequential function?

Originally I tried to use Promise.all, but that caused all of the readFile calls to happen concurrently, which is not what I want:

var readFiles = function(files) {
  return Promise.all(files.map(function(file) {
    return readFile(file);
  }));
};

Body:
Your approach is not bad, but it does have two issues: it swallows errors and it employs the Explicit Promise Construction Antipattern.

You can solve both of these issues, and make the code cleaner, while still employing the same general strategy:

var Q = require("q");

var readFile = function(file) {
  ... // Returns a promise.
};

var readFiles = function(files) {
  var readSequential = function(index) {
    if (index < files.length) {
      return readFile(files[index]).then(function() {
        return readSequential(index + 1);
      });
    }
  };

  // using Promise.resolve() here in case files.length is 0
  return Promise.resolve(readSequential(0)); // Start!
};


问:
Video capture dialog keeps popping up with embedded PC webcam delphi app
I have a delphi app that takes snapshots from a webcam at 1 sec intervals.  On the development PC it goes fine, but on the target platform (Atom-based tablet PC running embedded Windows 7 with a different camera) it is extremely flaky.  After a reboot and the first time the app is run, it normally manages to initialise the webcam OK and get regular frames from it, but the next time the app is run, it fails to locate the webcam driver, and also pops up a dialog asking me to specify the video source, presumably because it can't find one..

My question:  I'm sure this is related to video capture API calls not being in the right order or something, but is there a tool (like wireshark) that will enable me to sniff the API calls, so I can compare what is happening on the embedded Windows 7 system to the XP development system that works?

I am using the following calls/messages:

Initialisation:

```<code>capCreateCaptureWindow
WM_CAP_DRIVER_CONNECT
WM_CAP_SET_PREVIEW (false)
WM_CAP_SET_VIDEOFORMAT (as camera after boot is in format I can't handle)
WM_CAP_GET_VIDEOFORMAT
</code>```

On 1 sec timer:

```<code>WM_CAP_SET_CALLBACK_FRAME
WM_CAP_GRAB_FRAME_NOSTOP
</code>```

On callback:

```<code>WM_CAP_SET_CALLBACK_FRAME (nil)
</code>```

On finish:

```<code>WM_CAP_ABORT
WM_CAP_STOP
WM_CAP_DRIVER_DISCONNECT
</code>```

答:
The first step is a lot easier: Did you make absolutely sure you have the same driver?

It might also be that the sequence of detect - start acquisition is too fast for this slow system. See if introducing a few secs sleep inbetween helps

ContentLicense: CC BY-SA 2.5

Body:
I have a delphi app that takes snapshots from a webcam at 1 sec intervals.  On the development PC it goes fine, but on the target platform (Atom-based tablet PC running embedded Windows 7 with a different camera) it is extremely flaky.  After a reboot and the first time the app is run, it normally manages to initialise the webcam OK and get regular frames from it, but the next time the app is run, it fails to locate the webcam driver, and also pops up a dialog asking me to specify the video source, presumably because it can't find one..

My question:  I'm sure this is related to video capture API calls not being in the right order or something, but is there a tool (like wireshark) that will enable me to sniff the API calls, so I can compare what is happening on the embedded Windows 7 system to the XP development system that works?

I am using the following calls/messages:

Initialisation:

capCreateCaptureWindow
WM_CAP_DRIVER_CONNECT
WM_CAP_SET_PREVIEW (false)
WM_CAP_SET_VIDEOFORMAT (as camera after boot is in format I can't handle)
WM_CAP_GET_VIDEOFORMAT

On 1 sec timer:

WM_CAP_SET_CALLBACK_FRAME
WM_CAP_GRAB_FRAME_NOSTOP

On callback:

WM_CAP_SET_CALLBACK_FRAME (nil)

On finish:

WM_CAP_ABORT
WM_CAP_STOP
WM_CAP_DRIVER_DISCONNECT


问:
Juqey addclass is not working?
On click of "category_filter" class it should add active class when again reclick means it should remove class otherwise no if page reloads also How to resolve this?

Below is my html code,

 Fitted bed Sheet

 Flat bed sheet

 Full bed sheets

 Twin bed sheet

 Twinxl bed sheets

 Queen bed sheet

 King bed sheets

 Cal king bed sheets

 Duvet covers

 Bed skirts

 Standard Pillow cases

 King Pillow cases

 Pillow shells
```
</div>
</div>
</p>

<p>Juqey code,</p>

```$(document).ready(function () {
    $('.category_filter').click(function(e) {

        $('.category_filter').removeClass('active');

        var $parent = $(this).parent();
        if (!$parent.hasClass('active')) {
            $parent.addClass('active');
        }
        e.preventDefault();
    });
});
```

答:
Instead of this you can use toggleClass

```<code>$(document).ready(function () {
    $('.category_filter').click(function(e) {
        e.preventDefault();
        $('.category_filter').removeClass('active');
        var $parent = $(this).parent();
        if (!$parent.hasClass('active')) {
            $parent.toggleClass('active');
        }
    });
});
</code>```

Title: Juqey addclass is not working?

Body:
On click of "category_filter" class it should add active class when again reclick means it should remove class otherwise no if page reloads also How to resolve this?

Below is my html code,

 Fitted bed Sheet

 Flat bed sheet

 Full bed sheets

 Twin bed sheet

 Twinxl bed sheets

 Queen bed sheet

 King bed sheets

 Cal king bed sheets

 Duvet covers

 Bed skirts

 Standard Pillow cases

 King Pillow cases

 Pillow shells

Juqey code,

$(document).ready(function () {
    $('.category_filter').click(function(e) {

        $('.category_filter').removeClass('active');

        var $parent = $(this).parent();
        if (!$parent.hasClass('active')) {
            $parent.addClass('active');
        }
        e.preventDefault();
    });
});

Body:
Instead of this you can use toggleClass

$(document).ready(function () {
    $('.category_filter').click(function(e) {
        e.preventDefault();
        $('.category_filter').removeClass('active');
        var $parent = $(this).parent();
        if (!$parent.hasClass('active')) {
            $parent.toggleClass('active');
        }
    });
});


问:
convert string to date object give sunday web, GMT 00+ time i need in date formate dd/mm/yyyy
I am converting string to date object i have string like
2017/3/30. when i parse into date object it gives
 sunday web, GMT 03 00:00:00 GMT+05:00 2019
Code is </p>

```<code> String dob = "2017/3/30";
     SimpleDateFormat format = new SimpleDateFormat("yyyy/dd/MM");
            try {
                startDate = format.parse(dob);
                endDate = format.parse(formattedDate);
            } catch (ParseException e) {
                e.printStackTrace();
            }
</code>```

<p>I need same formate in date object not string . </p>

答:
I think your problem is that your actual date format, 2017/3/30, does not agree with the format string you are giving to your SimpleDateFormat, yyyy/dd/MM. The first has the month in the middle and the day-of month last; the latter has got them the other way around. Therefore the Date you get from dob is the 3rd of June, 2019 (I think this is what you were trying to say, it wasn’t 100 % clear). SimpleDateFormat is understanding your dob as the 3rd day of the 30th month of 2017; when there are only 12 months in a year it just continues counting months into 2018 and 2019. It is quite lenient about the values supplied.

You just need to decide on the order of day, month and year. Your question (with the title) mentions 3 different orders, dd/mm/yyyy, 2017/3/30 and yyyy/dd/MM. Once you’re being consistent, your problems will be solved, I expect.

In most cases we don’t want to let bugs like this one slip through unnoticed. The solution to this is

```<code>    format.setLenient(false);
</code>```

After this call, your date format will no longer accept 30 as a month number, and will report your error back to you so you know and can correct it (and may not need to ask on Stack Overflow :-)

Body:
I am converting string to date object i have string like
2017/3/30. when i parse into date object it gives
 sunday web, GMT 03 00:00:00 GMT+05:00 2019
Code is

 String dob = "2017/3/30";
     SimpleDateFormat format = new SimpleDateFormat("yyyy/dd/MM");
            try {
                startDate = format.parse(dob);
                endDate = format.parse(formattedDate);
            } catch (ParseException e) {
                e.printStackTrace();
            }

I need same formate in date object not string .

Body:
I think your problem is that your actual date format, 2017/3/30, does not agree with the format string you are giving to your SimpleDateFormat, yyyy/dd/MM. The first has the month in the middle and the day-of month last; the latter has got them the other way around. Therefore the Date you get from dob is the 3rd of June, 2019 (I think this is what you were trying to say, it wasn’t 100 % clear). SimpleDateFormat is understanding your dob as the 3rd day of the 30th month of 2017; when there are only 12 months in a year it just continues counting months into 2018 and 2019. It is quite lenient about the values supplied.

You just need to decide on the order of day, month and year. Your question (with the title) mentions 3 different orders, dd/mm/yyyy, 2017/3/30 and yyyy/dd/MM. Once you’re being consistent, your problems will be solved, I expect.

In most cases we don’t want to let bugs like this one slip through unnoticed. The solution to this is

    format.setLenient(false);

After this call, your date format will no longer accept 30 as a month number, and will report your error back to you so you know and can correct it (and may not need to ask on Stack Overflow :-)


问:
how do i get all the value of a table from a website
```<code>string Url = "http://www.dsebd.org/latest_share_price_scroll_l.php";
HtmlWeb web = new HtmlWeb();

HtmlDocument doc = web.Load(Url);
string a = doc.DocumentNode.SelectNodes("//iframe*[@src=latest_share_price_all\"]//html/body/div/table/tbody")[0].InnerText;
</code>```

<p>i have tried, but null value found in string a.           </p>

答:
Ok this one confused me for a while but I've got it now. Instead of pulling the whole page from http://www.dsebd.org/latest_share_price_scroll_l.php, you can get just the table data from http://www.dsebd.org/latest_share_price_all.php.

There was some strange behaviour with trying to select child elements of the #document node under the iframe element. Someone with more xpath experience might be able to explain this.

Now you can get all the table row nodes by using the following xpath:

```<code>string url = "http://www.dsebd.org/latest_share_price_all.php";

HtmlDocument doc = new HtmlWeb().Load(url);
HtmlNode docNode = doc.DocumentNode;

var nodes = docNode.SelectNodes("//body/div/table/tr");
</code>```

That will give you all the table row nodes. Then you need to go through each node you just got and get the values you want.

Just for example if you wanted to get the trading code, high, and volume you would do the following:

```<code>//Remove the first node because it is the header row at the top of the table
nodes.RemoveAt(0);
foreach(HtmlNode rowNode in nodes)
{
    HtmlNode tradingCodeNode = rowNode.SelectSingleNode("td[2]/a");
    string tradingCode = tradingCodeNode.InnerText;

    HtmlNode highNode = rowNode.SelectSingleNode("td[4]");
    string highValue = highNode.InnerText;

    HtmlNode volumeNode = rowNode.SelectSingleNode("td[11]");
    string volumeValue = volumeNode.InnerText;

    //Do whatever you want with the values here
    //Put them in a class or add them to a list
}
</code>```

XPath uses 1-based indices so when you are referring to a particular cell in a table row by number the first element is at index 1, instead of using index 0 as in a C# array.

Body:
string Url = "http://www.dsebd.org/latest_share_price_scroll_l.php";
HtmlWeb web = new HtmlWeb();

HtmlDocument doc = web.Load(Url);
string a = doc.DocumentNode.SelectNodes("//iframe*[@src=latest_share_price_all\"]//html/body/div/table/tbody")[0].InnerText;

i have tried, but null value found in string a.

Body:
Ok this one confused me for a while but I've got it now. Instead of pulling the whole page from http://www.dsebd.org/latest_share_price_scroll_l.php, you can get just the table data from http://www.dsebd.org/latest_share_price_all.php.

There was some strange behaviour with trying to select child elements of the #document node under the iframe element. Someone with more xpath experience might be able to explain this.

Now you can get all the table row nodes by using the following xpath:

string url = "http://www.dsebd.org/latest_share_price_all.php";

HtmlDocument doc = new HtmlWeb().Load(url);
HtmlNode docNode = doc.DocumentNode;

var nodes = docNode.SelectNodes("//body/div/table/tr");

That will give you all the table row nodes. Then you need to go through each node you just got and get the values you want.

Just for example if you wanted to get the trading code, high, and volume you would do the following:

//Remove the first node because it is the header row at the top of the table
nodes.RemoveAt(0);
foreach(HtmlNode rowNode in nodes)
{
    HtmlNode tradingCodeNode = rowNode.SelectSingleNode("td[2]/a");
    string tradingCode = tradingCodeNode.InnerText;

    HtmlNode highNode = rowNode.SelectSingleNode("td[4]");
    string highValue = highNode.InnerText;

    HtmlNode volumeNode = rowNode.SelectSingleNode("td[11]");
    string volumeValue = volumeNode.InnerText;

    //Do whatever you want with the values here
    //Put them in a class or add them to a list
}

XPath uses 1-based indices so when you are referring to a particular cell in a table row by number the first element is at index 1, instead of using index 0 as in a C# array.


问:
JSONP requests must use GET request method in angular 2
above error i get when i'm  using jsonp with post method

To request on cross domain i have used jsonp but jsonp support only get method ,and i want to post method to cross domain in angular 2

here is my code

```<code>this._InstUrl = 'https://api.instagram.com/v1/media/' + listOfMedia[x].id + '/likes?access_token=' + this.hdnaccess_token;

                let headers = new Headers({ 'Content-Type': 'application/json' });
                let options = new RequestOptions({ headers: headers });

                return this._jsonp.post(this._InstUrl, "", headers).map((res: Response) => { debugger; res.json() })
                                        .subscribe(
                                        (data) => {
                                            //if (this.Result.length == 0) { this.NoData = true; }
                                            debugger; console.log(this.Result);
                                        },
                                        (error) => {
                                            debugger; console.log(error);
                                        });
</code>```

答:
JSONP doesn't support other methods than GET and also doesn't support custom headers. This is not an Angular limitation but a JSONP limitation.

If you don't control the server and need more flexibility, use your own server to redirect CORS requests to the foreign server. CORS limitations only apply to the browser.

Body:
above error i get when i'm  using jsonp with post method

To request on cross domain i have used jsonp but jsonp support only get method ,and i want to post method to cross domain in angular 2

here is my code

this._InstUrl = 'https://api.instagram.com/v1/media/' + listOfMedia[x].id + '/likes?access_token=' + this.hdnaccess_token;

                let headers = new Headers({ 'Content-Type': 'application/json' });
                let options = new RequestOptions({ headers: headers });

                return this._jsonp.post(this._InstUrl, "", headers).map((res: Response) => { debugger; res.json() })
                                        .subscribe(
                                        (data) => {
                                            //if (this.Result.length == 0) { this.NoData = true; }
                                            debugger; console.log(this.Result);
                                        },
                                        (error) => {
                                            debugger; console.log(error);
                                        });


问:
I'm trying to make an android app where an alarm plays when the battery gets under 10%. Why isn't my code working?
The audio file (.mp3) gets played when I don't use the onPreparedListener, but I get an error after the file tries to replay after some time (because it's not listening for the state obviously). So basically the code is checking the battery state and if it's 10% or below it plays the alarm sound, I also have a button which I can click to stop the sound. Now with the onPreparedListener the alarm sound doesn't get played anymore. What am I doing wrong?</p>

```<code>    tv_battery = (TextView) findViewById(R.id.tv_battery);
    final MediaPlayer mp = MediaPlayer.create(this, R.raw.alarm);
    Button b = (Button) findViewById(R.id.stop_alarm);
    AudioManager audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
    audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, 20, 0);

    b.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            if(mp.isPlaying()) {
                mp.stop();
                mp.release();
            }
        }
    });
    runnable = new Runnable() {
        @Override
        public void run() {
            int level = (int) batteryLevel();

            tv_battery.setText("Battery: " + level + "%");
            handler.postDelayed(runnable, 5000);

            if(level <=  10) {

                mp.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {

                    @Override
                    public void onPrepared(final MediaPlayer mp) {
                        CountDownTimer count = new CountDownTimer(7000, 1000) {

                            public void onTick(long millisUntilFinished) {
                                mp.start();
                            }

                            public void onFinish() {
                                //code fire after finish
                                mp.stop();
                            }

                        };
                        count.start();
                    }
</code>```

答:
I think you have place mp.start(); on wrong place please move it before count.start(); as below :

```<code>CountDownTimer count = new CountDownTimer(7000, 1000) {
     public void onTick(long millisUntilFinished) {

     }

     public void onFinish() {
            //code fire after finish
            mp.stop();
     }
};
mp.start();
count.start();
</code>```

Also correct below condition if media player already started when battery is under 10 otherwise media player again prepared even after started :

```<code>if(level <=  10 && !mp.isPlaying()) {
</code>```

Body:
The audio file (.mp3) gets played when I don't use the onPreparedListener, but I get an error after the file tries to replay after some time (because it's not listening for the state obviously). So basically the code is checking the battery state and if it's 10% or below it plays the alarm sound, I also have a button which I can click to stop the sound. Now with the onPreparedListener the alarm sound doesn't get played anymore. What am I doing wrong?

    tv_battery = (TextView) findViewById(R.id.tv_battery);
    final MediaPlayer mp = MediaPlayer.create(this, R.raw.alarm);
    Button b = (Button) findViewById(R.id.stop_alarm);
    AudioManager audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
    audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, 20, 0);

    b.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            if(mp.isPlaying()) {
                mp.stop();
                mp.release();
            }
        }
    });
    runnable = new Runnable() {
        @Override
        public void run() {
            int level = (int) batteryLevel();

            tv_battery.setText("Battery: " + level + "%");
            handler.postDelayed(runnable, 5000);

            if(level <=  10) {

                mp.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {

                    @Override
                    public void onPrepared(final MediaPlayer mp) {
                        CountDownTimer count = new CountDownTimer(7000, 1000) {

                            public void onTick(long millisUntilFinished) {
                                mp.start();
                            }

                            public void onFinish() {
                                //code fire after finish
                                mp.stop();
                            }

                        };
                        count.start();
                    }

Body:
I think you have place mp.start(); on wrong place please move it before count.start(); as below :

CountDownTimer count = new CountDownTimer(7000, 1000) {
     public void onTick(long millisUntilFinished) {

     }

     public void onFinish() {
            //code fire after finish
            mp.stop();
     }
};
mp.start();
count.start();

Also correct below condition if media player already started when battery is under 10 otherwise media player again prepared even after started :

if(level <=  10 && !mp.isPlaying()) {


问:
JQuery scroll event not functioning properly
I am creating a mobile website, on one of the web pages I have created a dashboard with three scroll-able pages on. In the bottom right corner of each page is a button to press, upon pressing this button a JQuery event is fired and should scroll to the next page. Or back to the top if you are at the bottom. However the button on page 2 does not trigger the scroll event, but the button on page 1 and 3 do.

Here is the JQuery event;

```<code>if ($(".button-container").click(function () {
            event.preventDefault();
            var id = $(this).attr('id');
            $('html, body, scroll-container').animate({
                scrollTop: $("#" + "page" + id).offset().top
            });
        }));
</code>```

The JQuery find the id of the button press and creates a string to find the id of the page to scroll to.

Here is the HTML code:

```<code>    <div class="scroll-page" id="page1">
        <div class="field">
            <span class="fa-stack fa-4x">
                <i class="fa fa-calendar-o fa-stack-3x"></i>
                <i class="fa-stack-1x calendar-text">21</i>
                <i class="fa-stack-2x month-text">MAR</i>
            </span>
            <span><a href="#" class="button button21"><i class="fa fa-file-text-o" aria-hidden="true"></i> View latest payslip</a></span>
        </div>
        <div class="button-container" id="2">
            <a class="scroll-button" href="#">
                <i class="fa fa-arrow-down" aria-hidden="true"></i>
            </a>
        </div>
    </div>

    <div class="scroll-page" id="page2">
        <div class="button-container" id="3">
            <a class="scroll-button" href="#">
                <i class="fa fa-arrow-down" aria-hidden="true"></i>
            </a>
        </div>
    </div>

    <div class="scroll-page" id="page3">
        <div class="button-container" id="1">
            <a class="scroll-button" href="#">
                <i class="fa fa-arrow-up" aria-hidden="true"></i>
            </a>
        </div>
    </div>

</scroll-container>
</code>```

Thanks for any help in advance.

答:
There doesn't seem to be any obvious mistake, did you try to log the offset() value to the console to see if it's getting the right one? Also, you're calling event.preventDefault() without passing 'event' to the function, so that should actually throw an exception. You should replace your event handler with this:

```<code>$(".button-container").click(function (event) {
</code>```

Body:
I am creating a mobile website, on one of the web pages I have created a dashboard with three scroll-able pages on. In the bottom right corner of each page is a button to press, upon pressing this button a JQuery event is fired and should scroll to the next page. Or back to the top if you are at the bottom. However the button on page 2 does not trigger the scroll event, but the button on page 1 and 3 do.

Here is the JQuery event;

if ($(".button-container").click(function () {
            event.preventDefault();
            var id = $(this).attr('id');
            $('html, body, scroll-container').animate({
                scrollTop: $("#" + "page" + id).offset().top
            });
        }));

The JQuery find the id of the button press and creates a string to find the id of the page to scroll to.

Here is the HTML code:

                21
                MAR

             View latest payslip

</scroll-container>

Thanks for any help in advance.

Body:
There doesn't seem to be any obvious mistake, did you try to log the offset() value to the console to see if it's getting the right one? Also, you're calling event.preventDefault() without passing 'event' to the function, so that should actually throw an exception. You should replace your event handler with this:

$(".button-container").click(function (event) {


问:
Is increment an atomic operation in JavaScript?
Is increment an atomic operation in JavaScript? If one thread is accessing
++i; and at the same time another one starts to access the operation will there be any problems?

答:
In JavaScript, a function always runs to completion. That means if a function is running, then it will run completely; only after that, the other function will be called. So, there is no chance of interleaving between statements (but in case of Java it is different).

If you are confused with asynchronous execution, then always remember async means later not parallel. So, coming to your problem, the answer is, No you will not face any problem, it will be a total atomic operation.


问:
Using BabelBundle on asp.net application, when using BundleResolver is not working
In this moment I'm covert my buddleconfig to support babel transcription. For do that I have the following code:

```<code>bundles.Add(new BabelBundle(BundlesVirtualPaths.HeaderApp).Include(
                "~/Scripts/MobileApp/Apps/HeaderApp.js",
                "~/Scripts/MobileApp/Controllers/HeaderCtrl.js"
            ));
</code>```

Then, I what to get all scripts URL's in a List of string format as follows:

```<code>List<string> list =  new BundleResolver().GetBundleContents(virtualPath).ToList();
</code>```

But the compiler retrives the following error:

Unable to resolve type: React.IReactEnvironment

答:
After a search a lot and tried different solutions, the problem was that my project missed some libraries references.

Using the Nugget and this post I was able to solve the problem

Body:
In this moment I'm covert my buddleconfig to support babel transcription. For do that I have the following code:

bundles.Add(new BabelBundle(BundlesVirtualPaths.HeaderApp).Include(
                "~/Scripts/MobileApp/Apps/HeaderApp.js",
                "~/Scripts/MobileApp/Controllers/HeaderCtrl.js"
            ));

Then, I what to get all scripts URL's in a List of string format as follows:

List<string> list =  new BundleResolver().GetBundleContents(virtualPath).ToList();

But the compiler retrives the following error:

Unable to resolve type: React.IReactEnvironment


问:
Javascript - How to use promises with multiple .then()
I'm trying to create a array structure. So, we have parts and each part had articles.

So i did a promise to collect all parts .then() i need to iterate part promise and select the articles in this part .then() i want to push this to a array parts and render this in a view.

The structure is this:

```<code>-PARTS
      - part
            - u_order
            - u_familia
            - u_part
            - u_type
            - articles (article from each part)
</code>```

And my code is this:

```<code>var p1 = new Promise(function(resolve, reject) {
      var stamp = req.params.stamp;
      request.query("SELECT u_order, u_familia, u_part, u_type FROM u_part (nolock) where u_order <'92' and u_order <> '100'").then((data)=>resolve(data));
      // or
      // reject ("Error!");
    });

    p1.then(function(value){
      var stamp = req.params.stamp;
      console.log(value.length);
      for(var i= 0; i<value.length; i++)
      {
        console.log(value[i]);
        request.query("SELECT st.u_posic, sc.ref, sc.qtt, sc.design FROM st INNER JOIN sc ON st.ref = sc.ref where sc.ststamp ='"+stamp+"' and st.u_posic = '"+value[i].u_order+"'").then((data)=>resolve(data));
      }

    }, function(reason){
      console.log(reason);
    });

    p1.then(function(part, articles){
      var parts = [];
      console.log("PART: " +part.length);
      for(var j= 0; j<part.length; j++)
      {
        console.log(part[j].u_order);
        console.log(part[j].u_familia);
        console.log(part[j].u_part);
        console.log(part[j].u_type);
        console.log(articles[j]);
      };
    });
</code>```

In last .then() i just have the parts, i can't access to articles maybe because i'm not doing well with second .then()
I'm starting working with promises, i also read documentation but i can't do this.

Anyone can help me to understand and solve this?

Thank you

答:
The best I can do.

```<code>request.query("SELECT u_order, u_familia, u_part, u_type FROM u_part (nolock) where u_order <'92' and u_order <> '100'")
.then(function(parts){
    var stamp = req.params.stamp;
    return Promise.all(parts.map(function(part) {
        return request.query("SELECT st.u_posic, sc.ref, sc.qtt, sc.design FROM st INNER JOIN sc ON st.ref = sc.ref where sc.ststamp ='"+stamp+"' and st.u_posic = '"+part.u_order+"'")
        .then(function(articles) {
            part.articles = articles;
            return part;
        });
    }));
})
.then(function(parts){
    parts.forEach(function(part) {
        console.log(part.u_order);
        console.log(part.u_familia);
        console.log(part.u_part);
        console.log(part.u_type);
        part.articles.forEach(function(article) {
            console.log(article.u_posic);
            console.log(article.ref);
            console.log(article.qtt);
            console.log(article.design);
        });
    });
});
</code>```

BONUS ES2015+ version of above

```<code>request.query("SELECT u_order, u_familia, u_part, u_type FROM u_part (nolock) where u_order <'92' and u_order <> '100'")
.then(parts => Promise.all(parts.map(part => request.query(`SELECT st.u_posic, sc.ref, sc.qtt, sc.design FROM st INNER JOIN sc ON st.ref = sc.ref where sc.ststamp ='${req.params.stamp}' and st.u_posic = '${part.u_order}'`)
    .then(articles => {
        part.articles = articles;
        return part;
    })
)))
.then(parts => parts.forEach(part => {
    console.log(part.u_order);
    console.log(part.u_familia);
    console.log(part.u_part);
    console.log(part.u_type);
    part.articles.forEach(article => {
        console.log(article.u_posic);
        console.log(article.ref);
        console.log(article.qtt);
        console.log(article.design);
    });
}));
</code>```

Body:
I'm trying to create a array structure. So, we have parts and each part had articles.

So i did a promise to collect all parts .then() i need to iterate part promise and select the articles in this part .then() i want to push this to a array parts and render this in a view.

The structure is this:

-PARTS
      - part
            - u_order
            - u_familia
            - u_part
            - u_type
            - articles (article from each part)

And my code is this:

var p1 = new Promise(function(resolve, reject) {
      var stamp = req.params.stamp;
      request.query("SELECT u_order, u_familia, u_part, u_type FROM u_part (nolock) where u_order <'92' and u_order <> '100'").then((data)=>resolve(data));
      // or
      // reject ("Error!");
    });

    p1.then(function(value){
      var stamp = req.params.stamp;
      console.log(value.length);
      for(var i= 0; i<value.length; i++)
      {
        console.log(value[i]);
        request.query("SELECT st.u_posic, sc.ref, sc.qtt, sc.design FROM st INNER JOIN sc ON st.ref = sc.ref where sc.ststamp ='"+stamp+"' and st.u_posic = '"+value[i].u_order+"'").then((data)=>resolve(data));
      }

    }, function(reason){
      console.log(reason);
    });

    p1.then(function(part, articles){
      var parts = [];
      console.log("PART: " +part.length);
      for(var j= 0; j<part.length; j++)
      {
        console.log(part[j].u_order);
        console.log(part[j].u_familia);
        console.log(part[j].u_part);
        console.log(part[j].u_type);
        console.log(articles[j]);
      };
    });

In last .then() i just have the parts, i can't access to articles maybe because i'm not doing well with second .then()
I'm starting working with promises, i also read documentation but i can't do this.

Anyone can help me to understand and solve this?

Thank you

Body:
The best I can do.

request.query("SELECT u_order, u_familia, u_part, u_type FROM u_part (nolock) where u_order <'92' and u_order <> '100'")
.then(function(parts){
    var stamp = req.params.stamp;
    return Promise.all(parts.map(function(part) {
        return request.query("SELECT st.u_posic, sc.ref, sc.qtt, sc.design FROM st INNER JOIN sc ON st.ref = sc.ref where sc.ststamp ='"+stamp+"' and st.u_posic = '"+part.u_order+"'")
        .then(function(articles) {
            part.articles = articles;
            return part;
        });
    }));
})
.then(function(parts){
    parts.forEach(function(part) {
        console.log(part.u_order);
        console.log(part.u_familia);
        console.log(part.u_part);
        console.log(part.u_type);
        part.articles.forEach(function(article) {
            console.log(article.u_posic);
            console.log(article.ref);
            console.log(article.qtt);
            console.log(article.design);
        });
    });
});

BONUS ES2015+ version of above

request.query("SELECT u_order, u_familia, u_part, u_type FROM u_part (nolock) where u_order <'92' and u_order <> '100'")
.then(parts => Promise.all(parts.map(part => request.query(`SELECT st.u_posic, sc.ref, sc.qtt, sc.design FROM st INNER JOIN sc ON st.ref = sc.ref where sc.ststamp ='${req.params.stamp}' and st.u_posic = '${part.u_order}'`)
    .then(articles => {
        part.articles = articles;
        return part;
    })
)))
.then(parts => parts.forEach(part => {
    console.log(part.u_order);
    console.log(part.u_familia);
    console.log(part.u_part);
    console.log(part.u_type);
    part.articles.forEach(article => {
        console.log(article.u_posic);
        console.log(article.ref);
        console.log(article.qtt);
        console.log(article.design);
    });
}));


问:
EigenFace in opencv using python
when i try this code

```<code>import cv2, os
import numpy as np
from PIL import Image
#from trainner import *
path="dataset2"
cascadePath = "haarcascade_frontalface_default.xml"
faceCascade = cv2.CascadeClassifier(cascadePath)
recognizer =cv2.face.createEigenFaceRecognizer()

#recognizer = cv2.face.createLBPHFaceRecognizer()
threshold = 105
recognizer.load("recognizer/trainningData.yml")
id=0

image_paths = [os.path.join(path, f) for f in os.listdir(path)]
for image_path in image_paths:

    predict_image_pil = Image.open(image_path).convert('L')
    predict_image = np.array(predict_image_pil, 'uint8')

    faces = faceCascade.detectMultiScale(predict_image)
    for (x, y, w, h) in faces:
        resized_image = cv2.resize(predict_image[y:y+h,x:x+w], (200, 200))

        cv2.rectangle(predict_image,(x,y),(x+w,y+h),(0,255,0),2)
        id,conf = recognizer.predict(predict_image[y:y+h,x:x+w])

        print(id)
        print (conf)
        if(id==1):
            id="john"
        elif(id==2):
            id="brad"
        elif(id==3):
            id="scr"
        elif(id==4):
            id="natalie portman"
        elif(id==5):
            id="jennifer lawrence"
        elif(id==6):
            id="van diesel"
        elif(id==7):
            id="jennifer aniston"
        elif(id==8):
            id="leonardo dicaprio"
        else :
            id="unknown"
        print (id )
        cv2.imshow("Recognizing Face", predict_image[y: y + h, x: x + w])
        cv2.waitKey(1000)
cv2.destroyAllWindows()
</code>```

this error appear

error: (-5) Wrong input image size. Reason: Training and Test images must be of equal size! Expected an image with 77760 elements, but got 21316. in function cv::face::Eigenfaces::predict

答:
Whould you mind explaining your question ?

I guess you would like to understand the meaning of this error. It means you need to have the same images size for training and test images.

Title: EigenFace in opencv using python

Body:
when i try this code

import cv2, os
import numpy as np
from PIL import Image
#from trainner import *
path="dataset2"
cascadePath = "haarcascade_frontalface_default.xml"
faceCascade = cv2.CascadeClassifier(cascadePath)
recognizer =cv2.face.createEigenFaceRecognizer()

#recognizer = cv2.face.createLBPHFaceRecognizer()
threshold = 105
recognizer.load("recognizer/trainningData.yml")
id=0

image_paths = [os.path.join(path, f) for f in os.listdir(path)]
for image_path in image_paths:

    predict_image_pil = Image.open(image_path).convert('L')
    predict_image = np.array(predict_image_pil, 'uint8')

    faces = faceCascade.detectMultiScale(predict_image)
    for (x, y, w, h) in faces:
        resized_image = cv2.resize(predict_image[y:y+h,x:x+w], (200, 200))

        cv2.rectangle(predict_image,(x,y),(x+w,y+h),(0,255,0),2)
        id,conf = recognizer.predict(predict_image[y:y+h,x:x+w])

        print(id)
        print (conf)
        if(id==1):
            id="john"
        elif(id==2):
            id="brad"
        elif(id==3):
            id="scr"
        elif(id==4):
            id="natalie portman"
        elif(id==5):
            id="jennifer lawrence"
        elif(id==6):
            id="van diesel"
        elif(id==7):
            id="jennifer aniston"
        elif(id==8):
            id="leonardo dicaprio"
        else :
            id="unknown"
        print (id )
        cv2.imshow("Recognizing Face", predict_image[y: y + h, x: x + w])
        cv2.waitKey(1000)
cv2.destroyAllWindows()

this error appear

error: (-5) Wrong input image size. Reason: Training and Test images must be of equal size! Expected an image with 77760 elements, but got 21316. in function cv::face::Eigenfaces::predict


问:
Undefined Meteor.user() after refresh Angular2 Meteor
I'm quite new to Angular2 and Meteor.
I want to do a pretty simple thing : Get the current user information from Meteor with Meteor.user().
The thing is, whenever I refresh the page, the profile value of Meteor.user() becomes "undefined".

I did some search, apparently Meteor.user() is too long to be execute.
Apparently, you can use Tracker.autorun() to wait for Meteor.user() to get initialized.

At the moment my code looks like this:

```<code>Tracker.autorun(function () {
        Meteor.subscribe("userLoggedIn");
        console.log(Meteor.user());
        if(Meteor.user() !== undefined) {
           //Do something
           this.myFunction();
        }
     });
</code>```

The thing is that "myFunction" is "undefined" since it's not defined in the Tracker (I think at least).

Do you have any idea how can I call my function ?
Is this ok to execute that much of code in the tracker ?
Is it possible to wait for the initialization of Meteor.user() outside of the Tracker ?

(Yeah, i've got a lot of question :p )

Thank you by advance ! :)

答:
If you are relying on this, why not using an arrow function to keep the context?

```<code>Tracker.autorun(() => { this.myFunction(); });
</code>```

You could also set a scoped variable, old school way:

```<code>var self = this;

Tracker.autorun(function () { /* bla bla */ self.myFunction(); });
</code>```

Body:
I'm quite new to Angular2 and Meteor.
I want to do a pretty simple thing : Get the current user information from Meteor with Meteor.user().
The thing is, whenever I refresh the page, the profile value of Meteor.user() becomes "undefined".

I did some search, apparently Meteor.user() is too long to be execute.
Apparently, you can use Tracker.autorun() to wait for Meteor.user() to get initialized.

At the moment my code looks like this:

Tracker.autorun(function () {
        Meteor.subscribe("userLoggedIn");
        console.log(Meteor.user());
        if(Meteor.user() !== undefined) {
           //Do something
           this.myFunction();
        }
     });

The thing is that "myFunction" is "undefined" since it's not defined in the Tracker (I think at least).

Do you have any idea how can I call my function ?
Is this ok to execute that much of code in the tracker ?
Is it possible to wait for the initialization of Meteor.user() outside of the Tracker ?

(Yeah, i've got a lot of question :p )

Thank you by advance ! :)

Body:
If you are relying on this, why not using an arrow function to keep the context?

Tracker.autorun(() => { this.myFunction(); });

You could also set a scoped variable, old school way:

var self = this;

Tracker.autorun(function () { /* bla bla */ self.myFunction(); });


问:
Formatted output with control characters in C?
After reading about control characters from Wikipedia, I have tried to write some code using them.
When I write one of them, I could not successfully write the required/wanted output:

```<code>name    :  ...
surname :  ...
              asadsa  // these three words are some data
              adsdsa
              asdsds
</code>```

my effort:

```<code>fprintf(stdout, "\rname\t\t\b:%s\r\fsurname\t:%s\v %s \v%s \v%s ",
        name, surname, data1, ...)
</code>```

but output is:

```<code>name     : georg.
surname  : alafron.
                   to the school
                   ....
                   ....
</code>```

but this output is not desired one, so how can I fix it only using fprintf() and control
characters?

答:
In general, you will seldom have cause to use any of the control characters '\a', '\b', '\f', '\v', and you won't often use '\r'; that leaves '\t' and '\n', both of which you probably will use.  The last time I used '\r' and '\b', I was writing code to do bold on a daisy wheel printer by overstriking - writing the same data twice.  It doesn't help on a modern ink jet or laser printer.

It is a bit difficult to see what the differences between the required and actual outputs are.  However, assuming that your data is in variables name, surname, data1, data2, and data3, then this format string should do what you desire:

```<code>printf("name    :  %s\nsurname :  %s\n%14s%s\n%14s%s\n%14s%s\n",
       name, surname, "", data1, "", data2, "", data3);
</code>```

The '%14s' format specifies that the width should be 14 characters, which is the size of the indent on your data lines.  The empty string gets blank padded to 14 characters, and is followed by the relevant bit of data.

Body:
After reading about control characters from Wikipedia, I have tried to write some code using them.
When I write one of them, I could not successfully write the required/wanted output:

name    :  ...
surname :  ...
              asadsa  // these three words are some data
              adsdsa
              asdsds

my effort:

fprintf(stdout, "\rname\t\t\b:%s\r\fsurname\t:%s\v %s \v%s \v%s ",
        name, surname, data1, ...)

but output is:

name     : georg.
surname  : alafron.
                   to the school
                   ....
                   ....

but this output is not desired one, so how can I fix it only using fprintf() and control
characters?

Body:
In general, you will seldom have cause to use any of the control characters '\a', '\b', '\f', '\v', and you won't often use '\r'; that leaves '\t' and '\n', both of which you probably will use.  The last time I used '\r' and '\b', I was writing code to do bold on a daisy wheel printer by overstriking - writing the same data twice.  It doesn't help on a modern ink jet or laser printer.

It is a bit difficult to see what the differences between the required and actual outputs are.  However, assuming that your data is in variables name, surname, data1, data2, and data3, then this format string should do what you desire:

printf("name    :  %s\nsurname :  %s\n%14s%s\n%14s%s\n%14s%s\n",
       name, surname, "", data1, "", data2, "", data3);

The '%14s' format specifies that the width should be 14 characters, which is the size of the indent on your data lines.  The empty string gets blank padded to 14 characters, and is followed by the relevant bit of data.


答:
You want to unpivot the data.  I think cross apply is the easiest way:

```<code>select v.*
from t cross apply
     (values (city, cast('2016-01-12' as date), [01/12/2016]),
             (city, cast('2016-02-12' as date), [02/12/2016]),
             (city, cast('2016-03-12' as date), [03/12/2016]),
             . . .
     ) v(city, dte, cnt);
</code>```

Note that this makes the second column a bona fide date.

Title: How to transpose column headers to be rows without moving rows to columns

Body:
Not sure if I have worded the question right. I am using sql server  2014 management studio.

I have this table:

|------------------|--01/12/2016--|--02/12/2016--|--03/12/2016--|--04/12/2016--|

 |----Place------|--Count--Value|   Count   --Value|    Count--     Value|--    Count--value

|--London------|    random data--|random data--|-------------------|--------------------|
|--Manchester|-------------------|------------------|random data---|---------------------|
|--Birmingham|--------------------|---etc------------|etc----------------|-etc------------------|
|--Leeds--------|
|--Luton---------|
|--Scotland-----|

What I want to do is transpose the dates from the column headers to rows so it looks like this:

Place   ----------|---dates------|  Count--------|  Value

London  --------|01/12/2016
Manchester  --|01/12/2016
Birmingham  --|01/12/2016
Leeds   ---------|01/12/2016
Luton   ----------|01/12/2016
Scotland    ------|01/12/2016
London--------  |02/12/2016
Manchester--    |02/12/2016
Birmingham--    |02/12/2016
Leeds   ---------|02/12/2016
Luton   ----------|02/12/2016
Scotland------  |02/12/2016
London  --------|03/12/2016
Manchester  --|03/12/2016
Birmingham  --|03/12/2016
Leeds   ----------|03/12/2016
Luton   -----------|03/12/2016
Scotland    -------|03/12/2016
London  ---------|04/12/2016
Manchester  ---|04/12/2016
Birmingham  ---|04/12/2016
Leeds   ----------|04/12/2016
Luton-----------    |04/12/2016
Scotland    -------|04/12/2016

I have searched for transposing data but none seem to cover this situation.

Body:
You want to unpivot the data.  I think cross apply is the easiest way:

select v.*
from t cross apply
     (values (city, cast('2016-01-12' as date), [01/12/2016]),
             (city, cast('2016-02-12' as date), [02/12/2016]),
             (city, cast('2016-03-12' as date), [03/12/2016]),
             . . .
     ) v(city, dte, cnt);

Note that this makes the second column a bona fide date.


问:
getting error for VHDL shift_left operation
I have been searching this for a while and have not been able to replicate any posted solutions online so I was hoping some of you wonderful people could help me out.
     I am creating an ALU. i have a two 32 bit inputs and one 32 bit output along with a 5 bit shamt and a 4 bit control signal. My code is as follows with the error location commented on.

```<code>library ieee;
use ieee.std_logic_1164.all;
use IEEE.STD_LOGIC_UNSIGNED.ALL;
use ieee.numeric_std.all;

Entity mips_alu IS
    PORT(ALUControl : IN STD_LOGIC_VECTOR(3 DOWNTO 0);
    inputA, inputB      : IN STD_LOGIC_VECTOR(31 DOWNTO 0);
    shamt                   : IN STD_LOGIC_VECTOR(4 DOWNTO 0);
    Zero                    : OUT STD_LOGIC;
    ALU_Result          : OUT STD_LOGIC_VECTOR(31 DOWNTO 0)
    );
END mips_alu;

ARCHITECTURE behavior of mips_alu IS
BEGIN
    PROCESS(ALUControl)
    BEGIN
        CASE ALUControl is
        WHEN "0000" =>
            ALU_Result <= inputA AND inputB;
        WHEN "0001" =>
            ALU_Result <= inputA OR inputB;
        WHEN "0010" =>
            ALU_Result <= inputA + inputB;
        WHEN "0110" =>
            ALU_Result <= inputA - inputB;
        WHEN "0111" =>
            IF (inputA < inputB) THEN
                ALU_Result <= inputA;
            END IF;
        WHEN "1000" =>
            ALU_Result <= shift_left(inputB, to_integer(unsigned(shamt)));
            -- The line above is where i get my first error, The following lines will have the same issue
        WHEN "1001" =>
            ALU_Result <= shift_right(inputB, shamt);
        WHEN "1010" =>
            ALU_Result <= shift_left(inputB, inputA);
        WHEN "1011" =>
            ALU_Result <= shift_right(inputB, inputA);
        WHEN "1100" =>
            ALU_Result <= inputA NOR inputB;
        WHEN "1101" =>
            ALU_Result <= inputB(31 DOWNTO 16);
        WHEN OTHERS =>
            ALU_Result <= inputA;
        END CASE;
    END PROCESS;
END behavior;
</code>```

The error I am getting says:

10511 VHDL Qualified Expression error at mips_alu.vhd(33): shift_left type specified in qualified expression must match std_logic_vector type that is implied for expression by context

I have tried several variations of this so if i am missing something please let me know, all help is appreciated as I am a bit of a novice to vhdl

答:
What I usually do is just this:

```<code>ALU_Result <= inputB(30 downto 0) & '0';
</code>```

This stores is ALU_Result a vector equal to InputB shifted once.
In case you want to shift it more times you can use a loop.

```<code>while (i<to_integer(unsigned(shamt))) loop
ALU_Result <= inputB(30 downto 0) & '0';
i:=i+1;
end loop;
</code>```

Its not an elegant solution but it will probably work.

For shifting to the right do:

```<code>ALU_Result <= '0' & inputB(31 downto 1);
</code>```

Body:
I have been searching this for a while and have not been able to replicate any posted solutions online so I was hoping some of you wonderful people could help me out.
     I am creating an ALU. i have a two 32 bit inputs and one 32 bit output along with a 5 bit shamt and a 4 bit control signal. My code is as follows with the error location commented on.

library ieee;
use ieee.std_logic_1164.all;
use IEEE.STD_LOGIC_UNSIGNED.ALL;
use ieee.numeric_std.all;

Entity mips_alu IS
    PORT(ALUControl : IN STD_LOGIC_VECTOR(3 DOWNTO 0);
    inputA, inputB      : IN STD_LOGIC_VECTOR(31 DOWNTO 0);
    shamt                   : IN STD_LOGIC_VECTOR(4 DOWNTO 0);
    Zero                    : OUT STD_LOGIC;
    ALU_Result          : OUT STD_LOGIC_VECTOR(31 DOWNTO 0)
    );
END mips_alu;

ARCHITECTURE behavior of mips_alu IS
BEGIN
    PROCESS(ALUControl)
    BEGIN
        CASE ALUControl is
        WHEN "0000" =>
            ALU_Result <= inputA AND inputB;
        WHEN "0001" =>
            ALU_Result <= inputA OR inputB;
        WHEN "0010" =>
            ALU_Result <= inputA + inputB;
        WHEN "0110" =>
            ALU_Result <= inputA - inputB;
        WHEN "0111" =>
            IF (inputA < inputB) THEN
                ALU_Result <= inputA;
            END IF;
        WHEN "1000" =>
            ALU_Result <= shift_left(inputB, to_integer(unsigned(shamt)));
            -- The line above is where i get my first error, The following lines will have the same issue
        WHEN "1001" =>
            ALU_Result <= shift_right(inputB, shamt);
        WHEN "1010" =>
            ALU_Result <= shift_left(inputB, inputA);
        WHEN "1011" =>
            ALU_Result <= shift_right(inputB, inputA);
        WHEN "1100" =>
            ALU_Result <= inputA NOR inputB;
        WHEN "1101" =>
            ALU_Result <= inputB(31 DOWNTO 16);
        WHEN OTHERS =>
            ALU_Result <= inputA;
        END CASE;
    END PROCESS;
END behavior;

The error I am getting says:

10511 VHDL Qualified Expression error at mips_alu.vhd(33): shift_left type specified in qualified expression must match std_logic_vector type that is implied for expression by context

I have tried several variations of this so if i am missing something please let me know, all help is appreciated as I am a bit of a novice to vhdl

Body:
What I usually do is just this:

ALU_Result <= inputB(30 downto 0) & '0';

This stores is ALU_Result a vector equal to InputB shifted once.
In case you want to shift it more times you can use a loop.

while (i<to_integer(unsigned(shamt))) loop
ALU_Result <= inputB(30 downto 0) & '0';
i:=i+1;
end loop;

Its not an elegant solution but it will probably work.

For shifting to the right do:

ALU_Result <= '0' & inputB(31 downto 1);


问:
attempting to modify a field in codeigniter application db table but know how to identify the table
I am beginner in code igniter php framework. Today I have a task to modify existing code and somehow I am lost in the middle of the line on attempting to located a database table. This is the controller snippet that renders the view

```<code>..........
$data["all_types"] = $this->data_model->get_data("all_types",300,"Asc");
$this->load->view("preview_brands",$data);
...........
</code>```

when the view is loaded I am iterating through the in the view to load data as shown

```<code> <div class="decoration"></div>
 <?php foreach($all_types as $item): ?>
 <div style="display:block;color:#000;">
    <a style="font-size:17px;margin:15px 2px;font-family:Cgothic;"
                           href="<?php echo site_url()."...../..../".$item["id"]; ?>"
                           class="scale-hover"
                           title="<?php echo str_replace("_"," ",$item["name"]);?>">
    <strong><?php echo str_replace("_"," ",$item["name"]);?></strong>
    </a>

 </div>
 <?php endforeach; ?>
</code>```

this is the model snippet code as shown

```<code>function get_data($db,$i,$order)
{
   $this->db->order_by("name",$order);
   $this->db->where('consent',"yes");
   $query=$this->db->get($db);
   return $query->result_array();
}
</code>```

My challenge is how can I locate or identify the database table the above model is pointing to to fetch data. Hoping someone assists me

答:
all_types is your table name.

$this->db->get($your_table name), get method take table name as a parameter.

Get Method Documentation

If more help needed I'm happy to help.

Happy Coding.

Body:
I am beginner in code igniter php framework. Today I have a task to modify existing code and somehow I am lost in the middle of the line on attempting to located a database table. This is the controller snippet that renders the view

..........
$data["all_types"] = $this->data_model->get_data("all_types",300,"Asc");
$this->load->view("preview_brands",$data);
...........

when the view is loaded I am iterating through the in the view to load data as shown

 <?php foreach($all_types as $item): ?>

    <a style="font-size:17px;margin:15px 2px;font-family:Cgothic;"
                           href="<?php echo site_url()."...../..../".$item["id"]; ?>"
                           class="scale-hover"
                           title="<?php echo str_replace("_"," ",$item["name"]);?>">
    <?php echo str_replace("_"," ",$item["name"]);?>

 <?php endforeach; ?>

this is the model snippet code as shown

function get_data($db,$i,$order)
{
   $this->db->order_by("name",$order);
   $this->db->where('consent',"yes");
   $query=$this->db->get($db);
   return $query->result_array();
}

My challenge is how can I locate or identify the database table the above model is pointing to to fetch data. Hoping someone assists me


问:
What is new() function here?
I've been learning design patterns and I saw such a method call from a class :

```<code>class Client: SubjectAccessor {
    static void Main() {
        Console.WriteLine("Proxy Pattern\n");

        ISubject subject = new Proxy();
        Console.WriteLine(subject.Requesy());

        subject = new(); //Here is what I am asking
        COnsole.WriteLine(subject.Request());
    }
}
</code>```

As you can see there is a subject = new(); call there and I am wondering whether it is creating a new instance of Proxy or something else. I've not found anything related to this.

Your help is much appreciated.

If you need, I can paste the whole code or actually it is written on a book so I need to write it down here.

Thanks.

答: It is a typo in the book. There is no current version of C# in which that is valid (it should raise a "Type expected" compiler error). Without context it is impossible to know what it should be.

Title: What is new() function here?

Body:
I've been learning design patterns and I saw such a method call from a class :

class Client: SubjectAccessor {
    static void Main() {
        Console.WriteLine("Proxy Pattern\n");

        ISubject subject = new Proxy();
        Console.WriteLine(subject.Requesy());

        subject = new(); //Here is what I am asking
        COnsole.WriteLine(subject.Request());
    }
}

As you can see there is a subject = new(); call there and I am wondering whether it is creating a new instance of Proxy or something else. I've not found anything related to this.

Your help is much appreciated.

If you need, I can paste the whole code or actually it is written on a book so I need to write it down here.

Thanks.


问:
How to get a variable type in Typescript?
I have a variable.

```<code>abc:number|string;
</code>```

How can I check its type? I want to do something like below:

```<code>if (abc.type === "number") {
    // do something
}
</code>```

答:
I'd like to add that TypeGuards only work on strings or numbers, if you want to compare an object use instanceof</p>

```<code>if(task.id instanceof UUID) {
  //foo
}
</code>```

Body:
I have a variable.

abc:number|string;

How can I check its type? I want to do something like below:

if (abc.type === "number") {
    // do something
}

Body:
I'd like to add that TypeGuards only work on strings or numbers, if you want to compare an object use instanceof

if(task.id instanceof UUID) {
  //foo
}


问:
how to show UIImage file path on UILabel in objective c
I am new in iOS and I am facing problem regarding to show file path on UILabel. I am taking Image for gallery and I want to show Image name and its extension on UILabel.

My code is like this

Button Click...

```<code>UIImagePickerController *picker = [[UIImagePickerController alloc] init];
    picker.delegate = self;
    picker.allowsEditing = YES;
    picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    [self presentViewController:picker animated:YES completion:nil];

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingImage:(UIImage *)image editingInfo:(NSDictionary *)editingInfo
{
    imgPanCard.image = image;
    [picker dismissModalViewControllerAnimated:YES];
}
</code>```

I need to show Image name and its extension on UILabel "No. File Chosen" How to do this.Thanks in Advance!

答:
Add following code in "didFinishPickingMediaWithInfo" method:</p>

```<code>// get the ref url
NSURL *refURL = [info valueForKey:UIImagePickerControllerReferenceURL];

// define the block to call when we get the asset based on the url (below)
ALAssetsLibraryAssetForURLResultBlock resultblock = ^(ALAsset *imageAsset)
{
    ALAssetRepresentation *imageRep = [imageAsset defaultRepresentation];
    NSLog(@"[imageRep filename] : %@", [imageRep filename]);
};

// get the asset library and fetch the asset based on the ref url (pass in block above)
ALAssetsLibrary* assetslibrary = [[ALAssetsLibrary alloc] init];
[assetslibrary assetForURL:refURL resultBlock:resultblock failureBlock:nil];
</code>```

Body:
I am new in iOS and I am facing problem regarding to show file path on UILabel. I am taking Image for gallery and I want to show Image name and its extension on UILabel.

My code is like this

Button Click...

UIImagePickerController *picker = [[UIImagePickerController alloc] init];
    picker.delegate = self;
    picker.allowsEditing = YES;
    picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    [self presentViewController:picker animated:YES completion:nil];

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingImage:(UIImage *)image editingInfo:(NSDictionary *)editingInfo
{
    imgPanCard.image = image;
    [picker dismissModalViewControllerAnimated:YES];
}

I need to show Image name and its extension on UILabel "No. File Chosen" How to do this.Thanks in Advance!

Body:
Add following code in "didFinishPickingMediaWithInfo" method:

// get the ref url
NSURL *refURL = [info valueForKey:UIImagePickerControllerReferenceURL];

// define the block to call when we get the asset based on the url (below)
ALAssetsLibraryAssetForURLResultBlock resultblock = ^(ALAsset *imageAsset)
{
    ALAssetRepresentation *imageRep = [imageAsset defaultRepresentation];
    NSLog(@"[imageRep filename] : %@", [imageRep filename]);
};

// get the asset library and fetch the asset based on the ref url (pass in block above)
ALAssetsLibrary* assetslibrary = [[ALAssetsLibrary alloc] init];
[assetslibrary assetForURL:refURL resultBlock:resultblock failureBlock:nil];


问:
Sass image url reference error, chained imports

src

images/image1.jpg

sass/sass1.scss (background-image: url('../images/image1.jpg'))

folder1/folder2/sass2.scss (@import '../../sass/sass1')

This is my folder structure. When I try to import sass1 into sass2, the image's path is not resolved as the sass loader expects the image path to be relative to the final file ,i.e, sass2 in our case.

Path where the sass loader searches the image is - 'folder1/images/image1.jpg' and not 'src/images/image1.jpg'.

I am using webpack(v1) for bundling.

答:
edit this answer should also account for webpack using src/image1 or wherever the images are before the bundle.
You need to make sure the final css path for an image is relative to the css filepath on the server. (See final section below)

Given the folder directory

```<code>src/
  sass/
    sass1.scss
    sass2.scss
public/
  images/
    image1.png
</code>```

scss2

```<code>@import "scss1"
</code>```

scss1

```<code>.class {
  background: url("./images/image1.png")
 }
</code>```

If the output scss1.css is compiled into css and placed in public, such that the public folder now looks like

```<code>src/
  sass/
    sass1.scss
    sass2.scss
public/
  images/
    image1.png
index.html
scss1.css
</code>```

Body:
edit this answer should also account for webpack using src/image1 or wherever the images are before the bundle.
You need to make sure the final css path for an image is relative to the css filepath on the server. (See final section below)

Given the folder directory

src/
  sass/
    sass1.scss
    sass2.scss
public/
  images/
    image1.png

scss2

@import "scss1"

scss1

.class {
  background: url("./images/image1.png")
 }

If the output scss1.css is compiled into css and placed in public, such that the public folder now looks like

src/
  sass/
    sass1.scss
    sass2.scss
public/
  images/
    image1.png
index.html
scss1.css


答:
From your model code:

```<code>$query=$this->db->get($db);
</code>```

This means $db is the table name. Looking at your controller code which calls the model function:

```<code>$data["all_types"] = $this->data_model->get_data("all_types",300,"Asc");
</code>```

I can say that all_types is the name of the table.

Title: attempting to modify a field in codeigniter application db table but know how to identify the table

Body:
From your model code:

$query=$this->db->get($db);

This means $db is the table name. Looking at your controller code which calls the model function:

$data["all_types"] = $this->data_model->get_data("all_types",300,"Asc");

I can say that all_types is the name of the table.


问:
React - animate mount and unmount of a single component
Something this simple should be easily accomplished, yet I'm pulling my hair out over how complicated it is.

All I want to do is animate the mounting & unmounting of a React component, that's it. Here's what I've tried so far and why each solution won't work:

ReactCSSTransitionGroup - I'm not using CSS classes at all, it's all JS styles, so this won't work.

ReactTransitionGroup - This lower level API is great, but it requires you to use a callback when the animation is complete, so just using CSS transitions won't work here. There are always animation libraries, which leads to the next point:

GreenSock - The licensing is too restrictive for business use IMO.

React Motion - This seems great, but TransitionMotion is extremely confusing and overly complicated for what I need.

Of course I can just do trickery like Material UI does, where the elements are rendered but remain hidden (left: -10000px) but I'd rather not go that route. I consider it hacky, and I want my components to unmount so they clean up and are not cluttering up the DOM.

I want something that's easy to implement. On mount, animate a set of styles; on unmount, animate the same (or another) set of styles. Done. It also has to be high performance on multiple platforms.

I've hit a brick wall here. If I'm missing something and there's an easy way to do this, let me know.

答:
For those considering react-motion, animating a single component when it mounts and unmounts can be overwhelming to set up.

There's a library called react-motion-ui-pack that makes this process a lot easier to start with. It's a wrapper around react-motion, which means you get all the benefits from the library (i.e. you are able to interrupt the animation, have multiple unmounts happen at the same time).

Usage:

```<code>import Transition from 'react-motion-ui-pack'

<Transition
  enter={{ opacity: 1, translateX: 0 }}
  leave={{ opacity: 0, translateX: -100 }}
  component={false}
>
  { this.state.show &&
      <div key="hello">
        Hello
      </div>
  }
</Transition>
</code>```

Enter defines what the end state of the component should be; leave is the style that is applied when the component is unmounted.

You might find that once you have used the UI pack a couple of times, the react-motion library might not be as daunting anymore.

Body:
For those considering react-motion, animating a single component when it mounts and unmounts can be overwhelming to set up.

There's a library called react-motion-ui-pack that makes this process a lot easier to start with. It's a wrapper around react-motion, which means you get all the benefits from the library (i.e. you are able to interrupt the animation, have multiple unmounts happen at the same time).

Usage:

import Transition from 'react-motion-ui-pack'

<Transition
  enter={{ opacity: 1, translateX: 0 }}
  leave={{ opacity: 0, translateX: -100 }}
  component={false}
>
  { this.state.show &&
      <div key="hello">
        Hello
      </div>
  }
</Transition>

Enter defines what the end state of the component should be; leave is the style that is applied when the component is unmounted.

You might find that once you have used the UI pack a couple of times, the react-motion library might not be as daunting anymore.


问:
How to work using multiple Rnw files?
I have one Rnw file called name "main.Rnw" and it includes this

```<code>\documentclass{article}
\usepackage{float}
\title{Something}
\author{John Smith}
\setkeys{Gin}{width=1.15\textwidth}
\begin{document}
\SweaveOpts{concordance=TRUE}
\thispagestyle{empty}
\maketitle
\newpage
\thispagestyle{empty}
\tableofcontents
\newpage
\SweaveInput{reports/Child.Rnw}
\end{document}
</code>```

In the file "Child.Rnw" I have:

```<code>% !Rnw root = Main.Rnw
 \documentclass{article}
 \usepackage{float}
\begin{document}
\SweaveOpts{concordance=TRUE}
\section{section}
 Something something
\end{document}
</code>```

Now it gives error:

```<code>  Error in SweaveReadFile(c(ifile, file), syntax, encoding = encoding) :
  no Sweave file with name ‘./reports/Child.Rnw’ found
  Calls: <Anonymous> -> SweaveReadFile -> SweaveReadFile
  Execution halted
</code>```

If I change the code and take away reports from command \SweaveInput{reports/Child.Rnw} (so. code is \SweaveInput{Child.Rnw} ) it gives error:

```<code>Writing to file Main.tex
Processing code chunks with options ...
 Error in seq.default(from = which + 1L, length.out = length(linesout) -  :
 'from' must be of length 1
Calls: <Anonymous> -> <Anonymous> -> seq -> seq.default
In addition: Warning messages:
1: In 1L:which : numerical expression has 2 elements: only the first used
2: In seq.default(from = which + 1L, length.out = length(linesout) -  :
first element used of 'length.out' argument
Execution halted
</code>```

What I do wrong?
I use R Studio.

答:
One of the problems why your code doesn't work is because you are defining your document twice \begin{document} and \end{document} are in your Main.Rnw and in Child.Rnw.

Your Child file \SweaveInput{Child.Rnw} should look like this:

```<code>% !Rnw root = main.Rnw
\SweaveOpts{concordance=TRUE}
\section{section}
 Something something
</code>```

Try using this file and compile PDF.

I get PDF file of 3 pages

First is title, second content and third section.

Title: How to work using multiple Rnw files?

Body:
I have one Rnw file called name "main.Rnw" and it includes this

\documentclass{article}
\usepackage{float}
\title{Something}
\author{John Smith}
\setkeys{Gin}{width=1.15\textwidth}
\begin{document}
\SweaveOpts{concordance=TRUE}
\thispagestyle{empty}
\maketitle
\newpage
\thispagestyle{empty}
\tableofcontents
\newpage
\SweaveInput{reports/Child.Rnw}
\end{document}

In the file "Child.Rnw" I have:

% !Rnw root = Main.Rnw
 \documentclass{article}
 \usepackage{float}
\begin{document}
\SweaveOpts{concordance=TRUE}
\section{section}
 Something something
\end{document}

Now it gives error:

  Error in SweaveReadFile(c(ifile, file), syntax, encoding = encoding) :
  no Sweave file with name ‘./reports/Child.Rnw’ found
  Calls: <Anonymous> -> SweaveReadFile -> SweaveReadFile
  Execution halted

If I change the code and take away reports from command \SweaveInput{reports/Child.Rnw} (so. code is \SweaveInput{Child.Rnw} ) it gives error:

Writing to file Main.tex
Processing code chunks with options ...
 Error in seq.default(from = which + 1L, length.out = length(linesout) -  :
 'from' must be of length 1
Calls: <Anonymous> -> <Anonymous> -> seq -> seq.default
In addition: Warning messages:
1: In 1L:which : numerical expression has 2 elements: only the first used
2: In seq.default(from = which + 1L, length.out = length(linesout) -  :
first element used of 'length.out' argument
Execution halted

What I do wrong?
I use R Studio.

Body:
One of the problems why your code doesn't work is because you are defining your document twice \begin{document} and \end{document} are in your Main.Rnw and in Child.Rnw.

Your Child file \SweaveInput{Child.Rnw} should look like this:

% !Rnw root = main.Rnw
\SweaveOpts{concordance=TRUE}
\section{section}
 Something something

Try using this file and compile PDF.

I get PDF file of 3 pages

First is title, second content and third section.


问:
Modular Exponentiation of 2
I have written this code to calculate 2^n mod 10^9+7. But sadly this function works only till 2^31 and afterwards all the answers are zero.
Can somebody shed some light why?

```<code>typedef unsigned long long LL;
const int MOD = 1000000007;
LL powmod(int a,int n)
{
    LL p=1;
    for(;n;)
    {
        if(n%2) p=(p*a)%MOD;
        if(n/=2) a=(a*a)%MOD;
    }
    return p;
}
</code>```

答:
Just change LL powmod(int a,int n) to LL powmod(LL a,int n).

As squeamish ossifrage hinted at, with int a, the subexpression a*a is computed in int range and overflows "when a * a exceeds MAX_INT" (M.M), while with LL a, it is computed in unsigned long long range.

Title: Modular Exponentiation of 2

Body:
I have written this code to calculate 2^n mod 10^9+7. But sadly this function works only till 2^31 and afterwards all the answers are zero.
Can somebody shed some light why?

typedef unsigned long long LL;
const int MOD = 1000000007;
LL powmod(int a,int n)
{
    LL p=1;
    for(;n;)
    {
        if(n%2) p=(p*a)%MOD;
        if(n/=2) a=(a*a)%MOD;
    }
    return p;
}