How to always show the page browser in tt_news?

Question: Is there a way to always show the page browser, regardless of the set limit?
Answer: No built-in switch for this I suppose. Maybe you can place a generic marker to your template which is always replaced with a browsebox:
In the template:

###MYPAGEBROWSER###

In tt_news setup:
plugin.tt_news {
     genericmarkers {
         MYPAGEBROWSER < plugin.tt_news.pageBrowser
         MYPAGEBROWSER {
               (some config goes here)
         }
     }
}


Weird picture Distortions

Question: For some reason even after I updated the graphic drivers. I still get this weird picture on  every video or moving advertisement. It's a purple-green pixel texture that's almost impossible to recognize what the original picture looked like (not enough rep so I cant post an example). I've tried installing and updating the drivers, and it's still the same picture. I'm currently using a Toshiba Satellite A45-S150, Lubuntu 13.04. Is there a problem with the specific chipset, or is there a driver that I'm missing
Answer: gremlins?

try another browser and see if they still appear
reinstall your current browser.
toggle the hardware acceleration setting.
be careful if you have liquids around

have a good one.
Comment: Hey this is really late but thanks for the answer, unfortunately my laptops AC power cord and battery have died on me so I cannot use it any more due to no parts for it being sold any more (early 2000's laptop).

Weird picture Distortions


How do I know if my site is not using material design?

Question: I checked on google's design site, but couldn't find a comprehensive spec on this. There are only goals, principals and guidelines. In fact, in most websites I had searched there are only do's of material design, there are no don'ts.
That got me thinking about

how do I know what is missing from my site for it be certified as an app on material design?
how do I know that my app is not already on material design?

Someone told me that UX team these days put material design as their top priority and mandate that all websites should be on material design before it even come for review to them. So, I want to understand clearly when is an app not on material design.
Comment: ux teams most definitely do NOT make material design a priority. It's an option, but not in anyway better or worse than a multitude of other options. As for 'material design certification' I don't know who would do that or what value that would even bring to the users of your site.
Comment: thanks @DA01. I am not looking for an external certification rather want to understand 'don'ts of material design' myself.
Comment: Please leave a comment/reason for downvotes.
Comment: I didn't downvote, but it look like people are thinking this is just too broad. I tend to agree. There really aren't a list of "don'ts" for Material Design. It's just a set of guidelines that you should be free to use as you see fit.
Comment: @DA01 In that case `There are no specs and don'ts of material design` is also an acceptable reply. But how do I know that my app is already not on material design. And if not, then what is missing from it? I don't think this is too broad a question. Someone who knows material design should also know what is not a material design, and should be able to tell why. If it is too broad, can you help me in making it less broad? Thanks
Comment: From a UX perspective, I'd ask "why does it matter?". From a technical perspective, there is no officiating body to grant your app any sort of official material design status. Whether an app is considered 'material design' is going to be as much about subjective opinions as it is objective.
Comment: @DA01 I don't know if it matters at all for UX point of view. But UX teams are pushing for it and they are going to certify the apps as 'okay' for user, so I would like to know about more it before blindly following them.
Comment: In that case, you need to ask this question to the UX team you are working with, as the only answer that will matter is theirs if they are the ones 'certifying' it.
Comment: @DA01 off course I will, but I also want to know what experts on this site think about it as well.
Comment: Let us [continue this discussion in chat](http://chat.stackexchange.com/rooms/33557/discussion-between-da01-and-gurvinder372).
Answer: This question is a bit hard to answer. I actually don't know if there is certification on material design, if you can share this information, that will be great.
I had chance yo attended google launchpad day couple weeks ago, this is what I takeaway;
Material design is a "paper" foundation with make sense motions. It should act as paper as in physical world. Ex: if you take 2 piece of papers and lay one to the other, you should see very lightly shadow and the depth should calculate as such, if you increase the distance between 2 papers.  Since its paper concept, you should expect lots of negative spaces.
Motion is whats fun in material design, motion should make sense too, a btn trigger to enlarge a window from right hand bottom then when the window is set to close, it should shirk down the way it get enlarge but reversely.
You should check google codeslab.io , they have some solid resource to let u play with material design, else read google design guide inside out like me. :)
Hope these help.
Comment: Thanks Chia_tea, appreciate your inputs. But I think I will have to close this question since it is perceived as too broad by experts on this site.
Comment: Fair enough and I agree as well.
Answer: This blog by dreamweaver team suggest that difference between material design and flat design (older approach) is the introduction of z-axis.

Material design may be aesthetically flat, specifically the colors,
  but it is multi-dimensional: it takes the Z-axis into consideration.

Also as per google's guidelines a material is always suppose to have a uniform thickness of 1dp

Material has varying x & y dimensions (measured in dp) and a uniform
  thickness (1dp).
Promotes motion in design … which means that you have to implement it
  in order to make your creation true material design.

Interaction with material should be registered and trigger a subtle change in the state of material such as pressing of button, focus on a textbox, etc. So, if your button doesn't changes its state on being pressed then you are probably still on the earlier flat design approach.
As per a quote on wikipedia page by Martias Duarte (Google's Director of Android User Experience),

Material has physical surfaces and edges. Seams and shadows provide
  meaning about what you can touch.

Google implemented material design in gmail app by removing unnecessary borders and lines (some of them are reduced only to a portion of the screen), and there is less information shown to make it cleaner.


If I visit a friends island to invite his villager to live with me, will my friend lose that villager?

Question: To clarify, this is about Animal Crossing: New Horizon.
So I am looking for some specific villagers to inhabit my deserted island. So I thought I could just invite them from someone else who already has those villagers.
Now my friends are all afraid that if that villager moved in with me, they would lose him or her. But inviting someone to my campsite should not at the same time lead to them moving away from my friends' island.
Otherwise, the connection between our switches would have to be maintained for as long as my friend has not talked to the villagers about their plans to move out yet.
So my questions are:

Will the villagers move out of their homes at my friends island, if I invite them to live with me on my island?
Is it even possible to invite them by visiting a friend on their island?

When I remember correctly in New Leaf it was possible to invite villagers this way, but I couldn't find anything about how it is in New Horizon.
I kinda expect them to visit my camping ground the day after talking to them.
Comment: In my case I have 5 residents already and I can invite the next person visiting my camping grounds.
But theoretically I could do the same thing as well if I talk to the villager the same day someone else get kicked out of my town, so that the move out day and the visit to my camping grounds will overlap.
Answer: In New Horizons, the only way to swap villagers between islands works as follows.
Let's use Julian as an example, who lives on the island of Alfa. In order for Julian to move to Beta, the following must happen, in order.
Day 1

The Alfa player encounters Julian with thought bubbles above his head. When talked to, he admits that he's thinking about moving out. Alfa's player can encourage him to stay, or to follow his dreams and move out.

Day 2

If convinced to move out, Julian will be in "packing" mode the next day. (All furniture converted to cardboard boxes). This is colloquially known in the community as being "in boxes".
The Beta player visits Alfa via Online or Local play, talks to Julian, and suggests Julian move to Beta. (This requires an empty plot)

Day 3

Julian is no longer present on Alfa, and a Julian is moving in on Beta.

Conclusion
It is possible to get friends' villagers to move to your island, but only if your friend encourages them to leave first! But at the same time, it doesn't seem possible to "duplicate" villagers in this way -- they follow a strict "one-out, one-in" policy.
Comment: For (3), assuming that this is the exact same mechanic as for characters on Nook Miles isles (which seems a reasonable assumption), they get added to the queue of new villagers (which gets popped whenever a house is built on your island). So it will take at least one day (because a house only get populated on the day switch), but can take more (if you didn't have houses available yet).
Comment: That's too bad to hear, but good to know. Thanks alot!
Answer:
Will the villagers move out of their homes at my friends island, if I invite them to live with me on my island?

No. You can only invite a resident from a friend's island if that resident is already packing to move out AND you have a vacancy. You can have someone in the process of moving out, that counts as a vacancy.

Is it even possible to invite them by visiting a friend on their island?

Yes! Buy only if the friend has already given them leave to...er...leave.
Conditions for inviting a friend's villagers
You: Have a vacancy or a resident packed up and moving out.
If you are full, the resident will try calling Resident Services and tell you that there's no room.
Friend: Must have the resident moving out.
You can only attempt to invite residents that are moving out. There's never a dialog option to ask villagers in a regular state or who are moving in to move to your island. You cannot steal your friend's residents.
The timing can be tricky. Your vacancy needs to line up with a friend's resident moving out.
Tom Nook seems to fill vacancies after a day of a house plot being empty. If this happens, you get no say in who arrives. Which means you can't safely leave a house empty until your choice is ready to move, even if you and a friend are in agreement.
Campsite visitors are the only (current) way* to attempt to get a new resident without having a vacancy. You have no control over when campsite visitors show up (game text implies a higher rating means more visitors, but I haven't noticed much difference between 2 and 5 stars). Pressing a campsite visitor to move will trigger a Resident Services call, but this time a random resident will be selected as "considering" moving out. You can choose to accept the choice or not.
Weirdly, if you decline, it appears to trigger another resident to "think" about moving. Later that same day (or possibly the next) you will be able to see a resident with thought bubbles, asking you if they should move or stay. Which is to say, if you have a campsite visitor, you can convince them to call RS and then tell them no in order to have a good chance to get a vacancy within 2 days.
If you have a friend's cooperation, you can try to line things up. Unfortunately, the timing and randomness involved makes it very unlikely to get your choice in even a small number of attempts.
*Except for having a character's amiibo.


Where are all the purple eridium totems?

Question: As mentioned in this question, I've been finding eridium totems while playing through Sir Hammerlock's Big Game Hunt. By now I believe we've found 4 totems and dumped nearly 100 eridium into them, but there seem to be more to go.
Where are all the eridium totems located? Map(s) are ideal.
Answer: This link contains maps to all of the Eridium Totems:
http://orcz.com/Borderlands_2:_Dexiduous_Eridium_Totem_Furnace
There's four of them, all in Hunter's Grotto. Image from http://orcz.com reproduced here:


Get all records that "own" all of these other records

Question: I have a Recipe model that has_many Ingredients through RecipeIngredients:
  has_many :recipe_ingredients
  has_many :ingredients, through: :recipe_ingredients

RecipeIngredient model with recipe_id and ingredient_id columns.:
  belongs_to :recipe
  belongs_to :ingredient

My question is, how do I get all recipes that have all of a number of specific ingredients?

Attempt:
Recipe model:
scope :by_ingredient, -> ing { includes(:recipe_ingredients).where(recipe_ingredients: {ingredient_id: ing.id})}

When I do Recipe.by_ingredient(apple) it correctly returns all recipes that have apples and Recipe.by_ingredient(orange) correctly returns all recipes that have oranges.
But when I chain the scope like so: Recipe.by_ingredient(apple).by_ingredient(orange), it returns an empty array even though there are recipes that have apples AND oranges.
Comment: In `Recipe.by_ingredient(apple).by_ingredient(oranges)` is oranges a single object or a collection?
Comment: And does `Recipe.by_ingredient(oranges)` also return an empty array?
Comment: @AnthonyE Sorry, I meant to say `Recipe.by_ingredient(apple).by_ingredient(orange)`. Also, `Recipe.by_ingredient(orange)` does successfully return all recipes that have oranges.
Answer: Ok, so after hours of searching I found the method merge:
Recipe.by_ingredient(apple).merge(Recipe.by_ingredient(orange))

which successfully returns all recipes that have apples and oranges.


Touchpad gestures to change workspace

Question: I was talking to a friend who owns a Mac. He has his set up so that when he swipes three fingers across his touchpad, it moves to the workspace in that direction. Is it possible to set this up in Ubuntu?
Comment: I can't personally vouch for whether this method works, but there is a program called `EasyStroke` that may do what you're looking for. See [here](http://ubuntuforums.org/showthread.php?t=1859936) for setup instructions.
Comment: https://github.com/arunhedcet/mac-gestures
Answer: How to change workspaces using touchpad gestures in ubuntu
Complete tutorial using touchegg, easystroke is better to be used with mouse rather than touchpad.
In case you are using unity you may experience some conflicts with build-in gestures. The tutorial I gained information from deals with this issue (please see the link below). I didn't have any build in gestures, so this how-to provides only information how to set up things.

Download Touchegg:
sudo apt install touchegg

run it, but kill just after that, it will create a file
~/.config/touchegg/touchegg.conf

open it in an editor you desire and add those three lines below into the name="All" section
<gesture type="DRAG" fingers="3" direction="RIGHT">
   <action type="SEND_KEYS">Control+Alt+Left</action>
</gesture>
<gesture type="DRAG" fingers="3" direction="LEFT">
   <action type="SEND_KEYS">Control+Alt+Right</action>
</gesture>

Run touchegg to try it out
touchegg &

Edit the config file as you wish and then add touchegg to the list of startup applications

The tutorial I mentioned can be found here - there some things out of date (you don't have to compile it). Anyway thx to the creator!
Comment: Yeah, not working on my XPS13 either, running 15.04, or (today) 16.04 nightly. I wonder if there's a useful way to trouble shoot it, since the O/S does recognise 3-finger taps (mostly), but touchegg isn't interested.
Comment: is there a solution for Ubuntu 16.04??
Comment: This is not working on Ubuntu 15.04
Comment: Not working on my case, Ubuntu 16.04 is detecting two fingers scroll but not multitouch like 3 fingers. Need to install something more?
Comment: Gestures are not recognized on my computer :(
Comment: It's working fine :D with elementary OS
Comment: worked like a charm for me on ubuntu 16.04
Comment: I've got 4 workspaces arranged in a 2x2 grid: How can I reconfigure the 3-finger (or 4-finger) swipe on my Thinkpad touchpad to switch between these four (rather than only left <-> right with the 3-fingers) ?

Edit: just figured out I can use the 3-finger left <-> right "repeatedly" and browse all four workspaces, albeit not in a **2x2**, but rather a 1x4 "grid". How to make it 2x2, with **left <-> right and up <-> down** ?
Answer: Comfortable Swipe
Try comfortable-swipe. Provides 3-finger and 4-finger gestures for switching workspaces, plus a couple more like the window spread in mac.
This also uses xdotool, but more comfy than the laggy libinput-gestures if you ask me.
Comment: works with Ubuntu 18.04 LTS
Comment: For Ubuntu 18.10 you have to replace "libinput-debug-events" in src/comfortable-swipe.cpp with "libinput debug-events" three times. Than install with " bash install"
Comment: Works perfectly well on XPS 9500 15" with Ubuntu 20.10 (Gnome). Didn't need to restart, just log out and in again.
Comment: Works smoothly with Kubuntu 18.04 LTS
Comment: It works on my 18.04 but takes several seconds to respond and my fans go crazy fast and noisy making it not worth it. Nothing special appears on htop during this time.
Comment: Worked in 5 min, nothing else worked after hours. Brilliant, thanks for sharing !
Comment: Works on my Dell G5 with 18.04, make sure to run the permissions setting it shows in the README and log in+out. Up and down swipes work perfectly!
Comment: Worked like a charm on Ubuntu 20.04. Just note that, in the instructions given on the project's Github, it says to logout and then log back in. That doesn't work - you gotta restart your computer.
Answer: Your touchpad (hardware) needs to support this feature and you then may need to configure your touchpad (Ubuntu automatically recognizes and enables some hardware).
One common drier is synaptic. You can enable two finger scrolling from the mouse and touchpad section in the control panel.

If you wish additional options you will need to manually edit a few configuration files and the options are hardware dependent.
There is a debugging page here:
https://wiki.ubuntu.com/DebuggingTouchpadDetection
Take a look at that page, if you can identify your hardware we can perhaps give you more specific assistance.
An example of hardware specific guides: https://wiki.ubuntu.com/Multitouch/AppleMagicTrackpad
Consider easystroke
You can also take a look at "easystroke"
http://sourceforge.net/apps/trac/easystroke/wiki
Here is a demo of easystroke in action: http://www.youtube.com/watch?v=CagAEgXAAzA
Comment: I don't see the horizontal scrolling option on Ubuntu 14.04. Does this have to do with my hardware config?
Comment: is there a solution for Ubuntu 16.04??
Answer: The following worked for me on Ubuntu 16.04 and a 2017 Dell XPS 13 (9360):
sudo gpasswd -a $USER input
sudo apt-get install xdotool wmctrl libinput-tools
git clone http://github.com/bulletmark/libinput-gestures
cd libinput-gestures
sudo ./libinput-gestures-setup install

Restart your computer after the above steps. My ~/.config/libinput-gestures.conf is:
gesture swipe down  xdotool key ctrl+alt+Up
gesture swipe up    xdotool key ctrl+alt+Down
gesture swipe right xdotool key ctrl+alt+Left
gesture swipe left  xdotool key ctrl+alt+Right

Comment: Thanks, Working on 17.10 on HP Envy 13 with Synaptics Touchpad
Comment: This works perfectly, just make sure you have matching shortcuts configured in KDE as well, since xdotool just fires off key combos.
Comment: not working on an Acer with Ubuntu 16.04
Comment: not working on a Huawei Matebook with Ubuntu 20.04
Answer: This was my solution: 4 fingers and natural direction.
 <gesture type="DRAG" fingers="4" direction="RIGHT">
       <action type="SEND_KEYS">Control+Alt+Right</action>
    </gesture>
    <gesture type="DRAG" fingers="4" direction="LEFT">
       <action type="SEND_KEYS">Control+Alt+Left</action>
    </gesture>

Comment: What program does one need for this?
Comment: @g3mini touchegg, as tsusanka suggested
Comment: Thanks =) When I asked his/her answer wasn't there yet =D
Answer: I used the synaptics driver with xdotool to do that...
For speed of my macbook touchpad:
sudo nano /usr/share/X11/xorg.conf.d/70-synaptics.conf
# Touchpad Speedup
        Option "AccelFactor" "0.025"
        Option "MinSpeed" "0.80"
        Option "MaxSpeed" "0.95"
        Option "FingerHigh" "55"
        Option "FingerLow" "45"

For 3 fingers gesture change workspace:
sudo nano ~/.config/libinput-gestures.conf
gesture swipe up        3       xdotool key ctrl+alt+Up
gesture swipe down      3       xdotool key ctrl+alt+Down
gesture swipe left      3       xdotool key ctrl+alt+Left
gesture swipe right     3       xdotool key ctrl+alt+Right

Answer: Like already mentioned:
sudo gpasswd -a $USER input
sudo apt-get install xdotool wmctrl libinput-tools
git clone http://github.com/bulletmark/libinput-gestures
cd libinput-gestures
sudo ./libinput-gestures-setup install

But you have to go to:
cd ~/libinput-gestures

and edit the created libinput-gestures.conf:
gedit libinput-gestures.conf

And then make safe the following is set correctly:
gesture swipe down  xdotool key ctrl+alt+Up
gesture swipe up    xdotool key ctrl+alt+Down
gesture swipe right xdotool key ctrl+alt+Left
gesture swipe left  xdotool key ctrl+alt+Right

Remember: You have to set the key combinations in the Ubuntu settings to the ones shown above - these should be the default.

Touchpad gestures to change workspace


Style a JTextPane to have console-like formatting?

Question: Is there a way to make the text in a JTextPane look similar to that of console output? By that I mean, basically, how each character is the same width, so that things like ASCII art, or spacing indentation would work correctly.
For example, currently, if I type "First" and then 5 spaces, and then on a new line "Second" and then 4 spaces, the two lines do not end in the same position, so if there was text following those spaces, the text would not be aligned.
I don't know if it changes anything, but JComponents will also be included in the JTextPane.
Answer: set the font to a fixed width font such as courier, or use the Monospaced font-family.
JTextPane text = new JTextPane();
Font font = new Font(Font.MONOSPACED, Font.PLAIN, 14);
text.setFont(font);


Get the id of the nearest coordinate object

Question: I am using the answer in the example to find the nearest object coordinate. How do I find the index of the nearest point from var points if e.g. the nearest point is {x: 12, y: 18}, then index = 1?
I want to avoid using an extra indexOf() if that step can be saved.The code is:
var points = [
  {x: 10, y: 20},
  {x: 12, y: 18},
  {x: 20, y: 30},
  {x: 5, y: 40},
  {x: 100, y: 2}
];

function d(point) {
  return Math.pow(point.x, 2) + Math.pow(point.y, 2);
}

var closest = points.slice(1).reduce(function(min, p) {
  if (d(p) < min.d) min.point = p;
  return min;
}, {point: points[0], d:d(points[0])}).point;

console.log(closest);

Comment: What `id` means? I see only coordinates...
Comment: Also, in the reducer, you're always comparing the points to the first point in the array because you never change the `d` property of the accumulator, I'm not sure if that is your intention.
Comment: where is your origin?
Comment: Am I somewhat clearer now @Titus. Sorry, if I put it wrong previously
Answer: You could map the array to an array of objects first that also contain the index:

const points = [
  {x: 10, y: 20},
  {x: 12, y: 18},
  {x: 20, y: 30},
  {x: 5, y: 40},
  {x: 100, y: 2}
];

const distance = (point) => {
  return Math.pow(point.x, 2) + Math.pow(point.y, 2);
}

const result = points
     .map((point, index) => ({ point, index }))
     .reduce((a, b) => distance(a.point) < distance(b.point) ? a : b);

console.log(result);
Comment: Sorry for the edit, just wanted to make it runnable, but instead changed the code a little (removed target, because it wasn't there in the original function) and only realized after I hit apply. If you think it's against your intent, feel free to revert it :)


Prove that if $A\subset B$ then $P(A)\subset P(B)$.

Question: $A$ and $B$ being sets and $P(A)$ being the power set of $A$:
Prove that if $A\subset B$ then $P(A)\subset P(B)$.
It seems oblivious but I'm not sure how to write the proof properly.
Comment: Take an element in the power set, then this is a subset of A by definition, right? Then what follows from this?
Comment: Okey, every element of P(A) its a subset of A so its a subset B so its an element of P(B) therefore P(A)⊂P(B), thank you Pasternak.
Answer: Suppose (fill in details and watch carefully at the symbols)
$$X\in P(A)\implies X\subset A\subset B\implies X\subset B\implies X\in P(B)$$
Answer: Let $C\subset A$. Then since $A\subset B,$ we have $C\subset B$.


Calculate sum of a column by ID based on the value of another column in R

Question: I have some data that looks like this:
E_Add  Action  ActionType  Call  Callback  Email
xxxx   Task    Call        1     0         0
xxxx   Task    Call        1     0         0
xxxx   Event   Start       0     0         0
xxxx   Task    Call        1     0         0
xxxx   Event   Trial       0     0         0
yyyy   Task    Call        1     0         0
yyyy   Task    Callback    0     1         0
yyyy   Task    Email       0     0         1
yyyy   Task    Call        1     0         0
yyyy   Event   Start       0     0         0

And I want it to look like this:
E_Add  Action  ActionType  Call  Callback  Email CallSum CallbackSum EmailSum
xxxx   Task    Call        1     0         0
xxxx   Task    Call        1     0         0     2
xxxx   Event   Start       0     0         0
xxxx   Task    Call        1     0         0     1
xxxx   Event   Trial       0     0         0
yyyy   Task    Call        1     0         0
yyyy   Task    Callback    0     1         0             1
yyyy   Task    Email       0     0         1                         1
yyyy   Task    Call        1     0         0     2
yyyy   Event   Start       0     0         0

I mean it could look different than that, but that's the idea of what I want. I want to sum "calls", "callbacks", and "emails" by email and put them in a new column. But I want to reset the sum of "calls", "callbacks", or "emails" everytime I hit an "Event" in the Action column and of course do this by email.
Comment: Your description is unclear. Why in callSum column, for first email, the sum is written on the event line the first time and not on the event line the second time?
Answer: Your desired output isn't very clear, but I think this does what you need (you also have Email column twice)
library(data.table)
cols <- c("Call", "Callback", "Email") # Choose columns to modify

First solution (simple version)
setDT(df)[, paste0(cols, "Sum") :=
            lapply(.SD, function(x) c(rep(0L, .N - 1L), sum(x))),
            by = .(E_Add, cumsum(Action == "Event")),
            .SDcols = cols][]

#     E_Add   Action ActionType Call Callback Email.1 CallSum CallbackSum EmailSum
#  1:  xxxx   Task       Call    1        0       0       0           0          0
#  2:  xxxx   Task       Call    1        0       0       2           0          0
#  3:  xxxx  Event      Start    0        0       0       0           0          0
#  4:  xxxx   Task       Call    1        0       0       1           0          0
#  5:  xxxx  Event      Trial    0        0       0       0           0          0
#  6:  yyyy   Task       Call    1        0       0       0           0          0
#  7:  yyyy   Task   Callback    0        1       0       0           0          0
#  8:  yyyy   Task      Email    0        0       1       0           0          0
#  9:  yyyy   Task       Call    1        0       0       2           1          1
# 10:  yyyy  Event      Start    0        0       0       0           0          0

Second solution To match your exact output
setDT(df)[, paste0(cols, "Sum") :=
            lapply(.SD, function(x) {
            if(any(x == 1L)){
              indx <- max(which(x == 1L))
              x[indx] <- sum(x)
              x[-indx] <- 0L
              x
              } else 0L
           }),
            by = .(E_Add, cumsum(Action == "Event")),
           .SDcols = cols][]

#     E_Add   Action ActionType Call Callback Email.1 CallSum CallbackSum EmailSum
#  1:  xxxx   Task       Call    1        0       0       0           0          0
#  2:  xxxx   Task       Call    1        0       0       2           0          0
#  3:  xxxx  Event      Start    0        0       0       0           0          0
#  4:  xxxx   Task       Call    1        0       0       1           0          0
#  5:  xxxx  Event      Trial    0        0       0       0           0          0
#  6:  yyyy   Task       Call    1        0       0       0           0          0
#  7:  yyyy   Task   Callback    0        1       0       0           1          0
#  8:  yyyy   Task      Email    0        0       1       0           0          1
#  9:  yyyy   Task       Call    1        0       0       2           0          0
# 10:  yyyy  Event      Start    0        0       0       0           0          0

Edit per comment (If you want to display sum on Event
df[, paste0(cols, "Sum") :=
     lapply(.SD, function(x) c(rep(0L, .N - 1L), sum(x))),
     by = .(E_Add, cumsum(c(FALSE, (Action == "Event")[-length(Action)]))),
          .SDcols = cols][]

#     E_Add Action ActionType Call Callback Email CallSum CallbackSum EmailSum
#  1:  xxxx   Task       Call    1        0     0       0           0        0
#  2:  xxxx   Task       Call    1        0     0       0           0        0
#  3:  xxxx  Event      Start    0        0     0       2           0        0
#  4:  xxxx   Task       Call    1        0     0       0           0        0
#  5:  xxxx  Event      Trial    0        0     0       1           0        0
#  6:  yyyy   Task       Call    1        0     0       0           0        0
#  7:  yyyy   Task   Callback    0        1     0       0           0        0
#  8:  yyyy   Task      Email    0        0     1       0           0        0
#  9:  yyyy   Task       Call    1        0     0       0           0        0
# 10:  yyyy  Event      Start    0        0     0       2           1        1

Comment: I think this should work as I suspect the CallSum on the 3rd row as a typo.
Comment: @akrun yes, I also think it was a typo, thus , this seem to match *exact* output.
Comment: Thank you!! This worked perfectly despite my poor explanation of the problem.
Comment: What if I wanted to output the sums to the line where"Event" is?
Answer: df = structure(list(Email = structure(c(1L, 1L, 1L, 1L, 1L, 2L, 2L,
2L, 2L, 2L), .Label = c("xxxx", "yyyy"), class = "factor"), Action = structure(c(2L,
2L, 1L, 2L, 1L, 2L, 2L, 2L, 2L, 1L), .Label = c("Event", "Task"
), class = "factor"), ActionType = structure(c(1L, 1L, 4L, 1L,
5L, 1L, 2L, 3L, 1L, 4L), .Label = c("Call", "Callback", "Email",
"Start", "Trial"), class = "factor"), Call = c(1L, 1L, 0L, 1L,
0L, 1L, 0L, 0L, 1L, 0L), Callback = c(0L, 0L, 0L, 0L, 0L, 0L,
1L, 0L, 0L, 0L), Emails = c(0L, 0L, 0L, 0L, 0L, 0L, 0L, 1L, 0L,
0L)), .Names = c("Email", "Action", "ActionType", "Call", "Callback",
"Emails"), class = "data.frame", row.names = c(NA, -10L))

df$CallSum=''
df$CallBackSum=''
df$EmailSum=''

CSum =0
CBSum =0
ESum =0
for(i in 1:nrow(df)){

CSum = CSum+ df[[4]][i]
CBSum = CBSum+ df[[5]][i]
ESum = ESum+ df[[6]][i]

if(df[[2]][i] == 'Event'){

#
df[[7]][i] = CSum
df[[8]][i] = CBSum
df[[9]][i] = ESum

#clear out vars
CSum =0
CBSum =0
ESum =0
}

}

   Email Action ActionType Call Callback Emails CallSum CallBackSum EmailSum
1   xxxx   Task       Call    1        0      0
2   xxxx   Task       Call    1        0      0
3   xxxx  Event      Start    0        0      0       2           0        0
4   xxxx   Task       Call    1        0      0
5   xxxx  Event      Trial    0        0      0       1           0        0
6   yyyy   Task       Call    1        0      0
7   yyyy   Task   Callback    0        1      0
8   yyyy   Task      Email    0        0      1
9   yyyy   Task       Call    1        0      0
10  yyyy  Event      Start    0        0      0       2           1        1

Comment: How does your loop know to execute this "by Email"?
Comment: How could you put this into a function and then apply it to the data by "email"?
Answer: Here is my attempt. I eventually overwrote the three columns (i.e., Call, Callback, and Email.1). This could be one way to get what you are after. Initially, I created a group variable in the first mutate. I grouped the data by Email and group, and calculated sum for Call, Callback, and Email.1. Finally, I wanted to have zeros rather than empty space. So I used replace() in the final mutate.
library(zoo)
library(dplyr)

group_by(mydf, Email) %>%
mutate(group = ifelse(Action == "Event", row_number(), NA),
       group = na.locf(group, fromLast = TRUE)) %>%
group_by(Email, group) %>%
mutate_each(funs(sum(., na.rm = TRUE)), Call:Email.1) %>%
mutate_each(funs(replace(., which(Action != "Event"), 0)), Call:Email.1) %>%
ungroup %>%
select(-group)

#   Email Action ActionType Call Callback Email.1
#1   xxxx   Task       Call    0        0       0
#2   xxxx   Task       Call    0        0       0
#3   xxxx  Event      Start    2        0       0
#4   xxxx   Task       Call    0        0       0
#5   xxxx  Event      Trial    1        0       0
#6   yyyy   Task       Call    0        0       0
#7   yyyy   Task   Callback    0        0       0
#8   yyyy   Task      Email    0        0       0
#9   yyyy   Task       Call    0        0       0
#10  yyyy  Event      Start    2        1       1

DATA
mydf <- structure(list(Email = structure(c(1L, 1L, 1L, 1L, 1L, 2L, 2L,
2L, 2L, 2L), .Label = c("xxxx", "yyyy"), class = "factor"), Action = structure(c(2L,
2L, 1L, 2L, 1L, 2L, 2L, 2L, 2L, 1L), .Label = c("Event", "Task"
), class = "factor"), ActionType = structure(c(1L, 1L, 4L, 1L,
5L, 1L, 2L, 3L, 1L, 4L), .Label = c("Call", "Callback", "Email",
"Start", "Trial"), class = "factor"), Call = c(1L, 1L, 0L, 1L,
0L, 1L, 0L, 0L, 1L, 0L), Callback = c(0L, 0L, 0L, 0L, 0L, 0L,
1L, 0L, 0L, 0L), Email.1 = c(0L, 0L, 0L, 0L, 0L, 0L, 0L, 1L,
0L, 0L)), .Names = c("Email", "Action", "ActionType", "Call",
"Callback", "Email.1"), class = "data.frame", row.names = c(NA,
-10L))


Cordova plugin purchase. Approved event does not fire

Question: I'm using a plugin https://github.com/j3k0/cordova-plugin-purchase to implement a paid subscription in the app. I checked the work of the subscription on Android 5.1.1. And after I called the store.refresh() triggered the update event. But after that the approved event does not fire.
Here is my code
<code>function subscriptionIsApproved(product) {
    product.verify();
    console.log("Is approved: " + JSON.stringify(product));
}

function subscriptionIsVerified(product){
    product.finish();
    console.log("Is verified: " + JSON.stringify(product));
}

function subscriptionIsUnverified(){
    createErrorAlert(app,localDictionary[storage.getItem('language')].VERIFICATION_ERROR,null);
    setNotSubscribeMode(app,$$);
    console.log("Subscription is unverified");
}

function subscriptionIsUpdated(product){
    if (!product.owned) {
        store.order(product);
        setNotSubscribeMode(app, $$);
    }else
        setSubscribeMode(app,$$);

    console.log("Is updated: " + JSON.stringify(product));
}

function onDeviceReady() {
    var sbType;//subscription type
    if(Framework7.device.ios)
        sbType = store.NON_RENEWING_SUBSCRIPTION;
    else
        sbType = store.PAID_SUBSCRIPTION;

    store.register({
        id: subscriptionId,
        type: sbType
    });

    console.log("PRODUCT: " + JSON.stringify(store.get(subscriptionId)));

    store.error(function(e){
        console.log("ERROR " + e.code + ": " + e.message);
    });

    if(Framework7.device.ios)
        store.validator = app_store_verification;
    else if(Framework7.device.android)
        store.validator = play_market_verification;

    store.when(subscriptionId).approved(subscriptionIsApproved);
    store.when(subscriptionId).verified(subscriptionIsVerified);
    store.when(subscriptionId).unverified(subscriptionIsUnverified);
    store.when(subscriptionId).updated(subscriptionIsUpdated);
    store.when(subscriptionId).cancelled(function(product){console.log("Is cancelled: " +
    JSON.stringify(product));});
}

//init purchase by button click
$$(document).on('click','#continueBtn',function(){
    mainView.router.navigate('/confirmPhone/');
    store.refresh();
});
</code>
It doesn't work. After I press the button and call store.refresh() fires the update event in which I call store.order(product) method that should end with an approved event, but that doesn't work. What's wrong with my code?
Answer: I solved this problem. I added the cordova-plugin-purchase plugin, and it was necessary cc.fovea.cordova.purchase. Now approved works. But I still get an error: Your order is being processed. The product will be available in a few minutes


CTRL+ shortcuts doesn't work after compiz-manager installation

Question: It was working on Gnome Fallback/Classic. But after compiz-manager package installation, I lost Ctrl + shortcut keys, they don't work anymore.
For example, in web browser typing Ctrl+C on some text makes it gray, and don't get it copied. Deleting compiz-manager and reinstalling gnome didn't solve the problem.
However, on Gnome Shell 3 all works fine.
Please, help me to solve this.
Answer: I had a similar issue a little while back, and after going a little crazy I found that it was a small silly issue - I accidentally un-checked the Gnome Compatibility option in the CompizConfig settings manager.
The Gnome Compatibility option is what makes Compiz compatible with the Gnome desktop environment.
Hope this helps solve your issue :)
Comment: I have Gnome Compatibility box checked all time. Thats doesn't solved my problem.


What size SER and XHHW-2 do you use with a 200A meter base and a 225A load center (panel)?

Question: I'm going to be installing a 200A meter base with a 200A breaker in it, which acts as an external disconnect (required in California). Here's the spec sheet for it.
The load center I'm using (model LP422-MB) has a 225A main breaker in it. Here's the spec sheet for it.
I'm pretty sure that between the load center and the meter base I need 250 MCM aluminum SER cable. Right?
But where I start to get fuzzier is between the meter base and the service drop. The 200A meter is rated for 200A continuous load but something like 250A max load. And the load center is rated for 225A. The amperage for aluminum XHHW is:

200A - 4/0
250A - 300 MCM
225A - 250 MCM

So… which one do I go off of?
Thanks for your help!
Comment: I take it the loadcenter and the meter/main are in the same structure?
Comment: Yep! The meter is just on the outside and the load center is inside (in the garage).
Comment: I take it the main breaker is just there to provide a local disconnecting means for the panel then?
Answer: This is a 310.15(B)(7) question.
Generally, ampacity must be taken straight off Table 310.15(B)(16), rounding disfavorably.  The 75C thermal rating is used, since the breaker panel is rated for 75C (but not 90C) and every modern cable (except NM or UF, rarely used for feeder) are rated 75C.
This brings us to 250 kcmil for 200A.
However. Services to a dwelling get a discount.
When service wires power an entire dwelling, because of the load factors typical of dwellings, they get a 17% discount (83% favorable derate) - so e.g. a 200A service only requires 166A wire.
When we select wires from Table 310.15(B)(16), 4/0 wire (180A) is the minimum size (exceeding 166A).
It also says feeders never need to be larger.
You don't have service wire. You have feeder.  However, here's what they don't do: allow you 4/0 for service wire but require 250 kcmil for the feeder coming off that.  That would be stupid.
So 310.15(B)(7) says your feeder never needs to be larger than your service wire is allowed to be.  Since 4/0 is acceptable as service wire, it's acceptable as feeder for any circuit.
What this doesn't do is use the 83% favorable derate on smaller feeders.  If you run a 100A subpanel, you must run proper 100A wire, not "83A" wire.
Comment: This was incredibly helpful! Thank you so much for the detailed explanation! ❤


Drumroll sound not working in Ubuntu 16.04

Question: Whenever I login into my Ubuntu system, I don't hear the welcome drumroll sound effect, even though I get to hear it if I try to close Firefox. All other sounds are working. I used to hear it earlier, but now it has suddenly stopped. What could be the possible root cause and its solution?
Answer: The greeter is using a different sound setting to that of your normal login session. It is possible you accidentally lower or muted the audio in the login screen. Try increasing the volume while you are at the greeter login screen and reboot the system?
PS: If you are on a laptop, you may have to increase it via your hardware volume key at the login prompt.
Comment: You're right. Greeter volume was low. Had to increase it using volume slider on top right corner. That solved the problem. Thanks for answering.


Search for pages tagged with a tag title

Question: In order to get pages tagged with a certain tag in AEM query builder, we will do as this doc (https://helpx.adobe.com/experience-manager/6-2/sites/developing/using/querybuilder-api.html)
    path=/content/...
    type=cq:Page
    tagid=marketing:interest/product
    tagid.property=jcr:content/cq:tags

But how do we get pages that have the same tag title without using the whole tag's ID or full path above ?
For example
    path=/content/...
    type=cq:Page
    tagtitle=product
    tagid.property=jcr:content/cq:tags

Comment: When performing JCR queries in your back-end code, you should be using the name of the tag, not its title. Tags with the same title can be semantically different. At the same time, a single tag can have multiple, localized titles.
Comment: What the query should be when using tag name ?
Answer: You could use something like that:
JCR like:
path=/content/..
type=cq:Page
property=jcr:content/@cq:tags
property.value=%tagname
property.operation=like

This would search for cq:tags property with value that ends with "product".
See more about jcr:like  function.
Another possible solution:
Full text search:
path=/content/somesite
type=cq:Page
fulltext.relPath=jcr:content/@cq:tags
fulltext=tagname

See more about jcr:contains function


',' expected ts(1005) [19,10]

Question: I got this error in react. Is this is a syntax error or any other? Already check whole code in several times and couldn't solve it. This the code that i used. Shall i use ts here? And the error message screenshot added in following
    import React, { useState, useEffect } from './node_modules/react';
import { Link } from 'react-router-dom'
import axios from 'axios';
import { useSelector, useDispatch } from 'react-redux';
import { listProducts } from '../actions/productActions';

function HomeScreen(props) {
    const productList = useSelector(state => state.productList);
    const { products, loading, error} = productList;
    const dispatch = useDispatch();

    useEffect(() => {
        const fetchData = async () =>{
            dispatch(listProducts());

        return () =>{
            //
        };
    }, [])

    return loading ?
Loading...
 :
        error ?
{error}
 :

    {
        products.map(product =>

            < Link to= {'/product/' + product._id}>

                </ Link>

                    < Link to= {'/product/' + product._id}> {product.name} </Link>

{product.brand}

Rs.{product.price}

{product.rating} Stars ({product.numReivews}Reviews)

)
    }

}

export default HomeScreen;

Comment: Yes, it's a syntax error. You're missing a `}` on the async function you've assigned to `fetchData` in the `useEffect` callback.
Comment: When posting a question related to an error with a line number, help people out by indicating what line in the code you've quoted is the line mentioned. There aren't any line numbers in code blocks as shown on SO, and people tend to leave out parts of files when they post them anyway, so rather than making us count and hope that you haven't left some out, show us where the line is.
Comment: Do yourself a favor and give ESLint a try because that code isn't formatted properly... And with a set of rules your productivity will increase (and your team's productivity as well).
Answer: it's a syntax error you forgot the } in useEffect try this
useEffect(() => {
    const fetchData = async () =>{
        dispatch(listProducts());

    return () =>{
        //
    };
}}, [])

Answer: You missed one }. Correct way is this:
useEffect(() => {
    const fetchData = async () =>{
        dispatch(listProducts());
    } //<- this one
    return () =>{
        //
    };
}}, [])

',' expected ts(1005) [19,10]


How to delay re-delivery message?

Question: I am using the asynchronous pull of Cloud Pub/Sub
For now, when I call message.nack() method, it will re-delievery this message immediately.
subscription.on('message', (message) => {
  message.nack();
})

How to delay the re-delivery?
For example, I got a message with publishTime: '2019-05-28T10:24:31.055Z'
I want to let this message re-delivery 20 seconds(computed) later from last delivery.
Comment: Possible duplicate of [Why the message doesn't to be redelivered?](https://stackoverflow.com/questions/56353296/why-the-message-doesnt-to-be-redelivered)
Answer: There is currently no way in Cloud Pub/Sub to delay the redelivery of a message. When a message is nacked, it is immediately a candidate for redelivery to the same subscriber or to another subscdriber.
Comment: While this will potentially delay the message, it means that the message will still count against flow control limits. Therefore, if enough messages are in this state, then it is possible no new messages will be able to be processed until the outstanding ones are nacked.
Comment: How about `await sleep(duration); message.nack();`? Let the application process sleep for a duration then call `message.nack()`
Answer: You can now configure a retry policy in your Cloud Pub/Sub subscription. Retry policy allows users to have per message exponential backoff in case of failures.
More information can be found here.
Answer:
Pubsub guarantee at least one time delivery.
So unless you are not acknowledging the message, it will redeliver the
infinite time.
It expect to acknowledge message to complete in time which specified in
subscription setting(Acknowledgement deadline)

you can delay it by few setting in subscription

Change Acknowledgement deadline to 600seconds(10 Minutes)
Enable exactly one delivery (It will make sure once ur deadline time exceed then it will do reattempt for delivery message)
Enable dead Lettering(Create topic and after 5 attempts send to new topic.)

How to delay re-delivery message?


How to plumb and line, i.e., square, stud-frame walls if sheathing before raising

Question: I'm starting to frame a small house.  For background, the foundation is 2x12 sills bolted to pilings, then 2x8 joists and 3/4" plywood.
My question is about squaring the walls if they are sheathed while flat before raising.  I'm reading Larry Haun's The Very Efficient Carpenter.  He spends a few pages on the importance of plumbing and lining walls after they are raised, before sheathing.
If I sheath before raising, how to square?  My first thought is to simply pull diagonal measurements and make them equal before sheathing.   Then sheathing, raising with jacks, and hoping the sheathed wall stays square.  Not sure how to line a sheathed wall, as it should be fairly rigid.
Any ideas?
Answer: Your plan is correct. I usually tack the bottom plate to the wall line on the deck at several points to be sure it's straight. If you do this correctly you can easily pull the nails once the wall is up and nailed down. Don't do it from the bottom of the plate as the nails will hold the wall off the deck.
Now you pull diagonal measurements from the bottom plate corners to the top plate corners (not the double/tie plates as they don't match). Tack the top plate to the deck in one spot and you're golden. Sheathed walls are extremely rigid with respect to square. Don't expect to be able to make adjustments. They'll even show you where your deck has dips.
I'm not sure what you mean by "lining" but if it means straightening the top, I usually tack a scrap of two-by at each end, run a dryline between, and measure for 1-1/2". You'd have your ends plumbed and braced (or tied into perpendicular walls which are already square) first.
Comment: Thanks.  By "lining", I mean straightening the top plate after the ends of the wall are both plumbed so that, at the ends, the top plate is directly over the bottom plate.  That is, even after the ends are plumbed, the top plate can be bowed horizontally in the middle of the wall.  Haunt actually has a sketch showing exactly the method you describe.  Thanks.  That said, if the top plate does bow in or out, do you have a method to move it?  I'm thinking that a bowed 1x6 could be applied to the top plate to move it in or out.
Comment: They're usually very flexible in that direction. A diagonal brace to the deck is commonly used, and remains in place util the roof system is there to take over the job. Bracing must be robust and rigid, so your idea wouldn't do.


Concatenating two arrays?

Question: I'm struggling with a syntax issue to concatenate two arrays.
Basically, I have two arrays of string. The first contains several elements, the second only one (I use the , operator to create an array of string:
$array1= ,   "49e8e386-2f20-4139-ad61-a59500820afc",
             "70a4fad9-5b8f-4750-9d6c-1e69400ed63b",
             "1e368540-ebb3-4541-ab6e-78bcafaa6cf0"
$array2=   , "1c1fcc2c-ccef-4898-9562-127b3f749830"

I would like to merge the array in a new array of string, but it does not works as expected.
Specifically, I wrote :
$merged = $array1 + $array2

This seems to work, because I output $merged, I get:
49e8e386-2f20-4139-ad61-a59500820afc
70a4fad9-5b8f-4750-9d6c-1e69400ed63b
1e368540-ebb3-4541-ab6e-78bcafaa6cf0
1c1fcc2c-ccef-4898-9562-127b3f749830

But this is not an array of string:
PS C:\Users\steve> $merged | % { $_.GetType() }

IsPublic IsSerial Name     BaseType
-------- -------- ----     --------
True     True     Object[] System.Array
True     True     String   System.Object
True     True     String   System.Object
True     True     String   System.Object

As you can see, one of the value is a nested array, not a string. This is causing issues later in my scripts because of a string requirement.
What is to proper syntax to get an actual array of string?
Answer: Nevermind, the issue was related to the 1st array, and the , operator.
The correct syntax is :
$array1=     "49e8e386-2f20-4139-ad61-a59500820afc",
             "70a4fad9-5b8f-4750-9d6c-1e69400ed63b",
             "1e368540-ebb3-4541-ab6e-78bcafaa6cf0"
$array2=   , "1c1fcc2c-ccef-4898-9562-127b3f749830"

Actually, the array operator is required only when there is only one item in the array.
Comment: I searched for "array concatenation in Powershell" and stumbled upon your question. Upon reading it, I confirmed for myself your question effectively calls for a correct and idiomatic solution to concatenating arrays in Powershell, and so I scrolled for answers. The only answer is yours. But it doesn't communicate clearly to me how to concatenate arrays or what was even wrong -- how that comma affects what. It just specifies the presumably correct syntax for defining multiple arrays. Sitting with Powershell now to see what's going on here.
Comment: This answer makes no sense to me. So I have downvoted it. I don't understand the significance of the snippet as applied to the question and how does this solve the concatenation problem.
Comment: @amn: `$merged = $array1 + $array2` will contains actually five elements, which is the expected result. Thanks to the updated syntax. What's missing for your understanding ? ?
Comment: @amn I was confused too. I think it's b/c Steve is using `,` before `$array1` where he didn't need to. He's using `,` before the single element in `$array2` to make an array from a single object, but the `,` in the first makes element 0 an array of a string and then null? (`Write-Host ($merged[0][1] -eq $null)` gives $True) Better would be to say `$array2= @("1c1fcc2c-ccef-4898-9562-127b3f749830")` & to use `@()` in both. You're right: The question title does not reflect the title, & search engines pointing here are doing searchers a disservice. **The issue is declaration, not concatenation.**
Comment: Looks like my `@()` suggestion was wrong -- there are times with strings where you simply cannot create the intended single element array w/out [the comma operator](https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_operators?view=powershell-7.2&viewFallbackFrom=powershell-6#comma-operator-) or your array will "[unroll](https://stackoverflow.com/a/1829401/1028230)". More good info at [this answer](https://stackoverflow.com/a/53427301/1028230). Luckily still right that the take-away remains that the issue described here is declaration, not concatenation.

Concatenating two arrays?


How do I breed a Pollen Dragon?

Question: I received an in game announcement that a new Pollen Dragon is available for breeding. What is the best pair for breeding?  What is the breeding time (so I know if I was successful)?
Answer: From the Dragon Vale Wiki

The Pollen Dragon can be bred by selecting an air dragon to mate with a plant dragon at the Breeding Cave/Epic Breeding Island.

And the breeding time is 7 hours whereas the Willow Dragon is 8 hours.
Answer: Plant and air works for the pollen dragon

How do I breed a Pollen Dragon?


How to set abyss theme for komodo ide's editor?

Question: AFter I change komodo ide's default skin to abyss, the ui interface does change. But the main edit area did not change. How could I change it too?
Comment: i'm having opposite prob, i CANT get original skin to show anymore!
Answer: The skin choice (e.g. Abyss) affects the UI, not the code/edit view.  Try Edit > Preferences > Fonts & Colors


UIWebView is unavailable: not available on tvOS

Question: Is there anyway to use a UIWebView with an application targeted for tvos?
This Apple Doc, UIWebView Class Reference, would suggest otherwise would it not? Or am I just interpreting this all wrong?

UIWebViewNavigationType (New in tvos 9.0)
Comment: possible duplicate of [Web app in tvOS](http://stackoverflow.com/questions/32503582/web-app-in-tvos)
Comment: UIWebView / Webkit is not available in tvOS.
Comment: @JessBowers what would you suggest for the *hard* way?
Comment: deleted that qualifier. I would suggest making an app with UIKit
Comment: or rather, UIKit only. There isn't a way to use WebViews to render content on tvOS
Answer: UIWebView is not available for tvOS, as @JessBowers mentioned in the comments, and is documented here: UIKit Changes for Objective-C, UIKit Changes for Swift.
For a complete list of iOS API's that are available for tvOS refer to: iOS 9.0 to tvOS 9.0 API Differences
Answer: Although WebKit/UIWebView is not officially available in tvOS, some people have figured out that it is possible to use that functionality if you are willing to edit your system header files. No word on whether Apple would actually approve a tvOS app that is using such an undocumented API.

http://www.macrumors.com/2015/11/06/apple-tv-4-web-browser-tvos-hack/
https://github.com/steventroughtonsmith/tvOSBrowser


Solid angle and surface area values in (photometric) raytracing

Question: So, I started writing my second raytracer - this time focusing on photometric rendering that uses IES lights and standard photometric units.  I've got the basic raytracing up and running (using pure geometry), I've read any article I could found on radio- and photometry (I think I developed an intuition for it) but the issues started when I tried to validate/play with the underlying math.
I use IES lights as a function of spherical coordinates that gives me the intensity of light in that direction in candelas (lumens per unit solid angle). Also in the equation for Luminance/Radiance there are differential solid angle and differential surface area. On the paper everything looks good, however:
My question is: how should I deal with those parameters in my raytracer? I assume (but I'm not sure) that my (differential) solid angle is just a (unit) vector in descrete world and the surface area is simply a point - but what values should I plug in to those equations? I saw that on some websites that people just ignored those terms and replaced the integral with sum - but no explanation was given...
And my second question is related to those IES lights - how can I simply convert intensity to radiance? The intensity already has the solid angle, but for radiance I need the surface area... Or should I somehow integrate the luminious intensity to get luminious flux and then somehow calculate the radiance from that.
EDIT: I decided to try to grab a sheet of paper, try again and share with you my thought process. In order to simplify a lot of things:

each plane has a single scalar value as material (let's name it reflectivity between 0 and 1)

$p1$ has $reflectivity = 0.5$
$p2$ has $reflectivity = 1$

all materials are lambertian (no specular reflections nor emission)

So with those in mind let's imagine that we have following scene:

Step 1 - Illuminance at $p1$
The light luminious intensity at vertical angle $V=0$ is $I = 6619 [cd]$. In order to compute the illuminance at point $p1$ we can create a sphere with radius equal to the distance between the light and intersection point $p1$ which is $r = 2$ meters. That virtual sphere intersects with the first plane creating a small differential area $dA$. Knowing that $d\omega = \frac {dA}{r^2}$ we get $E_L(r) = \frac {I}{r^2} [ \frac {W}{m^2}]$ which is equal to illuminance measured at a plane perpendicular to light. We have to project it to know how many light hits the $p1$, so $E = E_L \times cos \theta$. I assume that $L_i = E$, but that is just a guess. I hope that at this point I got it right...
Step 2 - Outgoing luminance
In order to calculate the outgoing radiance I think that is the place for the rendering equation to kick in:
$$
L_o = L_e + \int_{\Omega} f_r(\omega_i, \omega_o) L_i(p, \omega_i) cos \theta d\omega
$$
since I ignore the emission and my BRDF is $f_r(\omega_i, \omega_o) = \frac {reflectivity}{\pi}$ which is constant across the integral giving me:
$$
L_o = \frac {reflectivity}{\pi} \int_{\Omega} L_i(p, \omega_i) cos \theta d\omega
$$
Now I have to discretize it, which I don't fully understand. Based on my notes that I've made based on many pages I've got:
$L_o = \frac {reflectivity}{\pi} \sum L_i(p, \omega_i) cos \theta \Rightarrow L_o = \frac {0.5}{\pi} L_i cos \theta$, where $L_i$ was calculated in step 1
Step 3 - Luminance at $p2$
Can I assume that $L_{i_{p2}} = L(p_1 \rightarrow p_2) \times cos \theta = L_{o_{p1}} \times cos \theta$ ? I'm not sure if I have to apply the $cos \theta$ twice (for outgoing and incoming $dA$s).
I also would like to apologize for making this question sooo long - but I had never taken any course that would introduce radiometry and I was forced to (try to) learn it by myself.
Comment: If you don't get good answers, graphicscodex.com talks about these things.
Answer: You have a lot of questions so let me take a shortcut and just try to explain how this is properly done (:
What you are interested in calculating is luminance (cd/m^2) for a pixel. A simple way you can do this is by using brute-force Monte Carlo integration over the hemisphere defined by the normal of a pixel, i.e. cast few thousand randomly distributed rays over the hemisphere. For each of those sample rays you evaluate the BRDF (1/sr) and multiply it with the luminance of the area light source the ray hits, or 0 if it doesn't hit anything. Sum up all these results and multiply by 2*pi/num_samples in the end, i.e. by the solid angle of each sample.
This operation gives you the the luminance for the pixel, which you then multiply by camera exposure factor to map to a proper range which you can tone map, i.e. calculate EV100 from camera aperture, shutter time and ISO-settings as follows:
float ev100=log2((aperture*aperture/shutter_time)*100.0f/iso);

And then calculate exposure factor:
float exposure_factor=1.2f*pow(2.0f, ev100);

For IES light profiles you can normalize the profile and modulate light luminance with the IES factor for the given direction the ray hits the light.


Quadratic residues and non-residues of p=4k+3 are complementary

Question: Given a prime p=4k+3 and an integer X, is it the case that if X is a quadratic residue of p, then -X (i.e. p-X) is NOT a quadratic residue of p?
How to prove this?  (Kudos for a simple proof!)
Comment: What have you tried? Since $p \equiv 3 \pmod{4}$, is $-1$ a quadratic residue mod $p$ or not?
Comment: What have you tried? Do you know that $(ab/p)=(a/p)(b/p)$ for the Legendre symbol?
Answer: We will use the notation of Legendre symbols. Suppose $x$ is a quadratic residue mod $p$ where $p \equiv 3 \mod 4$. Then $$\left(\frac{-x}{p}\right)=\left(\frac{-1}{p}\right)\left(\frac{x}{p}\right) = \left(\frac{-1}{p}\right)=-1.$$
The first equality follows from multiplicativity of the Legendre symbol. Then second equality follows from $x$ being a quadratic residue modulo $p$. And the last equality follows because $$\left(\frac{-1}{p}\right )= (-1)^{\frac{p-1}{2}} = (-1)^{\frac{4k+3-1}{2}} = (-1)^{2k+1} = -1. $$ Thus, $-x$ is not a quadratic residue modulo $p$.


Is there a program that can loop a youtube video?

Question: I would like to loop this video from YouTube, it's OK if it reloads every time although it would be nicer (and perhaps illegal ) to cache the video.
are there any suggestions on software that can do this?
Answer: You could create an HTML document and then just open it when you want this. Open your favorite editor and paste these contents into it. Save it anywhere, and then double-click the saved file to open in a Web browser.

    <title>Music</title>

    <embed
        src="http://www.youtube.com/v/pmfHHLfbjNQ?autoplay=1&loop=1"
        type="application/x-shockwave-flash"
        wmode="transparent"
        width="425"
        height="350">
    </embed>

Or just paste this in a browser and make a bookmark.
http://www.youtube.com/v/pmfHHLfbjNQ?autoplay=1&loop=1

Comment: could you clarify the command for looping a video? (there are no commercials as well! woho! :))
Comment: @Alvar Google has a great page on it: http://code.google.com/apis/youtube/player_parameters.html
Answer: Do you need it to actually be in the browser while it's playing?
If not, one thing you can do is:

Install youtube-dl
Open a terminal (ctrl-alt-t), and use youtube-dl to download the video you want to loop. Something like:

youtube-dl http://www.youtube.com/watch?v=QH2-TGUlwu4

WARNING: paste the Youtube URL for the video you need, don't use this example.

Play the downloaded .flv file with any video player capable of looping a video. I know vlc can do this (go to the playlist view for looping controls) but others might also work. Note that other video players may need you to install some additional codecs in order to be able to play .flv files.
Answer: you can play any youtube video with vlc. vlc <url of the video>
if you go into vlc preferences, all preferences, and then playlist, tick the box repeat current item
then it will loop any video you play.
after you do that go to the terminal, and play your specific video:
vlc http://www.youtube.com/watch?v=pmfHHLfbjNQ

it will keep looping. :)
Answer: i recently find this site https://www.youtuberpt.com, it gives you a simple way how to loop youtube videos and create custom playlist with part of your favorite videos, maybe it will help others who was trying to find something like this. Cheers!
Answer: You can use Enhancer for Youtube extension available for chrome and firefox.
Chrome Link Firefox Link
If you are on Android or iPhone then create playlist and then click on auto replay icon in the playlist.
Source: https://digitblogger.com/how-to-loop-youtube-videos/


Maximum number of vertices in connected graph with every degree at most 6 and distance between any two vertices at most 2

Question: The question is:
If $G$ is a connected undirected graph such that every vertex has degree at most 6, and the shortest path between any two vertices has length at most 2, then what is the maximum number of vertices in $G$?
My solution:
As it says the maximum degree can be 6, I connected 6 vertices to a central vertex and connected 5 vertices to each of those, but it violates the shortest path condition. The person who asked gave the answer as 37. I think he is wrong as this is the only configuration with 37 vertices.
How would you do it and what is your answer?
my attempt
for bob krueger saying answer as 32 the answer is 37, this is basically a Moore graph with d=6 and k=2. formula is in the following wiki. what i dont understand is how level 2 vertices connect like in simple explanation in link.
https://en.wikipedia.org/wiki/Moore_graph
Comment: now $1+6+ 5\times 6 =37$ is definitely an upper bound, the trick is to show that it is a lower bound. I do not yet know how one would do this. In fact as far as I know there may not exist a construction with $37$ vertices.
Comment: Fix a vertex $v \in G$. Then $N_G(v)$ has at most $6$ vertices, and $N^2_G(v)$ has at most $5 \times 6=30$ vertices. The constraint that $G$ has diameter at most $2$ gives $V(G) = \{v\} \cup N_G(v)\cup N^2_G(v)$ which gives $|V(G)| \le 1+6+30$.
Comment: thanks Andrew Uzzell.
Comment: So what is your answer? What is a maximum?
Comment: my answer is 37 i get the feeling there is a way to connect those tertiary vertices but cant put it in words. am confused.
Comment: What is that equation @Mike
Answer: A quick google search for "diameter 2, maximum degree 6 graphs" gives the following website with the answer: https://web.mat.upc.edu/francesc.comellas/delta-d/desc_g/desc_g2.html.
The maximum number of vertices is 32, and there are six such graphs.


HEVC/H265 videos not playing in SM Player

Question: I use SM Player for all videos.
Whenever i try to play HEVC/H265 videos sm player doesn't play it.
There is no h265 listed in codec list.
screen-shot:- http://prntscr.com/92x1is
I use Gnome Ubuntu 15.10
64-bit
I have latest version of SM Player.
H265/HEVC videos plays smoothly in vlc and default video player in ubuntu but it only not works in SM Player.
While in windows OS it plays smooth in SM Player but same file doesn't play in Ubuntu.
HEVC codec are already installed in ubuntu.
Answer: SMPlayer by default uses mplayer executable as its backend. You would need it to use mpv player instead.
Install mpv player first.
<code>sudo apt-get install mpv
</code>
Then open SMPlayer and go to its options. Change the location in Mplayer/mpv executable to
<code>/usr/bin/mpv
</code>
That should fix it. Make sure you have SMPlayer 15.9 installed.
Comment: getting the following error after trying to use mpv via SMplayer with the above solution:

Driver 'gl' has been replaced with 'opengl'!
Error parsing option yuv (option not found)
Option vo: Error while parsing gl parameter yuv (2)
Error parsing option vo (option could not be parsed)
Setting command line option '--vo=gl:yuv=2:force-pbo' failed.
Exiting... (Fatal error)

ideas on how to fix this?
Comment: BUMP CAN WE FIGURE THIS OUT YET>
Comment: Don't works. [On Mint Mate 17.2]


What does object mean in the Document object model (DOM)

Question: I was learning about DOM. The definition says that it is a representation of HTML document in a tree like structure to interact with the document. I I don't understand what object or object model means in this context.
Answer: Object is a general term in programming and not one unique to the DOM.
MDN is a reasonable place to start for an overview on objects.

Object refers to a data structure containing data and instructions for working with the data. Objects sometimes refer to real-world things, for example a car or map object in a racing game. JavaScript, Java, C++, Python, and Ruby are examples of object-oriented programming languages.

You might want to get to grips with object-oriented programming in general. MDN has an introduction using JavaScript.
Answer: First of all it is Document Object Model and not Document Object Modal, it is funny.
The object means that each element of the document (known as node) is represented as an object with its properties.
You can find more information here:
https://en.wikipedia.org/wiki/Document_Object_Model
In particular in the section Applications > JavaScript.
It says:
"When a web page is loaded, the browser creates a Document Object Model of the page, which is an object oriented representation of an HTML document that acts as an interface between JavaScript and the document itself."
Comment: What does it mean to be a tree like structure in DOM, does it mean representation of objects in the form of tree
Comment: Yes, for example you have the `html` that has two child: the `head` and the `body` and so on.
Comment: Does in tree representation objects and node are same thing. What is difference between node and object.


RadioButton always returning false - JavaScript

Question: I have a HTML page that have many section with inputs consisting of RadioButtons and CheckBox. The first one of them is like this:

    <input id="Answer1" type="radio" name="Answers" title="True" onclick="setAnswered();"/>True

    <input type="radio" name="Answers" title="False" onclick="setAnswered();" />False

Answer1

After the final input I am looking for each input and investigating that the correct answers are checked. Here is the part of script that is doing this job:
var ansList = document.getElementById(thisFrame + "_a").innerHTML.split(",");
for (var k = 0; k < ansList.length; k++) {
   var ele =  document.getElementById(ansList[k]);
   result = result & ele.checked ;
}

where thisFrame for this iteration is replaceAble1. Upon debugging it is clear that I am getting the correct element id in ansList[k] i.e. Answer1.
Now the problem is, every time, whether the Answer1 is checked or not ele.checked is returning false.
What could be the reason?
Update:
I think it would better to put complete code. So here it is:

    Q
        Do you live in Pakistan?

        <input id="Answer1" type="radio" name="Answers" title="True" onclick="setAnswered();"/>True

        <input type="radio" name="Answers" title="False" onclick="setAnswered();" />False

Answer1

null

    Q.
        Do you go for cycling daily?

        <input type="radio" name="Answers" title="True" onclick="setAnswered();" />True

        <input id="Answer2" type="radio" name="Answers" title="False" onclick="setAnswered();" />False

Answer2

null

    Q
        When Do you Sleep?

        <input id="notAnswer1" type="checkbox" name="Answers" title="True" onclick="setAnswered();"/>Morning

        <input id="notAnswer2" type="checkbox" name="Answers" title="False" onclick="setAnswered();" />Evening

        <input id="Answer3" type="checkbox" name="Answers" title="False" onclick="setAnswered();" />Night

Answer3

notAnswer1,notAnswer2

    Q
        What Do you Eat?

        <input id="Answer4" type="checkbox" name="Answers" title="False" onclick="setAnswered();" />Launch

        <input id="Answer5" type="checkbox" name="Answers" title="False" onclick="setAnswered();" />Break Fast

        <input id="Answer6" type="checkbox" name="Answers" title="False" onclick="setAnswered();" />Dinner

Answer4,Answer5,Answer6

null

And the script is:
var i = 0;
var answered = false;
var score = 0;
var unitScore = 5;
var totalScore = 20;
var frameList = ["replaceAble1", "replaceAble2", "replaceAble3", "replaceAble4"];
function setAnswered() {
    answered = true;
}
function displayAnswer(isTimeUp) {
    var Message;
    var j;
    if (isTimeUp) {
        Message = "Times Up";
    } else {
        Message = "Quiz End";
    }

    for (j = 0; j < frameList.length; j++) {
        var result = true;
        var thisFrame = frameList[j];
        var ansList = document.getElementById(thisFrame + "_a").innerHTML.split(",");
        for (var k = 0; k < ansList.length; k++) {
            var ele =  document.getElementById(ansList[k]);
            result = result & ele.checked ;
        }
        ansList = document.getElementById(thisFrame + "_n").innerHTML.split(",");
        for (var k = 0; k < ansList.length; k++) {
            if (ansList[k] !== "null")
                result = result & (!document.getElementById(ansList[k]).checked);
        }
        if (result) {
            score = Number(score) + Number(unitScore);
        }
    }
    document.getElementById("QuestionPan").style.display = "none";
    document.getElementById("resultPan").style.display = "block";
    document.getElementById("message").innerHTML = Message;
    document.getElementById("totalMarks").innerHTML = totalScore;
    document.getElementById("score").innerHTML = score;
    var timetaken = count - document.getElementById("time").innerHTML;
    document.getElementById("timetaken").innerHTML = timetaken + " minutes";
}
function submition() {
    if (!answered) {
        alert("Please select at least one Answer for this question.");
        return;
    }
    if (i === (frameList.length - 1)) {
        displayAnswer(false);
        return;
    }
    document.getElementById(frameList[i++]).style.display = "none";
    document.getElementById(frameList[i]).style.display = "block";
    document.getElementById("counter").innerHTML = (Number(i) + 1) + '/' + frameList.length;
    answered = false;
}

Only the first answer i.e. Answer1 is causing this problem. Every thing else is working fine.
Comment: what does **setAnswered()** contain?
Comment: @Emilian Manolache Nothing. It just alter a flag variable. It sets `var isAnswered` to `true`.
Comment: What exactly are you trying to return in this code: `for (var k = 0; k < ansList.length; k++) {
            var ele =  document.getElementById(ansList[k]);
            result = result & ele.checked ;
        }`? Are you trying to determine if the checked item is the "True" radio option, or if any radio option has been checked, so you can display the next question?
Comment: I am trying to make sure that the checked item is "True".
Answer: You probably want to use the boolean && operator, not the bitwise & operator.
result = result && ele.checked;

This also depends on the previous value of result. I'm not entirely sure this is your problem at this stage.
Update
I can't reproduce the problem. See http://jsfiddle.net/QA26Q/
My only other thought is that you have multiple radio buttons with the same ID as shown in this example - http://jsfiddle.net/QA26Q/1/.
Comment: No, I am talking only about `ele.checked`. Every thing else is working fine for me.
Answer: Got the problem. The problem was with HTML not the JavaScript. I have by mistake set the name field of all inputs same i.e. Answer. Hence all the radio button in all replaceable divs were belonging to same group. So when I set the Answer2 of replaceable2 the radio button of replaceable1 is reset. Being invisible I was't able to track this bug. So simply I changed the html to

    Q
        Do you live in Pakistan?

        <input id="Answer1" type="radio" name="Answers1" title="True" onclick="setAnswered();"/>True

        <input type="radio" name="Answers1" title="False" onclick="setAnswered();" />False

Answer1

null

    Q.
        Do you go for cycling daily?

        <input type="radio" name="Answers2" title="True" onclick="setAnswered();" />True

        <input id="Answer2" type="radio" name="Answers2" title="False" onclick="setAnswered();" />False

Answer2

null

    Q
        When Do you Sleep?

        <input id="notAnswer1" type="checkbox" name="Answers3" title="True" onclick="setAnswered();"/>Morning

        <input id="notAnswer2" type="checkbox" name="Answers3" title="False" onclick="setAnswered();" />Evening

        <input id="Answer3" type="checkbox" name="Answers3" title="False" onclick="setAnswered();" />Night

Answer3

notAnswer1,notAnswer2

    Q
        What Do you Eat?

        <input id="Answer4" type="checkbox" name="Answers4" title="False" onclick="setAnswered();" />Launch

        <input id="Answer5" type="checkbox" name="Answers4" title="False" onclick="setAnswered();" />Break Fast

        <input id="Answer6" type="checkbox" name="Answers4" title="False" onclick="setAnswered();" />Dinner

Answer4,Answer5,Answer6

null

And it worked properly.


Design pattern for sorting / ordering items in card view

Question: In a table design pattern there is usually a 'primary' key value which all the other values can be sorted by, and it is easy to sort or order the rest of the attributes associated with the item.
However, in a card design pattern this presents a real problem, especially when you want to compare multiple values.
I want to know if there is any standard patterns for using a card design pattern and then doing sort or ordering on the items. So for example where the primary key value is displayed on the card (e.g. top left, top right), and where secondary attributes are displayed so that it is easy to make comparisons when you are sorting or ordering the cards.
An example might be using a card interface to encapsulate a client record information, or a contact detail (e.g. business card), or even in social media applications to capture an event detail. This is in comparison to using cards for products and services as seen in many e-commerce websites and apps.
Comment: Can you provide an example of the use case that you are referring to and trying to improve?
Comment: @Ades updated my question to include some examples of use cases.
Answer: When sorting anything either a Vertical or Horizontal list of items is preferred. (but not both)
A vertical list is my personal preference as many devices are built to easily scroll up and down (i.e. mouse wheel, smartphones, etc.) among other reasons.

Sorting Cards in a Grid
First of all, this is a great question so go ahead and vote it up now.
Laying out content in bite-sized chunks <code>(cards)</code> that respond to look good and fit in any size space is a reality.  People seem to understand the card layout pattern used by many popular sites such as Pintrest.  Card layouts work well on any size display and consequently continue to grow in popularity.
Simply put, We are living in a responsive world and I am a responsive girl (or boy).
The problem is that anytime you try and sort items in a grid (vertical and horizontal at the same time) then someone is bound to interpret it wrong...
Dr. Fie Nogsh or Never Forget?

Below are some questions to ask when in a grid sorting situation...
1. Can I do the sorting automatically without any user interaction at all?
One reason that most people understand card layouts is that card layouts understand them!
For example, if you're listing movies from a certain category then just make the movie that other people watched the most and/or rated the highest bigger than the others.

2. Can I replace sorting with filters and/or groups?
Perhaps it's hard to find a lot of information on this topic is because there are better ways to get at the information besides sorting everything and then looking though all the items.  If there is an option to type anything I want and instantly see items disappear that have nothing to do with what I'm typing then this is my preferred approach.  Once I find the card I'm after you could provide additional options to see how many items come before and/or after in the list.  In any case, make absolutely sure that sorting items in a grid is what you require.
3. Do I really need to sort on more than one key at a time?
Avoid sorting a grid on multiple keys at all costs!  This would end up looking like a pivot table that no sane person can understand
If you must sort your content using both both rows and columns at the same time, however, then start in the top left corner and go to the right first before continuing on the next row like reading a book (top to bottom).  There may be rare times when you would start at the right and go left first such as countries where they read right to left but it should be self evident that putting the first sorted item at the bottom is always wrong.

Most of this information should really be self evident but various eye tracking studies show that the Top Left corner is where people look first so the key that you're sorting on probably belongs there as well.

An example of sorting a grid from left to right and then top to bottom.
Try and eliminate as much information as possible so the order of the cards can be understood quickly.  Only show the value you are sorting on (in this case carbohydrates) next to the most vital piece of information or even just a picture of the item.  Additional info can be shown/hidden on hover/click...

When sorting cards it is usually preferred to use either a Vertical or Horizontal layout but not both so for completeness I'll discuss those below...

Vertical List Sorting (preferred)
When sorting a list of cards vertically the key used to do the ordering should stand out from the card if possible so that it's instantly clear why the top card is at the top and the direction to go next.

Horizontal List Sorting
There are few examples of sorting cards horizontally though it should be clear that the item to the far Left is the Most Popular and goes without saying. The popularity decreases (or stays the same) the further to the Right I go in the example below.
Answer: This might help
http://blog.intercom.io/why-cards-are-the-future-of-the-web/
Its from a year or so ago, but it does touch on a few key points regarding organization of cards.
In a card organization pattern, the information is typically sorted based on the user, where they are coming from, and any other information the user has provided ahead of time to sort the cards in a manner relevant to them.
As mentioned in the previous post, the standard for that dissemination of information would be top left, to bottom right. This would likely only apply to cultures and languages that read in this pattern though.
Hope that helps.
Answer: I am developing a card-like interface right now, and it's tested internally to have 100% success vs. our current data-grid design. I embarked down this path when it came to light that our primary use case was not comparing data across cards, but performing actions on each. I endeavored to retain some measure of alignment, which I think goes a long way toward enhancing readability. Here's a prototype (blurred to hide some data but also to abstract the problem space a bit!):

Points I made sure to emphasize during usability testing were:

Whether or not the primary key (at the top right of each card and a bigger font) was visible and clear. It was.
Whether the tags (colored rectangles) still were easily scannable between records. I aligned them all as opposed to say the tags you see on github to achieve some consistency. This was well received.
Whether the controls/actions to be performed on each record are clear, discoverable, and intuitive. This tested better than a split-pane master-detail grid with shared controls. On hover of a card, the buttons apply a more active state that begets action.
Whether it was evident one could sort and filter records. This was a little wishy-washy  and needs better styling and design in it's current form.
Whether secondary information was comparable between cards. These are the remaining blurred out spots across the design. By locating them in the same place on each card, and coupling with sorting/filtering, it tested generally positive.

I've gone so far as to provide a very limited demo of how this card interface scales to a smaller viewport - and really there isn't much problem aside from the list growing vertically. This is the tradeoff one gets, but consistency is still key here.
One thing you will want explicit feedback on is whether or not people read the cards left to right (as I initially expected) or top down. I received feedback that the tags (the colored portions) should perhaps be located under the primary key. We will be iterating on both concepts soon with any luck.
Hope this helps. Far from a "best practice," but at least some real-world experience and considerations.
Comment: Nothing like real-world experience and considerations to help understand user concerns and behaviour!


Fields closed under countable additions?

Question: So I was learning about fields today and I came across the property that fields are closed under addition. That is, if $v_2,v_1 \in $ F ,then:
$ v_1 + v_2 \in$ F
Similarly, I we can say that:

$ v_1 + v_2 +v_3\in$ F
My question is can we extend this by saying:
$ \sum_{n=1}^{\infty} v_n \in$ F ?
Where $v_n \in $ F
I am pretty sure it won't hold for uncountably infinite additions, but will this be true for countably infinite addition as shown?
Comment: What does $\sum_{n=1}^\infty v_n$ even *mean*?
Comment: How would you define the sum?
Answer: No. Consider the field $\mathbb R$, and the countable sum $\sum\limits_{n=1}^{\infty}1$.

Additional comments:
The problem is that an infinite "sum" is not a sum at all. It is definitely NOT an infinite number of repeated additions. It is the limit of the sequence of finite sums (each of which IS an honest-to-goodness sum, and is an element of the field).
For your sum to exist in an arbitrary field, you would need to be able to define such a limit as a member of that field.
In the counterexample I gave, the partial sums are just $S_k = \overbrace{1+1+\cdots + 1}^{\textrm{$k$ terms}} = k$, but $\lim\limits_{k\to\infty}S_k$ does not exist as an element of $\mathbb R$.
Comment: That was silly so me, great explanation.


Can I replace my broken GFCI outlet with a single outlet with 2 USB ports?

Question: The new switch does have 2 backstab holes on each the load and the neutral side, but something tells me hooking both black to one side and both white to the other is not advisable. That would be great if that would be OK...
Also currently, when I check for power with a multimeter at the bottom, hot and neutral have power. At the top, however, I have none. I've screwed with the reset button, which seems shady, maybe broken.  I'm going to assume that's the problem.
Comment: Can you post a photo of this mess?
Answer: This GFCI probably has downstream outlets.
They probably were protected by the GFCI, up until the point the GFCI blew.  They will now be dead.
If any of them are in a garage, basement, laundry room, or pretty much any room containing a sink, those outlets need to still be GFCI.   So you will need to provide for their protection.
You can't defeat the GFCI ...probably.  As said, you can't break GFCI protection for any outlet that needs to be protected.
No such thing as a GFCI USB ... Yet.
The market doesn't appear to make what you want, a GFCI receptacle with a USB outlet also.   I could be wrong, if you've found one, carry on.   In the meantime, I'll talk about the workarounds in case you can't find one.
Install the GFCI protection upstream.
Follow the circuit in the other direction, back toward the circuit breaker.  These are outlets that are still working... but lose power when you turn off the breaker for this circuit.  Are there GFCI receptacles in any of those?  Is the breaker itself a GFCI?  Then you're all set.  If it's not that way, buy a GFCI outlet or breaker and  make it so.
You only need one GFCI and it will protect all the outlets downstream of it, provided those are connected to the LOAD side of the GFCI.  Some people daisy-chain GFCI's, that is redundant.
Now you can install your USB outlet (which does not have GFCI).
If you can't do the above, then replace the GFCI the way you found it, and put the USB outlet somewhere else.


microseconds epoch time parsing using strptime

Question: I am using fluentbit for sending logs and the logs have a timestamp like:
__REALTIME_TIMESTAMP : <micro seconds from epoch>
example -
__REALTIME_TIMESTAMP : 1528118184711009
Fluentbit uses strptime to parse the time string. But as I see in the documentation of strptime, I do not see a format string that does the parsing for microseconds from epoch or milliseconds from epoch.
I can only specify the format string in fluentbit.
I was guessing it like "%10s" for only taking the first 10 digits but it doesn't works.
Any help is appreciated.
Thanks in advance.
Answer: For posterity:
The %s works fine for even microseconds. It only takes the required number of digits if there is more precision given.


Python import not working

Question: spiders/
ekantipur.py
    class ekantipurSpider(XMLFeedSpider):

tests/
   responses
      __init__.py
      spiderdir
        Archive_ekantipur.html
   spiderdir_test.py
   from spiders import ekantipur

In the given file structure, when I try to access the class ekantipurSpider in spiderdir_test.py,i.e from spiders import ekantipur, it says following error.
from spiders import ekantipur
ImportError: No module named spiders

Comment: Do you have an `__init__.py` file there?
Comment: It looks like the formatting of your question isn't quite right, check your indentation please.
Comment: yes I have __init__.py file in spiders folder.
Answer: You cannot import spiders from the tests directory like that, unless you have it in your PYTHON_PATH environment variable. Please read about Python's import system.
For a quick and dirty (!) fix add this at the top of your file:
import sys
sys.path.append("..")

Or read this post about relative imports: Import a module from a relative path
Answer: try running the spiderdir_test.py from the parent folder of spiders and tests with this command "python -m tests/spiderdir_test". Note that you need to have __init__.py into tests folder also. Basically you will be running spiderdir_test.py as a module.
Comment: (news-scraper)➜  crawler git:(development) ✗ python -m tests/spiderdir_test.py
 /home/ramesh/.virtualenvs/news-scraper/bin/python: Import by filename   is not supported.  This is the error I got when try to run from shell.
Comment: use "spiderdir_test" instead of "spiderdir_test.py"
Comment: python -m tests/spiderdir_test
Traceback (most recent call last):
  File "/usr/lib/python2.7/runpy.py", line 162, in _run_module_as_main
    "__main__", fname, loader, pkg_name)
  File "/usr/lib/python2.7/runpy.py", line 72, in _run_code
    exec code in run_globals
  File "/var/www/news-scrapper/src/crawler/tests/spiderdir_test.py", line 3, in
    from spiders.ekantipur import ekantipur
  File "spiders/ekantipur.py", line 5, in
    from crawler.items import NewsItem
ImportError: No module named crawler.items
It effects on  from crawler.items import NewsItem import.
Comment: running the module from parent folder will need all the import statement made according to the parent folder. So the crawlers folder should be parallel to the tests and parallel folder. or else try like this "from tests.crawlers.items import NewsItem", (provides crawlers is inside tests folder), according to your folder structure.

Python import not working


Does MRG32k3a compare well with PCG and Xorshift256*?

Question: I've been using standard 32-bit Xorshift in my GPU path-tracer for a while, following Nathan Reed's approach with hashed seeds and decorrelated state. I (finally) discovered today that Xorshift is considered obsolete and I should use a 64-bit+ PRNG instead for better-distributed values, but I obviously can't fake the operations needed for PCG and modern Xorshift without expensive software arithmetic.
So, I've been considering the MRG32k3a hash by Pierre L'Ecuyer. It uses doubles instead of uint64s, it's included in Intel's Math Kernel Library, and some authors claim it has good statistical performance. It's also nearly twenty years old, though, and the paper linked above is dated from 2011.
Is MRG32k3a still considered an effective PRNG? Is it an effective alternative to PCG and modern Xorshift?
If not, what else should I use? Philox seems interesting, but it's another old technique (published 2011) and I'm not sure if it's been superseded in the meantime.

MRG32k3a MKL entry
Example implementation from L'Ecuyer's paper
The paper itself
Answer: Short answer is yes.
MRG32k3a has withstood the test of time, much more than PCG or XorShift256*. In fact, a recent paper by Matsumoto (creator of Mersenne-Twister) shows some poor properties of XorShift128 variants. So going 64-bit is not the answer.
64-bit is also ambiguous. The question indirectly assumes 64-bit+ of state. It could also mean the size of the one random integer output in bits. MRG32k3a will give you (almost) 32-bit numbers as output (I think actually 31).
The latest implementation by Vigna of MRG32k3a is fast on CPUs.
MRG32k3a has also a relatively efficient skip to arbitrary positions in the stream, which may be useful for multithreading, although there are faster alternatives, the fastests generators to skip are counter based generators derived from crypto, such as Chacha or Philox. But they are also slower in general at generating a single number. Finally Xoshiro256++, used in the Julia programming language by default, offers a decent compromise between fast generation and efficient skip.