问:
Hybridauth - PHP - Facebook returned an invalid user id
Well I had hybridauth working and login correctly using facebook since 2 weeks ago, I did not any change and this morning I found that it was not working. I tried to switch the facebook app (id and secret key) to another one which was also working before, but is still happening the same. I also tried to run the examples which comes with hybridauth, and they are not working neither, so i know is not per a configuration from my side, and neither from the facebook app configuration.

This is what is telling me when i try to login:

Error!
Authentification failed. The user has canceled the authentication or the provider refused the connection.

Original error message: Authentification failed! Facebook returned an invalide user id.

Can be happening per something related with my server?

Has facebook done any change on their API during the last 24 hours?

Any one has experimented something similar?

UPDATED:
I have it working just since 1 week ago, to get it working I found other people with the same problem before (less than 1 month ago), they fixed it 17 days ago by updating the Facebook PHP SDK.

Here is the link to GitHub where you can see the changes to fix this problem:

https://github.com/F21/hybridauth/commit/3b115ee3abb5afbf44c37082e63aa8b056bf550c

With this, I managed to get everything working, but now is happening the same error even with these changes (after one week working).

答:
It is due to api change of facebook graph api, you can download latest version of Hybridauth for facebook https://github.com/hybridauth/hybridauth, currently third party api is not available for facebook so you need to download facebook sdk and place it under thirdparty directory, you can download it from https://github.com/facebook/php-graph-sdk.

After downloading you may need to configure facebook sdk auto-load files.


来源: stackexchange

问:
Java program on "friendly numbers "
I am working on a assignment about so called "friendly-numbers" with the following definition: An integer is said to be friendly if the leftmost digit is divisible by 1, the leftmost two digits are divisible by 2, and the leftmost three digits are divisible by 3, and so on. The n-digit itself is divisible by n.

Also it was given we need to call a method (as I did or at least tried to do in the code below). It should print whether a number is friendly or not. However, my program prints "The integer is not friendly." in both cases. From what I have tried, I know the counter does work. I just cannot find what I am missing or doing wrong. Help would be appreciated, and preferably with an adaptation of the code below, since that is what I came up with myself.

```<code>import java.util.Scanner;
public class A5E4 {

    public static void main(String[] args)
    {
        Scanner in = new Scanner(System.in);
        System.out.print("Please enter an integer: ");
        int friendlyNumber = in.nextInt();
        boolean result = isFriendly(friendlyNumber);
        if (result)
        {
            System.out.println("The integer is friendly");
        }
        else
        {
            System.out.println("The integer is not friendly");
        }
    }
    public static boolean isFriendly(int number)
    {
        int counter = 1;

        while (number / 10 >= 1)
        {
            counter ++;
            number = number / 10;
        }

        boolean check = true;

        for (int i = 1; i <= counter; i++)
        {

            if (number / Math.pow(10, (counter - i)) % i == 0 && check)
            {
                check = true;
            }
            else
            {
                check = false;
            }

        }
        return check;

    }
}
</code>```

答:
Try something like this (change your isFriendly() method):

```<code>public static boolean isFriendly(int number)
{
    String numberAsString = String.valueOf(number); //Convert the int as a String to make it easier to iterate through

    for(int i = 0; i < numberAsString.length(); i++) {
        int currentDigit = Character.getNumericValue(numberAsString.charAt(numberAsString.length() - i - 1));   //Iterate over the number backwards
        System.out.println(currentDigit);   //Print the current digit
        if(currentDigit % (i + 1) != 0) {
            return false;
        }
    }
    return true;
}
</code>```

ContentLicense: CC BY-SA 3.0

Title: Java program on "friendly numbers "

Body:
I am working on a assignment about so called "friendly-numbers" with the following definition: An integer is said to be friendly if the leftmost digit is divisible by 1, the leftmost two digits are divisible by 2, and the leftmost three digits are divisible by 3, and so on. The n-digit itself is divisible by n.

Also it was given we need to call a method (as I did or at least tried to do in the code below). It should print whether a number is friendly or not. However, my program prints "The integer is not friendly." in both cases. From what I have tried, I know the counter does work. I just cannot find what I am missing or doing wrong. Help would be appreciated, and preferably with an adaptation of the code below, since that is what I came up with myself.

import java.util.Scanner;
public class A5E4 {

    public static void main(String[] args)
    {
        Scanner in = new Scanner(System.in);
        System.out.print("Please enter an integer: ");
        int friendlyNumber = in.nextInt();
        boolean result = isFriendly(friendlyNumber);
        if (result)
        {
            System.out.println("The integer is friendly");
        }
        else
        {
            System.out.println("The integer is not friendly");
        }
    }
    public static boolean isFriendly(int number)
    {
        int counter = 1;

        while (number / 10 >= 1)
        {
            counter ++;
            number = number / 10;
        }

        boolean check = true;

        for (int i = 1; i <= counter; i++)
        {

            if (number / Math.pow(10, (counter - i)) % i == 0 && check)
            {
                check = true;
            }
            else
            {
                check = false;
            }

        }
        return check;

    }
}

Body:
Try something like this (change your isFriendly() method):

public static boolean isFriendly(int number)
{
    String numberAsString = String.valueOf(number); //Convert the int as a String to make it easier to iterate through

    for(int i = 0; i < numberAsString.length(); i++) {
        int currentDigit = Character.getNumericValue(numberAsString.charAt(numberAsString.length() - i - 1));   //Iterate over the number backwards
        System.out.println(currentDigit);   //Print the current digit
        if(currentDigit % (i + 1) != 0) {
            return false;
        }
    }
    return true;
}


问:
Thread Safety in Concurrent Queue C#
I have a MessagesManager thread to which different threads may send messages and then this  MessagesManager thread is responsible to publish these messages inside SendMessageToTcpIP() (start point of MessagesManager thread ).

```<code>class MessagesManager : IMessageNotifier
{
    //private
    private readonly AutoResetEvent _waitTillMessageQueueEmptyARE = new AutoResetEvent(false);
    private ConcurrentQueue<string> MessagesQueue = new ConcurrentQueue<string>();

    public void PublishMessage(string Message)
    {
        MessagesQueue.Enqueue(Message);
        _waitTillMessageQueueEmptyARE.Set();
    }

    public void SendMessageToTcpIP()
    {
        //keep waiting till a new message comes
        while (MessagesQueue.Count() == 0)
        {
            _waitTillMessageQueueEmptyARE.WaitOne();
        }

        //Copy the Concurrent Queue into a local queue - keep dequeuing the item once it is inserts into the local Queue
        Queue<string> localMessagesQueue = new Queue<string>();

        while (!MessagesQueue.IsEmpty)
        {
            string message;
            bool isRemoved = MessagesQueue.TryDequeue(out message);
            if (isRemoved)
                localMessagesQueue.Enqueue(message);
        }

        //Use the Local Queue for further processing
        while (localMessagesQueue.Count() != 0)
        {
            TcpIpMessageSenderClient.ConnectAndSendMessage(localMessagesQueue.Dequeue().PadRight(80, ' '));
            Thread.Sleep(2000);
        }
    }
}
</code>```

The different threads (3-4) send their message by calling the PublishMessage(string Message) (using same object to MessageManager). Once the message comes, I push that message into a concurrent queue and notifies the  SendMessageToTcpIP() by setting _waitTillMessageQueueEmptyARE.Set();. Inside SendMessageToTcpIP(), I am copying the message from the concurrent queue inside a local queue and then publish one by one.

QUESTIONS: Is it thread safe to do enqueuing and dequeuing in this way? Could there be some strange effects due to it?

答:
This is an refactored code snippet of how I would implement this functionality:

```<code>class MessagesManager {
    private readonly AutoResetEvent messagesAvailableSignal = new AutoResetEvent(false);
    private readonly ConcurrentQueue<string> messageQueue = new ConcurrentQueue<string>();

    public void PublishMessage(string Message) {
        messageQueue.Enqueue(Message);
        messagesAvailableSignal.Set();
    }

    public void SendMessageToTcpIP() {
        while (true) {
            messagesAvailableSignal.WaitOne();
            while (!messageQueue.IsEmpty) {
                string message;
                if (messageQueue.TryDequeue(out message)) {
                    TcpIpMessageSenderClient.ConnectAndSendMessage(message.PadRight(80, ' '));
                }
            }
        }
    }
}
</code>```

Points to note here:

This drains the queue completely: if there is at least one message, it will process all of them

The 2000ms Thread sleep is removed

Title: Thread Safety in Concurrent Queue C#

Body:
I have a MessagesManager thread to which different threads may send messages and then this  MessagesManager thread is responsible to publish these messages inside SendMessageToTcpIP() (start point of MessagesManager thread ).

class MessagesManager : IMessageNotifier
{
    //private
    private readonly AutoResetEvent _waitTillMessageQueueEmptyARE = new AutoResetEvent(false);
    private ConcurrentQueue<string> MessagesQueue = new ConcurrentQueue<string>();

    public void PublishMessage(string Message)
    {
        MessagesQueue.Enqueue(Message);
        _waitTillMessageQueueEmptyARE.Set();
    }

    public void SendMessageToTcpIP()
    {
        //keep waiting till a new message comes
        while (MessagesQueue.Count() == 0)
        {
            _waitTillMessageQueueEmptyARE.WaitOne();
        }

        //Copy the Concurrent Queue into a local queue - keep dequeuing the item once it is inserts into the local Queue
        Queue<string> localMessagesQueue = new Queue<string>();

        while (!MessagesQueue.IsEmpty)
        {
            string message;
            bool isRemoved = MessagesQueue.TryDequeue(out message);
            if (isRemoved)
                localMessagesQueue.Enqueue(message);
        }

        //Use the Local Queue for further processing
        while (localMessagesQueue.Count() != 0)
        {
            TcpIpMessageSenderClient.ConnectAndSendMessage(localMessagesQueue.Dequeue().PadRight(80, ' '));
            Thread.Sleep(2000);
        }
    }
}

The different threads (3-4) send their message by calling the PublishMessage(string Message) (using same object to MessageManager). Once the message comes, I push that message into a concurrent queue and notifies the  SendMessageToTcpIP() by setting _waitTillMessageQueueEmptyARE.Set();. Inside SendMessageToTcpIP(), I am copying the message from the concurrent queue inside a local queue and then publish one by one.

QUESTIONS: Is it thread safe to do enqueuing and dequeuing in this way? Could there be some strange effects due to it?

Body:
This is an refactored code snippet of how I would implement this functionality:

class MessagesManager {
    private readonly AutoResetEvent messagesAvailableSignal = new AutoResetEvent(false);
    private readonly ConcurrentQueue<string> messageQueue = new ConcurrentQueue<string>();

    public void PublishMessage(string Message) {
        messageQueue.Enqueue(Message);
        messagesAvailableSignal.Set();
    }

    public void SendMessageToTcpIP() {
        while (true) {
            messagesAvailableSignal.WaitOne();
            while (!messageQueue.IsEmpty) {
                string message;
                if (messageQueue.TryDequeue(out message)) {
                    TcpIpMessageSenderClient.ConnectAndSendMessage(message.PadRight(80, ' '));
                }
            }
        }
    }
}

Points to note here:

This drains the queue completely: if there is at least one message, it will process all of them

The 2000ms Thread sleep is removed


问:
Linq to objects List in list
I have a list of movies

```<code>List<Movie> MovieList
</code>```

and I have a list of selected categories

```<code>List<string> SelCat
</code>```

And say I want to select from the movie list where it matches 2 categories, like the SQL statement below:

SELECT * FROM MovieList WHERE MovieList.Category = 'Action' AND MovieList.Category = 'Drama'

I can get kinda close with linq like so:

var q = (from b in MovieList where b.Categories.Any(p=> SelCat.Contains(p)) select b);

But it acts like an OR query, not an AND. I want it to select all movies that have a category of action and drama.

BTW: Movie.Categories is a List of string. AND Movie.Categories must contain items in the SelCat.

How do I achieve this with Linq to Objects?

答:
just do an intersect followed by except.
it works, im sorry i had to write it in vb.</p>

```<code>Dim categories As New List(Of String)
Dim selected As New List(Of String)

        categories.Add("ali")
        categories.Add("ali2")
        categories.Add("ali3")
        categories.Add("ali4")

        selected.Add("ali2")
        selected.Add("ali4")

        Dim common = categories.Intersect(selected)

        If common.Except(selected).Count = 0 Then
            'true
        Else
            'false
        End If
</code>```

ContentLicense: CC BY-SA 2.5

Title: Linq to objects List in list

Body:
I have a list of movies

List<Movie> MovieList

and I have a list of selected categories

List<string> SelCat

And say I want to select from the movie list where it matches 2 categories, like the SQL statement below:

SELECT * FROM MovieList WHERE MovieList.Category = 'Action' AND MovieList.Category = 'Drama'

I can get kinda close with linq like so:

var q = (from b in MovieList where b.Categories.Any(p=> SelCat.Contains(p)) select b);

But it acts like an OR query, not an AND. I want it to select all movies that have a category of action and drama.

BTW: Movie.Categories is a List of string. AND Movie.Categories must contain items in the SelCat.

How do I achieve this with Linq to Objects?

Body:
just do an intersect followed by except.
it works, im sorry i had to write it in vb.

Dim categories As New List(Of String)
Dim selected As New List(Of String)

        categories.Add("ali")
        categories.Add("ali2")
        categories.Add("ali3")
        categories.Add("ali4")

        selected.Add("ali2")
        selected.Add("ali4")

        Dim common = categories.Intersect(selected)

        If common.Except(selected).Count = 0 Then
            'true
        Else
            'false
        End If


问:
C#: Microsoft.Interop.Excel Refresh all not working
I have a really frustrating issue where whenever I call
RefreshAll() from Microsoft.Interop.Excel it does not refresh the data when I open the workbook in excel and I have to manually click the refresh all button within excel... I have even tried calling refresh all via vba and it still does not refresh the data... I am always prompted with:

"The PivotTable report was saved without underlying data. Use the
  Refresh Data command to update the report."

Despite the fact that I already called the "Refresh all command."

```<code>public void applyMacro(string excelFile)
{
    var excelApplication = new Microsoft.Office.Interop.Excel.Application { Visible = false };
    var targetExcelFile = excelApplication.Workbooks.Open(excelFile);
    try
    {
        string[] macros = addMacros(ref targetExcelFile);
        for (int i = 0; i < 2; i++)
            excelApplication.Run(macros[i]);
        targetExcelFile.RefreshAll();
        targetExcelFile.Save();
    }
    catch (Exception ex)
    {
        Console.WriteLine(ex);
        Console.ReadKey();
    }
    finally
    {
        excelApplication.Quit();
    }
}
</code>```

and in vba have tried adding the following before calling the refresh:

```<code>For Each ws In Worksheets
  For Each qt In ws.QueryTables
     qt.Refresh  BackGroundQuery:=False
  next qt
Next ws
</code>```

Any ideas??

答:
You can use this on your pivot table :</p>

```<code>YourPivotTable.PivotCache().RefreshOnFileOpen = true;
YourPivotTable.SaveData = true;
</code>```

Body:
I have a really frustrating issue where whenever I call
RefreshAll() from Microsoft.Interop.Excel it does not refresh the data when I open the workbook in excel and I have to manually click the refresh all button within excel... I have even tried calling refresh all via vba and it still does not refresh the data... I am always prompted with:

"The PivotTable report was saved without underlying data. Use the
  Refresh Data command to update the report."

Despite the fact that I already called the "Refresh all command."

public void applyMacro(string excelFile)
{
    var excelApplication = new Microsoft.Office.Interop.Excel.Application { Visible = false };
    var targetExcelFile = excelApplication.Workbooks.Open(excelFile);
    try
    {
        string[] macros = addMacros(ref targetExcelFile);
        for (int i = 0; i < 2; i++)
            excelApplication.Run(macros[i]);
        targetExcelFile.RefreshAll();
        targetExcelFile.Save();
    }
    catch (Exception ex)
    {
        Console.WriteLine(ex);
        Console.ReadKey();
    }
    finally
    {
        excelApplication.Quit();
    }
}

and in vba have tried adding the following before calling the refresh:

For Each ws In Worksheets
  For Each qt In ws.QueryTables
     qt.Refresh  BackGroundQuery:=False
  next qt
Next ws

Any ideas??

Body:
You can use this on your pivot table :

YourPivotTable.PivotCache().RefreshOnFileOpen = true;
YourPivotTable.SaveData = true;


问:
Shortcut for adding id="" and class="" to HTML tags in Sublime Text 2
How do you set up Sublime Text 2 so that typing a . (period) produces class=" " and # (hash) produces id=" " when typing an opening HTML tag?

答:
Type foo.bar, press Tab, and you'll get

```<code><foo class="bar"></foo>
</code>```

There's also foo#bar (for id instead of class). Both are implemented in Packages/HTML/html_completions.py

Body:
Type foo.bar, press Tab, and you'll get

<foo class="bar"></foo>

There's also foo#bar (for id instead of class). Both are implemented in Packages/HTML/html_completions.py


问:
Semantic ui dropdown, prevent auto select with input element
I added an option to the dropdown that allows user to add item if it doesn't exist.

For that matter, I added an input field to the dropdown but when the user enters something, the dropdown tries to match the entered text with items that are already in the list.

I find it quite annoying in that specific case. I have noticed in the docs that input elements are bound to the search function. Nevertheless, I couldn't find how to disable this behaviour.

Here's the HTML:

```<code><div class="ui fluid selection dropdown playlist">
    <input name="playlist" type="hidden">
    <i class="dropdown icon"></i>

    <div class="default text">playlist</div>

    <div class="menu">
        <div class="item create" data-value="0">
            <span class="create-placeholder">+ new playlist</span>

            <div class="ui action input add-playlist">
                <input placeholder="new playlist">
                <button class="ui button">Add</button>
            </div>
        </div>

        <div class="item" data-value="1">foo</div>
        <div class="item" data-value="2">bar</div>
        <div class="item" data-value="3">baz</div>
    </div>
</div>
</code>```

The .add-playlist div and its content are not shown but I'm willing to spare you with the CSS here.

And the js:

```<code>$dropdown = $('.ui.dropdown');

$dropdown.dropdown({
    action: (text, val) => {
        if (val == 0) { // eslint-disable-line
            $('.create-placeholder').hide(100);
            $('.add-playlist').css('display', 'inline-flex');
            $('.add-playlist input, .add-playlist button').show(200);
        }

        else $dropdown.dropdown('set selected', val).dropdown('hide');
    },
    onHide: () => {
        // do that after dropdown has been hidden
        setTimeout(() => {
            $('.add-playlist, .add-playlist input, .add-playlist button').hide();
            $('.create-placeholder').show();
        }, 400);
    }
});
</code>```

I've set up a fiddle to have a clear exemple. Just type "foo" and you'll see what I mean in case it's not crystal clear.

答:
To allow user to add new items just add allowAdditions: True To dropdown options, for more informtions see semantic-ui dropdown settings

Example:

$('dropdownSelector').dropdown({
        allowAdditions: True
    }).dropdown();

Body:
I added an option to the dropdown that allows user to add item if it doesn't exist.

For that matter, I added an input field to the dropdown but when the user enters something, the dropdown tries to match the entered text with items that are already in the list.

I find it quite annoying in that specific case. I have noticed in the docs that input elements are bound to the search function. Nevertheless, I couldn't find how to disable this behaviour.

Here's the HTML:

    <input name="playlist" type="hidden">

playlist

            + new playlist

                <input placeholder="new playlist">
                <button class="ui button">Add</button>

foo

bar

baz

The .add-playlist div and its content are not shown but I'm willing to spare you with the CSS here.

And the js:

$dropdown = $('.ui.dropdown');

$dropdown.dropdown({
    action: (text, val) => {
        if (val == 0) { // eslint-disable-line
            $('.create-placeholder').hide(100);
            $('.add-playlist').css('display', 'inline-flex');
            $('.add-playlist input, .add-playlist button').show(200);
        }

        else $dropdown.dropdown('set selected', val).dropdown('hide');
    },
    onHide: () => {
        // do that after dropdown has been hidden
        setTimeout(() => {
            $('.add-playlist, .add-playlist input, .add-playlist button').hide();
            $('.create-placeholder').show();
        }, 400);
    }
});

I've set up a fiddle to have a clear exemple. Just type "foo" and you'll see what I mean in case it's not crystal clear.


问:
Compiler can't find html extension method in Orchard theme
I'm working on an Orchard theme and have created the following Html extension method:

```<code>using System;
using System.Web.Mvc;

namespace Themes.MyTheme {
    public static class HtmlExtensions {
        public static bool IsCurrent(
            this HtmlHelper html,
            string actionName,
            string controllerName) {

            string contextAction = (string) html.ViewContext.RouteData.Values["action"];
            string contextController = (string) html.ViewContext.RouteData.Values["controller"];

            bool isCurrent =
                string.Equals(contextAction, actionName, StringComparison.CurrentCultureIgnoreCase)
                && string.Equals(contextController, controllerName, StringComparison.CurrentCultureIgnoreCase);

            return isCurrent;
        }
    }
}
</code>```

In a Razor view, I've then added this:

```<code>@using Themes.MyTheme

// More razor syntax

@if (!Html.IsCurrent("New", "Customer")) {
    Html.ActionLink(T("New Customer").ToString(), "New", new { Controller = "Customer", Area = "My.Area" }, new { })
}
</code>```

I am getting the following exception:

```<code>CS0246: The type or namespace name 'Themes' could not be found (are you missing a using directive or an assembly reference?)
</code>```

This answer (and others) led me to believe I had to add the namespace to the web.config in my Views folder, which I have done. But I still get this error.

The extension method is defined in the same assembly as the Razor view (the Themes project in a standard Orchard solution; I created the Theme using codegen and it added the theme there).

How can I get Razor/Orchard/the compiler to recognize this namespace?

答:
You will need to create your theme as its own project, not just a folder under themes. Themes without their own .csproj file cant have code in them I'm afraid. When creating a theme with codegen there is a flag:</p>

```<code>/CreateProject:true
</code>```

Body:
I'm working on an Orchard theme and have created the following Html extension method:

using System;
using System.Web.Mvc;

namespace Themes.MyTheme {
    public static class HtmlExtensions {
        public static bool IsCurrent(
            this HtmlHelper html,
            string actionName,
            string controllerName) {

            string contextAction = (string) html.ViewContext.RouteData.Values["action"];
            string contextController = (string) html.ViewContext.RouteData.Values["controller"];

            bool isCurrent =
                string.Equals(contextAction, actionName, StringComparison.CurrentCultureIgnoreCase)
                && string.Equals(contextController, controllerName, StringComparison.CurrentCultureIgnoreCase);

            return isCurrent;
        }
    }
}

In a Razor view, I've then added this:

@using Themes.MyTheme

// More razor syntax

@if (!Html.IsCurrent("New", "Customer")) {
    Html.ActionLink(T("New Customer").ToString(), "New", new { Controller = "Customer", Area = "My.Area" }, new { })
}

I am getting the following exception:

CS0246: The type or namespace name 'Themes' could not be found (are you missing a using directive or an assembly reference?)

This answer (and others) led me to believe I had to add the namespace to the web.config in my Views folder, which I have done. But I still get this error.

The extension method is defined in the same assembly as the Razor view (the Themes project in a standard Orchard solution; I created the Theme using codegen and it added the theme there).

How can I get Razor/Orchard/the compiler to recognize this namespace?

Body:
You will need to create your theme as its own project, not just a folder under themes. Themes without their own .csproj file cant have code in them I'm afraid. When creating a theme with codegen there is a flag:

/CreateProject:true


问:
Attempt to invoke virtual method 'int java.lang.Object.hashCode()' on a null object reference
I'm trying to implement Facebook login button, but i'm receiving these errors when trying to run app:

Error:

```<code>FATAL EXCEPTION: AsyncTask #4
Process: , PID: 4633
java.lang.NullPointerException: Attempt to invoke virtual method 'int java.lang.Object.hashCode()' on a null object reference
    at java.util.concurrent.ConcurrentHashMap.get(ConcurrentHashMap.java:746)
    at java.util.concurrent.ConcurrentHashMap.containsKey(ConcurrentHashMap.java:774)
    at com.facebook.internal.Utility.queryAppSettings(Utility.java:825)
    at com.facebook.login.widget.LoginButton$1.run(LoginButton.java:489)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
    at java.lang.Thread.run(Thread.java:818)
com.android.vlada.sportisa E/GoogleApiAvailability: Google Play services is invalid. Cannot recover.
</code>```

Code:

```<code>public class MainActivity extends AppCompatActivity implements GoogleApiClient.OnConnectionFailedListener {

    private Button buttonRegistrujSe, buttonPrijaviSeKaoGost, buttonPrijavaRegistrovaniKorisnik;
    private LoginButton loginButton;
    private CallbackManager callbackManager;
    private TextView info;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        FacebookSdk.sdkInitialize(getApplicationContext());
        setContentView(R.layout.activity_main);
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        FacebookSdk.sdkInitialize(getApplicationContext());

        GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
                .requestEmail()
                .build();

        GoogleApiClient mGoogleApiClient;
        mGoogleApiClient = new GoogleApiClient.Builder(this)
                .enableAutoManage(this /* FragmentActivity */, this /* OnConnectionFailedListener */)
                .addApi(Auth.GOOGLE_SIGN_IN_API, gso)
                .build();

        buttonRegistrujSe = (Button) (findViewById(R.id.button_registruj_se));
        buttonRegistrujSe.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent i = new Intent(MainActivity.this, RegistrationActivity.class);
                startActivity(i);
            }
        });

        buttonPrijaviSeKaoGost = (Button) (findViewById(R.id.button_prijavi_se_kao_gost));
        buttonPrijaviSeKaoGost.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent i2 = new Intent(MainActivity.this, LoginGostActivity.class);
                startActivity(i2);
            }
        });

        buttonPrijavaRegistrovaniKorisnik = (Button) (findViewById(R.id.button_prijava_registrovani_korisnik));
        buttonPrijavaRegistrovaniKorisnik.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent i3 = new Intent(MainActivity.this, LoginActivity.class);
                startActivity(i3);
            }
        });

        callbackManager = CallbackManager.Factory.create();
        setContentView(R.layout.activity_main);
        info = (TextView)findViewById(R.id.info);
        loginButton = (LoginButton)findViewById(R.id.connectWithFbButton);

        loginButton.registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
            @Override
            public void onSuccess(LoginResult loginResult) {
                info.setText(
                        "User ID: "
                                + loginResult.getAccessToken().getUserId()
                                + "\n" +
                                "Auth Token: "
                                + loginResult.getAccessToken().getToken()
                );
            }

            @Override
            public void onCancel() {
                info.setText("Login attempt canceled.");
            }

            @Override
            public void onError(FacebookException e) {
                info.setText("Login attempt failed.");
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        callbackManager.onActivityResult(requestCode, resultCode, data);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        System.exit(0);
    }

    @Override
    public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
    }
}
</code>```

Layout Code

```<code><com.facebook.login.widget.LoginButton
    android:id="@+id/connectWithFbButton"
    style="@style/com_facebook_loginview_default_style"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="center_horizontal"
    android:layout_above="@+id/sign_in_button"
    android:layout_centerHorizontal="true"
    android:layout_marginBottom="43dp" />
</code>```

Update: after i deleted duplicate code in MainActivity i'm still receiving the same errors when trying to ran app. I'm attaching Manifest code also as requested so maybe that would help? Thanx

```<code><?xml version="1.0" encoding="utf-8"?>
</code>```

```<code><!-- To auto-complete the email text field in the login form with the user's emails -->
<uses-permission android:name="android.permission.GET_ACCOUNTS" />
<uses-permission android:name="android.permission.READ_PROFILE" />
<uses-permission android:name="android.permission.READ_CONTACTS" />
<uses-permission android:name="android.permission.INTERNET" />

<permission
    android:name="com.android.vlada.sportisa.Entiteti.maps.permission.MAPS_RECEIVE"
    android:protectionLevel="signature" />

<uses-feature
    android:glEsVersion="0x00020000"
    android:required="true" />

<uses-permission android:name="com.android.vlada.sportisa.Entiteti.maps.permission.MAPS_RECEIVE" />

<meta-data
    android:name="com.google.android.maps.v2.API_KEY"
    android:value="AIzaSyAVb2JuN-5nbaVkGODivuXPJOF5OeRekzo" />
<meta-data
    android:name="com.facebook.sdk.ApplicationId"
    android:value="@string/facebook_login" />

<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:supportsRtl="true"
    android:theme="@style/AppTheme" >
    <activity android:name=".MainActivity" />
    <activity android:name=".SplashActivity" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
    <activity android:name=".RegistrationActivity" />
    <activity android:name=".LoginActivity" />
    <activity android:name=".BiranjeAktivnosti" />
    <activity
        android:name=".Trazim"
        android:label="@string/title_activity_trazim"
        android:theme="@style/AppTheme" />
    <activity
        android:name=".Organizujem"
        android:label="@string/title_activity_organizujem"
        android:theme="@style/AppTheme" />
    <activity
        android:name="com.facebook.FacebookActivity"
        android:configChanges="keyboard|keyboardHidden|screenLayout|screenSize|orientation"
        android:label="@string/app_name"
        android:theme="@android:style/Theme.Translucent.NoTitleBar" />
</application>
</code>```

答:
Don't what, but there's an issue with either FacebookActivity name or the support for Gradle Version 2.3.0 is removed. I faced the same issue and with the following I got rid of this.

Replaced <activity> tag

```<code><activity
    android:name="com.facebook.FacebookActivity"
    android:configChanges="keyboard|keyboardHidden|screenLayout|screenSize|orientation"
    android:label="@string/app_name"
    android:theme="@android:style/Theme.Translucent.NoTitleBar" />
</code>```

with the <meta> tag.

```<code><meta-data
    android:name="com.facebook.sdk.ApplicationId"
    android:value="@string/fb_id" />
</code>```

EDIT

Also, I have placed this <meta> tag at the bottom of the file below, all the activities, above the closing tag.

Body:
I'm trying to implement Facebook login button, but i'm receiving these errors when trying to run app:

Error:

FATAL EXCEPTION: AsyncTask #4
Process: , PID: 4633
java.lang.NullPointerException: Attempt to invoke virtual method 'int java.lang.Object.hashCode()' on a null object reference
    at java.util.concurrent.ConcurrentHashMap.get(ConcurrentHashMap.java:746)
    at java.util.concurrent.ConcurrentHashMap.containsKey(ConcurrentHashMap.java:774)
    at com.facebook.internal.Utility.queryAppSettings(Utility.java:825)
    at com.facebook.login.widget.LoginButton$1.run(LoginButton.java:489)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
    at java.lang.Thread.run(Thread.java:818)
com.android.vlada.sportisa E/GoogleApiAvailability: Google Play services is invalid. Cannot recover.

Code:

public class MainActivity extends AppCompatActivity implements GoogleApiClient.OnConnectionFailedListener {

    private Button buttonRegistrujSe, buttonPrijaviSeKaoGost, buttonPrijavaRegistrovaniKorisnik;
    private LoginButton loginButton;
    private CallbackManager callbackManager;
    private TextView info;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        FacebookSdk.sdkInitialize(getApplicationContext());
        setContentView(R.layout.activity_main);
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        FacebookSdk.sdkInitialize(getApplicationContext());

        GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
                .requestEmail()
                .build();

        GoogleApiClient mGoogleApiClient;
        mGoogleApiClient = new GoogleApiClient.Builder(this)
                .enableAutoManage(this /* FragmentActivity */, this /* OnConnectionFailedListener */)
                .addApi(Auth.GOOGLE_SIGN_IN_API, gso)
                .build();

        buttonRegistrujSe = (Button) (findViewById(R.id.button_registruj_se));
        buttonRegistrujSe.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent i = new Intent(MainActivity.this, RegistrationActivity.class);
                startActivity(i);
            }
        });

        buttonPrijaviSeKaoGost = (Button) (findViewById(R.id.button_prijavi_se_kao_gost));
        buttonPrijaviSeKaoGost.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent i2 = new Intent(MainActivity.this, LoginGostActivity.class);
                startActivity(i2);
            }
        });

        buttonPrijavaRegistrovaniKorisnik = (Button) (findViewById(R.id.button_prijava_registrovani_korisnik));
        buttonPrijavaRegistrovaniKorisnik.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent i3 = new Intent(MainActivity.this, LoginActivity.class);
                startActivity(i3);
            }
        });

        callbackManager = CallbackManager.Factory.create();
        setContentView(R.layout.activity_main);
        info = (TextView)findViewById(R.id.info);
        loginButton = (LoginButton)findViewById(R.id.connectWithFbButton);

        loginButton.registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
            @Override
            public void onSuccess(LoginResult loginResult) {
                info.setText(
                        "User ID: "
                                + loginResult.getAccessToken().getUserId()
                                + "\n" +
                                "Auth Token: "
                                + loginResult.getAccessToken().getToken()
                );
            }

            @Override
            public void onCancel() {
                info.setText("Login attempt canceled.");
            }

            @Override
            public void onError(FacebookException e) {
                info.setText("Login attempt failed.");
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        callbackManager.onActivityResult(requestCode, resultCode, data);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        System.exit(0);
    }

    @Override
    public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
    }
}

Layout Code

<com.facebook.login.widget.LoginButton
    android:id="@+id/connectWithFbButton"
    style="@style/com_facebook_loginview_default_style"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="center_horizontal"
    android:layout_above="@+id/sign_in_button"
    android:layout_centerHorizontal="true"
    android:layout_marginBottom="43dp" />

Update: after i deleted duplicate code in MainActivity i'm still receiving the same errors when trying to ran app. I'm attaching Manifest code also as requested so maybe that would help? Thanx

<?xml version="1.0" encoding="utf-8"?>

<uses-permission android:name="android.permission.GET_ACCOUNTS" />
<uses-permission android:name="android.permission.READ_PROFILE" />
<uses-permission android:name="android.permission.READ_CONTACTS" />
<uses-permission android:name="android.permission.INTERNET" />

<permission
    android:name="com.android.vlada.sportisa.Entiteti.maps.permission.MAPS_RECEIVE"
    android:protectionLevel="signature" />

<uses-feature
    android:glEsVersion="0x00020000"
    android:required="true" />

<uses-permission android:name="com.android.vlada.sportisa.Entiteti.maps.permission.MAPS_RECEIVE" />

<meta-data
    android:name="com.google.android.maps.v2.API_KEY"
    android:value="AIzaSyAVb2JuN-5nbaVkGODivuXPJOF5OeRekzo" />
<meta-data
    android:name="com.facebook.sdk.ApplicationId"
    android:value="@string/facebook_login" />

<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:supportsRtl="true"
    android:theme="@style/AppTheme" >
    <activity android:name=".MainActivity" />
    <activity android:name=".SplashActivity" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
    <activity android:name=".RegistrationActivity" />
    <activity android:name=".LoginActivity" />
    <activity android:name=".BiranjeAktivnosti" />
    <activity
        android:name=".Trazim"
        android:label="@string/title_activity_trazim"
        android:theme="@style/AppTheme" />
    <activity
        android:name=".Organizujem"
        android:label="@string/title_activity_organizujem"
        android:theme="@style/AppTheme" />
    <activity
        android:name="com.facebook.FacebookActivity"
        android:configChanges="keyboard|keyboardHidden|screenLayout|screenSize|orientation"
        android:label="@string/app_name"
        android:theme="@android:style/Theme.Translucent.NoTitleBar" />
</application>

Body:
Don't what, but there's an issue with either FacebookActivity name or the support for Gradle Version 2.3.0 is removed. I faced the same issue and with the following I got rid of this.

Replaced <activity> tag

<activity
    android:name="com.facebook.FacebookActivity"
    android:configChanges="keyboard|keyboardHidden|screenLayout|screenSize|orientation"
    android:label="@string/app_name"
    android:theme="@android:style/Theme.Translucent.NoTitleBar" />

with the <meta> tag.

<meta-data
    android:name="com.facebook.sdk.ApplicationId"
    android:value="@string/fb_id" />

EDIT

Also, I have placed this <meta> tag at the bottom of the file below, all the activities, above the closing tag.


问:
Hiding textView below toolbar in coordinator layout
I'm working on creating a layout that works as follows:

Toolbar at the top

textView(a title) below top toolbar

RecyclerView

button

where the toolbar is in the main_activity
and the others are in an other xml file

And when I scroll, I want to hide the textView in between top toolbar and recyclerView.

答:
and this is the main activity</p>

```<code><?xml version="1.0" encoding="utf-8"?>
    <android.support.design.widget.CoordinatorLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:fitsSystemWindows="true"
        >

        <android.support.design.widget.AppBarLayout
            android:id="@+id/appbar_layout"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"

            >

            <FrameLayout
                android:id="@+id/toolbar_container"
                android:layout_width="match_parent"
                android:layout_height="wrap_content">

                <android.support.v7.widget.Toolbar
                    android:id="@+id/toolbar"
                    android:layout_width="match_parent"
                    android:layout_height="?attr/actionBarSize"
                    android:layout_gravity="center"
                    app:titleMarginStart="10dp"

                <com.miguelcatalan.materialsearchview.MaterialSearchView
                    android:id="@+id/search_view"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:inputType="textAutoCorrect"
                    app:searchBackIcon="@drawable/ic_back_arrow"
                    app:searchVoiceIcon="@drawable/ic_voice_black"
                    />

            </FrameLayout>

        </android.support.design.widget.AppBarLayout>
    </android.support.design.widget.CoordinatorLayout>
</code>```

Body:
and this is the main activity

<?xml version="1.0" encoding="utf-8"?>
    <android.support.design.widget.CoordinatorLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:fitsSystemWindows="true"
        >

        <android.support.design.widget.AppBarLayout
            android:id="@+id/appbar_layout"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"

            >

            <FrameLayout
                android:id="@+id/toolbar_container"
                android:layout_width="match_parent"
                android:layout_height="wrap_content">

                <android.support.v7.widget.Toolbar
                    android:id="@+id/toolbar"
                    android:layout_width="match_parent"
                    android:layout_height="?attr/actionBarSize"
                    android:layout_gravity="center"
                    app:titleMarginStart="10dp"

                <com.miguelcatalan.materialsearchview.MaterialSearchView
                    android:id="@+id/search_view"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:inputType="textAutoCorrect"
                    app:searchBackIcon="@drawable/ic_back_arrow"
                    app:searchVoiceIcon="@drawable/ic_voice_black"
                    />

            </FrameLayout>

        </android.support.design.widget.AppBarLayout>
    </android.support.design.widget.CoordinatorLayout>


答:
While this is probably thread-safe, there are built-in classes in .NET to help with "many publishers one consumer" pattern, like BlockingCollection. You can rewrite your class like this:

```<code>class MessagesManager : IDisposable {
    // note that your ConcurrentQueue is still in play, passed to constructor
    private readonly BlockingCollection<string> MessagesQueue = new BlockingCollection<string>(new ConcurrentQueue<string>());

    public MessagesManager() {
        // start consumer thread here
        new Thread(SendLoop) {
            IsBackground = true
        }.Start();
    }

    public void PublishMessage(string Message) {
        // no need to notify here, will be done for you
        MessagesQueue.Add(Message);
    }

    private void SendLoop() {
        // this blocks until new items are available
        foreach (var item in MessagesQueue.GetConsumingEnumerable()) {
            // ensure that you handle exceptions here, or whole thing will break on exception
            TcpIpMessageSenderClient.ConnectAndSendMessage(item.PadRight(80, ' '));
            Thread.Sleep(2000); // only if you are sure this is required
        }
    }

    public void Dispose() {
        // this will "complete" GetConsumingEnumerable, so your thread will complete
        MessagesQueue.CompleteAdding();
        MessagesQueue.Dispose();
    }
}
</code>```

Title: Thread Safety in Concurrent Queue C#

Body:
While this is probably thread-safe, there are built-in classes in .NET to help with "many publishers one consumer" pattern, like BlockingCollection. You can rewrite your class like this:

class MessagesManager : IDisposable {
    // note that your ConcurrentQueue is still in play, passed to constructor
    private readonly BlockingCollection<string> MessagesQueue = new BlockingCollection<string>(new ConcurrentQueue<string>());

    public MessagesManager() {
        // start consumer thread here
        new Thread(SendLoop) {
            IsBackground = true
        }.Start();
    }

    public void PublishMessage(string Message) {
        // no need to notify here, will be done for you
        MessagesQueue.Add(Message);
    }

    private void SendLoop() {
        // this blocks until new items are available
        foreach (var item in MessagesQueue.GetConsumingEnumerable()) {
            // ensure that you handle exceptions here, or whole thing will break on exception
            TcpIpMessageSenderClient.ConnectAndSendMessage(item.PadRight(80, ' '));
            Thread.Sleep(2000); // only if you are sure this is required
        }
    }

    public void Dispose() {
        // this will "complete" GetConsumingEnumerable, so your thread will complete
        MessagesQueue.CompleteAdding();
        MessagesQueue.Dispose();
    }
}


问:
External method from an AJAX callback in JavaScript & jQuery
I have a function in JS & jQuery that fires an AJAX call and it has a callback block to let me know when it's finished:

```<code>function ajaxCall(url, type, dataType, dataToSend, callback) {

    if (dataType == undefined) dataType = "json";
    if (dataToSend == undefined) dataToSend = null;

    $.ajax({
        url: url,
        type: type,
        dataType: dataType,
        contentType: "application/json",
        data: dataToSend,
        async: true,
        success: function (result) {
            callback(result);
        },
        error: function (data, status) {
            console.error("Server Error: " + status);
        }
    });
}
</code>```

I am accessing it like so, but using external functions like showAjaxLoader() just doesn't work! it says this function is undefined:

```<code>function registerUser(data) {

    ajaxCall(pathServiceRegister, "POST", undefined, JSON.stringify(data), function (result) {

        // SOME CODE THAT RUNS WHEN IT'S COMPLETE

        // External method:
        showAjaxLoader(false); // Doesn't work

    });
});

function showAjaxLoader(show) {
    var loader = $('.ajax-loader');
    if (show) {
        loader.fadeIn("fast");
    } else {
        loader.fadeOut("fast");
    }
}
</code>```

What am I doing wrong?

Thanks :)

答:
Declare your method like this

```<code>var obj = {
showAjaxLoader : function(show) {
    var loader = $('.ajax-loader');
    if (show) {
        loader.fadeIn("fast");
    } else {
        loader.fadeOut("fast");
    }
}
}
</code>```

Then inside ajax, call obj.showAjaxLoader(false); This may work.

Body:
I have a function in JS & jQuery that fires an AJAX call and it has a callback block to let me know when it's finished:

function ajaxCall(url, type, dataType, dataToSend, callback) {

    if (dataType == undefined) dataType = "json";
    if (dataToSend == undefined) dataToSend = null;

    $.ajax({
        url: url,
        type: type,
        dataType: dataType,
        contentType: "application/json",
        data: dataToSend,
        async: true,
        success: function (result) {
            callback(result);
        },
        error: function (data, status) {
            console.error("Server Error: " + status);
        }
    });
}

I am accessing it like so, but using external functions like showAjaxLoader() just doesn't work! it says this function is undefined:

function registerUser(data) {

    ajaxCall(pathServiceRegister, "POST", undefined, JSON.stringify(data), function (result) {

        // SOME CODE THAT RUNS WHEN IT'S COMPLETE

        // External method:
        showAjaxLoader(false); // Doesn't work

    });
});

function showAjaxLoader(show) {
    var loader = $('.ajax-loader');
    if (show) {
        loader.fadeIn("fast");
    } else {
        loader.fadeOut("fast");
    }
}

What am I doing wrong?

Thanks :)

Body:
Declare your method like this

var obj = {
showAjaxLoader : function(show) {
    var loader = $('.ajax-loader');
    if (show) {
        loader.fadeIn("fast");
    } else {
        loader.fadeOut("fast");
    }
}
}

Then inside ajax, call obj.showAjaxLoader(false); This may work.


问:
Convert value number key to string php?
Here is my code :

```<code> foreach($urlImages as $key => $u){

        $nameImg = $id_product.'_'.$key.'_'.md5(uniqid(rand(), true)).'.png';

    }
</code>```

The key value is incremented, I want to change the key number to a string like:

```<code>if $key=1 i want $key=white
if $key=2 i want $key=black
</code>```

答:
I would use a switch case:</p>

```<code> foreach($urlImages as $key => $u){
    $type = 'default';

    switch ($key) {
      case 1:
        $type = 'white';
        break;
      case 2:
        $type = 'black';
        break;
    }

    $nameImg = $id_product.'_'.$type.'_'.md5(uniqid(rand(), true)).'.png';
 }
</code>```

Title: Convert value number key to string php?

Body:
Here is my code :

 foreach($urlImages as $key => $u){

        $nameImg = $id_product.'_'.$key.'_'.md5(uniqid(rand(), true)).'.png';

    }

The key value is incremented, I want to change the key number to a string like:

if $key=1 i want $key=white
if $key=2 i want $key=black

Body:
I would use a switch case:

 foreach($urlImages as $key => $u){
    $type = 'default';

    switch ($key) {
      case 1:
        $type = 'white';
        break;
      case 2:
        $type = 'black';
        break;
    }

    $nameImg = $id_product.'_'.$type.'_'.md5(uniqid(rand(), true)).'.png';
 }


问:
In pagerSlidindTabStrip text display incomplete for Moto G 4+ android 7
In my project I have used PagerSlidingTabStrip library .now in all other device it display proper text in PagerSlidingTabStrip . but in Moto G 4+ it displays incomplete text in PagerSlidingTabStrip. like it display only "Entertain” instead "Entertainment” . what need to change, plz help me. Thanks In advance.

```<code> <com.astuetz.PagerSlidingTabStrip
        android:id="@+id/VideoTabs"
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:background="@color/toolbar_color"
        android:paddingLeft="11dp"
        android:layout_marginRight="0dp"
        android:paddingRight="0dp"
        android:textSize="15sp"
        app:pstsActivateTextColor="@color/white"
        app:pstsDeactivateTextColor="@color/white"
        app:pstsDividerColor="@color/toolbar_color"
        app:pstsIndicatorHeight="0dp"
        app:pstsTabBackground="@color/toolbar_color"
        app:pstsTextAllCaps="false"
        app:pstsUnderlineHeight="0dp"
        android:layout_toLeftOf="@+id/ivNextFragment"/>
</code>```

In java file

```<code>   public void init(View rootview) {
      tabs = (PagerSlidingTabStrip) rootview.findViewById(R.id.VideoTabs);
      mTabsLinearLayout = ((LinearLayout) tabs.getChildAt(0));

      pager = (ViewPager) rootview.findViewById(R.id.viewpager);
     //        tabs.setShouldExpand(true);
     pager.setOffscreenPageLimit(listPublisherName.size());

     setupViewPager(pager);
     tabs.setViewPager(pager);
     tabs.setForegroundGravity(Gravity.CENTER);
     pager.setCurrentItem(0);
     tabs.setTabSwitch(true);

     TextView tv = (TextView) mTabsLinearLayout.getChildAt(pos);
     tv.setTextSize(16);
     tv.setTypeface(null, Typeface.BOLD);
   }
</code>```

screen is like this right now

Body:
In my project I have used PagerSlidingTabStrip library .now in all other device it display proper text in PagerSlidingTabStrip . but in Moto G 4+ it displays incomplete text in PagerSlidingTabStrip. like it display only "Entertain” instead "Entertainment” . what need to change, plz help me. Thanks In advance.

 <com.astuetz.PagerSlidingTabStrip
        android:id="@+id/VideoTabs"
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:background="@color/toolbar_color"
        android:paddingLeft="11dp"
        android:layout_marginRight="0dp"
        android:paddingRight="0dp"
        android:textSize="15sp"
        app:pstsActivateTextColor="@color/white"
        app:pstsDeactivateTextColor="@color/white"
        app:pstsDividerColor="@color/toolbar_color"
        app:pstsIndicatorHeight="0dp"
        app:pstsTabBackground="@color/toolbar_color"
        app:pstsTextAllCaps="false"
        app:pstsUnderlineHeight="0dp"
        android:layout_toLeftOf="@+id/ivNextFragment"/>

In java file

   public void init(View rootview) {
      tabs = (PagerSlidingTabStrip) rootview.findViewById(R.id.VideoTabs);
      mTabsLinearLayout = ((LinearLayout) tabs.getChildAt(0));

      pager = (ViewPager) rootview.findViewById(R.id.viewpager);
     //        tabs.setShouldExpand(true);
     pager.setOffscreenPageLimit(listPublisherName.size());

     setupViewPager(pager);
     tabs.setViewPager(pager);
     tabs.setForegroundGravity(Gravity.CENTER);
     pager.setCurrentItem(0);
     tabs.setTabSwitch(true);

     TextView tv = (TextView) mTabsLinearLayout.getChildAt(pos);
     tv.setTextSize(16);
     tv.setTypeface(null, Typeface.BOLD);
   }

screen is like this right now

Body: add tabs.setDistributeEvenly(false);


问:
How to add flex controls to my AS3 project?
I'm absolute newbie in Flash development but anyway I need to do something.
I have a pure AS3 project that plays video from youtube (chromeless player). I need to add some controls to manage this player. I don't know how to do that? If I just add mxml file into the project nothing happens. How to bind this file to as3?
Thanks</p>

答:
A short and simple example of how to add a button with an image:

```<code>loader = new Loader();
loader.contentLoaderInfo.addEventListener(Event.COMPLETE, onComplete);
loader.load(new URLRequest('http://i1.nyt.com/images/misc/nytlogo379x64.gif'));

function onComplete(event:Event):void
{
    var button:Sprite = new Sprite();
    button.addChild(event.currentTarget.content);
    addChild(button);
    button.buttonMode = true;
    button.addEventListener(MouseEvent.CLICK, onButtonClick);
}

function onButtonClick(event:MouseEvent):void
{
    trace ('click');
}
</code>```

This would be the most basic version of a button with a loaded bitmap image.
Normally you would like to check for errors as well... what to do if the image is not found, or when you're not allowed to access it.

If you're going to need more then one button you could make a class which accepts an url, so you could just pass the url to the class and the button would be created.

A completely other way to approach this is with an SWC file, you could create the buttons in the Flash IDE and export them as an swc, which you can embed and use in your pure AS3 project.

Body:
A short and simple example of how to add a button with an image:

loader = new Loader();
loader.contentLoaderInfo.addEventListener(Event.COMPLETE, onComplete);
loader.load(new URLRequest('http://i1.nyt.com/images/misc/nytlogo379x64.gif'));

function onComplete(event:Event):void
{
    var button:Sprite = new Sprite();
    button.addChild(event.currentTarget.content);
    addChild(button);
    button.buttonMode = true;
    button.addEventListener(MouseEvent.CLICK, onButtonClick);
}

function onButtonClick(event:MouseEvent):void
{
    trace ('click');
}

This would be the most basic version of a button with a loaded bitmap image.
Normally you would like to check for errors as well... what to do if the image is not found, or when you're not allowed to access it.

If you're going to need more then one button you could make a class which accepts an url, so you could just pass the url to the class and the button would be created.

A completely other way to approach this is with an SWC file, you could create the buttons in the Flash IDE and export them as an swc, which you can embed and use in your pure AS3 project.


问:
onclick in javascript makes active in css
I have a little content slider in css and I have two little points that change the image when they are in hover mode.

My question is how can I make the slide stay active by onclick

At the moment, my script looks like this but I think there is a problem with the add:

```<code><script>
    function myFunction() {
        var button = document.getElementsByClassName("dia");
        button.classList.add('active');
    }
</code>```

thanks for helping

答:
document.getElementsByClassName() returns a collection of HTML elements i.e.  it returns an array-like collection of elements. Iterate over it like you would with a real array.

You have to select a singular element to modify its classList. Hence, document.getElementsByClassName("dia")[0], which will pick the first element whose class matches with dia. And then you can add or remove from the classList of button.

Change your code to this:

```<code>function myFunction() {
    var button = document.getElementsByClassName("dia")[0];
    button.classList.add('active');
}
</code>```

Body:
document.getElementsByClassName() returns a collection of HTML elements i.e.  it returns an array-like collection of elements. Iterate over it like you would with a real array.

You have to select a singular element to modify its classList. Hence, document.getElementsByClassName("dia")[0], which will pick the first element whose class matches with dia. And then you can add or remove from the classList of button.

Change your code to this:

function myFunction() {
    var button = document.getElementsByClassName("dia")[0];
    button.classList.add('active');
}


问:
SelectSingleNode is giving compilation error in dnx core 5.0
I am getting this error with SelectSingleNode method:
 DNX Core 5.0 error CS1061: 'XmlDocument' does not contain a definition for 'SelectSingleNode' and no extension method 'SelectSingleNode' accepting a first argument of type 'XmlDocument' could be found (are you missing a using directive or an assembly reference?)

Is it not supported yet? What are my alternatives?

答:
In .Net Core 1.0 and .Net Standard 1.3 SelectSingleNode is an extenstion method

https://github.com/dotnet/corefx/issues/17349

Add a reference to make it available again:

```<code> <PackageReference Include="System.Xml.XPath.XmlDocument" Version="4.3.0" />
</code>```

Body:
In .Net Core 1.0 and .Net Standard 1.3 SelectSingleNode is an extenstion method

https://github.com/dotnet/corefx/issues/17349

Add a reference to make it available again:

 <PackageReference Include="System.Xml.XPath.XmlDocument" Version="4.3.0" />


问:
Build binary tree structure dynamically in asp.net
I am working on MLM project where I want to build a tree structure(one root node and only two child nodes). I have data stored in a SQL Server database in below format:

```<code>rootId   child1Id   child2Id   referbyid
----------------------------------------
1        2          3
2        4          5          1
3        6          7          1
4        8          9          2
5        10         11         1
6        12         13         3
</code>```

and so on (these data are simple and just for example)

I tried with googleOrgChart to display the data but doesn't meet my requirement. Please find the screenshots for more understanding

Actual

Result which I got

Expected

Result I am expecting

Can anybody help me display this data in binary tree format or in expected format which I have shown in the second screenshot?

Thanks in advance

答:
The data in your database doesn't line up quite correctly and is likely causing the issue.

From what I understand the column referbyid is the parent node, rootid is the current node and the two child columns are the child nodes.

The row with the rootId of 5 has a referbyid of 1, changing this to 2 should fix your issue.

Body:
I am working on MLM project where I want to build a tree structure(one root node and only two child nodes). I have data stored in a SQL Server database in below format:

rootId   child1Id   child2Id   referbyid
----------------------------------------
1        2          3
2        4          5          1
3        6          7          1
4        8          9          2
5        10         11         1
6        12         13         3

and so on (these data are simple and just for example)

I tried with googleOrgChart to display the data but doesn't meet my requirement. Please find the screenshots for more understanding

Actual

Result which I got

Expected

Result I am expecting

Can anybody help me display this data in binary tree format or in expected format which I have shown in the second screenshot?

Thanks in advance


问:
Warning: mysql_num_rows(): supplied argument is not a valid
Hi i'm receiving the error below, i've double checked everything and don't know why its being displayed.
Warning: mysql_num_rows(): supplied argument is not a valid MySQL result resource in /home/namebob/public_html/site_reg/statlookup.php on line 6</p>

```<code><?php
    include_once('common.php');
    $cid        =   $_REQUEST['cid'];
    $_elmID     =   $_REQUEST['elmID'];
    $scan = mysql_query("SELECT  `id`, `state` FROM `mast_state` WHERE `countryid` = $cid");
    if(mysql_num_rows($scan)>0)
    {
...
</code>```

答:
```
$scan = mysql_query("SELECT  `id`, `state` FROM `mast_state` WHERE `countryid` = '".mysql_real_escape_string($cid)."'");
```

But really, use PDO.

```
$stm = $db->prepare("SELECT  `id`, `state` FROM `mast_state` WHERE `countryid` = ?");
if( $stm && $stm->execute(array($cid)) ) {
  while( $data = $stm->fetch(PDO::FETCH_ASSOC) ) {

  }
}
```

Body:
Hi i'm receiving the error below, i've double checked everything and don't know why its being displayed.
Warning: mysql_num_rows(): supplied argument is not a valid MySQL result resource in /home/namebob/public_html/site_reg/statlookup.php on line 6

<?php
    include_once('common.php');
    $cid        =   $_REQUEST['cid'];
    $_elmID     =   $_REQUEST['elmID'];
    $scan = mysql_query("SELECT  `id`, `state` FROM `mast_state` WHERE `countryid` = $cid");
    if(mysql_num_rows($scan)>0)
    {
...

Body:
$scan = mysql_query("SELECT  `id`, `state` FROM `mast_state` WHERE `countryid` = '".mysql_real_escape_string($cid)."'");

But really, use PDO.

$stm = $db->prepare("SELECT  `id`, `state` FROM `mast_state` WHERE `countryid` = ?");
if( $stm && $stm->execute(array($cid)) ) {
  while( $data = $stm->fetch(PDO::FETCH_ASSOC) ) {

  }
}


问:
Pass JsonResponse to IntentService
I have My MainActivity and I can get response very well :

```<code> JSONObject responseVal = responseObj.getJSONObject("data");
                message = responseVal.getString("id");
                Log.i(TAG, "onResponse: " + message);
</code>```

and I have IntentService and want to pass that message value to it.

I tried with SharedPreferences and also with intentPutExtra but it doesn't work.

What is the best way to do that ?

答:
if you want to store that message into the application than user sharedprefrences other wise use putextra and getIntent.getextra() method.

on your click event

```<code>Intent i=new Intent(this,yourclass.class);
i.putExtra("demo",message);
</code>```

In yourclass.class

```<code>String mes=getIntent().getStringExtra("demo");
</code>```

Title: Pass JsonResponse to IntentService

Body:
I have My MainActivity and I can get response very well :

 JSONObject responseVal = responseObj.getJSONObject("data");
                message = responseVal.getString("id");
                Log.i(TAG, "onResponse: " + message);

and I have IntentService and want to pass that message value to it.

I tried with SharedPreferences and also with intentPutExtra but it doesn't work.

What is the best way to do that ?

Body:
if you want to store that message into the application than user sharedprefrences other wise use putextra and getIntent.getextra() method.

on your click event

Intent i=new Intent(this,yourclass.class);
i.putExtra("demo",message);

In yourclass.class

String mes=getIntent().getStringExtra("demo");


问:
sqlcmd - How to display all the set option setting values
What is the command in sqlcmd to show all the set options and their associated settings?

For example how do you show the current value for nocount?

```<code>set
set nocount
set nocount ?
</code>```

答:
DBCC USEROPTIONS (SQL 2008 and newer)

https://learn.microsoft.com/en-us/sql/t-sql/database-console-commands/dbcc-useroptions-transact-sql

Output:

```<code>    textsize    2147483647
    language    us_english
    dateformat  mdy
    datefirst   7
    lock_timeout    -1
    quoted_identifier   SET
    arithabort  SET
    ansi_null_dflt_on   SET
    ansi_warnings   SET
    ansi_padding    SET
    ansi_nulls  SET
    concat_null_yields_null SET
    isolation level read committed
</code>```

Body:
What is the command in sqlcmd to show all the set options and their associated settings?

For example how do you show the current value for nocount?

set
set nocount
set nocount ?

Body:
DBCC USEROPTIONS (SQL 2008 and newer)

https://learn.microsoft.com/en-us/sql/t-sql/database-console-commands/dbcc-useroptions-transact-sql

Output:

    textsize    2147483647
    language    us_english
    dateformat  mdy
    datefirst   7
    lock_timeout    -1
    quoted_identifier   SET
    arithabort  SET
    ansi_null_dflt_on   SET
    ansi_warnings   SET
    ansi_padding    SET
    ansi_nulls  SET
    concat_null_yields_null SET
    isolation level read committed


问:
FluentWait prints a lot of warning stack traces for ignored exception in the console when I upgrade Selenium from 3.0.1 to 3.1.0
I have the following method which I use intensively in my tests and which works ok with Selenium 3.0.1

```<code>def waitUntilVisibleByXPath(xpath:String, timeOutInMillis:Int)(implicit driver:WebDriver): Try[WebElement] ={
    val wait:FluentWait[WebDriver] = new FluentWait(driver)
      .withTimeout(timeOutInMillis, TimeUnit.MILLISECONDS)
      .pollingEvery(100, TimeUnit.MILLISECONDS)
      .ignoring(classOf[NoSuchElementException])
      .withMessage(s"for element to be visible and enabled by xpath: $xpath")
    val condition:ExpectedCondition[WebElement] = ExpectedConditions.elementToBeClickable(By.xpath(xpath))
    Try{wait.until(condition)}
  }
</code>```

I've tried to upgrade Selenium to 3.1.0 version and after that I noticed a lot of stack traces similar to this one in my console when running tests:

```<code>Mar 28, 2017 1:41:49 PM org.openqa.selenium.support.ui.ExpectedConditions findElement
WARNING: WebDriverException thrown by findElement(By.xpath: //a[text()='Log out'])
org.openqa.selenium.NoSuchElementException: Cannot locate an element using By.xpath: //a[text()='Log out']
For documentation on this error, please visit: http://seleniumhq.org/exceptions/no_such_element.html
Build info: version: '3.1.0', revision: 'b94c902', time: '2017-02-16 12:21:31 -0800'
System info: host: 'POSITRON', ip: '127.0.1.1', os.name: 'Linux', os.arch: 'amd64', os.version: '4.4.0-66-generic', java.version: '1.8.0_121'
Driver info: driver.version: unknown
    at org.openqa.selenium.support.ui.ExpectedConditions.lambda$findElement$0(ExpectedConditions.java:896)
</code>```

So basically it prints a WARNING stack trace every time it polls. It's not critical of course but it really bloats the console.
Could you explain how to disable such warnings to be printed from FluentWait-s and probably point out to some rationale behind such behavior?

答:
I've just set root logger level to SEVERE:

```<code>LogManager.getLogManager.getLogger("").setLevel(Level.SEVERE)
</code>```

That solved problem for me.

Body:
I have the following method which I use intensively in my tests and which works ok with Selenium 3.0.1

def waitUntilVisibleByXPath(xpath:String, timeOutInMillis:Int)(implicit driver:WebDriver): Try[WebElement] ={
    val wait:FluentWait[WebDriver] = new FluentWait(driver)
      .withTimeout(timeOutInMillis, TimeUnit.MILLISECONDS)
      .pollingEvery(100, TimeUnit.MILLISECONDS)
      .ignoring(classOf[NoSuchElementException])
      .withMessage(s"for element to be visible and enabled by xpath: $xpath")
    val condition:ExpectedCondition[WebElement] = ExpectedConditions.elementToBeClickable(By.xpath(xpath))
    Try{wait.until(condition)}
  }

I've tried to upgrade Selenium to 3.1.0 version and after that I noticed a lot of stack traces similar to this one in my console when running tests:

Mar 28, 2017 1:41:49 PM org.openqa.selenium.support.ui.ExpectedConditions findElement
WARNING: WebDriverException thrown by findElement(By.xpath: //a[text()='Log out'])
org.openqa.selenium.NoSuchElementException: Cannot locate an element using By.xpath: //a[text()='Log out']
For documentation on this error, please visit: http://seleniumhq.org/exceptions/no_such_element.html
Build info: version: '3.1.0', revision: 'b94c902', time: '2017-02-16 12:21:31 -0800'
System info: host: 'POSITRON', ip: '127.0.1.1', os.name: 'Linux', os.arch: 'amd64', os.version: '4.4.0-66-generic', java.version: '1.8.0_121'
Driver info: driver.version: unknown
    at org.openqa.selenium.support.ui.ExpectedConditions.lambda$findElement$0(ExpectedConditions.java:896)

So basically it prints a WARNING stack trace every time it polls. It's not critical of course but it really bloats the console.
Could you explain how to disable such warnings to be printed from FluentWait-s and probably point out to some rationale behind such behavior?

Body:
I've just set root logger level to SEVERE:

LogManager.getLogManager.getLogger("").setLevel(Level.SEVERE)

That solved problem for me.


问:
MSSQL: difference between servers regarding date conversion
I have this script:

```<code>SELECT UserID,
       CONVERT(SmallDateTime, cast([1]  + '/' + [2] + '/' + [3] as varchar)) as ReleaseDate,
       ChannelID
FROM
(
SELECT RU.UserID, U.FieldID,  RU.ChannelID, U.AnswerText
FROM dbo.Users U WITH (NOLOCK) INNER JOIN dbo.ResourceUsers RU WITH (NOLOCK)
      ON U.UserID = RU.UserID
WHERE  (FieldID = 1 -- release day
          OR FieldID = 2 -- release month
          OR FieldID = 3)
) AS P
PIVOT
(
      MAX(AnswerText) FOR FieldID in ([1], [2], [3])
) AS pvt
</code>```

The same script runs perfectly on a server. On other server, I got this error:

Msg 295, Level 16, State 3, Line 3 Conversion failed when converting
  character string to smalldatetime data type.

Why? What's the difference?
The tables have the same structure on both servers.

答:
In sql server 2012+ you can use datefromparts

```<code>SELECT UserID,
       convert(smalldatetime,datefromparts([3],[2],[1])) as ReleaseDate,
       ChannelID
FROM ....
</code>```

Prior to sql server 2012 that you can create a string in 'yyyyMMdd' format

```<code>SELECT UserID,
       convert(smalldatetime,
          convert(char(4),[3])
        + right('0'+convert(varchar(3),[2]),2)
        + right('0'+convert(varchar(3),[1]),2)
        ) as ReleaseDate,
       ChannelID
FROM ....
</code>```

Body:
I have this script:

SELECT UserID,
       CONVERT(SmallDateTime, cast([1]  + '/' + [2] + '/' + [3] as varchar)) as ReleaseDate,
       ChannelID
FROM
(
SELECT RU.UserID, U.FieldID,  RU.ChannelID, U.AnswerText
FROM dbo.Users U WITH (NOLOCK) INNER JOIN dbo.ResourceUsers RU WITH (NOLOCK)
      ON U.UserID = RU.UserID
WHERE  (FieldID = 1 -- release day
          OR FieldID = 2 -- release month
          OR FieldID = 3)
) AS P
PIVOT
(
      MAX(AnswerText) FOR FieldID in ([1], [2], [3])
) AS pvt

The same script runs perfectly on a server. On other server, I got this error:

Msg 295, Level 16, State 3, Line 3 Conversion failed when converting
  character string to smalldatetime data type.

Why? What's the difference?
The tables have the same structure on both servers.

Body:
In sql server 2012+ you can use datefromparts

SELECT UserID,
       convert(smalldatetime,datefromparts([3],[2],[1])) as ReleaseDate,
       ChannelID
FROM ....

Prior to sql server 2012 that you can create a string in 'yyyyMMdd' format

SELECT UserID,
       convert(smalldatetime,
          convert(char(4),[3])
        + right('0'+convert(varchar(3),[2]),2)
        + right('0'+convert(varchar(3),[1]),2)
        ) as ReleaseDate,
       ChannelID
FROM ....


问:
unable to click radio button after entering text into textbox..why cursor always in textbox?
HTML Code:

```<code><div class="radio">
<input id="passwordRadios1" class="password-radio" type="radio" value="guest" name="passwordRadios">
<input type="hidden" value=" " name="_D:passwordRadios">
<label for="passwordRadios1"> No (you can save your details later)</label>
</div>
<div class="form-inline">
<div class="radio">
<input id="passwordRadios2" class="password-radio" type="radio" value="register" name="passwordRadios">
<input type="hidden" value=" " name="_D:passwordRadios">
<label class="radio-inline" for="passwordRadios2">Yes, my password is:</label>
</div>
<div class="form-group">
<label class="sr-only" for="inputPassword">Password</label>
<input id="inputPassword" class="form-control fixed-width" type="password" value="" placeholder="Enter your password*" name="password" onblur="textboxValidator(id);">
<input type="hidden" value=" " name="_D:password">
</code>```

its showing error in second line

```<code> WebElement checkBox = driver.findElement(By.cssSelector("input[value='guest']"));
 checkBox.click();
</code>```

Error:

Exception in thread "main" org.openqa.selenium.WebDriverException: Element  is not clickable at point (168, 431.83331298828125). Other element would receive the click:
      Command duration or timeout: 78 milliseconds
      Build info: version: 'unknown', revision: '5234b32', time: '2017-03-10 09:00:17 -0800'
      System info: host: 'TWVEN-DES-05', ip: '172.16.24.53', os.name: 'Windows 7', os.arch: 'amd64', os.version: '6.1', java.version: '1.8.0_121'
      Driver info: org.openqa.selenium.firefox.FirefoxDriver
      Capabilities [{applicationCacheEnabled=true, rotatable=false, handlesAlerts=true, databaseEnabled=true, version=47.0.2, platform=WINDOWS, nativeEvents=false, acceptSslCerts=true, webStorageEnabled=true, locationContextEnabled=true, browserName=firefox, takesScreenshot=true, javascriptEnabled=true, cssSelectorsEnabled=true}]
      Session ID: 4857ae27-ea9a-4c3c-ba3d-e04148e04e45
          at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
          at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
          at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
          at java.lang.reflect.Constructor.newInstance(Unknown Source)
          at org.openqa.selenium.remote.ErrorHandler.createThrowable(ErrorHandler.java:216)
          at org.openqa.selenium.remote.ErrorHandler.throwIfResponseFailed(ErrorHandler.java:168)
          at org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:638)
          at org.openqa.selenium.remote.RemoteWebElement.execute(RemoteWebElement.java:274)
          at org.openqa.selenium.remote.RemoteWebElement.click(RemoteWebElement.java:84)
          at tesPack.Test1Class.main(Test1Class.java:43)

答: I've seen something like this before, in my case it was because the element itself wasn't visible within the browser window, and scrolled out of frame. Try adding in actions.moveToElement(checkBox) before your click.

Body:
HTML Code:

<input id="passwordRadios1" class="password-radio" type="radio" value="guest" name="passwordRadios">
<input type="hidden" value=" " name="_D:passwordRadios">
 No (you can save your details later)

<input id="passwordRadios2" class="password-radio" type="radio" value="register" name="passwordRadios">
<input type="hidden" value=" " name="_D:passwordRadios">
Yes, my password is:

Password
<input id="inputPassword" class="form-control fixed-width" type="password" value="" placeholder="Enter your password*" name="password" onblur="textboxValidator(id);">
<input type="hidden" value=" " name="_D:password">

its showing error in second line

 WebElement checkBox = driver.findElement(By.cssSelector("input[value='guest']"));
 checkBox.click();

Error:

Exception in thread "main" org.openqa.selenium.WebDriverException: Element  is not clickable at point (168, 431.83331298828125). Other element would receive the click:
      Command duration or timeout: 78 milliseconds
      Build info: version: 'unknown', revision: '5234b32', time: '2017-03-10 09:00:17 -0800'
      System info: host: 'TWVEN-DES-05', ip: '172.16.24.53', os.name: 'Windows 7', os.arch: 'amd64', os.version: '6.1', java.version: '1.8.0_121'
      Driver info: org.openqa.selenium.firefox.FirefoxDriver
      Capabilities [{applicationCacheEnabled=true, rotatable=false, handlesAlerts=true, databaseEnabled=true, version=47.0.2, platform=WINDOWS, nativeEvents=false, acceptSslCerts=true, webStorageEnabled=true, locationContextEnabled=true, browserName=firefox, takesScreenshot=true, javascriptEnabled=true, cssSelectorsEnabled=true}]
      Session ID: 4857ae27-ea9a-4c3c-ba3d-e04148e04e45
          at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
          at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
          at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
          at java.lang.reflect.Constructor.newInstance(Unknown Source)
          at org.openqa.selenium.remote.ErrorHandler.createThrowable(ErrorHandler.java:216)
          at org.openqa.selenium.remote.ErrorHandler.throwIfResponseFailed(ErrorHandler.java:168)
          at org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:638)
          at org.openqa.selenium.remote.RemoteWebElement.execute(RemoteWebElement.java:274)
          at org.openqa.selenium.remote.RemoteWebElement.click(RemoteWebElement.java:84)
          at tesPack.Test1Class.main(Test1Class.java:43)


问:
Refresh ListView in fragment TabHost
I have MainActivity, which holds fragment. One of my fragments (Participants) checks if there's anything in database. If no, shows fragment(EmptyParticipantsList) with message to add data. If yes, it shows fragment with TabHost with 2 tabs, one of them holds fragment (ParticipantsList) with ListView with database entries. There's a FAB button to add more records. How can I refresh ListView after adding another record? I'm not sure since TabHost is not working with FragmentManager which I'm using in app.

//TODO refresh ListView is the place where I need to put my code.

EDIT 6.5.2017
I modify the code and add 'myCursorAdapter.notifyDataSetChanged();' after adding/editting items in SQLite but List still not refresh it self. Any help?

Participants.java

```<code>  myDB =  new DBAdapter(getActivity());
    myDB.open();
    Class S;
    if (myDB.isEmptyParticipants()) {
        S = EmptyParticipantsList.class;
    } else {
        S = ParticipantsList.class;
    }
    myDB.close();

    mTabHost = (FragmentTabHost) root.findViewById(R.id.tabHost);
    mTabHost.setup(getContext(), getChildFragmentManager(), android.R.id.tabcontent);
    mTabHost.addTab(mTabHost.newTabSpec("tab1").setIndicator("List of participants"),
    S, bundle1);
    mTabHost.addTab(mTabHost.newTabSpec("tab2").setIndicator("Event information"),
            EventInfo.class, bundle1);
</code>```

ParticipantsList.java

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

DBAdapter myDB;
ListView participantList;
long id_eventu;
EditText participantName;
EditText participantSurname;
SimpleCursorAdapter myCursorAdapter;

public ParticipantsList() {
    // Required empty public constructor
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    final View root = inflater.inflate(R.layout.fragment_participants_list, container, false);
    myDB =  new DBAdapter(getContext());
    participantList = (ListView) root.findViewById(R.id.list_participants);
    myDB.open();
    FloatingActionButton fab1 = (FloatingActionButton) root.findViewById(R.id.fab_participant);
    Bundle bundle = getArguments();
    if (bundle != null) {
        id_eventu = bundle.getLong("key");
    }
    myDB.open();
    Cursor cursor = myDB.getAllRowsParticipant(id_eventu);
    String[] fromParticipantNames = new String[] {DBAdapter.PARTICIPANTS_NAME, DBAdapter.PARTICIPANTS_SURNAME};
    int[] toViewIDs = new int[] {R.id.name_of_participant, R.id.surname_of_participant};
    myCursorAdapter = new SimpleCursorAdapter(getActivity(),R.layout.row_participant, cursor, fromParticipantNames, toViewIDs,0 );
    participantList.setAdapter(myCursorAdapter);
    myCursorAdapter.notifyDataSetChanged();
    myDB.close();

    registerForContextMenu(participantList);

    fab1.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

            final AlertDialog.Builder addParticipantDialog = new AlertDialog.Builder(getContext());
            addParticipantDialog.setTitle("Add new Participant");
            final View viewInflated = LayoutInflater.from(getContext()).inflate(R.layout.dialog_add_participant, (ViewGroup) getView(), false);
            addParticipantDialog.setView(viewInflated);
            participantName = (EditText) viewInflated.findViewById(R.id.add_participant_name);
            participantSurname = (EditText) viewInflated.findViewById(R.id.add_participant_surname);
            addParticipantDialog.setPositiveButton(R.string.save, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialogInterface, int i) {
                    //TODO zde se načtou data z polí a uloží do databáze
                    String name = participantName.getText().toString();
                    String surname = participantSurname.getText().toString();
                    myDB.open();
                    myDB.insertRowParticipant(name,surname, id_eventu);
                    Toast.makeText(getActivity(),"Participant added", Toast.LENGTH_LONG).show();
                    myDB.close();
                    myCursorAdapter.notifyDataSetChanged();

                }
            });
            addParticipantDialog.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialogInterface, int i) {
                    dialogInterface.cancel();
                }
            });
            addParticipantDialog.show();
        }
    });

    return root;
}

@Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
    super.onCreateContextMenu(menu, v, menuInfo);
    MenuInflater inflater = getActivity().getMenuInflater();
    inflater.inflate(R.menu.event_popup, menu);
}

@Override
public boolean onContextItemSelected(MenuItem item) {
    AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();
    final long id = info.id;
    switch(item.getItemId()) {
        case R.id.edit_event_popup:
            final android.app.AlertDialog.Builder addEventDialog = new android.app.AlertDialog.Builder(getContext());
            addEventDialog.setTitle("Edit participant");
            final View viewInflated = LayoutInflater.from(getContext()).inflate(R.layout.dialog_add_participant, (ViewGroup) getView(), false);
            addEventDialog.setView(viewInflated);
            participantName = (EditText) viewInflated.findViewById(R.id.add_participant_name);
            participantSurname = (EditText) viewInflated.findViewById(R.id.add_participant_surname);
            myDB.open();
            Cursor c = myDB.db.rawQuery("SELECT * FROM participants WHERE _id=="+id, null);
            c.close();
            c.moveToFirst();
            String name_par = c.getString(c.getColumnIndex("name"));
            String surname_par = c.getString(c.getColumnIndex("surname"));
            participantName.setText(name_par); //tady se musí načíst data z db
            participantSurname.setText(surname_par);
            addEventDialog.setPositiveButton(R.string.save, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialogInterface, int i) {
                    //TODO zde se načtou data z polí a uloží do databáze
                    String str = participantName.getText().toString();
                    String str1 = participantSurname.getText().toString();
                    ContentValues cv = new ContentValues();
                    cv.put("name",str);
                    cv.put("surname",str1);
                    myDB.db.update("participants", cv, "_id="+id, null);
                    Toast.makeText(getActivity(),"participant changed", Toast.LENGTH_LONG).show();
                    myDB.close();
                    myCursorAdapter.notifyDataSetChanged();
                    //TODO refresh listview
                }
            });
            addEventDialog.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialogInterface, int i) {
                    dialogInterface.cancel();
                }
            });
            addEventDialog.show();
            return true;
        case R.id.delete_event_popup:
            myDB.open();
            myDB.deleteRowParticipant(id);
            Toast.makeText(getActivity(),"participant deleted", Toast.LENGTH_LONG).show();
            myCursorAdapter.notifyDataSetChanged();
            //TODO když je to poslední záznam, tak nahodit empty frag
            return true;
        default:
            return super.onContextItemSelected(item);
    }
}
</code>```

}

答:
You should call notifyDataSetChanged after setAdapter

Notifies the attached observers that the underlying data has been
  changed and any View reflecting the data set should refresh itself.

```<code>participantList.setAdapter(myCursorAdapter);
myCursorAdapter.notifyDataSetChanged(); // this
myDB.close();
</code>```

Title: Refresh ListView in fragment TabHost

Body:
I have MainActivity, which holds fragment. One of my fragments (Participants) checks if there's anything in database. If no, shows fragment(EmptyParticipantsList) with message to add data. If yes, it shows fragment with TabHost with 2 tabs, one of them holds fragment (ParticipantsList) with ListView with database entries. There's a FAB button to add more records. How can I refresh ListView after adding another record? I'm not sure since TabHost is not working with FragmentManager which I'm using in app.

//TODO refresh ListView is the place where I need to put my code.

EDIT 6.5.2017
I modify the code and add 'myCursorAdapter.notifyDataSetChanged();' after adding/editting items in SQLite but List still not refresh it self. Any help?

Participants.java

  myDB =  new DBAdapter(getActivity());
    myDB.open();
    Class S;
    if (myDB.isEmptyParticipants()) {
        S = EmptyParticipantsList.class;
    } else {
        S = ParticipantsList.class;
    }
    myDB.close();

    mTabHost = (FragmentTabHost) root.findViewById(R.id.tabHost);
    mTabHost.setup(getContext(), getChildFragmentManager(), android.R.id.tabcontent);
    mTabHost.addTab(mTabHost.newTabSpec("tab1").setIndicator("List of participants"),
    S, bundle1);
    mTabHost.addTab(mTabHost.newTabSpec("tab2").setIndicator("Event information"),
            EventInfo.class, bundle1);

ParticipantsList.java

 public class ParticipantsList extends DialogFragment {

DBAdapter myDB;
ListView participantList;
long id_eventu;
EditText participantName;
EditText participantSurname;
SimpleCursorAdapter myCursorAdapter;

public ParticipantsList() {
    // Required empty public constructor
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    final View root = inflater.inflate(R.layout.fragment_participants_list, container, false);
    myDB =  new DBAdapter(getContext());
    participantList = (ListView) root.findViewById(R.id.list_participants);
    myDB.open();
    FloatingActionButton fab1 = (FloatingActionButton) root.findViewById(R.id.fab_participant);
    Bundle bundle = getArguments();
    if (bundle != null) {
        id_eventu = bundle.getLong("key");
    }
    myDB.open();
    Cursor cursor = myDB.getAllRowsParticipant(id_eventu);
    String[] fromParticipantNames = new String[] {DBAdapter.PARTICIPANTS_NAME, DBAdapter.PARTICIPANTS_SURNAME};
    int[] toViewIDs = new int[] {R.id.name_of_participant, R.id.surname_of_participant};
    myCursorAdapter = new SimpleCursorAdapter(getActivity(),R.layout.row_participant, cursor, fromParticipantNames, toViewIDs,0 );
    participantList.setAdapter(myCursorAdapter);
    myCursorAdapter.notifyDataSetChanged();
    myDB.close();

    registerForContextMenu(participantList);

    fab1.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

            final AlertDialog.Builder addParticipantDialog = new AlertDialog.Builder(getContext());
            addParticipantDialog.setTitle("Add new Participant");
            final View viewInflated = LayoutInflater.from(getContext()).inflate(R.layout.dialog_add_participant, (ViewGroup) getView(), false);
            addParticipantDialog.setView(viewInflated);
            participantName = (EditText) viewInflated.findViewById(R.id.add_participant_name);
            participantSurname = (EditText) viewInflated.findViewById(R.id.add_participant_surname);
            addParticipantDialog.setPositiveButton(R.string.save, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialogInterface, int i) {
                    //TODO zde se načtou data z polí a uloží do databáze
                    String name = participantName.getText().toString();
                    String surname = participantSurname.getText().toString();
                    myDB.open();
                    myDB.insertRowParticipant(name,surname, id_eventu);
                    Toast.makeText(getActivity(),"Participant added", Toast.LENGTH_LONG).show();
                    myDB.close();
                    myCursorAdapter.notifyDataSetChanged();

                }
            });
            addParticipantDialog.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialogInterface, int i) {
                    dialogInterface.cancel();
                }
            });
            addParticipantDialog.show();
        }
    });

    return root;
}

@Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
    super.onCreateContextMenu(menu, v, menuInfo);
    MenuInflater inflater = getActivity().getMenuInflater();
    inflater.inflate(R.menu.event_popup, menu);
}

@Override
public boolean onContextItemSelected(MenuItem item) {
    AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();
    final long id = info.id;
    switch(item.getItemId()) {
        case R.id.edit_event_popup:
            final android.app.AlertDialog.Builder addEventDialog = new android.app.AlertDialog.Builder(getContext());
            addEventDialog.setTitle("Edit participant");
            final View viewInflated = LayoutInflater.from(getContext()).inflate(R.layout.dialog_add_participant, (ViewGroup) getView(), false);
            addEventDialog.setView(viewInflated);
            participantName = (EditText) viewInflated.findViewById(R.id.add_participant_name);
            participantSurname = (EditText) viewInflated.findViewById(R.id.add_participant_surname);
            myDB.open();
            Cursor c = myDB.db.rawQuery("SELECT * FROM participants WHERE _id=="+id, null);
            c.close();
            c.moveToFirst();
            String name_par = c.getString(c.getColumnIndex("name"));
            String surname_par = c.getString(c.getColumnIndex("surname"));
            participantName.setText(name_par); //tady se musí načíst data z db
            participantSurname.setText(surname_par);
            addEventDialog.setPositiveButton(R.string.save, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialogInterface, int i) {
                    //TODO zde se načtou data z polí a uloží do databáze
                    String str = participantName.getText().toString();
                    String str1 = participantSurname.getText().toString();
                    ContentValues cv = new ContentValues();
                    cv.put("name",str);
                    cv.put("surname",str1);
                    myDB.db.update("participants", cv, "_id="+id, null);
                    Toast.makeText(getActivity(),"participant changed", Toast.LENGTH_LONG).show();
                    myDB.close();
                    myCursorAdapter.notifyDataSetChanged();
                    //TODO refresh listview
                }
            });
            addEventDialog.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialogInterface, int i) {
                    dialogInterface.cancel();
                }
            });
            addEventDialog.show();
            return true;
        case R.id.delete_event_popup:
            myDB.open();
            myDB.deleteRowParticipant(id);
            Toast.makeText(getActivity(),"participant deleted", Toast.LENGTH_LONG).show();
            myCursorAdapter.notifyDataSetChanged();
            //TODO když je to poslední záznam, tak nahodit empty frag
            return true;
        default:
            return super.onContextItemSelected(item);
    }
}

}

Body:
You should call notifyDataSetChanged after setAdapter

Notifies the attached observers that the underlying data has been
  changed and any View reflecting the data set should refresh itself.

participantList.setAdapter(myCursorAdapter);
myCursorAdapter.notifyDataSetChanged(); // this
myDB.close();