问:
Builder design pattern: Why do we need a Director?
Recently I've come across the Builder design pattern. It seems that different authors use "Builder pattern" to refer to different flavours, so let me describe the pattern I'm asking about.

We have an algorithm for creating products, i.e., objects of different types.  At a sufficiently high level of abstraction the algorithm is the same for all product types, but each product type requires a different implementation of each of the algorithm's abstract steps.  For example, we might have the following cake-baking algorithm:

```<code> 1. Add liquids.
 2. Mix well.
 3. Add dry ingredients.
 4. Mix well.
 5. Pour batter into baking pan.
 6. Bake.
 7. Return baked cake.
</code>```

Different cakes would require different implementations of these steps, i.e., what liquids/dry ingredients to use, what speed to mix at, how long to bake, etc.

The pattern says to do it like so.  For each product we create a concrete builder class with an implementation for each of the above steps. All of these classes are derived from an abstract builder base class, which is essentially an interface.  So, for example, we will have an abstract base class CakeBaker with pure virtual methods AddLiquid(), MixLiquids(), etc.  The concrete cake bakers will be concrete subclasses, e.g.,

```<code>class ChocolateCakeBaker : public CakeBaker {
public:
   virtual void AddLiquids()
   {
        // Add three eggs and 1 cup of cream
   }

   virtual void AddDryIngredients()
   {
       // Add 2 cups flour, 1 cup sugar, 3 tbsp cocoa powder,
       // 2 bars ground chocolate, 2 tsp baking powder
   }
      ...
      ...
};
</code>```

The LemonCitrusCakeBaker would also be a subclass of CakeBaker, but would use different ingredients and quantities in its methods.

The different cake types will similarly be subclasses of an abstract Cake base class.

Finally, we have a class to implement the abstract algorithm.  This is the director.  In the bakery example we might call it ExecutiveBaker.  This class would accept (from the client) a concrete builder object and use its methods in order to create and return the desired product.

Here's my question.  Why do we need the director to be separate from the abstract builder?  Why not roll them into a single builder abstract base class, making the original abstract builder's public methods protected (and the concrete subclasses override these as before).

答: I agree with you. I think that the other approach is that the CakeBaker should have a GetCake() method which returns a cake(Cake class) and MakeCake() method where the algorithm will run. That's fine  but on other hand there is a responsible separation there. Consider abstract builder and specific bulders as builders of a cake parts only and Director as manager or designer whose responsibility is to assemble and produce a cake.</p>

Body:
Recently I've come across the Builder design pattern. It seems that different authors use "Builder pattern" to refer to different flavours, so let me describe the pattern I'm asking about.

We have an algorithm for creating products, i.e., objects of different types.  At a sufficiently high level of abstraction the algorithm is the same for all product types, but each product type requires a different implementation of each of the algorithm's abstract steps.  For example, we might have the following cake-baking algorithm:

 1. Add liquids.
 2. Mix well.
 3. Add dry ingredients.
 4. Mix well.
 5. Pour batter into baking pan.
 6. Bake.
 7. Return baked cake.

Different cakes would require different implementations of these steps, i.e., what liquids/dry ingredients to use, what speed to mix at, how long to bake, etc.

The pattern says to do it like so.  For each product we create a concrete builder class with an implementation for each of the above steps. All of these classes are derived from an abstract builder base class, which is essentially an interface.  So, for example, we will have an abstract base class CakeBaker with pure virtual methods AddLiquid(), MixLiquids(), etc.  The concrete cake bakers will be concrete subclasses, e.g.,

class ChocolateCakeBaker : public CakeBaker {
public:
   virtual void AddLiquids()
   {
        // Add three eggs and 1 cup of cream
   }

   virtual void AddDryIngredients()
   {
       // Add 2 cups flour, 1 cup sugar, 3 tbsp cocoa powder,
       // 2 bars ground chocolate, 2 tsp baking powder
   }
      ...
      ...
};

The LemonCitrusCakeBaker would also be a subclass of CakeBaker, but would use different ingredients and quantities in its methods.

The different cake types will similarly be subclasses of an abstract Cake base class.

Finally, we have a class to implement the abstract algorithm.  This is the director.  In the bakery example we might call it ExecutiveBaker.  This class would accept (from the client) a concrete builder object and use its methods in order to create and return the desired product.

Here's my question.  Why do we need the director to be separate from the abstract builder?  Why not roll them into a single builder abstract base class, making the original abstract builder's public methods protected (and the concrete subclasses override these as before).


来源: stackexchange

问:
Build fails on server if SpecificVersion is not set to false
Visual studio 2015 TFS.

I have come across a scenarios where if below mentioned property is not set to false and if team takes latest code and builds locally... no one get error...build is successful for all.
However, When we build on the server, it fails.

```<code>Proprty name: <SpecificVersion>False</SpecificVersion>
File name: Any cs project file
</code>```

edit: This property pertains to the dll that we reference in the project.

How this can be avoided ? Can we use any settings or tool in TFS that will validate all such settings, trigger the build on checks in and send notification if build fails?

答:
After setting the <SpecificVersion> value with true, you need to make sure the version of your server dll and local dll is the same.

If you want your local dll be used for TFS server build, the simplest way is checking that dll in version control and download it in build agent working folder.

If you want your local dll be used for TFS server build, you need to modify the version info of that dll including PublicKeyToken in the XX.csproj file. This could be done through a powershell script before msbuild in your XAML build definition.

ContentLicense: CC BY-SA 3.0

Body:
Visual studio 2015 TFS.

I have come across a scenarios where if below mentioned property is not set to false and if team takes latest code and builds locally... no one get error...build is successful for all.
However, When we build on the server, it fails.

Proprty name: <SpecificVersion>False</SpecificVersion>
File name: Any cs project file

edit: This property pertains to the dll that we reference in the project.

How this can be avoided ? Can we use any settings or tool in TFS that will validate all such settings, trigger the build on checks in and send notification if build fails?


问:
How to add EditText input to custom model using data binding adapter?
This is my data binding adapter:

```<code>@BindingAdapter("taskMinutes")
public static void taskMinutes(@NonNull TextView view, @NonNull Task task) {
    if (task.getDueDate() == null) {
        view.setText("");
        return;
    }
    view.setText(String.valueOf(DateUtils.getDateMinutes(task.getDueDate())));
}
</code>```

And in xml:

```<code>app:taskMinutes="@{task}"
</code>```

And minutes show in EditText normally but didn't add to task.dueDate.

But how can I add adapter for add new input from EditText filed to task.dueDate?

答: Please take a look on two-way data binding. You have to define an InversBindingAdapter.</p>

Body:
This is my data binding adapter:

@BindingAdapter("taskMinutes")
public static void taskMinutes(@NonNull TextView view, @NonNull Task task) {
    if (task.getDueDate() == null) {
        view.setText("");
        return;
    }
    view.setText(String.valueOf(DateUtils.getDateMinutes(task.getDueDate())));
}

And in xml:

app:taskMinutes="@{task}"

And minutes show in EditText normally but didn't add to task.dueDate.

But how can I add adapter for add new input from EditText filed to task.dueDate?


问:
z-index issue in ie
i know this issue is well documented but i cant find a working solution from what ive been reading. I have a pretty large site and i want a div to sit ontop of everything else on the site. now ive tried giving the div "position:absolute; z-index:99999;", this will work in everything apart from ie. How can i do this in ie?

答:
You can try:

```<code>position: fixed; z-index: 9999;
</code>```

This will make the div to appear on top of the others. (and follow as you scroll down)

ContentLicense: CC BY-SA 2.5

Title: z-index issue in ie

Body:
You can try:

position: fixed; z-index: 9999;

This will make the div to appear on top of the others. (and follow as you scroll down)


问:
PreferenceFragmentCompat requires preferenceTheme to be set
With the new PreferenceFragmentCompat from the v7 Preference Support Library: http://developer.android.com/tools/support-library/features.html#v7-preference, I get this error

```<code>E  java.lang.IllegalStateException: Must specify preferenceTheme in theme
E      at android.support.v7.preference.PreferenceFragmentCompat.onCreate(PreferenceFragmentCompat.java:202)
</code>```

What theme should be set?

Update: I have tried using

<item name="preferenceTheme">@style/PreferenceThemeOverlay</item>

as suggested by @Bogato but it doesn't look right and looks very Holo even on Lollipop.

Support library:

Native preferences:

答:
Solution that worked for me in API 25. I had this default theme:

```<code><style name="AppTheme.NoActionBar" parent="Theme.AppCompat.Light.NoActionBar">
    <item name="colorPrimary">@color/colorPrimary</item>
    <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
    <item name="colorAccent">@color/colorAccent</item>
</style>
</code>```

And added this line to it

```<code><style name="AppTheme.NoActionBar" parent="Theme.AppCompat.Light.NoActionBar">
    <item name="colorPrimary">@color/colorPrimary</item>
    <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
    <item name="colorAccent">@color/colorAccent</item>
    <item name="preferenceTheme">@style/PreferenceThemeOverlay</item>
</style>
</code>```

PreferenceThemeOverlay was was already defined, I didn't have to include it.
It worked on Android 4.x and 5.x devices of my own

Body:
With the new PreferenceFragmentCompat from the v7 Preference Support Library: http://developer.android.com/tools/support-library/features.html#v7-preference, I get this error

E  java.lang.IllegalStateException: Must specify preferenceTheme in theme
E      at android.support.v7.preference.PreferenceFragmentCompat.onCreate(PreferenceFragmentCompat.java:202)

What theme should be set?

Update: I have tried using

<item name="preferenceTheme">@style/PreferenceThemeOverlay</item>

as suggested by @Bogato but it doesn't look right and looks very Holo even on Lollipop.

Support library:

Native preferences:

Body:
Solution that worked for me in API 25. I had this default theme:

<style name="AppTheme.NoActionBar" parent="Theme.AppCompat.Light.NoActionBar">
    <item name="colorPrimary">@color/colorPrimary</item>
    <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
    <item name="colorAccent">@color/colorAccent</item>
</style>

And added this line to it

<style name="AppTheme.NoActionBar" parent="Theme.AppCompat.Light.NoActionBar">
    <item name="colorPrimary">@color/colorPrimary</item>
    <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
    <item name="colorAccent">@color/colorAccent</item>
    <item name="preferenceTheme">@style/PreferenceThemeOverlay</item>
</style>

PreferenceThemeOverlay was was already defined, I didn't have to include it.
It worked on Android 4.x and 5.x devices of my own


问:
Simple web crawler very slow
I have built a very simple web crawler to crawl ~100 small json files in the URL below. The issue is that the crawler takes more than an hour to complete. I find that hard to understand given how small the json files are. Am I doing something fundamentally wrong here?</p>

```<code>def get_senate_vote(vote):
    URL = 'https://www.govtrack.us/data/congress/113/votes/2013/s%d/data.json' % vote
    response = requests.get(URL)
    json_data = json.loads(response.text)
    return json_data

def get_all_votes():
    all_senate_votes = []
    URL = "http://www.govtrack.us/data/congress/113/votes/2013"
    response = requests.get(URL)
    root = html.fromstring(response.content)
    for a in root.xpath('/html/body/pre/a'):
        link = a.xpath('text()')[0].strip()
        if link[0] == 's':
            vote = int(link[1:-1])
            try:
                vote_json = get_senate_vote(vote)
            except:
                return all_senate_votes
            all_senate_votes.append(vote_json)

    return all_senate_votes

vote_data = get_all_votes()
</code>```

答:
If you are using python 3.x and you are crawling multiple sites, for even better performances I offer warmly to you to use the aiohttp module, which implements the asynchronous principles.
For example:

```<code>import aiohttp
import asyncio

sites = ['url_1', 'url_2']
results = []

def save_reponse(result):
    site_content = result.result()
    results.append(site_content)

async def crawl_site(site):
    async with aiohttp.ClientSession() as session:
        async with session.get(site) as resp:
            resp = await resp.text()
            return resp

tasks = []
for site in sites:
    task = asyncio.ensure_future(crawl_site(site))
    task.add_done_callback(save_reponse)
    tasks.append(task)
all_tasks = asyncio.gather(*tasks)

loop = asyncio.get_event_loop()
loop.run_until_complete(all_tasks)
loop.close()

print(results)
</code>```

For more reading about aiohttp.

Title: Simple web crawler very slow

Body:
I have built a very simple web crawler to crawl ~100 small json files in the URL below. The issue is that the crawler takes more than an hour to complete. I find that hard to understand given how small the json files are. Am I doing something fundamentally wrong here?

def get_senate_vote(vote):
    URL = 'https://www.govtrack.us/data/congress/113/votes/2013/s%d/data.json' % vote
    response = requests.get(URL)
    json_data = json.loads(response.text)
    return json_data

def get_all_votes():
    all_senate_votes = []
    URL = "http://www.govtrack.us/data/congress/113/votes/2013"
    response = requests.get(URL)
    root = html.fromstring(response.content)
    for a in root.xpath('/html/body/pre/a'):
        link = a.xpath('text()')[0].strip()
        if link[0] == 's':
            vote = int(link[1:-1])
            try:
                vote_json = get_senate_vote(vote)
            except:
                return all_senate_votes
            all_senate_votes.append(vote_json)

    return all_senate_votes

vote_data = get_all_votes()

Body:
If you are using python 3.x and you are crawling multiple sites, for even better performances I offer warmly to you to use the aiohttp module, which implements the asynchronous principles.
For example:

import aiohttp
import asyncio

sites = ['url_1', 'url_2']
results = []

def save_reponse(result):
    site_content = result.result()
    results.append(site_content)

async def crawl_site(site):
    async with aiohttp.ClientSession() as session:
        async with session.get(site) as resp:
            resp = await resp.text()
            return resp

tasks = []
for site in sites:
    task = asyncio.ensure_future(crawl_site(site))
    task.add_done_callback(save_reponse)
    tasks.append(task)
all_tasks = asyncio.gather(*tasks)

loop = asyncio.get_event_loop()
loop.run_until_complete(all_tasks)
loop.close()

print(results)

For more reading about aiohttp.


问:
How to load one page from another on select of option from drop down?
I have a drop down list on click of the option I want to redirect to another page in same tab according to type selected.

I want to redirect to, like if user selects ssgt then need to go to ssgt.php if selects tsgt then tsgt.php and like that for msgt.

Is it can be done with link inside? I tried but did not work.

```<code><!doctype html>
<html>
<head>
   <meta charset="utf-8">
   <title>MCQ Questions</title>
</head>
<body>
   <form method="post" enctype="multipart/form-data">
      Select rank :
      <select name="type" id="type" onchange="this.form.submit()">
         <option value="1">SSgt</option>
         <option value="2">TSgt</option>
         <option value="3">MSgt</option>
      </select>
      <br><br>
      <?php
         if(isset($_POST['type'])) {
            if(strcmp($_POST['type'],"1") == 0) {
            }
         }
      ?>
   </form>
</body>
</html>
</code>```

Please help.. Thank you.

EDIT:

```<code>   <!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>MCQ Questions</title>

</head>
<body>

<form method="post" action="mcq.php" enctype="multipart/form-data">
    <?php
    if(isset($_POST['type']))
    {

        if(strcmp($_POST['type'],"1") == 0)
        {
            header("Location: ssgt.php");
        }
        elseif(strcmp($_POST['type'],"2" == 0))
        {
            header("Location: tsgt.php");
        }
        elseif(strcmp($_POST['type'],"3" == 0))
        {
            header("Location: msgt.php");
        }
    }

    ?>

    <h2>Lets add a question, Select a rank for which you want to add a question.</h2>
<br><br>
Select rank :

<select name="type" id="type"  onchange="this.form.submit()">

    <option value="1">SSgt</option>
<option value="2">TSgt</option>
<option value="3">MSgt</option>
</select>

</form>
</body>
</html>
</code>```

I tried this way so for ssgt, and tsgt respective pages are getting open but for msgt the page of tsgt.php is getting open.

答:
You can do this like below;

```<code>if(isset($_POST['type']))
{
    if(strcmp($_POST['type'],"1") == 0)
    {
       header("Location: ssgt.php")
    } else {
       header("Location: msgt.php")
    }

}
?>
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>MCQ Questions</title>

</head>
<body>

<form method="post" enctype="multipart/form-data">

Select rank :

<select name="type" id="type" onchange="this.form.submit()">

    <option value="1">SSgt</option>
<option value="2">TSgt</option>
<option value="3">MSgt</option>
</select>

<br><br>

</form>
</body>
</html>
</code>```

You can add so many condition as you want as per your drop down list.

Thanks

Body:
I have a drop down list on click of the option I want to redirect to another page in same tab according to type selected.

I want to redirect to, like if user selects ssgt then need to go to ssgt.php if selects tsgt then tsgt.php and like that for msgt.

Is it can be done with link inside? I tried but did not work.

<!doctype html>

   <meta charset="utf-8">
   <title>MCQ Questions</title>

   <form method="post" enctype="multipart/form-data">
      Select rank :
      <select name="type" id="type" onchange="this.form.submit()">
         <option value="1">SSgt</option>
         <option value="2">TSgt</option>
         <option value="3">MSgt</option>
      </select>

      <?php
         if(isset($_POST['type'])) {
            if(strcmp($_POST['type'],"1") == 0) {
            }
         }
      ?>
   </form>

Please help.. Thank you.

EDIT:

   <!doctype html>

<meta charset="utf-8">
<title>MCQ Questions</title>

<form method="post" action="mcq.php" enctype="multipart/form-data">
    <?php
    if(isset($_POST['type']))
    {

        if(strcmp($_POST['type'],"1") == 0)
        {
            header("Location: ssgt.php");
        }
        elseif(strcmp($_POST['type'],"2" == 0))
        {
            header("Location: tsgt.php");
        }
        elseif(strcmp($_POST['type'],"3" == 0))
        {
            header("Location: msgt.php");
        }
    }

    ?>

Lets add a question, Select a rank for which you want to add a question.

Select rank :

<select name="type" id="type"  onchange="this.form.submit()">

    <option value="1">SSgt</option>
<option value="2">TSgt</option>
<option value="3">MSgt</option>
</select>

</form>

I tried this way so for ssgt, and tsgt respective pages are getting open but for msgt the page of tsgt.php is getting open.

Body:
You can do this like below;

if(isset($_POST['type']))
{
    if(strcmp($_POST['type'],"1") == 0)
    {
       header("Location: ssgt.php")
    } else {
       header("Location: msgt.php")
    }

}
?>
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>MCQ Questions</title>

</head>
<body>

<form method="post" enctype="multipart/form-data">

Select rank :

<select name="type" id="type" onchange="this.form.submit()">

    <option value="1">SSgt</option>
<option value="2">TSgt</option>
<option value="3">MSgt</option>
</select>

<br><br>

</form>
</body>
</html>

You can add so many condition as you want as per your drop down list.

Thanks


问:
Using bind variables in Solr
I am trying to load a huge amount of data from a Oracle database to Solr, and I see in the oracle console that Solr is not using any kind of "bind variables" in a query like:

```<code>select field1, field2, field3 from table where id = myId
</code>```

Where myId is the result of a iteration. Oracle is processing querys as they had no relation between them. Are there any way to force Solr to use bind variables in solr? Thanks !!

答: Maybe you could try to set CURSOR_SHARING=FORCE for session or system.</p>

Title: Using bind variables in Solr

Body:
I am trying to load a huge amount of data from a Oracle database to Solr, and I see in the oracle console that Solr is not using any kind of "bind variables" in a query like:

select field1, field2, field3 from table where id = myId

Where myId is the result of a iteration. Oracle is processing querys as they had no relation between them. Are there any way to force Solr to use bind variables in solr? Thanks !!


问:
HAProxy using even/odd or regex in uri
I would like to set some rules about query parameter URI, based on odd/even for example:

```<code>$ curl -I 'localhost:10001/test/?id=1' #  use one backend
$ curl -I 'localhost:10001/test/?id=2' #  user another back-end
</code>```

I can get the id number using an ACL like:

```<code>acl has_id  urlp(id) -m bool
</code>```

But I can't use even function, I didn't understand the docs.

http://cbonte.github.io/haproxy-dconv/1.7/configuration.html#7.3.1-odd

Also, I'm able to compare the id with some number, like this:

```<code>acl has_id  urlp(id) -m int ge 666
</code>```

But can't see if is odd or even.

I also tried to use path_reg but this not works with uri, only with path.

答:
Worked with:

acl is_odd urlp_val(id) odd -m found

Using urlp_val the value was converted to integer \m/

Title: HAProxy using even/odd or regex in uri

Body:
I would like to set some rules about query parameter URI, based on odd/even for example:

$ curl -I 'localhost:10001/test/?id=1' #  use one backend
$ curl -I 'localhost:10001/test/?id=2' #  user another back-end

I can get the id number using an ACL like:

acl has_id  urlp(id) -m bool

But I can't use even function, I didn't understand the docs.

http://cbonte.github.io/haproxy-dconv/1.7/configuration.html#7.3.1-odd

Also, I'm able to compare the id with some number, like this:

acl has_id  urlp(id) -m int ge 666

But can't see if is odd or even.

I also tried to use path_reg but this not works with uri, only with path.


问:
When I paste text, it can't get height of text
When I paste text, I got wrong height of text. It don't count it. I can get only height of first line. However, if I click return key, each line of text like "Software\nis\nawesome", it work well. here is code:

```<code>let font = UIFont(name: "HelveticaNeue", size: 18)!
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.alignment = .center
paragraphStyle.lineSpacing = 8

let textFontAttributes = [
     NSFontAttributeName: font,
     NSForegroundColorAttributeName: UIColor(red: 0.149, green: 0.149, blue: 0.145, alpha: 1.00),
     NSParagraphStyleAttributeName: paragraphStyle
     ] as [String : Any]

let string:NSString = NSString(string: self.txtView.text)
let size:CGSize = string.size(attributes: textFontAttributes)
print("size.height")
</code>```

But, when I did typing some text, I can get correct height of text.

How can I get correct height of text?

答:
put your code in

```<code>    func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
       let font = UIFont(name: "HelveticaNeue", size: 18)!
    let paragraphStyle = NSMutableParagraphStyle()
    paragraphStyle.alignment = .center
    paragraphStyle.lineSpacing = 8

    let textFontAttributes = [
         NSFontAttributeName: font,
         NSForegroundColorAttributeName: UIColor(red: 0.149, green: 0.149, blue: 0.145, alpha: 1.00),
         NSParagraphStyleAttributeName: paragraphStyle
         ] as [String : Any]

    let string:NSString = NSString(string: self.txtView.text)
    let size:CGSize = string.size(attributes: textFontAttributes)
    print("size.height")
    return true;
 }
</code>```

You can also use

```<code>func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
      let size = self.textView.sizeThatFits(CGSize(width: width_you_can_afford, height: CGFloat.greatestFiniteMagnitude))
}
</code>```

Body:
When I paste text, I got wrong height of text. It don't count it. I can get only height of first line. However, if I click return key, each line of text like "Software\nis\nawesome", it work well. here is code:

let font = UIFont(name: "HelveticaNeue", size: 18)!
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.alignment = .center
paragraphStyle.lineSpacing = 8

let textFontAttributes = [
     NSFontAttributeName: font,
     NSForegroundColorAttributeName: UIColor(red: 0.149, green: 0.149, blue: 0.145, alpha: 1.00),
     NSParagraphStyleAttributeName: paragraphStyle
     ] as [String : Any]

let string:NSString = NSString(string: self.txtView.text)
let size:CGSize = string.size(attributes: textFontAttributes)
print("size.height")

But, when I did typing some text, I can get correct height of text.

How can I get correct height of text?

Body:
put your code in

    func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
       let font = UIFont(name: "HelveticaNeue", size: 18)!
    let paragraphStyle = NSMutableParagraphStyle()
    paragraphStyle.alignment = .center
    paragraphStyle.lineSpacing = 8

    let textFontAttributes = [
         NSFontAttributeName: font,
         NSForegroundColorAttributeName: UIColor(red: 0.149, green: 0.149, blue: 0.145, alpha: 1.00),
         NSParagraphStyleAttributeName: paragraphStyle
         ] as [String : Any]

    let string:NSString = NSString(string: self.txtView.text)
    let size:CGSize = string.size(attributes: textFontAttributes)
    print("size.height")
    return true;
 }

You can also use

func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
      let size = self.textView.sizeThatFits(CGSize(width: width_you_can_afford, height: CGFloat.greatestFiniteMagnitude))
}


问:
Implementation of drawing from a set with non-uniform weights
I would like to discuss how to optimally implement the following:

Given a set of elements,

all of them are distinct. Call this input set N, it has size n. These element each have a weight. Now, you need to create a subset (R) of this N of size r, where r is smaller then or equal to n.
This subset, again, cannot contain repetitions. Every element of R needs to be randomly chosen from N, if an element has a higher weight, the chance of it being chosen needs to be higher. If the total weight of all element in N is W, then the chance that element i is chosen needs to be w_i/W.

One last detail is that the weights are prone to change, but only to increase, they cannot decrease.

I want a neat implementation for this. I am working in Java, but I am hoping to find some language agnostic properties or details (or even pseudo code) that are interesting.

Now, for my own solution: I create an Array List of the original set of elements. I make sure that the weights are natural numbers and I add them n times if the weight of the element is n. Then I shuffle the arraylist (collections.shuffle) and I keep on taking element from the shuffled list and adding them to a Java Set until the size of the set is r. If the weight of an element increases, it gets added some more times to the original array list. Shuffle again, make a new subset.

My implementation needs loads of memory and the shuffle thingy is also slower if the set becomes bigger. Is there a better idea out there?

答:
First, let's simplify it to drawing only one element, you calcualte

```<code>sum[-1] = 0
sum[i] = sum[i-1] + weight[i]
</code>```

Then, you simply draw a number r in range [0,sum), and do binary search for r. The range it falls on, is the number you draw.

This is O(n) time solution.

You can obviously do it for more elements, but you will have to remove elements you have chosen from the set, or to repeat until you chose a new item. Both solutions however decay to quadric complexity for large subset size :(

But, can we improve it to do better?

Yes. Use a binary search tree instead of array. The binary search tree is actually a variation of order statistics tree, where instead of storing #children(v), you store the sum of weights in each subtree. Other than that - that's basically remains the same as order statistics tree.

More information about the tree solution can be found as an answer to a similar question: Algorithm to shuffle an Array randomly based on different weights

Complexity of building the tree is O(nlogn), and each query + removal is O(logn), which gives you O(nlogn + klogn) = O(nlogn)

So, we have two options:

If k in o(logn) (little o here), prefer recreating array with O(n) time per each query. Otherwise, you should prefer (in terms of time complexity) O(nlogn) tree based solution.

In terms of space, both solutions are linear in amount of extra space needed.

This can be even done better, with a single pass. This is called weighted reservoir sampling. It's main drawback is instability due to numeric issues for large weights due to the exponent part (at least from my experience).

This solution runs in linear time, with O(1) extra space (if not including the output array of size k).

Body:
First, let's simplify it to drawing only one element, you calcualte

sum[-1] = 0
sum[i] = sum[i-1] + weight[i]

Then, you simply draw a number r in range [0,sum), and do binary search for r. The range it falls on, is the number you draw.

This is O(n) time solution.

You can obviously do it for more elements, but you will have to remove elements you have chosen from the set, or to repeat until you chose a new item. Both solutions however decay to quadric complexity for large subset size :(

But, can we improve it to do better?

Yes. Use a binary search tree instead of array. The binary search tree is actually a variation of order statistics tree, where instead of storing #children(v), you store the sum of weights in each subtree. Other than that - that's basically remains the same as order statistics tree.

More information about the tree solution can be found as an answer to a similar question: Algorithm to shuffle an Array randomly based on different weights

Complexity of building the tree is O(nlogn), and each query + removal is O(logn), which gives you O(nlogn + klogn) = O(nlogn)

So, we have two options:

If k in o(logn) (little o here), prefer recreating array with O(n) time per each query. Otherwise, you should prefer (in terms of time complexity) O(nlogn) tree based solution.

In terms of space, both solutions are linear in amount of extra space needed.

This can be even done better, with a single pass. This is called weighted reservoir sampling. It's main drawback is instability due to numeric issues for large weights due to the exponent part (at least from my experience).

This solution runs in linear time, with O(1) extra space (if not including the output array of size k).


问:
git_clone error message Assertion failed: git_atomic_get(&git__n_inits) > 0
When I tried to do git_clone() (using libgit2), this error message occured

Assertion failed: git_atomic_get(&git__n_inits) > 0, file C:\data\Install\Git\libgit2-0.25.1\src\global.c, line 199

My program is interrupted by Visual Studio:

R6010 - abort() has been called

There is my code :

```<code>git_repository *cloned_repo = NULL;

cout << all_urls.at(num).c_str() << " -> " << clone_to.at(num).c_str() << endl;

int error = git_clone(&cloned_repo, all_urls.at(num).c_str(),clone_to.at(num).c_str(), &clone_opts);

if (error != 0) {
    const git_error *err = giterr_last();

    cerr << "error in clone num " << num << " -> message :" << err->message << endl;
}

else cout << endl << "Clone " << num << " succesful" << "(from url : " << all_urls.at(num) << " " << "to path : " << clone_to.at(num) << ")" << endl;

git_repository_free(cloned_repo);
</code>```

I have properly set clone_opts (credentials), so I really do not know where is the problem. I have done git_clone() in different projects before, and I did it this way, but I hadn't had such errors before.

Thanks

答: I forgot to call the functions git_libgit2_init() and git_libgit2_shutdown() in this method. I called it in previous methods and I thought I don't have to do that also there.

Body:
When I tried to do git_clone() (using libgit2), this error message occured

Assertion failed: git_atomic_get(&git__n_inits) > 0, file C:\data\Install\Git\libgit2-0.25.1\src\global.c, line 199

My program is interrupted by Visual Studio:

R6010 - abort() has been called

There is my code :

git_repository *cloned_repo = NULL;

cout << all_urls.at(num).c_str() << " -> " << clone_to.at(num).c_str() << endl;

int error = git_clone(&cloned_repo, all_urls.at(num).c_str(),clone_to.at(num).c_str(), &clone_opts);

if (error != 0) {
    const git_error *err = giterr_last();

    cerr << "error in clone num " << num << " -> message :" << err->message << endl;
}

else cout << endl << "Clone " << num << " succesful" << "(from url : " << all_urls.at(num) << " " << "to path : " << clone_to.at(num) << ")" << endl;

git_repository_free(cloned_repo);

I have properly set clone_opts (credentials), so I really do not know where is the problem. I have done git_clone() in different projects before, and I did it this way, but I hadn't had such errors before.

Thanks


问:
how to inspect jquery code on chrome developer tools?
I use web developer tools to inspect html and subsequently see the css that is attached to the html element. This is proving to be a great process for learning from other websites (and the debugging my own)

Is there a way to inspect the javascript as well? So when I select the element, to be able to see the javascript related to the element?

答:
I had the same problem and have been wandering a bit until I found how to do it on Chrome:

1. Open the Inspector Ctrl + Shift + i

2. Select the element that you would like to inspect

3. Click on the Event Listeners tab

4. Click on the link next to the event listener you would like to check

5. Click on Pretty Print (Symbolized as {} at the bottom of the window)


问:
SimpleXML parser error: "Huge input lookup"
I am using PHP for the first time. I am getting the following error on running the PHP file:

```<code>PHP Warning:  simplexml_load_string(): Entity: line 35909: parser error : internal error: Huge input lookup in /home/alisverispasaji/public_html/system/xml/minikoli/test.php on line 8

PHP Warning:  simplexml_load_string(): p;lt;img src=&quot;/UserFiles/FCK/image/prima hangisi(1).jpg&quot; class in /home/alisverispasaji/public_html/system/xml/minikoli/test.php on line 8

PHP Warning:  simplexml_load_string():                                                                                ^ in /home/alisverispasaji/public_html/system/xml/minikoli/test.php on line 8

PHP Fatal error:  Call to a member function children() on boolean in /home/alisverispasaji/public_html/system/xml/minikoli/test.php on line 20
</code>```

How I can solve this error?

test.php:

```<code><?php
ini_set('user_agent', 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:9.0) Gecko/20100101 Firefox/9.0');
error_reporting(-1);

function simplexml_load_file_curl($url) {
    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    $xml = simplexml_load_string(curl_exec($ch)); // <--- line 8
    return $xml;
}

$url = 'xml link';

$xml = simplexml_load_file_curl($url);

$veri = '<?xml version="1.0" encoding="UTF-8"?>';
$veri .= '
<Urunler>';

foreach($xml->children() as $urun) { // <--- line 20
</code>```

答:
Problem Solved

Find ;

$xml = simplexml_load_string(curl_exec($ch));

Change ;

```<code>$xml = simplexml_load_string(curl_exec($ch), 'SimpleXMLElement', LIBXML_COMPACT | LIBXML_PARSEHUGE);
</code>```

Body:
I am using PHP for the first time. I am getting the following error on running the PHP file:

PHP Warning:  simplexml_load_string(): Entity: line 35909: parser error : internal error: Huge input lookup in /home/alisverispasaji/public_html/system/xml/minikoli/test.php on line 8

PHP Warning:  simplexml_load_string(): p;lt;img src=&amp;quot;/UserFiles/FCK/image/prima hangisi(1).jpg&amp;quot; class in /home/alisverispasaji/public_html/system/xml/minikoli/test.php on line 8

PHP Warning:  simplexml_load_string():                                                                                ^ in /home/alisverispasaji/public_html/system/xml/minikoli/test.php on line 8

PHP Fatal error:  Call to a member function children() on boolean in /home/alisverispasaji/public_html/system/xml/minikoli/test.php on line 20

How I can solve this error?

test.php:

<?php
ini_set('user_agent', 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:9.0) Gecko/20100101 Firefox/9.0');
error_reporting(-1);

function simplexml_load_file_curl($url) {
    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    $xml = simplexml_load_string(curl_exec($ch)); // <--- line 8
    return $xml;
}

$url = 'xml link';

$xml = simplexml_load_file_curl($url);

$veri = '<?xml version="1.0" encoding="UTF-8"?>';
$veri .= '
<Urunler>';

foreach($xml->children() as $urun) { // <--- line 20

Body:
Problem Solved

Find ;

$xml = simplexml_load_string(curl_exec($ch));

Change ;

$xml = simplexml_load_string(curl_exec($ch), 'SimpleXMLElement', LIBXML_COMPACT | LIBXML_PARSEHUGE);


问:
How to force int to string in Laravel JSON?
I've recently updated my server to a newer version of MySQL and PHP 7 for various reasons. On my previous instance, running PHP 5.5, Laravel's response()->json() always converted tinyint's into a string. Now running newer server software, it's returning me int's -as it should...

I'd have to change a lots of my codebase to either cast types / convert them into a string manually, whic I'm trying to avoid at the moment.

Is there a way to somehow force response()->json() to return int's as string's?

答:
Is there a way to somehow force response()->json() to return int's as string's

I don't want to change the code base - do not want to cast types, convert it,

No. There's no option for that. You need to do that yourself if needed.


问:
how to change the icon/logo for the push notification in ionic 2
i am able to receive the push notification and below is my code written in

```<code> let push = Push.init({
        android: {
            senderID: '907xxxxx860',
            icon: 'icon'
        },
        ios: {
            alert: 'true',
            badge: true,
            sound: 'false'
        },
        windows: {}
      });
</code>```

i am testing in android version 5.

in my assets folder i have an image assets/images/home/KmartLogo.png in this path. i want this image as my logo for the android.

how can i achieve this. according to this documentation doc i am trying to give the path in like this icon: 'icon' in to this icon:assets/images/home/KmartLogo.png but it is not working how can i change my logo

update notification image i am getting

答:
The icon name should not include the extension.

Doc

The name of a drawable resource to use as the small-icon. The name
  should not include the extension.

```<code>android: {
            senderID: '907xxxxx860',
            icon: './assets/images/home/KmartLogo'
        },
</code>```

Body:
i am able to receive the push notification and below is my code written in

 let push = Push.init({
        android: {
            senderID: '907xxxxx860',
            icon: 'icon'
        },
        ios: {
            alert: 'true',
            badge: true,
            sound: 'false'
        },
        windows: {}
      });

i am testing in android version 5.

in my assets folder i have an image assets/images/home/KmartLogo.png in this path. i want this image as my logo for the android.

how can i achieve this. according to this documentation doc i am trying to give the path in like this icon: 'icon' in to this icon:assets/images/home/KmartLogo.png but it is not working how can i change my logo

update notification image i am getting

Body:
The icon name should not include the extension.

Doc

The name of a drawable resource to use as the small-icon. The name
  should not include the extension.

android: {
            senderID: '907xxxxx860',
            icon: './assets/images/home/KmartLogo'
        },


答:
Put simple switch/case on very top of your script:

```<code><?php
    if(isset($_POST['type'])) {
        switch($_POST['type']) {
            case 1:
                header("Location: ssgt.php");
                break;
            case 2:
                header("Location: tsgt.php");
                break;
            case 3:
                header("Location: msgt.php");
                break;
        }
    }
?>
<!doctype html>
<html>
    <head>
        <meta charset="utf-8">
        <title>MCQ Questions</title>
    </head>
    <body>
        <form method="post" enctype="multipart/form-data">
            Select rank :
            <select name="type" id="type" onchange="this.form.submit()">
                <option value="">Select rank...</option>
                <option value="1">SSgt</option>
                <option value="2">TSgt</option>
                <option value="3">MSgt</option>
            </select>
        </form>
    </body>
</html>
</code>```

Title: How to load one page from another on select of option from drop down?

Body:
Put simple switch/case on very top of your script:

<?php
    if(isset($_POST['type'])) {
        switch($_POST['type']) {
            case 1:
                header("Location: ssgt.php");
                break;
            case 2:
                header("Location: tsgt.php");
                break;
            case 3:
                header("Location: msgt.php");
                break;
        }
    }
?>
<!doctype html>
<html>
    <head>
        <meta charset="utf-8">
        <title>MCQ Questions</title>
    </head>
    <body>
        <form method="post" enctype="multipart/form-data">
            Select rank :
            <select name="type" id="type" onchange="this.form.submit()">
                <option value="">Select rank...</option>
                <option value="1">SSgt</option>
                <option value="2">TSgt</option>
                <option value="3">MSgt</option>
            </select>
        </form>
    </body>
</html>


问:
Change properties of mediaelement in different wpf window
in my app i have 2 different wpf windows. the main window has some buttons and textboxes to control a medielement in a different window.

how can i control the mediaelement in window2 from window1?

For example I press button_play in window1 and the filename ist readed out from textbox1 in window1 and the source property of the mediaelement in window2 is set (from textbox1 value) and medialement.play.

Thanks SMerker

答:
There are different ways of doing this by the simplest one would probably be to expose the MediaElement in Window2, either by using the x:FieldModifier attribute in XAML or by defining a property in the code-behind:

```<code><MediaElement x:Name="me" x:FieldModifier="public" />
</code>```

You could then get a reference to Window2 using the Application.Current.Windows property and access the generated backing field or property directly:

```<code>Window2 win = Application.Current.Windows.OfType<Window2>().FirstOrDefault();
if (win != null)
    win.me.Source = ...;
</code>```

Body:
There are different ways of doing this by the simplest one would probably be to expose the MediaElement in Window2, either by using the x:FieldModifier attribute in XAML or by defining a property in the code-behind:

<MediaElement x:Name="me" x:FieldModifier="public" />

You could then get a reference to Window2 using the Application.Current.Windows property and access the generated backing field or property directly:

Window2 win = Application.Current.Windows.OfType<Window2>().FirstOrDefault();
if (win != null)
    win.me.Source = ...;


问:
Is it possible to add missing symbols to public symbols in a windbg debugging session?
I am trying to see the IMAGE_DOS_HEADER structure using the 'dt' command in windbg:

```<code>0:001> dt ntdll!IMAGE_DOS_HEADER
**Symbol ntdll!IMAGE_DOS_HEADER not found**
</code>```

I searched and found that others have been able to do this:
 MSDN Blogs   >   Junyoung's Blog    >   Portable Executable File Format on Memory Dump

```<code>0:000> dt IMAGE_DOS_HEADER 77c00000
ntdll!IMAGE_DOS_HEADER
   +0x000 e_magic          : 0x5a4d ? MZ
   +0x002 e_cblp           : 0x90
   +0x004 e_cp             : 3
   +0x006 e_crlc           : 0
   +0x008 e_cparhdr        : 4
   +0x00a e_minalloc       : 0
   +0x00c e_maxalloc       : 0xffff
   +0x00e e_ss             : 0
   +0x010 e_sp             : 0xb8
   +0x012 e_csum           : 0
   +0x014 e_ip             : 0
   +0x016 e_cs             : 0
   +0x018 e_lfarlc         : 0x40
   +0x01a e_ovno           : 0
   +0x01c e_res            : [4] 0
   +0x024 e_oemid          : 0
   +0x026 e_oeminfo        : 0
   +0x028 e_res2           : [10] 0
   +0x03c e_lfanew         : 232
</code>```

Is it possible to add the missing symbol to public symbols of ntdll so that I can access the data structure fields in a windbg debugging session?

This is really weird - I tried the following and got different results on a win7 and on winxp systems -
WinXP:

```<code>0:015> dt ntdll!*HEADER*
          ntdll!_IMAGE_NT_HEADERS
          ntdll!_IMAGE_FILE_HEADER
          ntdll!_IMAGE_OPTIONAL_HEADER
          ntdll!_SLIST_HEADER
          ntdll!_DISPATCHER_HEADER
          ntdll!_IMAGE_SECTION_HEADER
</code>```

Win7:

```<code>0:000> dt ntdll!*HEADER*
          ntdll!_IMAGE_NT_HEADERS
          ntdll!_IMAGE_FILE_HEADER
          ntdll!_IMAGE_OPTIONAL_HEADER
          ntdll!_IMAGE_DOS_HEADER
          ntdll!_SLIST_HEADER
          ntdll!_DISPATCHER_HEADER
          ntdll!_MM_PAGE_ACCESS_INFO_HEADER
          ntdll!_WHEA_ERROR_RECORD_HEADER
          ntdll!_HEAP_USERDATA_HEADER
          ntdll!_HEAP_USERDATA_HEADER
          ntdll!_WHEA_ERROR_RECORD_HEADER_VALIDBITS
          ntdll!_WHEA_ERROR_RECORD_HEADER_FLAGS
          ntdll!_XSAVE_AREA_HEADER
</code>```

So it seems that the _IMAGE_DOS_HEADER symbol is stripped from the public symbols of winxp's ntdll.dll - my question remains - how can I add the symbol if I know the structure to a public symbols dll of a dll I don't have the sources for?

答:
This happens, it can be quite frustrating actually (though they've done a good job cleaning a lot of these up).

You can add types to existing PDBs, though it requires that you have the Visual C compiler available (either from Visual Studio or the WDK). I outline the steps in my response here:

http://www.osronline.com/showthread.cfm?link=193747

We're using the kernel there, though you have the same steps. The differences will be:

1) Look for ntdll instead of nt

2) You'll need to write a C file with the definition of the structure that you want.

-scott

ContentLicense: CC BY-SA 4.0

Body:
I am trying to see the IMAGE_DOS_HEADER structure using the 'dt' command in windbg:

0:001> dt ntdll!IMAGE_DOS_HEADER
**Symbol ntdll!IMAGE_DOS_HEADER not found**

I searched and found that others have been able to do this:
 MSDN Blogs   >   Junyoung's Blog    >   Portable Executable File Format on Memory Dump

0:000> dt IMAGE_DOS_HEADER 77c00000
ntdll!IMAGE_DOS_HEADER
   +0x000 e_magic          : 0x5a4d ? MZ
   +0x002 e_cblp           : 0x90
   +0x004 e_cp             : 3
   +0x006 e_crlc           : 0
   +0x008 e_cparhdr        : 4
   +0x00a e_minalloc       : 0
   +0x00c e_maxalloc       : 0xffff
   +0x00e e_ss             : 0
   +0x010 e_sp             : 0xb8
   +0x012 e_csum           : 0
   +0x014 e_ip             : 0
   +0x016 e_cs             : 0
   +0x018 e_lfarlc         : 0x40
   +0x01a e_ovno           : 0
   +0x01c e_res            : [4] 0
   +0x024 e_oemid          : 0
   +0x026 e_oeminfo        : 0
   +0x028 e_res2           : [10] 0
   +0x03c e_lfanew         : 232

Is it possible to add the missing symbol to public symbols of ntdll so that I can access the data structure fields in a windbg debugging session?

This is really weird - I tried the following and got different results on a win7 and on winxp systems -
WinXP:

0:015> dt ntdll!*HEADER*
          ntdll!_IMAGE_NT_HEADERS
          ntdll!_IMAGE_FILE_HEADER
          ntdll!_IMAGE_OPTIONAL_HEADER
          ntdll!_SLIST_HEADER
          ntdll!_DISPATCHER_HEADER
          ntdll!_IMAGE_SECTION_HEADER

Win7:

0:000> dt ntdll!*HEADER*
          ntdll!_IMAGE_NT_HEADERS
          ntdll!_IMAGE_FILE_HEADER
          ntdll!_IMAGE_OPTIONAL_HEADER
          ntdll!_IMAGE_DOS_HEADER
          ntdll!_SLIST_HEADER
          ntdll!_DISPATCHER_HEADER
          ntdll!_MM_PAGE_ACCESS_INFO_HEADER
          ntdll!_WHEA_ERROR_RECORD_HEADER
          ntdll!_HEAP_USERDATA_HEADER
          ntdll!_HEAP_USERDATA_HEADER
          ntdll!_WHEA_ERROR_RECORD_HEADER_VALIDBITS
          ntdll!_WHEA_ERROR_RECORD_HEADER_FLAGS
          ntdll!_XSAVE_AREA_HEADER

So it seems that the _IMAGE_DOS_HEADER symbol is stripped from the public symbols of winxp's ntdll.dll - my question remains - how can I add the symbol if I know the structure to a public symbols dll of a dll I don't have the sources for?


问:
How Cursor Batches Works in MongoDb?
I'm new to mongodb,when i was going through  cursor batches it tells the amount of data in the batch will not exceed the maximum BSON document size,but when i go through Bson Document Size it tells The maximum BSON document size is 16 megabytes,i can't get whether the batch will be of size 16 megabytes or each document in batch will 16 megabytes, how does cursor batch works if my query returns 20 documents whose  minimum size  1mb

答: When you run a query looking for documents what mongodb does is it just return the cursor of selected documents,but returning cursor alone is not efficient so we can fetch first batch of results which also add overhead if result set is too large. So, as a compromise and to improve performance what mongodb does is return the first 101 documents in the initial batch wait for next cursor call after subsequent requests cursors dont have the default size so that it limits to 16mb message size!!!

Title: How Cursor Batches Works in MongoDb?


问:
"GetLatest" with Powershell doesn't download files on new TFS workspace
I'm trying to create a Powershell script that will setup a brand new workspace in a temporary location, do a GetLatest on selected solutions/projects, and download the source code so that I can then trigger further build/versioning operations.

I think I have the script more or less right, but the problem is every time I run this, it tells me there were 0 operations... i.e. I already have the latest versions. This results in nothing at all being downloaded.

Can anyone see what I'm doing wrong?

```<code>$subfolder = [System.Guid]::NewGuid().ToString()
$tfsServer = "http://tfsserver:8080/tfs"
$projectsAndWorkspaces = @(
    @("$/Client1/Project1","D:\Builds\$subfolder\Client1\Project1"),
    @("$/Client1/Project2","D:\Builds\$subfolder\Client1\Project2"),
)

$tfsCollection = [Microsoft.TeamFoundation.Client.TfsTeamProjectCollectionFactory]::GetTeamProjectCollection($tfsServer)
$tfsVersionCtrl = $tfsCollection.GetService([type] "Microsoft.TeamFoundation.VersionControl.Client.VersionControlServer")
$tfsWorkspace = $tfsVersionCtrl.CreateWorkspace($subfolder, $tfsVersionCtrl.AuthorizedUser)

Write-Host "Operations:"

foreach ($projectAndWs in $projectsAndWorkspaces)
{
    if (-not(Test-Path $projectAndWs[1]))
    {
        New-Item -ItemType Directory -Force -Path $projectAndWs[1] | Out-Null
    }

    $tfsWorkspace.Map($projectAndWs[0], $projectAndWs[1])
    $recursion = [Microsoft.TeamFoundation.VersionControl.Client.RecursionType]::Full
    $itemSpecFullTeamProj = New-Object Microsoft.TeamFoundation.VersionControl.Client.ItemSpec($projectAndWs[0], $recursion)
    $fileRequest = New-Object Microsoft.TeamFoundation.VersionControl.Client.GetRequest($itemSpecFullTeamProj, [Microsoft.TeamFoundation.VersionControl.Client.VersionSpec]::Latest)
    $getStatus = $tfsWorkspace.Get($fileRequest, [Microsoft.TeamFoundation.VersionControl.Client.GetOptions]::Overwrite)
    Write-Host ("[{0}] {1}" -f $getStatus.NumOperations, ($projectAndWs[0].Substring($projectAndWs[0].LastIndexOf("/") + 1)))
}

Write-Host "Finished"
</code>```

答:
The "$/Client1/Project1" string smells. I would add a backtick before the dollar sign so it is not read as a variable or use single quotes.

Backtick

"`$/Client1/Project1"

Single quote

'$/Client1/Project1'

Body:
I'm trying to create a Powershell script that will setup a brand new workspace in a temporary location, do a GetLatest on selected solutions/projects, and download the source code so that I can then trigger further build/versioning operations.

I think I have the script more or less right, but the problem is every time I run this, it tells me there were 0 operations... i.e. I already have the latest versions. This results in nothing at all being downloaded.

Can anyone see what I'm doing wrong?

$subfolder = [System.Guid]::NewGuid().ToString()
$tfsServer = "http://tfsserver:8080/tfs"
$projectsAndWorkspaces = @(
    @("$/Client1/Project1","D:\Builds\$subfolder\Client1\Project1"),
    @("$/Client1/Project2","D:\Builds\$subfolder\Client1\Project2"),
)

$tfsCollection = [Microsoft.TeamFoundation.Client.TfsTeamProjectCollectionFactory]::GetTeamProjectCollection($tfsServer)
$tfsVersionCtrl = $tfsCollection.GetService([type] "Microsoft.TeamFoundation.VersionControl.Client.VersionControlServer")
$tfsWorkspace = $tfsVersionCtrl.CreateWorkspace($subfolder, $tfsVersionCtrl.AuthorizedUser)

Write-Host "Operations:"

foreach ($projectAndWs in $projectsAndWorkspaces)
{
    if (-not(Test-Path $projectAndWs[1]))
    {
        New-Item -ItemType Directory -Force -Path $projectAndWs[1] | Out-Null
    }

    $tfsWorkspace.Map($projectAndWs[0], $projectAndWs[1])
    $recursion = [Microsoft.TeamFoundation.VersionControl.Client.RecursionType]::Full
    $itemSpecFullTeamProj = New-Object Microsoft.TeamFoundation.VersionControl.Client.ItemSpec($projectAndWs[0], $recursion)
    $fileRequest = New-Object Microsoft.TeamFoundation.VersionControl.Client.GetRequest($itemSpecFullTeamProj, [Microsoft.TeamFoundation.VersionControl.Client.VersionSpec]::Latest)
    $getStatus = $tfsWorkspace.Get($fileRequest, [Microsoft.TeamFoundation.VersionControl.Client.GetOptions]::Overwrite)
    Write-Host ("[{0}] {1}" -f $getStatus.NumOperations, ($projectAndWs[0].Substring($projectAndWs[0].LastIndexOf("/") + 1)))
}

Write-Host "Finished"


问:
all the data is gone in the form when i put ng-model angularjs
I want to load data of a selected row in a form in order to update it. I successfully had the data loaded in the form, the but the problem is when I use ng model to save the data all the stuff have been put in the form fields disappear.

```<code><div class="panel-body pan" ng-if="loadedpr">
<form action="#">
    <div class="form-body pal">
        <div class="row">
            <div class="col-md-2">
                <div class="form-group">
                    <label for="refprojet" class="control-label">
                        Référence Projet *</label>
                    <input id="refprojet" type="text" value="{{loadedpr.ref_projet}}"  class="form-control" disabled ng-model="ref_projet"/>
                </div>
            </div>
            <div class="col-md-5">
                <div class="form-group">
                    <label for="intitulefr" class="control-label">
                        Intitulé *</label>
                    <input id="intitulefr" type="text" value="{{loadedpr.intitule_fr}}" class="form-control" ng-model="intitule_fr" />
                </div>
            </div>
            <div class="col-md-5">
                <div class="form-group">
                    <label for="ctot" class="control-label"> Coût Total (TND) *</label>
                    <input id="ctot" type="text" value="{{loadedpr.cout_total}}" ng-model="cout_total" class="form-control" disabled ng-model="cout_total" />
                </div>
            </div>
        </div>

        <div class="form-group">
            <label for="description" class="control-label">
                Description</label><textarea id="description" rows="3" value="{{loadedpr.description}}" ng-model="description" class="form-control"></textarea>
        </div>
        <div class="form-actions text-center pal">
            <button type="submit" class="btn btn-primary" ng-click="upadateProjet()">Valider</button>
        </div>
    </div>
</form>
</code>```

this is the angularjs method:

```<code>$scope.updateProjet= function(){
    $scope.projet={'ref_projet':$scope.refprojet,'intitule_fr':$scope.intitule_fr,'description':$scope.description,cout_total':$scope.cout_total};
    $http.put("/editprojet", $scope.projet)
    .success(function(data,status,headers,config){

    });

}
</code>```

rest controller

```<code>@RequestMapping(value="/editprojet",method=RequestMethod.PUT)
public Projet editProjet(@RequestBody Projet p) {
    return projetMetier.editProjet(p);
}
</code>```

答:
have you tried removing the value attribute? this happened to me when I once added DOM forms on the fly, I managed by using jquery to force capture by:

```<code>$(this).find('.inputClass').val();
</code>```

this sort of jequery is already embeded inside Angular so no need to add the the library.

Body:
I want to load data of a selected row in a form in order to update it. I successfully had the data loaded in the form, the but the problem is when I use ng model to save the data all the stuff have been put in the form fields disappear.

<form action="#">

                        Référence Projet *
                    <input id="refprojet" type="text" value="{{loadedpr.ref_projet}}"  class="form-control" disabled ng-model="ref_projet"/>

                        Intitulé *
                    <input id="intitulefr" type="text" value="{{loadedpr.intitule_fr}}" class="form-control" ng-model="intitule_fr" />

                     Coût Total (TND) *
                    <input id="ctot" type="text" value="{{loadedpr.cout_total}}" ng-model="cout_total" class="form-control" disabled ng-model="cout_total" />

                Description<textarea id="description" rows="3" value="{{loadedpr.description}}" ng-model="description" class="form-control"></textarea>

            <button type="submit" class="btn btn-primary" ng-click="upadateProjet()">Valider</button>

</form>

this is the angularjs method:

$scope.updateProjet= function(){
    $scope.projet={'ref_projet':$scope.refprojet,'intitule_fr':$scope.intitule_fr,'description':$scope.description,cout_total':$scope.cout_total};
    $http.put("/editprojet", $scope.projet)
    .success(function(data,status,headers,config){

    });

}

rest controller

@RequestMapping(value="/editprojet",method=RequestMethod.PUT)
public Projet editProjet(@RequestBody Projet p) {
    return projetMetier.editProjet(p);
}

Body:
have you tried removing the value attribute? this happened to me when I once added DOM forms on the fly, I managed by using jquery to force capture by:

$(this).find('.inputClass').val();

this sort of jequery is already embeded inside Angular so no need to add the the library.


问:
Javascript: Redirect to if URL contains value but keep that value
I have a subpage where I need to set a redirect to another subpage if the URL contains a specific value. However I need to keep that value and paste it to the redirect value.
Example:
Every URL with "/sub1/value=xy" should be redirected to "/sub2/value=xy"

mypage.com/sub1/value=1234 should be redirected to mypage.com/sub2/value=1234

I am checking the URL with the JS below, but I don't know how to get paste the value to the redirect URL

$(document).ready(function () {
        if(window.location.href.indexOf("value=") > -1) {
        }
    });```

答:
```<code>$(document).ready(function () {
    if(window.location.href.indexOf("value=") > -1) {
        url=window.location.href;
        if(url.substr(url.indexOf('=')+1)=="your_specific_value")
            {
            url=url.replace("sub1","sub2");
            window.location.replace(url);
            }
    }
});
</code>```

I think this is what is you want

Body:
$(document).ready(function () {
    if(window.location.href.indexOf("value=") > -1) {
        url=window.location.href;
        if(url.substr(url.indexOf('=')+1)=="your_specific_value")
            {
            url=url.replace("sub1","sub2");
            window.location.replace(url);
            }
    }
});

I think this is what is you want


问:
Remove conditional sequence from string in R
I have a sequence encoded in a string, but one type of step in this sequence is entirely conditional on a previous step.

When this occurs, I'd like to remove the previous step.

For example, in the case:

"alpha_i, bravo_i, alpha_i, alpha_c, charlie_i, bravo_i, bravo_c,
  alpha_i, delta_c"

those steps where a *_c event occurs directly after an *_i event, I'd like to have the *_i event removed, the desired result being:

"alpha_i, bravo_i, alpha_c, charlie_i, bravo_c, alphai_i,
  delta_c"

In other words,

"alpha_i, alpha_c" goes to just "alpha_c"

"bravo_i, bravo_c" goes to just "bravo_c",

but we do not change "alpha_i, delta_c" because they are a different event name.

I think the syntax would use the gsub function, but I don't know how to match the prefixed term either side of the comma, and would appreciate some help.

*In addition to the point raised below; yes there will be many different examples of event names, not just the two being replaced here.

答:
Try this:

```<code>wds <- c("alpha_i", "bravo_i", "alpha_i", "alpha_c", "charlie_i", "bravo_i", "bravo_c", "alpha_i", "delta_c")

wds[cumsum(rle(as.character(substr(wds, 1, gregexpr('_', wds))))$lengths)]
</code>```

Alternatively, if your vector is of length 1, try this:

```<code>wds <- c("alpha_i, bravo_i, alpha_i, alpha_c, charlie_i, bravo_i, bravo_c, alpha_i, delta_c")
wds_split <- unlist(strsplit(wds, ', '))
wds_split[cumsum(rle(as.character(substr(wds_split, 1, gregexpr('_', wds_split))))$lengths)]
</code>```

Body:
Try this:

wds <- c("alpha_i", "bravo_i", "alpha_i", "alpha_c", "charlie_i", "bravo_i", "bravo_c", "alpha_i", "delta_c")

wds[cumsum(rle(as.character(substr(wds, 1, gregexpr('_', wds))))$lengths)]

Alternatively, if your vector is of length 1, try this:

wds <- c("alpha_i, bravo_i, alpha_i, alpha_c, charlie_i, bravo_i, bravo_c, alpha_i, delta_c")
wds_split <- unlist(strsplit(wds, ', '))
wds_split[cumsum(rle(as.character(substr(wds_split, 1, gregexpr('_', wds_split))))$lengths)]


问:
Disable animation of navigation bar
I am working on a navigation-based application. I have few View Controllers which I push in to Navigation Controller on different occasions. The following is the code I use to push new View Controller.

```<code>AnotherViewController *anotherViewController = [[AnotherViewController alloc] initWithNibName:@"AnotherView" bundle:nil];
[self.navigationController pushViewController:anotherViewController animated:YES];
[anotherViewController release];
</code>```

One thing I noticed is that, when new view controller is pushed the navigation bar also animated (slided). I have a back button, title text and right button in navigation bar. So it look weird when the navigation bar is animated.

Is there any way around to keep the navigation bar fixed and the view is only animated when a new view controller is pushed?

答: The navigation bar hides while viewing images in Apple’s Photo app to provide a better view of the image. Hiding the navigation bar is easy. While not exactly the same as the Photo app this technique will hide and show the navigation bar, with an option to animate the transition.</p>

Title: Disable animation of navigation bar

Body:
I am working on a navigation-based application. I have few View Controllers which I push in to Navigation Controller on different occasions. The following is the code I use to push new View Controller.

AnotherViewController *anotherViewController = [[AnotherViewController alloc] initWithNibName:@"AnotherView" bundle:nil];
[self.navigationController pushViewController:anotherViewController animated:YES];
[anotherViewController release];

One thing I noticed is that, when new view controller is pushed the navigation bar also animated (slided). I have a back button, title text and right button in navigation bar. So it look weird when the navigation bar is animated.

Is there any way around to keep the navigation bar fixed and the view is only animated when a new view controller is pushed?


问:
how to transfer data from fragment(contains recyclerview) to dialog fragment which is show selected items on dialog fragment
how to transfer data from fragment(contains recyclerview) to dialog fragment which is show selected items on dialog fragment , in my case i am getting error .

this is RecyclerViewCollegeNewsLetter.java ,

```<code>public class RecyclerViewCollegeNewsLetter extends RecyclerView.Adapter<RecyclerViewCollegeNewsLetter.MyCollege> {

static List<Topics> topicses = new ArrayList<>();
Context context;
Topics topics;

public RecyclerViewCollegeNewsLetter(Context context, ArrayList<Topics> topicses) {
    this.context = context;
    this.topicses = topicses;
}

@Override
public RecyclerViewCollegeNewsLetter.MyCollege onCreateViewHolder(ViewGroup parent, int viewType) {
    View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.recycler_row, parent, false);
    Log.d("ssss", "in oncreate");

    return new MyCollege(view);
}

@Override
public void onBindViewHolder(final RecyclerViewCollegeNewsLetter.MyCollege holder, final int position) {
    topics = topicses.get(position);
    holder.id.setText(topics.getId());
    holder.givenby.setText(topics.getGivenby());
    holder.article.setText(topics.getArticle());

    holder.more.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            FilterDialogFragment filterDialogFragment = new FilterDialogFragment();
            int pos=holder.getAdapterPosition();
            Bundle bundle = new Bundle();
            bundle.putString("more_id",topicses.get(pos).getId() );
            Log.e("rrrr",topicses.get(pos).getId());
            bundle.putString("more_given_by",topicses.get(pos).getGivenby());
            bundle.putString("more_article", topicses.get(pos).getArticle());
            bundle.putString("more_content", topicses.get(pos).getContent());

            //pasing data to filterDialogFragment
            filterDialogFragment.setArguments(bundle);

            showDialog();
        }
    });
    // holder.content.setText(topics.getContent());

    if (topics.getContent().length() > 100) {
        holder.content.setText((topics.getContent().substring(0, 99)) + "...");
    } else
        holder.content.setText(topics.getContent());

}

@Override
public int getItemCount() {
    return topicses.size();
}

public class MyCollege extends RecyclerView.ViewHolder {
    TextView id, content, article, givenby;
    Button more;

    public MyCollege(View itemView) {
        super(itemView);
        id = (TextView) itemView.findViewById(R.id.id);
        givenby = (TextView) itemView.findViewById(R.id.givenby);
        article = (TextView) itemView.findViewById(R.id.article);
        content = (TextView) itemView.findViewById(R.id.content);
        more = (Button) itemView.findViewById(R.id.more);

    }

}
void showDialog() {
    FilterDialogFragment filterDialogFragment = new FilterDialogFragment();
   // MoreDetails moreDetails = new MoreDetails();
    FragmentManager ft = ((MainActivity) context).getSupportFragmentManager();
    DialogFragment newFragment = filterDialogFragment.newInstance();
    newFragment.show(ft, "dialog");
 }
</code>```

this is FilterDialogFragment.java

```<code> public class FilterDialogFragment extends DialogFragment {

private AdView mAdView;
Bundle mArgs;
TextView more_id, more_content, more_article, more_givenby;

static FilterDialogFragment newInstance() {
    FilterDialogFragment f = new FilterDialogFragment();
    return f;
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    View v = inflater.inflate(R.layout.more_details, container, false);
    mAdView = (AdView) v.findViewById(R.id.adView);
    more_id = (TextView) v.findViewById(R.id.more_id);
    more_content = (TextView) v.findViewById(R.id.more_content);
    more_article = (TextView) v.findViewById(R.id.more_article);
    more_givenby = (TextView) v.findViewById(R.id.more_givenby);

    return v;
}

@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);
    AdRequest adRequest = new AdRequest.Builder()
            .build();
    mAdView.loadAd(adRequest);

    Bundle mArgs = getArguments();
    more_id.setText(mArgs.getString("more_id"));
}

@Override
public void onPause() {
    if (mAdView != null) {
        mAdView.pause();
    }
    super.onPause();
}

@Override
public void onResume() {
    super.onResume();
    if (mAdView != null) {
        mAdView.resume();
    }
}

@Override
public void onDestroy() {
    if (mAdView != null) {
        mAdView.destroy();
    }
    super.onDestroy();
}

@Override
public void onStart() {
    super.onStart();
    Dialog dialog = getDialog();
    if (dialog != null) {
        int width = ViewGroup.LayoutParams.MATCH_PARENT;
        int height = ViewGroup.LayoutParams.MATCH_PARENT;
        dialog.getWindow().setLayout(width, height);
    }
}
</code>```

i put Bundle mArgs = getArguments();

more_id.setText(mArgs.getString("more_id"));

in onActivityCreated but gives me error:-

```<code>java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.os.Bundle.getString(java.lang.String)' on a null object reference
                                                                                at com.example.kulde.itechvcet.FilterDialogFragment.onViewCreated(FilterDialogFragment.java:52)
                                                                                at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1314)
                                                                                at android.support.v4.app.FragmentManagerImpl.moveFragmentToExpectedState(FragmentManager.java:1528)
                                                                                at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1595)
                                                                                at android.support.v4.app.BackStackRecord.executeOps(BackStackRecord.java:758)
                                                                                at android.support.v4.app.FragmentManagerImpl.executeOps(FragmentManager.java:2363)
                                                                                at android.support.v4.app.FragmentManagerImpl.executeOpsTogether(FragmentManager.java:2149)
                                                                                at android.support.v4.app.FragmentManagerImpl.optimizeAndExecuteOps(FragmentManager.java:2103)
                                                                                at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:2013)
                                                                                at android.support.v4.app.FragmentManagerImpl$1.run(FragmentManager.java:710)
                                                                                at android.os.Handler.handleCallback(Handler.java:739)
                                                                                at android.os.Handler.dispatchMessage(Handler.java:95)
                                                                                at android.os.Looper.loop(Looper.java:152)
                                                                                at android.app.ActivityThread.main(ActivityThread.java:5497)
                                                                                at java.lang.reflect.Method.invoke(Native Method)
                                                                                at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
                                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
</code>```

Help me Pro Devs !

答:
check this and use in  FilterDialogFragment.java.</p>

```<code>  public Bundle getBundle = null;
getBundle = this.getIntent().getExtras();
  String id= getBundle.getString("more_id");
more_id.setText(id);
</code>```

Body:
how to transfer data from fragment(contains recyclerview) to dialog fragment which is show selected items on dialog fragment , in my case i am getting error .

this is RecyclerViewCollegeNewsLetter.java ,

public class RecyclerViewCollegeNewsLetter extends RecyclerView.Adapter<RecyclerViewCollegeNewsLetter.MyCollege> {

static List<Topics> topicses = new ArrayList<>();
Context context;
Topics topics;

public RecyclerViewCollegeNewsLetter(Context context, ArrayList<Topics> topicses) {
    this.context = context;
    this.topicses = topicses;
}

@Override
public RecyclerViewCollegeNewsLetter.MyCollege onCreateViewHolder(ViewGroup parent, int viewType) {
    View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.recycler_row, parent, false);
    Log.d("ssss", "in oncreate");

    return new MyCollege(view);
}

@Override
public void onBindViewHolder(final RecyclerViewCollegeNewsLetter.MyCollege holder, final int position) {
    topics = topicses.get(position);
    holder.id.setText(topics.getId());
    holder.givenby.setText(topics.getGivenby());
    holder.article.setText(topics.getArticle());

    holder.more.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            FilterDialogFragment filterDialogFragment = new FilterDialogFragment();
            int pos=holder.getAdapterPosition();
            Bundle bundle = new Bundle();
            bundle.putString("more_id",topicses.get(pos).getId() );
            Log.e("rrrr",topicses.get(pos).getId());
            bundle.putString("more_given_by",topicses.get(pos).getGivenby());
            bundle.putString("more_article", topicses.get(pos).getArticle());
            bundle.putString("more_content", topicses.get(pos).getContent());

            //pasing data to filterDialogFragment
            filterDialogFragment.setArguments(bundle);

            showDialog();
        }
    });
    // holder.content.setText(topics.getContent());

    if (topics.getContent().length() > 100) {
        holder.content.setText((topics.getContent().substring(0, 99)) + "...");
    } else
        holder.content.setText(topics.getContent());

}

@Override
public int getItemCount() {
    return topicses.size();
}

public class MyCollege extends RecyclerView.ViewHolder {
    TextView id, content, article, givenby;
    Button more;

    public MyCollege(View itemView) {
        super(itemView);
        id = (TextView) itemView.findViewById(R.id.id);
        givenby = (TextView) itemView.findViewById(R.id.givenby);
        article = (TextView) itemView.findViewById(R.id.article);
        content = (TextView) itemView.findViewById(R.id.content);
        more = (Button) itemView.findViewById(R.id.more);

    }

}
void showDialog() {
    FilterDialogFragment filterDialogFragment = new FilterDialogFragment();
   // MoreDetails moreDetails = new MoreDetails();
    FragmentManager ft = ((MainActivity) context).getSupportFragmentManager();
    DialogFragment newFragment = filterDialogFragment.newInstance();
    newFragment.show(ft, "dialog");
 }

this is FilterDialogFragment.java

 public class FilterDialogFragment extends DialogFragment {

private AdView mAdView;
Bundle mArgs;
TextView more_id, more_content, more_article, more_givenby;

static FilterDialogFragment newInstance() {
    FilterDialogFragment f = new FilterDialogFragment();
    return f;
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    View v = inflater.inflate(R.layout.more_details, container, false);
    mAdView = (AdView) v.findViewById(R.id.adView);
    more_id = (TextView) v.findViewById(R.id.more_id);
    more_content = (TextView) v.findViewById(R.id.more_content);
    more_article = (TextView) v.findViewById(R.id.more_article);
    more_givenby = (TextView) v.findViewById(R.id.more_givenby);

    return v;
}

@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);
    AdRequest adRequest = new AdRequest.Builder()
            .build();
    mAdView.loadAd(adRequest);

    Bundle mArgs = getArguments();
    more_id.setText(mArgs.getString("more_id"));
}

@Override
public void onPause() {
    if (mAdView != null) {
        mAdView.pause();
    }
    super.onPause();
}

@Override
public void onResume() {
    super.onResume();
    if (mAdView != null) {
        mAdView.resume();
    }
}

@Override
public void onDestroy() {
    if (mAdView != null) {
        mAdView.destroy();
    }
    super.onDestroy();
}

@Override
public void onStart() {
    super.onStart();
    Dialog dialog = getDialog();
    if (dialog != null) {
        int width = ViewGroup.LayoutParams.MATCH_PARENT;
        int height = ViewGroup.LayoutParams.MATCH_PARENT;
        dialog.getWindow().setLayout(width, height);
    }
}

i put Bundle mArgs = getArguments();

more_id.setText(mArgs.getString("more_id"));

in onActivityCreated but gives me error:-

java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.os.Bundle.getString(java.lang.String)' on a null object reference
                                                                                at com.example.kulde.itechvcet.FilterDialogFragment.onViewCreated(FilterDialogFragment.java:52)
                                                                                at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1314)
                                                                                at android.support.v4.app.FragmentManagerImpl.moveFragmentToExpectedState(FragmentManager.java:1528)
                                                                                at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1595)
                                                                                at android.support.v4.app.BackStackRecord.executeOps(BackStackRecord.java:758)
                                                                                at android.support.v4.app.FragmentManagerImpl.executeOps(FragmentManager.java:2363)
                                                                                at android.support.v4.app.FragmentManagerImpl.executeOpsTogether(FragmentManager.java:2149)
                                                                                at android.support.v4.app.FragmentManagerImpl.optimizeAndExecuteOps(FragmentManager.java:2103)
                                                                                at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:2013)
                                                                                at android.support.v4.app.FragmentManagerImpl$1.run(FragmentManager.java:710)
                                                                                at android.os.Handler.handleCallback(Handler.java:739)
                                                                                at android.os.Handler.dispatchMessage(Handler.java:95)
                                                                                at android.os.Looper.loop(Looper.java:152)
                                                                                at android.app.ActivityThread.main(ActivityThread.java:5497)
                                                                                at java.lang.reflect.Method.invoke(Native Method)
                                                                                at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
                                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)

Help me Pro Devs !

Body:
check this and use in  FilterDialogFragment.java.

  public Bundle getBundle = null;
getBundle = this.getIntent().getExtras();
  String id= getBundle.getString("more_id");
more_id.setText(id);


问:
How can use update UI Thread
I have same stock item , I want to send local database to ApiService, But when I send also I want to update ProgressBar message. I tried the code below but it just shows when all proccessing is finishing.

```<code>  ProgressDialog progress= new ProgressDialog(this);
  progress.setTitle(getResources().getString(R.string.progress_exporting));
  progress.setMessage("0/0");
</code>```

when click button I call below method

```<code>  public void Export() {

    runOnUiThread(new Runnable() {
        @Override
        public void run() {
            findViewById(R.id.btnExportOnlineWithStocktaking).setEnabled(false);
            progress.show();
        }
    });

    UpdateUI(send, total);

    try {

        switch (_stocktakingType) {
         case Division: {
                switch (_onlineExportType) {
                    case Item: {
                        isExport = ExportDivisionStocktakingItems(stocktakingId);
                    }
                    break;
                }
        } catch (Exception ex) {
    }

  }
</code>```

// ExportDivisionStocktaking method

```<code> public boolean ExportCustomStocktakingItems(int stocktakingId) {
     result = Boolean.parseBoolean(SendCustomStocktakingItems(stocktakingId,countResults).responseString);
}
</code>```

My call back method

```<code>public ResponseModel SendCustomStocktakingItems(int selectedDivision, List<ExtensionServiceStocktakingItem> countResults) throws ExecutionException, InterruptedException {

    return new SendCustomStocktakingItemsService(flag -> true).execute(String.valueOf(selectedDivision), countResults.toString()).get();

}
</code>```

//AsyncTask method

```<code> public class SendDivisionStocktakingItemsService extends AsyncTask<String, Void, ResponseModel> {

    public AsyncResponseSendDivisionStocktakingItems delegate = null;

    public SendDivisionStocktakingItemsService(AsyncResponseSendDivisionStocktakingItems delegate) {
        this.delegate = delegate;
    }

    @Override
    protected ResponseModel doInBackground(String... parameters) {

        RequestHandler requestHandler = new RequestHandler();

        JSONObject params = new JSONObject();
        try {
            params.put("stocktakingItems", parameters[1]);
        } catch (JSONException e) {
            e.printStackTrace();
        }

        ResponseModel responseModel = requestHandler.getRequestPostString(UHFApplication.getInstance().apiUrl
                        + "/api/MobileService/SendDivisionStocktakingItemsPost?stocktakingID="
                        + parameters[0],
                parameters[1]);
        return responseModel;

    }

    @Override
    protected void onPreExecute() {
        UpdateUI(send,total);
        super.onPreExecute();
    }

    @Override
    protected void onPostExecute(ResponseModel responseModel) {

        super.onPostExecute(responseModel);

        if (HttpURLConnection.HTTP_OK == responseModel.httpStatus) {

            delegate.processFinish(true);

        } else {
            delegate.processFinish(false);
        }
    }

}
</code>```

//UICalled method

```<code> public void UpdateUI(int send, int total) {
    runOnUiThread(() -> {
        progress.setMessage(send + "/" + total);
        Log.d("Send Data : ", send + "/" + total);

        if (send == total) {
            progress.dismiss();
            Toast.makeText(getApplicationContext(), "Succsess", Toast.LENGTH_SHORT).show();
        }
    });
}
</code>```

//Update

//Ok I have a simle example how can I use. Below code when I click button I wan to open progress firstly and after that for loop is working and update progres message. I try it but not working.

Firstly For loop is working and after that progres opened.

```<code> public void ExportTry(){
    UpdateUI(send,total);
    runOnUiThread(new Runnable() {
        @Override
        public void run() {
            btnExport.setEnabled(false);
            progress.show();
        }
    });

    for(int i=0;i<1000000;i++){
        UpdateUI(i,1000000);
    }
}
</code>```

答:
You are missing the part of AsyncTask that will allow you to show progress messages while doInBackground is running. Take a look at onProgressUpdate and publishProgress on the same page.

publishProgress

void publishProgress (Progress... values)

This method can be invoked from doInBackground(Params...) to publish updates on the UI thread while the background computation is still running. Each call to this method will trigger the execution of onProgressUpdate(Progress...) on the UI thread. onProgressUpdate(Progress...) will not be called if the task has been canceled.

Title: How can use update UI Thread

Body:
I have same stock item , I want to send local database to ApiService, But when I send also I want to update ProgressBar message. I tried the code below but it just shows when all proccessing is finishing.

  ProgressDialog progress= new ProgressDialog(this);
  progress.setTitle(getResources().getString(R.string.progress_exporting));
  progress.setMessage("0/0");

when click button I call below method

  public void Export() {

    runOnUiThread(new Runnable() {
        @Override
        public void run() {
            findViewById(R.id.btnExportOnlineWithStocktaking).setEnabled(false);
            progress.show();
        }
    });

    UpdateUI(send, total);

    try {

        switch (_stocktakingType) {
         case Division: {
                switch (_onlineExportType) {
                    case Item: {
                        isExport = ExportDivisionStocktakingItems(stocktakingId);
                    }
                    break;
                }
        } catch (Exception ex) {
    }

  }

// ExportDivisionStocktaking method

 public boolean ExportCustomStocktakingItems(int stocktakingId) {
     result = Boolean.parseBoolean(SendCustomStocktakingItems(stocktakingId,countResults).responseString);
}

My call back method

public ResponseModel SendCustomStocktakingItems(int selectedDivision, List<ExtensionServiceStocktakingItem> countResults) throws ExecutionException, InterruptedException {

    return new SendCustomStocktakingItemsService(flag -> true).execute(String.valueOf(selectedDivision), countResults.toString()).get();

}

//AsyncTask method

 public class SendDivisionStocktakingItemsService extends AsyncTask<String, Void, ResponseModel> {

    public AsyncResponseSendDivisionStocktakingItems delegate = null;

    public SendDivisionStocktakingItemsService(AsyncResponseSendDivisionStocktakingItems delegate) {
        this.delegate = delegate;
    }

    @Override
    protected ResponseModel doInBackground(String... parameters) {

        RequestHandler requestHandler = new RequestHandler();

        JSONObject params = new JSONObject();
        try {
            params.put("stocktakingItems", parameters[1]);
        } catch (JSONException e) {
            e.printStackTrace();
        }

        ResponseModel responseModel = requestHandler.getRequestPostString(UHFApplication.getInstance().apiUrl
                        + "/api/MobileService/SendDivisionStocktakingItemsPost?stocktakingID="
                        + parameters[0],
                parameters[1]);
        return responseModel;

    }

    @Override
    protected void onPreExecute() {
        UpdateUI(send,total);
        super.onPreExecute();
    }

    @Override
    protected void onPostExecute(ResponseModel responseModel) {

        super.onPostExecute(responseModel);

        if (HttpURLConnection.HTTP_OK == responseModel.httpStatus) {

            delegate.processFinish(true);

        } else {
            delegate.processFinish(false);
        }
    }

}

//UICalled method

 public void UpdateUI(int send, int total) {
    runOnUiThread(() -> {
        progress.setMessage(send + "/" + total);
        Log.d("Send Data : ", send + "/" + total);

        if (send == total) {
            progress.dismiss();
            Toast.makeText(getApplicationContext(), "Succsess", Toast.LENGTH_SHORT).show();
        }
    });
}

//Update

//Ok I have a simle example how can I use. Below code when I click button I wan to open progress firstly and after that for loop is working and update progres message. I try it but not working.

Firstly For loop is working and after that progres opened.

 public void ExportTry(){
    UpdateUI(send,total);
    runOnUiThread(new Runnable() {
        @Override
        public void run() {
            btnExport.setEnabled(false);
            progress.show();
        }
    });

    for(int i=0;i<1000000;i++){
        UpdateUI(i,1000000);
    }
}


问:
In Coded UI, how to identify and click only the part of HTML link
The application that I have been testing allows reviewing the images for the items that customer selected earlier. To do this, there is a list of HTML links provided at the bottom of the web page.
For instance, if customer picked the alcohol drinks, the HTML links may look like:

Vodka – Alcohol Drinks

Beer – Alcohol Drinks

Gin – Alcohol Drinks

Etc.

When I create my Coded UI script, it is an easy task to identify this whole text, e.g.  “Vodka – Alcohol Drinks” as the InnerText  for Htmlhyperlink and have my script clicking on it.

However, I can not predict which drink was selected earlier, e.g. vodka, beer or gin, and the one variant of InnerText (“Vodka – Alcohol Drinks” in my example) can not match all possible sorts of drinks' names.  Because of this, the Coded UI script fails mostly (unless if vodka was selected).

As such, it would be logical to cut off the name of drinks from the HTML links and let my Coded UI script to find and click only words “Alcohol Drinks” which remains the same.  And this is where I stuck.

I would appreciate for any idea on how to do this task.

This is the only piece that work for one match only.

```<code>HtmlHyperlink alcoholDrinksLink = new HtmlHyperlink(PreSelectedPage);
alcoholDrinksLink.SearchProperties.Add("ControlType", "Hyperlink");
alcoholDrinksLink.SearchProperties.Add("InnerText", "Vodka - Alcohol Drinks");
Mouse.Click(alcoholDrinksLink);
</code>```

答:
After working with our developer, we came up to the following solution that works:

HtmlTable hyperlinksBox = new HtmlTable(reviewPurchaseHtmlDocument); //Identify a container (or box) with all the hyperlinks

hyperlinksBox.SearchProperties.Add("Id", "DEApplication:content:vc:dt1"); //add the search properties to find your table

HtmlControl hyperlink = new HtmlControl(hyperlinksBox); //Identify each single hyperlink which resides in the container
           hyperlink.SearchProperties.Add("TagName", "A");
           UITestControlCollection drinksHyperlinks = hyperlink.FindMatchingControls();

```<code>       foreach (var link in drinksHyperlinks)
       {

           Mouse.Click(link); //click the link
           Playback.Wait(5000); //and review it for 5 seconds
       }
</code>```

Body:
The application that I have been testing allows reviewing the images for the items that customer selected earlier. To do this, there is a list of HTML links provided at the bottom of the web page.
For instance, if customer picked the alcohol drinks, the HTML links may look like:

Vodka – Alcohol Drinks

Beer – Alcohol Drinks

Gin – Alcohol Drinks

Etc.

When I create my Coded UI script, it is an easy task to identify this whole text, e.g.  “Vodka – Alcohol Drinks” as the InnerText  for Htmlhyperlink and have my script clicking on it.

However, I can not predict which drink was selected earlier, e.g. vodka, beer or gin, and the one variant of InnerText (“Vodka – Alcohol Drinks” in my example) can not match all possible sorts of drinks' names.  Because of this, the Coded UI script fails mostly (unless if vodka was selected).

As such, it would be logical to cut off the name of drinks from the HTML links and let my Coded UI script to find and click only words “Alcohol Drinks” which remains the same.  And this is where I stuck.

I would appreciate for any idea on how to do this task.

This is the only piece that work for one match only.

HtmlHyperlink alcoholDrinksLink = new HtmlHyperlink(PreSelectedPage);
alcoholDrinksLink.SearchProperties.Add("ControlType", "Hyperlink");
alcoholDrinksLink.SearchProperties.Add("InnerText", "Vodka - Alcohol Drinks");
Mouse.Click(alcoholDrinksLink);

Body:
After working with our developer, we came up to the following solution that works:

HtmlTable hyperlinksBox = new HtmlTable(reviewPurchaseHtmlDocument); //Identify a container (or box) with all the hyperlinks

hyperlinksBox.SearchProperties.Add("Id", "DEApplication:content:vc:dt1"); //add the search properties to find your table

HtmlControl hyperlink = new HtmlControl(hyperlinksBox); //Identify each single hyperlink which resides in the container
           hyperlink.SearchProperties.Add("TagName", "A");
           UITestControlCollection drinksHyperlinks = hyperlink.FindMatchingControls();

       foreach (var link in drinksHyperlinks)
       {

           Mouse.Click(link); //click the link
           Playback.Wait(5000); //and review it for 5 seconds
       }


问:
Cornerstone vs Versions for Mac OS X
I've been using svn on the command line for 5+ years, but I'm thinking of switching to GUI. The two kings of Mac subversion apps seem to be Versions and Cornerstone. Most of the reviews/comments I've seen comparing the two are from way back in 2008, when Cornerstone was first released. It's now 2010, and  both apps have undergone significant changes.

I've been running trial copies of both apps for the past week, and I still can't make up my mind. Which would you recommend and why?

答:
Cornerstone has been out a few years and version 2 was just released. It is now by far the best value, fastest and feature rich Subversion client for the Mac. The merge features and annotations alone are awesome. I have never seen such a cool take on either of them and the way you can just click a block of text when comparing and have the log message displayed for that block together with all the statistical information you'll ever need in a stunning UI, it's just awesome.

Seriously I can't recommend this tool enough. It is in a different league to Versions.

Title: Cornerstone vs Versions for Mac OS X


问:
Cannot use r.net within a wcf service
I am trying to set up an R.net WCF service as a server to run R commands on.

I have set up a test WinForms application where everything works.

This is how I use it:

```<code>void init()
{
    SetupPath()
    engine = REngine.GetInstanceFromID("test");
    if (engine == null) engine = REngine.CreateInstance("test");
    engine.Initialize();
}
...
    results.Add(engine.Evaluate(command).AsCharacter().ToArray());
</code>```

I created an equivalent WCF service which should work exactly the same;

REngine.CreateInstance() returns a valid REngine object,

engine.Initialize() silently crashes my service. Try-Catch section is ignored so I cannot see what exactly is happening.

What is the correct way to use R.net within a WCF service?

What could be the reason of different behaviours?

Where can I see detailed logs of the crash?

Service calls which don't use R.net complete successfully.

Both winforms test application and WCF service are 64 bit (i need them to be). (I did not manage to set up a 64-bit IIS express application, so am using IIS instead).

答: I did not manage to find the reason of the problem, however, switching to R.NET.Community package did the trick.

Title: Cannot use r.net within a wcf service

Body:
I am trying to set up an R.net WCF service as a server to run R commands on.

I have set up a test WinForms application where everything works.

This is how I use it:

void init()
{
    SetupPath()
    engine = REngine.GetInstanceFromID("test");
    if (engine == null) engine = REngine.CreateInstance("test");
    engine.Initialize();
}
...
    results.Add(engine.Evaluate(command).AsCharacter().ToArray());

I created an equivalent WCF service which should work exactly the same;

REngine.CreateInstance() returns a valid REngine object,

engine.Initialize() silently crashes my service. Try-Catch section is ignored so I cannot see what exactly is happening.

What is the correct way to use R.net within a WCF service?

What could be the reason of different behaviours?

Where can I see detailed logs of the crash?

Service calls which don't use R.net complete successfully.

Both winforms test application and WCF service are 64 bit (i need them to be). (I did not manage to set up a 64-bit IIS express application, so am using IIS instead).