问:
PHP program that requires user to accept a string as a parameter and return the same string randomly capitalized characters
PHP program that requires user to accept a string as a parameter and return the same string randomly capitalized characters. Example: the input is “php script” may display “PHP SCRIPT”, “pHp ScriPT”, “PHP script” or “php SCRIPT”.

I don't really know what i'm doing actually.

```<code><html>
<body>

<h2>Random Capitalized Character </h2>
<form action="Q5.php" method="post"><input type="text" name="input" value="<?php if (isset($_POST['input'])) echo $_POST['input']; ?>" /></p><input type="submit" />
</form>
</body>
</html>
<?php

$name = "input";

$lowercaseTitle = strtolower($name);
$uppercaseTitle = strtoupper($name);
$ucTitleString = ucwords($lowercaseTitle && $uppercaseTitle);
echo "$ucTitleString";
?>
</code>```

I would like to ask how to create this? already done this and that but results still no no.

答:
Here a custom function to randomly capitalized characters:

```<code>    function randomCapitalize($input)
    {
        $output = '';

        foreach (str_split($input) as $c) {
            if (rand(0, 1) == 1) {
                $output .= strtoupper($c);
            } else {
                $output .= strtolower($c);
            }
        }

        return $output;
    }
</code>```

And you just need to echo with your string in parameter:

```<code> echo randomCapitalize(“php script”);
</code>```

Body:
PHP program that requires user to accept a string as a parameter and return the same string randomly capitalized characters. Example: the input is “php script” may display “PHP SCRIPT”, “pHp ScriPT”, “PHP script” or “php SCRIPT”.

I don't really know what i'm doing actually.

Random Capitalized Character

<form action="Q5.php" method="post"><input type="text" name="input" value="<?php if (isset($_POST['input'])) echo $_POST['input']; ?>" />
<input type="submit" />
</form>

<?php

$name = "input";

$lowercaseTitle = strtolower($name);
$uppercaseTitle = strtoupper($name);
$ucTitleString = ucwords($lowercaseTitle && $uppercaseTitle);
echo "$ucTitleString";
?>

I would like to ask how to create this? already done this and that but results still no no.

Body:
Here a custom function to randomly capitalized characters:

    function randomCapitalize($input)
    {
        $output = '';

        foreach (str_split($input) as $c) {
            if (rand(0, 1) == 1) {
                $output .= strtoupper($c);
            } else {
                $output .= strtolower($c);
            }
        }

        return $output;
    }

And you just need to echo with your string in parameter:

 echo randomCapitalize(“php script”);


来源: stackexchange

问:
how to escape form filtering for certain fields using codeigniter
I am using codeigniter form validation and i have set some rules for my form fields. When i type %50 or %test% , I don't get the rest of the texts posted  after the first occurrence of % character.
Please help how to solve this. </p>

答:
```<code>remove the 'xss_clean' rule.
</code>```

consider your text box /textarea's name would be, 'mine'

```<code>$this->form_validation('mine','Mine', 'trim|required|xss_clean');
</code>```

to

```<code>$this->form_validation('mine','Mine', 'trim|required');
</code>```

xss clean prevent scripts and encode.

ContentLicense: CC BY-SA 3.0

Body:
remove the 'xss_clean' rule.

consider your text box /textarea's name would be, 'mine'

$this->form_validation('mine','Mine', 'trim|required|xss_clean');

to

$this->form_validation('mine','Mine', 'trim|required');

xss clean prevent scripts and encode.


问:
Sharepoint 2010 NullReferenceException
I'm upgrading our SharePoint 2007 install to SharePoint 2010. One of the problems I'm running into is a NullReferenceException when I go to Site Actions -> Site Settings -> Navigation. I'm not sure where or how to start debugging this issue. Anyone have any ideas?

The error message and stack trace I'm getting are:

```<code>[NullReferenceException]: Object reference not set to an instance of an object.
  at Microsoft.SharePoint.Publishing.Navigation.PortalWebSiteMapNode.FetchDynamicItems(PublishingWeb pubWeb, NodeTypes includedTypes, Boolean& websFetched, Boolean& pagesFetched)
  at Microsoft.SharePoint.Publishing.Navigation.PortalWebSiteMapNode.PopulateNavigationChildrenInner(NodeTypes includedTypes)
  at Microsoft.SharePoint.Publishing.Navigation.PortalWebSiteMapNode.PopulateNavigationChildren(NodeTypes includedTypes)
  at Microsoft.SharePoint.Publishing.Navigation.PortalSiteMapNode.GetNavigationChildren(NodeTypes includedTypes, NodeTypes includedHiddenTypes, Boolean trimmingEnabled, OrderingMethod ordering, AutomaticSortingMethod method, Boolean ascending, Int32 lcid)
  at Microsoft.SharePoint.Publishing.Internal.CodeBehind.AreaNavigationSettingsPage.AddChildrenToControl(String parentId, PortalSiteMapNode node, Int32 depth, Int32 maxDepth)
  at Microsoft.SharePoint.Publishing.Internal.CodeBehind.AreaNavigationSettingsPage.InitializeNavigationEditSort()
  at Microsoft.SharePoint.Publishing.Internal.CodeBehind.AreaNavigationSettingsPage.OnLoad(EventArgs e)
  at System.Web.UI.Control.LoadRecursive()
  at System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)
[HttpUnhandledException]: Exception of type 'System.Web.HttpUnhandledException' was thrown.
  at System.Web.UI.Page.HandleError(Exception e)
  at System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)
  at System.Web.UI.Page.ProcessRequest(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)
  at System.Web.UI.Page.ProcessRequest()
  at System.Web.UI.Page.ProcessRequest(HttpContext context)
  at ASP._layouts_areanavigationsettings_aspx.ProcessRequest(HttpContext context)
  at System.Web.HttpApplication.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()
  at System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously)
</code>```

答:
This is happening because you have nodes present in the database but the actual SPSite or SPWeb is not present in the content database. This indicates that one or more site was not completely migrated.

To debug this, write a custom utility, which will iterate over navigation nodes and try to instantiate it as SPWeb object.  The failure will indicate the offender.

ContentLicense: CC BY-SA 2.5

Title: Sharepoint 2010 NullReferenceException

Body:
I'm upgrading our SharePoint 2007 install to SharePoint 2010. One of the problems I'm running into is a NullReferenceException when I go to Site Actions -> Site Settings -> Navigation. I'm not sure where or how to start debugging this issue. Anyone have any ideas?

The error message and stack trace I'm getting are:

[NullReferenceException]: Object reference not set to an instance of an object.
  at Microsoft.SharePoint.Publishing.Navigation.PortalWebSiteMapNode.FetchDynamicItems(PublishingWeb pubWeb, NodeTypes includedTypes, Boolean& websFetched, Boolean& pagesFetched)
  at Microsoft.SharePoint.Publishing.Navigation.PortalWebSiteMapNode.PopulateNavigationChildrenInner(NodeTypes includedTypes)
  at Microsoft.SharePoint.Publishing.Navigation.PortalWebSiteMapNode.PopulateNavigationChildren(NodeTypes includedTypes)
  at Microsoft.SharePoint.Publishing.Navigation.PortalSiteMapNode.GetNavigationChildren(NodeTypes includedTypes, NodeTypes includedHiddenTypes, Boolean trimmingEnabled, OrderingMethod ordering, AutomaticSortingMethod method, Boolean ascending, Int32 lcid)
  at Microsoft.SharePoint.Publishing.Internal.CodeBehind.AreaNavigationSettingsPage.AddChildrenToControl(String parentId, PortalSiteMapNode node, Int32 depth, Int32 maxDepth)
  at Microsoft.SharePoint.Publishing.Internal.CodeBehind.AreaNavigationSettingsPage.InitializeNavigationEditSort()
  at Microsoft.SharePoint.Publishing.Internal.CodeBehind.AreaNavigationSettingsPage.OnLoad(EventArgs e)
  at System.Web.UI.Control.LoadRecursive()
  at System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)
[HttpUnhandledException]: Exception of type 'System.Web.HttpUnhandledException' was thrown.
  at System.Web.UI.Page.HandleError(Exception e)
  at System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)
  at System.Web.UI.Page.ProcessRequest(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)
  at System.Web.UI.Page.ProcessRequest()
  at System.Web.UI.Page.ProcessRequest(HttpContext context)
  at ASP._layouts_areanavigationsettings_aspx.ProcessRequest(HttpContext context)
  at System.Web.HttpApplication.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()
  at System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously)


问:
How can I call particular array value of array in php?
I'm getting below output as an array.

```<code>$array =
        Array
    (
        [12] => Array
            (
                [1] => Array
                    (
                        [14] => Array
                            (
                                [0] => Array
                                    (
                                        [name] => Avaya Implementation  Services
                                        [service_id] => 14
                                        [ser_type_id] => 1
                                        [service_desc] =>Avaya Implementation Servic
                                    )

                            )

                    )

            )

    );
</code>```

I want to print only service_desc array value. and I don't want call like $array[12][1][14][0]['service_desc'];

How can I call particular service_desc array value of the array?

答:
You can try this function: (Please optimize as per your requirements)</p>

```<code>$arr ="<YOUR ARRAY>";
$val = "service_desc";
echo removekey($arr, $val);

function removekey($arr, $val) {
    $return = array();
    foreach ($arr as $k => $v) {

        if (is_array($v) && $k !== $val) {

            removekey($v, $val);
            continue;
        }
        if ($k == $val) {

            echo ($arr[$k]);
            die;
         }
        $return[$k] = $v;
    }
    return $return;
}
</code>```

Body:
I'm getting below output as an array.

$array =
        Array
    (
        [12] => Array
            (
                [1] => Array
                    (
                        [14] => Array
                            (
                                [0] => Array
                                    (
                                        [name] => Avaya Implementation  Services
                                        [service_id] => 14
                                        [ser_type_id] => 1
                                        [service_desc] =>Avaya Implementation Servic
                                    )

                            )

                    )

            )

    );

I want to print only service_desc array value. and I don't want call like $array[12][1][14][0]['service_desc'];

How can I call particular service_desc array value of the array?

Body:
You can try this function: (Please optimize as per your requirements)

$arr ="<YOUR ARRAY>";
$val = "service_desc";
echo removekey($arr, $val);

function removekey($arr, $val) {
    $return = array();
    foreach ($arr as $k => $v) {

        if (is_array($v) && $k !== $val) {

            removekey($v, $val);
            continue;
        }
        if ($k == $val) {

            echo ($arr[$k]);
            die;
         }
        $return[$k] = $v;
    }
    return $return;
}


问:
ASP.NET C# foreach only print last item in list
I would like to show all valid links in a Literal Control container after clicking a button. However, only the last item in the list can be shown. I have used both for and foreach loop for testing but still not successful.

Any help is appreciated. Thanks in advance.

Here is my code:

```<code>public partial class Default : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            ValidateButton.Click += ValidateButtonHandler;
        }

        private void ValidateButtonHandler(object sender, EventArgs e)
        {
            List<string> validPages = new List<string>();
            validPages.Add("www.google.com");
            validPages.Add("www.yahoo.com");
            validPages.Add("www.facebook.com");

            List<string> invalidPages = new List<string>();
            invalidPages.Add("www.gogle.com");
            invalidPages.Add("www.yaoo.com");
            invalidPages.Add("www.facbook.com");

            for (int i = 0; i < validPages.Count; i++)
            {
                ValidLinksBox.Text = "<br/>" + validPages[i] + "<br/>";
            }

            foreach (string invalidPage in invalidPages)
            {
                InvalidLinksBox.Text = string.Format("<div class=\"alert success\"><p>{0}</p></div>", invalidPage);
            }
        }
    }
</code>```

Here is the aspx part:

```<code><div class="admin-page">
      <h1>Valid Links:</h1>
        <asp:Literal ID="ValidLinksBox" runat="server" />
      <h1>Invalid Links:</h1>
        <asp:Literal ID="InvalidLinksBox" runat="server" />
    <asp:Button ID="ValidateButton" runat="server" CssClass="btn btn-default" Text="Validate links" />
  </div>
</code>```

This is the result:

Validate Links result

答:
you are replacing value with every iteration , try to save the value before next iteration come

```<code>        StringBuilder sb1= new StringBuilder();
        StringBuilder sb2= new StringBuilder();
        for (int i = 0; i < validPages.Count; i++)
        {
            sb1.Append("<br/>" + validPages[i] + "<br/>");
        }
        ValidLinksBox.Text = sb1.ToString();
        foreach (string invalidPage in invalidPages)
        {
            sb2.Append(string.Format("<div class=\"alert success\"><p>{0}</p></div>", invalidPage));
        }
        ValidLinksBox.Text = sb2.ToString();
</code>```

Body:
I would like to show all valid links in a Literal Control container after clicking a button. However, only the last item in the list can be shown. I have used both for and foreach loop for testing but still not successful.

Any help is appreciated. Thanks in advance.

Here is my code:

public partial class Default : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            ValidateButton.Click += ValidateButtonHandler;
        }

        private void ValidateButtonHandler(object sender, EventArgs e)
        {
            List<string> validPages = new List<string>();
            validPages.Add("www.google.com");
            validPages.Add("www.yahoo.com");
            validPages.Add("www.facebook.com");

            List<string> invalidPages = new List<string>();
            invalidPages.Add("www.gogle.com");
            invalidPages.Add("www.yaoo.com");
            invalidPages.Add("www.facbook.com");

            for (int i = 0; i < validPages.Count; i++)
            {
                ValidLinksBox.Text = "
" + validPages[i] + "
";
            }

            foreach (string invalidPage in invalidPages)
            {
                InvalidLinksBox.Text = string.Format("

{0}

", invalidPage);
            }
        }
    }

Here is the aspx part:

Valid Links:

        <asp:Literal ID="ValidLinksBox" runat="server" />

Invalid Links:

        <asp:Literal ID="InvalidLinksBox" runat="server" />
    <asp:Button ID="ValidateButton" runat="server" CssClass="btn btn-default" Text="Validate links" />

This is the result:

Validate Links result

Body:
you are replacing value with every iteration , try to save the value before next iteration come

        StringBuilder sb1= new StringBuilder();
        StringBuilder sb2= new StringBuilder();
        for (int i = 0; i < validPages.Count; i++)
        {
            sb1.Append("<br/>" + validPages[i] + "<br/>");
        }
        ValidLinksBox.Text = sb1.ToString();
        foreach (string invalidPage in invalidPages)
        {
            sb2.Append(string.Format("<div class=\"alert success\"><p>{0}</p></div>", invalidPage));
        }
        ValidLinksBox.Text = sb2.ToString();


问:
Checkbox Header and Text in One Label
I have been trying to get a suitable styling for the following (including vertical alignment):

input {
    vertical-align:bottom;
    top:-5px;
}
label {
    display:inline;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><label><input type="checkbox"><h6>Header Text</h6> and Label text in one line</label>
<label><input type="checkbox"><h6>Header Text</h6> and Label text in one line</label>
<label><input type="checkbox"><h6>Header Text</h6> and Label text in one line</label></code>```

The issue is, after I added the
 header tag, it just wouldn't go into one line anymore. However I really do need that
 in there. I initially thought the label width wasn't wide enough, and that caused it to drop down below, but even after adding a generous width to the label css, nothing changed.

Is there anything more I can do here?

答:
Here is another example :

label {
  display:table;
}
label input,label h6{
  display:inline;
  vertical-align: middle;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><label><input type="checkbox"><h6>Header Text</h6> and Label text in one line</label>
<label><input type="checkbox"><h6>Header Text</h6> and Label text in one line</label>
<label><input type="checkbox"><h6>Header Text</h6> and Label text in one line</label></code>```

Title: Checkbox Header and Text in One Label

Body:
I have been trying to get a suitable styling for the following (including vertical alignment):

input {
    vertical-align:bottom;
    top:-5px;
}
label {
    display:inline;
}

<input type="checkbox">
Header Text
 and Label text in one line
<input type="checkbox">
Header Text
 and Label text in one line
<input type="checkbox">
Header Text
 and Label text in one line

The issue is, after I added the
 header tag, it just wouldn't go into one line anymore. However I really do need that
 in there. I initially thought the label width wasn't wide enough, and that caused it to drop down below, but even after adding a generous width to the label css, nothing changed.

Is there anything more I can do here?

Body:
Here is another example :

label {
  display:table;
}
label input,label h6{
  display:inline;
  vertical-align: middle;
}

<label><input type="checkbox"><h6>Header Text</h6> and Label text in one line</label>
<label><input type="checkbox"><h6>Header Text</h6> and Label text in one line</label>
<label><input type="checkbox"><h6>Header Text</h6> and Label text in one line</label>


问:
Unknown column keeps on appearing
I have already read the docs of CI however I am still encountering error with regards to my query. I posted my answer hoping you could help me with this.

```<code>    $code = $_SESSION['affiliate_code'];
    $email  = $this->db->query('select email from affiliates where referral_code = '.$code);
</code>```

What happening is that the query being created looks like this

```<code>    select email from affiliates where referral_code = dTE7TkDcOa86;
</code>```

but in order to work it should be like

```<code>    select email from affiliates where referral_code = 'dTE7TkDcOa86';
</code>```

How can I make my code work correctly?
I appreciate your help with this. Thank you.

答:
Try this:

```<code>$email  = $this->db->query("select email from affiliates where referral_code ='{$code}'");
</code>```

But better would be prepared Statements:

```<code>$sql = $this->db->query("select email from affiliates where referral_code = ?");
$email = $this->db->execute($sql, array($code)); // Or something like this
</code>```

Title: Unknown column keeps on appearing

Body:
I have already read the docs of CI however I am still encountering error with regards to my query. I posted my answer hoping you could help me with this.

    $code = $_SESSION['affiliate_code'];
    $email  = $this->db->query('select email from affiliates where referral_code = '.$code);

What happening is that the query being created looks like this

    select email from affiliates where referral_code = dTE7TkDcOa86;

but in order to work it should be like

    select email from affiliates where referral_code = 'dTE7TkDcOa86';

How can I make my code work correctly?
I appreciate your help with this. Thank you.

Body:
Try this:

$email  = $this->db->query("select email from affiliates where referral_code ='{$code}'");

But better would be prepared Statements:

$sql = $this->db->query("select email from affiliates where referral_code = ?");
$email = $this->db->execute($sql, array($code)); // Or something like this


问:
Find number in given range without if statement in javascript
I have 3 inputs Number min and max

if number is in range between min and max the function should return number

if number is less than min the function should return min

if number is greater than max the function should return max

```<code>3,4,5 -> 4
3,1,7 -> 3
9,1,7 -> 7
</code>```

I have tried doing it but cannot do it without if statement
Hint : Need to use Math function

```<code>function minCalulator(number,min,max){
    if(Math.min(number,min) == number){
        return min;
    }
    if(Math.min(number,max) === max){
            return max;
    }
    return number;
}
</code>```

How to implement this without if or any conditional statements?

答:
Math.min() return the smallest in an array of numbers.

```<code>Math.min(3,4,5) will output 3
Math.max(3,4,5) will output 5
</code>```

You could do:

```<code>var x = Math.min(number,maxNumber) //if the number is bigger than the maximum, x will keep the maximum, if the number is smaller than the max, x will keep number.
</code>```

then

```<code>var x = Math.max(x,minNumber) //same principal
</code>```

x will finally hold a number that is in the range you need.

Here's a fiddle with what you're looking for:
jsFiddle

Body:
I have 3 inputs Number min and max

if number is in range between min and max the function should return number

if number is less than min the function should return min

if number is greater than max the function should return max

3,4,5 -> 4
3,1,7 -> 3
9,1,7 -> 7

I have tried doing it but cannot do it without if statement
Hint : Need to use Math function

function minCalulator(number,min,max){
    if(Math.min(number,min) == number){
        return min;
    }
    if(Math.min(number,max) === max){
            return max;
    }
    return number;
}

How to implement this without if or any conditional statements?

Body:
Math.min() return the smallest in an array of numbers.

Math.min(3,4,5) will output 3
Math.max(3,4,5) will output 5

You could do:

var x = Math.min(number,maxNumber) //if the number is bigger than the maximum, x will keep the maximum, if the number is smaller than the max, x will keep number.

then

var x = Math.max(x,minNumber) //same principal

x will finally hold a number that is in the range you need.

Here's a fiddle with what you're looking for:
jsFiddle


问:
Angular2 ngFor get only selected values
I have a for loop that populates pre-defined hobbies as checkboxes.
hobbies = ['Sport', 'Reading', 'Singing', 'Travelling', 'Movies', 'Cooking'];

```<code><label *ngFor="let hobby of chunk" #checkbox class="mdl-checkbox mdl-js-checkbox">
    <input type="checkbox" name="hobbies" [value]="hobby"
    [(ngModel)]="hobby.selected" (change)="populateMyHobbies(hobby)" class="mdl-checkbox__input">
    <span class="mdl-checkbox__label">{{hobby}}</span>
</label>
</code>```

I have created an array my_hobbies: string[]=[]; in which I want to collect only the selected values i.e. ['Sport',..]

My function that collects those values is so far:

```<code>populateMyHobbies(value){

    this.my_hobbies.push(value)
    console.log(this.my_hobbies)
}
</code>```

How can I achieve this? Right now on check and uncheck the values get added even same value multiple times.

答:
Template side :

```<code><label *ngFor="let hobby of chunk" #checkbox class="mdl-checkbox mdl-js-checkbox">
    <input type="checkbox" name="hobbies" [value]="hobby"
    [(ngModel)]="hobby.selected" (change)="populateMyHobbies(hobby,$event.target.checked)" class="mdl-checkbox__input">
    <span class="mdl-checkbox__label">{{hobby}}</span>
</label>
</code>```

Component side :

```<code>selectedHobbies = [];

populateMyHobbies(value , status:boolean)
{
    if(this.selectedHobbies.indexOf(value) === -1 && status)
    {
        this.selectedHobbies.push(value);
    }
    else if(!status)
    {
        let index = this.selectedHobbies.indexOf(value);
        this.selectedHobbies.splice(index, 1);
    }
}
</code>```

Title: Angular2 ngFor get only selected values

Body:
I have a for loop that populates pre-defined hobbies as checkboxes.
hobbies = ['Sport', 'Reading', 'Singing', 'Travelling', 'Movies', 'Cooking'];

    <input type="checkbox" name="hobbies" [value]="hobby"
    [(ngModel)]="hobby.selected" (change)="populateMyHobbies(hobby)" class="mdl-checkbox__input">
    {{hobby}}

I have created an array my_hobbies: string[]=[]; in which I want to collect only the selected values i.e. ['Sport',..]

My function that collects those values is so far:

populateMyHobbies(value){

    this.my_hobbies.push(value)
    console.log(this.my_hobbies)
}

How can I achieve this? Right now on check and uncheck the values get added even same value multiple times.

Body:
Template side :

<label *ngFor="let hobby of chunk" #checkbox class="mdl-checkbox mdl-js-checkbox">
    <input type="checkbox" name="hobbies" [value]="hobby"
    [(ngModel)]="hobby.selected" (change)="populateMyHobbies(hobby,$event.target.checked)" class="mdl-checkbox__input">
    <span class="mdl-checkbox__label">{{hobby}}</span>
</label>

Component side :

selectedHobbies = [];

populateMyHobbies(value , status:boolean)
{
    if(this.selectedHobbies.indexOf(value) === -1 && status)
    {
        this.selectedHobbies.push(value);
    }
    else if(!status)
    {
        let index = this.selectedHobbies.indexOf(value);
        this.selectedHobbies.splice(index, 1);
    }
}


问:
Django Tastypie always returning 401 unauthorized
I'm using ajax requests to my tastypie resources, but even if I use SessionAuthentication() and DjangoAuthorization(), it gets always 401.

resources.py

```<code>class EventsResource(ModelResource):

user = fields.ForeignKey(UserResource, 'user')

    class Meta:
        queryset = Event.objects.all()
        resource_name = 'events'
        filtering = {'start': ALL,
                     'end':ALL
                     }
        list_allowed_methods = ['get', 'post','put', 'patch']
        detail_allowed_methods = ['get', 'post', 'put', 'delete']
        authentication = SessionAuthentication()
        authorization = Authorization()
        include_resource_uri = True
        limit = 0
        always_return_data = True
</code>```

This is a resource for a calendar, so I have a Event Model, and my ajax requests are in a javascript file loaded in django-admin; I also checked if requests headers had csrf token and session id, but it doesn't work.

```<code>.ajax({
                    url:  event.resource_uri,
                    dataType: 'json',
                    contentType: 'application/json; encode=UTF-8',
                    type: 'DELETE',
                    success: function () {
                        $calendar.fullCalendar('removeEvents');
                        $calendar.fullCalendar('refetchEvents');
                        $('#modal-confirm').modal('hide');
                        showmsg('Evento eliminato correttamente', 'warning');
                    }
                });
</code>```

答:
You should pass the CSRF token in as POST data with every POST request. The recommended source of the CSRF token is from cookies, like this:

```<code>getCookie: function(name) {
    var cookieValue = null;
    if (document.cookie && document.cookie != '') {
        var cookies = document.cookie.split(';');
        for (var i = 0; i < cookies.length; i++) {
            var cookie = $.trim(cookies[i]);
            if (cookie.substring(0, name.length + 1) == (name + '=')) {
                cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                break;
            }
        }
    }
    return cookieValue;
}
</code>```

Then, you’ll set the header on your AJAX request like this:

```<code>var csrftoken = this.getCookie('csrftoken');
//Use Setup prior or use the beforeSend on the fly
/*$.ajaxSetup({
    beforeSend: function(xhr, settings) {
            xhr.setRequestHeader("X-CSRFToken", csrftoken);
    }
});*/
$.ajax({
    type: "POST",
    dataType: "json",
    contentType: "application/json",
    url: "/my/uri/",
    data: {"any": "thing"},
    beforeSend: function(xhr, settings) {
        xhr.setRequestHeader("X-CSRFToken", csrftoken);
    },
    success: function(data) {
        console.log("Weeey") ;
    }
});
</code>```

Reference: https://docs.djangoproject.com/en/1.8/ref/csrf/#ajax

Body:
I'm using ajax requests to my tastypie resources, but even if I use SessionAuthentication() and DjangoAuthorization(), it gets always 401.

resources.py

class EventsResource(ModelResource):

user = fields.ForeignKey(UserResource, 'user')

    class Meta:
        queryset = Event.objects.all()
        resource_name = 'events'
        filtering = {'start': ALL,
                     'end':ALL
                     }
        list_allowed_methods = ['get', 'post','put', 'patch']
        detail_allowed_methods = ['get', 'post', 'put', 'delete']
        authentication = SessionAuthentication()
        authorization = Authorization()
        include_resource_uri = True
        limit = 0
        always_return_data = True

This is a resource for a calendar, so I have a Event Model, and my ajax requests are in a javascript file loaded in django-admin; I also checked if requests headers had csrf token and session id, but it doesn't work.

.ajax({
                    url:  event.resource_uri,
                    dataType: 'json',
                    contentType: 'application/json; encode=UTF-8',
                    type: 'DELETE',
                    success: function () {
                        $calendar.fullCalendar('removeEvents');
                        $calendar.fullCalendar('refetchEvents');
                        $('#modal-confirm').modal('hide');
                        showmsg('Evento eliminato correttamente', 'warning');
                    }
                });

Body:
You should pass the CSRF token in as POST data with every POST request. The recommended source of the CSRF token is from cookies, like this:

getCookie: function(name) {
    var cookieValue = null;
    if (document.cookie && document.cookie != '') {
        var cookies = document.cookie.split(';');
        for (var i = 0; i < cookies.length; i++) {
            var cookie = $.trim(cookies[i]);
            if (cookie.substring(0, name.length + 1) == (name + '=')) {
                cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                break;
            }
        }
    }
    return cookieValue;
}

Then, you’ll set the header on your AJAX request like this:

var csrftoken = this.getCookie('csrftoken');
//Use Setup prior or use the beforeSend on the fly
/*$.ajaxSetup({
    beforeSend: function(xhr, settings) {
            xhr.setRequestHeader("X-CSRFToken", csrftoken);
    }
});*/
$.ajax({
    type: "POST",
    dataType: "json",
    contentType: "application/json",
    url: "/my/uri/",
    data: {"any": "thing"},
    beforeSend: function(xhr, settings) {
        xhr.setRequestHeader("X-CSRFToken", csrftoken);
    },
    success: function(data) {
        console.log("Weeey") ;
    }
});

Reference: https://docs.djangoproject.com/en/1.8/ref/csrf/#ajax


问:
Xcode 7: App installation failed: A valid provisioning profile for this executable was not found
I have already searched and almost implemented max solution but it's not installing any app even though if I am creating just sample single view app.

App installation failed

  A valid provisioning profile for this executable was not found.

答:
Make sure you have added device UDID in your provisioning profile.

Go to provisioning portal.

Edit provisioning profile.

Make sure device is checked.

Done, download

Use new Profile

Another possible reason: Device date is set to later than the expiry of you provisioning profile.This is very weird but, it could happen.

ContentLicense: CC BY-SA 4.0


问:
How to set in a Report the format date in TextBox based current RegionalSetting?
I have in my Report, I'm using Visual Studio Ultimate 2013 a TextBox with DATE value

I would like to set the DATE format by current Regional Setting.

So : if is US I wold like to set format yyyy/mm/dd etc..
There is a possible way in Visual Studio. There is a specific property or formula ?

I need to set dynamically the date format.

Thanks!

答: You will need to navigate to Text box properties > Number > Date. Select any date format which begins with asterisk(*) as it denotes that regional settings will be applied. You can refer to the screenshot below for details


问:
SAP Sybase ASE: Huge Space Requirements in Tempdb
We have SAP Solution Manager running on a SAP Sybase ASE 15.7 Database. That means we have a user database holding the application data, and a special tempdb exclusively mapped to this user database.

Over the last weeks, the database server has been loggging messages like the following:

```<code>Can't allocate Space forobject 'temp worktable' in database 'saptempdb'
because 'system' segment is full/has no free extents.[...]
</code>```

So far so good. I have been extending the device and the database segment over and over up to a size of now 150 GB but the message keeps appearing. From the application administrators, I keep getting the statement that there is no possibility to further tune the application's configuration. I have been trying to manually get more information on what is really happening on the tempdb whenever the log message appears (for example by querying the sysusages table), but it seems I can not catch the database red-handed when it tries to use all the space in the system segment of saptempdb.

Does anyone have any tips or procedures for properly monitoring a temp database and finding the statements or transactions which cause a demand for huge temporary worktables?

答: There can be many reasons why space is consumed in your tempdb. You may get some insights by regularly querying the MDA table monProcessObject.</p>

Body:
We have SAP Solution Manager running on a SAP Sybase ASE 15.7 Database. That means we have a user database holding the application data, and a special tempdb exclusively mapped to this user database.

Over the last weeks, the database server has been loggging messages like the following:

Can't allocate Space forobject 'temp worktable' in database 'saptempdb'
because 'system' segment is full/has no free extents.[...]

So far so good. I have been extending the device and the database segment over and over up to a size of now 150 GB but the message keeps appearing. From the application administrators, I keep getting the statement that there is no possibility to further tune the application's configuration. I have been trying to manually get more information on what is really happening on the tempdb whenever the log message appears (for example by querying the sysusages table), but it seems I can not catch the database red-handed when it tries to use all the space in the system segment of saptempdb.

Does anyone have any tips or procedures for properly monitoring a temp database and finding the statements or transactions which cause a demand for huge temporary worktables?


问:
How can I write the query as raw in Laravel?
Here is my query:

```<code>SELECT rid
FROM relations
WHERE rootid IN (736, 781)
GROUP BY rid HAVING COUNT(rid) = 2");
</code>```

I'm trying to implement that in Laravel. How can I do that? (both "query builder and eloquent approaches are fine to me")

This doesn't work: (it throws "something went wrong")

```<code>DB::table('relations')
->select('')
->whereRaw('rootid IN (736, 781)')
->groupBy('rid')
->havingRaw('COUNT(rid) = 2')
->get();
</code>```

答:
Try this</p>

```<code>DB::table('relations')
->select(DB::raw('count(*) as user_count, status'))
->whereRaw('rootid IN (736, 781)')
->groupBy('rid')
->having(DB::Raw('COUNT(rid) = 2'))
->get();
</code>```

Body:
Here is my query:

SELECT rid
FROM relations
WHERE rootid IN (736, 781)
GROUP BY rid HAVING COUNT(rid) = 2");

I'm trying to implement that in Laravel. How can I do that? (both "query builder and eloquent approaches are fine to me")

This doesn't work: (it throws "something went wrong")

DB::table('relations')
->select('')
->whereRaw('rootid IN (736, 781)')
->groupBy('rid')
->havingRaw('COUNT(rid) = 2')
->get();

Body:
Try this

DB::table('relations')
->select(DB::raw('count(*) as user_count, status'))
->whereRaw('rootid IN (736, 781)')
->groupBy('rid')
->having(DB::Raw('COUNT(rid) = 2'))
->get();


问:
Get the most precise time in Ruby
I want to get the most possible precis time using Ruby.  For example:

```<code>3.times.map do
  Thread.new do
    # Expect 3 differnt results from each thread
    p Time.now.precis_time
  end
end.each(&:join)
</code>```

However, even using the strftime, I still can not achieve the goal. So is there any other way to get this?

答:
On JRuby, you can use java.lang.System.nano_time :

```<code>java.lang.System.nano_time - java.lang.System.nano_time
# -15607
</code>```

to get nanoseconds since a fixed but arbitrary origin. From the documentation :

This method can only be used to measure elapsed time and is not
  related to any other notion of system or wall-clock time. The value
  returned represents nanoseconds since some fixed but arbitrary origin
  time (perhaps in the future, so values may be negative). The same
  origin is used by all invocations of this method in an instance of a
  Java virtual machine; other virtual machine instances are likely to
  use a different origin.

If you want a precise Time with Java < 9, you could use currentTimeMillis :

```<code>java.lang.System.current_time_millis
#=> 1491214503112
</code>```

But then, you wouldn't get more information than from Time.now :

```<code>Time.now.to_f
#=> 1491214592.562
</code>```

So Time.now might be your best bet : it will work on any Ruby version on any system. Note that nanoseconds precision doesn't mean nanoseconds accuracy.

I dare say you could ignore any digit related to a shorter time than milliseconds. You could output the distance between NYC and Los-Angeles in micrometers, it doesn't mean it would be useful though.

Title: Get the most precise time in Ruby

Body:
I want to get the most possible precis time using Ruby.  For example:

3.times.map do
  Thread.new do
    # Expect 3 differnt results from each thread
    p Time.now.precis_time
  end
end.each(&:join)

However, even using the strftime, I still can not achieve the goal. So is there any other way to get this?

Body:
On JRuby, you can use java.lang.System.nano_time :

java.lang.System.nano_time - java.lang.System.nano_time
# -15607

to get nanoseconds since a fixed but arbitrary origin. From the documentation :

This method can only be used to measure elapsed time and is not
  related to any other notion of system or wall-clock time. The value
  returned represents nanoseconds since some fixed but arbitrary origin
  time (perhaps in the future, so values may be negative). The same
  origin is used by all invocations of this method in an instance of a
  Java virtual machine; other virtual machine instances are likely to
  use a different origin.

If you want a precise Time with Java < 9, you could use currentTimeMillis :

java.lang.System.current_time_millis
#=> 1491214503112

But then, you wouldn't get more information than from Time.now :

Time.now.to_f
#=> 1491214592.562

So Time.now might be your best bet : it will work on any Ruby version on any system. Note that nanoseconds precision doesn't mean nanoseconds accuracy.

I dare say you could ignore any digit related to a shorter time than milliseconds. You could output the distance between NYC and Los-Angeles in micrometers, it doesn't mean it would be useful though.


问:
GTLRDriveQuery_FilesCreate (Google REST API)
1.I need to create a folder in google drive.And I use this code to do this(official code from google developers page):

```<code>GTLRDrive_File *metadata = [GTLRDrive_File object];
metadata.name = @"Invoices";
metadata.mimeType = @"application/vnd.google-apps.folder";
GTLRDriveQuery_FilesCreate *query = [GTLRDriveQuery_FilesCreate queryWithObject:metadata
                                                               uploadParameters:nil];
query.fields = @"id";
[driveService executeQuery:query completionHandler:^(GTLRServiceTicket *ticket,
                                                     GTLRDrive_File *file,
                                                     NSError *error) {
    if (error == nil) {
        NSLog(@"File ID %@", file.identifier);
    } else {
        NSLog(@"An error occurred: %@", error);
    }
}];
</code>```

And the folder creates  fine!
The problem is that each time I run the App , the code creates dublicates of the folder in my Google Drive.But I need to create only one folder of that name and kind.
I know its a rookie question, but I cannot figure it out how to do this.And I know that I should compare( GTLRDrive_File *file) identifier (as it is a unique string),but how do I do it?

2.So the question is :How do check if the identifier is already created and compare it ?
I understand that to fulfil my tsk I should check if the Identifier is exists,if not I should create it, and if its doesn't exist do nothing.

答: The simplest way is to do a files.get of the id. It will return status 200 and the file object if it's there, or 404 not found.

Body:
1.I need to create a folder in google drive.And I use this code to do this(official code from google developers page):

GTLRDrive_File *metadata = [GTLRDrive_File object];
metadata.name = @"Invoices";
metadata.mimeType = @"application/vnd.google-apps.folder";
GTLRDriveQuery_FilesCreate *query = [GTLRDriveQuery_FilesCreate queryWithObject:metadata
                                                               uploadParameters:nil];
query.fields = @"id";
[driveService executeQuery:query completionHandler:^(GTLRServiceTicket *ticket,
                                                     GTLRDrive_File *file,
                                                     NSError *error) {
    if (error == nil) {
        NSLog(@"File ID %@", file.identifier);
    } else {
        NSLog(@"An error occurred: %@", error);
    }
}];

And the folder creates  fine!
The problem is that each time I run the App , the code creates dublicates of the folder in my Google Drive.But I need to create only one folder of that name and kind.
I know its a rookie question, but I cannot figure it out how to do this.And I know that I should compare( GTLRDrive_File *file) identifier (as it is a unique string),but how do I do it?

2.So the question is :How do check if the identifier is already created and compare it ?
I understand that to fulfil my tsk I should check if the Identifier is exists,if not I should create it, and if its doesn't exist do nothing.


答:
do like this:</p>

```<code>$email  = $this->db->query("select email from affiliates where referral_code = '$code'");
</code>```

Title: Unknown column keeps on appearing

Body:
do like this:

$email  = $this->db->query("select email from affiliates where referral_code = '$code'");


答:
Convert multidimensional array to single array using iterator_to_array

REF:  http://php.net/manual/en/function.iterator-to-array.php

```<code>$service_desc= iterator_to_array(new RecursiveIteratorIterator(new RecursiveArrayIterator($your_array)), 0);
print_r($service_desc);
</code>```

Result:

```<code>Array
(
    [name] => Avaya Implementation  Services
    [service_id] => 14
    [ser_type_id] => 1
    [service_desc] =>Avaya Implementation Servic
)
</code>```

Title: How can I call particular array value of array in php?

Body:
I'm getting below output as an array.

$array =
        Array
    (
        [12] => Array
            (
                [1] => Array
                    (
                        [14] => Array
                            (
                                [0] => Array
                                    (
                                        [name] => Avaya Implementation  Services
                                        [service_id] => 14
                                        [ser_type_id] => 1
                                        [service_desc] =>Avaya Implementation Servic
                                    )

                            )

                    )

            )

    );

I want to print only service_desc array value. and I don't want call like $array[12][1][14][0]['service_desc'];

How can I call particular service_desc array value of the array?

Body:
Convert multidimensional array to single array using iterator_to_array

REF:  http://php.net/manual/en/function.iterator-to-array.php

$service_desc= iterator_to_array(new RecursiveIteratorIterator(new RecursiveArrayIterator($your_array)), 0);
print_r($service_desc);

Result:

Array
(
    [name] => Avaya Implementation  Services
    [service_id] => 14
    [ser_type_id] => 1
    [service_desc] =>Avaya Implementation Servic
)


问:
How do I start my WifiDirect activity from my home screen?
I have two buttons on my start screen, one for starting google maps. And one "search button" for wanting to find peers and connect to them via WiFi direct. When I press the search button I want the app to start searching directly, and displaying the peers. What should I write for the "WiFiDirectActivity" to start when I press the search button on my HomeScreen?

My HomeScreen class:

```<code>public class HomeScreen extends Activity {

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.home_screen);

    Button mapButton = (Button) findViewById(R.id.mapButton);

    mapButton.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View view) {
            Intent intent = new Intent(HomeScreen.this, MapsActivity.class);
            startActivity(intent);
        }

    });

    Button sensorButton = (Button) findViewById(R.id.sensorBtn);

    sensorButton.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View view) {
            Intent intent = new Intent(HomeScreen.this, WiFiDirectActivity.class);
            startActivity(intent);
        }

    });

}

}
</code>```

My WiFiDirectActivity class:

```<code>public class WiFiDirectActivity extends Activity implements WifiP2pManager.ChannelListener, DeviceListFragment.DeviceActionListener {

public static final String TAG = "wifidirectdemo";
private WifiP2pManager manager;
private boolean isWifiP2pEnabled = false;
private boolean retryChannel = false;

private final IntentFilter intentFilter = new IntentFilter();
private WifiP2pManager.Channel channel;
private BroadcastReceiver receiver = null;

/**
 * @param isWifiP2pEnabled the isWifiP2pEnabled to set
 */
public void setIsWifiP2pEnabled(boolean isWifiP2pEnabled) {
    this.isWifiP2pEnabled = isWifiP2pEnabled;
}

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main_peers);

    // add necessary intent values to be matched.

    intentFilter.addAction(WifiP2pManager.WIFI_P2P_STATE_CHANGED_ACTION);
    intentFilter.addAction(WifiP2pManager.WIFI_P2P_PEERS_CHANGED_ACTION);
    intentFilter.addAction(WifiP2pManager.WIFI_P2P_CONNECTION_CHANGED_ACTION);
    intentFilter.addAction(WifiP2pManager.WIFI_P2P_THIS_DEVICE_CHANGED_ACTION);

    manager = (WifiP2pManager) getSystemService(Context.WIFI_P2P_SERVICE);
    channel = manager.initialize(this, getMainLooper(), null);

    Button sensorButton = (Button) findViewById(R.id.sensorBtn);

    sensorButton.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View view) {

            if (!isWifiP2pEnabled) {
                Toast.makeText(WiFiDirectActivity.this, R.string.p2p_off_warning,
                        Toast.LENGTH_SHORT).show();
                return;
            }
            final DeviceListFragment fragment = (DeviceListFragment) getFragmentManager()
                    .findFragmentById(R.id.frag_list);
            fragment.onInitiateDiscovery();
            manager.discoverPeers(channel, new WifiP2pManager.ActionListener() {

                @Override
                public void onSuccess() {
                    Toast.makeText(WiFiDirectActivity.this, "Discovery Initiated",
                            Toast.LENGTH_SHORT).show();
                }

                @Override
                public void onFailure(int reasonCode) {
                    Toast.makeText(WiFiDirectActivity.this, "Discovery Failed : " + reasonCode,
                            Toast.LENGTH_SHORT).show();
                }

            });

        }

    });

}

/** register the BroadcastReceiver with the intent values to be matched */
@Override
public void onResume() {
    super.onResume();
    receiver = new WiFiDirectBroadcastReceiver(manager, channel, this);
    registerReceiver(receiver, intentFilter);
}

@Override
public void onPause() {
    super.onPause();
    unregisterReceiver(receiver);
}

/**
 * Remove all peers and clear all fields. This is called on
 * BroadcastReceiver receiving a state change event.
 */
public void resetData() {
    DeviceListFragment fragmentList = (DeviceListFragment) getFragmentManager()
            .findFragmentById(R.id.frag_list);
    DeviceDetailFragment fragmentDetails = (DeviceDetailFragment) getFragmentManager()
            .findFragmentById(R.id.frag_detail);
    if (fragmentList != null) {
        fragmentList.clearPeers();
    }
    if (fragmentDetails != null) {
        fragmentDetails.resetViews();
    }
}

@Override
public void showDetails(WifiP2pDevice device) {
    DeviceDetailFragment fragment = (DeviceDetailFragment) getFragmentManager()
            .findFragmentById(R.id.frag_detail);
    fragment.showDetails(device);

}

@Override
public void connect(WifiP2pConfig config) {
    manager.connect(channel, config, new WifiP2pManager.ActionListener() {

        @Override
        public void onSuccess() {
            // WiFiDirectBroadcastReceiver will notify us. Ignore for now.
        }

        @Override
        public void onFailure(int reason) {
            Toast.makeText(WiFiDirectActivity.this, "Connect failed. Retry.",
                    Toast.LENGTH_SHORT).show();
        }
    });
}

@Override
public void disconnect() {
    final DeviceDetailFragment fragment = (DeviceDetailFragment) getFragmentManager()
            .findFragmentById(R.id.frag_detail);
    fragment.resetViews();
    manager.removeGroup(channel, new WifiP2pManager.ActionListener() {

        @Override
        public void onFailure(int reasonCode) {
            Log.d(TAG, "Disconnect failed. Reason :" + reasonCode);

        }

        @Override
        public void onSuccess() {
            fragment.getView().setVisibility(View.GONE);
        }

    });
}

@Override
public void onChannelDisconnected() {
    // we will try once more
    if (manager != null && !retryChannel) {
        Toast.makeText(this, "Channel lost. Trying again", Toast.LENGTH_LONG).show();
        resetData();
        retryChannel = true;
        manager.initialize(this, getMainLooper(), this);
    } else {
        Toast.makeText(this,
                "Severe! Channel is probably lost premanently. Try Disable/Re-Enable P2P.",
                Toast.LENGTH_LONG).show();
    }
}

@Override
public void cancelDisconnect() {

    /*
     * A cancel abort request by user. Disconnect i.e. removeGroup if
     * already connected. Else, request WifiP2pManager to abort the ongoing
     * request
     */
    if (manager != null) {
        final DeviceListFragment fragment = (DeviceListFragment) getFragmentManager()
                .findFragmentById(R.id.frag_list);
        if (fragment.getDevice() == null
                || fragment.getDevice().status == WifiP2pDevice.CONNECTED) {
            disconnect();
        } else if (fragment.getDevice().status == WifiP2pDevice.AVAILABLE
                || fragment.getDevice().status == WifiP2pDevice.INVITED) {

            manager.cancelConnect(channel, new WifiP2pManager.ActionListener() {

                @Override
                public void onSuccess() {
                    Toast.makeText(WiFiDirectActivity.this, "Aborting connection",
                            Toast.LENGTH_SHORT).show();
                }

                @Override
                public void onFailure(int reasonCode) {
                    Toast.makeText(WiFiDirectActivity.this,
                            "Connect abort request failed. Reason Code: " + reasonCode,
                            Toast.LENGTH_SHORT).show();
                }
            });
        }
    }

}
}
</code>```

The code that I am trying to redo from a search button in the menu to a search button on a different screen. (I removed the direct discover).

```<code>public class WiFiDirectActivity extends Activity implements WifiP2pManager.ChannelListener, DeviceListFragment.DeviceActionListener {

...

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.action_items, menu);
    return true;
}

/*
 * (non-Javadoc)
 * @see android.app.Activity#onOptionsItemSelected(android.view.MenuItem)
 */
@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
        case R.id.atn_direct_enable:
            if (manager != null && channel != null) {

                // Since this is the system wireless settings activity, it's
                // not going to send us a result. We will be notified by
                // WiFiDeviceBroadcastReceiver instead.

                startActivity(new Intent(Settings.ACTION_WIRELESS_SETTINGS));
            } else {
                Log.e(TAG, "channel or manager is null");
            }
            return true;

        case R.id.atn_direct_discover:
            Log.d("ADebugTag", "Value: " + isWifiP2pEnabled);

            if (!isWifiP2pEnabled) {
                Toast.makeText(WiFiDirectActivity.this, R.string.p2p_off_warning,
                        Toast.LENGTH_SHORT).show();
                return true;
            }
            final DeviceListFragment fragment = (DeviceListFragment) getFragmentManager()
                    .findFragmentById(R.id.frag_list);
            fragment.onInitiateDiscovery();
            manager.discoverPeers(channel, new WifiP2pManager.ActionListener() {

                @Override
                public void onSuccess() {
                    Toast.makeText(WiFiDirectActivity.this, "Discovery Initiated",
                            Toast.LENGTH_SHORT).show();
                }

                @Override
                public void onFailure(int reasonCode) {
                    Toast.makeText(WiFiDirectActivity.this, "Discovery Failed : " + reasonCode,
                            Toast.LENGTH_SHORT).show();
                }
            });
            return true;
        default:
            return super.onOptionsItemSelected(item);
    }
}
</code>```

答:
You can start to perform search in onResume as follows :</p>

```<code>public class WiFiDirectActivity extends Activity implements WifiP2pManager.ChannelListener, DeviceListFragment.DeviceActionListener {

public static final String TAG = "wifidirectdemo";
private WifiP2pManager manager;
private boolean isWifiP2pEnabled = false;
private boolean retryChannel = false;

private final IntentFilter intentFilter = new IntentFilter();
private WifiP2pManager.Channel channel;
private BroadcastReceiver receiver = null;

/**
 * @param isWifiP2pEnabled the isWifiP2pEnabled to set
 */
public void setIsWifiP2pEnabled(boolean isWifiP2pEnabled) {
    this.isWifiP2pEnabled = isWifiP2pEnabled;
}

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main_peers);

    // add necessary intent values to be matched.

    intentFilter.addAction(WifiP2pManager.WIFI_P2P_STATE_CHANGED_ACTION);
    intentFilter.addAction(WifiP2pManager.WIFI_P2P_PEERS_CHANGED_ACTION);
    intentFilter.addAction(WifiP2pManager.WIFI_P2P_CONNECTION_CHANGED_ACTION);
    intentFilter.addAction(WifiP2pManager.WIFI_P2P_THIS_DEVICE_CHANGED_ACTION);

    manager = (WifiP2pManager) getSystemService(Context.WIFI_P2P_SERVICE);
    channel = manager.initialize(this, getMainLooper(), null);

    Button sensorButton = (Button) findViewById(R.id.sensorBtn);

    sensorButton.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View view) {

            if (!isWifiP2pEnabled) {
                Toast.makeText(WiFiDirectActivity.this, R.string.p2p_off_warning,
                        Toast.LENGTH_SHORT).show();
                return;
            }
            final DeviceListFragment fragment = (DeviceListFragment) getFragmentManager()
                    .findFragmentById(R.id.frag_list);
            fragment.onInitiateDiscovery();
            manager.discoverPeers(channel, new WifiP2pManager.ActionListener() {

                @Override
                public void onSuccess() {
                    Toast.makeText(WiFiDirectActivity.this, "Discovery Initiated",
                            Toast.LENGTH_SHORT).show();
                }

                @Override
                public void onFailure(int reasonCode) {
                    Toast.makeText(WiFiDirectActivity.this, "Discovery Failed : " + reasonCode,
                            Toast.LENGTH_SHORT).show();
                }

            });

        }

    });

}

/** register the BroadcastReceiver with the intent values to be matched */
@Override
public void onResume() {
    super.onResume();
    receiver = new WiFiDirectBroadcastReceiver(manager, channel, this);
    registerReceiver(receiver, intentFilter);
    performSearch(); // start searching devices
}

@Override
public void onPause() {
    super.onPause();
    unregisterReceiver(receiver);
}

/**
 * Remove all peers and clear all fields. This is called on
 * BroadcastReceiver receiving a state change event.
 */
public void resetData() {
    DeviceListFragment fragmentList = (DeviceListFragment) getFragmentManager()
            .findFragmentById(R.id.frag_list);
    DeviceDetailFragment fragmentDetails = (DeviceDetailFragment) getFragmentManager()
            .findFragmentById(R.id.frag_detail);
    if (fragmentList != null) {
        fragmentList.clearPeers();
    }
    if (fragmentDetails != null) {
        fragmentDetails.resetViews();
    }
}

@Override
public void showDetails(WifiP2pDevice device) {
    DeviceDetailFragment fragment = (DeviceDetailFragment) getFragmentManager()
            .findFragmentById(R.id.frag_detail);
    fragment.showDetails(device);

}

@Override
public void connect(WifiP2pConfig config) {
    manager.connect(channel, config, new WifiP2pManager.ActionListener() {

        @Override
        public void onSuccess() {
            // WiFiDirectBroadcastReceiver will notify us. Ignore for now.
        }

        @Override
        public void onFailure(int reason) {
            Toast.makeText(WiFiDirectActivity.this, "Connect failed. Retry.",
                    Toast.LENGTH_SHORT).show();
        }
    });
}

@Override
public void disconnect() {
    final DeviceDetailFragment fragment = (DeviceDetailFragment) getFragmentManager()
            .findFragmentById(R.id.frag_detail);
    fragment.resetViews();
    manager.removeGroup(channel, new WifiP2pManager.ActionListener() {

        @Override
        public void onFailure(int reasonCode) {
            Log.d(TAG, "Disconnect failed. Reason :" + reasonCode);

        }

        @Override
        public void onSuccess() {
            fragment.getView().setVisibility(View.GONE);
        }

    });
}

@Override
public void onChannelDisconnected() {
    // we will try once more
    if (manager != null && !retryChannel) {
        Toast.makeText(this, "Channel lost. Trying again", Toast.LENGTH_LONG).show();
        resetData();
        retryChannel = true;
        manager.initialize(this, getMainLooper(), this);
    } else {
        Toast.makeText(this,
                "Severe! Channel is probably lost premanently. Try Disable/Re-Enable P2P.",
                Toast.LENGTH_LONG).show();
    }
}

@Override
public void cancelDisconnect() {

    /*
     * A cancel abort request by user. Disconnect i.e. removeGroup if
     * already connected. Else, request WifiP2pManager to abort the ongoing
     * request
     */
    if (manager != null) {
        final DeviceListFragment fragment = (DeviceListFragment) getFragmentManager()
                .findFragmentById(R.id.frag_list);
        if (fragment.getDevice() == null
                || fragment.getDevice().status == WifiP2pDevice.CONNECTED) {
            disconnect();
        } else if (fragment.getDevice().status == WifiP2pDevice.AVAILABLE
                || fragment.getDevice().status == WifiP2pDevice.INVITED) {

            manager.cancelConnect(channel, new WifiP2pManager.ActionListener() {

                @Override
                public void onSuccess() {
                    Toast.makeText(WiFiDirectActivity.this, "Aborting connection",
                            Toast.LENGTH_SHORT).show();
                }

                @Override
                public void onFailure(int reasonCode) {
                    Toast.makeText(WiFiDirectActivity.this,
                            "Connect abort request failed. Reason Code: " + reasonCode,
                            Toast.LENGTH_SHORT).show();
                }
            });
        }
    }

}

private void performSearch() {
   if (!isWifiP2pEnabled) {
            Toast.makeText(WiFiDirectActivity.this, R.string.p2p_off_warning,
                    Toast.LENGTH_SHORT).show();
            return;
        }
        final DeviceListFragment fragment = (DeviceListFragment) getFragmentManager()
                .findFragmentById(R.id.frag_list);
        fragment.onInitiateDiscovery();
        manager.discoverPeers(channel, new WifiP2pManager.ActionListener() {

            @Override
            public void onSuccess() {
                Toast.makeText(WiFiDirectActivity.this, "Discovery Initiated",
                        Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onFailure(int reasonCode) {
                Toast.makeText(WiFiDirectActivity.this, "Discovery Failed : " + reasonCode,
                        Toast.LENGTH_SHORT).show();
            }

        });
}

}
</code>```

Body:
I have two buttons on my start screen, one for starting google maps. And one "search button" for wanting to find peers and connect to them via WiFi direct. When I press the search button I want the app to start searching directly, and displaying the peers. What should I write for the "WiFiDirectActivity" to start when I press the search button on my HomeScreen?

My HomeScreen class:

public class HomeScreen extends Activity {

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.home_screen);

    Button mapButton = (Button) findViewById(R.id.mapButton);

    mapButton.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View view) {
            Intent intent = new Intent(HomeScreen.this, MapsActivity.class);
            startActivity(intent);
        }

    });

    Button sensorButton = (Button) findViewById(R.id.sensorBtn);

    sensorButton.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View view) {
            Intent intent = new Intent(HomeScreen.this, WiFiDirectActivity.class);
            startActivity(intent);
        }

    });

}

}

My WiFiDirectActivity class:

public class WiFiDirectActivity extends Activity implements WifiP2pManager.ChannelListener, DeviceListFragment.DeviceActionListener {

public static final String TAG = "wifidirectdemo";
private WifiP2pManager manager;
private boolean isWifiP2pEnabled = false;
private boolean retryChannel = false;

private final IntentFilter intentFilter = new IntentFilter();
private WifiP2pManager.Channel channel;
private BroadcastReceiver receiver = null;

/**
 * @param isWifiP2pEnabled the isWifiP2pEnabled to set
 */
public void setIsWifiP2pEnabled(boolean isWifiP2pEnabled) {
    this.isWifiP2pEnabled = isWifiP2pEnabled;
}

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main_peers);

    // add necessary intent values to be matched.

    intentFilter.addAction(WifiP2pManager.WIFI_P2P_STATE_CHANGED_ACTION);
    intentFilter.addAction(WifiP2pManager.WIFI_P2P_PEERS_CHANGED_ACTION);
    intentFilter.addAction(WifiP2pManager.WIFI_P2P_CONNECTION_CHANGED_ACTION);
    intentFilter.addAction(WifiP2pManager.WIFI_P2P_THIS_DEVICE_CHANGED_ACTION);

    manager = (WifiP2pManager) getSystemService(Context.WIFI_P2P_SERVICE);
    channel = manager.initialize(this, getMainLooper(), null);

    Button sensorButton = (Button) findViewById(R.id.sensorBtn);

    sensorButton.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View view) {

            if (!isWifiP2pEnabled) {
                Toast.makeText(WiFiDirectActivity.this, R.string.p2p_off_warning,
                        Toast.LENGTH_SHORT).show();
                return;
            }
            final DeviceListFragment fragment = (DeviceListFragment) getFragmentManager()
                    .findFragmentById(R.id.frag_list);
            fragment.onInitiateDiscovery();
            manager.discoverPeers(channel, new WifiP2pManager.ActionListener() {

                @Override
                public void onSuccess() {
                    Toast.makeText(WiFiDirectActivity.this, "Discovery Initiated",
                            Toast.LENGTH_SHORT).show();
                }

                @Override
                public void onFailure(int reasonCode) {
                    Toast.makeText(WiFiDirectActivity.this, "Discovery Failed : " + reasonCode,
                            Toast.LENGTH_SHORT).show();
                }

            });

        }

    });

}

/** register the BroadcastReceiver with the intent values to be matched */
@Override
public void onResume() {
    super.onResume();
    receiver = new WiFiDirectBroadcastReceiver(manager, channel, this);
    registerReceiver(receiver, intentFilter);
}

@Override
public void onPause() {
    super.onPause();
    unregisterReceiver(receiver);
}

/**
 * Remove all peers and clear all fields. This is called on
 * BroadcastReceiver receiving a state change event.
 */
public void resetData() {
    DeviceListFragment fragmentList = (DeviceListFragment) getFragmentManager()
            .findFragmentById(R.id.frag_list);
    DeviceDetailFragment fragmentDetails = (DeviceDetailFragment) getFragmentManager()
            .findFragmentById(R.id.frag_detail);
    if (fragmentList != null) {
        fragmentList.clearPeers();
    }
    if (fragmentDetails != null) {
        fragmentDetails.resetViews();
    }
}

@Override
public void showDetails(WifiP2pDevice device) {
    DeviceDetailFragment fragment = (DeviceDetailFragment) getFragmentManager()
            .findFragmentById(R.id.frag_detail);
    fragment.showDetails(device);

}

@Override
public void connect(WifiP2pConfig config) {
    manager.connect(channel, config, new WifiP2pManager.ActionListener() {

        @Override
        public void onSuccess() {
            // WiFiDirectBroadcastReceiver will notify us. Ignore for now.
        }

        @Override
        public void onFailure(int reason) {
            Toast.makeText(WiFiDirectActivity.this, "Connect failed. Retry.",
                    Toast.LENGTH_SHORT).show();
        }
    });
}

@Override
public void disconnect() {
    final DeviceDetailFragment fragment = (DeviceDetailFragment) getFragmentManager()
            .findFragmentById(R.id.frag_detail);
    fragment.resetViews();
    manager.removeGroup(channel, new WifiP2pManager.ActionListener() {

        @Override
        public void onFailure(int reasonCode) {
            Log.d(TAG, "Disconnect failed. Reason :" + reasonCode);

        }

        @Override
        public void onSuccess() {
            fragment.getView().setVisibility(View.GONE);
        }

    });
}

@Override
public void onChannelDisconnected() {
    // we will try once more
    if (manager != null && !retryChannel) {
        Toast.makeText(this, "Channel lost. Trying again", Toast.LENGTH_LONG).show();
        resetData();
        retryChannel = true;
        manager.initialize(this, getMainLooper(), this);
    } else {
        Toast.makeText(this,
                "Severe! Channel is probably lost premanently. Try Disable/Re-Enable P2P.",
                Toast.LENGTH_LONG).show();
    }
}

@Override
public void cancelDisconnect() {

    /*
     * A cancel abort request by user. Disconnect i.e. removeGroup if
     * already connected. Else, request WifiP2pManager to abort the ongoing
     * request
     */
    if (manager != null) {
        final DeviceListFragment fragment = (DeviceListFragment) getFragmentManager()
                .findFragmentById(R.id.frag_list);
        if (fragment.getDevice() == null
                || fragment.getDevice().status == WifiP2pDevice.CONNECTED) {
            disconnect();
        } else if (fragment.getDevice().status == WifiP2pDevice.AVAILABLE
                || fragment.getDevice().status == WifiP2pDevice.INVITED) {

            manager.cancelConnect(channel, new WifiP2pManager.ActionListener() {

                @Override
                public void onSuccess() {
                    Toast.makeText(WiFiDirectActivity.this, "Aborting connection",
                            Toast.LENGTH_SHORT).show();
                }

                @Override
                public void onFailure(int reasonCode) {
                    Toast.makeText(WiFiDirectActivity.this,
                            "Connect abort request failed. Reason Code: " + reasonCode,
                            Toast.LENGTH_SHORT).show();
                }
            });
        }
    }

}
}

The code that I am trying to redo from a search button in the menu to a search button on a different screen. (I removed the direct discover).

public class WiFiDirectActivity extends Activity implements WifiP2pManager.ChannelListener, DeviceListFragment.DeviceActionListener {

...

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.action_items, menu);
    return true;
}

/*
 * (non-Javadoc)
 * @see android.app.Activity#onOptionsItemSelected(android.view.MenuItem)
 */
@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
        case R.id.atn_direct_enable:
            if (manager != null && channel != null) {

                // Since this is the system wireless settings activity, it's
                // not going to send us a result. We will be notified by
                // WiFiDeviceBroadcastReceiver instead.

                startActivity(new Intent(Settings.ACTION_WIRELESS_SETTINGS));
            } else {
                Log.e(TAG, "channel or manager is null");
            }
            return true;

        case R.id.atn_direct_discover:
            Log.d("ADebugTag", "Value: " + isWifiP2pEnabled);

            if (!isWifiP2pEnabled) {
                Toast.makeText(WiFiDirectActivity.this, R.string.p2p_off_warning,
                        Toast.LENGTH_SHORT).show();
                return true;
            }
            final DeviceListFragment fragment = (DeviceListFragment) getFragmentManager()
                    .findFragmentById(R.id.frag_list);
            fragment.onInitiateDiscovery();
            manager.discoverPeers(channel, new WifiP2pManager.ActionListener() {

                @Override
                public void onSuccess() {
                    Toast.makeText(WiFiDirectActivity.this, "Discovery Initiated",
                            Toast.LENGTH_SHORT).show();
                }

                @Override
                public void onFailure(int reasonCode) {
                    Toast.makeText(WiFiDirectActivity.this, "Discovery Failed : " + reasonCode,
                            Toast.LENGTH_SHORT).show();
                }
            });
            return true;
        default:
            return super.onOptionsItemSelected(item);
    }
}

Body:
You can start to perform search in onResume as follows :

public class WiFiDirectActivity extends Activity implements WifiP2pManager.ChannelListener, DeviceListFragment.DeviceActionListener {

public static final String TAG = "wifidirectdemo";
private WifiP2pManager manager;
private boolean isWifiP2pEnabled = false;
private boolean retryChannel = false;

private final IntentFilter intentFilter = new IntentFilter();
private WifiP2pManager.Channel channel;
private BroadcastReceiver receiver = null;

/**
 * @param isWifiP2pEnabled the isWifiP2pEnabled to set
 */
public void setIsWifiP2pEnabled(boolean isWifiP2pEnabled) {
    this.isWifiP2pEnabled = isWifiP2pEnabled;
}

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main_peers);

    // add necessary intent values to be matched.

    intentFilter.addAction(WifiP2pManager.WIFI_P2P_STATE_CHANGED_ACTION);
    intentFilter.addAction(WifiP2pManager.WIFI_P2P_PEERS_CHANGED_ACTION);
    intentFilter.addAction(WifiP2pManager.WIFI_P2P_CONNECTION_CHANGED_ACTION);
    intentFilter.addAction(WifiP2pManager.WIFI_P2P_THIS_DEVICE_CHANGED_ACTION);

    manager = (WifiP2pManager) getSystemService(Context.WIFI_P2P_SERVICE);
    channel = manager.initialize(this, getMainLooper(), null);

    Button sensorButton = (Button) findViewById(R.id.sensorBtn);

    sensorButton.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View view) {

            if (!isWifiP2pEnabled) {
                Toast.makeText(WiFiDirectActivity.this, R.string.p2p_off_warning,
                        Toast.LENGTH_SHORT).show();
                return;
            }
            final DeviceListFragment fragment = (DeviceListFragment) getFragmentManager()
                    .findFragmentById(R.id.frag_list);
            fragment.onInitiateDiscovery();
            manager.discoverPeers(channel, new WifiP2pManager.ActionListener() {

                @Override
                public void onSuccess() {
                    Toast.makeText(WiFiDirectActivity.this, "Discovery Initiated",
                            Toast.LENGTH_SHORT).show();
                }

                @Override
                public void onFailure(int reasonCode) {
                    Toast.makeText(WiFiDirectActivity.this, "Discovery Failed : " + reasonCode,
                            Toast.LENGTH_SHORT).show();
                }

            });

        }

    });

}

/** register the BroadcastReceiver with the intent values to be matched */
@Override
public void onResume() {
    super.onResume();
    receiver = new WiFiDirectBroadcastReceiver(manager, channel, this);
    registerReceiver(receiver, intentFilter);
    performSearch(); // start searching devices
}

@Override
public void onPause() {
    super.onPause();
    unregisterReceiver(receiver);
}

/**
 * Remove all peers and clear all fields. This is called on
 * BroadcastReceiver receiving a state change event.
 */
public void resetData() {
    DeviceListFragment fragmentList = (DeviceListFragment) getFragmentManager()
            .findFragmentById(R.id.frag_list);
    DeviceDetailFragment fragmentDetails = (DeviceDetailFragment) getFragmentManager()
            .findFragmentById(R.id.frag_detail);
    if (fragmentList != null) {
        fragmentList.clearPeers();
    }
    if (fragmentDetails != null) {
        fragmentDetails.resetViews();
    }
}

@Override
public void showDetails(WifiP2pDevice device) {
    DeviceDetailFragment fragment = (DeviceDetailFragment) getFragmentManager()
            .findFragmentById(R.id.frag_detail);
    fragment.showDetails(device);

}

@Override
public void connect(WifiP2pConfig config) {
    manager.connect(channel, config, new WifiP2pManager.ActionListener() {

        @Override
        public void onSuccess() {
            // WiFiDirectBroadcastReceiver will notify us. Ignore for now.
        }

        @Override
        public void onFailure(int reason) {
            Toast.makeText(WiFiDirectActivity.this, "Connect failed. Retry.",
                    Toast.LENGTH_SHORT).show();
        }
    });
}

@Override
public void disconnect() {
    final DeviceDetailFragment fragment = (DeviceDetailFragment) getFragmentManager()
            .findFragmentById(R.id.frag_detail);
    fragment.resetViews();
    manager.removeGroup(channel, new WifiP2pManager.ActionListener() {

        @Override
        public void onFailure(int reasonCode) {
            Log.d(TAG, "Disconnect failed. Reason :" + reasonCode);

        }

        @Override
        public void onSuccess() {
            fragment.getView().setVisibility(View.GONE);
        }

    });
}

@Override
public void onChannelDisconnected() {
    // we will try once more
    if (manager != null && !retryChannel) {
        Toast.makeText(this, "Channel lost. Trying again", Toast.LENGTH_LONG).show();
        resetData();
        retryChannel = true;
        manager.initialize(this, getMainLooper(), this);
    } else {
        Toast.makeText(this,
                "Severe! Channel is probably lost premanently. Try Disable/Re-Enable P2P.",
                Toast.LENGTH_LONG).show();
    }
}

@Override
public void cancelDisconnect() {

    /*
     * A cancel abort request by user. Disconnect i.e. removeGroup if
     * already connected. Else, request WifiP2pManager to abort the ongoing
     * request
     */
    if (manager != null) {
        final DeviceListFragment fragment = (DeviceListFragment) getFragmentManager()
                .findFragmentById(R.id.frag_list);
        if (fragment.getDevice() == null
                || fragment.getDevice().status == WifiP2pDevice.CONNECTED) {
            disconnect();
        } else if (fragment.getDevice().status == WifiP2pDevice.AVAILABLE
                || fragment.getDevice().status == WifiP2pDevice.INVITED) {

            manager.cancelConnect(channel, new WifiP2pManager.ActionListener() {

                @Override
                public void onSuccess() {
                    Toast.makeText(WiFiDirectActivity.this, "Aborting connection",
                            Toast.LENGTH_SHORT).show();
                }

                @Override
                public void onFailure(int reasonCode) {
                    Toast.makeText(WiFiDirectActivity.this,
                            "Connect abort request failed. Reason Code: " + reasonCode,
                            Toast.LENGTH_SHORT).show();
                }
            });
        }
    }

}

private void performSearch() {
   if (!isWifiP2pEnabled) {
            Toast.makeText(WiFiDirectActivity.this, R.string.p2p_off_warning,
                    Toast.LENGTH_SHORT).show();
            return;
        }
        final DeviceListFragment fragment = (DeviceListFragment) getFragmentManager()
                .findFragmentById(R.id.frag_list);
        fragment.onInitiateDiscovery();
        manager.discoverPeers(channel, new WifiP2pManager.ActionListener() {

            @Override
            public void onSuccess() {
                Toast.makeText(WiFiDirectActivity.this, "Discovery Initiated",
                        Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onFailure(int reasonCode) {
                Toast.makeText(WiFiDirectActivity.this, "Discovery Failed : " + reasonCode,
                        Toast.LENGTH_SHORT).show();
            }

        });
}

}


问:
How to display extra data in highcharts bubble chart tooltip with datetime x-axis
I am trying to display some more data in highcharts bubble chart tooltip with no success. How can I access this.point.comments inside the tooltip formatter?

The bubble chart I am using has datetime as x-axis.

```<code>$('#chart-bubble').highcharts({

    chart: {
        type: 'bubble',
        zoomType: 'xy',
            plotBorderWidth: 1
    },

    title: {
        text: 'Risk & Profit Vs Date'
    },

       tooltip: {
        useHTML: true,
        formatter: function(){

            var expectedProfit = '';

            if( this.point.z !== 'none' )
            {
                expectedProfit = formatExpectedProfit(this.point.z);
            }

            var tooltip = '<table class="table table-bordered" style="width: 300px;"><tbody><tr><td colspan="2"><h5>'+this.series.name.substr(0,75)+'...</h5></td></tr>' +
            '<tr><td>Risk:</td><td>'+this.y+'</td></tr>';

            if( expectedProfit !== '' )
            {
                tooltip += '<tr><td>Profit:</td><td>'+expectedProfit+'</td></tr>';
            }
            else
            {
                tooltip += '<tr><td>Comments:</td><td>'+this.point.comments+'</td></tr>';
            }

            tooltip += '</tbody></table>';
            return tooltip;
        },
        followPointer: false
    },

        rangeSelector: {
        enabled:true
    },
        xAxis:{

            type: 'datetime',
            dateTimeLabelFormats: {
                day: '%e of %b'
            }

        },

        yAxis: {
            title: {
                text: 'Ri'
            }
        },

    series: prepareData(res.bubble)

});
</code>```

Here is the prepareData function:

```<code>function prepareData(data)
{
    for( var i in data )
    {
        var item = data[i];

        for( var k in item.data )
        {
            var itemData = item.data[k];

            if( itemData[0] )
            {
                var split    = itemData[0].split("-");
                var y        = split[0];
                var m        = split[1]-1;
                var d        = split[2];

                itemData[0]  = Date.UTC(y,m,d);
                item.data[k] = itemData;
            }
        }

        data[i] = item;
    }

    return data;
}
</code>```

And the res.bubble json returned from PHP:

```<code>$list = array();
$list[]   = array('name'=>'project 1','color'=>'#FF0000','data'=>array(new \DateTime(),20,'none'),'pointInterval'=>86400000,'comments'=>'this is a comment');
</code>```

//.... repeating by adding some more elements to this array

答:
You can access all additional properties via point.options[/* property */.

```<code>Highcharts.chart('container', {

chart: {
    type: 'bubble',
},

tooltip: {
  formatter: function () {
    return this.point.options.comments[0];
  }
},

    series: [{
        data: [
            { x: 95, y: 95, z: 13.8, name: 'BE', comments: ['this is a comment'] },
        ]
    }]
});
</code>```

example: http://jsfiddle.net/yd1vjfmp/

Body:
I am trying to display some more data in highcharts bubble chart tooltip with no success. How can I access this.point.comments inside the tooltip formatter?

The bubble chart I am using has datetime as x-axis.

$('#chart-bubble').highcharts({

    chart: {
        type: 'bubble',
        zoomType: 'xy',
            plotBorderWidth: 1
    },

    title: {
        text: 'Risk & Profit Vs Date'
    },

       tooltip: {
        useHTML: true,
        formatter: function(){

            var expectedProfit = '';

            if( this.point.z !== 'none' )
            {
                expectedProfit = formatExpectedProfit(this.point.z);
            }

            var tooltip = '

'+this.series.name.substr(0,75)+'...

' +
            '
Risk:	'+this.y+'
';

            if( expectedProfit !== '' )
            {
                tooltip += '
Profit:	'+expectedProfit+'
';
            }
            else
            {
                tooltip += '
Comments:	'+this.point.comments+'
';
            }

            tooltip += '

';
            return tooltip;
        },
        followPointer: false
    },

        rangeSelector: {
        enabled:true
    },
        xAxis:{

            type: 'datetime',
            dateTimeLabelFormats: {
                day: '%e of %b'
            }

        },

        yAxis: {
            title: {
                text: 'Ri'
            }
        },

    series: prepareData(res.bubble)

});

Here is the prepareData function:

function prepareData(data)
{
    for( var i in data )
    {
        var item = data[i];

        for( var k in item.data )
        {
            var itemData = item.data[k];

            if( itemData[0] )
            {
                var split    = itemData[0].split("-");
                var y        = split[0];
                var m        = split[1]-1;
                var d        = split[2];

                itemData[0]  = Date.UTC(y,m,d);
                item.data[k] = itemData;
            }
        }

        data[i] = item;
    }

    return data;
}

And the res.bubble json returned from PHP:

$list = array();
$list[]   = array('name'=>'project 1','color'=>'#FF0000','data'=>array(new \DateTime(),20,'none'),'pointInterval'=>86400000,'comments'=>'this is a comment');

//.... repeating by adding some more elements to this array

Body:
You can access all additional properties via point.options[/* property */.

Highcharts.chart('container', {

chart: {
    type: 'bubble',
},

tooltip: {
  formatter: function () {
    return this.point.options.comments[0];
  }
},

    series: [{
        data: [
            { x: 95, y: 95, z: 13.8, name: 'BE', comments: ['this is a comment'] },
        ]
    }]
});

example: http://jsfiddle.net/yd1vjfmp/


问:
Python Celery single base class instance for all tasks
I have a tasks.py that contains a subclass of Task.
According to the docs the base class is instantiated only once per tasks.

But this is only true for same tasks method. Calling a different task creates a new instance. So I can't access sessions via get_sessions created with create_session. How may I have only a single instance that is shared between different tasks?

```<code>class AuthentificationTask(Task):
    connections = {}

    def login(self, user, password, server):

    if not user in self.connections:
        self.connections = {user: ServerConnection(verbose=True)}
    # from celery.contrib import rdb
    # rdb.set_trace()

    self.connections[user].login(user=user, password=password, server=server)

@task(bind=True, max_retries=1, queue='test', base=AuthentificationTask)
def create_session(self, user, password, server):
    self.login(user, password, server)

@task(bind=True, max_retries=1, queue='test', base=AuthentificationTask)
def get_sessions(self, user, password, server):
    return self.connections[user].sessions
</code>```

答:
Seems this was an issue on my site caused by reinitialising self.connections each time.

```<code>self.connections = {user: ServerConnection(verbose=True)}
</code>```

In further tests base was instantiated only once for all (different) tasks. Thanks @Danila Ganchar for suggesting an alternative approach. I will give it a try!

Body:
I have a tasks.py that contains a subclass of Task.
According to the docs the base class is instantiated only once per tasks.

But this is only true for same tasks method. Calling a different task creates a new instance. So I can't access sessions via get_sessions created with create_session. How may I have only a single instance that is shared between different tasks?

class AuthentificationTask(Task):
    connections = {}

    def login(self, user, password, server):

    if not user in self.connections:
        self.connections = {user: ServerConnection(verbose=True)}
    # from celery.contrib import rdb
    # rdb.set_trace()

    self.connections[user].login(user=user, password=password, server=server)

@task(bind=True, max_retries=1, queue='test', base=AuthentificationTask)
def create_session(self, user, password, server):
    self.login(user, password, server)

@task(bind=True, max_retries=1, queue='test', base=AuthentificationTask)
def get_sessions(self, user, password, server):
    return self.connections[user].sessions

Body:
Seems this was an issue on my site caused by reinitialising self.connections each time.

self.connections = {user: ServerConnection(verbose=True)}

In further tests base was instantiated only once for all (different) tasks. Thanks @Danila Ganchar for suggesting an alternative approach. I will give it a try!