问:
method throws exception rather then returning Try in for comprehension
Please find below sample source code, that returns :-

website home page, when auth service is not available,

default home page, when auth service available, but page service is
  not available,

error page, when both services are not available,

user page, when all services are available

```<code>package tryeg

import scala.util._

/**
  * Created by mogli on 6/6/17.
  */
class TrySample(val service : TryService) {

  def homePageForUser(userId: String, secret: String): Try[Page] = {
    val tryhomepage = for {
      user     <- service.authenticate(userId, secret)
      homePage <- service.fetchHomePage(user)
    } yield homePage

    tryhomepage match {
      case Failure(e: ServiceUnavailableException) =>
        e.service match{
          case "AuthService" =>
            Try(WebsiteHomePage)
          case "PageService" =>
            Try(DefaultHomePage)
          case _ =>
            Try(ErrorPage)

        }

      case _ =>
        tryhomepage
    }
  }
}

case class User(id: Long)

case class Page(title: String, content: String)
object DefaultHomePage extends Page("Welcome!", "This is your amazing Homepage!")
object WebsiteHomePage extends Page("Welcome!", "This is your amazing website")
object ErrorPage extends Page("Sorry!", "Unhandled Erro")

sealed class MyException(msg: String) extends Exception(msg, null)
case class UnknownUserException(userId: Long) extends MyException(s"User with id [$userId] is unknown.")
case class WrongSecretException(userId: Long) extends MyException(s"User with id [$userId] provided the wrong secret.")
case class ServiceUnavailableException(service: String) extends MyException(s"The Service [$service] is currently unavailable")

trait TryService {
  def authenticate(userId: String, secret: String): Try[User]
  def fetchHomePage(user: User): Try[Page]
}
</code>```

Also, find below the sample unit test cases :-

```<code>package tryeg

import org.junit.runner.RunWith
import org.scalamock.scalatest.MockFactory
import org.scalatest.FlatSpecLike
import org.scalatest.junit.JUnitRunner

import scala.util.Try

/**
  * Created by mogli on 6/6/17.
  */
@RunWith(classOf[JUnitRunner])
class TrySampleTest extends FlatSpecLike with MockFactory{

  val user = User(123)
  val tryuser = Try(user)
  val userpage = Page("jbaba", "jbaba ka page")
  val tryuserpage = Try(userpage)

  "non happy path with authentication service not available" should "return website page" in {
    val service = stub[TryService]
    ( service.authenticate(_, _) ).when("123", "secret") throws ServiceUnavailableException("AuthService")
    val trySample = new TrySample(service)
    val page = trySample.homePageForUser("123", "secret")
    //page should be (Try(WebsiteHomePage))
    println("non happy path for authentication service down ")
  }

  "non happy path with page service not available" should "return default home page" in {
    val service = stub[TryService]
    ( service.authenticate(_, _) ).when("123", "secret") returns (tryuser)
    ( service.fetchHomePage(_) ).when(user) throws ServiceUnavailableException("PageService")
    val trySample = new TrySample(service)
    val page = trySample.homePageForUser("123", "secret")
    //page should be (Try(DefaultHomePage))
    println("non happy path for page service down ")
  }

}
</code>```

Now, the first test case is throwing below exception, but the expected result was Try(WebsiteHomePage)

```<code>tryeg.ServiceUnavailableException: The Service [AuthService] is currently unavailable

    at tryeg.TrySampleTest$$anonfun$1.apply$mcV$sp(TrySampleTest.scala:31)
    at tryeg.TrySampleTest$$anonfun$1.apply(TrySampleTest.scala:29)
    at tryeg.TrySampleTest$$anonfun$1.apply(TrySampleTest.scala:29)
</code>```

答: Your TryService stub is throwing an exception instead of returning a Failure.

Body:
Please find below sample source code, that returns :-

website home page, when auth service is not available,

default home page, when auth service available, but page service is
  not available,

error page, when both services are not available,

user page, when all services are available

package tryeg

import scala.util._

/**
  * Created by mogli on 6/6/17.
  */
class TrySample(val service : TryService) {

  def homePageForUser(userId: String, secret: String): Try[Page] = {
    val tryhomepage = for {
      user     <- service.authenticate(userId, secret)
      homePage <- service.fetchHomePage(user)
    } yield homePage

    tryhomepage match {
      case Failure(e: ServiceUnavailableException) =>
        e.service match{
          case "AuthService" =>
            Try(WebsiteHomePage)
          case "PageService" =>
            Try(DefaultHomePage)
          case _ =>
            Try(ErrorPage)

        }

      case _ =>
        tryhomepage
    }
  }
}

case class User(id: Long)

case class Page(title: String, content: String)
object DefaultHomePage extends Page("Welcome!", "This is your amazing Homepage!")
object WebsiteHomePage extends Page("Welcome!", "This is your amazing website")
object ErrorPage extends Page("Sorry!", "Unhandled Erro")

sealed class MyException(msg: String) extends Exception(msg, null)
case class UnknownUserException(userId: Long) extends MyException(s"User with id [$userId] is unknown.")
case class WrongSecretException(userId: Long) extends MyException(s"User with id [$userId] provided the wrong secret.")
case class ServiceUnavailableException(service: String) extends MyException(s"The Service [$service] is currently unavailable")

trait TryService {
  def authenticate(userId: String, secret: String): Try[User]
  def fetchHomePage(user: User): Try[Page]
}

Also, find below the sample unit test cases :-

package tryeg

import org.junit.runner.RunWith
import org.scalamock.scalatest.MockFactory
import org.scalatest.FlatSpecLike
import org.scalatest.junit.JUnitRunner

import scala.util.Try

/**
  * Created by mogli on 6/6/17.
  */
@RunWith(classOf[JUnitRunner])
class TrySampleTest extends FlatSpecLike with MockFactory{

  val user = User(123)
  val tryuser = Try(user)
  val userpage = Page("jbaba", "jbaba ka page")
  val tryuserpage = Try(userpage)

  "non happy path with authentication service not available" should "return website page" in {
    val service = stub[TryService]
    ( service.authenticate(_, _) ).when("123", "secret") throws ServiceUnavailableException("AuthService")
    val trySample = new TrySample(service)
    val page = trySample.homePageForUser("123", "secret")
    //page should be (Try(WebsiteHomePage))
    println("non happy path for authentication service down ")
  }

  "non happy path with page service not available" should "return default home page" in {
    val service = stub[TryService]
    ( service.authenticate(_, _) ).when("123", "secret") returns (tryuser)
    ( service.fetchHomePage(_) ).when(user) throws ServiceUnavailableException("PageService")
    val trySample = new TrySample(service)
    val page = trySample.homePageForUser("123", "secret")
    //page should be (Try(DefaultHomePage))
    println("non happy path for page service down ")
  }

}

Now, the first test case is throwing below exception, but the expected result was Try(WebsiteHomePage)

tryeg.ServiceUnavailableException: The Service [AuthService] is currently unavailable

    at tryeg.TrySampleTest$$anonfun$1.apply$mcV$sp(TrySampleTest.scala:31)
    at tryeg.TrySampleTest$$anonfun$1.apply(TrySampleTest.scala:29)
    at tryeg.TrySampleTest$$anonfun$1.apply(TrySampleTest.scala:29)


来源: stackexchange

问:
what is the data type that i want to use when merging Array when i merge String array and Integer Array into merge Array
I have an String Array and Integer Array,

```<code>String[] strArray={"a","b","c"};
Integer[] intArray={1,2,3};
</code>```

I want two merge them into another array.What is the data type of merge Array?and how i implement merge Array?

答:
The first instinct would be to me:

In Java you just can have one Type for container, if you want to mix two types, you have to create some abstraction, like an Interface, or create another way to relate your String with your Integer.

But

consider the @kimdung answer if you just want to mix the two arrays and just this, and if you don't care anything else.

ContentLicense: CC BY-SA 3.0

Body:
I have an String Array and Integer Array,

String[] strArray={"a","b","c"};
Integer[] intArray={1,2,3};

I want two merge them into another array.What is the data type of merge Array?and how i implement merge Array?


问:
How to verify xml digital signature in c# without using SignedXml?
How to verify xml signature (used in SOAP requests) without usage of SignedXml (which is not available in dotnet core)? </p>

<p>I am trying like this, but it gives me false all the time: </p>

```<code> public static void CheckSignature(XElement responseXml, MyResponseType response)
    {
        string originalDigestValue = Convert.ToBase64String(response.Signature.SignedInfo.Reference.FirstOrDefault().DigestValue);
        var originalSignatureValue = response.Signature.SignatureValue.Value;

        X509DataType certificateData = (X509DataType)response.Signature.KeyInfo.Items[0];
        X509Certificate2 certificate = new X509Certificate2((byte[])certificateData.Items[0]);

        //for calculating digest value
        //responseXml.Descendants(nm + "Signature").SingleOrDefault().Remove();
        //var digestValue = Convert.ToBase64String(SHA1.Create().ComputeHash(System.Text.Encoding.UTF8.GetBytes(responseXml.Document.ToString())));

        XNamespace nm = @"http://www.w3.org/2000/09/xmldsig#";
        var signedInfoNode = responseXml.Descendants(nm + "SignedInfo").SingleOrDefault();

        var signedInfo = signedInfoNode.ToString().Trim();

        byte[] signedInfoBytes = Encoding.UTF8.GetBytes(signedInfo);

        var hash = SHA1.Create().ComputeHash(signedInfoBytes);

        RSA rsa = certificate.GetRSAPublicKey();

        try
        {
            Console.WriteLine("Signed Info: \n" + signedInfo);
            Console.WriteLine("Verification: \n" + rsa.VerifyData(signedInfoBytes, originalSignatureValue, HashAlgorithmName.SHA1, RSASignaturePadding.Pkcs1));
            Console.WriteLine("Verification hash: \n" + rsa.VerifyData(hash, originalSignatureValue, HashAlgorithmName.SHA1, RSASignaturePadding.Pkcs1));
        }
        catch (Exception exc)
        {
           //
        }
    }
</code>```

答:
xmldsig is a very large, very complicated spec.  You can try to implement it if you like, the complicated bits are turning the XML document into bytes for doing signing and verification (the canonicalization (or c14n) spec is separate, and large).

SignedXml should be available now with .NET Core 2.0 Preview 1, and upgrading is definitely your easiest bet.

Body:
How to verify xml signature (used in SOAP requests) without usage of SignedXml (which is not available in dotnet core)?

I am trying like this, but it gives me false all the time:

 public static void CheckSignature(XElement responseXml, MyResponseType response)
    {
        string originalDigestValue = Convert.ToBase64String(response.Signature.SignedInfo.Reference.FirstOrDefault().DigestValue);
        var originalSignatureValue = response.Signature.SignatureValue.Value;

        X509DataType certificateData = (X509DataType)response.Signature.KeyInfo.Items[0];
        X509Certificate2 certificate = new X509Certificate2((byte[])certificateData.Items[0]);

        //for calculating digest value
        //responseXml.Descendants(nm + "Signature").SingleOrDefault().Remove();
        //var digestValue = Convert.ToBase64String(SHA1.Create().ComputeHash(System.Text.Encoding.UTF8.GetBytes(responseXml.Document.ToString())));

        XNamespace nm = @"http://www.w3.org/2000/09/xmldsig#";
        var signedInfoNode = responseXml.Descendants(nm + "SignedInfo").SingleOrDefault();

        var signedInfo = signedInfoNode.ToString().Trim();

        byte[] signedInfoBytes = Encoding.UTF8.GetBytes(signedInfo);

        var hash = SHA1.Create().ComputeHash(signedInfoBytes);

        RSA rsa = certificate.GetRSAPublicKey();

        try
        {
            Console.WriteLine("Signed Info: \n" + signedInfo);
            Console.WriteLine("Verification: \n" + rsa.VerifyData(signedInfoBytes, originalSignatureValue, HashAlgorithmName.SHA1, RSASignaturePadding.Pkcs1));
            Console.WriteLine("Verification hash: \n" + rsa.VerifyData(hash, originalSignatureValue, HashAlgorithmName.SHA1, RSASignaturePadding.Pkcs1));
        }
        catch (Exception exc)
        {
           //
        }
    }


问:
How to retrieve usage on Amazon S3 based on tags?
We are only implement one bucket for all data stored in S3, there are many data from different organization. Can we retrieve usage from 'foo' organization or 'bar' organization by its 'foo' or 'bar' tag?

Usecase :

We deploy a mobile app for our client called 'foo' and 'bar', this app used to upload file (images and videos) contains 'foo' tag, and 'bar' tag based on organization. We use the same API for the app, and same bucket in S3. So I just want to get the metrics like total storage used by 'foo' tag or 'bar' tag. So i can monitor that 'foo' or 'bar' already use N GB.

答:
Tagging at the object-level for Amazon S3 was introduced in March 2017. It allows:

Lifecycle Management by tag (eg move to Amazon Glacier)

Access control policies

It does not provide metrics based on tags at the object level.

You would need to write your own script to retrieve a list of objects and calculate storage based on tag. However, it appears that the only way to retrieve tags on an object is to request for each individual object. This means you would be making large quantities of API calls.

An alternative is to use object metadata against each object. Metadata is returned by the list-objects API call, so it would only require one API call per 1000 objects (which is the paging size of returned data).

Finally, you could store the objects in separate buckets, which would make it possible to use Amazon CloudWatch metrics. Amazon S3 sends metrics to Amazon CloudWatch for the number of objects and the amount of storage space.


问:
How to format/control output of Symfony ChoiceType
Is it possible to iterate over ChoiceType values in Symfony 3? I can setup the values fine, but they just output in big block for which i can't control. I would like to loop over each value and format it/put in table/div/columns etc.

```<code>$builder->add('tOptions', ChoiceType::class, array(
    'choices'  => array(
        'one' => true,
        'two' => true,
        'three' => true,
        'four' => true,
        'five' => true,
    ),
    'expanded' => true,
    'multiple' => true,
    'required' => false,
));
</code>```

Note: I am not outputting in twig, just in PHP.

```<code>echo $view['form']->widget($form['tOptions']);
</code>```

Results in:

```<code><div id="t_options_tOptions">
<input type="checkbox" id="t_options_tOptions_0" name="t_options[tOptions][]" value="0">
<label for="t_options_tOptions_0">one</label>

<input type="checkbox" id="t_options_tOptions_1" name="t_options[tOptions][]" value="1">
<label for="t_options_tOptions_1">two</label>

<input type="checkbox" id="t_options_tOptions_2" name="t_options[tOptions][]" value="2">
<label for="t_options_tOptions_2">three</label>

<input type="checkbox" id="t_options_tOptions_3" name="t_options[tOptions][]" value="3">
<label for="t_options_tOptions_3">four</label>

<input type="checkbox" id="t_options_tOptions_4" name="t_options[tOptions][]" value="4">
<label for="t_options_tOptions_4">five</label>
</div>
</code>```

How does one iterate over these input options, in order to wrap each in div or split into two even columns etc.

答:
To customize that you'd have to create a custom template for the choices widget. Specifically, you could extend the choice_widget_options.html.php file.

To apply the styling you can follow the Form Theming in PHP documentation. It's worth noting that extending the template with Twig would be simpler.

Body:
Is it possible to iterate over ChoiceType values in Symfony 3? I can setup the values fine, but they just output in big block for which i can't control. I would like to loop over each value and format it/put in table/div/columns etc.

$builder->add('tOptions', ChoiceType::class, array(
    'choices'  => array(
        'one' => true,
        'two' => true,
        'three' => true,
        'four' => true,
        'five' => true,
    ),
    'expanded' => true,
    'multiple' => true,
    'required' => false,
));

Note: I am not outputting in twig, just in PHP.

echo $view['form']->widget($form['tOptions']);

Results in:

<input type="checkbox" id="t_options_tOptions_0" name="t_options[tOptions][]" value="0">
one

<input type="checkbox" id="t_options_tOptions_1" name="t_options[tOptions][]" value="1">
two

<input type="checkbox" id="t_options_tOptions_2" name="t_options[tOptions][]" value="2">
three

<input type="checkbox" id="t_options_tOptions_3" name="t_options[tOptions][]" value="3">
four

<input type="checkbox" id="t_options_tOptions_4" name="t_options[tOptions][]" value="4">
five

How does one iterate over these input options, in order to wrap each in div or split into two even columns etc.


问:
Using angularjs custom filter instead of a function to perform a search
I am currently using a filter function (not a custom filter) on ng-repeat. However I have been told that using a custom filter is better performance. How would I go about using a custom filter to do the same search as this:

```<code>        $scope.searchInOrder = function (item)
        {
            if($scope.search)
            {
                if(item.match("^"+$scope.search, "i"))
                {
                    return item;
                }
            }
            else
            {
                return item;
            }
        }
</code>```

Here is my fiddle.

So I use this filter using "key in keyboard.keys | filter: searchInOrder" but how do I do the same thing using a custom filter e.g. "key in keyboard.keys | customSearchInOrder:search" is it better for performance doing it this way (with a custom filter instead of a function) and if so why? Also which way is better for code maintainability?

答:
Which way is better? This totally depends on your requirements and application. Because repeated filter may lead to performance issues. As explained in this very good post Angular Performance tips . So its for you to decide wha will be the best fir for your case a custom filter or filtering in code.

But if you are not worried about this then yes a custom filter would be good. As it will be reusable and you need not to repeat the filtering again in case you need the same filter for different views/controllers. Below is a custom filter for your case.

Updated Fiddle

var app = angular.module('myApp', []);

app.controller('myCtrl', function($scope) {

  $scope.keyboard = {
    "keys": ["cntrlA", "cntrlB", "cntrlC", "cntrlD", "space1", "space2", "space3", "shift"]
  }

});

app.filter('searchKeys', function() {
  return function(items, search) {
    var filtered = [];
    if (search) {
      angular.forEach(items, function(item) {
        if (item.match("^" + search, "i")) {
          filtered.push(item);
        }
      });
    }else{
     filtered=items;
    }
    return filtered;
  }
})```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.22/angular.min.js"></script>
<div data-ng-app='myApp' data-ng-controller='myCtrl'>

  <!-- using scope function as a filter -->
  <input ng-model="search" placeholder="Search..." />
  <div ng-repeat="key in keyboard.keys | searchKeys: search">
    {{key}}
  </div>
</div></code>```

Hope it helps :).

Body:
I am currently using a filter function (not a custom filter) on ng-repeat. However I have been told that using a custom filter is better performance. How would I go about using a custom filter to do the same search as this:

        $scope.searchInOrder = function (item)
        {
            if($scope.search)
            {
                if(item.match("^"+$scope.search, "i"))
                {
                    return item;
                }
            }
            else
            {
                return item;
            }
        }

Here is my fiddle.

So I use this filter using "key in keyboard.keys | filter: searchInOrder" but how do I do the same thing using a custom filter e.g. "key in keyboard.keys | customSearchInOrder:search" is it better for performance doing it this way (with a custom filter instead of a function) and if so why? Also which way is better for code maintainability?

Body:
Which way is better? This totally depends on your requirements and application. Because repeated filter may lead to performance issues. As explained in this very good post Angular Performance tips . So its for you to decide wha will be the best fir for your case a custom filter or filtering in code.

But if you are not worried about this then yes a custom filter would be good. As it will be reusable and you need not to repeat the filtering again in case you need the same filter for different views/controllers. Below is a custom filter for your case.

Updated Fiddle

var app = angular.module('myApp', []);

app.controller('myCtrl', function($scope) {

  $scope.keyboard = {
    "keys": ["cntrlA", "cntrlB", "cntrlC", "cntrlD", "space1", "space2", "space3", "shift"]
  }

});

app.filter('searchKeys', function() {
  return function(items, search) {
    var filtered = [];
    if (search) {
      angular.forEach(items, function(item) {
        if (item.match("^" + search, "i")) {
          filtered.push(item);
        }
      });
    }else{
     filtered=items;
    }
    return filtered;
  }
})

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.22/angular.min.js"></script>
<div data-ng-app='myApp' data-ng-controller='myCtrl'>

  <!-- using scope function as a filter -->
  <input ng-model="search" placeholder="Search..." />
  <div ng-repeat="key in keyboard.keys | searchKeys: search">
    {{key}}
  </div>
</div>

Hope it helps :).


问:
filter Java collection in lambda w/o creating new one
I have a final ConcurrentMap in Java and want to filter it's elements without creating a new one.

Question is: can I reference collection (people) from inside the lambda?

```<code>final ConcurrentMap<String, String> people = new ConcurrentHashMap<>();
people.put("Sam", "developer");
people.put("Kate", "tester");

people.forEach((name, role) -> {
    if (name.length() > 3)
        people.remove(name);
});
</code>```

答:
.keySet(), .values(), and .entrySet() return live views of a map's keys, values and entries respectively.  You can remove elements from those collections and the corresponding entries will be removed from the map:

```<code>people.keySet().removeIf(name -> name.length() > 3);
</code>```

Body:
I have a final ConcurrentMap in Java and want to filter it's elements without creating a new one.

Question is: can I reference collection (people) from inside the lambda?

final ConcurrentMap<String, String> people = new ConcurrentHashMap<>();
people.put("Sam", "developer");
people.put("Kate", "tester");

people.forEach((name, role) -> {
    if (name.length() > 3)
        people.remove(name);
});

Body:
.keySet(), .values(), and .entrySet() return live views of a map's keys, values and entries respectively.  You can remove elements from those collections and the corresponding entries will be removed from the map:

people.keySet().removeIf(name -> name.length() > 3);


问:
JSON Template in Lua
I have a JSON object which I would like to templatize in lua. For example:

```<code>{
  "type":"email",
  "version":"1.0",
  "account":"%emailId%"
}
</code>```

I would like to substitute the %emailId% with a list of e-mail ids. Is there a templatization support for JSON in lua?

答: No, there is no built-in support for either JSON or templating in the core Lua language or libraries. There are a number of JSON modules available, but I'm not sure whether any of them have template support. You might have to write a templating function yourself, but it probably won't be too hard - it's just a matter of iterating over all the string values with the JSON module and using string.gsub on them.</p>

Title: JSON Template in Lua

Body:
I have a JSON object which I would like to templatize in lua. For example:

{
  "type":"email",
  "version":"1.0",
  "account":"%emailId%"
}

I would like to substitute the %emailId% with a list of e-mail ids. Is there a templatization support for JSON in lua?


答: You need to use object type array, as in your case you are using integer wrapper object and string, which can be merge as object in java</p>

Title: what is the data type that i want to use when merging Array when i merge String array and Integer Array into merge Array


问:
Are there any good open source smalltalk implementations?
Do you know any good smalltalk implementations which meet the following criteria:

are open source (and free)

are enterprise ready - I can do commercial apps into it

works on os x

I'm asking this because I heard a lot about smalltalk, and I want to learn it - just for fun. But it seems to be hard to find the right tools and books for this language.

答:
I would go by Pharo. Check:

http://www.pharo-project.org/

http://pharobyexample.org/

http://book.pharo-project.org/

ContentLicense: CC BY-SA 2.5


问:
Android: How to start an activity which is in device settings?
How can I start an activity which is in device settings? I need to start a settings page with intent.</p>

答:
If I understand it correctly, you would like to start device settings from your app using intent.
Then please use:

```<code>startActivityForResult(new Intent(android.provider.Settings.ACTION_SETTINGS), 0);
</code>```

I know I am late. However this might help someone who want to do this task.

Body:
If I understand it correctly, you would like to start device settings from your app using intent.
Then please use:

startActivityForResult(new Intent(android.provider.Settings.ACTION_SETTINGS), 0);

I know I am late. However this might help someone who want to do this task.


问:
WPF converter on grid column and row length only works if gridsplitter is not used
In WPF I have a boolean to length converter that I have binded to column and row definitions.

This converter is used to read a binded boolean in order to determine whether the row/column should be hidden or shown.

This is done so I can "maximize" a given portion of a grid or return it back to its original size.  This works so long as I don't use the gridsplitter to resize.  As soon as this happens it no longer sets the desired length.  I have a feeling once the gridsplitter is used it removes the binding on the column definition.  Is there a work around for this?

Converter

```<code>[ValueConversion(typeof(bool), typeof(GridLength))]
public class BoolToGridLengthConverter : IValueConverter
{
    public int Length { get; set; }

    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        return ((bool)value == true) ? new GridLength(Length == 0 ? 1 : Length, GridUnitType.Star) : new GridLength(0);
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {    // Don't need any convert back
        return null;
    }
}
</code>```

XAML

```<code><Grid>
    <Grid.Resources>
        <helpers:BoolToGridLengthConverter x:Key="BoolToGridLengthConverter1" Length="1" />
        <helpers:BoolToGridLengthConverter x:Key="BoolToGridLengthConverter2" Length="2" />
    </Grid.Resources>
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="{Binding ShowColumn1, Mode=TwoWay, Converter={StaticResource BoolToGridLengthConverter1}}" />
        <ColumnDefinition Width="5" />
        <ColumnDefinition Width="{Binding ShowColumn2, Mode=TwoWay, Converter={StaticResource BoolToGridLengthConverter1}}" />
        <ColumnDefinition Width="5" />
        <ColumnDefinition Width="{Binding ShowColumn3, Mode=TwoWay, Converter={StaticResource BoolToGridLengthConverter1}}" />
    </Grid.ColumnDefinitions>
    <Grid.RowDefinitions>
        <RowDefinition Height="{Binding ShowRow1, Mode=TwoWay, Converter={StaticResource BoolToGridLengthConverter1}}" />
        <RowDefinition Height="5" />
        <RowDefinition Height="{Binding ShowRow2, Mode=TwoWay, Converter={StaticResource BoolToGridLengthConverter2}}" />
    </Grid.RowDefinitions>
    <Grid Grid.Column="0" Grid.ColumnSpan="5" Grid.Row="0"></Grid>
    <GridSplitter Grid.Column="0" Grid.ColumnSpan="5" Grid.Row="1" ResizeDirection="Rows" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" Height="5" />
    <Grid Grid.Column="0" Grid.Row="2"></Grid>
    <GridSplitter Grid.Column="1" Grid.Row="2" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" Width="5" />
    <Grid Grid.Column="2" Grid.Row="2"></Grid>
    <GridSplitter Grid.Column="3" Grid.Row="2" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" Width="5" />
    <Grid Grid.Column="4" Grid.Row="2"></Grid>
</Grid>
</code>```

Edit: Restructured question to include more XAML

Edit: Additional info, when I wish to expand a grid section I set all booleans to false and set the section I want to true.  For example, if I wish to maximize Grid.Column 2 and Grid.Row 2 I set all the booleans to false except ShowColumn2 and ShowRow2.  This works as intended and when the booleans are all set to true, to get the original view back it, it works as intended as well.  The issue is once I use a gridsplitter to resize a column it doesn't work as before.  When I maximize the same section as before it works fine, but when I attempt to resize back to the original size Grid.Column 2 and Grid.Row 2 takes up the whole bottom row.  The two columns besides them are minimized.

This leads me to believe that when the gridsplitter is used the converter will no longer be able to set the column's value to true.

答:
In your ColumnDefinition you need to set the MaxWidth to zero to hide the Column and MaxHeight to zero for Row.

try the following converter:

```<code>[ValueConversion(typeof(bool), typeof(double))]
public class BoolToMaxConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        return ((bool)value == true) ? double.MaxValue : 0d;
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {    // Don't need any convert back
        return null;
    }
}
</code>```

and your xaml:

```<code><Grid>
    <Grid.Resources>
        <local:BoolToMaxConverter x:Key="BoolToMaxConverter" />
    </Grid.Resources>
    <Grid.ColumnDefinitions>
        <ColumnDefinition MaxWidth="{Binding ShowColumn1, Converter={StaticResource BoolToMaxConverter}}"  />
        <ColumnDefinition Width="5" />
        <ColumnDefinition MaxWidth="{Binding ShowColumn2, Converter={StaticResource BoolToMaxConverter}}" />
        <ColumnDefinition Width="5" />
        <ColumnDefinition MaxWidth="{Binding ShowColumn3, Converter={StaticResource BoolToMaxConverter}}" />
    </Grid.ColumnDefinitions>
    <Grid.RowDefinitions>
        <RowDefinition MaxHeight="{Binding ShowRow1, Converter={StaticResource BoolToMaxConverter}}" />
        <RowDefinition Height="5" />
        <RowDefinition  MaxHeight="{Binding ShowRow2, Converter={StaticResource BoolToMaxConverter}}" />
    </Grid.RowDefinitions>
    <Grid Grid.Column="0" Grid.ColumnSpan="5" Grid.Row="0"></Grid>
    <GridSplitter Grid.Column="0" Grid.ColumnSpan="5" Grid.Row="1" ResizeDirection="Rows" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" Height="5" />
    <Grid Grid.Column="0" Grid.Row="2"></Grid>
    <GridSplitter Grid.Column="1" Grid.Row="2" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" Width="5" />
    <Grid Grid.Column="2" Grid.Row="2"></Grid>
    <GridSplitter Grid.Column="3" Grid.Row="2" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" Width="5" />
    <Grid Grid.Column="4" Grid.Row="2"></Grid>
</Grid>
</code>```

Also consider to remove TwoWay-Binding.

Body:
In WPF I have a boolean to length converter that I have binded to column and row definitions.

This converter is used to read a binded boolean in order to determine whether the row/column should be hidden or shown.

This is done so I can "maximize" a given portion of a grid or return it back to its original size.  This works so long as I don't use the gridsplitter to resize.  As soon as this happens it no longer sets the desired length.  I have a feeling once the gridsplitter is used it removes the binding on the column definition.  Is there a work around for this?

Converter

[ValueConversion(typeof(bool), typeof(GridLength))]
public class BoolToGridLengthConverter : IValueConverter
{
    public int Length { get; set; }

    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        return ((bool)value == true) ? new GridLength(Length == 0 ? 1 : Length, GridUnitType.Star) : new GridLength(0);
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {    // Don't need any convert back
        return null;
    }
}

XAML

<Grid>
    <Grid.Resources>
        <helpers:BoolToGridLengthConverter x:Key="BoolToGridLengthConverter1" Length="1" />
        <helpers:BoolToGridLengthConverter x:Key="BoolToGridLengthConverter2" Length="2" />
    </Grid.Resources>
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="{Binding ShowColumn1, Mode=TwoWay, Converter={StaticResource BoolToGridLengthConverter1}}" />
        <ColumnDefinition Width="5" />
        <ColumnDefinition Width="{Binding ShowColumn2, Mode=TwoWay, Converter={StaticResource BoolToGridLengthConverter1}}" />
        <ColumnDefinition Width="5" />
        <ColumnDefinition Width="{Binding ShowColumn3, Mode=TwoWay, Converter={StaticResource BoolToGridLengthConverter1}}" />
    </Grid.ColumnDefinitions>
    <Grid.RowDefinitions>
        <RowDefinition Height="{Binding ShowRow1, Mode=TwoWay, Converter={StaticResource BoolToGridLengthConverter1}}" />
        <RowDefinition Height="5" />
        <RowDefinition Height="{Binding ShowRow2, Mode=TwoWay, Converter={StaticResource BoolToGridLengthConverter2}}" />
    </Grid.RowDefinitions>
    <Grid Grid.Column="0" Grid.ColumnSpan="5" Grid.Row="0"></Grid>
    <GridSplitter Grid.Column="0" Grid.ColumnSpan="5" Grid.Row="1" ResizeDirection="Rows" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" Height="5" />
    <Grid Grid.Column="0" Grid.Row="2"></Grid>
    <GridSplitter Grid.Column="1" Grid.Row="2" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" Width="5" />
    <Grid Grid.Column="2" Grid.Row="2"></Grid>
    <GridSplitter Grid.Column="3" Grid.Row="2" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" Width="5" />
    <Grid Grid.Column="4" Grid.Row="2"></Grid>
</Grid>

Edit: Restructured question to include more XAML

Edit: Additional info, when I wish to expand a grid section I set all booleans to false and set the section I want to true.  For example, if I wish to maximize Grid.Column 2 and Grid.Row 2 I set all the booleans to false except ShowColumn2 and ShowRow2.  This works as intended and when the booleans are all set to true, to get the original view back it, it works as intended as well.  The issue is once I use a gridsplitter to resize a column it doesn't work as before.  When I maximize the same section as before it works fine, but when I attempt to resize back to the original size Grid.Column 2 and Grid.Row 2 takes up the whole bottom row.  The two columns besides them are minimized.

This leads me to believe that when the gridsplitter is used the converter will no longer be able to set the column's value to true.

Body:
In your ColumnDefinition you need to set the MaxWidth to zero to hide the Column and MaxHeight to zero for Row.

try the following converter:

[ValueConversion(typeof(bool), typeof(double))]
public class BoolToMaxConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        return ((bool)value == true) ? double.MaxValue : 0d;
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {    // Don't need any convert back
        return null;
    }
}

and your xaml:

<Grid>
    <Grid.Resources>
        <local:BoolToMaxConverter x:Key="BoolToMaxConverter" />
    </Grid.Resources>
    <Grid.ColumnDefinitions>
        <ColumnDefinition MaxWidth="{Binding ShowColumn1, Converter={StaticResource BoolToMaxConverter}}"  />
        <ColumnDefinition Width="5" />
        <ColumnDefinition MaxWidth="{Binding ShowColumn2, Converter={StaticResource BoolToMaxConverter}}" />
        <ColumnDefinition Width="5" />
        <ColumnDefinition MaxWidth="{Binding ShowColumn3, Converter={StaticResource BoolToMaxConverter}}" />
    </Grid.ColumnDefinitions>
    <Grid.RowDefinitions>
        <RowDefinition MaxHeight="{Binding ShowRow1, Converter={StaticResource BoolToMaxConverter}}" />
        <RowDefinition Height="5" />
        <RowDefinition  MaxHeight="{Binding ShowRow2, Converter={StaticResource BoolToMaxConverter}}" />
    </Grid.RowDefinitions>
    <Grid Grid.Column="0" Grid.ColumnSpan="5" Grid.Row="0"></Grid>
    <GridSplitter Grid.Column="0" Grid.ColumnSpan="5" Grid.Row="1" ResizeDirection="Rows" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" Height="5" />
    <Grid Grid.Column="0" Grid.Row="2"></Grid>
    <GridSplitter Grid.Column="1" Grid.Row="2" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" Width="5" />
    <Grid Grid.Column="2" Grid.Row="2"></Grid>
    <GridSplitter Grid.Column="3" Grid.Row="2" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" Width="5" />
    <Grid Grid.Column="4" Grid.Row="2"></Grid>
</Grid>

Also consider to remove TwoWay-Binding.


答:
According to the current documentation you can only use bucket tags for cost allocation reports.

http://docs.aws.amazon.com/AmazonS3/latest/dev/BucketBilling.html

However with CloudWatch you can use a metric configuration with an object tag filter which returns metrics for only those tagged S3 objects. It may be limited to request metrics. You will need to use the new S3 Console and instructions are here: http://docs.aws.amazon.com/AmazonS3/latest/user-guide/configure-metrics.html

See http://docs.aws.amazon.com/AmazonS3/latest/dev/metrics-configurations.html

Also http://docs.aws.amazon.com/AmazonS3/latest/dev/cloudwatch-monitoring.html

Title: How to retrieve usage on Amazon S3 based on tags?

Body:
We are only implement one bucket for all data stored in S3, there are many data from different organization. Can we retrieve usage from 'foo' organization or 'bar' organization by its 'foo' or 'bar' tag?

Usecase :

We deploy a mobile app for our client called 'foo' and 'bar', this app used to upload file (images and videos) contains 'foo' tag, and 'bar' tag based on organization. We use the same API for the app, and same bucket in S3. So I just want to get the metrics like total storage used by 'foo' tag or 'bar' tag. So i can monitor that 'foo' or 'bar' already use N GB.


问:
jquery add dash between characters if length is greater than x
I am trying to format a US zip code as the user types, and need to add a dash between the 5th and and 6th characters if the user types more than 5 so the the zip code is formatted like

55555 or 55555-5555

what I have now adds a dash, but regardless if a 6th number is added

```<code>//zip code formatting
$(".zip-val").keyup(function() {
    if($(this).val().length == 5) {
        $(this).val($(this).val() + "-");
    }
});
</code>```

答:
You can try this.</p>

```<code>$(".zip-val").keyup(function() {
    if($(this).val().length > 5 ) {
        res = $(this).val().split("");//convert string to array
       if(jQuery.inArray( "-", res )){//checks if dash exist
       for (var i=res.length-1; i>=0; i--) {//removes dashes
          if (res[i] === '-') {
              res.splice(i, 1);
              }
            }
            res.splice(5, 0, "-");
        }
        $(this).val(res.join(''));
    }
});
</code>```

Body:
I am trying to format a US zip code as the user types, and need to add a dash between the 5th and and 6th characters if the user types more than 5 so the the zip code is formatted like

55555 or 55555-5555

what I have now adds a dash, but regardless if a 6th number is added

//zip code formatting
$(".zip-val").keyup(function() {
    if($(this).val().length == 5) {
        $(this).val($(this).val() + "-");
    }
});

Body:
You can try this.

$(".zip-val").keyup(function() {
    if($(this).val().length > 5 ) {
        res = $(this).val().split("");//convert string to array
       if(jQuery.inArray( "-", res )){//checks if dash exist
       for (var i=res.length-1; i>=0; i--) {//removes dashes
          if (res[i] === '-') {
              res.splice(i, 1);
              }
            }
            res.splice(5, 0, "-");
        }
        $(this).val(res.join(''));
    }
});


问:
How to shake virtual device created by Genymotion (Android Emulator)
I created a virtual device using Genymotion. I want to test an app that works with shaking the device. How can I make virtual device shake? I couldn't find how to shake that device. </p>

答:
This method only work api under 15

For test accelerator and other like gravity,gyroscope,... can use this application.

First download sensorsimulator

This is 2 application. One install(SensorSimulatorSettings-2.0-rc1.apk) in emulator second(sensorsimulator-2.0-rc1.jar) run in your PC.

More info and full tutorial

Genymotion not support this feature :

More info Genymotion Shell

Other way :

You can use Android Studio emulator Android 6.0(Google APIS) x86.

This this emulator(All x86/x64 bit) very fast and support all sensors.

Like this:


问:
axis break in plot metaMDS
I have an abundance table of fungal species from 16 different samples (xylem tree tissue) belonging to three healthy classes.

I want to visualize the similarity of these samples according to the health class.
I have run metaMDS (vegan package) and plot the output from metaMDS, here's an example of the distances obtained (data_mds)

```<code>      NMDS1        NMDS2
1  -25.82806 -0.216970172
2  -24.59347 -0.377391024
3  -25.80740  0.268355050
4  -23.41391 -0.793553278
5  -25.93017  0.179795622
6  -25.39369  0.471681826
7  -25.29794  0.044754740
8  -24.68337  1.612166365
9  400.26576  0.003309978
10 -23.21608 -0.632045558
11 -22.67440  0.268931564
12 -23.93604  0.551203963
13 -23.55546 -1.304642023
14 -25.77035 -0.989877602
15 -25.77835 -0.226395569
16 -24.38708  1.140676118
</code>```

If I plot them, sample 9 will skew all the graph, so all the other 15 samples will overlap in one place (as you can see in the figure).

15 samples overlapping and sample no.9 alone

I have tried using gap.plot to create a gap between the two groups but I can't figure out how to create a plot where the 15 samples are more separated (both x and y axes) and then having a separate part for sample 9.
With this code I have manage to create two separate plots but as you can see in figure 2 the 15 samples are not spread out on the x axis.

```<code>nmds_plot <- plot(data_mds, main = "NMDS", type="none")
gap.plot(nmds_plot, gap=c(300, 350), gap.axis="x", xlim=c(-30, 500), ylim = c(-2, 2))

cols <- c("darkturquoise","darkturquoise","darkturquoise","darkturquoise","darkturquoise","darkturquoise","darkturquoise","darkturquoise",
      "grey0","grey0","grey0","grey0",
      "chocolate1","chocolate1","chocolate1","chocolate1")
pch_data_mds<-c(15,15,15,15,15,15,15,15,17,17,17,17,19,19,19,19)

points(nmds_plot, col=cols, pch=pch_data_mds, cex=1.4)

abline(v=0, col="gray59", lty="dotted")
abline(h=0, col="gray59", lty="dotted")

colsleg <- c("darkturquoise", "grey0", "chocolate1")
legend("topright", legend = c("Low", "Medium", "High"), col=colsleg , pch=c(15,17,19), cex=0.5, title = "Vitality classes")
</code>```

graphs divided but with the 15 samples not spaced on the x axis

Thank you for the help

答: You have discontinuity and an outlier. There is no way of having axis breaks in ordination diagrams, but the result is what it is. However, you can have xlimand ylim arguments to limit the plot to the desired range. Usually you have to give both limits, because the ordination plot will have equal aspect ratio. However, often you find little structure in the overlaid bunch of points, but you need to deal with the outlier. Often the reason to be is an outlier is to have nothing in common with the rest of the points. Removing an outlier often helps. Sometimes it helps to set noshare = TRUE in the metaMDS call.

Title: axis break in plot metaMDS

Body:
I have an abundance table of fungal species from 16 different samples (xylem tree tissue) belonging to three healthy classes.

I want to visualize the similarity of these samples according to the health class.
I have run metaMDS (vegan package) and plot the output from metaMDS, here's an example of the distances obtained (data_mds)

      NMDS1        NMDS2
1  -25.82806 -0.216970172
2  -24.59347 -0.377391024
3  -25.80740  0.268355050
4  -23.41391 -0.793553278
5  -25.93017  0.179795622
6  -25.39369  0.471681826
7  -25.29794  0.044754740
8  -24.68337  1.612166365
9  400.26576  0.003309978
10 -23.21608 -0.632045558
11 -22.67440  0.268931564
12 -23.93604  0.551203963
13 -23.55546 -1.304642023
14 -25.77035 -0.989877602
15 -25.77835 -0.226395569
16 -24.38708  1.140676118

If I plot them, sample 9 will skew all the graph, so all the other 15 samples will overlap in one place (as you can see in the figure).

15 samples overlapping and sample no.9 alone

I have tried using gap.plot to create a gap between the two groups but I can't figure out how to create a plot where the 15 samples are more separated (both x and y axes) and then having a separate part for sample 9.
With this code I have manage to create two separate plots but as you can see in figure 2 the 15 samples are not spread out on the x axis.

nmds_plot <- plot(data_mds, main = "NMDS", type="none")
gap.plot(nmds_plot, gap=c(300, 350), gap.axis="x", xlim=c(-30, 500), ylim = c(-2, 2))

cols <- c("darkturquoise","darkturquoise","darkturquoise","darkturquoise","darkturquoise","darkturquoise","darkturquoise","darkturquoise",
      "grey0","grey0","grey0","grey0",
      "chocolate1","chocolate1","chocolate1","chocolate1")
pch_data_mds<-c(15,15,15,15,15,15,15,15,17,17,17,17,19,19,19,19)

points(nmds_plot, col=cols, pch=pch_data_mds, cex=1.4)

abline(v=0, col="gray59", lty="dotted")
abline(h=0, col="gray59", lty="dotted")

colsleg <- c("darkturquoise", "grey0", "chocolate1")
legend("topright", legend = c("Low", "Medium", "High"), col=colsleg , pch=c(15,17,19), cex=0.5, title = "Vitality classes")

graphs divided but with the 15 samples not spaced on the x axis

Thank you for the help


问:
c++ parse int from string

Possible Duplicate:

  How to parse a string to an int in C++?

I have done some research and some people say to use atio and others say it's bad, and I can't get it to work anyways.

So I just want to ask flat out, whats the right way to convert a string to a int.

```<code>string s = "10";
int i = s....?
</code>```

Thanks!

答:
In C++11, use std::stoi as:

```<code> std::string s = "10";
 int i = std::stoi(s);
</code>```

Note that std::stoi will throw exception of type std::invalid_argument if the conversion cannot be performed, or std::out_of_range if the conversion results in overflow(i.e when the string value is too big for int type). You can use std::stol or std:stoll though in case int seems too small for the input string.

In C++03/98, any of the following can be used:

```<code> std::string s = "10";
 int i;

 //approach one
 std::istringstream(s) >> i; //i is 10 after this

 //approach two
 sscanf(s.c_str(), "%d", &i); //i is 10 after this
</code>```

Note that  the above two approaches would fail for input s = "10jh". They will return 10 instead of notifying error. So the safe and robust approach is to write your own function that parses the input string, and verify each character to check if it is digit or not, and then work accordingly. Here is one robust implemtation (untested though):

```<code>int to_int(char const *s)
{
     if ( s == NULL || *s == '\0' )
        throw std::invalid_argument("null or empty string argument");

     bool negate = (s[0] == '-');
     if ( *s == '+' || *s == '-' )
         ++s;

     if ( *s == '\0')
        throw std::invalid_argument("sign character only.");

     int result = 0;
     while(*s)
     {
          if ( *s < '0' || *s > '9' )
            throw std::invalid_argument("invalid input string");
          result = result * 10  - (*s - '0');  //assume negative number
          ++s;
     }
     return negate ? result : -result; //-result is positive!
}
</code>```

This solution is slightly modified version of my another solution.

Title: c++ parse int from string

Body:
Possible Duplicate:

  How to parse a string to an int in C++?

I have done some research and some people say to use atio and others say it's bad, and I can't get it to work anyways.

So I just want to ask flat out, whats the right way to convert a string to a int.

string s = "10";
int i = s....?

Thanks!

Body:
In C++11, use std::stoi as:

 std::string s = "10";
 int i = std::stoi(s);

Note that std::stoi will throw exception of type std::invalid_argument if the conversion cannot be performed, or std::out_of_range if the conversion results in overflow(i.e when the string value is too big for int type). You can use std::stol or std:stoll though in case int seems too small for the input string.

In C++03/98, any of the following can be used:

 std::string s = "10";
 int i;

 //approach one
 std::istringstream(s) >> i; //i is 10 after this

 //approach two
 sscanf(s.c_str(), "%d", &i); //i is 10 after this

Note that  the above two approaches would fail for input s = "10jh". They will return 10 instead of notifying error. So the safe and robust approach is to write your own function that parses the input string, and verify each character to check if it is digit or not, and then work accordingly. Here is one robust implemtation (untested though):

int to_int(char const *s)
{
     if ( s == NULL || *s == '\0' )
        throw std::invalid_argument("null or empty string argument");

     bool negate = (s[0] == '-');
     if ( *s == '+' || *s == '-' )
         ++s;

     if ( *s == '\0')
        throw std::invalid_argument("sign character only.");

     int result = 0;
     while(*s)
     {
          if ( *s < '0' || *s > '9' )
            throw std::invalid_argument("invalid input string");
          result = result * 10  - (*s - '0');  //assume negative number
          ++s;
     }
     return negate ? result : -result; //-result is positive!
}

This solution is slightly modified version of my another solution.

ContentLicense: CC BY-SA 4.0


问:
How to make div/popup to show once in the browser. Plain vanilla script
// JavaScript Document

I am trying to do when the user goes to the browser it only shows up once. I know it is something to do with local storage but all I see is jquery when I search something similar.

I really want to know how to do it in plain javascript no jquery.

```<code>(function() {
    "use strict";
    console.log("SEAF Fired");

    function popup (hideOrshow){
        if (hideOrshow == 'hide')
        document.getElementById("popupBox").style.display="none";
        else document.getElementById("popupBox").style.display="block";
    }

    window.onload = function (){
        setTimeout(function(){
            popup('show');
        },3000);

        document.getElementById('close').onclick=function(){
            document.getElementById('popupBox').style.display="none"
        };
    }
})();
</code>```

答:
More about local/ session storage is here;
https://www.w3schools.com/html/html5_webstorage.asp

I'd encourage you to use session storage rather than the local storage.

Why?

window.localStorage - stores data with no expiration date

window.sessionStorage - stores data for one session (data is lost when the browser tab is closed)

Assuming that your browser supports local storage, and you handle the case otherwise.

```<code>if (!window.sessionStorage.popupFlag) {
   // Logic to show popup once goes here...
   window.sessionStorage.popupFlag = true;
}
</code>```

Body:
// JavaScript Document

I am trying to do when the user goes to the browser it only shows up once. I know it is something to do with local storage but all I see is jquery when I search something similar.

I really want to know how to do it in plain javascript no jquery.

(function() {
    "use strict";
    console.log("SEAF Fired");

    function popup (hideOrshow){
        if (hideOrshow == 'hide')
        document.getElementById("popupBox").style.display="none";
        else document.getElementById("popupBox").style.display="block";
    }

    window.onload = function (){
        setTimeout(function(){
            popup('show');
        },3000);

        document.getElementById('close').onclick=function(){
            document.getElementById('popupBox').style.display="none"
        };
    }
})();

Body:
More about local/ session storage is here;
https://www.w3schools.com/html/html5_webstorage.asp

I'd encourage you to use session storage rather than the local storage.

Why?

window.localStorage - stores data with no expiration date

window.sessionStorage - stores data for one session (data is lost when the browser tab is closed)

Assuming that your browser supports local storage, and you handle the case otherwise.

if (!window.sessionStorage.popupFlag) {
   // Logic to show popup once goes here...
   window.sessionStorage.popupFlag = true;
}


问:
Trying to make the navbar width 100% to fit nav items on one line
For some reason my navbar is not becoming 100% width. I tried to make .main-header 100% width but still not sure what the problem. The reason to make the navbar 100% is for all the nav items fit on one line. Any ideas what I am doing wrong?

Here is what the navbar looks like on the machine
http://imgur.com/a/za9LH

HTML

**Css**

/* Navigation */
.main-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  background-color: purple;
  width: 100%;
}
.logo-name {
  margin-left: 1%;
  background-color: red;
}
.main-nav {
  display: flex;
  background-color: yellow;
}

.main-nav li {
  padding: 0.3em;
  align-items: flex-end;
  background-color: transparent;
  font-size: 17px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><header class="main-header">
<!--<h1 class="logo-name"><li>R.J Roofer</li></h1>-->
  <h1 class="logo-name">R.J Roofer</h1>

  <nav class="main-nav">
    <li class="nav-item-1">home</li>
    <li>services</li>
    <li>gallery</li>
    <li>about us</li>
    <li>contact</li>
<!--<li>FREE QUOTE</li>-->
  </nav>
</header></code>```

答:
By default body take 8px margin, thats why your navbar is not fullwifth. So add margin:0 in your body tag. Here is the codepen: https://codepen.io/bhuwanb9/pen/XgmegE

```<code>body{
   margin:0;
}
</code>```

Body:
For some reason my navbar is not becoming 100% width. I tried to make .main-header 100% width but still not sure what the problem. The reason to make the navbar 100% is for all the nav items fit on one line. Any ideas what I am doing wrong?

Here is what the navbar looks like on the machine
http://imgur.com/a/za9LH

HTML

**Css**

/* Navigation */
.main-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  background-color: purple;
  width: 100%;
}
.logo-name {
  margin-left: 1%;
  background-color: red;
}
.main-nav {
  display: flex;
  background-color: yellow;
}

.main-nav li {
  padding: 0.3em;
  align-items: flex-end;
  background-color: transparent;
  font-size: 17px;
}

R.J Roofer

home

services

gallery

about us

contact

Body:
By default body take 8px margin, thats why your navbar is not fullwifth. So add margin:0 in your body tag. Here is the codepen: https://codepen.io/bhuwanb9/pen/XgmegE

body{
   margin:0;
}


问:
BDD Cucumber test management tool
Is there an open source tool available to control the running of BDD cucumber tests?

We are developing BDD cucumber tests and would like the option to control the tests when running them (start/stop/pause/restart) using an open source (or proprietary) test tool.

答:
The short answer it, yes.

The somewhat longer answer is that it depends on your echo system.

If you are using Java, then any build tool will be sufficient. That is Maven, Gradle or similar. These are easy to integrate in your Continuous Integration, CI, environment. With a tool chain like that, you are able to execute Cucumber on every build and will always know if your system works or not.

Title: BDD Cucumber test management tool


问:
Angular2 PrimeNG Conditional row Formatting
I have an Angular2 app using PrimeNG components. I am attempting to make it so that when a field is of a certain value, the row in a DataTable is coloured a particular colour. I have another field which contains a colour value to use for the row highlight but cannot work out how to get it to work.

My Model is as follows (very simplified):

```<code>export class RepackRequest{
AdhereToLeadTime:   boolean;
LeadTimeRemaining: string;

constructor() {
    var today = new Date();
    if(this.AdhereToLeadTime){
        var difference = today.getTime() - this.StartDate.getTime();
        if(difference >= 3 && difference <= 4){
            this.LeadTimeRemaining = "orange";
        }
        else if(difference >= 5){
            this.LeadTimeRemaining = "red";
        }
    }
    else {
        this.LeadTimeRemaining = 'white';
    }
 }
}
</code>```

So basically if it adhered to the lead time of 5 days, it changes colour depending on how close to the lead time it is.

In my template i then have the following:

```<code><p-dataTable    [value]="approvalRepacks"
                            [rows]="10"
                            [paginator]="true"
                            [pageLinks]="5"
                            [rowsPerPageOptions]="[5,10,20]"
                            selectionMode="single"
                            [(selection)]="selectedRepack"
                            (onRowSelect)="onSelect()"
                            [globalFilter]="na">
                <header>
                    <div style="text-align:center;">
                        <button pButton type="button" icon="fa-plus" iconPos="left" label="Create New Request" (click)="addNew()"></button>
                    </div>
                </header>
                <p-column field="DateRequested" header="Date Requested" sortable="true">
                    <template let-col let-rep="rowData" pTemplate type="body">
                        <span [style.background]="{{rep.LeadTimeRemaining}}">{{rep[col.field] | date:'dd/MM/yyyy'}}</span>
                    </template>
                </p-column>
                <p-column field="OrderNum"          header="Order No"           sortable="true" styleClass="wordBreak"></p-column>
                <p-column field="Customer"          header="Customer"           sortable="true"></p-column>
                <p-column field="FromItem"          header="Repack From"        sortable="true" styleClass="wordBreak"></p-column>
                <p-column field="ToItem"            header="Repack To"          sortable="true" styleClass="wordBreak"></p-column>
                <p-column field="FromWarehouse"     header="From Whse"          sortable="true"></p-column>
                <p-column field="FromLocation"      header="From Bin"           sortable="true"></p-column>
                <p-column field="ToWarehouse"       header="To Whse"          sortable="true"></p-column>
                <p-column field="ToLocation"        header="To Bin"           sortable="true"></p-column>
                <p-column field="Quantity"          header="Qty"                sortable="true"></p-column>
                <p-column field="RequestedBy"       header="Requested By"       sortable="true" styleClass="wordBreak"></p-column>
                <p-column header="Actions">
                    <template let-col let-rep="rowData" pTemplate type="body">
                        <button pButton type="button" icon="fa-check" label="Approve" (click)="approve(rep.ID)"></button>
                    </template>
                </p-column>
            </p-dataTable>
</code>```

As you can see i have [style.background]="{{rep.LeadTimeRemaining}}" to attempt to set the colour of the column.

I guess this is the wrong way to go about it as its setting it just for that column and id need the same on every column.

Can anyone help with this i cannot find any information anywhere regarding it.

Many Thanks

EDIT

Using the following on every column highlights it to a point however it is very unsightly as you can see below as it just colours the div rather than the td or tr.

```<code><template let-col let-rep="rowData" pTemplate type="body">
    <div [style.background]="rep.LeadTimeRemaining" style="margin:-50px;">
         <span>{{rep[col.field]}}</span>
    </div>
</template>
</code>```

答:
You can highlight row in datatable using rowStyleClass attribute.
You should pass function to this attribute. The function should return class name which will be applied on table row.

Template:

```<code><p-dataTable [rowStyleClass]="highlightRow" ...>
</code>```

Component code:

```<code>highlightRow(rowData: any, rowIndex: number) {
    return rowData.LeadTimeRemaining + '-highlighting';
}
</code>```

CSS:

```<code>.red-highlighting { background-color: red; }
.white-highlighting { background-color: white; }
.orange-highlighting { background-color: orange; }
</code>```

Body:
I have an Angular2 app using PrimeNG components. I am attempting to make it so that when a field is of a certain value, the row in a DataTable is coloured a particular colour. I have another field which contains a colour value to use for the row highlight but cannot work out how to get it to work.

My Model is as follows (very simplified):

export class RepackRequest{
AdhereToLeadTime:   boolean;
LeadTimeRemaining: string;

constructor() {
    var today = new Date();
    if(this.AdhereToLeadTime){
        var difference = today.getTime() - this.StartDate.getTime();
        if(difference >= 3 && difference <= 4){
            this.LeadTimeRemaining = "orange";
        }
        else if(difference >= 5){
            this.LeadTimeRemaining = "red";
        }
    }
    else {
        this.LeadTimeRemaining = 'white';
    }
 }
}

So basically if it adhered to the lead time of 5 days, it changes colour depending on how close to the lead time it is.

In my template i then have the following:

                        <button pButton type="button" icon="fa-plus" iconPos="left" label="Create New Request" (click)="addNew()"></button>

                    <template let-col let-rep="rowData" pTemplate type="body">
                        {{rep[col.field] | date:'dd/MM/yyyy'}}
                    </template>

                    <template let-col let-rep="rowData" pTemplate type="body">
                        <button pButton type="button" icon="fa-check" label="Approve" (click)="approve(rep.ID)"></button>
                    </template>

As you can see i have [style.background]="{{rep.LeadTimeRemaining}}" to attempt to set the colour of the column.

I guess this is the wrong way to go about it as its setting it just for that column and id need the same on every column.

Can anyone help with this i cannot find any information anywhere regarding it.

Many Thanks

EDIT

Using the following on every column highlights it to a point however it is very unsightly as you can see below as it just colours the div rather than the td or tr.

<template let-col let-rep="rowData" pTemplate type="body">

         {{rep[col.field]}}

</template>

Body:
You can highlight row in datatable using rowStyleClass attribute.
You should pass function to this attribute. The function should return class name which will be applied on table row.

Template:

<p-dataTable [rowStyleClass]="highlightRow" ...>

Component code:

highlightRow(rowData: any, rowIndex: number) {
    return rowData.LeadTimeRemaining + '-highlighting';
}

CSS:

.red-highlighting { background-color: red; }
.white-highlighting { background-color: white; }
.orange-highlighting { background-color: orange; }


问:
How to make console program to disappear and work in background?
How can I make console program disappear and work in the background?
I mean, I don't want to see the program, but I want to see it running in the task manager.

Thanks.

答:
You could alternatively make one that goes to the system tray. This would also allow you to add a Kill Process directly from the system tray instead of going to the task manager. In .NET I have used the following:
http://www.developer.com/net/csharp/article.php/3336751

This may offer a few advantages.

OwnerDisplayName: Tal

OwnerDisplayName: Anthony Potts


问:
Lucene.NET encrypted full text search
So the basic situation is that I have to store some text information in a SQL Server database. The problem is that the text must be encrypted AND searchable.
I've done some research about the topic and it seems that this is not yet feasible (as far as I understand, this type of encryption technique, homomorphic encryption is not mature enough to be used in real life applications).

I've come up with an idea, but I'm not sure if it is feasible at all. Can someone advise?

So I know that Lucene.NET can be used for full-text searching. What I'd like to do is index the plain text with Lucene.NET, store the index but not the plain text, store the encrypted value in SQL Server, then search the Lucene index and return the ID of the record from the Lucene index, read that specific row from SQL Server and then decrypt the data.

Is this possible? Can I index something with Lucene and then not store the indexed data?

答:
It's not going to be easy. What you're describing is rarely implemented in commercial databases, although there are some theoretical results in the field. I'd suggest that you go to google scholar and start looking for papers on the subject.

Here are a few references to get you started:

Dawn Xiaodong Song, David Wagner, and Adrian Perrig. Practical techniques for searches on encrypted data.

R. Brinkman, L. Feng, J. Doumen, P.H. Hartel, and W. Jonke. Efficient Tree Search in Encrypted Data. In Security In Information Systems, pages 126-135, 2004.

D Boneh, G Di Crescenzo, R Ostrovsky, G Persiano. Public Key Encryption with keyword Search

P Golle, J Staddon, B Waters. Secure Conjunctive Keyword Search over Encrypted Data.

Also take a look at this presentation: How to Search on Encrypted Data.

Title: Lucene.NET encrypted full text search


问:
How to invoke @PostConstruct on request scoped bean before @HandleBeforeCreate handler?
In my Spring application I have a bean with request scope:

```<code>@Component
@Scope(value = "request", proxyMode = ScopedProxyMode.TARGET_CLASS)
public class MyBean {

    @PostConstruct
    public void init() {
       ...
    }
</code>```

I have also a MongoDB event handler:

```<code>@Component
@RepositoryEventHandler
public class MyEventHandler {

    @HandleBeforeCreate
    public void beforeCreateInstance(Object instance) {
        ...
    }
 }
</code>```

When I call Spring Data REST endpoint to save my resource, the @HandleBeforeCreate gets invoked first and @PostConstruct gets invoked afterwards.

How can I change the order of this invocations? I'd like to invoke @PostConstruct on MyBean before the MongoDB event handlers kick in?

答:
As explained in this answer, scoped beans get only initialized when the get referenced. So if MyEventHandler references a MyBean the MyBean should get initialized, including any PostConstruct processing.

Of course, it would be weird to depend on a bean that you then don't use. That's exactly the purpose of @DependsOn. So change your MyEventHandler like this:

```<code>@Component
@RepositoryEventHandler
@DependsOn("myBean")
public class MyEventHandler {

    @HandleBeforeCreate
    public void beforeCreateInstance(Object instance) {
         ...
    }
}
</code>```

Body:
In my Spring application I have a bean with request scope:

@Component
@Scope(value = "request", proxyMode = ScopedProxyMode.TARGET_CLASS)
public class MyBean {

    @PostConstruct
    public void init() {
       ...
    }

I have also a MongoDB event handler:

@Component
@RepositoryEventHandler
public class MyEventHandler {

    @HandleBeforeCreate
    public void beforeCreateInstance(Object instance) {
        ...
    }
 }

When I call Spring Data REST endpoint to save my resource, the @HandleBeforeCreate gets invoked first and @PostConstruct gets invoked afterwards.

How can I change the order of this invocations? I'd like to invoke @PostConstruct on MyBean before the MongoDB event handlers kick in?

Body:
As explained in this answer, scoped beans get only initialized when the get referenced. So if MyEventHandler references a MyBean the MyBean should get initialized, including any PostConstruct processing.

Of course, it would be weird to depend on a bean that you then don't use. That's exactly the purpose of @DependsOn. So change your MyEventHandler like this:

@Component
@RepositoryEventHandler
@DependsOn("myBean")
public class MyEventHandler {

    @HandleBeforeCreate
    public void beforeCreateInstance(Object instance) {
         ...
    }
}


问:
Calculating Manhattan Distance in Python in an 8-Puzzle game
I am trying to code a simple A* solver in Python for a simple 8-Puzzle game.
I have represented the goal of my game in this way:

```<code>goal = [[1, 2, 3],
        [8, 0, 4],
        [7, 6, 5]]
</code>```

My problem is that I don't know how to write a simple Manhattan Distance heuristic for my goal. I know it should be defined as the sum of the distances between a generic state and my goal state. I think I should code something like:

```<code>def manhattan_distance(state):
    distance = 0
    for x in xrange(3):
        for y in xrange(3):
            value = state[x][y]
            x_value = x
            y_value = y
            x_goal = ...?
            y_goal = ...?
            distance += abs(x_value - x_goal) + abs(y_value - y_goal)
    return distance
</code>```

My problem is that I don't have an explicit representation of the coordinates of the pieces in the goal state, so I don't know how to define 'x_goal' and 'y_goal' for the 'value' piece of the board. I am trying to do it using division and module operations, but it's difficult.

Can you give me some hints to define my 'x_goal' and 'y_goal' variables?

Thank you

答:
you may be able to use it</p>

```<code>def manhatan_dist(board,goal_stat):
    #Manhattan priority function. The sum of the Manhattan distances
    #(sum of the vertical and horizontal distance) from the blocks to their goal positions,
    #plus the number of moves made so far to get to the search node.
    import math
    b = board
    g = goal_stat

    manh_dist = 0
    for i in range (0,3,1):
        for j in range (0,3,1):
            bij = b[i][j]
            i_b = i
            j_b = j

            i_g, j_g = value_index(g,bij)

            manh_dist += (math.fabs(i_g - i_b) + math.fabs(j_g - j_b))

    return manh_dist
</code>```

Body:
I am trying to code a simple A* solver in Python for a simple 8-Puzzle game.
I have represented the goal of my game in this way:

goal = [[1, 2, 3],
        [8, 0, 4],
        [7, 6, 5]]

My problem is that I don't know how to write a simple Manhattan Distance heuristic for my goal. I know it should be defined as the sum of the distances between a generic state and my goal state. I think I should code something like:

def manhattan_distance(state):
    distance = 0
    for x in xrange(3):
        for y in xrange(3):
            value = state[x][y]
            x_value = x
            y_value = y
            x_goal = ...?
            y_goal = ...?
            distance += abs(x_value - x_goal) + abs(y_value - y_goal)
    return distance

My problem is that I don't have an explicit representation of the coordinates of the pieces in the goal state, so I don't know how to define 'x_goal' and 'y_goal' for the 'value' piece of the board. I am trying to do it using division and module operations, but it's difficult.

Can you give me some hints to define my 'x_goal' and 'y_goal' variables?

Thank you

Body:
you may be able to use it

def manhatan_dist(board,goal_stat):
    #Manhattan priority function. The sum of the Manhattan distances
    #(sum of the vertical and horizontal distance) from the blocks to their goal positions,
    #plus the number of moves made so far to get to the search node.
    import math
    b = board
    g = goal_stat

    manh_dist = 0
    for i in range (0,3,1):
        for j in range (0,3,1):
            bij = b[i][j]
            i_b = i
            j_b = j

            i_g, j_g = value_index(g,bij)

            manh_dist += (math.fabs(i_g - i_b) + math.fabs(j_g - j_b))

    return manh_dist


问:
what is the data type that i want to use when merging Array when i merge String array and Integer Array into merge Array
I have an String Array and Integer Array,

```<code>String[] strArray={"a","b","c"};
Integer[] intArray={1,2,3};
</code>```

I want two merge them into another array.What is the data type of merge Array?and how i implement merge Array?

答:
Make a Sting array and merge both into that array, you will have to convert Integer to String while merging and the converse when you are retrieving for any purpose</p>

```<code>for(int i=0; i<intArray.length; i++) {
     mergerArray[i] = String.value(intArray[i]);
}
</code>```

Body:
I have an String Array and Integer Array,

String[] strArray={"a","b","c"};
Integer[] intArray={1,2,3};

I want two merge them into another array.What is the data type of merge Array?and how i implement merge Array?

Body:
Make a Sting array and merge both into that array, you will have to convert Integer to String while merging and the converse when you are retrieving for any purpose

for(int i=0; i<intArray.length; i++) {
     mergerArray[i] = String.value(intArray[i]);
}


问:
Angular AOT & Rollup - Uncaught ReferenceError: exports is not defined
I am trying to implement Angular's AOT tutorial:
https://angular.io/docs/ts/latest/cookbook/aot-compiler.html

Using ngc part works and it generates aot folder. However,when I run the application, I get the below error

```<code>bundle.js:1 Uncaught ReferenceError: exports is not defined
</code>```

My code is as below :-

tsconfig-aot.json

```<code>    {
      "compilerOptions": {
        "target": "es5",
        "module": "es2015",
        "moduleResolution": "node",
        "sourceMap": true,
        "emitDecoratorMetadata": true,
        "experimentalDecorators": true,
        "lib": ["es2015", "dom"],
        "noImplicitAny": true,
        "suppressImplicitAnyIndexErrors": true
      },

    "files": [
    "src/app/app.module.ts",
    "src/main.ts"
  ],

      "angularCompilerOptions": {
       "genDir": "aot",
       "skipMetadataEmit" : true
     },
     "exclude": [
            "node_modules",
            "bower_components",
            "typings/main",
            "typings/main.d.ts"
        ]
    }
</code>```

After executing node_modules/.bin/ngc -p tsconfig-aot.json, aot folder is successfully generated.

main.ts

```<code>import { platformBrowser }    from '@angular/platform-browser';
import { AppModuleNgFactory } from '../aot/src/app/app.module.ngfactory';
console.log('Running AOT compiled');
platformBrowser().bootstrapModuleFactory(AppModuleNgFactory);
</code>```

I read in one of the SO link that "You need to compile these ts files as es2015 modules, in order to benefit from "tree-shaking". This means there must be one more config file (tsconfig-compile-aot.json) that only points to main-aot.ts file."

tsconfig-compile-aot.json

```<code>{
  "compilerOptions": {
    "target": "es5",
    "module": "es2015",
    "moduleResolution": "node",
    "sourceMap": true,
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "lib": ["es2015", "dom"],
    "noImplicitAny": true,
    "suppressImplicitAnyIndexErrors": true
  },

   "files": [
    "src/main.ts"
  ],

  "angularCompilerOptions": {
   "genDir": "aot",
   "skipMetadataEmit" : true
 },
 "exclude": [
        "node_modules",
        "bower_components",
        "typings/main",
        "typings/main.d.ts"
    ]
}
</code>```

Compile main-aot.ts files with tsc and tsconfig-compile-aot.json, again as es2015 modules and generate your js files. On compiling I get my js files
I executed the command

 tsc src/main.ts

rollup-config.js

```<code>import rollup      from 'rollup'
import nodeResolve from 'rollup-plugin-node-resolve'
import commonjs    from 'rollup-plugin-commonjs';
import uglify      from 'rollup-plugin-uglify'

export default {
  entry: 'src/main.js',
  dest: 'bundle.js', // output a single application bundle
  sourceMap: false,
  format: 'iife',
  onwarn: function(warning) {
    // Skip certain warnings
    // should intercept ... but doesn't in some rollup versions
    if ( warning.code === 'THIS_IS_UNDEFINED' ) { return; }
    // console.warn everything else
    console.warn( warning.message );
  },
  plugins: [
      nodeResolve({jsnext: true, module: true}),
      commonjs({
        include: 'node_modules/rxjs/**',
      }),
      uglify()
  ]
}
</code>```

After that I executed, the below command
node_modules/.bin/rollup -c rollup-config.js

and then on executing npm run lite,I get the error .

答:
You need to add following code in your master page:</p>

```<code>window.module = {
    id: 'foo',
    exports: []
}
</code>```

Body:
I am trying to implement Angular's AOT tutorial:
https://angular.io/docs/ts/latest/cookbook/aot-compiler.html

Using ngc part works and it generates aot folder. However,when I run the application, I get the below error

bundle.js:1 Uncaught ReferenceError: exports is not defined

My code is as below :-

tsconfig-aot.json

    {
      "compilerOptions": {
        "target": "es5",
        "module": "es2015",
        "moduleResolution": "node",
        "sourceMap": true,
        "emitDecoratorMetadata": true,
        "experimentalDecorators": true,
        "lib": ["es2015", "dom"],
        "noImplicitAny": true,
        "suppressImplicitAnyIndexErrors": true
      },

    "files": [
    "src/app/app.module.ts",
    "src/main.ts"
  ],

      "angularCompilerOptions": {
       "genDir": "aot",
       "skipMetadataEmit" : true
     },
     "exclude": [
            "node_modules",
            "bower_components",
            "typings/main",
            "typings/main.d.ts"
        ]
    }

After executing node_modules/.bin/ngc -p tsconfig-aot.json, aot folder is successfully generated.

main.ts

import { platformBrowser }    from '@angular/platform-browser';
import { AppModuleNgFactory } from '../aot/src/app/app.module.ngfactory';
console.log('Running AOT compiled');
platformBrowser().bootstrapModuleFactory(AppModuleNgFactory);

I read in one of the SO link that "You need to compile these ts files as es2015 modules, in order to benefit from "tree-shaking". This means there must be one more config file (tsconfig-compile-aot.json) that only points to main-aot.ts file."

tsconfig-compile-aot.json

{
  "compilerOptions": {
    "target": "es5",
    "module": "es2015",
    "moduleResolution": "node",
    "sourceMap": true,
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "lib": ["es2015", "dom"],
    "noImplicitAny": true,
    "suppressImplicitAnyIndexErrors": true
  },

   "files": [
    "src/main.ts"
  ],

  "angularCompilerOptions": {
   "genDir": "aot",
   "skipMetadataEmit" : true
 },
 "exclude": [
        "node_modules",
        "bower_components",
        "typings/main",
        "typings/main.d.ts"
    ]
}

Compile main-aot.ts files with tsc and tsconfig-compile-aot.json, again as es2015 modules and generate your js files. On compiling I get my js files
I executed the command

 tsc src/main.ts

rollup-config.js

import rollup      from 'rollup'
import nodeResolve from 'rollup-plugin-node-resolve'
import commonjs    from 'rollup-plugin-commonjs';
import uglify      from 'rollup-plugin-uglify'

export default {
  entry: 'src/main.js',
  dest: 'bundle.js', // output a single application bundle
  sourceMap: false,
  format: 'iife',
  onwarn: function(warning) {
    // Skip certain warnings
    // should intercept ... but doesn't in some rollup versions
    if ( warning.code === 'THIS_IS_UNDEFINED' ) { return; }
    // console.warn everything else
    console.warn( warning.message );
  },
  plugins: [
      nodeResolve({jsnext: true, module: true}),
      commonjs({
        include: 'node_modules/rxjs/**',
      }),
      uglify()
  ]
}

After that I executed, the below command
node_modules/.bin/rollup -c rollup-config.js

and then on executing npm run lite,I get the error .

Body:
You need to add following code in your master page:

window.module = {
    id: 'foo',
    exports: []
}


问:
Add number of days to a date
I want to add  number of days to current date:
I am using following code:

```<code>$i=30;
echo $date = strtotime(date("Y-m-d", strtotime($date)) . " +".$i."days");
</code>```

But instead of getting proper date i am getting this:
2592000

Please suggest.

答:
```<code>//Set time zone
date_default_timezone_set("asia/kolkata");
$pastdate='2016-07-20';
$addYear=1;
$addMonth=3;
$addWeek=2;
$addDays=5;
$newdate=date('Y-m-d', strtotime($pastdate.' +'.$addYear.' years +'.$addMonth. ' months +'.$addWeek.' weeks +'.$addDays.' days'));
echo $newdate;
</code>```

Title: Add number of days to a date

Body:
I want to add  number of days to current date:
I am using following code:

$i=30;
echo $date = strtotime(date("Y-m-d", strtotime($date)) . " +".$i."days");

But instead of getting proper date i am getting this:
2592000

Please suggest.


问:
Create a single Dictionary from a Nested Dictionary to Update MySQLdb
I'm new to python and have run into an issue when trying to insert data from a nested dictionary into a MySQLdb. I have a dictionary that looks something like this, but much longer and can be variable in length.

```<code>d = {
    'Object_a': {
        'parameter_1': {
            'Cost': 12.00,
            'Markup': 23.4555
        },
        'parameter_2': {
            'Cost': 45.22,
            'Markup': 11.222,
            'Height': 44.33
        }
    },
    'Object_b': {
        'parameter_3': {
            'Length': 12.00,
            'Width': 23.4555
        },
        'parameter_1': {
            'Cost': 1.12,
            'Area': 4,
            'Volume': 16.72
        }
    }
}
</code>```

I have been searching everywhere for a way to manipulate a nested dictionary into the form below. (I didn't know how to do a table so it's in csv style, sorry)

```<code>Object, Parameter, Cost, Markup, Height, Length, Width, Area, Volume
Object_a, parameter_1, 12.00, 23.4555, , , , , ,
Object_a, parameter_2, 45.22, 11.222, 44.33, , , , ,
Object_b, parameter_3, , , , 12.00, 23.4555, ,
Object_b, parameter_2, 1.12, , , , , 4, 16.72
</code>```

My Code to input the data into an SQL database is shown below:

Currently it takes a database name, table name, and dictionary given to it in another part of the program. Currently this checks if a table is created and if not will create one, if there is one created it will check which columns exist, if any are new it will add them and insert values into both new and existing columns.

I'm not so worried about any of this code, but my main concern is having no idea on how to pass one dictionary to this function to get to the desired form, or how to iterate through the above nested dictionary.

```<code>def tablecreate(cursor, tablename, dict):

    # Creates a list of keys to use as column names
    cols = list(dict.keys())

    # If warning occurs, no table exists so create one
    try:
        sqlcheck = "SELECT 1 FROM {} LIMIT 1".format(tablename)
        cursor.execute(sqlcheck)
    except:
        sql = "CREATE TABLE IF NOT EXISTS %s (ID INT AUTO_INCREMENT, PRIMARY
               KEY(ID))" %(tablename)
        cursor.execute(sql)
        # Creating the rest of the columns
        for i in range(0, len(cols)):
            sql = "ALTER TABLE %s ADD COLUMN %s VARCHAR (50)" % (tablename,
                  cols[i])
            cursor.execute(sql)

    #Creates a list of new columns to be inserted into Table

    sql = "SELECT COLUMN_NAME FROM information_schema.columns WHERE
           TABLE_NAME ='%s'" % (tablename)
    cursor.execute(sql)
    a = cursor.fetchall()
    b=[element for tupl in a for element in tupl]
    new_cols = [x for x in cols if x not in b]
    print (new_cols)

    for i in range(0, len(new_cols)):
        sql = "ALTER TABLE %s ADD COLUMN %s VARCHAR (50)" % (tablename,
               new_cols[i])
        cursor.execute(sql)

    # Inserting values into the created columns
    placeholders = ', '.join(['%s'] *len(dict))
    columns = ', '.join(dict.keys())
    sql = "INSERT INTO %s (%s) VALUES (%s)" % (tablename, columns,
           placeholders)
    cursor.execute(sql, dict.values())
</code>```

答:
It was not clear from your question what form you wanted the data in, but for manipulating the data, pandas is quite good at this sort of thing:

Code:

```<code>import pandas as pd

objs = []
for obj in d:
    for param in d[obj]:
        x = {
            'Object': obj,
            'Parameter': param,
        }
        x.update(d[obj][param])
        objs.append(x)
df = pd.DataFrame(objs).fillna('').set_index(['Object', 'Parameter'])
print(df)
print(df.to_csv())
</code>```

Test Data:

```<code>d = {
    'Object_a': {
        'parameter_1': {
            'Cost': 12.00,
            'Markup': 23.4555
        },
        'parameter_2': {
            'Cost': 45.22,
            'Markup': 11.222,
            'Height': 44.33
        }
    },
    'Object_b': {
        'parameter_3': {
            'Length': 12.00,
            'Width': 23.4555
        },
        'parameter_1': {
            'Cost': 1.12,
            'Area': 4,
            'Volume': 16.72
        }
    }
}
</code>```

DataFrame Results:

```<code>                     Area   Cost Height Length   Markup Volume    Width
Object   Parameter
Object_a parameter_2       45.22  44.33          11.222
         parameter_1          12                23.4555
Object_b parameter_3                        12                  23.4555
         parameter_1    4   1.12                         16.72
</code>```

CSV Results:

```<code>Object,Parameter,Area,Cost,Height,Length,Markup,Volume,Width
Object_a,parameter_2,,45.22,44.33,,11.222,,
Object_a,parameter_1,,12.0,,,23.4555,,
Object_b,parameter_3,,,,12.0,,,23.4555
Object_b,parameter_1,4.0,1.12,,,,16.72,
</code>```

Body:
I'm new to python and have run into an issue when trying to insert data from a nested dictionary into a MySQLdb. I have a dictionary that looks something like this, but much longer and can be variable in length.

d = {
    'Object_a': {
        'parameter_1': {
            'Cost': 12.00,
            'Markup': 23.4555
        },
        'parameter_2': {
            'Cost': 45.22,
            'Markup': 11.222,
            'Height': 44.33
        }
    },
    'Object_b': {
        'parameter_3': {
            'Length': 12.00,
            'Width': 23.4555
        },
        'parameter_1': {
            'Cost': 1.12,
            'Area': 4,
            'Volume': 16.72
        }
    }
}

I have been searching everywhere for a way to manipulate a nested dictionary into the form below. (I didn't know how to do a table so it's in csv style, sorry)

Object, Parameter, Cost, Markup, Height, Length, Width, Area, Volume
Object_a, parameter_1, 12.00, 23.4555, , , , , ,
Object_a, parameter_2, 45.22, 11.222, 44.33, , , , ,
Object_b, parameter_3, , , , 12.00, 23.4555, ,
Object_b, parameter_2, 1.12, , , , , 4, 16.72

My Code to input the data into an SQL database is shown below:

Currently it takes a database name, table name, and dictionary given to it in another part of the program. Currently this checks if a table is created and if not will create one, if there is one created it will check which columns exist, if any are new it will add them and insert values into both new and existing columns.

I'm not so worried about any of this code, but my main concern is having no idea on how to pass one dictionary to this function to get to the desired form, or how to iterate through the above nested dictionary.

def tablecreate(cursor, tablename, dict):

    # Creates a list of keys to use as column names
    cols = list(dict.keys())

    # If warning occurs, no table exists so create one
    try:
        sqlcheck = "SELECT 1 FROM {} LIMIT 1".format(tablename)
        cursor.execute(sqlcheck)
    except:
        sql = "CREATE TABLE IF NOT EXISTS %s (ID INT AUTO_INCREMENT, PRIMARY
               KEY(ID))" %(tablename)
        cursor.execute(sql)
        # Creating the rest of the columns
        for i in range(0, len(cols)):
            sql = "ALTER TABLE %s ADD COLUMN %s VARCHAR (50)" % (tablename,
                  cols[i])
            cursor.execute(sql)

    #Creates a list of new columns to be inserted into Table

    sql = "SELECT COLUMN_NAME FROM information_schema.columns WHERE
           TABLE_NAME ='%s'" % (tablename)
    cursor.execute(sql)
    a = cursor.fetchall()
    b=[element for tupl in a for element in tupl]
    new_cols = [x for x in cols if x not in b]
    print (new_cols)

    for i in range(0, len(new_cols)):
        sql = "ALTER TABLE %s ADD COLUMN %s VARCHAR (50)" % (tablename,
               new_cols[i])
        cursor.execute(sql)

    # Inserting values into the created columns
    placeholders = ', '.join(['%s'] *len(dict))
    columns = ', '.join(dict.keys())
    sql = "INSERT INTO %s (%s) VALUES (%s)" % (tablename, columns,
           placeholders)
    cursor.execute(sql, dict.values())

Body:
It was not clear from your question what form you wanted the data in, but for manipulating the data, pandas is quite good at this sort of thing:

Code:

import pandas as pd

objs = []
for obj in d:
    for param in d[obj]:
        x = {
            'Object': obj,
            'Parameter': param,
        }
        x.update(d[obj][param])
        objs.append(x)
df = pd.DataFrame(objs).fillna('').set_index(['Object', 'Parameter'])
print(df)
print(df.to_csv())

Test Data:

d = {
    'Object_a': {
        'parameter_1': {
            'Cost': 12.00,
            'Markup': 23.4555
        },
        'parameter_2': {
            'Cost': 45.22,
            'Markup': 11.222,
            'Height': 44.33
        }
    },
    'Object_b': {
        'parameter_3': {
            'Length': 12.00,
            'Width': 23.4555
        },
        'parameter_1': {
            'Cost': 1.12,
            'Area': 4,
            'Volume': 16.72
        }
    }
}

DataFrame Results:

                     Area   Cost Height Length   Markup Volume    Width
Object   Parameter
Object_a parameter_2       45.22  44.33          11.222
         parameter_1          12                23.4555
Object_b parameter_3                        12                  23.4555
         parameter_1    4   1.12                         16.72

CSV Results:

Object,Parameter,Area,Cost,Height,Length,Markup,Volume,Width
Object_a,parameter_2,,45.22,44.33,,11.222,,
Object_a,parameter_1,,12.0,,,23.4555,,
Object_b,parameter_3,,,,12.0,,,23.4555
Object_b,parameter_1,4.0,1.12,,,,16.72,


问:
Android READ_EXTERNAL_STORAGE permission not working
I'm trying to create a simple app that can get an image from the Gallery app and display it on an imageButton. I'm testing with API 21 on a phone running Android 5.0.1. Unfortunately, no matter what I try I keep getting a security error - even when I specify the permissions.

My code for getting retrieving the image is:

```<code>@Override
protected void onActivityResult(int requestCode, int resultCode, Intent imageReturnedIntent){
    super.onActivityResult(requestCode, resultCode, imageReturnedIntent);

    switch(requestCode){
        case PICK_IMAGE_REQUEST:
            if(resultCode == RESULT_OK && imageReturnedIntent != null && imageReturnedIntent.getData() != null) {
                Uri uri = imageReturnedIntent.getData();
                try {
                    Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), uri);
                    // Log.d(TAG, String.valueOf(bitmap));
                    ImageButton ib = (ImageButton) findViewById(R.id.inputImg);
                    ib.setImageBitmap(bitmap);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            break;
    }
}
</code>```

The code works when I try to select an image from Dropbox, but when I select an image from gallery, I get

```<code>java.lang.SecurityException: Permission Denial: reading com.android.providers.media.MediaProvider uri content://media/external/images/media/35634 from pid=25240, uid=10070 requires android.permission.READ_EXTERNAL_STORAGE, or grantUriPermission()
</code>```

I made the use-permission tag for READ_EXTERNAL_STORAGE a child of manifest:

```<code><?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
package="[REDACTED]">

    <uses-sdk
    android:minSdkVersion="14"
    android:targetSdkVersion="23" />

    <uses-permission tools:node="replace" android:name="android.permission.READ_EXTERNAL_STORAGE" android:maxSdkVersion="18" />

    <application>
        [REDACTED]
    </application>

</manifest>
</code>```

I've searched high and low on other posts, but still can't seem to figure out why I'm still getting this pesky error.

答:
In addition to adding the below in AndroidManifest.xml

<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
```

we also need to request permission in the activity for the app to actually have access to external storage. https://developer.android.com/training/permissions/requesting.html

Body:
I'm trying to create a simple app that can get an image from the Gallery app and display it on an imageButton. I'm testing with API 21 on a phone running Android 5.0.1. Unfortunately, no matter what I try I keep getting a security error - even when I specify the permissions.

My code for getting retrieving the image is:

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent imageReturnedIntent){
    super.onActivityResult(requestCode, resultCode, imageReturnedIntent);

    switch(requestCode){
        case PICK_IMAGE_REQUEST:
            if(resultCode == RESULT_OK && imageReturnedIntent != null && imageReturnedIntent.getData() != null) {
                Uri uri = imageReturnedIntent.getData();
                try {
                    Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), uri);
                    // Log.d(TAG, String.valueOf(bitmap));
                    ImageButton ib = (ImageButton) findViewById(R.id.inputImg);
                    ib.setImageBitmap(bitmap);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            break;
    }
}

The code works when I try to select an image from Dropbox, but when I select an image from gallery, I get

java.lang.SecurityException: Permission Denial: reading com.android.providers.media.MediaProvider uri content://media/external/images/media/35634 from pid=25240, uid=10070 requires android.permission.READ_EXTERNAL_STORAGE, or grantUriPermission()

I made the use-permission tag for READ_EXTERNAL_STORAGE a child of manifest:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
package="[REDACTED]">

    <uses-sdk
    android:minSdkVersion="14"
    android:targetSdkVersion="23" />

    <uses-permission tools:node="replace" android:name="android.permission.READ_EXTERNAL_STORAGE" android:maxSdkVersion="18" />

    <application>
        [REDACTED]
    </application>

</manifest>

I've searched high and low on other posts, but still can't seem to figure out why I'm still getting this pesky error.

Body:
In addition to adding the below in AndroidManifest.xml

<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

we also need to request permission in the activity for the app to actually have access to external storage. https://developer.android.com/training/permissions/requesting.html