问:
How to clear a remote pushed notification for iOS?
So I've been reading up on remote notifications, and have finally made it work; our app is receiving notifications from our server. We now want to remove or update an unread notification if a certain condition meets on our server (e.g the notification is no longer valid). I understand that "silent" notifications are the only way to go, but I am still confused as to how.
If a silent notification triggers my app to wake up, I would be able to schedule local notifications, but will I be able to remove already existing remote notifications?

Is the only solution to exclusively use silent notifications from the server, and schedule all notifications as local notifications with a custom identifier which I can later remove?
E.g, can I never use fire&forget remote push notifications from my server to devices if I want this feature?

Edit: This app supports down to iOS 9 :/

答:
I ended up doing it like TawaNicolas suggested in his answer, by getting the received notifications with getDeliveredNoti...., then check the userInfo of every notification to find which ones I wanted to delete. I stored the removable notifications' identifiers in an array, and called removeDelivered....

This is exactly as his answer suggests, but this didn't work at first, and I had a hard time finding out why. I'm still not completely sure I have fixed it, but my tests shows that it's working - and my solution somewhat makes sense.

The thing was, inside the didReceiveRemote..-function, you have to call completionHandler(.newData) at the end. This is to notify the NotificationCenter that something has changed. I started to suspect that this callback was called before the removable notifications actually got removed. I checked the documentation, and removeDeliveredNotifications is indeed async. This means that when I do this:

```<code>UNUserNotificationCenter.current().removeDeliveredNotifications(withIdentifiers: removableIDs)
completionHandler(.newData)
</code>```

it is not guaranteed that the first function is completed before calling the second function. This means that the completionHandler, which tells my NotificationCenter that something has been updated, is completed first, and THEN the notifications gets removed from the system. (NotificationCenter apparently does not invoke its own completionHandler to update the UI after that function).

All this may or may not happen. As I was experiencing; when connected to the debugger, the removeDeliveredNotifications-function was so fast that it was always completed before the completionHandler was invoked, meaning that the notifications were removed before updating the system. So everything looked great when developing this. When I disconnected from the debugger, the removeDeliveredNotifications-function was slightly slower, and since it's async, it was completed after I invoked the completionHandler - causing the system to update too soon.

The best way to solve this would be for Apple to give us a completionBlock for removeDeliveredNotifications and call our completionHandler inside it, but they haven't.

To solve this now I have gone dirty by adding a fixed delay of 0.2 seconds. It could probably be lower than 0.2, but it isn't really important with a second from or to for what we're doing.

This is a class and function I created to easily delay something from anywhere:

```<code>class RuntimeUtils{
    class func delay(seconds delay:Double, closure:@escaping ()->()){
        DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + Double(Int64(delay*Double(NSEC_PER_SEC))) / Double(NSEC_PER_SEC), execute: closure)
    }
}
</code>```

And here I use it inside didReceiveRemoteNotification: in AppDelegate:

```<code>UNUserNotificationCenter.current().removeDeliveredNotifications(withIdentifiers: removableIDs)
RuntimeUtils.delay(seconds: 0.2, closure: {
    completionHandler(.newData)
})
</code>```

After adding this delay to the completionHandler, it is always executed after my deletion of notification, and it seems to work every time, with or without debugger connected.

This was a disgusting problem, with a nasty fix.

Body:
I ended up doing it like TawaNicolas suggested in his answer, by getting the received notifications with getDeliveredNoti...., then check the userInfo of every notification to find which ones I wanted to delete. I stored the removable notifications' identifiers in an array, and called removeDelivered....

This is exactly as his answer suggests, but this didn't work at first, and I had a hard time finding out why. I'm still not completely sure I have fixed it, but my tests shows that it's working - and my solution somewhat makes sense.

The thing was, inside the didReceiveRemote..-function, you have to call completionHandler(.newData) at the end. This is to notify the NotificationCenter that something has changed. I started to suspect that this callback was called before the removable notifications actually got removed. I checked the documentation, and removeDeliveredNotifications is indeed async. This means that when I do this:

UNUserNotificationCenter.current().removeDeliveredNotifications(withIdentifiers: removableIDs)
completionHandler(.newData)

it is not guaranteed that the first function is completed before calling the second function. This means that the completionHandler, which tells my NotificationCenter that something has been updated, is completed first, and THEN the notifications gets removed from the system. (NotificationCenter apparently does not invoke its own completionHandler to update the UI after that function).

All this may or may not happen. As I was experiencing; when connected to the debugger, the removeDeliveredNotifications-function was so fast that it was always completed before the completionHandler was invoked, meaning that the notifications were removed before updating the system. So everything looked great when developing this. When I disconnected from the debugger, the removeDeliveredNotifications-function was slightly slower, and since it's async, it was completed after I invoked the completionHandler - causing the system to update too soon.

The best way to solve this would be for Apple to give us a completionBlock for removeDeliveredNotifications and call our completionHandler inside it, but they haven't.

To solve this now I have gone dirty by adding a fixed delay of 0.2 seconds. It could probably be lower than 0.2, but it isn't really important with a second from or to for what we're doing.

This is a class and function I created to easily delay something from anywhere:

class RuntimeUtils{
    class func delay(seconds delay:Double, closure:@escaping ()->()){
        DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + Double(Int64(delay*Double(NSEC_PER_SEC))) / Double(NSEC_PER_SEC), execute: closure)
    }
}

And here I use it inside didReceiveRemoteNotification: in AppDelegate:

UNUserNotificationCenter.current().removeDeliveredNotifications(withIdentifiers: removableIDs)
RuntimeUtils.delay(seconds: 0.2, closure: {
    completionHandler(.newData)
})

After adding this delay to the completionHandler, it is always executed after my deletion of notification, and it seems to work every time, with or without debugger connected.

This was a disgusting problem, with a nasty fix.


来源: stackexchange

问:
Getting error in LINQ query to sqlite
I'm trying to make login query in sqlite but can't convert AsyncTableQuery in boolean

```<code>public bool queryLogIn(string userNameLogIn,string passwordLogIn)
{
    var query=database.Table<Users>().Where(i => i.UserName == userNameLogIn && i.Password == passwordLogIn);

    if (query == true)//There is error
    {
        return true;
    }
    else
    {
        return false;
    }
}
</code>```

答:
You can use FirstOrDefault function for login is success.</p>

```<code>public bool queryLogIn(string userNameLogIn,string passwordLogIn)
{
var query=database.Table<Users>().FirstOrDefault(i => i.UserName == userNameLogIn && i.Password == passwordLogIn);

if (query == null)//There is error
{
    return false;
}
else
{
    return true;
}
}
</code>```

ContentLicense: CC BY-SA 3.0

Title: Getting error in LINQ query to sqlite

Body:
I'm trying to make login query in sqlite but can't convert AsyncTableQuery in boolean

public bool queryLogIn(string userNameLogIn,string passwordLogIn)
{
    var query=database.Table<Users>().Where(i => i.UserName == userNameLogIn && i.Password == passwordLogIn);

    if (query == true)//There is error
    {
        return true;
    }
    else
    {
        return false;
    }
}

Body:
You can use FirstOrDefault function for login is success.

public bool queryLogIn(string userNameLogIn,string passwordLogIn)
{
var query=database.Table<Users>().FirstOrDefault(i => i.UserName == userNameLogIn && i.Password == passwordLogIn);

if (query == null)//There is error
{
    return false;
}
else
{
    return true;
}
}


问:
Stop virtualenv using global site-packages pip?
I'm using Python 2.7.14 installed through Homebrew on MacOS. How do I stop this happening?:

```<code>$ virtualenv --no-site-packages venv
New python executable in /private/tmp/venv/bin/python2.7
Also creating executable in /private/tmp/venv/bin/python
Installing setuptools, pip, wheel...done.
$ . venv/bin/activate
(venv) $ pip --version
pip 9.0.1 from /usr/local/lib/python2.7/site-packages (python 2.7)
</code>```

What I expected

```<code>$ env -i PATH=/tmp/venv/bin pip --version
pip 9.0.1 from /private/tmp/venv/lib/python2.7/site-packages (python 2.7)
</code>```

EDIT: Solution related Why does virtualenv inherit $PYTHONPATH from my shell?

答:
I edited venv/bin/activate with this line:

```<code>unset PYTHONPATH
</code>```

Body:
I'm using Python 2.7.14 installed through Homebrew on MacOS. How do I stop this happening?:

$ virtualenv --no-site-packages venv
New python executable in /private/tmp/venv/bin/python2.7
Also creating executable in /private/tmp/venv/bin/python
Installing setuptools, pip, wheel...done.
$ . venv/bin/activate
(venv) $ pip --version
pip 9.0.1 from /usr/local/lib/python2.7/site-packages (python 2.7)

What I expected

$ env -i PATH=/tmp/venv/bin pip --version
pip 9.0.1 from /private/tmp/venv/lib/python2.7/site-packages (python 2.7)

EDIT: Solution related Why does virtualenv inherit $PYTHONPATH from my shell?

Body:
I edited venv/bin/activate with this line:

unset PYTHONPATH

ContentLicense: CC BY-SA 4.0


问:
Multivalued attributes in MySQL
I am working on a database in MySQL to show multivalued attributes. I am trying to find a way to create a parent and child table. The idea that I am working with is having an employee table and a hobby table. The hobbies in the hobby table would be considered the multivalued attributes since employees can have more than one hobby. My question would be, when creating these tables, should I use 3NF and add a 3 table to show the relation between the two or is there a way to implement this idea with simply two tables. I’m not very familiar with multivalued attributes so I need help creating the tables as far as what kind of keys each would use, as well as the end form. I believe I would need to make it in 3NF form and have the hobbies as the multivalued attribute, but have the hobby id from the hobby table as a primary key and the employee id as another primary key and then making the relational table contain both the employee id and hobby id as foreign keys referencing the other two tables. Any help or suggestions to show multivalued attributes would be greatly appreciated!</p>

答:
You have a table for employees already. It probably has a primary key we'll call employee_id.

You need a table for hobbies. It will need a primary key we'll call hobby_id.

Then, you need a way to relate employees and hobbies many-to-many.  That's implemented with a third table, let's call it employees_hobbies. Using a name like that is a good idea, because the next guy to work on your code will recognize its purpose right away.

employees_hobbies should have two columns, employee_id and hobby_id. Those two columns together should be the composite primary key. Then, to confer a hobby on an employee, you add a row to employees_hobbies containing the two id values. If an employee drops a hobby, you delete the row.

If you want a list of employees showing their hobbies, you do this

```<code> SELECT e.name, GROUP_CONCAT(h.hobbyname) hobbies
   FROM employees e
   LEFT JOIN employees_hobbies eh ON e.employee_id = eh.employee_id
   LEFT JOIN hobbies h ON eh.hobby_id = h.hobby_id
  GROUP BY e.employee_id, e.name
</code>```

Use LEFT JOIN operations here to keep employees without any hobbies (all work and no play) in your list.

If you want to find the most common five hobbies and the employees doing them, try this

```<code> SELECT COUNT(*) hobbycount, h.hobbyname,
        GROUP_CONCAT(e.name ORDER BY e.name) people
   FROM hobbies h
   LEFT JOIN employees_hobbies eh ON h.hobby_id = eh.hobby_id
   LEFT JOIN employees e ON eh.employee_id = e.employee_id
  GROUP BY h.hobbyname
  ORDER BY 1 DESC
  LIMIT 5
</code>```

This way of handling many-to-many relationships gives you all kinds of ways of slicing and dicing your data.

MySQL is made for this sort of thing and handles it very efficiently at small scale and large, opinions to the contrary notwithstanding.

(Avoid putting a surrogate primary id key into your employees_hobbies table. It adds no value.)

Title: Multivalued attributes in MySQL

Body:
You have a table for employees already. It probably has a primary key we'll call employee_id.

You need a table for hobbies. It will need a primary key we'll call hobby_id.

Then, you need a way to relate employees and hobbies many-to-many.  That's implemented with a third table, let's call it employees_hobbies. Using a name like that is a good idea, because the next guy to work on your code will recognize its purpose right away.

employees_hobbies should have two columns, employee_id and hobby_id. Those two columns together should be the composite primary key. Then, to confer a hobby on an employee, you add a row to employees_hobbies containing the two id values. If an employee drops a hobby, you delete the row.

If you want a list of employees showing their hobbies, you do this

 SELECT e.name, GROUP_CONCAT(h.hobbyname) hobbies
   FROM employees e
   LEFT JOIN employees_hobbies eh ON e.employee_id = eh.employee_id
   LEFT JOIN hobbies h ON eh.hobby_id = h.hobby_id
  GROUP BY e.employee_id, e.name

Use LEFT JOIN operations here to keep employees without any hobbies (all work and no play) in your list.

If you want to find the most common five hobbies and the employees doing them, try this

 SELECT COUNT(*) hobbycount, h.hobbyname,
        GROUP_CONCAT(e.name ORDER BY e.name) people
   FROM hobbies h
   LEFT JOIN employees_hobbies eh ON h.hobby_id = eh.hobby_id
   LEFT JOIN employees e ON eh.employee_id = e.employee_id
  GROUP BY h.hobbyname
  ORDER BY 1 DESC
  LIMIT 5

This way of handling many-to-many relationships gives you all kinds of ways of slicing and dicing your data.

MySQL is made for this sort of thing and handles it very efficiently at small scale and large, opinions to the contrary notwithstanding.

(Avoid putting a surrogate primary id key into your employees_hobbies table. It adds no value.)


问:
Different activity title in different intent actions
I have one activity and three intet filters, each with different label set on, (AndroidManifiest.xml below)

```<code>    <activity android:name=".activities.RecordActivity">
        <intent-filter>
            <category android:name="android.intent.category.DEFAULT" />
            <action android:name="com.keitai.enigma.OPEN_RECORD" />
        </intent-filter>
        <intent-filter android:label="@string/newRecord">
            <category android:name="android.intent.category.DEFAULT" />
            <action android:name="com.keitai.enigma.NEW_RECORD" />
        </intent-filter>
        <intent-filter android:label="@string/editRecord">
            <category android:name="android.intent.category.DEFAULT" />
            <action android:name="com.keitai.enigma.EDIT_RECORD" />
        </intent-filter>
    </activity>
</code>```

But activity title is not changing to label set in intent filter :( Activity always contains application label.

What I'm donig wrong?

答:
Are you sure you don't have code that is setting the title explicitly?

Are you sure that  the OPEN_RECORD intent isn't the one being triggered every time?

Have you tried debugging by making sure everything has a distinct label (application, activity, each intent-filter) and seeing what happens?

I agree with you that what you expected to happen is what the docs say should happen. But it seems like the default <application> label is being used regardless. I'm afraid if one of the above ideas doesn't help, then I'm out of ideas. I might try it myself later on my system to see if it happens for me.

http://developer.android.com/guide/topics/manifest/intent-filter-element.html#label

android:label

A user-readable label for the parent component. This label, rather than the one set by the parent component, is used when the component is presented to the user as having the capability described by the filter.

...

The default value is the label set by the parent component. If the parent does not specify a label, the default is the label set by the  element's label attribute.

http://developer.android.com/guide/topics/manifest/manifest-intro.html#iconlabel

Icons and Labels

...

In every case, the icon and label set in a containing element become the default icon and label settings for all of the container's subelements. Thus, the icon and label set in the  element are the default icon and label for each of the application's components. Similarly, the icon and label set for a component — for example, an  element — are the default settings for each of the component's  elements. If an  element sets a label, but an activity and its intent filter do not, the application label is treated as the label for both the activity and the intent filter.

...

ContentLicense: CC BY-SA 2.5

Body:
I have one activity and three intet filters, each with different label set on, (AndroidManifiest.xml below)

    <activity android:name=".activities.RecordActivity">
        <intent-filter>
            <category android:name="android.intent.category.DEFAULT" />
            <action android:name="com.keitai.enigma.OPEN_RECORD" />
        </intent-filter>
        <intent-filter android:label="@string/newRecord">
            <category android:name="android.intent.category.DEFAULT" />
            <action android:name="com.keitai.enigma.NEW_RECORD" />
        </intent-filter>
        <intent-filter android:label="@string/editRecord">
            <category android:name="android.intent.category.DEFAULT" />
            <action android:name="com.keitai.enigma.EDIT_RECORD" />
        </intent-filter>
    </activity>

But activity title is not changing to label set in intent filter :( Activity always contains application label.

What I'm donig wrong?


问:
What is the idiomatic way to compare two lists for equality?
I have two lists I need to check whether their elements are equal (not shallow check, for elements I might rely on Kernel.==/2.)

Currently, I have:

```<code>[l1 -- l2] ++ [l2 -- l1] == []
</code>```

It looks a bit overcomplicated and not quite idiomatic to me. Am I missing something? Is there a better way to compare two lists for equality?

答:
The shortest way I can think of is to sort the lists and compare them:

```<code>Enum.sort(l1) == Enum.sort(l2)
</code>```

This will run in O(n log n) time instead of O(n ^ 2) for your Kernel.--/2 based solution.

We can't use a plain Set data structure here since the list can contain duplicates and their counts must be kept track of. We can use a Map which counts the frequency of each element and then to compare them:

```<code>iex(1)> l1 = ~w|a a b|a
[:a, :a, :b]
iex(2)> l2 = ~w|a b|a
[:a, :b]
iex(3)> m1 = l1 |> Enum.reduce(%{}, fn x, acc -> Map.update(acc, x, 1, & &1 + 1) end)
%{a: 2, b: 1}
iex(4)> m2 = l2 |> Enum.reduce(%{}, fn x, acc -> Map.update(acc, x, 1, & &1 + 1) end)
%{a: 1, b: 1}
iex(5)> m1 == m2
false
iex(6)> l2 = ~w|a b a|a
[:a, :b, :a]
iex(7)> m2 = l2 |> Enum.reduce(%{}, fn x, acc -> Map.update(acc, x, 1, & &1 + 1) end)
%{a: 2, b: 1}
iex(8)> m1 == m2
true
</code>```

This is also O(n log n) so you may want to benchmark the two solutions with the kind of data you'll have to see which performs better.

Body:
I have two lists I need to check whether their elements are equal (not shallow check, for elements I might rely on Kernel.==/2.)

Currently, I have:

[l1 -- l2] ++ [l2 -- l1] == []

It looks a bit overcomplicated and not quite idiomatic to me. Am I missing something? Is there a better way to compare two lists for equality?

Body:
The shortest way I can think of is to sort the lists and compare them:

Enum.sort(l1) == Enum.sort(l2)

This will run in O(n log n) time instead of O(n ^ 2) for your Kernel.--/2 based solution.

We can't use a plain Set data structure here since the list can contain duplicates and their counts must be kept track of. We can use a Map which counts the frequency of each element and then to compare them:

iex(1)> l1 = ~w|a a b|a
[:a, :a, :b]
iex(2)> l2 = ~w|a b|a
[:a, :b]
iex(3)> m1 = l1 |> Enum.reduce(%{}, fn x, acc -> Map.update(acc, x, 1, & &1 + 1) end)
%{a: 2, b: 1}
iex(4)> m2 = l2 |> Enum.reduce(%{}, fn x, acc -> Map.update(acc, x, 1, & &1 + 1) end)
%{a: 1, b: 1}
iex(5)> m1 == m2
false
iex(6)> l2 = ~w|a b a|a
[:a, :b, :a]
iex(7)> m2 = l2 |> Enum.reduce(%{}, fn x, acc -> Map.update(acc, x, 1, & &1 + 1) end)
%{a: 2, b: 1}
iex(8)> m1 == m2
true

This is also O(n log n) so you may want to benchmark the two solutions with the kind of data you'll have to see which performs better.


问:
TYPO3 Extension: I changed my extension folder name and now TYPO3 throws an error message
So today my extension_builder overwrote my entire TCAs while saving, so I did something stupid: I changed the folder name of my extension via winscp and uploaded the backupfolder of my extension I made yesterday. Now I get the error message

```<code>Oops, an error occurred!
TYPO3 Fatal Error: Extension key "icingaconfgen" is NOT loaded!
</code>```

I know the error could be fixed with changing the state of the extension in the PackageStates.php to inactive, but the problem is: The extension doesn't appear in this file. Interesting enough the foldername I changed my old old extension folder to ("x") appears in the file as inactive though. What should I do now?

答:
If there is no non-existent extension listed in your PackageStates.php you should be fine after clearing TYPO3s cache.

Go to the install tool and do it under "important actions".

Or remove the contents of the typo3temp folder.

Body:
So today my extension_builder overwrote my entire TCAs while saving, so I did something stupid: I changed the folder name of my extension via winscp and uploaded the backupfolder of my extension I made yesterday. Now I get the error message

Oops, an error occurred!
TYPO3 Fatal Error: Extension key "icingaconfgen" is NOT loaded!

I know the error could be fixed with changing the state of the extension in the PackageStates.php to inactive, but the problem is: The extension doesn't appear in this file. Interesting enough the foldername I changed my old old extension folder to ("x") appears in the file as inactive though. What should I do now?


问:
Get user's current location when they click on button
I am building a web application based on users current location using javascript/jquery. How to get current location of user when he browse my application on all browsers?</p>

答:
I think something like below code can help. You can call getLocation() and it will save the location inside _position variable which can be used later.</p>

```<code>var _position;

function getLocation(){
    navigator.geolocation.getCurrentPosition(onSuccess, onError);
}

var onSuccess = function(position) {
    _position = position;
};

function onError(error) {
    alert('Error: ' + error.message);
}
</code>```

Body:
I think something like below code can help. You can call getLocation() and it will save the location inside _position variable which can be used later.

var _position;

function getLocation(){
    navigator.geolocation.getCurrentPosition(onSuccess, onError);
}

var onSuccess = function(position) {
    _position = position;
};

function onError(error) {
    alert('Error: ' + error.message);
}


问:
long-poll jQuery.ajax() fails to callback after phone sleeps?
My web app uses the 'long poll' method to keep up to date with the latest data from my server. The server only responds when it has new data, which can be many minutes apart. (It is a heating control system where you only see updates when room temperatures changes or somebody changes the settings).

```<code>var version = "0";
function updater() {
    $.ajax({
        type: "POST",
        url: "/listen",
        data: version,
        success: function (data) {
            version = handleUpdates(data);
            updater();
        },
        error: function () {
            setTimeout(updater, 1000);
        }
    });
}
</code>```

It works fine on desktop browsers and on phones except in one case. I have found that on android phones with Chrome something odd happens after the phone has gone to sleep for more then about 10 minutes. The post request seems to be dropped, which I guess is reasonable since the phone is asleep. In the Chrome debugger's Network tab, the Status Text of the POST request says (canceled).

The problem is when I wake the phone up while the request is cancelled, neither the success() or error() function is called, and my web app never gets updated. $.ajax() has broken its promise to call me back.

The problem only happens on some devices. I have been able to do a few ad-hoc tests by borrowing devices off friends. So far I have only seen the problem on android phones. But not is the phone is connected to a charger. I have not seen it on any tablets, on apple devices or windows PCs.

I have tried adding a timeout to the ajax settings:

```<code>     timeout: 120 * 1000,
</code>```

This helps because the error() function is eventually called up to 2 minutes after the wake up. But I'd like the user to see updates within 1 or 2 seconds. I don't want to make the timeout so short because it would create unnecessary server traffic.

I have also tried detecting whether device is asleep by looking for lateness in a one second setInterval as described in Can any desktop browsers detect when the computer resumes from sleep?.
When I detect the wake up, I abort() the post and start another. This helps in most cases. But it turns out to be unreliable. Sometimes time events seem to keep ticking normally during sleep and the post request gets cancelled anyway. And it it does not feel like a reliable fix.

I am using latest version of jQuery: (2.1.2) and Chrome (47).

答: How about a setInterval, that stores the time it was called, then compares the last time it was called to the current time - if your interval is 10 seconds and the time passed since the last run was 5 minutes, you can assume you've just woken from sleep? Then abort the current ajax call, and restart it.

Body:
My web app uses the 'long poll' method to keep up to date with the latest data from my server. The server only responds when it has new data, which can be many minutes apart. (It is a heating control system where you only see updates when room temperatures changes or somebody changes the settings).

var version = "0";
function updater() {
    $.ajax({
        type: "POST",
        url: "/listen",
        data: version,
        success: function (data) {
            version = handleUpdates(data);
            updater();
        },
        error: function () {
            setTimeout(updater, 1000);
        }
    });
}

It works fine on desktop browsers and on phones except in one case. I have found that on android phones with Chrome something odd happens after the phone has gone to sleep for more then about 10 minutes. The post request seems to be dropped, which I guess is reasonable since the phone is asleep. In the Chrome debugger's Network tab, the Status Text of the POST request says (canceled).

The problem is when I wake the phone up while the request is cancelled, neither the success() or error() function is called, and my web app never gets updated. $.ajax() has broken its promise to call me back.

The problem only happens on some devices. I have been able to do a few ad-hoc tests by borrowing devices off friends. So far I have only seen the problem on android phones. But not is the phone is connected to a charger. I have not seen it on any tablets, on apple devices or windows PCs.

I have tried adding a timeout to the ajax settings:

     timeout: 120 * 1000,

This helps because the error() function is eventually called up to 2 minutes after the wake up. But I'd like the user to see updates within 1 or 2 seconds. I don't want to make the timeout so short because it would create unnecessary server traffic.

I have also tried detecting whether device is asleep by looking for lateness in a one second setInterval as described in Can any desktop browsers detect when the computer resumes from sleep?.
When I detect the wake up, I abort() the post and start another. This helps in most cases. But it turns out to be unreliable. Sometimes time events seem to keep ticking normally during sleep and the post request gets cancelled anyway. And it it does not feel like a reliable fix.

I am using latest version of jQuery: (2.1.2) and Chrome (47).


问:
Including CSS files in PDF using wicked_pdf helpers
I am successfully loading CSS files in my PDF file using wicked_pdf gem helpers:

```<code><%= wicked_pdf_stylesheet_link_tag "pdf" %>
</code>```

This works great in development, however when i deploy in production the pdf CSS file is not correctly imported.  Also note that the file is "pdf.scss.erb" and not just "pdf.css".

I am not sure how to fix this problem. Looking at the server logs, i do not see any missed file warnings.

答:
I myself solved the problem by duplicating the styles right onto the layout page.

However at this github thread people are advising to do several things:

Include the files in your precompile list in config/initializers/assets.rb as described in the Asset pipeline usage section of the README.

Using stylesheet_link_tag wicked_pdf_asset_base64('pdf')

Body:
I am successfully loading CSS files in my PDF file using wicked_pdf gem helpers:

<%= wicked_pdf_stylesheet_link_tag "pdf" %>

This works great in development, however when i deploy in production the pdf CSS file is not correctly imported.  Also note that the file is "pdf.scss.erb" and not just "pdf.css".

I am not sure how to fix this problem. Looking at the server logs, i do not see any missed file warnings.


问:
Jquery hovers all elements
I am trying to implement jquery hover function into my div elements, so I have a div that firstly it is not shown , so i hide it with css, display:none and i am using jquery hover to show it, so this is my code

```<code>$('.fc-day-grid-event').hover(
  function() {
    $(".hidenDiv").css("display", "inline-block");
  },
  function() {
    $(".hidenDiv").css("display", "none");
  }
);
</code>```

but when i hover through the element , all elements with the class .fc-day-grid-event shows the hidden div , it should show the hidenDiv only in the element that i hover

答:
Use Context Selector or .find() to target the child of current fc-day-grid-event element

```<code>$('.fc-day-grid-event').hover(function () {
    $(".hidenDiv", this).css("display", "inline-block");
    //$(this).find(".hidenDiv").css("display", "inline-block");
}, function () {
    $(".hidenDiv", this).css("display", "none");
});
</code>```

Title: Jquery hovers all elements

Body:
I am trying to implement jquery hover function into my div elements, so I have a div that firstly it is not shown , so i hide it with css, display:none and i am using jquery hover to show it, so this is my code

$('.fc-day-grid-event').hover(
  function() {
    $(".hidenDiv").css("display", "inline-block");
  },
  function() {
    $(".hidenDiv").css("display", "none");
  }
);

but when i hover through the element , all elements with the class .fc-day-grid-event shows the hidden div , it should show the hidenDiv only in the element that i hover

Body:
Use Context Selector or .find() to target the child of current fc-day-grid-event element

$('.fc-day-grid-event').hover(function () {
    $(".hidenDiv", this).css("display", "inline-block");
    //$(this).find(".hidenDiv").css("display", "inline-block");
}, function () {
    $(".hidenDiv", this).css("display", "none");
});


问:
Configure mouse in tmux on OSX
It seems that mouse support changed in one of the recent versions of tmux and every article I am finding on the subject uses outdated settings. All I want to be able to do is use my mouse to scroll when in scroll mode and use it to copy/paste with the left button like it usually does in a terminal. Unfortunately, if I set set -g mouse on the copy/paste doesn't work and if I set it to off, scroll doesn't work. I am on OSX 10.12 Sierra if that makes a difference and I am using the default Terminal app.

答:
Using the set -g mouse on as specified above works to use the mouse for scrolling.

On Linux the shift button works to allow the normal mouse selection and copy/paste, but on Mac it seems to be the Alt button, give that a try (it works for me using tmux on iTerm2).

Title: Configure mouse in tmux on OSX


问:
Scroll to an element in a div
I would like my

```<code>div="#course_navigation"
</code>```

in my sidebar with this css:

```<code>.sidebar #course_navigation {
    max-height: 700px !important;
    overflow-y: auto !important;
    overflow-x: hidden !important;
}
</code>```

to scroll to this class on page load:

```<code>.learndash-current-menu-item
</code>```

I try this, but nothing happens:

```<code>$('#course_navigation').scrollTo('.learndash-current-menu-item');
</code>```

I have tried many other codes, with no success. Don't know the problem is.

The structure looks like this:

Maybe I was not specific enough, so I repeat:

```<code>#course_navigation
</code>```

is scrollable.

I need #course_navigation scrolled until .learndash-current-menu-item can be seen at the top or center of #course_navigation on page load.

I have this at field of Theme Space before /head:

```<code><script src="code.jquery.com/jquery-1.10.2.js"></script>;
</code>```

I put the script to Space before /body like this:

```<code><script>$('#course_navigation').scrollTo('.learndash-current-menu-item');</script>
</code>```

No succes yet, nothing happens, none of the solution works...

Please help me out here with JS or jquery. The best should be scroll the element to the center of the div.

Thank you in advance!

András

答:
This works for me.

$(window).scrollTop($('.learndash-current-menu-item').offset().top);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<div id="course_navigation">
Some text here <br/> Some text here <br/> Some text here <br/> Some text here <br/> Some text here <br/> Some text here <br/> Some text here <br/> Some text here <br/> Some text here <br/> Some text here <br/> Some text here <br/> Some text here <br/> Some text here <br/> Some text here <br/> Some text here <br/> Some text here <br/> Some text here <br/> Some text here <br/> Some text here <br/> Some text here <br/> Some text here <br/> Some text here <br/> Some text here <br/> Some text here <br/> Some text here <br/> Some text here <br/> Some text here <br/> Some text here <br/> Some text here <br/> Some text here <br/> Some text here <br/> Some text here <br/> Some text here <br/> Some text here <br/> Some text here <br/> Some text here <br/> Some text here <br/> Some text here <br/> Some text here <br/>
<div class="learndash-current-menu-item">
   <h1>Scrool to me</h1>
</div>
Some text here <br/> Some text here <br/>Some text here <br/> Some text here <br/>Some text here <br/> Some text here <br/>Some text here <br/> Some text here <br/>Some text here <br/> Some text here <br/>Some text here <br/> Some text here <br/>Some text here <br/> Some text here <br/>Some text here <br/> Some text here <br/>Some text here <br/> Some text here <br/>Some text here <br/> Some text here <br/>Some text here <br/> Some text here <br/>Some text here <br/> Some text here <br/>Some text here <br/> Some text here <br/>Some text here <br/> Some text here <br/>
</div>

</div></code>```

Title: Scroll to an element in a div

Body:
I would like my

div="#course_navigation"

in my sidebar with this css:

.sidebar #course_navigation {
    max-height: 700px !important;
    overflow-y: auto !important;
    overflow-x: hidden !important;
}

to scroll to this class on page load:

.learndash-current-menu-item

I try this, but nothing happens:

$('#course_navigation').scrollTo('.learndash-current-menu-item');

I have tried many other codes, with no success. Don't know the problem is.

The structure looks like this:

Maybe I was not specific enough, so I repeat:

#course_navigation

is scrollable.

I need #course_navigation scrolled until .learndash-current-menu-item can be seen at the top or center of #course_navigation on page load.

I have this at field of Theme Space before /head:

;

I put the script to Space before /body like this:

No succes yet, nothing happens, none of the solution works...

Please help me out here with JS or jquery. The best should be scroll the element to the center of the div.

Thank you in advance!

András

Body:
This works for me.

$(window).scrollTop($('.learndash-current-menu-item').offset().top);

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<div id="course_navigation">
Some text here <br/> Some text here <br/> Some text here <br/> Some text here <br/> Some text here <br/> Some text here <br/> Some text here <br/> Some text here <br/> Some text here <br/> Some text here <br/> Some text here <br/> Some text here <br/> Some text here <br/> Some text here <br/> Some text here <br/> Some text here <br/> Some text here <br/> Some text here <br/> Some text here <br/> Some text here <br/> Some text here <br/> Some text here <br/> Some text here <br/> Some text here <br/> Some text here <br/> Some text here <br/> Some text here <br/> Some text here <br/> Some text here <br/> Some text here <br/> Some text here <br/> Some text here <br/> Some text here <br/> Some text here <br/> Some text here <br/> Some text here <br/> Some text here <br/> Some text here <br/> Some text here <br/>
<div class="learndash-current-menu-item">
   <h1>Scrool to me</h1>
</div>
Some text here <br/> Some text here <br/>Some text here <br/> Some text here <br/>Some text here <br/> Some text here <br/>Some text here <br/> Some text here <br/>Some text here <br/> Some text here <br/>Some text here <br/> Some text here <br/>Some text here <br/> Some text here <br/>Some text here <br/> Some text here <br/>Some text here <br/> Some text here <br/>Some text here <br/> Some text here <br/>Some text here <br/> Some text here <br/>Some text here <br/> Some text here <br/>Some text here <br/> Some text here <br/>Some text here <br/> Some text here <br/>
</div>

</div>


问:
fold expression: right shift initialization behavior
I am having fun with the fold expressions to understand better where I will be able to use them in my projects. So I choose to initialize them with a simple

```<code>(datas = ... = 1);
</code>```

So far everything work as expected, every value is at 1. Then I tryed to use the left shift initialization so:

```<code>    (datas = ... = 1);
    (datas <<= ...);
</code>```

Here is also work as I expect it, it increase by a power of 2 it's nice.
And finally I tryed this:

```<code>(datas = ... = 1);
(datas >>= ...);
</code>```

And it give me as output a 0, 1, 0, 1, 0, 1, ..., I expected it would be all at 0. So here the code:

```<code>#include <iostream>

template<typename... T>
void test(T&&... datas) {
    (datas = ... = 1);
    (datas >>= ...);
    (std::cout << ... << (std::to_string(datas) + " ")) << std::endl;
}

int main(int argc, char const *argv[])
{
    int v1, v2, v3, v4;
    test(v1, v2, v3, v4);
    return 0;
}
</code>```

Why it is 0, 1, 0, 1 etc instead of 0, 0, 0, 0 ? I through for every argument it will do more something like that:
arg1 >>= arg2, arg2 >>= arg3, arg3 >>= arg4, etc
but it's true that then the last value should be 1 then so it could also be 0, 0, 0, 1.

答:
(datas >>= ...) is equivalent to d1 >>= (d2 >>= (d3 >>= d4));

proof:

```<code>#include <iostream>

template<typename...Ts>
void set(Ts&&... datas)
{
    (datas = ... = 1);
}

template<typename...Ts>
void print(Ts&&... datas)
{
    (std::cout << ... << (std::to_string(datas) + " ")) << std::endl;
}

template<typename... T>
void test(T&&... datas) {
    set(datas...);
    (datas >>= ...);
    print(datas...);
}

void test2(int& d1, int& d2, int& d3, int& d4)
{
    set(d1,d2,d3,d4);
    d1 >>= (d2 >>= (d3 >>= d4));
    print(d1,d2,d3,d4);
}

int main(int argc, char const *argv[])
{
    int v1, v2, v3, v4;
    test(v1, v2, v3, v4);
    test2(v1, v2, v3, v4);
    return 0;
}
</code>```

expected results:

```<code>0 1 0 1
0 1 0 1
</code>```

http://coliru.stacked-crooked.com/a/e0435451bcf8af70

Body:
I am having fun with the fold expressions to understand better where I will be able to use them in my projects. So I choose to initialize them with a simple

(datas = ... = 1);

So far everything work as expected, every value is at 1. Then I tryed to use the left shift initialization so:

    (datas = ... = 1);
    (datas <<= ...);

Here is also work as I expect it, it increase by a power of 2 it's nice.
And finally I tryed this:

(datas = ... = 1);
(datas >>= ...);

And it give me as output a 0, 1, 0, 1, 0, 1, ..., I expected it would be all at 0. So here the code:

#include <iostream>

template<typename... T>
void test(T&&... datas) {
    (datas = ... = 1);
    (datas >>= ...);
    (std::cout << ... << (std::to_string(datas) + " ")) << std::endl;
}

int main(int argc, char const *argv[])
{
    int v1, v2, v3, v4;
    test(v1, v2, v3, v4);
    return 0;
}

Why it is 0, 1, 0, 1 etc instead of 0, 0, 0, 0 ? I through for every argument it will do more something like that:
arg1 >>= arg2, arg2 >>= arg3, arg3 >>= arg4, etc
but it's true that then the last value should be 1 then so it could also be 0, 0, 0, 1.

Body:
(datas >>= ...) is equivalent to d1 >>= (d2 >>= (d3 >>= d4));

proof:

#include <iostream>

template<typename...Ts>
void set(Ts&&... datas)
{
    (datas = ... = 1);
}

template<typename...Ts>
void print(Ts&&... datas)
{
    (std::cout << ... << (std::to_string(datas) + " ")) << std::endl;
}

template<typename... T>
void test(T&&... datas) {
    set(datas...);
    (datas >>= ...);
    print(datas...);
}

void test2(int& d1, int& d2, int& d3, int& d4)
{
    set(d1,d2,d3,d4);
    d1 >>= (d2 >>= (d3 >>= d4));
    print(d1,d2,d3,d4);
}

int main(int argc, char const *argv[])
{
    int v1, v2, v3, v4;
    test(v1, v2, v3, v4);
    test2(v1, v2, v3, v4);
    return 0;
}

expected results:

0 1 0 1
0 1 0 1

http://coliru.stacked-crooked.com/a/e0435451bcf8af70


问:
Add something to a non-empty list in Scala
I have this:

```<code>private val vertexIdListPartitions: TrieMap[Long, List[Long]] = TrieMap.empty[Long,List[Long]]
</code>```

and i need to add something to the list of vertexIdListPartitions

if i write:

```<code>vertexIdListPartition.update(3,List(4,3))
</code>```

I overwrite what was in the list before

if the list already has something inside, how can I link this new list? or still add numbers to the list?

How do i concat what was there before with this new list?

答:
Here is one way how to do this in a 2-step way:

```<code>vertexIdListPartition.update(3,
  vertexIdListPartition.getOrElse(3, List()) ++ List(4,3)
</code>```

I could not find a better way to do it in one step, which would be better though.

The getOrElse makes sure that if nothing is in there we return an empty list, otherwise we get the list that is already in there.  Afterwards we append your new list to it.

Body:
I have this:

private val vertexIdListPartitions: TrieMap[Long, List[Long]] = TrieMap.empty[Long,List[Long]]

and i need to add something to the list of vertexIdListPartitions

if i write:

vertexIdListPartition.update(3,List(4,3))

I overwrite what was in the list before

if the list already has something inside, how can I link this new list? or still add numbers to the list?

How do i concat what was there before with this new list?

Body:
Here is one way how to do this in a 2-step way:

vertexIdListPartition.update(3,
  vertexIdListPartition.getOrElse(3, List()) ++ List(4,3)

I could not find a better way to do it in one step, which would be better though.

The getOrElse makes sure that if nothing is in there we return an empty list, otherwise we get the list that is already in there.  Afterwards we append your new list to it.


问:
How to copy unique individuals from a csv file into new files
I am very new to python so please bear with me. I have a csv file that looks like this:

.

I am trying to loop through the file and for every unique individual there are, create a new csv file and copy rows over. I was successful in doing this for one animal but I am having trouble creating the syntax for a more generic approach. Here is what I currently have:

```<code>import arcpy
import csv
from csv import DictReader

WS = arcpy.env.workspace = raw_input("Where if your workspace")
infile = raw_input("where is your file?")
outfile = raw_input("What is your outfile name?")
arcpy.env.overwriteOutput = True

with open(infile, "r") as csvFile, open(outfile, "w") as out, open("outfile2.csv", "w") as out2:
    reader = csv.DictReader(csvFile)
    writer = csv.writer(out)
    writer.writerow(reader.fieldnames)
    for row in reader:
         if row["Animal"] == "1":
            values = [row[field] for field in reader.fieldnames]
            writer.writerow(values)
</code>```

答:
To write each Animal into its own CSV file, you would need to open a different file for each type of animal. This could be done by using a dictionary to store the file object and csv writer object for each animal. At the end, this could then be used to close all the files correctly:

```<code>import csv

output_csvs = {}    # e.g. {'1' : [file_object, csv_object]}

with open('input.csv', 'rb') as f_input:
    csv_reader = csv.reader(f_input)
    header = next(csv_reader)

    for row in csv_reader:
        animal = row[0]

        if animal in output_csvs:
            output_csvs[animal][1].writerow(row)
        else:
            f_output = open('animal_{}.csv'.format(animal), 'wb')
            csv_output = csv.writer(f_output)
            output_csvs[animal] = [f_output, csv_output]
            csv_output.writerow(header)
            csv_output.writerow(row)

for csv_file, csv_writer in output_csvs.values():
    csv_file.close()
</code>```

This would give you a set of output CSV files named according to the animal, e.g. animal_1.csv

Alternatively, if the data is small enough to be read into memory, it could be sorted by animal and output one block at a time by making use of Python's itertools.groupby() function:

```<code>from itertools import groupby
import csv

with open('input.csv', 'rb') as f_input:
    csv_reader = csv.reader(f_input)
    header = next(csv_reader)

    for animal, group in groupby(sorted(csv_reader), lambda x: x[0]):
        with open('animal_{}.csv'.format(animal), 'wb') as f_output:
            csv_output = csv.writer(f_output)
            csv_output.writerow(header)
            csv_output.writerows(group)
</code>```

Using sorted() ensures that all animals of the same kind are grouped together. If this is already the case in the data, sorting is not needed.

To access these files you could use glob.glob():

```<code>import matplotlib.pyplot as plt
import glob

for animal_filename in glob.glob('animal_*.csv'):
    with open(animal_filename, 'rb') as f_input:
        csv_input = csv.reader(f_input)
        heading = next(csv_input)
        x, y = [], []

        for row in csv_input:
            x.append(int(row[1]))
            y.append(int(row[2]))

        fig, ax = plt.subplots()
        plt.title(animal_filename)
        ax.scatter(x, y)

plt.show()
</code>```

Body:
I am very new to python so please bear with me. I have a csv file that looks like this:

.

I am trying to loop through the file and for every unique individual there are, create a new csv file and copy rows over. I was successful in doing this for one animal but I am having trouble creating the syntax for a more generic approach. Here is what I currently have:

import arcpy
import csv
from csv import DictReader

WS = arcpy.env.workspace = raw_input("Where if your workspace")
infile = raw_input("where is your file?")
outfile = raw_input("What is your outfile name?")
arcpy.env.overwriteOutput = True

with open(infile, "r") as csvFile, open(outfile, "w") as out, open("outfile2.csv", "w") as out2:
    reader = csv.DictReader(csvFile)
    writer = csv.writer(out)
    writer.writerow(reader.fieldnames)
    for row in reader:
         if row["Animal"] == "1":
            values = [row[field] for field in reader.fieldnames]
            writer.writerow(values)

Body:
To write each Animal into its own CSV file, you would need to open a different file for each type of animal. This could be done by using a dictionary to store the file object and csv writer object for each animal. At the end, this could then be used to close all the files correctly:

import csv

output_csvs = {}    # e.g. {'1' : [file_object, csv_object]}

with open('input.csv', 'rb') as f_input:
    csv_reader = csv.reader(f_input)
    header = next(csv_reader)

    for row in csv_reader:
        animal = row[0]

        if animal in output_csvs:
            output_csvs[animal][1].writerow(row)
        else:
            f_output = open('animal_{}.csv'.format(animal), 'wb')
            csv_output = csv.writer(f_output)
            output_csvs[animal] = [f_output, csv_output]
            csv_output.writerow(header)
            csv_output.writerow(row)

for csv_file, csv_writer in output_csvs.values():
    csv_file.close()

This would give you a set of output CSV files named according to the animal, e.g. animal_1.csv

Alternatively, if the data is small enough to be read into memory, it could be sorted by animal and output one block at a time by making use of Python's itertools.groupby() function:

from itertools import groupby
import csv

with open('input.csv', 'rb') as f_input:
    csv_reader = csv.reader(f_input)
    header = next(csv_reader)

    for animal, group in groupby(sorted(csv_reader), lambda x: x[0]):
        with open('animal_{}.csv'.format(animal), 'wb') as f_output:
            csv_output = csv.writer(f_output)
            csv_output.writerow(header)
            csv_output.writerows(group)

Using sorted() ensures that all animals of the same kind are grouped together. If this is already the case in the data, sorting is not needed.

To access these files you could use glob.glob():

import matplotlib.pyplot as plt
import glob

for animal_filename in glob.glob('animal_*.csv'):
    with open(animal_filename, 'rb') as f_input:
        csv_input = csv.reader(f_input)
        heading = next(csv_input)
        x, y = [], []

        for row in csv_input:
            x.append(int(row[1]))
            y.append(int(row[2]))

        fig, ax = plt.subplots()
        plt.title(animal_filename)
        ax.scatter(x, y)

plt.show()


问:
How to start using composer in your project after installation on Windows 10?
I downloaded the Composer-Setup.exe and run to install Composer using the installer within few mouse clicks.

Opened terminal by typing in cmd. At the command prompt typed in Composer and saw all the information related to Composer which means I've installed Composer successfully on my Windows 10 machine.

I'm using XAMPP for development. So, C:\xampp\htdocs\ is my document root directory.

I created a new directory titled composer_demo in document root. The path of which is C:\xampp\htdocs\composer_demo

Now, I want to use composer in this directory. How should I use it?

I went through the documentation but it's not saying anything clearly whether I've to create the composer.json file manually inside the directory composer_demo or what?

Do I need to write the dependency package manually into composer.json file manually or what like?

```<code>{
    "require": {
        "monolog/monolog": "1.0.*"
    }
}
</code>```

I'm clueless. Please someone give me step-by-step instructions to use the composer inside my newly created directory composer_demo.

Thanks.

答:
It is just like you said, create a composer.json file on your composer_demo folder, be sure that it is not a text file with a hidden .txt ending. Open the shell inside the folder using shift + right click and selecting ‘Open Command window here’ and run

```<code>composer install
</code>```

This command tells Composer to install your dependencies, not Composer itself. It will search for a composer.json file and download every dependency you listed there into a vendor folder. Composer will generate a composer.lock file with the versions it downloaded so you don't have problems once the third party libraries update.

Body:
I downloaded the Composer-Setup.exe and run to install Composer using the installer within few mouse clicks.

Opened terminal by typing in cmd. At the command prompt typed in Composer and saw all the information related to Composer which means I've installed Composer successfully on my Windows 10 machine.

I'm using XAMPP for development. So, C:\xampp\htdocs\ is my document root directory.

I created a new directory titled composer_demo in document root. The path of which is C:\xampp\htdocs\composer_demo

Now, I want to use composer in this directory. How should I use it?

I went through the documentation but it's not saying anything clearly whether I've to create the composer.json file manually inside the directory composer_demo or what?

Do I need to write the dependency package manually into composer.json file manually or what like?

{
    "require": {
        "monolog/monolog": "1.0.*"
    }
}

I'm clueless. Please someone give me step-by-step instructions to use the composer inside my newly created directory composer_demo.

Thanks.

Body:
It is just like you said, create a composer.json file on your composer_demo folder, be sure that it is not a text file with a hidden .txt ending. Open the shell inside the folder using shift + right click and selecting ‘Open Command window here’ and run

composer install

This command tells Composer to install your dependencies, not Composer itself. It will search for a composer.json file and download every dependency you listed there into a vendor folder. Composer will generate a composer.lock file with the versions it downloaded so you don't have problems once the third party libraries update.


问:
what is the reason to have <header> <footer> tags in html5
why to use     tags in html5 even though we can achieve that functionality by html4  by adding css styles,
Other than every technology with latest version will have more flexibility or features. please help me to understand..</p>

答: As @panther wrote, the main reason is semantics. Also it's better for search engines to use html5. You can achieve a lot of tags using some css, for example adding display: inline to div will give you span etc


答: You can use the Geolocation.getCurrentPosition API available in all modern browsers. By using this you can get the user's location via the most optimal way for their device, i.e. via GPS or IP.</p>

Title: Get user's current location when they click on button

Body: I am building a web application based on users current location using javascript/jquery. How to get current location of user when he browse my application on all browsers?


问:
mp4 video uploaded from android not play on ios
We have an app that allows user to upload videos and images to server.
if i upload a mp4 video from android , it is not playing in ios devices.
this is my code. player status shows up readytoplay but it doesn't load up and no error comes up. vieo is playing fine with web and android.
 here is video url : https://justgolive.net/assets/uploads/newrecordings/20919/19777983355a28e15326df6.mp4</p>

```<code>  NSURL *streamURL = [NSURL URLWithString:_videoUrl];
    player = [AVPlayer playerWithURL:streamURL];

    AVPlayerLayer *playerLayer = [AVPlayerLayer playerLayerWithPlayer:player];
    playerLayer.frame =self.previewView.frame;
    playerLayer.videoGravity = AVLayerVideoGravityResizeAspectFill;
    //CGRectMake(0, 50, self.view.frame.size.width, self.view.frame.size.height/1.2);
    [self.previewView.layer addSublayer:playerLayer];

    // [self.playerContainer setUserInteractionEnabled:NO];   //to avoid touch events when activity is on
    [self.player addObserver:self forKeyPath:@"status" options:NSKeyValueObservingOptionInitial | NSKeyValueObservingOptionNew context:NULL];
    player.actionAtItemEnd = AVPlayerActionAtItemEndNone;

    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(playerItemDidReachEnd:)
                                                 name:AVPlayerItemDidPlayToEndTimeNotification
                                               object:[player currentItem]];
</code>```

答:
I have tried with your url of Video and working with below code:

header file like this:

```<code>#import <UIKit/UIKit.h>

@interface ViewController : UIViewController

@property (weak, nonatomic) IBOutlet UIView *playerView;

@end
</code>```

Implementation file like this:

```<code>#import "ViewController.h"
#import <AVFoundation/AVFoundation.h>

@interface ViewController ()
@property (nonatomic) AVPlayer *player;
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    NSURL *url = [NSURL URLWithString:@"https://justgolive.net/assets/uploads/newrecordings/20919/19777983355a28e15326df6.mp4"];

    AVPlayerItem *playerItem = [AVPlayerItem playerItemWithURL:url];

    self.player = [AVPlayer playerWithPlayerItem:playerItem];

    CALayer *superlayer = self.playerView.layer;
    self.player.volume = 20.0;

    AVPlayerLayer *playerLayer = [AVPlayerLayer playerLayerWithPlayer:self.player];
    [playerLayer setFrame:self.playerView.bounds];
    playerLayer.videoGravity = AVLayerVideoGravityResizeAspect;
    playerLayer.frame = self.playerView.layer.bounds;
    [superlayer addSublayer:playerLayer];
    [self.player seekToTime:kCMTimeZero];
    [self.player play];

}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
</code>```

Body:
We have an app that allows user to upload videos and images to server.
if i upload a mp4 video from android , it is not playing in ios devices.
this is my code. player status shows up readytoplay but it doesn't load up and no error comes up. vieo is playing fine with web and android.
 here is video url : https://justgolive.net/assets/uploads/newrecordings/20919/19777983355a28e15326df6.mp4

  NSURL *streamURL = [NSURL URLWithString:_videoUrl];
    player = [AVPlayer playerWithURL:streamURL];

    AVPlayerLayer *playerLayer = [AVPlayerLayer playerLayerWithPlayer:player];
    playerLayer.frame =self.previewView.frame;
    playerLayer.videoGravity = AVLayerVideoGravityResizeAspectFill;
    //CGRectMake(0, 50, self.view.frame.size.width, self.view.frame.size.height/1.2);
    [self.previewView.layer addSublayer:playerLayer];

    // [self.playerContainer setUserInteractionEnabled:NO];   //to avoid touch events when activity is on
    [self.player addObserver:self forKeyPath:@"status" options:NSKeyValueObservingOptionInitial | NSKeyValueObservingOptionNew context:NULL];
    player.actionAtItemEnd = AVPlayerActionAtItemEndNone;

    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(playerItemDidReachEnd:)
                                                 name:AVPlayerItemDidPlayToEndTimeNotification
                                               object:[player currentItem]];

Body:
I have tried with your url of Video and working with below code:

header file like this:

#import <UIKit/UIKit.h>

@interface ViewController : UIViewController

@property (weak, nonatomic) IBOutlet UIView *playerView;

@end

Implementation file like this:

#import "ViewController.h"
#import <AVFoundation/AVFoundation.h>

@interface ViewController ()
@property (nonatomic) AVPlayer *player;
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    NSURL *url = [NSURL URLWithString:@"https://justgolive.net/assets/uploads/newrecordings/20919/19777983355a28e15326df6.mp4"];

    AVPlayerItem *playerItem = [AVPlayerItem playerItemWithURL:url];

    self.player = [AVPlayer playerWithPlayerItem:playerItem];

    CALayer *superlayer = self.playerView.layer;
    self.player.volume = 20.0;

    AVPlayerLayer *playerLayer = [AVPlayerLayer playerLayerWithPlayer:self.player];
    [playerLayer setFrame:self.playerView.bounds];
    playerLayer.videoGravity = AVLayerVideoGravityResizeAspect;
    playerLayer.frame = self.playerView.layer.bounds;
    [superlayer addSublayer:playerLayer];
    [self.player seekToTime:kCMTimeZero];
    [self.player play];

}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end


问:
C# - How to invoke WCF callback calls from outside the service

I have a solution which runs as a service and communicates with another application via WCF.
Basically I added WCF service library and define the service contract as "CallbackContract"

```<code>[ServiceContract(CallbackContract = typeof(IKioskWcfCallback))]
public interface IKioskWcfService
{
    [OperationContract]
    void OpenSession();
}

public interface IKioskWcfCallback
{

    [OperationContract]
    void OnCallback();
}
</code>```

I launch the WCF service from the main project using the class ServiceHost

```<code>        Wcfservice = new ServiceHost(typeof(KioskWcf.KioskWcfService));
        Wcfservice.Open();
</code>```

From inside the WCF web service I can call the callback without any issue. I save the callback reference when the client connects and just invoke that callback later.

```<code>public class KioskWcfService : IKioskWcfService
{
    public static IKioskWcfCallback Callback;
    public static Timer Timer;

    public void OpenSession()
    {
        Console.WriteLine("> Session opened at {0}", DateTime.Now);
        Callback = OperationContext.Current.GetCallbackChannel<IKioskWcfCallback>();

        Timer = new Timer(3000);
        Timer.Elapsed += OnTimerElapsed;
        Timer.Enabled = true;
    }
    void OnTimerElapsed(object sender, System.Timers.ElapsedEventArgs e)
    {
        Callback.OnCallback();
    }
</code>```

Now, I would like to invoke the callback in some other part of my project but I dont know how to reference the callback of the connected client.

I saw in some answers that a method GetClients() exists but in my case VS 2015 does not offer that method.

Here my App.cfg

```<code>      <service name="KioskWcf.KioskWcfService">
    <endpoint address="" binding="wsDualHttpBinding" contract="KioskWcf.IKioskWcfService">
      <identity>
        <dns value="localhost" />
      </identity>
    </endpoint>
    <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" />
    <host>
      <baseAddresses>
        <add baseAddress="http://localhost:8090/KioskWcf/KioskWcfService/" />
      </baseAddresses>
    </host>
  </service>
</code>```

Many thanks.

答:
I would like to invoke the callback in some other part of my project

What you can do is ,in the client application or wherever you want to call this callback ,then you have to implement the callback's interface in the client application.

Suppose MyClient application is the client or other project where you want to consume or call the IKioskWcfCallback ,then

```<code>class MyClient :KioskNamespace.IKioskWcfCallback
{
  //control is returned from callback to here.
  public void OnCallback()
  {

  }
}
</code>```

Body:
I have a solution which runs as a service and communicates with another application via WCF.
Basically I added WCF service library and define the service contract as "CallbackContract"

[ServiceContract(CallbackContract = typeof(IKioskWcfCallback))]
public interface IKioskWcfService
{
    [OperationContract]
    void OpenSession();
}

public interface IKioskWcfCallback
{

    [OperationContract]
    void OnCallback();
}

I launch the WCF service from the main project using the class ServiceHost

        Wcfservice = new ServiceHost(typeof(KioskWcf.KioskWcfService));
        Wcfservice.Open();

From inside the WCF web service I can call the callback without any issue. I save the callback reference when the client connects and just invoke that callback later.

public class KioskWcfService : IKioskWcfService
{
    public static IKioskWcfCallback Callback;
    public static Timer Timer;

    public void OpenSession()
    {
        Console.WriteLine("> Session opened at {0}", DateTime.Now);
        Callback = OperationContext.Current.GetCallbackChannel<IKioskWcfCallback>();

        Timer = new Timer(3000);
        Timer.Elapsed += OnTimerElapsed;
        Timer.Enabled = true;
    }
    void OnTimerElapsed(object sender, System.Timers.ElapsedEventArgs e)
    {
        Callback.OnCallback();
    }

Now, I would like to invoke the callback in some other part of my project but I dont know how to reference the callback of the connected client.

I saw in some answers that a method GetClients() exists but in my case VS 2015 does not offer that method.

Here my App.cfg

      <service name="KioskWcf.KioskWcfService">
    <endpoint address="" binding="wsDualHttpBinding" contract="KioskWcf.IKioskWcfService">
      <identity>
        <dns value="localhost" />
      </identity>
    </endpoint>
    <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" />
    <host>
      <baseAddresses>
        <add baseAddress="http://localhost:8090/KioskWcf/KioskWcfService/" />
      </baseAddresses>
    </host>
  </service>

Many thanks.

Body:
I would like to invoke the callback in some other part of my project

What you can do is ,in the client application or wherever you want to call this callback ,then you have to implement the callback's interface in the client application.

Suppose MyClient application is the client or other project where you want to consume or call the IKioskWcfCallback ,then

class MyClient :KioskNamespace.IKioskWcfCallback
{
  //control is returned from callback to here.
  public void OnCallback()
  {

  }
}


问:
query.addListenerForSingleValueEvent won't run...?

i try to connect to firebase to get display_name and also profile_photo
for my post like instagram
like this one
example image
but when i run my app it says that i have nullPointerException on my variable
mUserAccountSettings cause my app won't run onDataChanged() or onDataCancelled()
function.

i already tried to get data from mUserAccountSettings for Profile class and actually it work perfectly but in ViewFragment class it won't work

it says :

E/AndroidRuntime: FATAL EXCEPTION: main
                    Process: com.example.jesslyn.foodylife, PID: 5655
                    java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String
  com.example.jesslyn.foodylife.FoodyLife.models.UserAccountSettings.getProfile_photo()'
  on a null object reference
                        at com.example.jesslyn.foodylife.FoodyLife.Utils.ViewPostFragment.setupWidgets(ViewPostFragment.java:156)
                        at com.example.jesslyn.foodylife.FoodyLife.Utils.ViewPostFragment.onCreateView(ViewPostFragment.java:117)
                        at android.support.v4.app.Fragment.performCreateView(Fragment.java:2192)
                        at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1299)
                        at android.support.v4.app.FragmentManagerImpl.moveFragmentToExpectedState(FragmentManager.java:1528)
                        at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1595)
                        at android.support.v4.app.BackStackRecord.executeOps(BackStackRecord.java:758)
                        at android.support.v4.app.FragmentManagerImpl.executeOps(FragmentManager.java:2363)
                        at android.support.v4.app.FragmentManagerImpl.executeOpsTogether(FragmentManager.java:2149)
                        at android.support.v4.app.FragmentManagerImpl.optimizeAndExecuteOps(FragmentManager.java:2103)
                        at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:2013)
                        at android.support.v4.app.FragmentManagerImpl$1.run(FragmentManager.java:710)
                        at android.os.Handler.handleCallback(Handler.java:742)
                        at android.os.Handler.dispatchMessage(Handler.java:95)
                        at android.os.Looper.loop(Looper.java:154)
                        at android.app.ActivityThread.main(ActivityThread.java:5544)
                        at java.lang.reflect.Method.invoke(Native Method)
                        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:739)
                        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:629)
  E/MQSEventManagerDelegate: failed to get MQSService.

and this is my code in ViewFragment class:

package com.example.jesslyn.foodylife.FoodyLife.Utils;

import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.text.LoginFilter;
import android.util.EventLogTags;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.RatingBar;
import android.widget.TextView;

import com.example.jesslyn.foodylife.FoodyLife.Utils.BottomNavigationViewHelper;
import com.example.jesslyn.foodylife.FoodyLife.Utils.FirebaseMethods;
import com.example.jesslyn.foodylife.FoodyLife.Utils.GridImageAdapter;
import com.example.jesslyn.foodylife.FoodyLife.Utils.SquareImageView;
import com.example.jesslyn.foodylife.FoodyLife.Utils.UniversalImageLoader;
import com.example.jesslyn.foodylife.FoodyLife.models.Photo;
import com.example.jesslyn.foodylife.FoodyLife.models.UserAccountSettings;
import com.example.jesslyn.foodylife.R;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.auth.GetTokenResult;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.Query;
import com.google.firebase.database.ValueEventListener;
import com.ittianyu.bottomnavigationviewex.BottomNavigationViewEx;

import junit.framework.Test;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;
import java.util.TimeZone;
import java.util.concurrent.Executor;

/**
 * Created by Jesslyn on 12/4/2017.
 */

public class ViewPostFragment extends Fragment {

    private static final String TAG = "ViewPostFragment";
    private SquareImageView mPostImage;
    private BottomNavigationViewEx bottomNavigationViewEx;
    private TextView mBackLabel, mCaption, mUsername, mTimeStamp;
    private ImageView mBackArrow, mEllipses, mProfileImage;
    private RatingBar mStars;
    private String photoUrl;

    private Photo mPhoto;
    private int mActivityNumber = 0;
    private String photoUsername = "";
    private String profilePhotoUrl = "";
    private UserAccountSettings mUserAccountSettings;

    // firebase
    private FirebaseAuth mAuth;
    private FirebaseAuth.AuthStateListener mAuthListener;
    private FirebaseDatabase mFirebaseDatabase;
    private DatabaseReference myRef;
    private FirebaseMethods mFirebaseMethods;
    private String userID;
    public ViewPostFragment() {
        super();
        setArguments(new Bundle());
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_view_post, container, false);
        mPostImage = (SquareImageView) view.findViewById(R.id.post_image);
        bottomNavigationViewEx = (BottomNavigationViewEx) view.findViewById(R.id.bottomNavViewBar);
        mBackArrow = (ImageView) view.findViewById(R.id.backArrow);
        mBackLabel = (TextView) view.findViewById(R.id.tvBackLabel);
        mCaption = (TextView) view.findViewById(R.id.image_caption);
        mUsername = (TextView) view.findViewById(R.id.username);
        mTimeStamp = (TextView) view.findViewById(R.id.image_time_posted);
        mEllipses = (ImageView) view.findViewById(R.id.iv_ellipses);
        mStars = (RatingBar) view.findViewById(R.id.ratingBar);

        mStars.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                RatingBar bar = (RatingBar) v;
                Log.d(TAG,"VALUE IS : "+bar.getRating()+"         **************************************************");
            }
        });
        mStars.setRating(0);
        mProfileImage = (ImageView) view.findViewById(R.id.profile_photo);

        try {
            mPhoto = getPhotoFromBundle();
            UniversalImageLoader.setImage(mPhoto.getImage_path(), mPostImage, null, "");
        } catch (NullPointerException e) {
            Log.e(TAG, "onCreateView NullPointerException : " + e.getMessage());
        }
        setupBottomNavigationView();
        setupFirebaseAuth();
        getPhotoDetails();
        setupWidgets();
        return view;
    }

    private void getPhotoDetails(){
        Log.d(TAG, "getPhotoDetails: retrieving photo details.");
        DatabaseReference reference = FirebaseDatabase.getInstance().getReference();
        Query query = reference
                .child(getString(R.string.dbname_user_account_settings))
                .orderByChild(getString(R.string.field_user_id))
                .equalTo(mPhoto.getUser_id());
        query.addListenerForSingleValueEvent(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                Log.d(TAG, "onDataChange: ");
                for ( DataSnapshot singleSnapshot :  dataSnapshot.getChildren()){
                    Log.d(TAG, "onDataChange: " +singleSnapshot.getValue().toString());
                    mUserAccountSettings = singleSnapshot.getValue(UserAccountSettings.class);
                    Log.d(TAG, "onDataChange: "+mUserAccountSettings.getUsername());

                }
                setupWidgets();
            }

            @Override
            public void onCancelled(DatabaseError databaseError) {
                Log.d(TAG, "onCancelled: query cancelled.");
            }
        });
    }

    private void setupWidgets(){
        String timestampDiff = getTimeStampDifference();
        if(!timestampDiff.equals("0")){
           mTimeStamp.setText(timestampDiff + " DAYS AGO");
        }else{
            mTimeStamp.setText("TODAY");
        }
       UniversalImageLoader.setImage(mUserAccountSettings.getProfile_photo(), mProfileImage, null, "");
       mUsername.setText(mUserAccountSettings.getUsername());
    }

    //get how many days ago of post
    private String getTimeStampDifference() {
        Log.d(TAG, "getTimeStampDifference : getting time difference");
        String difference = "";
        Calendar c = Calendar.getInstance();
        SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy'T'HH:mm:ss'Z'", Locale.ENGLISH);
        sdf.setTimeZone(TimeZone.getTimeZone("Asia/Jakarta"));
        Date timestamp;
        Date today = c.getTime();
        sdf.format(today);
        final String photoTimestamp = mPhoto.getDate_created();

        try {
            timestamp = sdf.parse(photoTimestamp);
            difference = String.valueOf(Math.round(((today.getTime() - timestamp.getTime()) / 1000 / 60 / 60 / 24)));
        } catch (ParseException e) {
            Log.e(TAG, "PARSE EXCEPTION : " + e.getMessage());
            difference = "0";
        }
        return difference;
    }

    private int getActivityFromBundle() {
        Log.d(TAG, "getActivityFromBundle arguments : " + getArguments());

        Bundle bundle = this.getArguments();
        if (bundle != null) {
            return bundle.getInt(getString(R.string.activity_number));
        } else {
            return 0;
        }
    }

    private Photo getPhotoFromBundle() {
        Log.d(TAG, "getPhotoFromBundle arguments : " + getArguments());

        Bundle bundle = this.getArguments();
        if (bundle != null) {
            return bundle.getParcelable(getString(R.string.photo));
        } else {
            return null;
        }
    }

    /**
     * BottomNavigationView setup
     */
    private void setupBottomNavigationView() {
        Log.d(TAG, "setupBottomNavigationView: setting up BottomNavigationView");
        BottomNavigationViewHelper.setupBottomNavigationView(bottomNavigationViewEx);
        BottomNavigationViewHelper.enableNavigation(getActivity(), getActivity(), bottomNavigationViewEx);
        Menu menu = bottomNavigationViewEx.getMenu();
        MenuItem menuItem = menu.getItem(mActivityNumber);
        menuItem.setChecked(true);
    }

    /**
     * ----------------------------------Firebase stuffs-----------------------------------------
     */

    //setup the firebase auth obj
    private void setupFirebaseAuth() {
        Log.d(TAG, "setupFirebaseAuth : setting up firebase auth");
        mAuth = FirebaseAuth.getInstance();
        mFirebaseDatabase = FirebaseDatabase.getInstance();
        myRef = mFirebaseDatabase.getReference();

        mAuthListener = new FirebaseAuth.AuthStateListener() {
            @Override
            public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
                FirebaseUser user = firebaseAuth.getCurrentUser();

                if (user != null) {
                    //user is signed in
                    Log.d(TAG, "user is signed in" + user.getUid());
                } else {
                    //user is signed out
                    Log.d(TAG, "onAuthStateChanged : signed out");
                }
            }
        };
    }

    @Override
    public void onStart() {
        super.onStart();
        mAuth.addAuthStateListener(mAuthListener);

    }

    @Override
    public void onStop() {
        super.onStop();
        if (mAuthListener != null) {
            mAuth.removeAuthStateListener(mAuthListener);
        }
    }
}```

答:
It is because the variable mUserAccountSettings is initialized in onDataChange() method which is a callback and is executed async. Before this it initialized your main thread is trying to access that in setupWidgets()

A possible fix would be to move the below code from setupWidgets() to onDataChange().

```<code> UniversalImageLoader.setImage(mUserAccountSettings.getProfile_photo(), mProfileImage, null, "");
</code>```

NOTE: this is not intend to show you any best practice. This solution is just to show that all UI updates which depends on value from server, should happen ones you get the response from server.

Body:
It is because the variable mUserAccountSettings is initialized in onDataChange() method which is a callback and is executed async. Before this it initialized your main thread is trying to access that in setupWidgets()

A possible fix would be to move the below code from setupWidgets() to onDataChange().

 UniversalImageLoader.setImage(mUserAccountSettings.getProfile_photo(), mProfileImage, null, "");

NOTE: this is not intend to show you any best practice. This solution is just to show that all UI updates which depends on value from server, should happen ones you get the response from server.


问:
Importing sqldump into docker-container
I am trying to import a sqldump into a running MySQL Docker-Container with this command:

```<code> sudo docker exec -i a2bdd4db352a /usr/bin/mysql -u username -ppassword --max_allowed_packet=1500M --default-character-set=utf8 database < /srv/Dump.sql
</code>```

After a while getting these error:

```<code>ERROR 2006 (HY000) at line 979: MySQL server has gone away
read unix @->/var/run/docker.sock: read: connection reset by peer
</code>```

Logs:

```<code>2017-12-07T09:44:21.099302Z 3 [Note] Aborted connection 3 to db: 'database' user: 'database' host: 'localhost' (Got a packet bigger than 'max_allowed_packet' bytes)
</code>```

Tried to increase the max_allowed_package variable in my MySQL-Conf ---> Nothing changed - still the same error.

My Dump has a size of 16 GB.

Has anybody a idea - how to fix this?

答: Do you have tried to increase the paramater --max_allowed_packet=1500M to --max_allowed_packet=200000M ?

Title: Importing sqldump into docker-container

Body:
I am trying to import a sqldump into a running MySQL Docker-Container with this command:

 sudo docker exec -i a2bdd4db352a /usr/bin/mysql -u username -ppassword --max_allowed_packet=1500M --default-character-set=utf8 database < /srv/Dump.sql

After a while getting these error:

ERROR 2006 (HY000) at line 979: MySQL server has gone away
read unix @->/var/run/docker.sock: read: connection reset by peer

Logs:

2017-12-07T09:44:21.099302Z 3 [Note] Aborted connection 3 to db: 'database' user: 'database' host: 'localhost' (Got a packet bigger than 'max_allowed_packet' bytes)

Tried to increase the max_allowed_package variable in my MySQL-Conf ---> Nothing changed - still the same error.

My Dump has a size of 16 GB.

Has anybody a idea - how to fix this?


问:
css input corner triangle label with border radius
I would like to create an triangle label inside input (text) element exactly like this:

What I managed to do so far is this:

How can I put this triangle "under" the input border to, let's just say, keep border radius from input cutting the edge of this triangle?

This is my code:

```<code><div class="input">
   <label>email adress</label>
   <div class="note">
      <p>*</p>
      <input type="text" placeholder="Enter your email adress">
   </div>
</div>

.input {
   display: flex;
   flex-direction: column;
   width: 100%;
}
.note > input {
   width: 515px;
   height: 48px;
   border-radius: 5px;
   border: 1px solid #7d7d7d;
   box-shadow:inset 0 0 5px 1px lightgray;
   padding-left: 20px;
   color: #acacac;
   -webkit-color: #acacac;
   -moz-color: #acacac;
   -ms-color: #acacac;
   -o-color: #acacac;
   font-size: 16px;
   background-color: rgba(211, 211, 211, 0.50);
}

.note > input:focus {
   outline: none;
   background-color: #f9f9f9;
}

.note {
   position: relative;
   display: inline-block;
}
.note:after {
   content: "";
   position: absolute;
   top: 0;
   right: 0;
   width: 0;
   height: 0;
   display: block;
   border-left: 35px solid transparent;
   border-bottom: 35px solid transparent;
   border-top: 35px solid #0094bb;
}
</code>```

I imagine there is no way to give border-radius to this triangle itself without losing its shape, am I right?

答:
The closest i could get with your solution. But I found other ways you're satisfied with this okay...

.note > input {
   width: 515px;
   height: 48px;
   border-radius: 5px;
   border: 1px solid #7d7d7d;
   box-shadow:inset 0 0 5px 1px lightgray;
   padding-left: 20px;
   color: #acacac;
   -webkit-color: #acacac;
   -moz-color: #acacac;
   -ms-color: #acacac;
   -o-color: #acacac;
   font-size: 16px;
   background-color: rgba(211, 211, 211, 0.50);
}

.note > input:focus {
   outline: none;
   background-color: #f9f9f9;
}

.note {
   position: relative;
   display: inline-block;
}
.note:after {
   content: "";
   position: absolute;
   top: 0;
   right: 0;
   width: 0;
   height: 0;
   display: block;
   line-height: 48px;
   text-align: top;
   border-left: 35px solid transparent;
   border-bottom: 35px solid transparent;
   border-top: 35px solid #0094bb;
}
.note::before {
   content: "*";
   position: absolute;
   right: 7px;
   z-index: 1;
   top: 5px;
   color: white;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="input">
   <label>email adress</label>
   <div class="note">
      <input type="text" placeholder="Enter your email adress">
   </div>
</div></code>```

Body:
I would like to create an triangle label inside input (text) element exactly like this:

What I managed to do so far is this:

How can I put this triangle "under" the input border to, let's just say, keep border radius from input cutting the edge of this triangle?

This is my code:

   email adress

*

      <input type="text" placeholder="Enter your email adress">

.input {
   display: flex;
   flex-direction: column;
   width: 100%;
}
.note > input {
   width: 515px;
   height: 48px;
   border-radius: 5px;
   border: 1px solid #7d7d7d;
   box-shadow:inset 0 0 5px 1px lightgray;
   padding-left: 20px;
   color: #acacac;
   -webkit-color: #acacac;
   -moz-color: #acacac;
   -ms-color: #acacac;
   -o-color: #acacac;
   font-size: 16px;
   background-color: rgba(211, 211, 211, 0.50);
}

.note > input:focus {
   outline: none;
   background-color: #f9f9f9;
}

.note {
   position: relative;
   display: inline-block;
}
.note:after {
   content: "";
   position: absolute;
   top: 0;
   right: 0;
   width: 0;
   height: 0;
   display: block;
   border-left: 35px solid transparent;
   border-bottom: 35px solid transparent;
   border-top: 35px solid #0094bb;
}

I imagine there is no way to give border-radius to this triangle itself without losing its shape, am I right?

Body:
The closest i could get with your solution. But I found other ways you're satisfied with this okay...

.note > input {
   width: 515px;
   height: 48px;
   border-radius: 5px;
   border: 1px solid #7d7d7d;
   box-shadow:inset 0 0 5px 1px lightgray;
   padding-left: 20px;
   color: #acacac;
   -webkit-color: #acacac;
   -moz-color: #acacac;
   -ms-color: #acacac;
   -o-color: #acacac;
   font-size: 16px;
   background-color: rgba(211, 211, 211, 0.50);
}

.note > input:focus {
   outline: none;
   background-color: #f9f9f9;
}

.note {
   position: relative;
   display: inline-block;
}
.note:after {
   content: "";
   position: absolute;
   top: 0;
   right: 0;
   width: 0;
   height: 0;
   display: block;
   line-height: 48px;
   text-align: top;
   border-left: 35px solid transparent;
   border-bottom: 35px solid transparent;
   border-top: 35px solid #0094bb;
}
.note::before {
   content: "*";
   position: absolute;
   right: 7px;
   z-index: 1;
   top: 5px;
   color: white;
}

<div class="input">
   <label>email adress</label>
   <div class="note">
      <input type="text" placeholder="Enter your email adress">
   </div>
</div>


问:
Check if variable is defined javascript
I am working in php and have a javascript file linked with 2 controllers. Now for one controller I declared a variable that is used by it. But when the second controller goes through it since there is no definition or declaration for it in that controller I get an error that the variable is not defined. I tried using the following statement in javascript to check for its existence or declaration/definition but still got the error. Secondly is this a good practice of using one javascript file for both the controllers?
Statements I have tried so far:</p>

```<code>if(variable){}

if(variable === null){}
</code>```

答:
Use typeof

```<code>if(typeof variable === "undefined"){
  /* It is undefined */
}
</code>```

Title: Check if variable is defined javascript

Body:
I am working in php and have a javascript file linked with 2 controllers. Now for one controller I declared a variable that is used by it. But when the second controller goes through it since there is no definition or declaration for it in that controller I get an error that the variable is not defined. I tried using the following statement in javascript to check for its existence or declaration/definition but still got the error. Secondly is this a good practice of using one javascript file for both the controllers?
Statements I have tried so far:

if(variable){}

if(variable === null){}

Body:
Use typeof

if(typeof variable === "undefined"){
  /* It is undefined */
}


问:
Facebook Tab App dynamic URL
I'm making a facebook tab app that will contain a widget for our main ASP MVC app.
Each user in our real app has a public profile like this: domain.com/widget/{profile_url} that is suppose to be shown in the tab. So that means that each page tab a user installs needs a unique page tab url which is something facebook page tabs dont seem to support.

I've been searching but cant find a clear answer, how to get dynamic url data I control inside my facebook tab app?

So my idea is that when the user is adding the tab app a parameter would get passed containing our apps profile url, and later when displaying the tab that parameter would get passed every time. our app would read the parameter and display the correct profile

答:
```<code><%@ page import ="java.io.*,java.util.*" %> <%@ page import = "java.util.Arrays,javax.crypto.Mac,javax.crypto.SecretKey,javax.crypto.spec.SecretKeySpec" %> <%@ page import = "org.json.simple.parser.*,org.apache.commons.codec.binary.Base64" %> <%@ page import = "java.io.UnsupportedEncodingException,javax.xml.bind.DatatypeConverter" %> <%

if (request.getParameter("signed_request") != null) {
    String input  =  request.getParameter("signed_request");
    //input ="q3v8X8hbmkKXaF_DZaLBPapMPVjMgpq8bZe-SmYc6Fs.eyJhbGdvcml0aG0iOiJITUFDLVNIQTI1NiIsImlzc3VlZF9hdCI6MTUxMjYyOTY5MiwicGFnZSI6eyJpZCI6IjEzOTg4MTM1MDM3NTUyMzEiLCJhZG1pbiI6dHJ1ZSwibGlrZWQiOnRydWV9LCJ1c2VyIjp7ImNvdW50cnkiOiJpbiIsImxvY2FsZSI6ImVuX0dCIiwiYWdlIjp7Im1pbiI6MjF9fX0";
    String secretKey = "d8e6e697b9c958a8ee8f2e";
    int max_age = 3600;
    try
    {
        String[] split = input.split("[.]", 2);
        String encoded_sig = split[0];
        String encoded_envelope = split[1];
        JSONParser parser = new JSONParser();
        // check
        //out.println("<br>"+ new String(new Base64(true).decode(encoded_envelope)));
        Map envelope = (Map) parser.parse(new String(new Base64(true).decode(encoded_envelope)));
        String algorithm = (String) envelope.get("algorithm");
        if (!algorithm.equals("HMAC-SHA256")) {
            throw new Exception("Invalid request. (Unsupported algorithm.)");
        }
        if (((Long) envelope.get("issued_at")) < System.currentTimeMillis() / 1000 - max_age) {
            throw new Exception("Invalid request. (Too old.)");
        }
        byte[] key = secretKey.getBytes();
        SecretKey hmacKey = new SecretKeySpec(key, "HMACSHA256");
        Mac mac = Mac.getInstance("HMACSHA256");
        mac.init(hmacKey);
        byte[] digest = mac.doFinal(encoded_envelope.getBytes());
        if (!Arrays.equals( new Base64(true).decode(encoded_sig), digest)) {
            throw new Exception("Invalid request. (Invalid signature.)");
        }
        String pageId = ((Map)envelope.get("page")).get("id").toString();
        if(pageId.equals("1398813503755231")){
            response.sendRedirect("https://yourdomain.com/1111");
        }
        else if(pageId.equals("151433128812548")){
            response.sendRedirect("https://yourdomain1.com/2222");
        }  }
    catch(Exception e)
    {
        out.println("error"+e);
    } } %> <html> <head> Facebook Store <script> var appId = 'your app id'; var pageId=''; window.fbAsyncInit = function() {
    FB.init({
      appId            : appId,
      autoLogAppEvents : true,
      xfbml            : true,
      version          : 'v2.11'
    });   };   (function(d, s, id){
     var js, fjs = d.getElementsByTagName(s)[0];
     if (d.getElementById(id)) {return;}
     js = d.createElement(s); js.id = id;
     js.src = "https://connect.facebook.net/en_US/sdk.js";
     fjs.parentNode.insertBefore(js, fjs);    }(document, 'script', 'facebook-jssdk')); function createPageTab(){
    FB.ui(
        {
            method: 'pagetab',
            redirect_uri:'https://9d5b71a7.ngrok.io/facebook-store.jsp'
        },
        function(response) {
            console.log(JSON.stringify(response));
            if (response != null && response.tabs_added != null) {
                for( pageid in  response.tabs_added){
                      pageId = pageid;
                }
            }
        }
    ); }

function viewPageTab(){
    var url = 'https://facebook.com/pages/-/'+pageId+'?sk=app_'+appId;
    window.open(url,'_blank'); }

</script> </head> <body>
    <button onClick="createPageTab()" >Connect your store with facebook </button>
    <button onClick="viewPageTab();" > View your Store </button> </body> </html>
</code>```

Title: Facebook Tab App dynamic URL


问:
java.lang.IllegalStateException: Fragment not attached to Activity
I am rarely getting this error while making an API call.

```<code>java.lang.IllegalStateException: Fragment  not attached to Activity
</code>```

I tried putting the code inside isAdded() method to check whether  fragment is currently added to its activity but still i rarely gets this error. I fail to understand why I am still getting this error. How can i prevent it?

Its showing error on the line-

```<code>cameraInfo.setId(getResources().getString(R.string.camera_id));
</code>```

Below is the sample api call that i am making.

```<code>SAPI.getInfo(getActivity(),
                new APIResponseListener() {
                    @Override
                    public void onResponse(Object response) {

                        cameraInfo = new SInfo();
                        if(isAdded()) {
                            cameraInfo.setId(getResources().getString(R.string.camera_id));
                            cameraInfo.setName(getResources().getString(R.string.camera_name));
                            cameraInfo.setColor(getResources().getString(R.string.camera_color));
                            cameraInfo.setEnabled(true);
                        }

                    }

                    @Override
                    public void onError(VolleyError error) {
                        mProgressDialog.setVisibility(View.GONE);
                        if (error instanceof NoConnectionError) {
                            String errormsg = getResources().getString(R.string.no_internet_error_msg);
                            Toast.makeText(getActivity(), errormsg, Toast.LENGTH_LONG).show();
                        }
                    }
                });
</code>```

答: Sometimes this exception is caused by a bug in the support library implementation. Recently I had to downgrade from 26.1.0 to 25.4.0 to get rid of it.</p>

Body:
I am rarely getting this error while making an API call.

java.lang.IllegalStateException: Fragment  not attached to Activity

I tried putting the code inside isAdded() method to check whether  fragment is currently added to its activity but still i rarely gets this error. I fail to understand why I am still getting this error. How can i prevent it?

Its showing error on the line-

cameraInfo.setId(getResources().getString(R.string.camera_id));

Below is the sample api call that i am making.

SAPI.getInfo(getActivity(),
                new APIResponseListener() {
                    @Override
                    public void onResponse(Object response) {

                        cameraInfo = new SInfo();
                        if(isAdded()) {
                            cameraInfo.setId(getResources().getString(R.string.camera_id));
                            cameraInfo.setName(getResources().getString(R.string.camera_name));
                            cameraInfo.setColor(getResources().getString(R.string.camera_color));
                            cameraInfo.setEnabled(true);
                        }

                    }

                    @Override
                    public void onError(VolleyError error) {
                        mProgressDialog.setVisibility(View.GONE);
                        if (error instanceof NoConnectionError) {
                            String errormsg = getResources().getString(R.string.no_internet_error_msg);
                            Toast.makeText(getActivity(), errormsg, Toast.LENGTH_LONG).show();
                        }
                    }
                });