问:
UITableViewCell Not Displaying Data - Swift Playgrounds
I have been trying to implement some custom cells in a table view I created in a view controller in the swift playgrounds iPad app. Please note that I have seen a lot of the other stack overflow posts dealing with similar issues but have not been able to find a solution that fixes my problem.

Here is my CustomCell Class:

```<code>class CustomCell: UITableViewCell {

    let projectImage = UIImageView()
    //let projectDivider = UIView()
    let projectTitle = UILabel()

    override func awakeFromNib() {
        projectImage.frame = CGRect(x: 0, y: 0, width: 100, height: 100)
        //projectDivider.frame = CGRect(x: 100, y: 0, width: 20, height: 100)
        projectTitle.frame = CGRect(x: 120, y: 0, width: 200, height: 100)

        self.contentView.addSubview(projectImage)
        //self.contentView.addSubview(projectDivider)
        self.contentView.addSubview(projectTitle)
    }

}
</code>```

The following is my view controller code:

```<code>class AboutViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {

    let tableView = UITableView()
    let cellReuseIdentifier: String = "cell"

    var projectTitles = ["Madhubani Coffee", "World Savvy", "Zipshare", "CrashThatCode", "Future Plans"]
    var images: [UIImage] = [UIImage(named: "IMG_0061.JPG")!, UIImage(named: "IMG_0064.JPG")!, UIImage(named: "IMG_0062.JPG")!, UIImage(named: "IMG_0062.JPG")!, UIImage(named: "IMG_0062.JPG")!]

    override func viewDidLoad() {
        view.backgroundColor = UIColor.white

        tableView.frame = CGRect(x: -82.5, y: 250, width: 600, height: 600)
        tableView.delegate = self
        tableView.dataSource = self
        tableView.backgroundColor = UIColor.white

        self.tableView.register(CustomCell.self as AnyClass, forCellReuseIdentifier: cellReuseIdentifier)
        view.addSubview(tableView)

     }

     func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 5
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

        var cell = self.tableView.dequeueReusableCell(withIdentifier: cellReuseIdentifier, for: indexPath) as! CustomCell

        if cell == nil {
            cell = UITableViewCell(style: UITableViewCellStyle.default, reuseIdentifier: cellReuseIdentifier) as! CustomCell
        }

        cell.projectImage.image = images[indexPath.row]
        cell.projectTitle.text = projectTitles[indexPath.row]

        cell.clipsToBounds = true

        return cell
    }
}
</code>```

I don't know what the problem is. It seems that the cells simply do not display. Any help would be appreciated!

答:
Your problem is that you don't have a nib (or xib) file to do an awakeFromNib from.

Try doing this for your CustomCell instead:

```<code>class CustomCell: UITableViewCell {

    let projectImage = UIImageView()
    //let projectDivider = UIView()
    var projectTitle = UILabel()

    override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)

        projectImage.frame = CGRect(x: 0, y: 0, width: 100, height: 30)
        //projectDivider.frame = CGRect(x: 100, y: 0, width: 20, height: 100)
        projectTitle.frame = CGRect(x: 10, y: 0, width: 200, height: 30)
        projectTitle.font = UIFont.systemFont(ofSize: 20.0)
        //self.contentView.addSubview(projectImage)
        //self.contentView.addSubview(projectDivider)
        self.contentView.addSubview(projectTitle)
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

}
</code>```

Body:
I have been trying to implement some custom cells in a table view I created in a view controller in the swift playgrounds iPad app. Please note that I have seen a lot of the other stack overflow posts dealing with similar issues but have not been able to find a solution that fixes my problem.

Here is my CustomCell Class:

class CustomCell: UITableViewCell {

    let projectImage = UIImageView()
    //let projectDivider = UIView()
    let projectTitle = UILabel()

    override func awakeFromNib() {
        projectImage.frame = CGRect(x: 0, y: 0, width: 100, height: 100)
        //projectDivider.frame = CGRect(x: 100, y: 0, width: 20, height: 100)
        projectTitle.frame = CGRect(x: 120, y: 0, width: 200, height: 100)

        self.contentView.addSubview(projectImage)
        //self.contentView.addSubview(projectDivider)
        self.contentView.addSubview(projectTitle)
    }

}

The following is my view controller code:

class AboutViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {

    let tableView = UITableView()
    let cellReuseIdentifier: String = "cell"

    var projectTitles = ["Madhubani Coffee", "World Savvy", "Zipshare", "CrashThatCode", "Future Plans"]
    var images: [UIImage] = [UIImage(named: "IMG_0061.JPG")!, UIImage(named: "IMG_0064.JPG")!, UIImage(named: "IMG_0062.JPG")!, UIImage(named: "IMG_0062.JPG")!, UIImage(named: "IMG_0062.JPG")!]

    override func viewDidLoad() {
        view.backgroundColor = UIColor.white

        tableView.frame = CGRect(x: -82.5, y: 250, width: 600, height: 600)
        tableView.delegate = self
        tableView.dataSource = self
        tableView.backgroundColor = UIColor.white

        self.tableView.register(CustomCell.self as AnyClass, forCellReuseIdentifier: cellReuseIdentifier)
        view.addSubview(tableView)

     }

     func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 5
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

        var cell = self.tableView.dequeueReusableCell(withIdentifier: cellReuseIdentifier, for: indexPath) as! CustomCell

        if cell == nil {
            cell = UITableViewCell(style: UITableViewCellStyle.default, reuseIdentifier: cellReuseIdentifier) as! CustomCell
        }

        cell.projectImage.image = images[indexPath.row]
        cell.projectTitle.text = projectTitles[indexPath.row]

        cell.clipsToBounds = true

        return cell
    }
}

I don't know what the problem is. It seems that the cells simply do not display. Any help would be appreciated!

Body:
Your problem is that you don't have a nib (or xib) file to do an awakeFromNib from.

Try doing this for your CustomCell instead:

class CustomCell: UITableViewCell {

    let projectImage = UIImageView()
    //let projectDivider = UIView()
    var projectTitle = UILabel()

    override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)

        projectImage.frame = CGRect(x: 0, y: 0, width: 100, height: 30)
        //projectDivider.frame = CGRect(x: 100, y: 0, width: 20, height: 100)
        projectTitle.frame = CGRect(x: 10, y: 0, width: 200, height: 30)
        projectTitle.font = UIFont.systemFont(ofSize: 20.0)
        //self.contentView.addSubview(projectImage)
        //self.contentView.addSubview(projectDivider)
        self.contentView.addSubview(projectTitle)
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

}


来源: stackexchange

问:
How to run a vba macro on a specific worksheet without leaving the current worksheet
I would like to have a VBA code run on one, or more, specific worksheets of a workbook in Excel. But I do not wish to activate the worksheets where the code will run, I wish to have it done in the background and have the results shown on the current worksheet, where there will be a button do call the code.
All the responses I have seen to such question require visiting the worksheet where the macro will run but I would like to avoid that.
Perhaps putting the code inside a With statement will do the job? I have investigated it but cannot figure out all the dots in front of the lines.
I tried to post the code here but I keep getting indentation errors so I will omit it for now.

Thanks in advance.

答:
Thanks guys! I ended up activating every sheet (was in a hurry).
Best regards,</p>

ContentLicense: CC BY-SA 3.0


问:
Why Google Tag Manager is not always implemented as it is in the Google Demo Shop?
got some questions about the Google Tag Manager snippet. If I'm looking at the Google Demo Shop website the GTM implementation is like this :

```<code><head>
    <script async="" src="//www.googletagmanager.com/gtm.js?id=GTM-XXXXX"></script>
            ... some stuff ...
    <noscript> <iframe src="//www.googletagmanager.com/ns.html?id=GTM-XXXX" height="0" width="0" style="display:none;visibility:hidden"></iframe>
    </noscript>
    <script>(function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({'gtm.start': new Date().getTime(),event:'gtm.js'});var f=d.getElementsByTagName(s)[0],j=d.createElement(s),dl=l!='dataLayer'?'&l='+l:'';j.async=true;j.src='//www.googletagmanager.com/gtm.js?id='+i+dl;f.parentNode.insertBefore(j,f);})(window,document,'script','dataLayer','GTM-5Q5LZH');
    </script>
</head>
</code>```

So basically everything is in the header. So first question, what is this line for :

```<code><script async="" src="//www.googletagmanager.com/gtm.js?id=GTM-XXXXX"></script>
</code>```

Second question, I've read that the code below:

```<code><noscript> <iframe src="//www.googletagmanager.com/ns.html?id=GTM-XXXX" height="0" width="0" style="display:none;visibility:hidden"></iframe>
</noscript>
<script>(function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({'gtm.start': new Date().getTime(),event:'gtm.js'});var f=d.getElementsByTagName(s)[0],j=d.createElement(s),dl=l!='dataLayer'?'&l='+l:'';j.async=true;j.src='//www.googletagmanager.com/gtm.js?id='+i+dl;f.parentNode.insertBefore(j,f);})(window,document,'script','dataLayer','GTM-5Q5LZH');
</script>
</code>```

could be implemented just after the opening of the body tag... and I've seen this a lot.

Is there some real differences between these different kind of implementation ? It doesn't seems to make any differences for Google Tag Assistant.
Thanks !

答:
Initially Google Tag Manager recommended that the GTM snippet be located in the , however it has recently updated its recomendation for it to be in the .

This is most likely due to two reasons.

1) Apparently there were concerns about the way that the GTM library made modifications to the document object model which might have lead to conflicts for IE7  or older.

2) The  within the  is embedded content, rather then HTML, which is not allowed in the  of the document.

Recently Google has updated its guides and documentation to show a split implementation, with the in the  in the Tag Assistant is not the actual code, but how the Tag Management extension interprets the code.

3) The  implementation was the previously recommended implementation, which is why you have seen it a lot.

4) Going forward, I would recommend the implementation advised by Google when setting up a Google Tag Manager container, spiting the placement between the  and the . This means that GTM will load as early as possible, with an iframe backup if required.

5) Tag Assistant merely checks the code against rules manually set within the extension. The obvious caveat of this is that the extension needs to be kept up to date. An example of this is that recently the GTM container id's moved from 6 to 7 characters however the extension was not updated, leading to a lot of people getting errors in the Tag Assistant stating that their container ID was incorrect.

Body:
got some questions about the Google Tag Manager snippet. If I'm looking at the Google Demo Shop website the GTM implementation is like this :

            ... some stuff ...

So basically everything is in the header. So first question, what is this line for :

Second question, I've read that the code below:

could be implemented just after the opening of the body tag... and I've seen this a lot.

Is there some real differences between these different kind of implementation ? It doesn't seems to make any differences for Google Tag Assistant.
Thanks !

Body:
Initially Google Tag Manager recommended that the GTM snippet be located in the <body>, however it has recently updated its recomendation for it to be in the <head>.

This is most likely due to two reasons.

1) Apparently there were concerns about the way that the GTM library made modifications to the document object model which might have lead to conflicts for IE7  or older.

2) The <iframe> within the <noscript> is embedded content, rather then HTML, which is not allowed in the <head> of the document.

Recently Google has updated its guides and documentation to show a split implementation, with the in the <script> in the <head> and the <noscript><iframe> in the <body>.

This makes sense, as there is no reason why an asynchonrous JavaScript library needs to be in the <body>. As with all tracking its ideal to have the dependencies loaded as early as possible to ensure that your tracking is available prior to the user interacting with the website. However due to reason 2, the <noscript><iframe> is still recommended to be placed in the <body>.

So, to answer your questions:

1) the implementation on the Google Demo Store is incorrect, the entire code should not be placed in the <head>.

2) The <script async="" src="//www.googletagmanager.com/gtm.js?id=GTM-XXXXX"></script> in the Tag Assistant is not the actual code, but how the Tag Management extension interprets the code.

3) The <body> implementation was the previously recommended implementation, which is why you have seen it a lot.

4) Going forward, I would recommend the implementation advised by Google when setting up a Google Tag Manager container, spiting the placement between the <head> and the <body>. This means that GTM will load as early as possible, with an iframe backup if required.

5) Tag Assistant merely checks the code against rules manually set within the extension. The obvious caveat of this is that the extension needs to be kept up to date. An example of this is that recently the GTM container id's moved from 6 to 7 characters however the extension was not updated, leading to a lot of people getting errors in the Tag Assistant stating that their container ID was incorrect.


问:
Trouble downloading images into array from Firebase
Here is the code I'm having trouble with.

Shared:

```<code>// Firebase services
var database: FIRDatabase!
var storage: FIRStorage!
...
// Initialize Database, Auth, Storage
database = FIRDatabase.database()
storage = FIRStorage.storage()
...
// Initialize an array for your pictures
var picArray: [UIImage]()
</code>```

Upload:

```<code>let fileData = NSData() // get data...
let storageRef = storage.reference().child("myFiles/myFile")
storageRef.putData(fileData).observeStatus(.Success) { (snapshot) in
// When the image has successfully uploaded, we get it's download URL
let downloadURL = snapshot.metadata?.downloadURL()?.absoluteString
// Write the download URL to the Realtime Database
let dbRef = database.reference().child("myFiles/myFile")
dbRef.setValue(downloadURL)
</code>```

}

Download:

```<code>let dbRef = database.reference().child("myFiles")
dbRef.observeEventType(.ChildAdded, withBlock: { (snapshot) in
// Get download URL from snapshot
let downloadURL = snapshot.value() as! String
// Create a storage reference from the URL
let storageRef = storage.referenceFromURL(downloadURL)
// Download the data, assuming a max size of 1MB (you can change this as necessary)
storageRef.dataWithMaxSize(1 * 1024 * 1024) { (data, error) -> Void in
// Create a UIImage, add it to the array
let pic = UIImage(data: data)
picArray.append(pic)
 })
})
</code>```

I've been trying to use the above code posted originally by @Mike-McDonald a few months ago, to pull and append an array of images from my Firebase DB.  I am successfully able to upload images using the above, but for the life of me, I cannot get the images to download, nor append to an images array.

I'm not getting any errors - it's just that simply the "download" code does not appear to be running (I've tried to verify this in the console as well).  A couple of lines are different for Swift 3, but the only one that I'm unsure about is:

```<code>let storageRef = storage.referenceFromURL(downloadURL)
</code>```

is now

```<code>let storageRef = self.storage.reference(forURL: downloadURL)
</code>```

Any suggestions on this, or on how to create/append an array of images using the childadded observer with Firebase would be appreciated. Thanks!

答:
I figured out the answer to this in my case. I wasn't uploading the image as data. And so the download as data was never happening. It doesn't trigger an error, it just doesn't execute. Here is the change I made:

```<code>let fileData = NSData()
</code>```

changed to:

```<code>let fileData = (UIImagePNGRepresentation(self.imagefile.image!)! as NSData?)!
</code>```

It's working perfectly now!

Body:
Here is the code I'm having trouble with.

Shared:

// Firebase services
var database: FIRDatabase!
var storage: FIRStorage!
...
// Initialize Database, Auth, Storage
database = FIRDatabase.database()
storage = FIRStorage.storage()
...
// Initialize an array for your pictures
var picArray: [UIImage]()

Upload:

let fileData = NSData() // get data...
let storageRef = storage.reference().child("myFiles/myFile")
storageRef.putData(fileData).observeStatus(.Success) { (snapshot) in
// When the image has successfully uploaded, we get it's download URL
let downloadURL = snapshot.metadata?.downloadURL()?.absoluteString
// Write the download URL to the Realtime Database
let dbRef = database.reference().child("myFiles/myFile")
dbRef.setValue(downloadURL)

}

Download:

let dbRef = database.reference().child("myFiles")
dbRef.observeEventType(.ChildAdded, withBlock: { (snapshot) in
// Get download URL from snapshot
let downloadURL = snapshot.value() as! String
// Create a storage reference from the URL
let storageRef = storage.referenceFromURL(downloadURL)
// Download the data, assuming a max size of 1MB (you can change this as necessary)
storageRef.dataWithMaxSize(1 * 1024 * 1024) { (data, error) -> Void in
// Create a UIImage, add it to the array
let pic = UIImage(data: data)
picArray.append(pic)
 })
})

I've been trying to use the above code posted originally by @Mike-McDonald a few months ago, to pull and append an array of images from my Firebase DB.  I am successfully able to upload images using the above, but for the life of me, I cannot get the images to download, nor append to an images array.

I'm not getting any errors - it's just that simply the "download" code does not appear to be running (I've tried to verify this in the console as well).  A couple of lines are different for Swift 3, but the only one that I'm unsure about is:

let storageRef = storage.referenceFromURL(downloadURL)

is now

let storageRef = self.storage.reference(forURL: downloadURL)

Any suggestions on this, or on how to create/append an array of images using the childadded observer with Firebase would be appreciated. Thanks!

Body:
I figured out the answer to this in my case. I wasn't uploading the image as data. And so the download as data was never happening. It doesn't trigger an error, it just doesn't execute. Here is the change I made:

let fileData = NSData()

changed to:

let fileData = (UIImagePNGRepresentation(self.imagefile.image!)! as NSData?)!

It's working perfectly now!


问:
Joomla add article via php script Application Instantiation Error
i created a script in order to insert some articles via a php script. This script is working on my local machine (xampp), but when i deploy the whole joomla project to my web server i get the following error message:

Error displaying the error page: Application Instantiation Error: Application Instantiation Error

By adding some echo calls, i was able to find the line which causes the error:

```<code>$app = JFactory::getApplication('site');
</code>```

Now i am wondering how to fix this behaviour and make my function also run on the web server.

Below i will provide my system informations and the beginning of my php function until the line, which causes the error message:

Systeminformations

joomla version: 3.6.5 Stable

db version: 5.6.34-79.1-log

php version: 5.6.30-he.0

web server: Apache

PHP snippet

```<code><?php

echo "STARTING;   ";

// get db connection
include('../includes/mysql.inc.php');

// get all sql querys
include('./autoNewsQuerys.inc.php');

/**
 * Prepare joomla framework to insert article correctly
 */
if (!defined('_JEXEC')) {
    define('_JEXEC', 1);
    define('JPATH_BASE','/is/htdocs/wp1088688_4E1H7PYJFK/www');
    require_once(JPATH_BASE . '/includes/defines.php');
    require_once(JPATH_BASE . '/includes/framework.php');
    defined('DS') or define('DS', DIRECTORY_SEPARATOR);
}

echo "searching app;";
$app = JFactory::getApplication('site');
echo "Found app;";

</code>```

Full browser output

STARTING; searching app;Error displaying the error page: Application Instantiation Error: Failed to start the session because headers have already been sent by "/is/htdocs/wp1088688_4E1H7PYJFK/www/1500AutoNews/autoNews.php" at line 3.

So as you can see the error is caused by the JFactory call. 'Found app' is never printed out.

答:
Just copy the Joomla index.php file to another file and then replace the $app->execute code with your code.

Note: You don't need to include any MySQL library - since you are loading the Joomla environment then you have access to the JDatabase class, which is a database abstraction layer.

Another note: this file autoNewsQuerys.inc.php likely contains some issues (maybe you are trying to instantiate the app there, but the Joomla environment hasn't loaded yet). You should move it to the end.

Body:
i created a script in order to insert some articles via a php script. This script is working on my local machine (xampp), but when i deploy the whole joomla project to my web server i get the following error message:

Error displaying the error page: Application Instantiation Error: Application Instantiation Error

By adding some echo calls, i was able to find the line which causes the error:

$app = JFactory::getApplication('site');

Now i am wondering how to fix this behaviour and make my function also run on the web server.

Below i will provide my system informations and the beginning of my php function until the line, which causes the error message:

Systeminformations

joomla version: 3.6.5 Stable

db version: 5.6.34-79.1-log

php version: 5.6.30-he.0

web server: Apache

PHP snippet

<?php

echo "STARTING;   ";

// get db connection
include('../includes/mysql.inc.php');

// get all sql querys
include('./autoNewsQuerys.inc.php');

/**
 * Prepare joomla framework to insert article correctly
 */
if (!defined('_JEXEC')) {
    define('_JEXEC', 1);
    define('JPATH_BASE','/is/htdocs/wp1088688_4E1H7PYJFK/www');
    require_once(JPATH_BASE . '/includes/defines.php');
    require_once(JPATH_BASE . '/includes/framework.php');
    defined('DS') or define('DS', DIRECTORY_SEPARATOR);
}

echo "searching app;";
$app = JFactory::getApplication('site');
echo "Found app;";

Full browser output

STARTING; searching app;Error displaying the error page: Application Instantiation Error: Failed to start the session because headers have already been sent by "/is/htdocs/wp1088688_4E1H7PYJFK/www/1500AutoNews/autoNews.php" at line 3.

So as you can see the error is caused by the JFactory call. 'Found app' is never printed out.


问:
Do I need NSMetadataQueryDidFinishGathering, if I watch every NSMetadataQueryGatheringProgress?
NSMetadataQuery posts NSMetadataQueryGatheringProgress as the query runs and then NSMetadataQueryDidFinishGathering, when it's done.  I'm receiving both notifications, and they work fine.

I notice, though, that when I get NSMetadaQueryDidFinishGathering, there's never any new data since the final gathering progress. Is that guaranteed to always be the case?

I've read the docs for both these constants, and it's not clear to me if that's what was intended.

If I deal with incoming results in NSMetadataQueryDidFinishGathering?, will that always get me every result?

答:
As far as I understand the documentation this is true for a static search, but it is not true for a live search.

A NSMetadataQueryDidFinishGathering is send after the initial search (gathering process). You can stop then the search inside your did finish method with -stopQuery. Then, of course, no new data will be delivered.

But you can simply pause the search with -disableUpdate, too. Then you read the results and restart the (live) search with -enableUpdates. Then you will get updates after the finish notification, i. e. when the user changes files to match the search criteria.


问:
Is there an equivalent of SimpleTest's "partial mocks" in PHPUnit?
I'm trying to migrate a bunch of tests from SimpleTest to PHPUnit and I was wondering if there is an equivalent for SimpleTest's partial mocks.

I can't seem to find anything in the documentation which suggests that this feature is available, but it occurred to me that I could just use a subclass. Is this a good or bad idea?

```<code>class StuffDoer {
    protected function doesLongRunningThing() {
        sleep(10);
        return "stuff";
    }
    public function doStuff() {
        return $this->doesLongRunningThing();
    }
}

class StuffDoerTest {
    protected function doesLongRunningThing() {
        return "test stuff";
    }
}

class StuffDoerTestCase extends PHPUnit_Framework_TestCase {
    public function testStuffDoer() {
        $sd = new StuffDoerTest();
        $result = $sd->doStuff();
        $this->assertEquals($result, "test stuff");
    }
}
</code>```

答:
PHPUnit_Framework_TestCase::getMock is deprecated since phpunit 5.4. We can use setMethods instead.

setMethods(array $methods) can be called on the Mock Builder object to specify the methods that are to be replaced with a configurable test double. The behavior of the other methods is not changed. If you call setMethods(null), then no methods will be replaced.

https://phpunit.de/manual/current/en/test-doubles.html

```<code>$observer = $this->getMockBuilder(Observer::class)
                 ->setMethods(['update'])
                 ->getMock();
</code>```

Note that the above getMock is PHPUnit_Framework_MockObject_MockBuilder::getMock. (phpunit5.6)

ContentLicense: CC BY-SA 4.0

Body:
I'm trying to migrate a bunch of tests from SimpleTest to PHPUnit and I was wondering if there is an equivalent for SimpleTest's partial mocks.

I can't seem to find anything in the documentation which suggests that this feature is available, but it occurred to me that I could just use a subclass. Is this a good or bad idea?

class StuffDoer {
    protected function doesLongRunningThing() {
        sleep(10);
        return "stuff";
    }
    public function doStuff() {
        return $this->doesLongRunningThing();
    }
}

class StuffDoerTest {
    protected function doesLongRunningThing() {
        return "test stuff";
    }
}

class StuffDoerTestCase extends PHPUnit_Framework_TestCase {
    public function testStuffDoer() {
        $sd = new StuffDoerTest();
        $result = $sd->doStuff();
        $this->assertEquals($result, "test stuff");
    }
}

Body:
PHPUnit_Framework_TestCase::getMock is deprecated since phpunit 5.4. We can use setMethods instead.

setMethods(array $methods) can be called on the Mock Builder object to specify the methods that are to be replaced with a configurable test double. The behavior of the other methods is not changed. If you call setMethods(null), then no methods will be replaced.

https://phpunit.de/manual/current/en/test-doubles.html

$observer = $this->getMockBuilder(Observer::class)
                 ->setMethods(['update'])
                 ->getMock();

Note that the above getMock is PHPUnit_Framework_MockObject_MockBuilder::getMock. (phpunit5.6)


问:
Play sound when opening folder (AppleScript)
Pretty new to this.

I'm trying to figure out how to play an audio file when opening a folder without any windows opening or using any external apps. Any help would be appreciated.

答:
If you want to make life a little easier for yourself, I would suggest creating a new script editor file, allowing you to choose the audio file you would like to use on your folder action.  In this new AppleScript document, just enter this code:

```<code>choose file
</code>```

and then click the “Run” button.  This will open a file chooser window, allowing you to go to any directory on your computer and choose any audio file you would like to use.

After you choose your file, copy the entire text from the result window.  Now it's time to create your new folder action.  Create a another new script editor document and place your cursor at the top of the document and Ctrl+Click

Now remember you copied that file information from the result window in the “choose file” script.  Paste that information into your code as you can see in my sample Image.

```<code>on opening folder this_folder
    set a to alias "Macintosh HD:Users:Smokestack:Music:iTunes:iTunes Media:Music:Pink Floyd:Dark Side Of The Moon - 30th Anniversary SACD:09 Brain Damage.mp3"
    set p to POSIX path of a
    do shell script "afplay -t 25 " & quoted form of p
    (* The "-t 25" Is just an option telling afplay shell script to only play the audio for 25 seconds.  You can adjust that number to what ever you would like or remove that part of the command completely.
    the code below this line is what you would use if you don't want a time limit on the audio
    do shell script "afplay " & quoted form of p  *)
end opening folder
</code>```

Now compile and save your script to your /Users/YOUR_SHORT_USER_NAME/Library/Workflows/Applications/Folder Actions

The next thing you want to do is open your Folder Actions Setup.app which you can find here: /System/Library/CoreServices/Applications/Folder Actions Setup.app

Because you saved that AppleScript folder action file to that specific location, it will now be available in your Folder Actions Setup.app when you choose “attach script to folder”

Body:
If you want to make life a little easier for yourself, I would suggest creating a new script editor file, allowing you to choose the audio file you would like to use on your folder action.  In this new AppleScript document, just enter this code:

choose file

and then click the “Run” button.  This will open a file chooser window, allowing you to go to any directory on your computer and choose any audio file you would like to use.

After you choose your file, copy the entire text from the result window.  Now it's time to create your new folder action.  Create a another new script editor document and place your cursor at the top of the document and Ctrl+Click

Now remember you copied that file information from the result window in the “choose file” script.  Paste that information into your code as you can see in my sample Image.

on opening folder this_folder
    set a to alias "Macintosh HD:Users:Smokestack:Music:iTunes:iTunes Media:Music:Pink Floyd:Dark Side Of The Moon - 30th Anniversary SACD:09 Brain Damage.mp3"
    set p to POSIX path of a
    do shell script "afplay -t 25 " & quoted form of p
    (* The "-t 25" Is just an option telling afplay shell script to only play the audio for 25 seconds.  You can adjust that number to what ever you would like or remove that part of the command completely.
    the code below this line is what you would use if you don't want a time limit on the audio
    do shell script "afplay " & quoted form of p  *)
end opening folder

Now compile and save your script to your /Users/YOUR_SHORT_USER_NAME/Library/Workflows/Applications/Folder Actions

The next thing you want to do is open your Folder Actions Setup.app which you can find here: /System/Library/CoreServices/Applications/Folder Actions Setup.app

Because you saved that AppleScript folder action file to that specific location, it will now be available in your Folder Actions Setup.app when you choose “attach script to folder”


问:
Tool for storing per environment configuration
I have a requirement to store configuration information on a per environment basis in a tool.

This is a tool with a GUI for adding/updating configuration values (e.g connection strings). This should have a default value and be able to change this based on different environments.

There should be an API to retrieve these configuration values during deployment to a particular environment to add to the application.

I have googled for a while and can't see any tools that would fit this bill. Are there any suggestions?

答:
It would be great to know more about where you will be using the configs, ie. local, cloud etc. but consider using Puppet with a source control repo like Github.
There are GUIs but you can find lots of template examples to get started if you want to change the conn settings in the config code yourself and then commit them to your repo or set them as a variable and you'll only have to change the variables file.
Doing it this way will allow you to eventually start running automated builds.</p>


问:
c# Active Directory.... weirdness when creating a OU just under the root
So, I've run thi scode a dozen times and it worked,
now it's not working. I'm assuming its some kind of permission on the ad server for the account that's logged in, but the behavior is still puzzling.

here is the code

```<code>public JCDCDirectoryEntry CreateOrgUnit( string organizationalUnit, string description, ADS_GROUP_TYPE type )
{
    log.Debug( GetMethodNameAndParms() + " - in" );

    // Bind to the domain that this user is currently connected to.
    DirectoryEntry g = ADEntry.Children.Add( "ou=" + organizationalUnit, "organizationalUnit" );
    g.Properties[ "description" ].Value = description;

    // Commit the new organizationalUnit to the directory.
    g.CommitChanges();
    JCDCDirectoryEntry newOrgUnit = new JCDCDirectoryEntry( g, BuildType.distinguishedName, ADManager );

    g.Close();

    return newOrgUnit;
}
</code>```

this part just does a search for the OU "Centers" by name

```<code>JCDCDirectoryEntry newOrgUnit = new JCDCDirectoryEntry( g, BuildType.distinguishedName, ADManager );
</code>```

everything runs with no errors till it hits that line, then that line says no such object exists on the server.

I go look in the LDAP browser,and yes, the Centers OU does not exist.

But if it's a permissions thing, why does it not throw and error on this bit...

```<code>DirectoryEntry g = ADEntry.Children.Add( "ou=" + organizationalUnit, "organizationalUnit" );
g.Properties[ "description" ].Value = description;

// Commit the new organizationalUnit to the directory.
g.CommitChanges();
</code>```

Shouldn't it throw an error on CommitChanges(); ?

Anyone have any idea what could have changed to make this code stop working?
the same user deleted the tree, so it's got permissions to do at least somethings...

I used this same code, at least a dozen times testing earlier on this same domain, say a month ago.

Any help or hint is greatly appreciated.

答:
Sigh,

I rebooted my machine and it started working agian.

Sorry Everyone.

Cal-

ContentLicense: CC BY-SA 2.5

Body:
So, I've run thi scode a dozen times and it worked,
now it's not working. I'm assuming its some kind of permission on the ad server for the account that's logged in, but the behavior is still puzzling.

here is the code

public JCDCDirectoryEntry CreateOrgUnit( string organizationalUnit, string description, ADS_GROUP_TYPE type )
{
    log.Debug( GetMethodNameAndParms() + " - in" );

    // Bind to the domain that this user is currently connected to.
    DirectoryEntry g = ADEntry.Children.Add( "ou=" + organizationalUnit, "organizationalUnit" );
    g.Properties[ "description" ].Value = description;

    // Commit the new organizationalUnit to the directory.
    g.CommitChanges();
    JCDCDirectoryEntry newOrgUnit = new JCDCDirectoryEntry( g, BuildType.distinguishedName, ADManager );

    g.Close();

    return newOrgUnit;
}

this part just does a search for the OU "Centers" by name

JCDCDirectoryEntry newOrgUnit = new JCDCDirectoryEntry( g, BuildType.distinguishedName, ADManager );

everything runs with no errors till it hits that line, then that line says no such object exists on the server.

I go look in the LDAP browser,and yes, the Centers OU does not exist.

But if it's a permissions thing, why does it not throw and error on this bit...

DirectoryEntry g = ADEntry.Children.Add( "ou=" + organizationalUnit, "organizationalUnit" );
g.Properties[ "description" ].Value = description;

// Commit the new organizationalUnit to the directory.
g.CommitChanges();

Shouldn't it throw an error on CommitChanges(); ?

Anyone have any idea what could have changed to make this code stop working?
the same user deleted the tree, so it's got permissions to do at least somethings...

I used this same code, at least a dozen times testing earlier on this same domain, say a month ago.

Any help or hint is greatly appreciated.


问:
c/c++ image loading/saving libraries
I'm looking for a c/c++ library that can load and save image from all these requirements :

multiple supported image format

can load and save huge image (> 2GB) (that often mean a logic image from tiling multiple images)

can read/write metadata

have callback mechanism while loading/writing for user feedback

I saw a multitude of libraries but none of them seam to do the job :

OpenCV

Qt

FreeImage

Boost::GIL

MIL (Matrox Imaging Library)

LeadTools

Cimg

DevIl

...

I saw multiple posts addressing this problem but none of them answer my needs. Do I miss something? I am interested as much as a free or a paid library.

Thanks for your time!

答: Have you looked at libGD or ImageMagick?</p>

Title: c/c++ image loading/saving libraries


问:
unoconv return error when running as www-data
When running this from command line as root it works

```<code>unoconv -f csv $file
</code>```

But when running it as www-data this error is returned

```<code>Traceback (most recent call last):
  File "/usr/bin/unoconv", line 1114, in <module>
    office_environ(of)
  File "/usr/bin/unoconv", line 203, in office_environ
    os.environ['PATH'] = realpath(office.basepath, 'program') + os.pathsep + os.environ['PATH']
  File "/usr/lib/python3.4/os.py", line 633, in __getitem__
    raise KeyError(key) from None
KeyError: 'PATH'
</code>```

update

```<code>echo shell_exec('echo $PATH');
/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
</code>```

答:
centos 7.3 with php via php-fpm
the env in php is cleaned by php-fpm

u can use putenv to set evn["PATH"] in php code, examples

```<code>putenv("PATH=/sbin:/bin:/usr/sbin:/usr/bin");
var_dump(shell_exec('unoconv -vvvv -f pdf -o 123.pdf 123.doc));
</code>```

or u can set env use one line shell cmd

```<code>var_dump(shell_exec('PATH=/sbin:/bin:/usr/sbin:/usr/bin'.' unoconv -vvvv -f pdf -o 123.pdf 123.doc));
</code>```

or u can change /etc/php-fpm.d/www.conf to pass the env to php, add this line

```<code>clean_env = no
</code>```

and the restart php-fpm

```<code>systemctl restart php-fpm.service
</code>```

Body:
When running this from command line as root it works

unoconv -f csv $file

But when running it as www-data this error is returned

Traceback (most recent call last):
  File "/usr/bin/unoconv", line 1114, in <module>
    office_environ(of)
  File "/usr/bin/unoconv", line 203, in office_environ
    os.environ['PATH'] = realpath(office.basepath, 'program') + os.pathsep + os.environ['PATH']
  File "/usr/lib/python3.4/os.py", line 633, in __getitem__
    raise KeyError(key) from None
KeyError: 'PATH'

update

echo shell_exec('echo $PATH');
/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin

Body:
centos 7.3 with php via php-fpm
the env in php is cleaned by php-fpm

u can use putenv to set evn["PATH"] in php code, examples

putenv("PATH=/sbin:/bin:/usr/sbin:/usr/bin");
var_dump(shell_exec('unoconv -vvvv -f pdf -o 123.pdf 123.doc));

or u can set env use one line shell cmd

var_dump(shell_exec('PATH=/sbin:/bin:/usr/sbin:/usr/bin'.' unoconv -vvvv -f pdf -o 123.pdf 123.doc));

or u can change /etc/php-fpm.d/www.conf to pass the env to php, add this line

clean_env = no

and the restart php-fpm

systemctl restart php-fpm.service


问:
dynamic select with relation to other selection
I have two methods to get data from remote service.

Api.types() returns me [{name:'vegetable', id:0}, {name:'fruit', id:1}]. Based on that returns and if i change selected type it should update variety field data with data about fruits/vegetables. What's wrong at that code?

```<code>controller('MainCtrl', ['$log', 'Api', function($log, Api) {
  this.formFields = [
    {
       key: "type",
       type: "select",
       templateOptions: {
         label: "Types",
         valueProp: "id",
         labelProp: "name",
         options:[],
       },
       expressionProperties: {
         'templateOptions.options': function($viewValue, $modelValue, scope) {
            Api.types()
              .then(function(ok) { scope.to.options=ok;}, function(error){});
         }
       },
    },
    {
       key: "variety",
       type: "select",
       templateOptions: {
         label: "variety",
         valueProp: "id",
         labelProp: "name",
         options:[],
       },
       expressionProperties: {
         'templateOptions.options': function($viewValue, $modelValue, scope) {
            Api.variety(scope.model.type)
             .then(function(ok) { scope.to.options=ok;}, function(error){});
         }
       },
    }
  ];

});
</code>```

答:
You aren't returning anything.  </p>

```<code>expressionProperties: {
         'templateOptions.options': function($viewValue, $modelValue, scope) {
           $scope.to.options=[]; //reset to avoid having issues when selecting
           return Api.variety(scope.model.type)
             .then(function(ok) {
                  scope.to.options=ok;
                  return $scope.to.options;
             }, function(error){});

         }
       },
</code>```

Body:
I have two methods to get data from remote service.

Api.types() returns me [{name:'vegetable', id:0}, {name:'fruit', id:1}]. Based on that returns and if i change selected type it should update variety field data with data about fruits/vegetables. What's wrong at that code?

controller('MainCtrl', ['$log', 'Api', function($log, Api) {
  this.formFields = [
    {
       key: "type",
       type: "select",
       templateOptions: {
         label: "Types",
         valueProp: "id",
         labelProp: "name",
         options:[],
       },
       expressionProperties: {
         'templateOptions.options': function($viewValue, $modelValue, scope) {
            Api.types()
              .then(function(ok) { scope.to.options=ok;}, function(error){});
         }
       },
    },
    {
       key: "variety",
       type: "select",
       templateOptions: {
         label: "variety",
         valueProp: "id",
         labelProp: "name",
         options:[],
       },
       expressionProperties: {
         'templateOptions.options': function($viewValue, $modelValue, scope) {
            Api.variety(scope.model.type)
             .then(function(ok) { scope.to.options=ok;}, function(error){});
         }
       },
    }
  ];

});

Body:
You aren't returning anything.

expressionProperties: {
         'templateOptions.options': function($viewValue, $modelValue, scope) {
           $scope.to.options=[]; //reset to avoid having issues when selecting
           return Api.variety(scope.model.type)
             .then(function(ok) {
                  scope.to.options=ok;
                  return $scope.to.options;
             }, function(error){});

         }
       },


问:
asp.net VB.net file download handler not work properly
I have big file (about 2GB) to distribute to our customer, My website is written by asp.net vb, this is my file download handler:

```<code>Public Class FileHandler
    Implements IHttpHandler
    Public Sub ProcessRequest(ByVal httpcontext As HttpContext) Implements IHttpHandler.ProcessRequest
        If HttpContext.User.Identity.IsAuthenticated Then
            Dim FileName As String = HttpContext.Request.QueryString("File")
            HttpContext.Response.Buffer = False
            HttpContext.Response.Clear()
            HttpContext.Response.AddHeader("content-disposition", "attachment; filename=" & FileName)
            HttpContext.Response.ContentType = "application/exe"
            HttpContext.Response.TransmitFile("~/download/ExE/" & FileName)
            HttpContext.Response.Flush()
            HttpContext.Response.Close()
        End If
    End Sub
    Public ReadOnly Property IsReusable As Boolean Implements IHttpHandler.IsReusable
        Get
            Return False
        End Get
    End Property
End Class
</code>```

My problem is this handler sometimes could not work properly.
Most customer could download it by this handler, but some customer click the download link, it will endless waiting for server's response, after long time waiting, it shows the error page says the IE cannot display the webpage. some customer try to download the file from IE8, it will show the error page directly.
I am really appreciate any one can help with this issue. Thank you!

答:
I use a button or just a plain link to the file itself, I've never had to use a handler to download files.

For example, on the aspx I have a button and in the code behind I send the user to the file using the response object:

```<code>Protected Sub Button_DownloadFile_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button_DownloadFile.Click

    Response.AddHeader("Content-Disposition", "attachment; filename=TheFileName.ext")
    Response.WriteFile("~/App_Data/TheFileName.ext")

END SUB
</code>```

Body:
I have big file (about 2GB) to distribute to our customer, My website is written by asp.net vb, this is my file download handler:

Public Class FileHandler
    Implements IHttpHandler
    Public Sub ProcessRequest(ByVal httpcontext As HttpContext) Implements IHttpHandler.ProcessRequest
        If HttpContext.User.Identity.IsAuthenticated Then
            Dim FileName As String = HttpContext.Request.QueryString("File")
            HttpContext.Response.Buffer = False
            HttpContext.Response.Clear()
            HttpContext.Response.AddHeader("content-disposition", "attachment; filename=" & FileName)
            HttpContext.Response.ContentType = "application/exe"
            HttpContext.Response.TransmitFile("~/download/ExE/" & FileName)
            HttpContext.Response.Flush()
            HttpContext.Response.Close()
        End If
    End Sub
    Public ReadOnly Property IsReusable As Boolean Implements IHttpHandler.IsReusable
        Get
            Return False
        End Get
    End Property
End Class

My problem is this handler sometimes could not work properly.
Most customer could download it by this handler, but some customer click the download link, it will endless waiting for server's response, after long time waiting, it shows the error page says the IE cannot display the webpage. some customer try to download the file from IE8, it will show the error page directly.
I am really appreciate any one can help with this issue. Thank you!

Body:
I use a button or just a plain link to the file itself, I've never had to use a handler to download files.

For example, on the aspx I have a button and in the code behind I send the user to the file using the response object:

Protected Sub Button_DownloadFile_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button_DownloadFile.Click

    Response.AddHeader("Content-Disposition", "attachment; filename=TheFileName.ext")
    Response.WriteFile("~/App_Data/TheFileName.ext")

END SUB


问:
WPF - DataBind TextBlock.Text to Integer
I know this a really simple question..

I have a Textblock who's text property I want to be databound to an integer I have in the codebehind.. right now I'm doing this

```<code><TextBlock Name="TextBlockCompeltedSongsNumber" Text="{Binding}"></TextBlock>
</code>```

Then in c#..

```<code>            this.TextBlockCompeltedSongsNumber.DataContext = CompeltedTracks;
</code>```

Where CompletedTracks is a public int

What am I missing?

答:
Maybe you set DataContext too late. After it's rendered.

Wouldn't it better to bind directly to a property and raise PropertyChanged event?

```<code><TextBlock Text="{Binding CompletedTracks}"></TextBlock>
</code>```

and set DataContext of the TextBlock's parent to CompletedTracks's owner.

Body:
I know this a really simple question..

I have a Textblock who's text property I want to be databound to an integer I have in the codebehind.. right now I'm doing this

<TextBlock Name="TextBlockCompeltedSongsNumber" Text="{Binding}"></TextBlock>

Then in c#..

            this.TextBlockCompeltedSongsNumber.DataContext = CompeltedTracks;

Where CompletedTracks is a public int

What am I missing?

Body:
Maybe you set DataContext too late. After it's rendered.

Wouldn't it better to bind directly to a property and raise PropertyChanged event?

<TextBlock Text="{Binding CompletedTracks}"></TextBlock>

and set DataContext of the TextBlock's parent to CompletedTracks's owner.


问:
Calling a ptototype function
I am working with a piece of code that I found in another project on the net and I am trying to adapt it to my needs. I wasn't able to find out how this function was originally being called so I am hoping to find some assistance here.

```<code>var gatewayIP = '192.168.10.21',
sock = new WebSocket('ws://' + gatewayIP + ':8000');
sock.binaryType = "arraybuffer";

// Constructor, expects a socket/stream to write device commands
function HTDLync(sock, log) {
    this.sock = sock;
    this.log = log;
}

// Change zone power state ('On', 'Off', '1', or '0')
HTDLync.prototype.setPower = function(zone, power) {

    powerStr = power.toString().toLowerCase();

    var packet = Buffer.from([0x02, 0x00, 0x00, 0x04, 0x58]);
    packet.writeUInt8(this.cleanZone(zone), 2);

    if (powerStr == 'on' || powerStr == '1'){
        packet.writeUInt8(0x57, 4);
    }
    else if (powerStr == 'off' || powerStr == '0'){
        packet.writeUInt8(0x58, 4);
    }
    else {
        this.log.warn('Unknown setPower argument:', powerStr);
        return;
    }

    var dataOut = addChecksum(packet);
    this.log.debug('Sending setPower command:', dataOut.toString('hex'));
    msg.payload = dataOut;
};
</code>```

I have tried calling the following:

```<code>setPower('1', 'On');
this.setPower('1', 'On');
HTDLync.setPower('1', 'On');
</code>```

All of the above hit the console with function not defined errors.

I feel like I am either missing some other code or calling this function incorrectly.

How would I go about calling this setPower prototype function ?

答:
To call a (prototype) method, you need to make an instance of the class first by calling the constructor:

```<code>var obj = new HTDLync(new WebSocket('ws://192.168.10.21:8000'), console);
</code>```

Only then you can invoke the method on that object:

```<code>obj.setPower('1', 'On');
</code>```

Have a look at MDN's introduction to OOP in JS and usage of prototypes.

Title: Calling a ptototype function

Body:
I am working with a piece of code that I found in another project on the net and I am trying to adapt it to my needs. I wasn't able to find out how this function was originally being called so I am hoping to find some assistance here.

var gatewayIP = '192.168.10.21',
sock = new WebSocket('ws://' + gatewayIP + ':8000');
sock.binaryType = "arraybuffer";

// Constructor, expects a socket/stream to write device commands
function HTDLync(sock, log) {
    this.sock = sock;
    this.log = log;
}

// Change zone power state ('On', 'Off', '1', or '0')
HTDLync.prototype.setPower = function(zone, power) {

    powerStr = power.toString().toLowerCase();

    var packet = Buffer.from([0x02, 0x00, 0x00, 0x04, 0x58]);
    packet.writeUInt8(this.cleanZone(zone), 2);

    if (powerStr == 'on' || powerStr == '1'){
        packet.writeUInt8(0x57, 4);
    }
    else if (powerStr == 'off' || powerStr == '0'){
        packet.writeUInt8(0x58, 4);
    }
    else {
        this.log.warn('Unknown setPower argument:', powerStr);
        return;
    }

    var dataOut = addChecksum(packet);
    this.log.debug('Sending setPower command:', dataOut.toString('hex'));
    msg.payload = dataOut;
};

I have tried calling the following:

setPower('1', 'On');
this.setPower('1', 'On');
HTDLync.setPower('1', 'On');

All of the above hit the console with function not defined errors.

I feel like I am either missing some other code or calling this function incorrectly.

How would I go about calling this setPower prototype function ?

Body:
To call a (prototype) method, you need to make an instance of the class first by calling the constructor:

var obj = new HTDLync(new WebSocket('ws://192.168.10.21:8000'), console);

Only then you can invoke the method on that object:

obj.setPower('1', 'On');

Have a look at MDN's introduction to OOP in JS and usage of prototypes.


问:
javascript - how to use a text box input in a for loop
I am trying to write a solution for a javascript application that takes a number input & depending on that number is how many times it runs a specific function. I am using a text box for input field & a button to process the number of times the user wants the function to run. It is for a game of dice game. User enters how many games he wants to play and clicks button to run the roll_dice function that many times. I'm not sure if I am going the right way with using a for loop to take users numeric input and loop through its value until it ends for example</p>

```<code>function games() {
        var num = document.getElementById("inp").vale;
        var i;

        for (i = 0; i < num; i++) {
            roll_dice();
        }
}
</code>```

答:
The value you get from input box is string you need to convert it into int . If you are using int in loop .</p>

```<code>var num = parseInt(document.getElementById("inp").value);
</code>```

Body:
I am trying to write a solution for a javascript application that takes a number input & depending on that number is how many times it runs a specific function. I am using a text box for input field & a button to process the number of times the user wants the function to run. It is for a game of dice game. User enters how many games he wants to play and clicks button to run the roll_dice function that many times. I'm not sure if I am going the right way with using a for loop to take users numeric input and loop through its value until it ends for example

function games() {
        var num = document.getElementById("inp").vale;
        var i;

        for (i = 0; i < num; i++) {
            roll_dice();
        }
}

Body:
The value you get from input box is string you need to convert it into int . If you are using int in loop .

var num = parseInt(document.getElementById("inp").value);


问:
Issue with return pointer
I am trying to duplicate a copy of the array but the new copy needs to be in reverse order. My  problem is my reverse function, I commented what the error is stating, what I don't understand is why it's stating that? If copy is a pointer variable? I'm still struggling with pointers, and I really just want some clarification on what I am doing wrong. I didn't make a reverse pointer variable yet, I was planning to do that once I figure out why I'm given this error.

Here's the function

```<code>int* reverse(int elements, int size)
{
    int* copy = new int [size];
    int k =0;
    for(int j=size-1; j >=0;j--)
    {
        copy[k] = size[j]; // Error-> Subscripted value is not an array,pointer or vector
        k++;
    }
    return copy;
}
</code>```

Here's the entire code without the function,

```<code>#include <iostream>

int* allocation(int);
void output(int*, int);
int* reverse(int*, int);

int main()
{
    int size;
    std::cout << "Enter the size you want to allocate" << std::endl;
    std::cin >> size;
    int* array = allocation(size);
    std::cout << "Displays the elements of the array";
    output(array,size);
    return 0;
}

void output(int* array, int size)
{
    for(int k=0;k<size;k++)
    {
        std::cout << " " << array[k];
    }
}

int* allocation(int elements)
{
    int* ptr = new int[elements];
    std::cout << "Enter the elements for size of array." << std::endl;
    for(int i =0; i < elements; i++)
    {
        std:: cin >> ptr[i];
    }
    return ptr;
}
</code>```

答:
The problem with your reverse function is that you are not passing pointer to source array which has to be copied in the reverse order. Instead, you have passed two ints.

The error

Error-> Subscripted value is not an array,pointer or vector

happens when you try to use size as an array by adding a subscript to it size[j] which is obvious because size is an int type and not a pointer, array or a vector

I have changed the signature of your function from

```<code>int* reverse(int elements, int size)
</code>```

to

```<code>int* reverse(int *elements, int size)
</code>```

I have modified your function to look this way

```<code>int* reverse(int *elements, int size)
{
    int* copy = new int [size];
    for(int j=size-1, k=0; j >=0; j--, k++)
    {
        // copy from elements and not size, elements is the array containing
        // the values to be copied, size denotes the size of the array
        copy[k] = elements[j];
    }
    return copy;
}
</code>```

Side note:

I have also put k in the scope of the for loop.

You may want to use std::vector or std::array instead of using raw arrays

I see that you have used the correct signature while defining the function int* reverse(int*, int);

Title: Issue with return pointer

Body:
I am trying to duplicate a copy of the array but the new copy needs to be in reverse order. My  problem is my reverse function, I commented what the error is stating, what I don't understand is why it's stating that? If copy is a pointer variable? I'm still struggling with pointers, and I really just want some clarification on what I am doing wrong. I didn't make a reverse pointer variable yet, I was planning to do that once I figure out why I'm given this error.

Here's the function

int* reverse(int elements, int size)
{
    int* copy = new int [size];
    int k =0;
    for(int j=size-1; j >=0;j--)
    {
        copy[k] = size[j]; // Error-> Subscripted value is not an array,pointer or vector
        k++;
    }
    return copy;
}

Here's the entire code without the function,

#include <iostream>

int* allocation(int);
void output(int*, int);
int* reverse(int*, int);

int main()
{
    int size;
    std::cout << "Enter the size you want to allocate" << std::endl;
    std::cin >> size;
    int* array = allocation(size);
    std::cout << "Displays the elements of the array";
    output(array,size);
    return 0;
}

void output(int* array, int size)
{
    for(int k=0;k<size;k++)
    {
        std::cout << " " << array[k];
    }
}

int* allocation(int elements)
{
    int* ptr = new int[elements];
    std::cout << "Enter the elements for size of array." << std::endl;
    for(int i =0; i < elements; i++)
    {
        std:: cin >> ptr[i];
    }
    return ptr;
}

Body:
The problem with your reverse function is that you are not passing pointer to source array which has to be copied in the reverse order. Instead, you have passed two ints.

The error

Error-> Subscripted value is not an array,pointer or vector

happens when you try to use size as an array by adding a subscript to it size[j] which is obvious because size is an int type and not a pointer, array or a vector

I have changed the signature of your function from

int* reverse(int elements, int size)

to

int* reverse(int *elements, int size)

I have modified your function to look this way

int* reverse(int *elements, int size)
{
    int* copy = new int [size];
    for(int j=size-1, k=0; j >=0; j--, k++)
    {
        // copy from elements and not size, elements is the array containing
        // the values to be copied, size denotes the size of the array
        copy[k] = elements[j];
    }
    return copy;
}

Side note:

I have also put k in the scope of the for loop.

You may want to use std::vector or std::array instead of using raw arrays

I see that you have used the correct signature while defining the function int* reverse(int*, int);


问:
Are global objects guaranteed to be destructed after all thread-local-storage objects are destructed?
```<code>#include <thread>

using namespace std;

struct A
{
    A() {}
    ~A() {}
};

A g_a;

int main()
{
    thread([]()
    {
         thread_local A tl_a;
         exit(0);
    }).detach();
}
</code>```

Does the C++ standard guarantee g_a will be destructed after tl_a be destructed?

答:
Yes it does.

Section [basic.start.term] in the language spec says

Destructors (12.4) for initialized objects (that is, objects whose lifetime (3.8) has begun) with static storage
  duration are called as a result of returning from main and as a result of calling std::exit (18.5). Destructors
  for initialized objects with thread storage duration within a given thread are called as a result of returning
  from the initial function of that thread and as a result of that thread calling std::exit. The completions
  of the destructors for all initialized objects with thread storage duration within that thread are sequenced
  before the initiation of the destructors of any object with static storage duration.

So the thread local variables will be destroyed before the static (global) ones.

Body:
#include <thread>

using namespace std;

struct A
{
    A() {}
    ~A() {}
};

A g_a;

int main()
{
    thread([]()
    {
         thread_local A tl_a;
         exit(0);
    }).detach();
}

Does the C++ standard guarantee g_a will be destructed after tl_a be destructed?


问:
Seeing the active css element outline style in chrome developer tooling?
In chrome the below button will retain it's outline after it has been clicked.  If I looked at the buttons css settings after selecting the :active checkbox in chrome's developer tools I still can't see what the CSS values are for the outline.  It appears to be about 1px in width and grey visually, but I don't see these values.  Is there a way to see them?

  <button style="background-color: aquamarine; margin-top: 50px; margin-left: 50px;">HI</button>
```
</div>
</div>
</p>

<p>In other words google chrome does add this style (As indicated by one of the answer below):</p>

``` :focus {
     outline: -webkit-focus-ring-color auto 5px;
 }
```

However when I click the focus checkbox in order to be able to see all the CSS that is triggered by focus, I don't see that style in the developer tooling pane ... Is it a google developer tooling bug or do other people see it?

答:
Can you post a link to the website?

In the meantime, I would suggest looking the "Computed" styles tab

Side note about why this might be happening--I've noticed sometimes I haven't been able to see the :active styles when it's JavaScript controlling the button's state

Edit: Hi Ole, I can see your demo, thanks.

Based on Obsidian Age's helpful reply, I ran this code snippet and it got rid of the borders on click. That's the behavior you want, right?

  <button style="background-color: aquamarine; margin-top: 50px; margin-left: 50px;">HI</button>
```

By looking in the "Computed" tab (next to "Styles" when you're inspecting an element in Chrome), I saw that there was a gray, 2px-wide border-top, -right, -bottom, -left for the button. For some reason it was enough just to set the border-top property to none and the border-width to 0. I don't know why but I tried a bunch of other combinations that didn't work--this did it with the least amount of CSS.

Body:
In chrome the below button will retain it's outline after it has been clicked.  If I looked at the buttons css settings after selecting the :active checkbox in chrome's developer tools I still can't see what the CSS values are for the outline.  It appears to be about 1px in width and grey visually, but I don't see these values.  Is there a way to see them?

  <button style="background-color: aquamarine; margin-top: 50px; margin-left: 50px;">HI</button>

In other words google chrome does add this style (As indicated by one of the answer below):

 :focus {
     outline: -webkit-focus-ring-color auto 5px;
 }

However when I click the focus checkbox in order to be able to see all the CSS that is triggered by focus, I don't see that style in the developer tooling pane ... Is it a google developer tooling bug or do other people see it?

Body:
Can you post a link to the website?

In the meantime, I would suggest looking the "Computed" styles tab

Side note about why this might be happening--I've noticed sometimes I haven't been able to see the :active styles when it's JavaScript controlling the button's state

Edit: Hi Ole, I can see your demo, thanks.

Based on Obsidian Age's helpful reply, I ran this code snippet and it got rid of the borders on click. That's the behavior you want, right?

<body>
<style>
button:focus {
    outline: none; // Remove the outline
 border-top: none;
    border-width: 0;
}
button.active: {
    border-style: none; //Remove the border
}
</style>
  <button style="background-color: aquamarine; margin-top: 50px; margin-left: 50px;">HI</button>
</body>

By looking in the "Computed" tab (next to "Styles" when you're inspecting an element in Chrome), I saw that there was a gray, 2px-wide border-top, -right, -bottom, -left for the button. For some reason it was enough just to set the border-top property to none and the border-width to 0. I don't know why but I tried a bunch of other combinations that didn't work--this did it with the least amount of CSS.


问:
Text links wont style and are not always clickable
I've got a mess with two links at the top of this page ("WORK" and "ABOUT").

http://danux.me/

I'm not sure why I can't get them to style. I only seem to be able to apply a float and nothing else in the CSS does anything.

```<code>#nav_container {

float: right;
position: relative;
padding-right: 110px;
padding-top: 60px;
}

#nav_container li {
float: left;
display: inline;
color: #fff;
list-style: none;
text-decoration: none;
cursor: pointer;
}
</code>```

As far as the clickable part, if I expand my browser so they are off to the right of the tiled images they are clickable.

I have the tiled images set to relative for that overlap effect, and the blue bar is set to absolute.

I have the z-index higher for the tiled images and tried applying a higher z-index to those nav links thinking I could get them to pop up on top and be clickable, but no dice.

Any guesses?

答:
The problem is that your #home_console_wrapper element actually overlaps your #color_beam, and has a large padding-top on it to hide this behaviour. It also has a higher z-index, meaning that it will make your links unclickable.

To rectify this, you need to remove position: absolute from #color_beam, and padding-top: 190px from #home_console_wrapper.

This will cause your links to become clickable, without changing the display at all.

If you would like to still have the slight 'overlap' effect, simply set a negative margin-top on #home_console_wrapper:

```<code>#home_console_wrapper {
  margin-top: -35px;
}
</code>```

Hope this helps! :)

Body:
I've got a mess with two links at the top of this page ("WORK" and "ABOUT").

http://danux.me/

I'm not sure why I can't get them to style. I only seem to be able to apply a float and nothing else in the CSS does anything.

#nav_container {

float: right;
position: relative;
padding-right: 110px;
padding-top: 60px;
}

#nav_container li {
float: left;
display: inline;
color: #fff;
list-style: none;
text-decoration: none;
cursor: pointer;
}

As far as the clickable part, if I expand my browser so they are off to the right of the tiled images they are clickable.

I have the tiled images set to relative for that overlap effect, and the blue bar is set to absolute.

I have the z-index higher for the tiled images and tried applying a higher z-index to those nav links thinking I could get them to pop up on top and be clickable, but no dice.

Any guesses?

Body:
The problem is that your #home_console_wrapper element actually overlaps your #color_beam, and has a large padding-top on it to hide this behaviour. It also has a higher z-index, meaning that it will make your links unclickable.

To rectify this, you need to remove position: absolute from #color_beam, and padding-top: 190px from #home_console_wrapper.

This will cause your links to become clickable, without changing the display at all.

If you would like to still have the slight 'overlap' effect, simply set a negative margin-top on #home_console_wrapper:

#home_console_wrapper {
  margin-top: -35px;
}

Hope this helps! :)


问:
Small native cross-platform GUI framework for C++
I wrote a small program with Boost in c++. It works fine and so I want to give it a graphical interface so that it is easier to use.

In order to do so, I am looking for small cross-platform framework which provides native look and feel. Windows and Linux support would be enough, currently i do not need os x...

I used wxWidgets for some other project, but it was a pain to set everything up and ship this big library with the software.

But I was really amazed by the use of real native controls.
In order to keep the program small I also tried fltk, but it has an awful look.

I just need an simple framework without network support or other gimmicks.

So my question: Is there any framework out there which fits all the requirements? Or if not, which frameworks fits at least some of these needs?

Thanks in advance!

答: don't forget to check juce as well</p>

Body: don't forget to check juce as well


答:
You must new HTDLync first to use!

```<code>var htdLync = new HTDLync();
htdLync.setPower('1', 'On');
</code>```

Title: Calling a ptototype function

Body:
You must new HTDLync first to use!

var htdLync = new HTDLync();
htdLync.setPower('1', 'On');


问:
Jython binary error on execution
As soon as I execute jython binary, I get the following error:

```<code>Traceback (most recent call last):
  File "/opt/jython2.7.0/bin/jython", line 444, in <module>
    main(sys.argv)
  File "/opt/jython2.7.0/bin/jython", line 431, in main
    os.execvp(command[0], command[1:])
  File "/usr/lib/python2.7/os.py", line 346, in execvp
    _execvpe(file, args)
  File "/usr/lib/python2.7/os.py", line 370, in _execvpe
    func(file, *argrest)
OSError: [Errno 2] No such file or directory
</code>```

It is not clear for me which file is missing here, but what is stranger is that it can be executed from Eclipse with no problems.

Any idea? I'm a bit lost here

答:
Check your JAVA_HOME environment variable. Mine was pointing to a non-existing Java installation.

Broken:

```<code>$ export JAVA_HOME=bad path
$ jython2.7.0/bin/jython
Traceback (most recent call last):
  File "jython2.7.0/bin/jython", line 444, in <module>
    main(sys.argv)
  File "jython2.7.0/bin/jython", line 431, in main
    os.execvp(command[0], command[1:])
  File "/usr/lib/python2.7/os.py", line 346, in execvp
    _execvpe(file, args)
  File "/usr/lib/python2.7/os.py", line 370, in _execvpe
    func(file, *argrest)
OSError: [Errno 2] No such file or directory
</code>```

Fixed:

```<code>$ export JAVA_HOME=$HOME/java/jdk1.8.0_121
$ jython2.7.0/bin/jython
Jython 2.7.0 (default:9987c746f838, Apr 29 2015, 02:25:11)
[Java HotSpot(TM) 64-Bit Server VM (Oracle Corporation)] on java1.8.0_121
Type "help", "copyright", "credits" or "license" for more information.
</code>```

Title: Jython binary error on execution

Body:
As soon as I execute jython binary, I get the following error:

Traceback (most recent call last):
  File "/opt/jython2.7.0/bin/jython", line 444, in <module>
    main(sys.argv)
  File "/opt/jython2.7.0/bin/jython", line 431, in main
    os.execvp(command[0], command[1:])
  File "/usr/lib/python2.7/os.py", line 346, in execvp
    _execvpe(file, args)
  File "/usr/lib/python2.7/os.py", line 370, in _execvpe
    func(file, *argrest)
OSError: [Errno 2] No such file or directory

It is not clear for me which file is missing here, but what is stranger is that it can be executed from Eclipse with no problems.

Any idea? I'm a bit lost here

Body:
Check your JAVA_HOME environment variable. Mine was pointing to a non-existing Java installation.

Broken:

$ export JAVA_HOME=bad path
$ jython2.7.0/bin/jython
Traceback (most recent call last):
  File "jython2.7.0/bin/jython", line 444, in <module>
    main(sys.argv)
  File "jython2.7.0/bin/jython", line 431, in main
    os.execvp(command[0], command[1:])
  File "/usr/lib/python2.7/os.py", line 346, in execvp
    _execvpe(file, args)
  File "/usr/lib/python2.7/os.py", line 370, in _execvpe
    func(file, *argrest)
OSError: [Errno 2] No such file or directory

Fixed:

$ export JAVA_HOME=$HOME/java/jdk1.8.0_121
$ jython2.7.0/bin/jython
Jython 2.7.0 (default:9987c746f838, Apr 29 2015, 02:25:11)
[Java HotSpot(TM) 64-Bit Server VM (Oracle Corporation)] on java1.8.0_121
Type "help", "copyright", "credits" or "license" for more information.


问:
Javascript: silently fail on undefined assignment
Suppose I am trying to assign a variable in a way that causes an exception

I am going to access a non-existent key of a dictionary:

```<code>myObject.property = dictionary['NO_KEY'][0];
</code>```

Now, because 'NO_KEY' does not exist on dictionary, my program will catch an exception when trying to subscript 0 of undefined - and crash. Is it possible to execute this line above as a no-op so that my script can continue running? I know there is try-catch syntex, but is there a more elegant syntax with ESMA6?

答:
You can use an if condition and statement, Object.hasOwnProperty() or as suggested by @Ryan in operator

```<code>if (dictionary.hasOwnProperty("NO_KEY")) {
  myObject.property = dictionary["NO_KEY"][0];
}
</code>```

```<code>if ("NO_KEY" in dictionary) {
  myObject.property = dictionary["NO_KEY"][0];
}
</code>```

Body:
Suppose I am trying to assign a variable in a way that causes an exception

I am going to access a non-existent key of a dictionary:

myObject.property = dictionary['NO_KEY'][0];

Now, because 'NO_KEY' does not exist on dictionary, my program will catch an exception when trying to subscript 0 of undefined - and crash. Is it possible to execute this line above as a no-op so that my script can continue running? I know there is try-catch syntex, but is there a more elegant syntax with ESMA6?

Body:
You can use an if condition and statement, Object.hasOwnProperty() or as suggested by @Ryan in operator

if (dictionary.hasOwnProperty("NO_KEY")) {
  myObject.property = dictionary["NO_KEY"][0];
}

if ("NO_KEY" in dictionary) {
  myObject.property = dictionary["NO_KEY"][0];
}


问:
modified coin toss program won't run
So I have to complete an assignment in which a coin toss is simulated and the number of flips, tails, and heads must be counted.

My first problem was that I could not get the number of heads or tails to display, fixed that, but then it was doubling(ex: I request 50 flips and the total amount of heads and tails would equate to 100), figured out that I had accidentally made it so it was counting up twice instead of once per flip, when I changed that the program just doesn't seem to run.

When I input the amount of times I would like the coin to flip and hit enter it just does nothing and goes to the next line on my terminal. I have removed all white space off my program in case of infinite looping other than that I cannot figure out what is causing this.

Thank you for any help.

答:
You need to remove below line, otherwise it will keep on looping

```<code>count +=1
</code>```

Because, at the same time you are incrementing head or tail as well.

Assuming, you provided input 1 then, it will check

```<code>head+tail < count # 0 < 1 , which is true
</code>```

then assuming coin=1 then,

```<code>count+=1
head= head+1
</code>```

For the next loop

```<code>head+tail < count # 1 < 2 , which is true
</code>```

Title: modified coin toss program won't run

Body:
You need to remove below line, otherwise it will keep on looping

count +=1

Because, at the same time you are incrementing head or tail as well.

Assuming, you provided input 1 then, it will check

head+tail < count # 0 < 1 , which is true

then assuming coin=1 then,

count+=1
head= head+1

For the next loop

head+tail < count # 1 < 2 , which is true


问:
Ruby post title to slug
How should I convert a post title to a slug in Ruby?

The title can have any characters, but I only want the slug to allow [a-z0-9-_] (Should it allow any other characters?).

So basically:

downcase all letters

convert spaces to hyphens

delete extraneous characters

答:
```<code>slug = title.downcase.strip.gsub(' ', '-').gsub(/[^\w-]/, '')
</code>```

downcase makes it lowercase. The strip makes sure there is no leading or trailing whitespace. The first gsub replaces spaces with hyphens. The second gsub removes all non-alpha non-dash non-underscore characters (note that this set is very close to \W but includes the dash as well, which is why it's spelled out here).

Title: Ruby post title to slug

Body:
slug = title.downcase.strip.gsub(' ', '-').gsub(/[^\w-]/, '')

downcase makes it lowercase. The strip makes sure there is no leading or trailing whitespace. The first gsub replaces spaces with hyphens. The second gsub removes all non-alpha non-dash non-underscore characters (note that this set is very close to \W but includes the dash as well, which is why it's spelled out here).


问:
Java housework ,a simple logic
```<code>package Easy;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

public class Demo1 {
    public static void main(String[] args) {
        int[] nums = {2, 7, 11, 15};
        int t = 26;
        int[] arr = twoSum(nums, t);
    System.out.println(Arrays.toString(arr));//printout is supposed to be [2,3],however it's [3, 4],what's wrong?
    }
    public static int[] twoSum(int[] numbers, int target) {
        int[] result = new int[2];
        Map<Integer, Integer> map = new HashMap<Integer, Integer>();
        for (int i = 0; i < numbers.length; i++) {
            if (map.containsKey(target - numbers[i])) {
                result[1] = i + 1;
                result[0] = map.get(target - numbers[i]);
                return result;
            }
            map.put(numbers[i], i + 1);
        }
        return result;
    }
}
</code>```

printout is supposed to be [2,3],however it's [3, 4],what's wrong?thank you for your help.

description:
    Given an array of integers, return indices of the two numbers such that they add up to a specific target.

```<code>You may assume that each input would have exactly one solution, and you may not use the same element twice.

Example:
Given nums = [2, 7, 11, 15], target = 9,

Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].
</code>```

答:
your way is complicated you can solve it in more simple approach:

```<code>  int[] nums = {2, 7, 11, 15};
  ArrayList<Integer> index = new ArrayList<Integer>();
  int t = 26;
  for(int i=0 ; i < nums.length-1 ; i++){
      for(int j=i+1 ; j < nums.length ; j++){
          if(nums[i] + nums[j] == t){
               index.add(i);
               index.add(j);
          }
      }
  }
    System.out.println(index);
</code>```

output:

```<code>[2, 3]
</code>```

check it: https://ideone.com/jM1wJQ

Title: Java housework ,a simple logic

Body:
package Easy;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

public class Demo1 {
    public static void main(String[] args) {
        int[] nums = {2, 7, 11, 15};
        int t = 26;
        int[] arr = twoSum(nums, t);
    System.out.println(Arrays.toString(arr));//printout is supposed to be [2,3],however it's [3, 4],what's wrong?
    }
    public static int[] twoSum(int[] numbers, int target) {
        int[] result = new int[2];
        Map<Integer, Integer> map = new HashMap<Integer, Integer>();
        for (int i = 0; i < numbers.length; i++) {
            if (map.containsKey(target - numbers[i])) {
                result[1] = i + 1;
                result[0] = map.get(target - numbers[i]);
                return result;
            }
            map.put(numbers[i], i + 1);
        }
        return result;
    }
}

printout is supposed to be [2,3],however it's [3, 4],what's wrong?thank you for your help.

description:
    Given an array of integers, return indices of the two numbers such that they add up to a specific target.

You may assume that each input would have exactly one solution, and you may not use the same element twice.

Example:
Given nums = [2, 7, 11, 15], target = 9,

Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].

Body:
your way is complicated you can solve it in more simple approach:

  int[] nums = {2, 7, 11, 15};
  ArrayList<Integer> index = new ArrayList<Integer>();
  int t = 26;
  for(int i=0 ; i < nums.length-1 ; i++){
      for(int j=i+1 ; j < nums.length ; j++){
          if(nums[i] + nums[j] == t){
               index.add(i);
               index.add(j);
          }
      }
  }
    System.out.println(index);

output:

[2, 3]

check it: https://ideone.com/jM1wJQ


问:
Convert UTC time to local time zone
I have to convert UTC time into user local time zone. Currently, I have the two parameters one is time in long format and another is time zone name in string format like "(UTC-05:00) Eastern Time (US and Canada), (UTC-06:00) Central Time (US and Canada)" etc.

So now using these two parameters I have to get date time in string format. I am facing the issue while I am trying to convert the date into a string because the SimpleDateFormat.format(...) will convert the date using its default time zone.

Below are the code portion

```<code>public static void main(String[] args)
{
long time = 1490112300000L;
System.out.println("UTC Time "+ convertLongToStringUTC(time));

String EST = "(UTC-05:00) Eastern Time (US and Canada)";
TimeZone  timeZone1 = TimeZone.getTimeZone(EST);
System.out.println("EST "+ convertTimeZone(time, timeZone1));

String CST = "(UTC-06:00) Central Time (US and Canada)";
TimeZone timeZone2 = TimeZone.getTimeZone(CST);
System.out.println("CST "+ convertTimeZone(time, timeZone2));

String IST =  "IST";
TimeZone timeZone = TimeZone.getTimeZone(IST);
System.out.println("IST "+ convertTimeZone(time, timeZone));
</code>```

}

```<code>public String convertTimeZone(long time, TimeZone timeZone)
{
Date date = new Date(time);
DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
format.setTimeZone(timeZone);
return format.format(date);
}

public String convertLongToStringUTC(long time)
{
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
String utcTime = sdf.format(new Date(time));
return utcTime;
}
</code>```

Also let me know if we can achieve this using offset ?

答:
tl;dr

```<code>Instant.ofEpochMilli( 1_490_112_300_000L )
       .atOffset( ZoneOffset.of( "-05:00" ) )

Instant.ofEpochMilli( 1_490_112_300_000L )
       .atZone( ZoneId.of( "America/New_York" ) )
</code>```

Details

The Answer by Dennis is close. I will provide further information.

Your Question is not exactly clear about the inputs. I will assume your long integer number represents a moment in UTC.

An offset-from-UTC is an number of hours and minutes and seconds before or after UTC. In java.time, we represent that with a ZoneOffset.

While ZoneId technically works (as seen in code by Dennis), that is misleading as a zone is much more than an offset. A zone is a region’s history of various offsets that were in effect at different periods of history. A zone also includes any planned future changes such as DST cutovers coming in the next months.

```<code>ZoneOffset offset = ZoneOffset.of( 5 , 30 ); // Five-and-a-half hours ahead of UTC.

ZoneOffset offset = ZoneOffset.of( "+05:30" );
</code>```

Tip: Always include the padding zero on the hours. While not always required in various protocols such as ISO 8601, I have seen software systems burp when encountering single-digit hours like +5:00.

If you know the intended time zone for certain, use it. A zone is always better than a mere offset as it brings all that historical information of other offsets for the past, present, and future.

Specify a proper time zone name in the format of continent/region, such as America/Montreal, Africa/Casablanca, or Pacific/Auckland. Never use the 3-4 letter abbreviation such as EST or IST as they are not true time zones, not standardized, and not even unique(!).

```<code>ZoneId z = ZoneId.of( "Asia/Kolkata" );
</code>```

I am guessing your number is a number of milliseconds since the epoch of 1970-01-01T00:00:00Z.

```<code>Instant instant = Instant.ofEpochMilli( 1_490_112_300_000L );
</code>```

The Instant class represents a moment on the timeline in UTC with a resolution of nanoseconds (up to nine (9) digits of a decimal fraction).

You can adjust into a time zone.

```<code>ZonedDateTime zdt = instant.atZone( z );
</code>```

These issues have been covered many times in Stack Overflow. Hence the down-votes you are collecting (I am guessing). Please search Stack Overflow thoroughly before posting.

About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

Where to obtain the java.time classes?

Java SE 8 and SE 9 and later

Built-in.

Part of the standard Java API with a bundled implementation.

Java 9 adds some minor features and fixes.

Java SE 6 and SE 7

Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.

Android

The ThreeTenABP project adapts ThreeTen-Backport (mentioned above) for Android specifically.

See How to use ThreeTenABP….

The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

Title: Convert UTC time to local time zone

Body:
I have to convert UTC time into user local time zone. Currently, I have the two parameters one is time in long format and another is time zone name in string format like "(UTC-05:00) Eastern Time (US and Canada), (UTC-06:00) Central Time (US and Canada)" etc.

So now using these two parameters I have to get date time in string format. I am facing the issue while I am trying to convert the date into a string because the SimpleDateFormat.format(...) will convert the date using its default time zone.

Below are the code portion

public static void main(String[] args)
{
long time = 1490112300000L;
System.out.println("UTC Time "+ convertLongToStringUTC(time));

String EST = "(UTC-05:00) Eastern Time (US and Canada)";
TimeZone  timeZone1 = TimeZone.getTimeZone(EST);
System.out.println("EST "+ convertTimeZone(time, timeZone1));

String CST = "(UTC-06:00) Central Time (US and Canada)";
TimeZone timeZone2 = TimeZone.getTimeZone(CST);
System.out.println("CST "+ convertTimeZone(time, timeZone2));

String IST =  "IST";
TimeZone timeZone = TimeZone.getTimeZone(IST);
System.out.println("IST "+ convertTimeZone(time, timeZone));

}

public String convertTimeZone(long time, TimeZone timeZone)
{
Date date = new Date(time);
DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
format.setTimeZone(timeZone);
return format.format(date);
}

public String convertLongToStringUTC(long time)
{
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
String utcTime = sdf.format(new Date(time));
return utcTime;
}

Also let me know if we can achieve this using offset ?

Body:
tl;dr

Instant.ofEpochMilli( 1_490_112_300_000L )
       .atOffset( ZoneOffset.of( "-05:00" ) )

Instant.ofEpochMilli( 1_490_112_300_000L )
       .atZone( ZoneId.of( "America/New_York" ) )

Details

The Answer by Dennis is close. I will provide further information.

Your Question is not exactly clear about the inputs. I will assume your long integer number represents a moment in UTC.

An offset-from-UTC is an number of hours and minutes and seconds before or after UTC. In java.time, we represent that with a ZoneOffset.

While ZoneId technically works (as seen in code by Dennis), that is misleading as a zone is much more than an offset. A zone is a region’s history of various offsets that were in effect at different periods of history. A zone also includes any planned future changes such as DST cutovers coming in the next months.

ZoneOffset offset = ZoneOffset.of( 5 , 30 ); // Five-and-a-half hours ahead of UTC.

ZoneOffset offset = ZoneOffset.of( "+05:30" );

Tip: Always include the padding zero on the hours. While not always required in various protocols such as ISO 8601, I have seen software systems burp when encountering single-digit hours like +5:00.

If you know the intended time zone for certain, use it. A zone is always better than a mere offset as it brings all that historical information of other offsets for the past, present, and future.

Specify a proper time zone name in the format of continent/region, such as America/Montreal, Africa/Casablanca, or Pacific/Auckland. Never use the 3-4 letter abbreviation such as EST or IST as they are not true time zones, not standardized, and not even unique(!).

ZoneId z = ZoneId.of( "Asia/Kolkata" );

I am guessing your number is a number of milliseconds since the epoch of 1970-01-01T00:00:00Z.

Instant instant = Instant.ofEpochMilli( 1_490_112_300_000L );

The Instant class represents a moment on the timeline in UTC with a resolution of nanoseconds (up to nine (9) digits of a decimal fraction).

You can adjust into a time zone.

ZonedDateTime zdt = instant.atZone( z );

These issues have been covered many times in Stack Overflow. Hence the down-votes you are collecting (I am guessing). Please search Stack Overflow thoroughly before posting.

About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

Where to obtain the java.time classes?

Java SE 8 and SE 9 and later

Built-in.

Part of the standard Java API with a bundled implementation.

Java 9 adds some minor features and fixes.

Java SE 6 and SE 7

Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.

Android

The ThreeTenABP project adapts ThreeTen-Backport (mentioned above) for Android specifically.

See How to use ThreeTenABP….

The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.


问:
InfoPath 2003 and the xs:any type
I am implementing exception handling for our BizTalk services, and have run into a fairly major stumbling block.

In order to make the exception processing as generic as possible, and therefore to allow us to use it for any BizTalk application, our XML error schema includes an xs:any node, into which we can place a variety of data, depending on the actual exception.  The generated XML should then be presented to a user through an InfoPath 2003 form for manual intervention before being represented back to BizTalk.

The problem is that InfoPath 2003 doesn't like schemas with an xs:any node.  What we'd really like to do is the show the content of the exception report in a form with all relevant parameters mapped , and the entire content of the xs:any node in a text box, since users who are able to see these messages will be conversant with XML.  Unfortunately, I am unable to make InfoPath even load the schema at design time.

Does anyone have any recommendation for how to achieve what we need, please?

答:
Does your xs:any element have a minOccurs > 0?

http://msdn.microsoft.com/en-us/library/bb251017.aspx#UnsupportedConstructs

I've also read that due to the way that InfoPath works, it can not handly more than one schema for each namespace.  Hence, your xs:any (and the sequence that it defines) should have a unique namespace.

OwnerDisplayName: ZombieSheep

Title: InfoPath 2003 and the xs:any type

OwnerDisplayName: bryansh


问:
How to convert from IObservable to IObservable
I have a method which returns the interface IObservable (in silverlight) and wish to transforms this into another IObservable?

So what do I need to put in place of 'CONVERT_SOME_HOW'

```<code>public IObservable<Bar> Get(IEnumerable<object> @params)
{

    IObservable<Foo> fooObservable = _resources.Get(@params);
    IObservable<Bar> barObservable = CONVERT_SOME_HOW(fooObservable);

    return barObservable;
}
</code>```

答:
Just as you would in LINQ to Objects, use a projection:

```<code>var observableB = observableA.Select(a => new B(a));
</code>```

(Obviously, adjust according to your conversion.)

That's assuming I understand the question correctly. It's not quite clear what you mean by "when the subscription to the first observer is executed".

Title: How to convert from IObservable<A> to IObservable<B>

Body:
I have a method which returns the interface IObservable (in silverlight) and wish to transforms this into another IObservable?

So what do I need to put in place of 'CONVERT_SOME_HOW'

public IObservable<Bar> Get(IEnumerable<object> @params)
{

    IObservable<Foo> fooObservable = _resources.Get(@params);
    IObservable<Bar> barObservable = CONVERT_SOME_HOW(fooObservable);

    return barObservable;
}

Body:
Just as you would in LINQ to Objects, use a projection:

var observableB = observableA.Select(a => new B(a));

(Obviously, adjust according to your conversion.)

That's assuming I understand the question correctly. It's not quite clear what you mean by "when the subscription to the first observer is executed".