How can I use masks on f.input on Rails?

Question: First of all, sorry if I made language mistakes, this is not my mother tongue.
I'm learning RoR and I'm building a CRUD to register the information of a lot of computers, and I'm using Simple Form to generate the forms. My question is, how can I use masks in the f.input element?
Like when the user goes to insert the Ip adress, he get something like ---.---.---.--- in the text field.
if helps, here is this part of the form:

    <%= f.input :mac_adress, label: 'Type the machine\'s MAC ADRESS: ', placeholder: 'XX:XX:XX:XX:XX:XX' %>

    <%= f.input :patrimony, label: 'What is the patrimony number? ', placeholder: 'XXXXXX' %>

    <%= f.input :ip, label: 'Inform the IP adress: ', placeholder: 'XXX.XXX.XXX.XXX' %>

    <%= f.label :lab_id %>:
    <%= f.text_field :lab_id, :value => @machine.lab.name, :hidden => true %>

    <%= f.button :submit %>

Thanks for any help, and if any additional information needed just ask.
Comment: Take a look into [jQuery Mask plugin](http://igorescobar.github.io/jQuery-Mask-Plugin/), this should help you achieve what you need.
Comment: also you could try [maskedinput](http://digitalbush.com/projects/masked-input-plugin/) and [inputmask](https://github.com/RobinHerbots/jquery.inputmask)
Comment: I tried [Input mask](https://github.com/RobinHerbots/jquery.inputmask) and I couldn't make it work right.
Comment: And how I can insert the mask on the text field? I really don't now if I'm doing this correctly
Answer: Mine:
<%= f.text_field :phone, class: "form-control", :required => true, :data => {:mask=> '999-999-9999'} %>

Yours:
<%= f.input :ip, label: 'Inform the IP adress: ', placeholder: 'XXX.XXX.XXX.XXX', :data=> {:mask=> '999.999.999.9999' %>

add this js in your application.js

jasny/jasny-bootstrap.min.js


Cant connect to wifi when bluetooth is on

Question: I am using Ubuntu 20.04 LTS, and when using my Bluetooth headphones I cant connect to my home wifi, but somehow I can connect to a mobile hotspot, what do you think is causing this problem?
Comment: Bluetooth and WiFi share the same EM spectrum and can interfere with each other. See if changing the channel on your router makes a difference.
Comment: Ideally, a fixed channel, not any autoselect.
Answer: Did the first two answers, don't know which one fixed it, but now it works
wi-fi and bluetooth not working simultaneously


Carpet washer keeps tripping main switch

Question: I have this carpet washer you can see in the picture which keeps tripping my main switch.
The 1st time I used it all worked fine, now I can only use it for 30 seconds and then the main switch trips. I did try to use different sockets in the house and I have the same problem no matter which socket it is plugged in to.
Any suggestion will be much appreciated.
Thank you
Comment: Does your "main switch" have a TEST button on it that trips it?
Answer: Certainly sounds like you are in an area with a RCBO on the main switch and the carpet washer has a >30ma ground fault, since there's no conceivable way that the cord to that device could carry enough current to trip the main on overcurrent more than once (the cord would be slag before the second time.) Given the UK-style plug visible, that matches the normal power setup I'm familiar with there from visiting.
The carpet washer needs to be serviced to correct the fault (conceivable, but rare these days) or replaced.
Comment: Thanks for saying it for me.  The carpet washer is drawing too much electricity.  This is typical when the motor is seeing too much back resistance (meaning bearings or belts need maintenance) or the motor's windings are slightly damaged (due to abrasion by dust) or some other means.   Effectively you have a motor that already uses a lot of power doing double-duty as an even less efficient motor and a heater.  The breaker is cutting out the circuit before that heat hits something critical, requiring a fire extinguisher.


Should function return a customException or a String to hint that an error occured?

Question: I am trying to understand what is a better design choice in the case when we have functions in a Class which does a bunch of things and should either return a string or raise a custom exception when a particular check fails.
Example :
Suppose I have a class like :-
#Division only for +ve numbers
class DivisionError(Exception):
 pass

class Division(object):
 def __init__(self, divisor, dividend):
   self.divisor = divisor
   self.dividend = dividend

 def divide():
   if self.divisor<0:
     #return "-ve_divisor_error"
     or
     #raise DivisonError.divisorError

   if self.dividend<0:
     #return "-ve_dividend_error"
     or
     #raise DivisionError.dividendError

   return self.dividend/self.divisor

What is better to return a custom string or raise exception especially in case of writing a python library.
And do we need to write separate classes for all Custom exception that we raise or is there a way to have an enum of some kind on a single customexception class?
Answer: Exceptions. Almost 100% of the time the idiom in python is to throw an error
Comment: Ya. Also bcoz if I return a custom string and the function is complex I might have to do all those 100 checks to see what was the return value of the function - from wherever it was invoked.
Answer: The more pythonic way would be to throw an exception. One of the python mantras is EAFP: Easier to ask for forgiveness than permission. If you look around the standard library, you'll see try/except all over the place.


creating facebook application

Question: i have this problem..
I created account to develop facebook api for my apps..
I registered and created account and vertified with email and phone.
But when i try to create new app, i get this error:
You've been blocked from creating apps because we haven't been able to verify your account. You need to use your real name to maintain an account on Facebook
I dont get it, what do i have to do, to get my account vertified and working? I need this account only for development and i dont want to use account, cos other developers can see my password.
and when i try to ask this question anyware on facebook forums i get this message, so i dont know what to do:
This message contains blocked content that has previously been flagged as abusive or spammy
Btw, i added apps on my real facebook account, but i dont remember having any problems..
Answer: If i not understand wrongly, did you mean that you are creating another facebook account for your development purpose? actually you can use your own account to create the facebook application. After that, you can grant access to others developer from the app. They can have the access to edit your application configuration too.
Regards,
Woolei - Facebook Consultant at www.woolei.com

creating facebook application


How to get connectionString from EF Core 2.0 DbContext

Question: In EF6 works this code:
<code>    public string GetConnectionString(DbContext ctx)
    {
        ObjectContext _objectContext = ((IObjectContextAdapter)ctx).ObjectContext;
        if (_objectContext?.Connection != null)
        {
            EntityConnection entityConnection = _objectContext.Connection as EntityConnection;
            return entityConnection?.StoreConnection?.ConnectionString;
        }
        return null;
    }
</code>
How to do it in EF Core 2.0 ?
Answer: <code>var connectionString = ctx.Database.GetDbConnection().ConnectionString;
</code>
with EF Core 5:
<code>   var connectionString = ctx.Database.GetConnectionString();
</code>
Comment: thanks, found it in nuget package: `Microsoft.EntityFrameworkCore.Relational`
Comment: In Ef Core 2.2 you need to add using Microsoft.EntityFrameworkCore;
Comment: But it doesn't include the password.
Comment: @Khodaie, the password will be in there [until a connection is opened](https://stackoverflow.com/questions/12467335/connectionstring-loses-password-after-connection-open), unless you use Persist Security Info = true in your connection string. You could fetch the connection string in your context's constructor and store it in a private field, that way you have access to it later on. However, that defeats some of the added security, so be careful.


In Terraria, is it possible to completely reclaim a Corrupted area?

Question: Well, what I tried to do was completely cleanse a Corruption area. I assumed it's all about the grass, since that seems to be how the Corruption spreads, and other biomes (such as the Underground Jungle) work like that.
So, I bought a few stacks of Purification Powder and Sunflowers, and purified every bit of Corrupted grass I could find.
It didn't completely work, however. Slimes/Zombies now spawn, but so do Eaters of Souls, still — and the music hasn't changed.
Is there something else that has to be done to completely eradicate the Corruption? (I've already smashed every single Shadow Orb; I doubled checked using the World Viewer.)
Answer: The Eaters of Souls spawn when Ebonstone is present.  You need to mine or purify all of that.
Comment: Oh. Well, that makes sense and is really annoying. Screw getting rid of the Corruption then, there's tons of the stuff...
Comment: you need quite a bit of ebonstone in close proximity, though, so move on as soon as the music stops and don't hunt down every single piece.
Comment: Good point.  You don't need to mine/purify all the Ebonstone.  Thanks.
Answer: You can do this a lot faster with Dynamite. ;)
Comment: True, but in this case "faster" means "still a lot more time than I'm willing to invest, given how effective [my current solution](http://cloud.steampowered.com/ugc/577798892362649169/A6C2E41D5C35BF2658D89F1E3BEE9DB5723F38EF/) already is". Also, expensive.
Comment: @lunboks: You are still left with the monsters that spawn above, so it's more efficient to remove the upper half of the chasms with dynamite... ;)


Creating a deck of cards using a class array?

Question: I am very new to VB. I am having trouble using a class (a card class I created) into another class (Deck class).  I am not sure on how to get and set array property's once I have created my fields.
Here is the code for my card class
Namespace Game Public Class Card

'create fields Private cardValue As Integer Private cardSuite As String

Property CardValue_Prop() As Integer
    Get
        Return cardValue
    End Get
    Set(value As Integer)
        cardValue = value
    End Set
End Property

Property CardSuite_Prop() As String
    Get
        Return cardSuite
    End Get
    Set(value As String)
        cardSuite = value
    End Set
End Property

Sub New(cardValue As Integer, cardSuite As String)
    Me.cardValue = cardValue
    Me.cardSuite = cardSuite
End Sub

End Class
End Namespace

Here is the start of my deck class - I basically want to make all the card objects (all the cards in the 52 card deck):
Namespace Game

Public Class Deck 'create fields

Private spades(12) As Card

Private Hearts(12) As Card

Private Diamonds(12) As Card

Private clovers(12) As Card

ReadOnly Property Spades_Prop(---------) As Card  <-- stuck here
      Get
          Return
      End Get
   End Property
End Class
End Namespace

Any help would be appreciated!
Answer: First of all:
I wouldnt use 4 arrays. Rather use one array of card and add a 'suit' to class card.
Namespace Game Public Class Card

'create fields Private cardValue As Integer Private cardSuite As String

...
Public Property Suit as Suit
Get
 Return _suit
End Get
End Property
...

End Class
End Namespace

Define Enum Suit:
Public Enum Suit
   Spades
   Diamonds
   Hearts
   Clubs
End Enum

And then in your main class game:
Namespace Game

Public Class Deck

Private _cards(51) As Card

Public ReadOnly Property Cards() As Card()  <-- here is your answer
Get
  Return _cards
End Get
End Property
End Class
End Namespace

Also, you were really close to the answer. You just had to add two brackets to define it's an array.
Comment: A deck of cards doesn't hold 53 cards;) Change to `Private _cards(52 - 1) As Card`.
Comment: @Bjørn-RogerKringsjå thanks. I always get mixed up with Java :(
Comment: Hehe, you're not alone;)
Comment: 0-51 my bad.  Thank you.  I really wanted to practice creating my own class and using it in another user defined class.
Comment: Fabian when I enter ReadOnly Property Cards()() As Card <-- I get an error that says End of Statement expected anda blue line under () As Card
Comment: Ah sorry i think i fixed it now


Can I get free PS+ games 'retroactively'?

Question: I just discovered to my utter dismay that I was paying for Plus membership (for over a year), thinking that it is required to access PlayStation Shop. I would have continued to do so, but luckily I saw a YT video, where it was explained that I have free games each month given by Sony.
I was stupid and assume things, which is my fault totally. Now, for the March 2018 I saw BloodBorne given for free, which made me very happy (as I wanted to get that game anyway).
Also, I checked the previous 'giveawys' and there are some titles I would want to have. Is there a way to get them 'retroactively'?
Comment: Since all your questions have been answered, I just have to add this important info: You can only play these free games when you have an active PlayStation Plus membership. If your membership runs out you can't play these games until you pay again. Sadly.
Comment: On a related note (but not an answer), if you purchase a game for even $0.01 (say, it was discounted 90% to PS+ members), you do get to keep it, even if you later cancel your subscription.
Comment: You don't need this to access the shop, but you do need this if you ever want to play online with others, which is basically the sole purpose and source of joy of the non-story-driven games anyways, e.g. Pro Evolution Soccer. Also I'm pretty sure not allowing the users to play previous free games is exactly the point of their business model.
Answer: Unfortunately, there is no way to retroactively redeem past PS Plus games.
If you haven't redeemed those games when they were free, you'll have to either purchase them or wait until they're offered for free once more.
To redeem a PS Plus game, simply "purchase" it while it is still free. You don't need to actually download the game.
Comment: Also keep in mind that you need to maintain your ps plus subscription to play games you have obtained with PS Plus
Comment: it should be noted that after the 8th of March next year (2019) Playstation will stop offering any more PS3 and Vita games (you'll still keep the ones you have now) so after then if you're waiting for an older game to be free again (ie. one of the PS3's Yakuza games) you'll be fresh out of luck
Comment: "or wait until they're offered for free once more" – something to keep in mind is that, at least thus far, PS+ free games essentially never repeat. ([full list](https://www.reddit.com/r/PlayStationPlus/wiki/list/fullna))
Comment: Is there an unofficial way to do it?
Comment: Oh no :(. Well now I will keep my eyes on it.
Comment: @NuclearWang. I'm not aware of any, sorry.
Comment: @Memor-X didn't they stop offering free games for ps3 already?
Comment: @Jorrit not yet, I believe they will stop March next year
Comment: @Jorrit nope, [here's the web version of the email i got](http://view.playstationmail.net/?qs=171a6481fa72e3b5698f19161fa64411db9533128d2242ec951d2869265d67deecb9f9d74aff15bbb4d216ac779f2527c08546344aa1944b086991a0454c4c7b34651de044ef25e4). if your looking at the though though a console you'll get a filtered view for just that console (ie, viewing the free games on the PS4 will only show you PS4 Games). i generally check [the browser version](https://store.playstation.com/) which will show me all the games regardless of console
Comment: @Memor-X thanks I've had the same mail but couldn't find it anymore. And my memory might have changed the 9 to a 8
Answer: You cannot claim free games from past months. For instance, it's April now, meaning if I didn't visit the store and download Bloodborne through PS+ last month then I can't go back and do so now, even if my subscription is still active.
However, if you already claimed a free game in the month it was offered, then wait a few months and remove it from your system, you can go back and re-download it for free as long as you're still subscribed to PS+


Synchronize On Same String Value

Question: Let's say I have a method that creates a new user for a web application.  The method itself calls a static helper class that creates a SQL statement that performs the actual insertion into my DB.
public void createUserInDb(String userName){
    SQLHelper.insertUser(userName);
}

I want to synchronize this method such that it cannot be called concurrently by different threads if the passed in parameter (userName) is the same on those threads.  I know I can synchronize method execution using the synchronized keyword, but this would prevent different threads from concurrently executing the method in general.  I only want to prevent concurrent execution if the passed in variable is the same.  Is there an easy construct in Java that would let me do this?
Answer: There is no guarantee that two strings with the same value would point to the same instance in Java, especially if they are created from user input.
However, you can easily force them into the string pool using the intern() method, which would guarantee it's the same instance being used:
public void createUserInDb(String userName){
    String interned = userName.intern();
    synchronized (interned) {
        SQLHelper.insertUser(interned);
    }
}

Comment: @Jesper That hasn't been true for a considerable number of years. Interned strings can be garbage-collected just like the others. See [this answer](http://stackoverflow.com/a/18153570/207421) and my comments on [this one](http://stackoverflow.com/a/2431597/207421), heavily upvoted.
Comment: Interning strings like this is, however, not a good idea. It can cause a memory leak - strings that are interned in the string pool stay there until the JVM exits.
Comment: @EJP the behaviour of `String.intern()` depends on the JVM Version. The behaviour of `String.intern` is very the different for JVM 6,7,8 see for example the blog of  [Mikhail Vorontsov - String.intern in Java 6, 7 and 8 – string pooling](http://java-performance.info/string-intern-in-java-6-7-8/). Or  for some more details have a look at http://bugs.sun.com/view_bug.do?bug_id=6962931 and http://bugs.sun.com/view_bug.do?bug_id=6962930.

Synchronize On Same String Value


AKS cannot pull image from GitHub Private registry but Minikube could pull the same one

Question: I am trying to build an application, but when I try to create a Deployment, the container failed at creation stage with the error:
   "docker.pkg.github.com/XXXXX/XXXXXX/XXXXXXXXXXXX:latest": rpc error: code = NotFound desc = failed to pull and unpack image "docker.pkg.github.com/XXXXX/XXXXXXX/XXXXXXXXXX:latest": failed to copy: httpReaderSeeker: failed open: content at https://docker.pkg.github.com/v2/XXXXXXX/XXXXXX/XXXXXXX/manifests/sha........ not found: not found

I followed exactly along with this tutorial: https://kubernetes.io/docs/tasks/configure-pod-container/pull-image-private-registry/
And I tried with kubectl both on Cloudshell and on my local machine, same issue:
Then I tried minikube on my local machine, and deploy using the YAML, and the deployment created without any issue. Also, docker pull is also working. I guess then it should not be the github credential issue.
I really cannot figure out the reason for kubernetes behave so differently on azure and on minikube. Would appreciate any help on how to troubleshooting and solving this issue.
Just FYI, I use below shell cmd to create the resource on Azure, wondering if I miss any steps:
 az group create \
     --name $RESOURCE_GROUP \
     --location $REGION_NAME

 az network vnet create \
     --resource-group $RESOURCE_GROUP \
     --location $REGION_NAME \
     --name $VNET_NAME \
     --address-prefixes 10.0.0.0/8 \
     --subnet-name $SUBNET_NAME \
     --subnet-prefixes 10.240.0.0/16

 SUBNET_ID=$(az network vnet subnet show \
     --resource-group $RESOURCE_GROUP \
     --vnet-name $VNET_NAME \
     --name $SUBNET_NAME \
     --query id -o tsv)

 VERSION=$(az aks get-versions \
     --location $REGION_NAME \
     --query 'orchestrators[?!isPreview] | [-1].orchestratorVersion' \
     --output tsv)

 az aks create \
     --resource-group $RESOURCE_GROUP \
     --name $AKS_CLUSTER_NAME \
     --vm-set-type VirtualMachineScaleSets \
     --node-count 1 \
     --load-balancer-sku standard \
     --location $REGION_NAME \
     --kubernetes-version $VERSION \
     --network-plugin azure \
     --vnet-subnet-id $SUBNET_ID \
     --service-cidr 10.2.0.0/24 \
     --dns-service-ip 10.2.0.10 \
     --docker-bridge-address 172.17.0.1/16 \
     --generate-ssh-keys

echo 'xxxxxxx' | docker login https://docker.pkg.github.com -u xxxxxxx --password-stdin

Answer: The failure was because the latest version of AKS (1.20 or higher) has deprecated the docker as a container runtime (use ContainerD instead). After I switch to the older version to 1.18, the problem solved.
Comment: Did you recreate the cluster from scratch as we don't have an inbuilt provision to downgrade AKS?
Comment: @JithinZachariah thanks for pointing it out. Yes, that's was a careless statement. I just recreate the new cluster with an old version of Kubernetes


How to compute this gross limit.

Question:
How do I compute this limit?
  $$
  \lim_{n \to \infty}
  \frac{\left(1 + \frac{1}{n} + \frac{1}{n^2}\right)^n -
        \left(1 + \frac{1}{n} - \frac{1}{n^2}\right)^n
  }{
       2 \left(1 + \frac{1}{n} + \frac{1}{n^2}\right)^n -
        \left(1 + \frac{1}{n} - \frac{1}{n^2 + 1}\right)^n -
        \left(1 + \frac{1}{n} - \frac{1}{n^2 (n^2 +1)}\right)^n
  }
$$

I think I got the correct limit by using fast converging limits to $e$.
In particular I used truncated Taylor series for the sqrt and 4th root.
Or squares and bisquares.
Example
$(1+1/2n)^{2n}$
 Becomes
$(1 + 1/n + 1/4n^2)^n.$
In combination with l'hopital it gives me the answer.
But I guess that is not a very good (fast) method.
Comment: what are your thoughts?
Comment: probably you have in the denominator a $   2( 1+ \frac{1}{n}+ \frac{1}{n^2} )^n  $, otherwise the answers solve you this problem
Comment: *Taylor formula at order $1$* on the function $f_n(x)=(1+1/n+x)^n$ yields readily, using the shorthands $a=f_n(0)\in\Theta(1)$ and $b=f'_n(0)\in\Theta(n)$, that the ratio is $$\frac{a+b/n^2-(a-b/n^2)+o(1/n)}{2(a+b/n^2)-(a-b/n^2)-a+o(1/n)}=\frac{2b/n^2+o(1/n)}{3b/n^2+o(1/n^2)}\to\frac23.$$ Note that exact asymptotics of $a$ and $b$, not to mention the exact limit of $a$, are irrelevant.
Comment: Close votes ? Really ?
Comment: Thanks Clark !! A typo sorry.
Comment: I fail to see how this is " off topic " :/ Imho too many close votes these days ... Or is it just me ?
Comment: @Did In case you saw it, I just wrote you a comment about your post: I deleted my  comment, because you were right, and I was wrong... sigh
Answer: Hint: First show $(1+1/n +o(1/n))^n \to e.$
Comment: Sorry , I made a typo !
Comment: Well with the new version, I'm not sure "gross" is the right term. Perhaps "perverse"? (Maybe there's a nice way to see it. Sorry, but I have to clean the lint trap now.)
Comment: I could do that with taylor or with l'hopital. But how does that help " much " here ?
Comment: Suppose you know this. What is the limit of the numerator? What is the limit of the denominator?
Answer: Use the fact that $a^n-b^n = (a-b)(a^{n-1}+a^{n-2}b+\cdots+ab^{n-2}+b^{n-1})$. It is going to be quite lengthy so bear with me: The numerator is
$$
\left(1+\frac{1}{n}+\frac{1}{n^2}\right)^n-
\left(1+\frac{1}{n}-\frac{1}{n^2}\right)^n = \frac{2}{n^2}\sum_{m=0}^{n-1}
\left(1+\frac{1}{n}+\frac{1}{n^2}\right)^{n-1-m}
\left(1+\frac{1}{n}-\frac{1}{n^2}\right)^m
$$
Write the above as $2/n^2 f(n)$.
The denominator has two parts
$$
\left(1+\frac{1}{n}+\frac{1}{n^2}\right)^n-
\left(1+\frac{1}{n}-\frac{1}{n^2+1}\right)^n = \left(\frac{1}{n^2}+\frac{1}{n^2+1}\right)g(n)
$$
where
$$g(n) = \sum_{m=0}^{n-1}\left(1+\frac{1}{n}+\frac{1}{n^2}\right)^{n-1+m}\left(1+\frac{1}{n}-\frac{1}{n^2+1}\right)^m$$
and the second part
$$
\left(1+\frac{1}{n}+\frac{1}{n^2}\right)^n-
\left(1+\frac{1}{n}-\frac{1}{n^2(n^2+1)}\right)^n = \frac{1}{n^2}\left(1+\frac{1}{n^2+1}\right)k(n)
$$
where
$$k(n)=\sum_{m=0}^{n-1}\left(1+\frac{1}{n}+\frac{1}{n^2}\right)^{n-1+m}\left(1+\frac{1}{n}-\frac{1}{n^2(n^2+1)}\right)^m$$
so in the end you have
$$
\lim_{n\to\infty}\frac{\frac{2}{n^2}f(n)}{\frac{2n^2+1}{n^2(n^2+1)}g(n)+\frac{n^2+2}{n^2(n^2+1)}h(n)}=
\lim_{n\to\infty}\frac{2(n^2+1)f(n)}{(2n^2+1)g(n)+(n^2+2)h(n)}
$$
Now note that as $n\to \infty$ then $f(n)$ becomes approximately
$$f(n) = \sum_{m=0}^{n-1}
\left(1+\frac{1}{n}+\frac{1}{n^2}\right)^{n-1-m}
\left(1+\frac{1}{n}-\frac{1}{n^2}\right)^m\approx n\left(1+\frac{1}{n}\right)^n\approx ne$$
where $\approx$ means to order of $o(1)$. Actually $g(n)\approx ne\approx h(n)$ too.
 So the limit reduces to
$$\to \lim_{n\to\infty}\frac{2(n^2+1)}{(2n^2+1)+(n^2+2)}=\frac{2}{3}$$
Hopefully I haven't made a mistake anywhere, but at least I think the method is clear.
Comment: I don't immediately see why the errors in your computation of $f(n)$ are only $o(1/n)$, but you only need them to be $o(n)$, which is easy to see because each of the $n$ terms is converging to $e$ and this convergence is uniform across all the terms.
Comment: You're completely right. Actually I was just thinking about that myself. The order is definitely not $o(1/n)$, at most it is $o(1)$ (I'm not sure about this either). But as you just said $o(n)$ is enough.
Answer: Perhaps a  way to 'see the answer' is to use the MVT: for the numerator, write $f( x) = x^n$, $a = 1 + 1/n -1/n^2$, $b = 1 + 1/n + 1/n^2$. Then
$$ f( b) - f(a) = f'(c)(b-a),$$
for some $c \in (a,b)$.
 Therefore the numerator is
$$ n\left(1 + 1/n + o(1/n^2)\right)^{n-1} 2/n^2.$$
Similarly, in the denominator, using the same trick twice, one gets
$$ n\left(1 +1/n + o(1/n^2)\right)^{n-1} ( 2/n^2 + 1/(n^2+1) + 1/n^2(n^2+1) ).$$
Taking the limit (of the ratio!), one gets Hamed's answer of $2/3$.
Comment: @Hamed just to confirm your answer of 2/3...
Answer: Hint: (for the first version, before multiplying by 2)
$$
\left(1+\frac1n\right)^n\leq\left(1+\frac1n+\frac1{n^2}\right)^n\leq\left(1+\frac{1+\epsilon}n\right)^n
$$
for large $n$. Hence all partial limits are $e$ and the final one — 0.
Comment: Yes.  But I made a typo. Sorry.
Comment: Not trying to be rude but : so what ? Far from a solution ?
Comment: @mick The limit of the second term is between $e$ and $e^{1+\epsilon}$, hence is equal to $e$. You can show in the similar way, that the other limits of expressions of the form $(...)^n$ are also $e$.
Comment: Perhaps better to use $$(1+1/n+c/n^2)^n=\exp(n·\ln(1+1/n+c/n^2))\\=\exp(n·((1/n+c/n^2)-(1/n+c/n^2)^2/2+O(1/n^3)))\\=e·(1+(c-1/2)/n+O(n^2))$$ to get a better quantification of the error.
Answer: You might get some easy simplifications by extending the fraction with the factor $(1-\frac1n)^n$ so that all terms transform to the form
$$
\left(1+\frac{c_n}{n^2}\right)^n=1+\frac{c_n}{n}+O(n^{-2}).
$$
to obtain
\begin{align}
&\ \lim_{n \to \infty}
  \frac{\left(1  - \frac{1}{n^3}\right)^n -
        \left(1  - \frac{2}{n^2} + \frac{1}{n^3}\right)^n
  }{
       2 \left(1 - \frac{1}{n^3}\right)^n -
        \left(1 - \frac{2n^2+1-n}{n^2 (n^2 + 1)}\right)^n -
        \left(1 - \frac{n^2+2}{n^2 (n^2+1)} + \frac{1}{n^3 (n^2 +1)}\right)^n
  }
\\ \\
&=\lim_{n \to \infty}
  \frac{\left(1 + O(n^{-2})\right) -
       \left(1-\frac2n +  O(n^{-2}) \right)
  }{
       2 \left(1 +  O(n^{-2})\right) -
        \left(1 - \frac{2}{n} + O(n^{-2})\right) -
        \left(1 - \frac{1}{n} + O(n^{-2})\right)
  }
\\ \\
&=\frac 23
\end{align}
Answer: $$
n\log\left(1+\frac1n+\frac{x}{n^2}+O\left(\frac1{n^3}\right)\right)=1+\frac xn-\frac1{2n}+O\left(\frac1{n^2}\right)
$$
Therefore,
$$
\left(1+\frac1n+\frac{x}{n^2}+O\left(\frac1{n^3}\right)\right)^n=e\left(1+\frac xn-\frac1{2n}\right)+O\left(\frac1{n^2}\right)
$$
Thus
$$
\begin{align}
&\frac{\overbrace{\left(1+\frac1n+\frac1{n^2}\right)^n}^{x=1}-\overbrace{\left(1+\frac1n-\frac1{n^2}\right)^n}^{x=-1}}{2\underbrace{\left(1+\frac1n+\frac1{n^2}\right)^n}_{x=1}-\underbrace{\left(1+\frac1n-\frac1{n^2+1}\right)^n}_{x=-1}-\underbrace{\left(1+\frac1n-\frac1{n^2(n^2+1)}\right)^n}_{x=0}}\\
&=\frac{e\left(1+\frac1n-\frac1{2n}\right)-e\left(1-\frac1n-\frac1{2n}\right)+O\left(\frac1{n^2}\right)}{2e\left(1+\frac1n-\frac1{2n}\right)-e\left(1-\frac1n-\frac1{2n}\right)-e\left(1-\frac1{2n}\right)+O\left(\frac1{n^2}\right)}\\[6pt]
&=\frac{\frac2n+O\left(\frac1{n^2}\right)}{\frac3n+O\left(\frac1{n^2}\right)}
\end{align}
$$

How to compute this gross limit.


Aurora Mysql takes lot of time to write csv records

Question: I am trying to write my csv file records into Aurora Mysql RDS.
I didn't made any settings/performance tuning.
it is taking 7 minutes to write 500 lines/records

Is it normal or do I need to change any settings.
I am using jooq.
Loader<?> loader = create.loadInto(Tables.DUMMY_PROCESS_LISTING)
        .onErrorIgnore()
        .loadCSV(new File("/tmp/" + fileName))
        .fields(Tables.DUMMY_PROCESS_LISTING.COL1,
                Tables.DUMMY_PROCESS_LISTING.COL2,
                Tables.DUMMY_PROCESS_LISTING.COL3)
        .execute();

Current Max thread connection is 40 - default one.
CPU usage is around 7%
Comment: Where is this code actually running, relative to the location of the Aurora server?  What do you see if you repeatedly run the query `SHOW PROCESSLIST;` on a different connection while the data is loading?
Answer: I cannot comment on your Amazon setup and on your concrete databasese, but from the jOOQ side, there are some ways to tune the Loader API.
Default loader commit / batch / bulk values:
The default commit / batch / bulk flags on jOOQ's LoaderOptionsStep are:

commitNone()
batchNone()
bulkNone()

This is usually not the fastest way to insert data, especially if there is a significant amount of latency between the client and the server. Here's an explanation for each:
Commit sizes
The commit size specifies how many batches should be executed in one transaction. In many databases, having a commit size that is too small will negatively affect performance as there is too much work on the UNDO/REDO log by the process that imports the data. Conversely, having a commit size that is too large will also negatively affect performance, as there might be substantial work on the UNDO log on other transactions (especially in MVCC transaction models).
In your case, this shouldn't be a problem, as you're only inserting 500 rows.
Batch sizes
In jOOQ-speak, a "batch" is the same thing as a JDBC batch, so the batch size is the number of individual insert statements that are sent to the server in a single batch statement.
Batching optimises latency because it allows for sending several statements in a single go to a server.
The default is not to batch any statements. Here, you can definitely gain quite a bit of throughput.
Bulk sizes
In jOOQ-speak, a "bulk" corresponds to a "bulk of rows" that are inserted / modified by a single statement. For instance, if you specify a bulk size of 5, then 5 rows will be inserted with a single statement, e.g.:
INSERT INTO t (a, b, c)
VALUES (1, 2, 3),
       (2, 3, 4),
       (3, 4, 5),
       (4, 5, 6),
       (5, 6, 7);

If the above syntax is not supported, jOOQ will emulate it as follows:
-- Depending on the database, FROM DUAL or something similar is added, too.
INSERT INTO t (a, b, c)
SELECT 1, 2, 3 UNION ALL
SELECT 2, 3, 4 UNION ALL
SELECT 3, 4, 5 UNION ALL
SELECT 4, 5, 6 UNION ALL
SELECT 5, 6, 7;

A bulk insert operation optimises performance inside of the database, as the database can optimise for the insertion of several rows, e.g. allocating disk space.
As a side-effect, of course, this also optimises latency, because a single statement will now transfer 5 rows over the wire from the client to the server.
This is also something that could benefit you.
Other reasons
Again, these are means to tune jOOQ's Loader API. There may be other ways to tune your database, which are not related to jOOQ.


Value too large for defined data type

Question: I need to burn a ISO (3.3GB in size) using Brasero using my Ubuntu machine, however when I try to do it which the ISO is saved in my Portable USB Drive with NTFS file system, Ubuntu 64-bit says:
Value too large for defined data type

Is there a work around for this, so I can burn ISO into disk?
$uname -a

Linux ubuntu-desktop 3.5.0-23-generic #35~precise1-Ubuntu SMP Fri Jan 25 17:13:26 UTC 2013 x86_64 x86_64 x86_64 GNU/Linux

And i tried to create a large file:
username:~/temp$ dd if=/dev/zero of=file bs=1048576 count=51205120+0 records in
5120+0 records out
5368709120 bytes (5.4 GB) copied, 92.9742 s, 57.7 MB/s

Comment: yest there is much space available I even did a large file using 'dd' and it worked just fine
Comment: Do you have sufficient space in `/`, as it needs to write some files in  temp directory. use `df -h` to find disk space.
Answer: The disk Burner softwares do not support burning of huge images .This at least applies to Brasero and K3B.
There seems to  be a workaround.Run these commands one by one
dd if=/dev/zero of=file.iso bs=1024 count=4589800
mkudffs file.iso  #your filename here
mkdir /media/tmpdvd # if you haven't already a directory
mount -o loop -t udf file.iso /media/tmpdvd
cp big_file /media/tmpdvd
umount /media/tmpdvd

Then try to burn the file using GUI or terminal as per your choice.

If the above method dosen't work, see the output of
ulimit -f

if it is not unlimited, run this command
ulimit -f unlimited

Answer: Just to expand the beforementioned workaround:
I have to also note that I've tried doing the same with a 4.8 GB ISO image on two different machines with (almost) the same version of the gnome-disk-utility package (which contains the gnome-archive-writer and gnome-archive-mounter tools) and I had the same error on the 32 bit machine, however, it worked flawlessly on the 64 bit one, so I am almost sure that it has to do with the system architecture and the limits of 32 bit integers. Check the architecture of the installed package, because since x86_64 kernels support the execution of x86 apps, it is not uncommon to have both x86 and x86_64 (amd64) binaries coexisting in your system. Just replace your package with the corresponding amd64 build and it should work fine.

Value too large for defined data type


get value into output variable when executing stored procedure through dynamic query

Question: i am using sql server 2008 r2, I have created a dynamic stored procedure because this is my requirement to implement to filteration of data based on certain conditions. I am not able to get value into @RecordCount
ALTER PROCEDURE [dbo].[sp_getAssetListAudit]
    @type nvarchar(20),
    @typeid nvarchar(5),
    @clientId nvarchar(5),
    @PageIndex nvarchar(5),
    @PageSize nvarchar(5),
    @RecordCount nvarchar(5) output
AS
BEGIN
    SET NOCOUNT ON;
    DECLARE @SQL    nvarchar(max)

SET @SQL ='

select ROW_NUMBER() OVER ( ORDER BY ad.arid ASC )
AS rownum, ad.arid,ad.ast_code,ad.ast_descp,isnull(cat.name,'''') ''cat'',ISNULL(loc.name,'''') ''loc'',isnull(gp.name,'''') ''grp'',
isnull(cc.name,'''') ''cc'' ,
ad.ast_qty ''qty'' into #Results
from tbl_AssetDetails ad
left join tbl_Category cat on ad.ast_cat = cat.catid
left join tbl_Subcategory scat on ad.ast_subcat = scat.subcatid
left join tbl_Location loc on loc.lid = ad.ast_loc
left join tbl_Group gp on gp.gid = ad.ast_grp
left join tbl_CostCenter cc on cc.ccid = ad.ast_costcen
where ad.ast_status not in (3,-1) AND ad.clientId = '+@clientId+' AND '

IF(@type='cat')
SET @SQL = @SQL +' ad.ast_cat='+@typeid+' AND '
IF(@type='subcat')
SET @SQL = @SQL +' ad.ast_subcat='+@typeid+' AND '
IF(@type='loc')
SET @SQL = @SQL +' ad.ast_loc='+@typeid+' AND '
IF(@type='grp')
SET @SQL = @SQL +' ad.ast_grp='+@typeid+' AND '
IF(@type='cc')
SET @SQL = @SQL +' ad.ast_costcen='+@typeid+' AND '
IF(@type='ast')
SET @SQL = @SQL +' ad.arid='+@typeid+' AND '

SET @SQL = @SQL +' 1=1 '
SET @SQL =@SQL + ' SELECT '+@RecordCount+' = count(*) FROM #Results '
SET @SQL  = @SQL +' SELECT * FROM #Results WHERE rownum
BETWEEN('+@PageIndex+' -1) * '+@PageSize+' + 1 AND((('+@PageIndex+' -1) * '+@PageSize+'+ 1) + '+@PageSize+') - 1 '

SET @SQL = @SQL + ' drop table #Results '

EXEC sp_executesql @SQL, @RecordCount OUTPUT

END
I am not able to get value into @RecordCount and subsequently no result set.
Answer: You need to assign the value to the OUTPUT parameter:
SET @SQL =@SQL + ' SELECT @RecordCount = count(*) FROM #Results; '

You also need to pass the parameter definitions to sp_executesql as in @wannuanguo's answer. You should use also use parameters for @typeid, @pageindex, etc. too instead of literals in the query.
Answer: Add the second parameter for sp_executesql:
EXEC sp_executesql @SQL, N'@RecordCount nvarchar(5) output',@RecordCount OUTPUT


Show the path of a nested list with jQuery

Question: So I have a nested list:

        a

                a.1

                a.2

        b

                b.1

                b.2

And I have an event that fires on a click that moves the item to the next nested list (if you click a, it will show a.1 and a.2 in a list). What I want to do is to be able to set the current menu by simulating clicks; however, I don't know of the best way to get the chain to execute the function. In this instance, I'd have to execute the click on b, and then on b.2, and in that order. How could I accomplish this with the least amount of code? And the real kicker is that I might have many nested lists (up to 4), so I want this to be somewhat flexible. Help! This is as far as I've made it:
currentMenu: function() {
    var $open = $mID.find('.open');
    if($open.length > 0) {

    }
}

Thanks!
Comment: wrap your `ul` element give it a classname and invoke it using `show()` `hide()` or fadeIn() fadeOut() methods.
Comment: I have added a demo in my answer please let me know if its the thing that you are looking for.
Comment: Sorry, not exactly what I was looking for. I ended up making an array of the path of ul tags, and reversed it to execute the function in the proper order, if that makes any sense. Thanks though!
Answer: I have added a demo here this is what you might do. Hope it helps!


SQL query - I don't know all identifiers

Question: Is there a way, where I can see every parameter or identifier I can query from my database? Not the contents but the "column names"
Something like
SELECT * FROM myDb AS String

Comment: You may retrieve this data from `INFORMATION_SCHEMA.COLUMNS` table. https://dev.mysql.com/doc/refman/8.0/en/information-schema-columns-table.html
Comment: You have it all here https://dev.mysql.com/doc/refman/8.0/en/information-schema.html
Comment: Could you please be more specific? If database contains 1000 tables what do you want to see?
Comment: All attributes/parameters that are used in the Database(I only have access trough a query), e.g. If its a customerDb to show me what attributes are used like: customer_name, customer_address (I don't want the input, I want the "column names"
Answer: To simply get the column names and types of a table.
You could SHOW them.
SHOW COLUMNS FROM myTable;

But if you want to know the column names of your table, and only a bit of data from it (to see what it looks like).
Then use LIMIT to get only a few records.
SELECT *
FROM myTable
LIMIT 3

It's fast and easy.
But you can also just see the columns without data if you use a criteria that's false.
SELECT *
FROM myTable
WHERE 0=1

Answer: You can also use:
show create table table_name;

but as "LukStorms" mentioned, the below statement shows you the data in table format and in a pretier way
show columns from table_name;

Comment: I like this one. Getting the full create statement might be a bit to technical for most users, but it's easier than using the system views.
Answer: You can use INFORMATION_SCHEMA.COLUMNS to retrieve all columns name

select column_name from INFORMATION_SCHEMA.COLUMNS where Table_Name='Your_Table'


How does parry work?

Question: I've seen several videos (like Evo finals, etc) in which top players were abble to parry attacks: unlike blocks, parries will avoid you to lose any life (I think).
One of the most famous examples, with Daigo "the beast" (SF3):

But I have no idea about

how to perform a parry
how does it work exactly (it looks like a part of your life is glowing in a bright yellow, right after the parry)
Answer: There is no parry in Street Fighter IV. Something similar is Focus Attack.
Focus attack doesn't require a perfect timing which you need in parry. Also, you can`t parry all upcoming attacks and you are not invincible when doing it. To do a Focus Attack, press and hold Medium Punch + Medium Kick at the same time and your character will start charging. There are a lot of differences between focus attack and parry:

Focus attack is an offensive move that can stun the opponent. It has three different "levels" depending on how long you've held it and only crumples ("stuns") if it's a counterhit (level 1), unblocked (level 2), or always (level 3).
Focus attack doesn't completely negate the damage, you absorb it into your health bar as recoverable health. You should not focus when low on life, as you will die if you take 200% of your current HP as "recoverable" damage.
You can only focus one attack, so moves which hit twice or just a couple of jabs or short will be able to penetrate the focus.
Throws, command grabs, and many ultras and specials that are called armorbreakers which will hit you regardless of focus. When this happens you'll hear a sound like a pane of glass shattering.

In order to cancel the Focus Attack, right after the parry, for instance, keep Medium Punch and Medium Kick pressed down and dash forward or backward.

If you land a L3 focus attack or any other focus that crumples, you should immediately dash towards your opponent and execute your most powerful combo, ultra, etc. This is a great chance to deal damage.
Comment: @Dhaval Yes, Gouken does have a parry move, but it's a special move, not a standard mechanic that everyone has in the game.
Comment: you can also do focus absorb instead of attack, you don't necessarily have to finish the attack animation.
Comment: i think GOUKEN has parry in Street Fighter IV .. is it not ??
Comment: @z' You mean a focus dash cancel, once you hold the buttons down, you can't stop the attack unless you dash cancel.
Comment: @Joetjah Any special move, super, or ultra is performed that is a reversal (done on the first frame of a wake up), it has the armor breaking property.  You might want to add that to the last bullet point.  Also, you'll want to include Red Focus for Ultra Street Fighter 4.

How does parry work?


L2TP VPN is not working on Ubuntu 20.04. Same credential is working fine with Ubuntu 18.04

Question: L2TP VPN is not working on newly installed Ubunut 20.04 and 20.10. Credentials are correct and same is working with Ubuntu 18.04
Comment: Viewing the output of `sudo journalctl --unit=NetworkManager` after a failed connection would be useful to determine what is going wrong.
Comment: Even I format and reinstall ubuntu 20.04 without any other software, only required update installed, It is not working.
Answer: The package network-manager-l2tp is required.
You may have to install it:
sudo apt install network-manager-l2tp

I hope it helps
Comment: Well! I have already tried and installed it. but it doesn't work
Answer: I was facing this myself in Ubuntu 20.04 and 21.04, and a simple one-liner solved all requirements necessary for my L2TP/IPsec setup to work properly:
sudo apt install --install-suggests network-manager-l2tp-gnome

This installs all packages mentioned in the previous answers, too. Endpoint to connect to is a Ubiquiti EdgeRouter ERLite-3.
Comment: This worked for me on 21.10. `network-manager-l2tp` wasn't enough
Answer: Check your log i suspect you may need to install these as well if the dependancy is not met:
 sudo apt install libstrongswan-standard-plugins libstrongswan-extra-plugins


Entity Framework 6 Code First - Multiple Model/Configurations

Question: After many fruitless searches I have decided to put my head above the parapet. I am building an EF6 code first application for an embedded device.
I have successfully followed many references to enable me to create SQL CE files in the folder locations I need.
However, I need to have two separate models running at the same time
1 - Admin model deals with common things like user logins and generic details.
2 - Project specific model where the real work gets done.

The concept is that the Admin database file resides and remains on the
  device, but the project database file can be passed from one device to
  another.

Is it possible to have two different model databases open at the same time in EF6?
If so is there a good reference site that my search terms have not yet found that will offer advice appropriate to my use-case?
Thanks folks.
Answer: I have been able to solve my own question now having found a new article to refer to Multiple Model EF 6 Data points
Read the article on how to solve my question and other variants of similar problems. The key to solving this problem was to specify separate folders for each context migration when commanding the NuGet Package Manager Console. Then in the initialiser for each context, refer to the configuration in the appropriate migration folder. Rather than repeating here, please see the article on MSDN I linked to as all the information I needed was in there, plus lots more.


Invalid 'reference' directive syntax error when referencing angular 1.5

Question: I have upgraded to Typescript 2.0.3 yesterday and updated the reference path to
/// <reference types="angular" />

after installing the typings for Angular 1.5x using the following command
npm install -s @types/angular

I get the error when I build the project and the error doesn't go away.

Invalid 'reference' directive syntax

How does one fix this?
/// <reference types="angular" />
/// <reference types="d3" />

(function () {
    'use strict';

    var app = angular.module('charts', []);

    app.controller('mainCtrl', function mainCtrl($scope, appService) {

        var vm = this;

        vm.data1 = [1, 2, 3, 4];
        vm.data2 = [4, 5, 7, 11];
        vm.update = function (d, i) {
            vm.data1 = appService.GetRandomData();
            console.log('new data1', vm.data1);
        };

        vm.update2 = function (d, i) {
            vm.data2 = appService.GetRandomData();
            console.log('new data2', vm.data2);
        };
    });

    app.directive('barChart', function ($timeout) {
        var chart = d3.custom.barChart();
        return {
            restrict: 'E',
            replace: true,
            scope: true,
            bindToController: {
                data: '=',
            },
            controller: 'mainCtrl',
            controllerAs: 'ctrl',
            link: function (scope, element, attrs, ctrl) {
                var chartEl = d3.select(element[0]);

                chartEl.datum(ctrl.data).call(chart)
            }
        }
    });

    app.directive('chartForm', function () {
        return {
            restrict: 'E',
            replace: true,
            controller: 'mainCtrl',
            templateUrl: 'chartform.html'
        }
    });

    app.service('appService', function () {
        this.GetRandomData = function () {
            var rdata;

            rdata = d3.range(~~(Math.random() * 50) + 1).map(function (d, i) {
                return ~~(Math.random() * 100);
            });

            return rdata;
        }
    });

} ());

Comment: Please post actual code, not pictures of it
Comment: I have added the code.
Answer: I was getting this error in the build server, VSTS.
Upgrading the type script version resolved my issue.
In package,json: changed from
"typescript": "2.8.3"

to
 "typescript": "3.5.1"

Answer: I have updated the typescript path in workspace settings file .vscode/settings.json to point to the latest typescript version. This will make VS Code to use the latest version typescript.
{
    "typescript.tsdk": "C:\\Users\\UserName\\AppData\\Roaming\\npm\\node_modules\\typescript\\lib"
}

I didn't assume this to be the problem because when I run tsc -v in the integrated terminal, I got 2.0.3.
Now I am onto fixing the compiler errors.
Helpful links:

Can I use a relative path to configure typescript sdk?
"Invalid 'reference' directive syntax" Typescript2 @types references
Answer: For the mac people out there, if you install TypeScript globally, your path looks like this:
  "typescript.tsdk": "/Users/me_me_me/.nvm/versions/node/VERSIION/bin/tsc"


What is the Fb.ui feed picture size limits?

Question: I'm using the Fb.ui feed and I'm trying to find the picture size limits/requirements. Not all of my images appear using the feed, and I'd like to know exactly what the image requirements are. This is not well documented.
Answer: I'm pretty sure the open graph image rules apply:

An image URL which should represent your object within the graph. The
  image must be at least 50px by 50px and have a maximum aspect ratio of
  3:1. We support PNG, JPEG and GIF formats. You may include multiple
  og:image tags to associate multiple images with your page.

What is the size of the image you are unable to post?
Comment: 200x200 -> it is downsized to 90x90
Answer: From my testing, the max size is 320x320.  It'll keep your aspect ratio within those bounds.
Comment: Hey can you mention how you are doing this?
Comment: If I remember, I made two example images, one a super tall portrait and the other a super wide landscape and then just saw what FB did.


kernel crash when trying to free the skb with `nlmsg_free(skb_out)`

Question: I'm developing a kernel module which send messages to user space via netlink.
To create a message (message to send): skb_out = nlmsg_new(msg_size,0);.
After sending the first message and before sending the second one, I tried to free the skb_out with nlmsg_free(skb_out) but this function cause a kernel crash.

How to fix this crash ?

or

Are there any other alternative to fre the skb_out after the send of the message?

here after the source code:
            skb_out = nlmsg_new(msg_size,0);
    if(!skb_out)
    {
        printk(KERN_ERR "Failed to allocate new skb\n");
        return;
    }

    nlh=nlmsg_put(skb_out,0,0,NLMSG_DONE,msg_size,0);
    NETLINK_CB(skb_out).dst_group = 0; /* not in mcast group */
    strncpy(nlmsg_data(nlh),msg,msg_size);
    res=nlmsg_unicast(nl_sk,skb_out,pid);
    if(res<0)
    {
        printk(KERN_INFO "Error while sending bak to user\n");
    }

    nlmsg_free(skb_out);

Answer: You're not allowed to free the skb after you've sent it. nlmsg_unicast() will take care of that.
The reason is fairly simple: once you send the message it can be queued in the netlink socket for a while before anyone reads it. Just because nlmsg_unicast() returned it doesn't mean that the other side of the socket already got the message. If you free it before it's received you end up with a freed message in the queue, which causes the crash when the kernel tries to deliver it.
Simply allocate a new skb for every message.
Comment: I need your help: http://stackoverflow.com/questions/23852866/netlink-giving-kernel-panic
Comment: @kristof-provost what if for any reason nlmsg_unicast() fails in sending the message? If you have a module that produces a burst of packets, sometimes nlmsg_unicast() fails with -EAGAIN. How to handle such cases?


Show navigation drawer menu item only when a Fragment is shown

Question: I am trying to show a button in the actionbar when a Fragment is shown and to hide the button when the other Fragment are shown.
I Override the onCreateOptionsMenu method:
@Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        inflater.inflate(R.menu.main, menu);
        MenuItem item= menu.findItem(R.id.action_example);

         item.setVisible(true);

        super.onCreateOptionsMenu(menu,inflater);
    }

And use setHasOptionMenu(true):
@Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setHasOptionsMenu(true);
        }

I have done a test and I noticed that initially the button doesn't appear in the other Fragment , but after I open the Fragment in which I put this code above, the button is shown also in the other Fragment.
Comment: 2006 you have to use sethhasOptionMenu() for that fragment.make sure u are replacing the fragment not as stack
Comment: @Asthme the problem is when i use this code to replace the Fragment: `fragmentManager.popBackStack();
   fragmentManager.beginTransaction()
      .replace(R.id.container,SceltaDiete.newIstance(position + 1))
      .commit();`
Comment: try setHasOptionMenu(false) or create empty menu.xml with no items and setHasOptionMenu(true)..Please try and tell me
Comment: @Asthme I try your solution but it didn't work :(
Comment: use menu.clear() in onCreateOptionMenu(); in first line.
Answer: What you are missing is removing the optionsMenu in the onDestroy of the fragment. The behaviour you describe is logical with your code: when the Fragment is created you also create the options menu. It will not automatically be destroyed when the Fragment is destroyed.


matlab count rows contain same elements in matrix

Question: I have a matrix like this:
A = [1   2   3
     3   4   5
     6   8   7
     7   9   11
     12  13  15
     17  18  19
];

How can I count rows that contain same element? In this case it  will result 4: row 1 and row 2 contain 3; row 3 and row 4 contain 7.
thank you...
Comment: No, the conditions I have doesn't allow that..
Comment: If you can't have duplicates on a single line as you say, and each row may only have duplicate values with one other row: `2*(numel(A) - numel(unique(A)))`?
Answer: A = [1   2   3
 3   4   5
 6   8   7
 7   9   11
 12  13  15
 17  18  19
]
B = unique(A)
L = length(B)
Z = []
R = 0
for t=1:L
  [C,D] = ismember(A,B(t))
  SS = sum(sum(D))
  if(SS>1)
     Z(end+1) = B(t)
     R = R + nnz(sum(D,2))
  end
end

at the end of this, the vector Z will contain all repeated values
R will give you the total number of repeated rows
This has been done quite roughly. but with a bit of effort you can improve this code by eliminating the loop somehow....
Hope it helps
Comment: Hey Phoenix small advice: when you use `sum(sum(2Dmatrix))` you can also use `sum(2Dmatrix(:))`. It's a more general way to sum a matrix along all dimensions.
Comment: @obchardon Thanks very much! I never thought of that trick. It will make my future codes a lil bit better! Especially when you are not sure of the dimension of the matrix
Answer: One solution, not really optimized but it will work fine if your matrix is not that big.
A = [1   2   3;
     3   4   5;
     6   8   7;
     7   9   11;
     12  13  15;
     17  18  19];

for ii = 1:size(A,1)
    B = A;
    B(ii,:) = [];
    ind(ii,:) = sum(ismember(unique(A(ii,:)),unique(B)))>0; %check if there is a common value for the row ii.
end

nbrrow = sum(ind) %number of row that contain a similar value.

Answer: Here is a fast way that is also robust for a value repeating in more than 2 rows (but not in the same row):
[~,~,ci] = unique(A);
u = accumarray(ci,1);
row_count = sum(u(u>1))


Serving static css and java script while using parameters in Golang using github.com/julienschmidt/httprouter

Question: So I'm trying to serve static css and java script to an html template, but the parameters are hindering my ability to do so.
here's my code
package main

import (
    "net/http"
    "html/template"
    "github.com/julienschmidt/httprouter"
    "fmt"
)

type PageData struct {
    Chapter int
    Page int
    Source string
}

func main(){

    //I'm using the julienschmidt router because it has parameters that I can use
    //Create a router
    router := httprouter.New()

    //Create the route with the parameters
    router.GET("/:chapter/:page",paramHandler)
    //Create the default route last
    router.GET("/",defaultHandler)

    //get all of the static files working
    router.ServeFiles("/:chapter/:page/*filepath",http.Dir("/js/"))

    //http.Handle("/js/",http.StripPrefix("/js/",http.FileServer(http.Dir("./public/js/"))))
    //http.Handle("/viewjs/",http.StripPrefix("/viewjs/",http.FileServer(http.Dir("./public/viewjs/"))))

    //crate a message telling the user which port the server is running on
    fmt.Println("Now serving on port 8080")
    //Start the server on the specified port
    http.ListenAndServe(":8080",router)
}

func defaultHandler(rw http.ResponseWriter,r *http.Request,p httprouter.Params){
    //Parse the html file
    index := template.Must(template.ParseFiles("public/index.html"))
    chapter := 1
    page := 1
    //Get data from server
    //TODO

    //Test Data
    //defaultPage := PageData{Chapter:chapter,Page:page,Source:"http://lokeshdhakar.com/projects/lightbox2/images/image-4.jpg"}

    //Send the html file to the browser
    fmt.Printf("\nThe chapter is %d and the page is %d",chapter,page)
    index.Execute(rw,nil)
}

func paramHandler(rw http.ResponseWriter,r*http.Request,p httprouter.Params){
    index := template.Must(template.ParseFiles("public/index.html"))
    //Get the page parameters
    chapter := p.ByName("chapter")
    page:= p.ByName("page")

    //Get data from server
    //TODO

    //send the html to the page
    fmt.Printf("\nThe chapter is %s and the page is %s",chapter,page)
    index.Execute(rw,nil)
}

so basically, I want to serve a different image based on the chapter and page variable (That isn't my current problem, but it is the reason I need the url parameters), but the router thinks that the static file path (the one I use to serve js and css) is full of parameters. I tried to just add "/foo/foo/" to the begging of every path in the html, but that didn't work either
Here's a sample output from the console:
from "/"
The chapter is 1 and the page is 1
The chapter is viewjs and the page is index.js
The chapter is viewjs and the page is index.js

from "/1/2"
The chapter is 1 and the page is 2
The chapter is viewjs and the page is index.js
The chapter is viewjs and the page is index.js

here's the repository with all of my files so you can see my project structure.
Thanks!
Comment: Currently there are no images. The /js/ folder contains things like reactjs and jQuery sources. The viewjs files are my react classes. Those are what I'm having trouble serving at the moment. Sorry if my wording confused you. I'll change that. Thanks.
Answer: I would suggest that you restructure your project files
├── main.go
├── templates/
│   ├── index.html
├── assets/
    ├── js/
    └── react/

Use the following handlers
router.GET("/", defaultHandler)
router.GET("/chapters/:chapter/pages/:page", paramHandler)
router.ServeFiles("/assets/*filepath", http.Dir("assets"))

And change your script sources to include the full path, e.g.
/assets/js/react/build/react.js

Things would be a lot easier if httprouter could match routes like
router.GET("/:chapter/:page", paramHandler)
router.ServeFiles("/*filepath", http.Dir("assets"))

But

Only explicit matches: By design of this router, a request can only match exactly one or no
  route.

https://github.com/julienschmidt/httprouter#features


Replacing a 1963 GE 125 Amp, 240V service panel

Question: In a recent question I asked about finding parts for my old 1960s electrical panel. I've given up on finding parts, and this new question is about replacing it with a new, modern panel:
One of the lugs burned up in my house's service panel. It was installed when the house was built in 1963. The lug is integral to the panel, and the panel is no longer available. I've looked for used panels of that model -- a GE TRX2012F -- but did not find any. So I'm told I need a new service panel.
I want to do the replacement myself. I've done minor DYI electrical work but nothing this involved. I'm reading and watching what I can find on replacing electrical panels. Can anyone offer answers to any of my questions below?
1) First, any suggestions on what panel to choose? The current one is installed flush in an unfinished stud wall. But surface-mount on top of the studs sounds fine to me too. There is about 14.5" between the studs, and they are about 3.5" deep. There is no real limit on height except that some bolts for the meter pipe extend into the wall about 6 - 7 inches above where the feeder wires come out of the wall from the meter.
2) Next, should I expect to reuse the breakers, or do I need new ones? If new ones, can you suggest what I need?
3) Regarding the fat black wires running from the breaker at the upper left down to between breakers below -- would I be duplicating that, or is that done differently in today's panels?
4) I'll need to know how to shut off the power to the panel box. If I understand correctly that would be done at the meter. And since the meter is locked by the power company, I believe that would mean calling them and asking them to turn it off, then asking them to come out and turn it back on when I'm done. Is that correct?
5) Are there any other components, or any special tools, I'll need?
Thanks! Pictures below:

More pictures:
https://i.stack.imgur.com/7Zz8V.jpg
https://i.stack.imgur.com/OMDuv.jpg
https://i.stack.imgur.com/HqDY4.jpg
https://i.stack.imgur.com/6pI5w.jpg
https://i.stack.imgur.com/CVbSY.jpg
Comment: Sorry nvm, I now see what you did there..
Answer: Find a GE distributor in your area and have them order you a new INTERIOR for whatever their current product line is that matches your needs. The box dimensions haven't changed enough in 40 years to be a problem, a new interior (and cover) should drop right in.
You also have what's called a "split bus" installed there; the lower section of the panel is protected by a breaker in the upper section. There are two main reasons for this, one of which is not in play here, the other of which is something you need to determine if it applies.
The main reason for a "split bus" panel is to take advantage of what's called the "6 hand rule" meaning that if a firefighter needs to kill all power in your building, they only have to move their hand 6 times. So when a panel doesn't have a "Main Breaker" (as yours doesn't), then the top 6 spaces are all supposed to be 2 pole breakers, and one of those 2 pole breakers then feeds the bottom section where all the single pole breakers are. Your setup already violates that, you have 10 handles up top. Maybe that's because it has been changed by someone who didn't understand, who knows but that is already a violation if that was the original reason.
The other reason for doing a split bus is if you have a backup generator (or now a Solar Power system) in which you only want to power SOME of the loads when under the backup source. That too does not appear to be the case here because that typically needs to have some sort of interlocking system to isolate the unwanted parts of the system when connecting that backup source, and I don't see anything like that. But only you can tell for sure.
So in all likelihood you can get a more standard GE panel interior with enough spaces (20) and that will fit in that box. If it were me, I would get one with a Main Breaker now rather than rely on that 6 hand rule issue and trying to rearrange all of the circuits so that there are only 6 breakers on the upper half, but you may not have enough physical space in the box for that. If that's the case, you may just need to change out to a new box too. But GE has not changed the breakers themselves, so by sticking with GE you can re-use those and save yourself some money.
Comment: It may very well be the case that no interiors with sufficient circuit counts fit that cabinet due to the wire bending space changes in the NEC that have happened between then and now...


Doubt regarding a lemma

Question: So I am going through this paper.
Could someone please explain how they proved this lemma:

Lemma 1.2 Let $I_1,\dots,I_n\subset\mathbb R$ be segments of lengths $\ell_1,\dots,\ell_n$ with midpoints $c_1,\dots,c_n$. Assume the union $\bigcup I_i$ is a segment (i.e. the family of segments is non-separable). Then the segment $I$ of length $\sum \ell_i$ with midpoint at the center of mass $c=\frac{\sum \ell_i c_i}{\sum \ell_i}$ covers $\bigcup I_i$.

P.S. I tried to access the research paper where this is proved but it seems it is not accessible to the public domain.
Thank you!!
Comment: There surely [must be a way](https://en.wikipedia.org/wiki/Sci-Hub) to get access to the [paper](http://dx.doi.org/10.2307/2304537) by Goodman and Goodman.
Comment: I'm not sure but IMO the proof-writing tag is wrongly used for this question.
Comment: @Amelia I have removed it
Comment: @Christoph Oh! I had no idea about this. This is amazing.
Answer: I read  Goodman & Goodman proof and this is a short summery in OP's notations.
Let $\bigcup_{i=1}^n I_i=[a,b]$. We may assume that $I_i=[a_i,b_i]$ with $a=a_1\leq a_2\leq a_3\leq\dots\leq a_n$. Then for any $1\leq i\leq n$,
$$c_i-a=a_i+\frac{l_i}{2}-a\leq l_1+l_2+\dots+l_{i-1}+\frac{l_i}{2}$$
which implies that
$$
\begin{align}c-a&=\frac{\sum_{i=1}^n l_i c_i}{\sum_{i=1}^n l_i}-a=\frac{\sum_{i=1}^n l_i (c_i-a)}{\sum_{i=1}^n l_i}\\
&\leq \frac{\sum_{i=1}^n l_i \left(l_1+l_2+\dots+l_{i-1}+\frac{l_i}{2}\right)}{\sum_{i=1}^n l_i}\\
&=\frac{\sum_{1\leq j<i\leq n} l_i l_j+\sum_{i=1}^n\frac{l^2_i}{2}}{\sum_{i=1}^n l_i}=\frac{(\sum_{i=1}^n l_i)^2}{2\sum_{i=1}^n l_i}=\frac{\sum_{i=1}^n l_i}{2}
\end{align}$$
which means that $c-\frac{\sum_{i=1}^n l_i}{2}\leq a.$
In a similar way, we show that $b\leq c+\frac{\sum_{i=1}^n l_i}{2}$ and we are done,
$$\bigcup_{i=1}^n I_i=[a,b]\subset \left[c-\frac{\sum_{i=1}^n l_i}{2},c+\frac{\sum_{i=1}^n l_i}{2}\right].$$

Doubt regarding a lemma


Only shows 10 rows?

Question: global $wpdb;
$args = array(
    'post_type' => 'product_variation',
    'meta_key' => '_stock',
    'meta_value' => '0',
    'meta_compare' => '>'
);

$variationloop = new WP_Query( $args );
echo  $wpdb->num_rows . 'Rows Found
';

while ( $variationloop->have_posts() ) :
    $variationloop->the_post();
    echo '
'.get_the_title().'';
endwhile;

The num_rows indicates 499 rows. But i only get 10 rows displayed. Why?
Comment: [WP_Query documentation](https://codex.wordpress.org/Class_Reference/WP_Query#Pagination_Parameters). Search the page for `posts_per_page`. It doesn't mention a default value but there probably is one somewhere.
Comment: pass posts_per_page in your $args
Answer: Add a new argument:
'posts_per_page' => '-1'

Other questions you may have about $wpdb may be answered here.

Only shows 10 rows?


How do I find the kernel version, Ubuntu release and disk partition information from the terminal?

Question: Which commands will give me information about following using Terminal?

Kernel Version
Distribution version no.
All partition size of the HDD
Comment: `hostnamectl status` will show -kernal version and distribution
Comment: @user44517. that command was not present in 2012.
Answer:
uname -a for all information regarding the kernel version,
uname -r for the exact kernel version

lsb_release -afor all information related to the Ubuntu version,
lsb_release -r for the exact version

sudo fdisk -l for partition information with all details.
For more understandable information regarding paritions, please use commands given in other answers.
Comment: Not correct `uname -a` return all not just kernel version  also `lsb_release -a` return all not only Ubuntu version moreover `sudo fdisk -l` return the block numbers and size and not human readable information
Comment: It's a great answer, however, instead of all the information (-a option switch used in Web-E's answer) you can just get the specific numbers. This is much less confusing for a beginner - For this reason I prefer MrVaykadji and Hadi improvements.
Answer: Kernel Version
cat /proc/version             # detail about for the kernel image version

Distribution Version
lsb_release -a

Partition Sizes
cat /proc/partitions          # for basic sizes
sudo fdisk -l /dev/<device>   # eg /dev/sda

Comment: +1 for the `cat /proc/version`
Answer: Commands:

Kernel Version:
uname -r

Distribution version number:
lsb_release -sr

All partition sizes of the HDD in Terminal:
lsblk -o NAME,SIZE

Example:
Comment: what terminal is that? how did you get that triangle?
Comment: it's a bashrc modification with default unity terminal. The triangle is in the characters table.
Answer: Kernel version is:
uname -r

Ubuntu release version is:
lsb_release -r

All partition size of the HDD in Terminal
df -ht ext4

replace ext4 with your FS type if it's not so

With respect to the marked as answer post:
Not correct uname -a return all not just kernel version  also lsb_release -a return all not only Ubuntu version moreover sudo fdisk -l return the block numbers and size and not human readable information
Answer: Open terminal.  Just press Ctrl+Alt+T on your keyboard to open Terminal. When it opens, run the command below.
sudo fdisk -l; uname -a; lsb_release -a

Answer: uname -r
sudo fdisk -l
lsb_release -a
Answer: To find the exact distribution, that is Ubuntu 16.04.1 or Ubuntu 16.04.3 you would use
lsb_release -d


SQL table access: Many accessing one or one accessing many better?

Question: I am making some SQL tables for books for a digital library. I have a table "book", which stores mostly static information about each book.
My other table is "ownedBook" which stores data about the books in relation to the users that own them in their own collection.
As users read the books, I want to frequently update the database with how much time they have spent looking at each book (in seconds). The question:
Is it more efficient for my sql database to have many users adding their time to the one table's "book" column or should I be recording that time in the "ownedBook" table?
Considering both options: If saved in the "book" table, one row in "book" would be getting updated very frequently with different users adding time(seconds they've spent on a certain book) to one column. That might be bad, but on the other time it would be easy to look up how much time people had spent looking at that book.
On the other hand, if recording this time in the "ownedBook" table, only one row in that would be getting updated at a time and much less frequently, but the task of finding out how much time readers have spent looking at each book would then involve getting all the "ownedBooks" and adding up the time users had accrued in each one.
Any help appreciated!
-Not Aliens
Comment: Can you clarify "frequently"?
Comment: Haven't gotten that far yet, plan is to find a way to save the time spent on a book as frequently as possible while they are online reading it - as I don't know how to send that data upon the user's session expiring- or something like that
Comment: Edit your question and provide sample data and desired results.  I don't understand what "add time" is supposed to be doing.
Comment: alright done. Thanks
Comment: I would go with the second option of updating the `ownedBooks`. Proper indexing and, perhaps, a materialized view (if such a concept is supported in your RDBMS) would help with speedy lookups. Furthermore you can tell each user how much time they've spent reading books, or a specific genre, where if you store on `books` you lose that ability.
Answer: If you only store the total time per book, you lose the information of time spent per book per user. I assume you don't want to lose this information. Going with that assumption, you want to store total time per user per book (in the ownedBook table). I assume you will also want to query the total time per book frequently, so to avoid performance issues, you may want to denormalize the data by also storing the total time per book (in the book table).
Since you are designing this to support high-frequency updates, I suggest having a third table as a queue. Let's call it bookReading. Instead of updating the other tables directly, you would insert a new row into this table for each update coming from a user (i.e. user id, book id, read_started_timestamp, read_ended_timestamp). This should support a high frequency of inserts (don't set up foreign keys for even faster performance). You can then set up a scheduled recurring task (e.g. every five seconds) which processes all accumulated reads in one go: updates the total times in book and ownedBook tables, and removes the processed reads from bookReading.
This should allow you to have good performance on writes as well as on reads (queries).
Answer: I would go with the 2 table options.
1 table for the books, 1 table for who has read and for how long.
Also you need 1 field in each table that is the same, that link the 2 tables together.
It would be a unique field in the books table, perhaps the ISBN number, if you don't have them you can have SQL create a uniqueidentifier for you using newid(). You don't have to show anyone this field.
This helps keeps your data consistent.


Why does my CSS code not work? It is linked correctly but the style rules just dont apply at all

Question: I am just learning to code right now using an online course and I already set up a server and brought a test website online just to test out how it actually looks in the browser. Unfortunately, my CSS just doesn't work although I have uploaded both the index.html and style.css file in the same folder in public-HTML on my server. I have linked the CSS stylesheet correctly I think but it just doesn't work for some reason. This is what it looks like, it does not make any sense at all:
<!DOCTYPE html>

    <link rel="stylesheet" type="text/css" href="style.css">
    <title>home</title>

(coming soon)

-Websites, presenting your company to the world-

Playing around with coding course

Portfolio

Prices

Team

Contact

Elegant Interactive Websites

Beautiful Graphic Design

Seamless Animations

Reliable Databases

Code written in HTML, (some CSS) and JavaScript

This is my CSS code:
html, body {
    margin: 0;
    padding: 0;
    background-color: black;
  }

a {
    color: red;
}

.brand{
    color: red;
    font-size: 300px;
    font-family: cursive;
    background-color: black;
}

h1{
    color: red;
    font-size: 300px;
    background-color: black;
}

Comment: Are the `css` and `html` files in the same directory? The `` states that they must be.
Comment: Use your browser's dev-tools to inspect the elements and see what styles have been applied. Also check for any errors in the _Console_ and _Network_ panels
Comment: No repro ~ https://codesandbox.io/s/shy-dawn-91uuy?file=/index.html
Comment: It seems that your `HTML` and `CSS` do not exist same directory. Please learn how to include external css in HTML file. e.g [link1](https://www.w3schools.com/html/html_css.asp)  OR [link2](https://www.tutorialrepublic.com/css-tutorial/css-get-started.php)
Answer: If your CSS is one folder outside of current directory of your HTML then you might try linking it like this
 <link rel="stylesheet" type="text/css" href="./style.css">


Remove first and last  from string

Question: I have this html code :

Visit
 stackoverflow
 or jsfiddle

<button onclick="myFunction()">Try it</button>

function myFunction()
{
    var str = document.getElementById("demo").innerHTML;
    var res = str.replace("
","");
    document.getElementById("demo").innerHTML=res;
}

I want to remove  first and last
 from it not all of them.
this is my jsfiddle http://jsfiddle.net/3W83m/
Answer: Here's a solution to the general problem you ask:
var arr = str.split(/
/);
var res = arr[0]+arr.slice(1,-1).join('
')+arr.slice(-1);

This answer doesn't require the first and last child to be
.
If you just want to remove
 at the ends, then it's easy :
var res = str.replace(/^\s*
|
\s*$/g,'');

Demonstration
Answer: You can try this way, if you are sure that first and last element child are br: Other wise you can loop through to test for the first and last br and remove them.
function myFunction() {
    var elem= document.getElementById("demo");
    elem.removeChild(elem.firstElementChild);
    elem.removeChild(elem.lastElementChild);
}

Demo
To ensure it removes only fist and last brs and not any other element if first/last one is not a BR, you can add a simple check for safety.
function myFunction() {
    var elem= document.getElementById("demo"),
        fChild = elem.firstElementChild,
        lChild =elem.lastElementChild;

if(fChild.tagName === "BR")
    elem.removeChild(fChild);
if(lChild.tagName === "BR")
    elem.removeChild(lChild);

}

Answer: first
:
if (myString.indexOf('
') > 0) {
  myString = myString.slice(myString.indexOf('
')+5, myString.length);
}

last
:
if (myString.lastIndexOf('
') == myString.length - 5) {
  myString = myString.slice(0, -4);
}

Remove first and last  from string


Wall mounted Heated towel rail plug not marked

Question: Looking for correct wiring configuration as this plus has not colour coding like others I have wired. I sure there must be a standard for these.

[]1
Comment: I am quite sure that on a focused image you could see something
Comment: 'Towel rail plug'? It looks like a cable outlet - not a plug. (1) What is it - a switch (not a good idea in a bathroom) or a fused outlet? (2) What are you connecting to? (3) Can you give us an in-focus photo of both sides of it? (4) What country are you in? Edit your question rather than comment.
Comment: Are the screw terminals labeled? Is one green, one silver, and one gold?
Comment: That looks like an American  shape of faceplate. Which is a bit worrying given the EU standard wiring colours. Whatever you are doing, first check voltage compatibility.
Answer: Brown/blue and green with a yellow stripe are an EU standard.
More information on the coloring scheme can be found here:
Wiring color codes
Brown is the phase (hot; black in the US), and blue is the neutral (white in the US). The green/yellow wire is the ground wire (green or bare in the US).
Answer: What they said.
Plus:
Do check that towel rail rated voltage and local mains voltage are compatible.
Wire colours are as noted elsewhere.
Brown: Phase / Hot / Live
Blue:  Neutral /Return
Green-yellow: Ground.
Switch can be checked with Ohm meter and MUST be.
Bottom left two contacts are PROBABLY a SPST on/off switch BUT contact on right may be a "common" for a SPDT switch.
Most likely BUT NOT CERTAINLY terminal on right is a "loop" contact isolated from switch proper, used for joining mains and load neutrals together.
If so, usual use is to:

Feed Phase via switch.
Phase in to one left hand contact,
Phase out to load on other left hand contact.
Use floating loop terminal on right to join Neutral lead from load to Neutral lead from mains.

In such an arrangement earth is not dealt with BUT SHOULD BE USED.
3 important points:

Use an Ohm meter to verify what all switch contacts do
Use an Ohm meter to verify what all switch contacts do
Use an Ohm meter to verify what all switch contacts do

Also, ensure that ground/earth on rail connects to mains ground - that your towel users' lives may be long on the land.

The diagram below seems likely to be correct, but may not be. Having a test meter is a near essential when doing such work. Small DMM's (Digital Multi Meter) are available at low cost. The main requirement here is the ability to measure on / off continuity of a switch. In this case, viewing what is written on the switch adjacent to each terminal would help greatly.
Comment: Thanks Russell its a great help. so basically the feed from the house live wires split the switch, so positive from house mains would go to right loop. positive from heated rail go to left and 2 neutrals bottom. or am I not correct. I don't have a metre at this time.
Comment: @Glen Completely wrong, alas. A meter costs very little at entry level and is an almost essential thing to have in such situations. | Follow what I said above and you should be OK. Do what you said and it goes bang. I'll edit my text and add a few extra words to make it clearer - the instructions per se will not change.


Is there any point in delaying restart?

Question: I'm not 100% certain on how it works but I believe that on completing level 30 you get rewarded with 30 helium which when you restart you can spend on upgrades.
I believe that I was also presented with an option to continue and I could restart later. Is that right?
If so, what is the point in continuing?
Answer: After you unlock the Portal (by defeating the boss - "Mega blimp" of the map "Dimension of Anger"), it also mentions that you can now gain helium by killing "regular blimps", which means you get helium by completing any subsequent zones. You get the map by defeating the boss of Zone 20.

Is there any point in delaying restart?


Deserialize JSON Facebook feed using Gson

Question: I have a JSON response from Facebook with the following structure:
{
    "data": [
      {
         "id": "105458566194298_411506355589516",
         "message": "...",
         "type": "status",
         "created_time": "2012-11-25T17:26:41+0000",
         "updated_time": "2012-11-25T17:26:41+0000",
         "comments": {
            "count": 0
      },
      {
         "id": "105458566194298_411506355589516",
         "message": "...",
         "type": "status",
         "created_time": "2012-11-25T17:26:41+0000",
         "updated_time": "2012-11-25T17:26:41+0000",
         "comments": {
            "count": 0
      }
    ]
}

I'm trying to deserialize it using the Gson library:
public class FacebookPost {
    public String Message;
    public String Created_time;
}

Gson gson = new GsonBuilder().create();

Type listType = new TypeToken<ArrayList<FacebookPost>>() {}.getType();

ArrayList<FacebookPost> userList = gson.fromJson(responseJsonString, listType);

This would obviosuly just work if the response wasn't wrapper in the "data": [ ] - container. But how do I tell gson to look inside data in the JSON response?
Answer: You should do something like that:
InputStream source = retrieveStream(url);
Gson gson = new Gson();
Reader reader = new InputStreamReader(source);
APIResponse response = gson.fromJson(reader, APIResponse.class);

With:
Public class APIResponse{

    ArrayList <FacebookPost> data;

    public class FacebookPost {
        public String message;
        public String created_time;
    }
}


Flotr & Server Side Processing

Question: Is there any way to send object / image content type created by Flotr (http://code.google.com/p/flotr/) to server side scripting.
For comparison, with protovis () we can send SVG generated to server side servlet to have PNG / JPG result with Apache Batik.
Appreciate for any clue.
Regards,
Dino
Answer: As far as I can tell, Flotr generates a <canvas> HTML element image, which you can convert to base64 encoding with the canvas.toDataURL() method.
Then, it should not be painful to send it to web server with an AJAX HTTP POST call.
Cheers,

Flotr & Server Side Processing


Localisation of an integral domain

Question: My question started as follows:
An intermediate ring $\Bbb Z\subseteq R\subseteq\Bbb Q$ arises as a localisation.
In particular it holds that $R=S_{P}^{-1}\Bbb Z$, where $S_{P}$ is the multiplicative
subset of $\Bbb Z$ generated by the primes which are invertible in $R$, i.e. the
set of primes $\{p:1/p\in R\}$. The crucial part to prove this is the property
$$\forall a/b\in\Bbb Q \ \ \ \ (a/b\in R \iff 1/b\in R) \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ (*)$$
which follows easily from the Bézout identity.
Now, I want to find an intermediate ring $\Bbb Q[x,y]\subseteq R\subseteq\Bbb Q(x,y)$ which
is not a localisation of $\Bbb Q[x,y]$. So I came up with the ring $\Bbb Q[x,y,x/y]$, in which
while it holds that $x/y\in R$, I managed to prove that $1/y\not\in R$.
So if I assume that $R$ is a localisation of $\Bbb Q[x,y]$ at a multiplicative closed subset $S\subseteq\Bbb Q[x,y]$ then I am pretty sure that
taking into account the fact that $\Bbb Q[x,y]$ is a domain we have the property $(*)$, which will end the proof. However, I cannot prove it until now. So I made up the conjecture below:
Conjecture: Let $A$ be an integral domain and $S\subseteq A$ a multiplicative subset of $A$. Then for every $a/b\in \mathrm{Frac}(A)$ it holds that $a/b\in S^{-1}A\iff 1/b\in S^{-1}A$.
Comment: Have you considered your conjecture for integral domains which are not unique factorization domains?
Comment: Not all subrings of $\mathbb{Q}$ arise simply by inverting a set of primes. Consider, for example, $\mathbb{Z}[2/3]$.
Comment: Yeah, I meant rings with identity.
Comment: See [here](https://math.stackexchange.com/a/194719/242) for citations to works studying such proiperties.
Answer: As written, the conjecture is false.
Let $A=\mathbb{Z}$ and $S$ the set of odd numbers.  Observe that $S$ is a multiplicatively closed.  We also observe that $2/2\in\operatorname{Frac}(A)$ is in $S^{-1}A$ since $2/2=1/1$ and $1/1\in S^{-1}A$.  Note, however, that $1/2\not\in S^{-1}A$ since if $1/2=a/s$ with $a\in A$ and $s\in S$, then $2a=s$, but the LHS is even while the RHS is odd.  A contradiction.
Now, one might argue that this example is unfair since $2/2$ is not in lowest terms.  However, if $A$ is not a unique factorization domain (or worse), lowest terms might not make sense.

Localisation of an integral domain


Fallout 4 - Materials not being shared

Question: I have the Local Leader perk installed and have been enjoying building up settlements all over the Commonwealth & the Island, sharing the resources though supply lines. Recently I noticed though that some of my settlements are not actually sharing materials. For example, I have 2 shipments of concrete in the workbench at Sanctuary, which is connected to all settlements:

But I am unable to build anything with concrete at Longfellow's Cabin & Dalton's Farm (both on the Island). I thought at somepoint that both these Island settlements were connected to the rest of the grid but it appears they are not. I just started building up Longfellow's Cabin, and assigned him to the Supply Line duty, but it appears there is no concrete shipment avaialable (I actually cant build anything out of concrete).
So my questions are:

Is the Island actually capable of being connected to the Commonwealth through supply lines?
What can I do to make sure settlements are actually connected?
Comment: @RoddyoftheFrozenPeas Yes that is the confusing part. I see many people asking about this. I understand now, but wish the devs would have through this through better.
Comment: Did you actually connect your island settlement with something on the mainland? I can't really tell from your illustration. But yes you can share between far harbor, mainland, and nuka world.
Comment: I think what happened is that I nuked a couple of connecting settlements, and with that the supply connections were broken (even though the connection lines were still present on the map). I essentially had to rebuild 2 entire settlements, and wait around for the caravan settlers to appear so I could reassign them to something else. Its been a major pain in the ass, but I think I am making progress. I am still not 100 if this is the cause for the Island settlements though. But to answer your question, yes the island settlements were connected to Commonwealth ones.
Comment: Ya, something is not right. I just connected Graygarden to Oberland Station and the shipments that are present in the Graygarden workshop inventory are not showing up in Oberland Station, even after the new supply line shows up on the map.
Comment: So it seems while the nuclear material that I have at one settlement is not showing up in the other, I am still able to use the material to make things. What a broken ass system they designed for this. It would be helpful to at least know what is available.
Comment: Do you use settlers or robots for supply lines?
Comment: @A.bakker settlers
Comment: @KalamalkaKid the only thing i can think of is that one of the settlers is in combat, if  supply line settler is fighting the supply line is (temporary) disabled. But this can only happen if you are near the settler.
Comment: Wait -- are you expecting to _see_ the physical material from settlement A in the workshop in settlement B? It doesn't work like that. If you stash something at Sanctuary, you won't magically see that thing in Red Rocket; but you'll be able to use it to build stuff.
Comment: OK I thought that the problem was that you connected the two settlements, but you couldn't _use_ the material stored in one settlement when building in the other. :)
Answer:
What can I do to make sure settlements are actually connected?

Caravans do get occasionally stuck and indeed there are glitches that break them down, it's not a very stable mechanic and I have no definite answer what's causing it. I have some vague memory about power losses in one settlement causing problems, because beacons etc go offline. Or maybe it is missing something else like food or water, so that the caravanner can't work. If a settlement is attacked and you don't respond, raiders will break things up. Including, power, food or water. You'll have to repair the resource if that happens.
You can also try to hunt down the person assigned as caravanner and re-assign them the same route. If they get involved in fights with raiders etc that might also cause problems, but that only happens when the player and the caravanner are both near hostiles.
Also avoiding excessively long routes seems wise, I never had much problems when I just connected all settlements to the closest one and built up a network like that, rather than having most of them go to lets say Sanctuary.

Is the Island actually capable of being connected to the Commonwealth through supply lines?

Yes you can connect to Longfellow's cabin in Far Harbor and also to the gas station on the Nuka World DLC map. It works like any other trade route, though I always picked a settlement near the DLC map. For Far Harbor, the nearest would be "Coastal Cottage" and for Nuka World, "Sunshine Tidings". Not sure if it matters.
Answer: You need to work both ways sometimes theres a glitch where some items appear to link due to modding at this piont i have ten penny one way to sactuary and i cant share workshop items hope that helps

Fallout 4 - Materials not being shared


Database relationship issue

Question: I am having a issue in identifying the relationship I have the following scenario

A teacher can review many paper
A paper can be review by 4 teachers
A teacher can create a paper
A paper can have statuses (under review, approved)
A subject head who is also a teacher will select the teachers to review the paper.
A teacher can have many types (i.e. can be author of the paper, reviewer, subject head, etc)

I have identified the following tables:

Teacher
Paper
TeacherType

Now as teacher can be of many types and many teachers can have same type, the relation is many to many, this will be broken into one to many, so there will be a table TEACHER_TYPE (the junction table). I have to identify each roll of the teacher differently how will I use this, for e.g. a teacher authoring a paper and the same time reviewing paper by some other teacher. So will I use the primary keys in TEACHER_TYPE to record the reviewing and authoring process differently? or the same id in Teacher table with some different approach?
Comment: Information unclear in your specification: does a paper have one status at a time, or several at a time; is historical tracking of paper statuses required; and are all subject heads also teachers.
Answer: I would make a 4th table PAPER_TEACHER, this would make you question much easier.
TABLE TEACHER T_ID
TABLE PAPER P_ID
TABLE TEACHER_TYPE T_ID and TT_Type
TABLE PAPER_TEACHER T_ID, P_ID, AND PT_Status
SELECT *
  FROM PAPER t1
 INNER JOIN PAPER_TEACHER t2 on t1.P_ID = t2.P_ID AND t2.PT_status = "under review"
 INNER JOIN TEACHER t3 on t2.T_ID = t3.T_ID
 INNER JOIN TEACHRE_TYPE t4 on t3.T_ID = = t4.T_ID AND t4.TT_Type = "reviewer"
Where you ask for the PP_status, you can use all kind of things.
Answer: At first glance, one thing that seems to be missing is a link or association table to represent the many to many relationship between teachers and papers.  The table could look something like...
review         <-- this name can be descriptive of the purpose (review)
----------         but is also often just the name of the association
fk_paper_id    <-- foreign key to paper
fk_teacher_id  <-- foreign key to teacher performing review
review_status  <-- one or more columns indicating the status of this review

The teacher types are likely just attributes of the teacher and/or the paper.
Since there is a hierarchy between teachers (subject head, etc) that could also be represented as an attribute of the teacher, and not a separate type.  The table can be self referencing...  for example, an employee table....
employee
--------------
pk_employee_id
name, etc
fk_manager_id     <-- foreign key referencing back to the managing employee

Database relationship issue


How to construct sequence diagrams using reverse engineering in Enterprise Architect for android application

Question: I am new to EA and still learning this tool to generate the sequence diagram using reverse engineering but could not find enough information on this topic. Please help me if anybody knows to create this.
I found out the way to create the class diagram using reverse engineering and that we can do by creating the new model and importing the source project into EA. steps are as mentioned below.

Create a new model
create a new diagram
Go to project tab in EA
Goto source code engineering option
Import source directory

This will import all the java file into EA and will generate the class diagram using reverse engineering.
Next i am looking to create sequence diagram using EA for android application but could not get any information. Please guide me if anyone has done this already or any one want to share information on this.
Thanks in Advance.
Comment: You cannot generate sequence diagrams in EA by reverse engineering (static analysis). You can only generate sequence diagrams by executing your code and tracing the execution.
Comment: @chimp is correct, EA cannot create sequence diagrams from source code. It can create them by recording an actual execution (attaching EA to the process like you would a debugger), but this will only give you a partial view, since it will only follow one branch of 'if' and 'switch' statements, etc.
Comment: Links to 2 tutorials about sequence diagrams using the "Execution Analyzer" are available in http://stackoverflow.com/questions/26460519/code-execution-flow-using-enterprise-architecture
Comment: @chimp, how can you generate sequence diagrams by execution?
Comment: What's the manual say?
Comment: @Uffe Can you please tell me the process of recording as actual execution (attaching EA to the process like you would a debugger). I was asking this only in my question. Thanks for correction my point, I will update my question accordingly.
Comment: There is a whole chapter in the EA help file, under Execution Analyzer, called Recording Sequence Diagrams. You will need to work your way through this chapter. I'm sorry I can't be more helpful but it's something I've only done once, quite a long time ago.
Answer: Generating Sequence Diagrams
Enterprise Architect 11 and 12
This took me days and hours to get right, but now I use this program all the time.

SET UP ENVIRONMENT

Go to 'Analyzer' -> 'Manage Debug Scripts'.
Go to 'Analyzer' -> 'Debug' -> 'Debugger'.
Go to 'Analyzer' -> 'Debug' -> 'Recorder'.
Go to 'Analyzer' -> 'Breakpoints and Markers'

SET UP DEBUG SCRIPT (Java)

In the 'Execution Analyzer' window, Add a new script.
Right-click on the new script that was created in the last step, and choose 'edit'.
In the left pane, Select 'debug' -> 'Platform'.
From the 'Debugger' drop-down menu, select 'Java'.
For 'Default Directory', without the square brackets, put your [project root path]
For 'Application Class', without the square brackets, put [name of package with main class].[main class name]
For 'Java Virtual Machine Options' customize the following script.

jre=C:\Program Files\Java\jdk1.8.0_66\jre\bin\server,-Djava.class.path=.;src;bin;lib\some_3rd_party_library01.jar;lib\some_3rd_party_library02.jar
script components that may be different for you:

The JDK version.
'src' is the folder containing the java source code.
'bin' is the folder containing the class files.
The 3rd party library jar files.

Select the various radio buttons that suit your intentions, i.e. 'x64' and 'Run'.
Click OK.

You may want to check this script at this point by running the debug.
Right-click on the script icon and choose debug.

MARK-UP CLASS FOR ANALYSIS

In the project browser, right-click on a class from which you want sequence diagrams to begin from.
Choose 'Execution Analyzer' -> 'Markup Class for Recording'.
Give this setup a name.
Select the methods from which you want sequence diagrams to begin.
From the 'Marker Type' drop down box, select 'Record Function'.
Choose the class depth of the sequence diagram.
Click OK.

BEGIN RUN-TIME ANALYSIS

On the 'Record & Analyze' window, click on the play symbol.
From the 'Recording Set' drop down menu, choose the name of the configuration saved in step 9.
press OK.

GENERATE SEQUENCE DIAGRAM

During debug execution, at least one method/class trace should have appeard in the 'Record & Analyze' window.

Right-click on a 'Record and Analyze' entry and choose 'Generate Sequence Diagram'

DONE. (feel free to ask further questions.)
Comment: I will check this solution... Thanks for the reply


Inverse Laplace with a irreducible quadratic in the denominator and a 1 in the numerator

Question: Please help me find the Inverse Laplace transform of:
$$F(s) = \frac{1}{s(s^2+8s+4)}$$
After completing the square, I obtained
$$F(s) = \frac{1}{s((s+4)^2-12)}$$
Thank you.
Answer: Using partial fraction decomposition gives
$$F(s) = \frac{1}{s(s^2+8s+4)}=\frac{1}{4}\bigg(\frac{1}{s}-\frac{s}{s^2+8s+4}-\frac{8}{s^2+8s+4}\bigg)$$
$$\therefore F(s)=\frac{1}{4}\bigg(\frac{1}{s}-\frac{s}{(s+4)^2-12}-\frac{8}{(s+4)^2-12}\bigg)$$
Then in order to use
$$\mathcal{L}\{e^{at}\}=\frac{1}{s-a}$$
$$\mathcal{L}\{e^{at}\sinh{(bt)}\}=\frac{b}{(s-a)^2-b^2}$$
$$\mathcal{L}\{e^{at}\cosh{(bt)}\}=\frac{s-a}{(s-a)^2-b^2}$$
we can rewrite $F(s)$ as
$$F(s)=\frac{1}{4}\bigg(\frac{1}{s}-\frac{s+4}{(s+4)^2-12}-\frac{4}{(s+4)^2-12}\bigg)$$
$$=\mathcal{L}\bigg\{\frac{1}{4}\bigg(1-e^{-4t}\cosh{(\sqrt{12}t)}-\frac{4}{\sqrt{12}}e^{-4t}\sinh{(\sqrt{12}t)}\bigg)\bigg\}$$