Roots of square equation, the solution for the value of element K in a series of numbers

Question: I'm facing an informatics problem, math based.
Having this series:
1,  1, 2,  1, 2, 3,  1, 2, 3, 4,  1, 2, 3, 4, 5 ....

i have to efficiently find the value of element from position K;
for example, on position k = 5, element has the value 2
the way to solve this is to solve a square equation like this:
x^2 - x - 2*i

where i stands from k-1 to 1 and we downgrade k until we find a solution which satisfies this:

one root of the equation is higher than 0
it's a natural number

and the value of that element on position k will be k-i
i did that on C++ and works 100%, with help from a friend;
for example, when k = 5 and our i iterator gets the value 3, the equation will be:
x^2 - x - 6

with positive root x1 = 3
and in final, the solution will be k-i -> 5-3 which is clearly 2, the value of the element from position K
i am trying to understand this for hours, but i dont get why the solution of that equation gives us the value from position K
if anybody knows the answer, i'm waiting for it!
Thanks!
Answer: Mon Feb 20 11:57:46 PST 2017
    1    1        1    1
    2    1        1    1
    3    2        2    3
    4    1        2    3
    5    2        2    3
    6    3        3    6
    7    1        3    6
    8    2        3    6
    9    3        3    6
   10    4        4   10
   11    1        4   10
   12    2        4   10
   13    3        4   10
   14    4        4   10
   15    5        5   15
   16    1        5   15
   17    2        5   15
   18    3        5   15
   19    4        5   15
   20    5        5   15
   21    6        6   21
   22    1        6   21
   23    2        6   21
   24    3        6   21
   25    4        6   21

========================================================
  system("date");

  for(int k = 1; k <= 25; ++k)
  {
    int q = IntSqrt( 1 + 8 * k)  ;
    int n = ( q - 1) / 2 ;
    int t = n * ( n+1) / 2;
    int val = k - t;
    if( val == 0 )   val +=  n;
    cout << setw(5) << k  << setw(5) << val  << "    " << setw(5) << n  << setw(5) << t  << endl;

  }

  system("date");

============================================
The triangular numbers are
$$ 1, 3, 6, 10, 15, 21,  $$
and by formula
$$  T_n = \frac{n^2 + n}{2} $$
Your description says that the entry at position $k =T_n$ is $n$ itself. The next several entries are then $1, 2, 3, 4, \ldots, n, n+1.$
So, the first task is to (correctly!) find the largest $n$ such that
$$ T_n  = \frac{n^2 + n}{2}   \leq k.  $$ Then, if $T_n= k,$ the entry is $n.$ If $k > T_n$ but $k < T_{n+1},$ the entry is
$$ k - T_n  $$
All you need, as a separate item, is a C++ function that gives a correct value for
$$  \lfloor \sqrt w \rfloor $$
when $w > 0$ is an integer. We want
$$ n^2 + n - 2 k \leq 0,   $$
$$ 4n^2 + 4n - 8 k \leq 0,   $$
$$ 4n^2 + 4n + 1 - 1 - 8 k \leq 0,   $$
$$ 4n^2 + 4n + 1 \leq 1 + 8 k,   $$
$$ (2n+1)^2 \leq 1 + 8 k,   $$
$$ 2n+1 \leq \sqrt { 1 + 8 k},   $$
$$ 2n \leq -1 + \sqrt { 1 + 8 k},   $$
$$ n \leq  \frac{ -1 + \sqrt { 1 + 8 k}}{2}.   $$
$$ n = \left\lfloor  \frac{ -1 + \sqrt { 1 + 8 k}}{2} \right\rfloor   $$
$$ n = \left\lfloor  \frac{ -1 + \lfloor \sqrt { 1 + 8 k} \rfloor}{2} \right\rfloor   $$
int IntSqrt(int i)
{
  // cerr << "called intsqrt  with   " << i << endl;
  if ( i <= 0 ) return 0;
  else if ( i <= 3) return 1;
  else if ( i >= 2147395600) return 46340;
  else
  {
    float r;
    r = 1.0 * i;
    r = sqrt(r);
    int root = (int) ceil(r);
    while ( root * root   <= i ) ++root;
    while ( root * root   > i ) --root;
    return  root ;
  }
} // IntSqrt

Comment: uhh, that's a good answer, thanks !
which is the relation between (n^2 + n) / 2 with that series? that's what i'm trying to reach.
Comment: got it! thanks a lot ;)
Comment: @GabiMMinimalART I added a short output at the beginning and  the heart of main()
Comment: i have noticed it :) very well explained


Identifying a cluster of low transit speeds in GPS tracking data

Question: I'm working with a GPS tracking dataset, and I've been playing around with filtering the dataset based on speed and time of day. The species I am working with becomes inactive around dusk, during which it rests on the ocean's surface, but then resumes activity once night has fallen. For each animal in the dataset, I would like to remove all data points after it initially becomes inactive around dusk (21:30). But because each animal becomes inactive at different times, I cannot simply filter out all the data points occurring after 21:30.
My data looks like this...
AnimalID  Latitude  Longitude  Speed  Date
99B       50.86190  -129.0875  5.6    2015-05-14 21:26:00
99B       50.86170  -129.0875  0.6    2015-05-14 21:32:00
99B       50.86150  -129.0810  0.5    2015-05-14 21:33:00
99B       50.86140  -129.0800  0.3    2015-05-14 21:40:00
99C.......

Essentially, I want to find a cluster of GPS positions (say, a minimum of 5), occurring after 21:30:00, that all have speeds of <0.8. I then want to delete all points after this point (including the identified cluster).
Does anyone know a way of identifying clusters of points in R? Or is this type of filtering WAY to complex?
Answer: Using data.table, you can use a rolling forward/backwards max to find the max of the next five or previous five entries by animal ID. Then, filter out any that don't meet the criteria. For example:
library(data.table)

set.seed(40)
DT <- data.table(Speed = runif(1:1000), AnimalID = rep(c("A","B"), each = 500))

DT[ , FSpeed := Reduce(pmax,shift(Speed,0:4, type = "lead", fill = 1)), by = .(AnimalID)] #0 + 4 forward
DT[ , BSpeed := Reduce(pmax,shift(Speed,0:4, type = "lag", fill = 1)), by = .(AnimalID)] #0 + 4 backwards

DT[FSpeed < 0.5 | BSpeed < 0.5] #min speed

          Speed AnimalID    FSpeed    BSpeed
 1: 0.220509197        A 0.4926640 0.8897597
 2: 0.225883211        A 0.4926640 0.8897597
 3: 0.264809801        A 0.4926640 0.6648507
 4: 0.184270587        A 0.4926640 0.6589303
 5: 0.492664002        A 0.4926640 0.4926640
 6: 0.472144689        A 0.4721447 0.4926640
 7: 0.254635219        A 0.7409803 0.4926640
 8: 0.281538568        A 0.7409803 0.4926640
 9: 0.304875597        A 0.7409803 0.4926640
10: 0.059605991        A 0.7409803 0.4721447
11: 0.132069268        A 0.2569604 0.9224052
12: 0.256960449        A 0.2569604 0.9224052
13: 0.005059727        A 0.8543111 0.2569604
14: 0.191478376        A 0.8543111 0.2569604
15: 0.170969244        A 0.4398143 0.7927442
16: 0.059577719        A 0.4398143 0.7927442
17: 0.439814267        A 0.4398143 0.7927442
18: 0.307714603        A 0.9912536 0.4398143
19: 0.075750773        A 0.9912536 0.4398143
20: 0.100589403        A 0.9912536 0.4398143
21: 0.032957748        A 0.4068012 0.7019594
22: 0.080091554        A 0.4068012 0.7019594
23: 0.406801193        A 0.9761119 0.4068012
24: 0.057445020        A 0.9761119 0.4068012
25: 0.308382143        A 0.4516870 0.9435490
26: 0.451686996        A 0.4516870 0.9248595
27: 0.221964923        A 0.4356419 0.9248595
28: 0.435641917        A 0.5363373 0.4516870
29: 0.237658906        A 0.5363373 0.4516870
30: 0.324597512        A 0.9710011 0.4356419
31: 0.357198893        B 0.4869905 0.9226573
32: 0.486990475        B 0.4869905 0.9226573
33: 0.115922994        B 0.4051843 0.9226573
34: 0.010581766        B 0.9338841 0.4869905
35: 0.003976893        B 0.9338841 0.4869905
36: 0.405184342        B 0.9338841 0.4051843
37: 0.412468699        B 0.4942280 0.9113595
38: 0.402063509        B 0.4942280 0.9113595
39: 0.494228013        B 0.8254665 0.4942280
40: 0.123264949        B 0.8254665 0.4942280
41: 0.251132449        B 0.4960371 0.9475821
42: 0.496037128        B 0.8845043 0.4960371
43: 0.250853014        B 0.3561290 0.9858652
44: 0.356129033        B 0.3603769 0.8429552
45: 0.225943145        B 0.7028077 0.3561290
46: 0.360376907        B 0.7159759 0.3603769
47: 0.169606203        B 0.3438164 0.9745535
48: 0.343816363        B 0.4396962 0.9745535
49: 0.067265545        B 0.9641856 0.3438164
50: 0.439696243        B 0.9641856 0.4396962
51: 0.024403516        B 0.3730828 0.9902976
52: 0.373082846        B 0.4713596 0.9902976
53: 0.290466668        B 0.9689225 0.3730828
54: 0.471359568        B 0.9689225 0.4713596
55: 0.402111615        B 0.4902595 0.8045104
56: 0.490259530        B 0.8801029 0.4902595
57: 0.477884140        B 0.4904800 0.6696598
58: 0.490480001        B 0.8396014 0.4904800
          Speed AnimalID    FSpeed    BSpeed

This shows all the clusters where either the following or previous four (+ the anchor cell) all have a max speed below our min speed (in this case 0.5)
In your code, just run DT <- as.data.table(myDF) where myDF is the name of the data.frame you are using.
For this analysis, we assume that GPS measurements are measured at constant intervals. I also am throwing out the first 4 and last 4 observations by setting fill=1. You should set fill= to your max speed.
Comment: @Splash1199 try `DT[!((FSpeed < 0.8 | BSpeed < 0.8) & date>as.Date("2015-05-15 21:30:00"))]`. This will return a `data.table` excluding (thats what the ! at the beginning does) all of the rows that meet the criteria.
Comment: if your GPS is not at constant times, then you need to rephrase your criteria (i.e not 5 events, but x seconds)
Comment: and finally, `date>as.Date("2015-05-15 21:30:00")` will exlude all times after that point in time (including the next day at say 8am.). You might want to switch that to be within a specific daily time range, something like `(hour(date) > 21.5 | hour(date) < 8)`
Comment: thanks for your answer! What do I do if my GPS data is not taken at constant time intervals?

Also, do you know how I can incorporate the other components of my filter? I figured I could incorporate time my running something like
`DT[FSpeed < 0.8 & date>as.POSIXct("2015-05-15 21:30:00")]`, but is there a way to delete the points after the first identified cluster?

I'm an R novice, so I'm finding this quite challenging.
Comment: actually, that `hour` returns an integer, so it wont work for 30 min intervals.... you'll need to use `as.ITime()`, and then `77400` (21:30 in seconds)
Comment: Hmm, okay. But I want to delete ALL points after the first identified cluster. Not just the ones that meet the condition [FSpeed < 0.8 & date>as.POSIXct("2015-05-15 21:30:00")]


Why i am getting !insertmacro: macro named "MUI_DEFAULT" not found error?

Question: I am writing a script in for my installer.i am using ultra modern ui for better look .so i have used following code.
But I am getting error insermacro mui_default not found;
Code:
<code>!insertmacro MUI_DEFAULT MUI_TEXT_COLOR FFFFFF
!insertmacro MUI_DEFAULT MUI_BGCOLOR 3d66ab
!insertmacro MUI_DEFAULT UMUI_TEXT_LIGHTCOLOR FFFF00
!insertmacro MUI_DEFAULT UMUI_BRANDINGTEXTFRONTCOLOR 8b8ca4
!insertmacro MUI_DEFAULT UMUI_BRANDINGTEXTBACKCOLOR eeeef3
!insertmacro MUI_DEFAULT UMUI_LEFTIMAGE_BMP \
    "${NSISDIR}\Contrib\UltraModernUI\Skins\blue\LeftBranding.bmp"
!insertmacro MUI_DEFAULT UMUI_HEADERIMAGE_BMP \
    "${NSISDIR}\Contrib\UltraModernUI\Skins\blue\Header.bmp"
!insertmacro MUI_DEFAULT UMUI_BOTTOMIMAGE_BMP \
    "${NSISDIR}\Contrib\UltraModernUI\Skins\blue\BtmImg.bmp"
!insertmacro MUI_DEFAULT MUI_ICON \
    "${NSISDIR}\Contrib\Graphics\UltraModernUI\Icon.ico"
!insertmacro MUI_DEFAULT MUI_UNICON \
    "${NSISDIR}\Contrib\Graphics\UltraModernUI\UnIcon.ico"
</code>
Comment: Please add some details - what error you got?
Answer: That macro only works after <code>!include "UMUI.nsh"</code> but for the global settings you can probably just use a define:
<code>!define MUI_TEXT_COLOR FFFFFF
...
!define  UMUI_BRANDINGTEXTBACKCOLOR eeeef3

!include "UMUI.nsh"

!insertmacro MUI_PAGE_...
</code>


Integral of a function on a product measure space using Fubini's theorem

Question: I have the following question: Let $(X, \mathcal M, \mu)$ be a measure space, and let $f \in L^p(X,\mu)$ be a nonnegative, real-valued function. Let $\lambda_f: [0,\infty) \to [0,\infty)$ be the distribution function of $f$, defined by
$$\lambda_f(\alpha) = \mu \left\{ x : f(x)> \alpha \right\}.$$
(i) First assume $p=1$. Show that the integral of $f$ is equal to
$$\int_{0}^{\infty} \lambda_f(\alpha) d\alpha.$$
Hint: consider the product measure space $(X \times \mathbb R, \mathcal M \times \mathcal L, \mu \times \lambda)$ where ($\mathbb R, \mathcal L, \lambda$) is the real line with the $\sigma$-algebra of Lebesgue measurable sets and the Lebesgue measure. Relate the integral of $f$ to the set
$$\left\{ (x, \alpha) \in X \times \mathbb R : 0 \leq \alpha \leq f(x) \right\}$$
and use Fubini's theorem.
(ii) In a similar fashion, show that for $1 \leq p < \infty$
$$\| f \|^p_p = \int_0^\infty p \alpha^{p-1} \lambda_f(\alpha) d \alpha.$$
Attempt: I know for part (i) we're aiming for something resembling
$$\int_{X \times \mathbb R} \boldsymbol{1}_{f(x)>\alpha} d\mu(x)d\lambda(\alpha),$$
then we express this as a double integral, use Fubini, and the result follows. However I can't seem to start off, and specifically am having trouble relating the integral of $f$ to the set mentioned above. Any help would be appreciated. Thanks.
Answer: Hint: $$\int_0^{\infty}  p \alpha^{p-1} 1_{\{f(x)>\alpha\}}d\alpha = \int_0^{f(x)} p\alpha^{p-1}  d\alpha = f(x)^p$$


S3 Principal Bucket Policy Permissions

Question: I have a cloudformation template up in an S3 bucket (the url follows the pattern but is not exactly equal to: https://s3.amazonaws.com/bucket-name/cloudform.yaml).  I need to be able to access it from CLI for a bash script.  I'd prefer that everybody in an organization (all in this single account) has access to this template but other people outside of the organization don't have access to the template.  A bucket policy I've tried looks like:
<code>{
"Version": "2012-10-17",
"Id": "Policy11111111",
"Statement": [
    {
        "Sid": "Stmt111111111",
        "Effect": "Allow",
        "Principal": {
            "AWS": "arn:aws:iam::7777777777:root"
        },
        "Action": "s3:GetObject",
        "Resource": "arn:aws:s3:::bucket-name/*"
    }
]
}
</code>
With this policy, I and a couple other people in my office are unable to access the url.  Even when I'm logged in with the root account I'm getting Access Denied.
Also, this change (only setting Principal to *) makes the bucket accessible to anybody:
<code>{
    "Version": "2012-10-17",
    "Id": "Policy11111111",
    "Statement": [
        {
            "Sid": "Stmt111111111",
            "Effect": "Allow",
            "Principal": {
                "AWS": "*"
            },
            "Action": "s3:GetObject",
            "Resource": "arn:aws:s3:::bucket-name/*"
        }
    ]
}
</code>
Obviously the signs point to my Principal field being misconfigured.  777777777 is the replacement for the Account ID I see under the My Account page.
So, do I need to worry about this on the IAM front?  Considering that I am logged in as the root user, I'd guess I should have access to this as long as I put in a bucket policy.  Any help would be much appreciated.
Answer: Short and sweet:
The bucket policy doesn't allow you to do what you want because of a wildcard limitation of the Principal element. Your best bet is to create an IAM group and put all IAM users into that group if they need access.
Long version:
Just to make it clear, any request to https://s3.amazonaws.com/bucket-name/cloudform.yaml MUST be signed and have the necessary authentication parameters or the request will be rejected with Access Denied. The only exception is if the bucket policy or the bucket ACL allows public access, but it doesn't sound like this is what you want.
When you say "everybody in an organization (all in this single account)" I assume you mean IAM users under the account who are accessing the file from the AWS console, or IAM users who are using some other code or tool (e.g. AWS CLI) to access the file.
So what it sounds like what you want is the ability to specify the Principal as
<code>"Principal": {
    "AWS": "arn:aws:iam::777777777777:user/*"
}
</code>
since that is what the pattern would be for any IAM user under the 777777777777 account id. Unfortunately this is not allowed because no wildcard is allowed in the Principal unless you use the catch-all wildcard "*". In other words "*" is allowed, but either "prefix*" or "*suffix" is not. (I wish AWS documented this better.)
You could specify every IAM user you have in the bucket policy like so:
<code>"Principal": {
    "AWS": [
        "arn:aws:iam::777777777777:user/alice",
        "arn:aws:iam::777777777777:user/bob",
        "arn:aws:iam::777777777777:user/carl",
        ...
        "arn:aws:iam::777777777777:user/zed",
}
</code>
But you probably don't want to update the policy for every new user.
It would be easiest to create an IAM group that grants access to that file. Then you would add all IAM users to that group. If you add new users then you'll have to manually add them to that group, so it is not as convenient as what you originally wanted.

S3 Principal Bucket Policy Permissions


How to Add the Split App into Main Full Screen app in SAPUI5?

Question: I am working on a Master Detail application in SAPUI5. I have created the master view containing the list of information. On top of the master section I have placed one button to view the hierarchy information about the list in Full screen.
So my question is how to switch the view from Master-Detail (Split App) to Full Screen.
Comment: Do you want to hide your master, so that the Detail Page has the hole screen? I don't get it
Answer: Instead of using a SplitApp directly, you could use an App with a SplitContainer so you have a structure like this:
- App
  - FullScreenView
  - SplitContainer
    - MasterView
    - DetailView

See a minimal example here: http://plnkr.co/edit/gD8bJk
Comment: @hirse: Your Plunker is VERY enlightening and solved this problem for me. Thanks!
Comment: Thank you so much. But in my application i am not using router functionality.I have a root view called App.view.js and App.controller.js. As you suggested i made the changes on App.view.js. Now sap.m.App is my parent view type. But now i need to add the Full screen view and Split app view with my Main view. How to achieve this?
Comment: Use the Router. Is there any reason not to use it?

Generally you could also copy the behavior by setting the content of the App and SplitContainer in the Controller, but I don't recommend it.
Comment: There is no any specific reason for that. i  will try it out. Thanks
Comment: A notice for a SplitApp component: As of SAPUI5 release 1.48, the split screen layout is deprecated for freestyle applications. https://experience.sap.com/fiori-design-web/split-screen/
Answer: There is a problem, using a SplitApp in a App.
The App needs to be filled with pages, not with a SplitApp. You probably can create a page, set the SplitApp as her content and add it to the App. But believe me, it doesn't look good.
The only solution you have is to disable the App and enable the SplitApp.
I'm doing this with two div-containers:

and control the display elemnt if I want to show the SplitApp:
document.getElementById('content_app').style.display = 'none';
document.getElementById('content_splitapp').style.display = 'inline';
splitApp.placeAt("content_splitapp");

or if I want to go back to the App:
document.getElementById('content_splitapp').style.display = 'none';
document.getElementById('content_app').style.display = 'block';

Hope this helps you


Run SQL script inside Visual Studio

Question: I have a scripted database SQL file that I need to execute inside Visual Studio to create a new database. I am so far unable to locate any function that allows me to do this.
Comment: What do you mean "execute inside visual studio" - that doesn't really mean anything in terms of running an SQL script
Answer: Go to server explorer in VS, right click on server and select run query.
Do you mind telling us why it has to be run inside VS?
In addition, the database projects offers a lot of features that are worth looking at:
http://www.informit.com/articles/article.aspx?p=31764 //old article but still worth reading.
http://www.ssw.com.au/ssw/standards/BetterSoftwareSuggestions/Images/VisualStudio_DataDude_SchemaCompare.gif
http://www.emadibrahim.com/2008/07/10/database-schema-compare-upgrade/
Answer: There is a green arrow of play on the upper left corner of the window query. And down the tabs of the names of open files in VS. Just click to play and ready.

Run SQL script inside Visual Studio


How do I add an outlet between two other outlets?

Question: I would like to place my tv in between two outlets on my wall.  The TV will be far enough from either outlet that I would need to run an extension cord which doesn't seem like a good permanent solution.  To bring power where I need it, I would like to add an outlet between the existing two.
These outlets are on a finished, exterior wall (with the existing outlets and proposed new outlet on the inside).  They are 12/3 Romex (best guess on gauge) and the outlets are all half switched.  I believe that the two outlets I would like to add the new outlet between are in sequence on the circuit though I'm not sure how to confirm this before cutting the wall.
My plan was to cut the hole in the drywall for my new box and outlet and split the romex there for my new outlet.  However, if I cut the romex there, it probably doesn't have enough slack to wire the new outlet and remain connected to the two existing outlets.
So what is the best way for me to add a new outlet in the desired location?  I've seen plenty of tutorials on adding an outlet at the end of a sequence or off of one existing outlet but I haven't been able to find information on my scenario.
EDIT - Additional information:

The walls have a mud swirl finish that will be nearly impossible to match (as far as I know).  Because of this, I'd really like to just add a box.
I do have attic access. Would it be better to run from the first outlet up to the attic and over and down for the new outlet and to reconnect the existing outlet?
Answer: I would run up to the attic, over, and down. Unless you have basement access, it's the only way you'll do this without cutting up the wall. (I also value the absence of cords across my walls.)

Carefully disconnect all wires in one box, removing the outlet and all nuts. Take photos or make notes if you think you'll need them later.
Depending on the box type, remove it by cutting the nails with a small saw. A hacksaw blade in a Vice Grip plier can be useful. If it's a brown fiber box you can break it up with a plier. Remove the box from the wall completely while taking care to not damage your drywall. A couple layers of painter's tape around the opening are a good idea.
From the attic, drill through the double top plate in the same stud bay as the box.
Drop a new 12/2 cable down to the box opening, ideally in front of the insulation but behind the vapor barrier. An assistant is helpful here.
Cut a new hole behind your tv, sized for a remodeler (old work) box. Double check stud locations first. You don't want to have to notch a stud. If you mess up there, a sharp 1" spade bit will make quick work of the stud. Be sure to consider your tv mount location as well.
Drill through the top plates in that stud bay as well, and drop other end of the cable down.
Install remodeler boxes at both locations and install the outlets. Be sure to use a deeper box at the original location as it'll have many connections.

Be prepared to do some sweating and swearing, but for the aesthetically-minded homeowner it's worth it to have completely clean walls around a hanging tv panel.
Comment: I actually need an outlet lower down for the entertainment center (receiver, media, etc).  Would you still recommend coming down from the attic to get to the normal receptacle height (a foot or so off the floor)?

And to be clear, go up to the attic from the first outlet and then drop down from the attic for both of the other receptacles?
Comment: Yep. What do you mean both? One high, one low? In that case, yep again.
Comment: I made a crude MS Paint diagram real quick: http://imgur.com/a/m8VFU.  Is this what you're suggesting?  In other words, leave the two existing outlets connected as they are and run a new wire from the end of the chain up into the attic and back over to the middle?  (The word "both" in my previous comment refers to the existing receptacle and the new receptacle, that wasn't very clear).
Comment: Yes. I wouldn't disturb the wire between the two existing outlets with this plan. As you said, there's not enough length there. Now that I realize you meant a low location, though, I'd investigate whether you can pull from the existing boxes first. That may be an easier route.
Comment: what would be the best way to do that? That's the part I'm kind of stuck on.
Comment: Seel the answer by Carl Witthoft and the comment by Ed Beal. Extended comment discussions are discouraged.
Answer: The only reason not to use an extension cord is cosmetic.   But if you must :-), then first verify the wiring in the wall is where you think it is. And if there's not enough slack, use the existing wire (after cutting) to pull a longer piece from your new box to the existing boxes and wire those new, longer runs into the existing boxes.
Comment: The problem is going to be the staples at each box on the line you want to cut there is almost never a full foot of wire in a daisy chain and that would be the minimum extra length needed. I would open the wall where you want to add and you may need to open at one of the boxes , use the existing wire as a pull once the staple is removed. When making a splice to pull make sure the splice is not larger than the wire or it may not make through the holes in the studs. Pulling to the new location will provide the length plus some going to the next box.
Comment: I suspected this was the answer.  What's the best way to do this?  Will insulation be a problem?  How do I get the new wire into the old boxes? Or will I need to replace them as well?
Comment: I'm not being snooty, but rather cautious.  I don't want you to get hurt, so: if you're not familiar with code (e.g. all wire ends must be wire-nutted and inside a elec. box) or with proper safety techiniques, I recommend you get a skilled friend or electrician to do this.
Comment: @EdBeal - The wall has a mud swirl finish that will be nearly impossible for me to match so I'd like to avoid opening the wall more than just for the box if at all possible. What staples do you mean?
Comment: @EdBeal - In all the research I was doing, no one mentioned the staples, probably because all of them involved adding a new, fished wire instead of replacing an existing one.  Would it be better to disconnect the existing wire and fish a new one up to the attic to connect all the boxes together?
Comment: Unless there is more to this than I understand, there is no possible benefit to this project that would balance the expense and trouble of accomplishing it. You risk ending up damaging a wall with a unique finish. There is a limit to the number of receptacles and lights allowed by code on a branch circuit. How many are already on this circuit?
Comment: The original mud swirl finish was done *after* the holes for the electrical boxes were cut. You would be diminishing the artistic construct of the artisan who created it. Maybe he went on to become, or might later be recognized as, a major artist and each of his creations quite valuable. Don't risk being recognized as someone who wrecked a valuable work of art. Think before you act on this!
Comment: @jim Stewart residential doesn't have the maximum # per branch circuit although my county uses the commercial/ industrial and the 50-80% rule. I have been flamed on this one but agree it should be the same.
Comment: Going up to an attic or down to a crawl space is much easier especially if you can find a lightly loaded circuit, TV's don't draw much.


How to detect when all directives have loaded?

Question: This is a spinoff of another question (Angular: running function in controller when all directives are loaded) as this one is general.
How can I detect when all angular directives on a page have loaded?
EDIT:
The only way I found so far is by setting up a directive at the highest level which triggers a scope function during it's link function. This works as angular compiles all directives on a page from outer to inner and calls link functions from inner to outer.
Downside: This no longer works if any of the inner directives uses a templateUrl as this will happen asynchronous. This will lead to the outer directives link function running before the inner directives link function. Additionally you'll have to add a directive to all views/includes.
EDIT2:
I found a great answer to a similar question which describes the problem above. And in the comments j_walker_dev mentions the following:
The way i got around this was to use template, like mentioned.
But to inject $templateCache and do template: $templateCache.get('url.tpl.html').

SO question: How to execute parent directive before child directive?
At least with this once can continue using templateUrls as it avoids the asynchronous behavior of template loading in directives.
Comment: do you mean in the index.html?
Comment: On any html side where you include directives. This could also be inside ng-view or ng-include.
Answer: this is how protractor synchronize  :
functions.waitForAngular = function(rootSelector, callback) {
  var el = document.querySelector(rootSelector);
  try {
    if (angular.getTestability) {
      angular.getTestability(el).whenStable(callback);
    } else {
      angular.element(el).injector().get('$browser').
          notifyWhenNoOutstandingRequests(callback);
    }
  } catch (e) {
    callback(e);
  }
};

Knowing that directives in cache will execute synchronously and one that needs to load template from server will execute before the $browser notify, This is how I would do it (if waiting for ajax requests others than for templates is not an issue)
Comment: Sounds interesting, I'll have to take a look. The downside of this though seems to be that this is an internal API and should therefore not be used directly?
Comment: the getTestability 'might' be an internal API (this would mean that protractor in an internal angular project, which is not really the case). The 'notifyWhenNoOutstandingRequests' is actually public on the browser service and can be used freely


Additional harddrive only in read mode

Question: I have additional HDD:
cat /etc/fstab
# /etc/fstab: static file system information.
...
# External 1TB drive for some data
/dev/disk/by-uuid/20A949F121CEADD8 /mnt/20A949F121CEADD8 auto rw,acl 0 0

but its always mounted in read only mode..
Partition type of this HDD is NTFS.
uname -a
Linux My-Tower 5.14.0-1052-oem #59-Ubuntu SMP Fri Sep 9 09:37:59 UTC 2022 x86_64 x86_64 x86_64 GNU/Linux

I tried from other SO but:
sudo mount -o rw,users,umask=000,exec /dev/sdc1 /mnt/hdd_data
The disk contains an unclean file system (0, 0).
Metadata kept in Windows cache, refused to mount.
Falling back to read-only mount because the NTFS partition is in an
unsafe state. Please resume and shutdown Windows fully (no hibernation
or fast restarting.)
Could not mount read-write, trying read-only

what can I do to change it for normal usage?
thanks
Comment: Does this answer your question? [How to make read-only file system writable?](https://askubuntu.com/questions/47538/how-to-make-read-only-file-system-writable)
Comment: You've still not provided any OS/release details; but you've highlighted it's NTFS and also it's in an *unclean* state, thus any attempt to mount it RW is automatically *flipped* to RO to prevent dataloss.  Close the file-system making it clean (on the machine that has left it *unclean*), then you can mount it RW (ie. turn off hibernation etc. which include fastboot on windows which is just a form of hibernation; fastboot resumes from a hibernate file created during upgrades).
Comment: You've not provided any OS/release details, but have you checked system logs for issues that will cause a RW mount to *flip* to RO?  You also didn't provide us with any clues as to what sort of *file-system* you're trying to mount.
Comment: You've added kernel details but still not OS/release details (it's an OEM kernel which would require more specific details about your hardware for us to interpret the results into your *unstated* Ubuntu product/release details, so why not tell us?)  Have you explored system logs for clues?  (*Its the first place I'd look, and I still don't know what OS/product/release details though I now know you're using an OEM kernel on that unstated release*)
Comment: [This link](https://askubuntu.com/questions/11840/how-do-i-use-chmod-on-an-ntfs-or-fat32-partition/956072#956072) to an answer [to another question] at AskUbuntu may help you solve the problem.
Comment: Does this answer your question? [How do I use 'chmod' on an NTFS (or FAT32) partition?](https://askubuntu.com/q/11840/)
Answer: ok thanks guys for help!
I found here how to mount it properly:
How do I use 'chmod' on an NTFS (or FAT32) partition?
then I realized about NTFS issues so I did fix:
sudo ntfsfix /dev/sdc1

and its ok now :)
Comment: That can be a dangerous fix; it'll allow you to mount it RW on a GNU/Linux system like Ubuntu, but can create problems if that drive is later used on a windows system that believes that system is currently *hibernated*, ie. it may ignore any changes working from the image it stored of what the file-system was like before the machine entered the hibernate/off mode.   *Ensure your backups of data on that drive are up-to-date first!  and don't forget the corruption may take time before its noticed if the cause was hibernate/fastboot*
Comment: @guiverc thanks but that Issue was due to that in the past there was some Windows there, not I keep on this HDD only data. So no problem at all :)
Comment: I had the same issue. .In my case, I just needed to shutdown windows properly.

Additional harddrive only in read mode


Kill Process in windows when the download speed drops

Question: I am looking for a code in for instance powershell/cmd to kill a process when the download speed goes below 5 mbps.
The situation is that i am using VLC mediaplayer to do live broadcasting. Often it happens that the broadcast goes down or starts having hickups.
The solution is to just restart. But I only restart it when someone complains about not being able to connect.
I am looking for a script/code to monitor this process and automatically restart/kill it when the download speed goes below a certain level or isn't consistent.
Answer: Implying VLC reads the content from disk and the speed matches its outbound network speed you can use a disk read speed process performance counter measured for 1 second:
@echo off
setlocal enableDelayedExpansion

set LIMIT=500000
set PROCESS=VLC

:LOOP
set line=0
for /f "delims=, tokens=2" %%a in ('typeperf -sc 1 "\Process(%PROCESS%)\IO Read Bytes/sec"') do (
    set /a line+=1
    if !line!==2 (
        set speed=%%a
        set speed=!speed:"=!
        for /f "delims=. tokens=1" %%b in ("!speed!") do set speed=%%b
        if !speed! LSS %LIMIT% (
            taskkill /f /im %PROCESS%.exe
            call RUN-VLC.bat
        )
    )
)
goto LOOP

Assuming 5mbps is 500kBps the LIMIT is set accordingly to 500000.
Comment: Thanks for replying but it is a network activity nit a IO activity. So actually nothing is being stored or written to the discs. If this check could be performed with the networkadapters or some sort than it would work. but if i look in the taskmanager VLC has no IO activities only Network.
Comment: If VLC is the only process using the network bandwidth then only the counter name should be changed, which is trivial.
Comment: To what should the counter name changed? And vlc is not the only application using the bandwith so it should be application specific.
Comment: There is no application specific network counter. To view the entire list run `typeperf -q`.
Comment: The workaround for the logic above is to store the stream locally while broadcasting and restart the stream every 24 hours to prevent a full disk.

And while storing the bitrate should be the same as while streaming. So during the stream if a hickup happens than it should stop recording also, which means no IO activity and this could result in a kill...

But this is the only way i suppose if it cannot be covered otherwise....
Comment: Try asking on [VLC support forum](https://forum.videolan.org/), maybe it's a known problem and there are other solutions.
Comment: VLC has no solution to this. This needs to be done with monitoring software  or scripting...But it seems that the only way to do this is by reading IO activity of the harddisk.
Comment: Apparently [tshark](https://www.wireshark.org/docs/man-pages/tshark.html) may be used to measure traffic on the port used by VLC: `tshark -d tcp.port==8888,rtp` (or `http` instead of `rtp` depending on your VLC stream parameters).
Comment: Great! Will have a look at tshark i guess that will be the


capistrano version 3 upgrade confusing

Question: I am struggling with upgrading capistrano v2 to v3 for 5 days.I am trying to deploy from my local machine to ec2 instance development environment. I can't move further. My trace is here
$cap development deploy:check
INFO [429e612c] Running /usr/bin/env mkdir -p /tmp/my_app_name/ on 70.22.320.14
DEBUG [429e612c] Command: ( RVM_BIN_PATH=~/.rvm/bin /usr/bin/env mkdir -p /tmp/my_app_name/ )
 INFO [429e612c] Finished in 6.208 seconds with exit status 0 (successful).
DEBUG Uploading /tmp/my_app_name/git-ssh.sh 0.0%
 INFO Uploading /tmp/my_app_name/git-ssh.sh 100.0%
 INFO [c3a41f2e] Running /usr/bin/env chmod +x /tmp/my_app_name/git-ssh.sh on 70.22.320.14
DEBUG [c3a41f2e] Command: ( RVM_BIN_PATH=~/.rvm/bin /usr/bin/env chmod +x /tmp/my_app_name/git-ssh.sh )
 INFO [c3a41f2e] Finished in 0.720 seconds with exit status 0 (successful).
DEBUG [c5891dcc] Running /usr/bin/env git ls-remote email@example.com:example/webapp.git
 on 70.22.320.14
DEBUG [c5891dcc] Command: ( RVM_BIN_PATH=~/.rvm/bin GIT_ASKPASS=/bin/echo GIT_SSH=/tmp/my_app_name/git-ssh.sh /usr/bin/env git ls-remote  email@example.com:example/webapp.git
DEBUG [c5891dcc]    /usr/bin/env:
DEBUG [c5891dcc]    git
DEBUG [c5891dcc]    : No such file or directory
DEBUG [c5891dcc]
DEBUG [c5891dcc] Finished in 0.664 seconds with exit status 127 (failed).

config/deploy.rb
set :application, 'my_app_name'
set :repo_url, '.'
set :branch, 'master'
set :scm, :git
set :deploy_to, "/home/ec2-user/capistrano-3/}"
set :ssh_options, {:keys => ["#{ENV['HOME']}/.ssh/my_pem.pem"], :forward_agent =>true}
set :keep_releases, 5
set :rvm_type, :user
set :rvm_ruby_version, '2.0.0-p353'
set :default_env, { rvm_bin_path: '~/.rvm/bin' }
set :whenever_command, "bundle exec whenever"
set :git_shallow_clone, 1
set :deploy_via, :copy

set :log_level, :debug
set :pty, true
set :linked_files, %w{config/database.yml}

SSHKit.config.command_map[:rake]  = "bundle exec rake"
SSHKit.config.command_map[:rails] = "bundle exec rails"

namespace :deploy do

  desc 'Restart application'
  task :restart do
    on roles(:app), in: :sequence, wait: 5 do
      # Your restart mechanism here, for example:
      # execute :touch, release_path.join('tmp/restart.txt')
    end
  end

  after :restart, :clear_cache do
    on roles(:web), in: :groups, limit: 3, wait: 10 do
      # Here we can do anything such as:
      # within release_path do
      #   execute :rake, 'cache:clear'
      # end
    end
  end

  after :finishing, 'deploy:cleanup'

end

config/deploy/development.rb
set :stage, :development

role :app, %firstname.lastname@example.com}
role :web, %firstname.lastname@example.com}
role :db,  %email@example.com}
role :all,  %firstname.lastname@example.com}

server 'email@example.com', user: 'ec2-user', roles: %w{web app}

Capfile
require 'capistrano/setup'
require 'capistrano/deploy'
require 'capistrano/bundler'
require 'capistrano/rails/assets'
require 'capistrano/rails/migrations'

Dir.glob('lib/capistrano/tasks/*.cap').each { |r| import r }

My problems:

My git path is not accepted
ssh key problems

git and ssh keys work with capistrano 2 for the same app I am deploying. Upgrading to capistrano v3 gives a bigger head-ache. What can I do consecutively. Kindly guide me through the correct steps
Comment: No need to `SSHKit.config.command_map` `:rake` and `:rails`, `capistrano/bundler` takes care of that.
Comment: Also, only one of `server` and `role :app/:web/:db` is needed. In this case I think `server` overrides the specific `:app/:web/:db`
Answer: I have spent some time struggling with capistrano3 and here are some hints, probably they can be useful:
1) Official manual capistranorb.com. There are tips about what you should do consecutively. Section about authentication and authorisation also helpful. There are some hints about ssh configuring on workstation and on server. I have followed on this guide and it helps me. Try to build your deploy.rb by following this guide from scratch.
Also helpful guides: guide1, guide2
2) Here is my Capfile. Notice rvm1/capistrano3 and capistrano3/unicorn. Very useful gems.
    require 'capistrano/setup'

    require 'capistrano/deploy'
    require 'capistrano3/unicorn'
    require 'rvm1/capistrano3'
    require 'capistrano/rvm'
    require 'capistrano/bundler'
    require 'capistrano/rails/assets'
    require 'capistrano/rails/migrations'

3) You can try the command:
ssh ubuntu@ec2....amazonaws.com -v

or
ssh email@example.com -v   # from your EC2 server

to understand what happens when you try connect to your EC2 server. Probably the problem with pem key? Create .pub key and try to use it. Don't forget to add it to the ~/ssh/authorized_keys
cat id_rsa_aws.pub | ssh ubuntu@....amazonaws.com "cat >>
/home/ubuntu/.ssh/authorized_keys"

configure your ssh-agent and don't forget to add in your ~/.bash_profile something like this:
eval $(ssh-agent)
ssh-add ~/.ssh/id_rsa_deploy_github
ssh-add ~/.ssh/id_rsa_digital_ocean

If you have problems with ssh, probably you should look at this ssh-guide
Also you can watch my app, where i am using capistrano3. Probably you can find there something for you: #project
P.s. On some VPS git is not installed, so it is good idea to check:
deployer@ec2***.amazonaws.com$ which git

if not found:
deployer@ec2***.amazonaws.com$ sudo apt-get install git

Comment: My remote serverdoes not contain git. So I added git in my remote. Now my problem solved

capistrano version 3 upgrade confusing


How to Put Other People's Pull Request in Eclipse

Question: I am fairly new to the eclipse world. When reviewing other people's pull request from Github, is there a way to get their code in my eclipse like creating a new branch. And get their code running on the my server to test out.
Answer: You'll want to go to the Git Repositories view in Eclipse and specify a new repository to clone, using the url of the repository from Github.  Make sure you specify to fetch all of the branches.  After the clone is complete, select "Switch to" on the repository, and select the option to specify the branch to switch to.  Specify the branch you want, then select "Check Out".  You now have the code for that branch.


is it possible to add action.open url inside the body array in adaptive card?

Question: In my bot application i need to display a action.open Url button in-between the text.I need to Add Action.Open url inside the body tag of the json at the end of date as shown in the image and need to click the url link to do some actions.
Adaptive Card Design Image
is it possible to add the button in-between text or at the top of text inside the body tag.?

<code>{
    "type": "AdaptiveCard",
    "body": [
        {
            "type": "TextBlock",
            "size": "Medium",
            "weight": "Bolder",
            "color": "Warning",
            "text": "Company Name"
        },
        {
            "type": "TextBlock",
            "text": "Meeting Details",
            "wrap": true
        },
        {
            "type": "FactSet",
            "facts": [
                {
                    "title": "Description",
                    "value": "xxx"
                },
                {
                    "title": "Key Note Speaker",
                    "value": "yyy"
                },
                {
                    "title": "Date :",
                    "value": "03/25/2019 12:30:00 PM"
                }
            ]
        },

        {
            "type": "TextBlock",
            "horizontalAlignment": "Center",
            "size": "ExtraLarge",
            "weight": "Bolder",
            "color": "Accent",
            "text": "**************"
        },
        {
            "type": "TextBlock",
            "text": "Meeting Details",
            "wrap": true
        },
        {
            "type": "FactSet",
            "facts": [
                 {
                    "title": "Description",
                    "value": "xxx"
                },
                {
                    "title": "Key Note Speaker",
                    "value": "yyy"
                },
                {
                    "title": "Date :",
                    "value": "03/25/2019 12:30:00 PM"
                }
            ]
        },
        {
            "type": "TextBlock",
            "horizontalAlignment": "Center",
            "size": "ExtraLarge",
            "weight": "Bolder",
            "color": "Accent",
            "text": "**************"
        }
    ],

     "actions": [
          {
            "type": "Action.OpenUrl",
            "title": "Add to Calender",
            "url": "http://adaptivecards.io"
            },
             {
            "type": "Action.OpenUrl",
            "title": " Click here to add more Info ",
            "url": "http://adaptivecards.io"
            }
     ],
    "$schema": "http://adaptivecards.io/schemas/adaptive-card.json",
    "version": "1.0"
}</code>
Answer: Unfortunately, the default location for buttons in AdaptiveCards is at the bottom of the card, and you are unable to change that. However, you can add an image styled how ever you'd like to the card with a selectAction attribute that will submit data associated with the action when the user clicks the image. For more details see the example AdaptiveCard JSON below and the AdaptiveCard Documentation for Images and Select Actions.
Screenshot

JSON
<code>{
    "type": "AdaptiveCard",
    "body": [
        {
            "type": "TextBlock",
            "size": "Large",
            "weight": "Bolder",
            "color": "Accent",
            "text": "Company Name"
        },
        {
            "type": "TextBlock",
            "separator": true,
            "size": "Medium",
            "text": "Meeting Details"
        },
        {
            "type": "TextBlock",
            "text": "Description:"
        },
        {
            "type": "TextBlock",
            "text": "Keynote Speaker:"
        },
        {
            "type": "TextBlock",
            "text": "Date:"
        },
        {
            "type": "Image",
            "selectAction": {
                "type": "Action.Submit",
                "data": "Meeting 1"
            },
            "url": "C:\\Users\\v-thdurn\\Developer\\Node\\Azure\\thdurn-all-channels-src\\resources\\button.png"
        },
        {
            "type": "TextBlock",
            "separator": true,
            "size": "Medium",
            "text": "Meeting Details"
        },
        {
            "type": "TextBlock",
            "text": "Description:"
        },
        {
            "type": "TextBlock",
            "text": "Keynote Speaker:"
        },
        {
            "type": "TextBlock",
            "text": "Date:"
        },
        {
            "type": "Image",
            "selectAction": {
                "type": "Action.Submit",
                "data": "Meeting 2"
            },
            "url": "C:\\Users\\v-thdurn\\Developer\\Node\\Azure\\thdurn-all-channels-src\\resources\\button.png"
        }
    ],
    "$schema": "http://adaptivecards.io/schemas/adaptive-card.json",
    "version": "1.0"
}
</code>
Hope this helps!
Comment: Thank you  tdurnford. I set local path to image URL for button, it is working when i tested in emulator. When i publish the channel image not available. Where i want to store the image.
Comment: You can either configure your project to serve static files or you can use a 3rd party provider like PhotoBucket or Imgur  to host your image for you.


Rescuing error does nothing?

Question: I'm trying to rescue an exception with this method:
def template_deleted
  mailchimp_client.templates.info(mailchimp_id)
rescue Mailchimp::InvalidTemplateError => error
  puts "Template deleted in Mailchimp: #{error}"
  return true
else
  return false
end

And no matter what I use to output the message, whether it's STDERR, STDOUT, log.error, p, puts, or print, nothing gets out to the environment's log. This should definitely be returning an error, because the template definitely doesn't exist in Mailchimp.
When I try the same code in the console I can read the error just fine, so either there's something wrong with the rescuing itself (i.e., my method is returning false which it shouldn't), or there's something wrong with the way I'm outputting it.
Comment: Did you try to use `logger.debug` instead of just `puts`?
Comment: Perhaps the exception that is being thrown is not the one you're expecting. To check the class of the exception, use this model: `begin 1/0 ; rescue Exception => error ; puts error.class end`
Comment: You are not clear. Are you getting the output in the console, but want to direct that to a log instead?
Comment: Sorry, I updated the question to be clearer.
Comment: @peak Yeah, that looks usefull, I'll try that now. Thanks.
Answer: To output something in the log file of the current environment, use the Rails logger like this:
logger.debug "Template deleted in Mailchimp: #{error}"

You can replace the debug method call with any logging level name, that are briefly described in the link above. Also don't forget to make sure you're running in correct environment!
Comment: @CD-RUM you need to read the link in the answer, because you may need to change the log level. Also, make sure you're looking at the correct of the environment that's currently running.
Comment: `loggger` is only present in the Rails scope. If you are trying this on a PORO class, you're doing it the wrong way. You can also access it with `Rails.logger.debug`
Comment: Yeah, that gives me nothing too.
Comment: Whoa, not what I was expecting. It returned `NameError (undefined local variable or method 'logger' for class Whatever`.

Rescuing error does nothing?


Replacing Insulating blanket around oven (patching grease spill)

Question:
I accidentally spilled some oil on the stove which seeped down below the top.  The oil is now in the insulating blanket that surrounds the oven and caught fire while a burner was on.  Can I buy new insulating material, cut out this patch and replace it?  Any help appreciated.
edit:  can I use this product to patch it?
https://www.amazon.com/Ceramic-Insulation-Ceramics-CM-Ceramics-Instructions/dp/B015GD0QCW/ref=pd_cp_60_2?_encoding=UTF8&psc=1&refRID=G3MA4QEVGWZ0CFCYCDKX
Answer: You'll have to find the right material, as this is certainly high-temperature insulation and you don't want to have a new fire. Where to find that insulation is off-topic here, but once it's in hand it doesn't look like replacing that small section will be too bad a job (certainly less work than you've already put in).
Comment: Thanks, if you have expertise, can you verify that the link I posted would be an appropriate material?
Comment: I don't have expertise (aside being an engineer), but that does look good.


How do I find how many integers fall into a range[a...b] in O(1) time using python?

Question: I have the following code and I am trying to figure out how to find how many integers fall into a range[a...b] in O(1) time using python after the array has been sorted using Counting Sort. I am supposed to sort the array and then see how many integers fall in the range.
def CountingSort(A, B, k):

    C = [0] * (k+1)
    for x in range(k+1): C[k] = 0

    for j in range(0,len(A)):
        C[A[j]] = C[A[j]] + 1

    for i in range(1, k+1):
        C[i] = C[i] + C[i-1]

    for j in range(len(A)-1, -1, -1):
        B[C[A[j]]-1] = A[j]
        C[A[j]] = C[A[j]] - 1

arr=[ 3, 1, 3, 0, 1, 0, 1, 2, 3, 4, 5, 0, 2 ]
res=[0] * (len(arr))

CountingSort(arr, res, 5)

print(res)

a = int(input("Enter value for a (lower value) in range:"))
b = int(input("Enter value for b (higher value) in range:"))
print("The value for A entered is:",a)
print("The value for B entered is:",b)
def CountRange(a,b):

 for a,b in range ((len(res))):

        return res[b] - res[a-1]

CountRange(a,b)

I am unsure of how to do the counting in range part. I know that to achieve it I need to do C[B] – C[A-1] but I am unsure of how to do that in the function as I am new to python.
Do I have to create another function or can I just continue with the CountingSort function?
When I try the above code I get the following error: cannot unpack non-iterable int object
Answer: Your counting sort algorithm has a part that is useful: it counts frequencies in C. But then it does not return that information, but only returns a sorted list. The sorted list is not going to help you achieve a time complexity of O(1) for a range count.
You should use the frequency of each value to calculate a running sum. That way you know for each value how many numbers come before it (in sorted order). That is the info you need, not so much the sorted list. With that running frequency sum info you can do the subtraction without any loop:
def count_less(lst, high):
    res = [0] * (high+1)

    for val in lst:
        res[val] += 1

    # make running sum
    running = 0
    for val, count in enumerate(res):
        running += count
        res[val] = running
    return res

def count_range(res, a, b):
    return res[b] - (res[a-1] if a > 0 else 0)

lst=[ 3, 1, 3, 0, 1, 0, 1, 2, 3, 4, 5, 0, 2 ]
res=[0] * len(lst)

res = count_less(lst, 5)

print(res)

a = int(input("Enter value for a (lower value) in range:"))
b = int(input("Enter value for b (higher value) in range:"))
print("The value for A entered is:",a)
print("The value for B entered is:",b)

print(count_range(res, a, b))

Comment: Oh ok, so I was missing the running sum from my code to get O(1). Thank you very much for your help and explanation. I am starting to understand where I went wrong.
Comment: Thank you for your answer it works, but I am required to sort the list first as it uses the CountingSort algorithm.
Comment: *"I am required"*: you should clearly set out our restrictions in the question.
Comment: I thought I did, apologies
Comment: But there is no reason why you cannot call your CountingSort function first. Just call it, and then go on with this code. The point is that counting sort is not going to bring you any closer if you are not going to count frequencies of each number. And that you can do as well on an unsorted as on a sorted list. It doesn't matter.
Comment: If you are only going to rely on the sorted list, then it is not possible to do the job in O(1). You need to get the frequencies, and store a running sum.
Comment: Oh ok. I believe I was counting the frequencies through my counting sort function because I thought counting sort counts the frequencies of each number.
Comment: Yes, you count the frequencies, but you don't use that info for anything else than sorting, while you should actually use it to make a running sum, not sort the list.
Comment: Thank you for your explanation. I thought that counting sort sorted the list and then I can answer any query about how many of the integers fall in that range.
Comment: No, a sorted list can only help to perform binary searches, which are still O(logn). For 0(1) range count, you really need the running sum.


Looking for replacement part for under-drawer catch

Question: I have a drawer which uses the following catch mounted under it. The problem is that the straight vertical-ish segment doesn't extend enough to the right to be able to click firmly into the runner.

For now, I have hacked it by inserting a small flexible eraser that puts sufficient force to hold it against the rail:

Can someone help me identify where I can find a replacement part for this? I googled for 710.611 and some references to "Salice" showed up, but no exact matches for the part number. Does anyone know if 710.610 would work instead? (e.g. https://www.wwhardware.com/salice-front-fixing-clips-left-right-futura)
Comment: aren't the 610 and 611 the same thing in left and right versions?
Answer:
Unscrew, plug holes with toothpicks and glue, trim right end of the part near the top of the picture, reinstall shoved further right, drill new screw holes.
 If the white lever that moves the gray cam provides enough range of motion, you could possibly move it far enough over not to have to plug the screw holes, but that seems dubious. Ideally set that to the middle of its range when determining how much to trim.
Or, loosen both screws, shim between the left end the drawer where it screws in, and tighten both screws.
Comment: Ha, I'm kicking myself for not thinking of the shim approach :) should work well enough. And you're right, the white lever only adjusts drawer vertical leveling/alignment.


How do I run specific golang test using go test -run

Question: What am I doing wrong here? I just want to run this one ConnectionPoolTest.TestNew and what ever I try, I get back 'no test to run'
:go test  --check.list *.go |grep Connectio
ConnectionPoolTest.TestNew
:go test  --run ConnectionPoolTest *.go
ok      command-line-arguments  0.005s [no tests to run]
:go test  --run ConnectionPoolTest.TestNew *.go
ok      command-line-arguments  0.005s [no tests to run]

Comment: `go test` requires packages, not go files, and to filter what tests you want to run, use `-run X`, where `X` is a regexp that will be matched against test names. Run `go help test` for more details; and [Go tool: Test packages](https://golang.org/cmd/go/#hdr-Test_packages); and [Go tool: Description of testing flags](https://golang.org/cmd/go/#hdr-Description_of_testing_flags).
Comment: To run that test alone, go to its folder, and type: `go test -run TestNew`. If you have other tests whose name contas the `TestNew` substring, then run `go test -run ^TestNew$`.
Comment: I don't understand. Is there a simple way to run that one test  by itself. My regex should match the test output by -check.list
Comment: That is how I thought it would work but it's not
    go test --run ^TestNew$
    testing: warning: no tests to run
    PASS

    go test -check.vv --run TestNew
    testing: warning: no tests to run
    PASS
Comment: Just one dash: `-run`, and make sure you're in the package's folder, else you have to pass the package name too.
Comment: Then there is no test called `TestNew` in your current package. What is `--check.list`? You can list all tests with `go test -list .`
Comment: go test -list . only outputs Test. go test -run Test runs all tests
Comment: @AC. then you only have a test called `Test`, and that is running all the others. Again, what is `--check.list` from? Presumably you're using some sort of test suite package, and that has flags to filter what tests to run.
Comment: Sorry, this is someone else's code that got thrown at me. I see they imported . "gopkg.in/check.v1"; I need to look into whether this is somehow causing me issues
Answer: If you want to run a specific test, you may run as bellow
package main

import (
    "testing"
    "github.com/stretchr/testify/assert"
)

func TestA(t *testing.T) {
    assert.True(t, true)
}

func TestB(t *testing.T) {
    assert.True(t, false)
}

Run Test:
$ go test -run B
--- FAIL: TestB (0.00s)
        Error Trace:    a_test.go:13
        Error:          Should be true
FAIL
exit status 1
FAIL    test    0.004s
$ go test -run A
PASS
ok      test    0.003s
shahriar@Kite ~/g/s/test>

-run flag
-run regexp
        Run only those tests and examples matching the regular expression.
        For tests the regular expression is split into smaller ones by
        top-level '/', where each must match the corresponding part of a
        test's identifier.

Comment: You can answer your own question, if you have more appropriate answer. @AC. Then it will help everyone
Comment: The code base is using "gopkg.in/check.v1" and to run a specific test one needs to use -check.f REGEX where REGEX is the regex for the name of the suite.test


Lighting in a Detached Garage

Question: I have a 20'x24' 2-story unfinished, detached garage. The first floor is a two-story garage. The second floor will be living space (kinda like a studio apartment). The ceiling of each floor is about 8 feet.
I am researching lighting options for the first floor garage area. I like recessed lighting because there are no light fixtures to bump into while moving stuff around in the garage.
Then there is "How to chose the right product". If I use LED, there are varying quality of light and products. How many lumens, spacing, number of circuits. Installation is the easy part. Design is the hard part.
I feel like I am just rambling, so forgive me if this does not make much sense.
Side Note: I wish I could find a good general contractor (GC) with good subs, but don't even know how to search for one and determine if I have found a good GC. Maybe a GC is not what I am looking for. Who would design and draw up the plans. Architect?
Thanks,
Comment: You are, unfortunately, correct - you were rambling. The only actual question I see here is "Architect?" and that's really not a question. Please [edit] your post to focus on and ask a _specific_ question. I get that you're not sure where to start, but you gotta start somewhere...
Answer: Go to a real lighting store. Often times they'll consult with you free of charge if you purchase the fixtures there. They may cost a bit more, but are usually of higher quality than the big box stores and you get the advice. If you buy enough, sometimes they'll bend their policies a bit and give you contractor pricing. Clearly you need design input and they can give it to you, right down to calculating the lumens per square foot you need as well as other lighting options, such as task lighting.
Also, many lighting stores are small, locally owned businesses worth supporting. IMHO.
Comment: Always worth a few extra bucks in purchase price - It's _far_ less than the price you 'd pay for the advice you'll get.
Answer: If you want to spend more money, sure, an architect or (more specifically, and perhaps cutting out one superfluous factor) lighting designer can multiply the cost of your project by X=Large Factor.
If you'd rather not spend so much, testing and evaluation are good. Look at LED lights you like. Find out what they are, or what specs you like for color temperature at least. Buy one or two, try them out in the space - see how you like them at various spacings. Plan from there. If you do a good job figuring out first (from store displays or friends' lights) what you like you might not need to do much testing to find fixtures you actually like, but having a few and TESTING the spacing is really helpful.
Circuits for LED lights - you can run a LOT of LED fixtures on one 15A circuit if you don't put anything ELSE on that circuit. One circuit per floor is probably quite adequate; one circuit for the building might well be adequate. At a typical 10 or 20 watts per fixture, between 72 and 144 fixtures per 15A 120V circuit (derated for continuous load.)
If you end up with a few extra test fixtures, you'll probably still come out money ahead - you can also sell them off.

Lighting in a Detached Garage


Breaker compatibility

Question: I'm needing to replace a 20A single pole breaker in my Thomas & Betts, TBB20(20-40)CG Mod. 1 panel. Is there a site with a compatibility chart so I can buy the same type breakers?
I saw the post from a lady replacing her 30A water heater breaker and the comment had a link to a Pratt site, but the site doesn't load anymore.

Thank you
Update - You don't have to read below the following line. I am just adding a little bit of history to this issue.

My wife and I bought this place in November from San Antonio, TX (pressed for time and sight unseen by us. Our son, who lives near did look the place over, however doesn't know to look deeply into the electrical).
Anyway, the house (1998 Clayton mobile home) is outside of the city limits. It was moved onsite in 2006 and never registered in Florida (until we bought it). The owners built a roughly 20' x 30' addition to the mobile home.
From what I'm finding, the wiring would not pass code to the addition because they ran NM-B underground from the addition to the Service panel outside. They also ran NM-B to two sheds, where they commenced to splicing the two sheds in to the feeder and only taped the connections. Needless to say, the NM-b sheathing was damaged and when it rained hard it shorted out and tripped the 20A breaker. I've since dug (by hand no less) the trenches 24" deep and buried new UF-B to the shed and created a branch circuit to feed a 20A WR GFCI and branched to a 20A WR TR outlet. Both in outdoor weather resistant boxes.
I've since ran UF-B to the NM-B lines under the house and connected them inside gang boxes (14 inches above the ground) back to the meter panel.
If you've read all this then you know most of the story. Ha ha ha ha
Thank you all for your assistance.
Comment: If you haven't done these things yet, talk to us. We can save you a LOT of digging and/or some coin.  And avoid a code violation.
Comment: Example? Even though I already finished, I'd like to know where I could've saved. :)
Answer: TLDR: For full-size breakers, use Eaton "CL" (CLassified) type - authorized by UL.  For double-stuff breakers, use Eaton's BRD which are marked "Type A" - authorized by your panel labeling.  Replace Square-D, green handle BR, and "no-name" tandem/quad breakers.
Dangerous old breakers
Wow, you really do have a "breaker museum" in there.  As ThreePhaseEel advises, the Square D breaker needs to go. Even Square D forbids them in alien panels.
Your panel labeling says

The breakers starting with "TB" aren't made anymore. So all that's left is type "A", which are "double-stuffs" - tandem or quadplex.  Why is that outlier there?  It seems apparent that Thomas & Betts never developed their own "double stuff" breakers -- they simply private-labeled Challenger brand double-stuffs (as evidenced by careful comparison and the CSA file number being the same as Challenger).
Problem: Challenger breakers had huge problems with their safety certification, and the things are "fire starters".  They need to go.
Solution: Eaton BRD types are also labeled Type A!  There was nothing wrong with Challenger's bus design, and BRyant used the same bus.  Bryant relabeled it "BR", so they could exclude the faulty type C and A breakers.  Then, they asked UL to cross-list BR breakers for Type C and Type A, since they are, after all, the same bus.  How convenient for us!  BR became Cutler-Hammer BR and today it is Eaton BR.
However, the label does not allow the use of BR or Type C breakers.  (such as the Bryant BR with the green handle). It's probably fine, but it's a code violation.
For full-size breakers, you can use Eaton CL type breakers for a different reason: Eaton sent them to UL with a pile of legacy T&B panels, and UL tested them exhaustively and certified them as safe. They are UL-"Classified" for T&B panels.  CL breakers are available in 1-pole GFCI up to 30A, and 1-pole AFCI up to 20A.
Common trip required
Whenever a 240V circuit carries a neutral wire, the breaker is required to have "common trip", so that an overload on one leg shuts off the other leg also. That applies to the dryer and range.
240V circuits without a neutral,  only need common maintenance shutoff... electric heaters, A/C, etc.
Note the words "Non Common Trip" on the dryer and range quadplex.  Those are the circuits that need it and they don't have it.
So this breaker must be changed to a common-trip version of that breaker.  Fortunately again the Eaton double-stuff line provides; you need a BQC230240.
So I see a bit of a punch-list of work to do here.

The labeled T&B breakers can stay.
The Square D gets replaced with an Eaton CL220. *
The green handle BR230 gets replaced with a CL230. *
The QUADPLEX breaker in the middle needs common trip; Eaton BQC230240.
All the "no-name" tandem breakers are the suspect Challenger type, and need to be replaced with "Type A" equivalents from the Eaton BR line.  That is BD1515 and BD2020.

* If Eaton CL is hard to find or prohibitive
If locating Eaton CL breakers proves burdensome: you can simply use Eaton double-stuffs instead.  For instance, the two 240V circuits (BR and HOM breakers) could be consolidated onto a single BQC220230 breaker (or if common trip is not needed, BQ220230).
Likewise, I apologize - I overlooked your original question.  Again a BR2020 could be used as its replacement.  This will give you a second breaker; just don't use it.
All empty holes MUST be filled!  Do not leave gaps in your panel! The best hole filler is an actual breaker connected to nothing. So save back a few that you're pulling out.   I would prefer the green handled BR, as it's the least wrong for this panel.
Comment: I wish to thank each and every one of you for your replies and information. @Harper - Reinstate Monica I am grateful for your answer since you listed the type I need to buy and the location it will replace. I plan to print the photo and mark each one with all of your replies just to keep it straight for me.
Comment: anyway to pm or message offsite? I have a question?
Comment: @KurtM - best you ask your follow-up here or as a new question so it can get the attention it deserves
Comment: @ThreePhaseEel - Is this one good to use in my panel?

BR 1-30 Amp 2 Pole and 1-40 Amp 2 Pole BQC (Common Trip) Quad Circuit Breaker
by Eaton

I found it on Home Depot's site.
Comment: Yeah, that's the BQC230240 Harper refers to in his answer
Comment: Thank you @ThreePhaseEel. It's almost half the price at HD than the other site I found it on. Dang, unavailable through HD...
Answer: The correct replacement breaker is a CL120
The correct replacement for a T&B breaker, generally speaking, is an Eaton CL circuit breaker.  It's UL tested and classified to work in your panel, and also carries a factory warranty.  In your specific case, it's a CL120 you want, as you need a 1-pole, 20A breaker to replace what you have.
Note that you'll want to replace the alien HOM220 in the bottom left of your photo with a CL220 while you're in there; however, we're stuck keeping the other breakers (which look to be a mix of Challenger? and T&B) in service since there are no UL classified "double stuff" breakers.

Breaker compatibility


What does the 'Play in Starships' button do?

Question: In the game menu of Civilization: Beyond Earth, there is an option labelled 'Play in starships'. It appears to be disabled.

I know there is a game titled Sid Meier's Starships - does this have anything to do with it?
What is this button, what does it do, and how can I unlock/click it?
Answer:
You need to own and install both Civ:BE and Starships
You need to login to your 2K Account on both games, so they are registered there
After winning a game press "one more turn"
The Play in Starships button should now be usable and will transfer your save to Starships
This allows you to start a Starships game with several bonuses.

Here is a list detailling all the possible bonuses: Civ-Wiki
The hybrid affinities essentially grant you the abilities of both, so they are much stronger than the basic affinities you can pick in Starships.
Comment: Angus: Yes, This also works vice versa, I.e. you can unlock new things in Civ: Be by playing Starships. I updated the answer with a link to a wiki-page detailing the bonuses. @AntoineHejlík As far as I know, only the 2K Account works.
Comment: So basically it gives you an advantage in Starships?
Comment: Does Steam account work as well?


Django rest-auth: calling RegisterView from other viewset; sensitive_post_parameters didn't receive an HttpRequest

Question: In my application powered by django-rest-framework I use django-rest-auth and allauth to handle the user registration, etc. Everything works fine.
I have one API endpoint that handles users' testimonials. The idea is that if someone who has no account at my website is adding a testimonial, I want to automatically create an account for him/her (in case if an email was entered) and the welcome email should be sent, profile created, etc.
So from the viewset that handles adding a testimonial, I am calling RegisterView like this; this is POST:
from rest_auth.registration.views import RegisterView

class AddTestimonialView(viewsets.ModelViewSet):
    serializer_class = TestimonialSerializer
    queryset = Testimonial.objects.all()
    permission_classes = [permissions.AllowAny, ]

def create(self, request, *args, **kwargs):
    ................
    RegisterView.as_view()(self.request)

But I am getting an error:
AssertionError at /api/auth/testimonial/add/
sensitive_post_parameters didn't receive an HttpRequest. If you are decorating a classmethod, be sure to use @method_decorator.

Seems that I should create a custom class and override some method(s) of RegisterView, dispatch likely. But can't figure out what exactly should I do. In fact the request has no sensitive data at all, just email, name, testimonial text, etc. No passwords or tokens.
This is an original code from RegisterView @ rest_auth.registration.views:
sensitive_post_parameters_m = method_decorator(
    sensitive_post_parameters('password1', 'password2')
)

class RegisterView(CreateAPIView):
    serializer_class = RegisterSerializer
    permission_classes = register_permission_classes()
    token_model = TokenModel

    @sensitive_post_parameters_m
    def dispatch(self, *args, **kwargs):
        return super(RegisterView, self).dispatch(*args, **kwargs)

    def get_response_data(self, user):
        if allauth_settings.EMAIL_VERIFICATION == \
                allauth_settings.EmailVerificationMethod.MANDATORY:
            return {"detail": _("Verification e-mail sent.")}

        if getattr(settings, 'REST_USE_JWT', False):
            data = {
                'user': user,
                'token': self.token
            }
            return JWTSerializer(data).data
        else:
            return TokenSerializer(user.auth_token).data

    def create(self, request, *args, **kwargs):
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        user = self.perform_create(serializer)
        headers = self.get_success_headers(serializer.data)

        return Response(self.get_response_data(user),
                        status=status.HTTP_201_CREATED,
                        headers=headers)

    def perform_create(self, serializer):
        user = serializer.save(self.request)
        if getattr(settings, 'REST_USE_JWT', False):
            self.token = jwt_encode(user)
        else:
            create_token(self.token_model, user, serializer)

        complete_signup(self.request._request, user,
                        allauth_settings.EMAIL_VERIFICATION,
                        None)
        return user

Any ideas? Thanks
Comment: what is type is `self.request`?
Comment: @PawełKordowski I added more code, thanks
Comment: can you put `print(type(self.request))` above `RegisterView.as_view()(self.request)` in order to check type?
Comment: @PawełKordowski it's ``````
Comment: try `self.request._request`
Comment: @PawełKordowski I've tried, forgot to mention, sorry. Got another error: ```RawPostDataException at /api/auth/testimonial/add/. You cannot access body after reading from request's data stream```
Comment: This is POST by the way
Answer: Can you just replace:
RegisterView.as_view()(self.request)

with
serializer = RegisterSerializer(data=self.request.data)
serializer.is_valid(raise_exception=True)
user = self.perform_create(serializer)

?


Help to make jQuery simple

Question: How can i make this shooter.
It does what it should but it is very long. Oh and I need to run a function for each number.
This is my HTML

View count

Click count

Profile

Inbox

Uploads

TV

Notes

More

And this is my jQuery
    $("#moremenu ul li").click(function () {

    var index = $('#moremenu ul li').index(this);
    var clickval = $('#moremenu ul li').text(this);

    //$('.status').prepend('
click index was '+index+'
').fadeOut('fast').fadeIn('slow');
    if(index == 0){
        $('.status').prepend('
click index was '+index+'
').prepend('
You clicked '+clickval+'
').fadeOut('fast').fadeIn('slow');
    }
    if(index == 1){
        $('.status').prepend('
click index was '+index+'
').prepend('
You clicked '+clickval+'
').fadeOut('fast').fadeIn('slow');
    }
    if(index == 2){
        $('.status').prepend('
click index was '+index+'
').prepend('
You clicked '+clickval+'
').fadeOut('fast').fadeIn('slow');
    }
    if(index == 3){
        $('.status').prepend('
click index was '+index+'
').prepend('
You clicked '+clickval+'
').fadeOut('fast').fadeIn('slow');
    }
    if(index == 4){
        $('.status').prepend('
click index was '+index+'
').prepend('
You clicked '+clickval+'
').fadeOut('fast').fadeIn('slow');
    }
    if(index == 5){
        $('.status').prepend('
click index was '+index+'
').prepend('
You clicked '+clickval+'
').fadeOut('fast').fadeIn('slow');
    }
    if(index == 6){
        $('.status').prepend('
click index was '+index+'
').prepend('
You clicked '+clickval+'
').fadeOut('fast').fadeIn('slow');
    }
    if(index == 7){
        $('.status').prepend('
click index was '+index+'
').prepend('
You clicked '+clickval+'
').fadeOut('fast').fadeIn('slow');
    }
    if(index == 8){
        $('.status').prepend('
click index was '+index+'
').prepend('
You clicked '+clickval+'
').fadeOut('fast').fadeIn('slow');
    }
});

Answer: var index = $('#moremenu ul li').index(this);
var clickval = $('#moremenu ul li').text(this);

if(index >= 0 && index <= 8){
    $('.status').prepend('
click index was '+index+'
').prepend('
You clicked '+clickval+'
').fadeOut('fast').fadeIn('slow');
}

This is simple JavaScript.
Answer:     var index = $('#moremenu ul li').index(this);
    var clickval = $('#moremenu ul li').text(this);

    if(index >= 0 && index <= 8){
       $('.status').prepend('
click index was '+index+'
').prepend('
You clicked '+clickval+'
').fadeOut('fast').fadeIn('slow');
    }

Comment: That condition is always true.

Help to make jQuery simple


Counting the number of rows from multiple tables

Question: I'm trying to do something very basic but can't quite figure this one out. I'm using PHP and MySQLi (OOP) rather than MySQL. I could use multiple single select statements then put the count from each number into a variable, but I think it's inefficient.
Okay, there are a few tables;
TABLE NAME: UCC_STAFF
id
email
username
password
status

TABLE NAME: UCC_TEMP_STAFF
id
email
username
password
status

TABLE NAME: UCC_TEMP_STUDENTS
id
email
username
password
status

TABLE NAME: UCC_VISITORS
id
email
username
password
status

What I'm trying to do is count the number of rows from each table, each row represents a user. As I've explained; It's easy enough to do with one table but I'd like to combine results with a single request into a an array rather than multiple statements into multiple variables.
An example of the desired result would be;
$a = results('UCC_STAFF' => '35',
            'UCC_TEMP_STAFF' => '12',
            'UCC_STUDENTS' => '543',
            'UCC_VISITORS'  => '6',);

What I would imagine this to look like would be;
$db_host = "dbhost";
$db_username = "username";
$db_pass = "password";
$db_name = "dbname";

$mysqli = new mysqli("$db_host", "$db_username", "$db_pass", "$db_name");

if ($mysqli->connect_errno) {
    printf("Connect failed: %s\n", $mysqli->connect_error);
    exit();
}

$query  = "SELECT * FROM UCC_STAFF;";
$query .= "SELECT * FROM UCC_TEMP_STAFF;";
$query .= "SELECT * FROM UCC_STUDENTS;";
$query .= "SELECT * FROM UCC_VISITORS";

if ($mysqli->multi_query($query)) {

// Results into $results
// How do I do this, what goes here?

    }

// Print Array
print_r ($results);

Answer: You could do something like that to count data from multiple tables with one query.
$query  = "SELECT ";
$query .= "(SELECT COUNT(*) FROM UCC_STAFF) AS count_staff, ";
$query .= "(SELECT COUNT(*) FROM UCC_TEMP_STAFF) AS count_temp_staff, ";
$query .= "(SELECT COUNT(*) FROM UCC_TEMP_STUDENTS) AS count_students, ";
$query .= "(SELECT COUNT(*) FROM UCC_VISITORS) AS count_visitors";

Answer: Create one table
TABLE NAME: UCC_PEOPLE
id
email
username
password
status
type <-- use this field to distinguish different types

Run one query to get the count of records, not records themselves
SELECT type, count(*) cnt, FROM UCC_PEOPLE GROUP BY type

Comment: Thanks for that, it is quite sensible however it's just a scenario, I'm still learning and what I'd like to know is how to count the rows from different tables and put those results into an array.
Answer: i think you looking for something like this with UNION
 $query  =(  (SELECT CONCAT('UCC_STAFF', '')as UCC_STAFF ,count(*)as count from UCC_STAFF )

              UNION ALL
              (SELECT CONCAT('UCC_TEMP_STAFF', '')as UCC_TEMP_STAFF ,count(*) from UCC_TEMP_STAFF )

              UNION ALL
              (SELECT CONCAT('UCC_TEMP_STUDENTS', '')as UCC_TEMP_STUDENTS ,count(*) from  UCC_TEMP_STUDENTS )

              UNION ALL
              (SELECT CONCAT('UCC_VISITORS', '')as UCC_VISITORS ,count(*) from UCC_VISITORS ) );

DEMO SQLFIDDLE HERE


Should I use"$_server document root" or" ..\ "when going b/t folders to access other files?

Question: I was wondering if there's any difference in using:
$_SERVER['DOCUMENT_ROOT] . '/path/to/document.html';
Instead of:
'../path/to/document.html';
...assuming they both lead to the same place.
Is there any "best practice" for it or does it not really matter?
Thanks
P.S. How do I accept answers? I didn't know that there was such an option and I look like an idiot with all these unaccepted answers for questions...
Comment: To accept an answer, click on the tick next to the one that you want to accept. Sometimes, for users with low rep, there's a delay between asking a question and being able to accept an answer to it.
Comment: "Assuming they both lead to the same place.... " Well, they might not. So, there.
Answer: Really it doesn't matter too much. I would say the best practice is to use the $_Server['DOCUMENT_ROOT'] because that way you know exactly where you are going to end up, whereas if you've got directories nested a few deep, then '..' won't always take you to the same place in different files, so it's just more to keep track of.
You can accept answers by clicking on the check mark next to the up and down arrows to the left of the post that you'd like to accept.
Answer: I personally use defined constants, such as follows:
define('PATH_BASE', rtrim(strtr(__DIR__, '\\', '/'), '/') . '/');

Appending relative paths to PATH_BASE:
$dir = PATH_BASE . 'path/to/file.php';

Answer: It's slightly faster to have an absolute path, but I like to stick with the "../" for about 3 levels, and then resort to an absolute path.


Two numbers sharing an unknown prime factor. Find a method to quickly factor both numbers.

Question: $x$ and $y$ are two number which share a prime factor. You do not know what the prime factor is. Explain how one can factor $x$ and $y$ quickly. Prove it works by using $x = 41685823$ and $y= 39034579$.
I don't really know how to approach this question because sharing a prime factor, does that mean they can share other factors too? Any help would be splendid! Cheers.
Edit: Apparently a classmate said that the two prime are consecutive primes. Maybe this will make the question clearer. Thanks!
Comment: hint: gcd computation
Comment: If $x$ and $y$ share a common divisor, $x-y$ and $x+y$ also share that common divisor and may be easier to factor, at least to remove some of the smaller divisors.
Comment: LOL,I am a student in UofWaterloo and having Math135 class. I think you are probabily one of my classmates.
Anyway, I did not get the right way to solve the quention. But I am sure that it is not as simple as using Euclid's algorithm, as the question required to use RSA and required us to find a way to solve it quickly.
Meanwile, the question gives the condition that both N1 and N2 has and only has tow prime factors.
Answer: You can use Euclid's algorithm to find the greatest common divisor, which the prime will divide.  If you are given that $x$ and $y$ are semiprimes, that they each have only two prime factors, you can just divide them each by the GCD and have the factorization.  The example numbers you have meet this criterion, but I don't see it in the problem statement.  If $x$ and $y$ each had four large prime factors and shared two of them, the GCD would be the product of the two shared factors and the rest would be the product of the other two.  That is a factorization, but not a complete one.
Comment: I'm not quite sure I follow. You are right that my two numbers given in the question dont specify them as semiprimes which is why I am confused on what the best way to do with this question. Should I treat the question as semi primes or can I just pick and choose which prime I want?
Comment: Still factoring $\frac{x}{GCD}$, $\frac{y}{GCD}$ and $GCD$ is most of the times much easier than factoring $x,y$...
Comment: I asked one of classmates and the question has changed to that they have consecutive primes which factor into them. Does that change the question to make it solvable clearer? Thanks1
Comment: @Michael:  whether the primes are consecutive doesn't matter, just how many there are.  If they are about the same size, instead of factoring $x$ you are factoring something about $\sqrt x$, so if you are doing trial division you now need to go up to $x^{\frac 14}$ instead of $x^{\frac 12}$.  This is the point of N.S.'s comment.
Comment: @Michael, please do follow the advice that's been given to you, and apply the Euclidean algorithm to the two numbers. It's only a handful (OK, make it two) of Euclidean divisions.


What disadvantages are there from being wet?

Question: I've just started playing Magicka, and I'm constantly getting reminded of how to dry myself out using fire, without being told why.
What disadvantages do I suffer as a result of being wet?
Answer:
Recognized by dripping clothes.
  Attempting to conjure a lightning
  element whilst in this state will
  damage a wizard and cause him to lose
  charges. Thus, it is impossible to
  cast any spell involving a lightning
  element while wet.
Wet characters also take twice as much
  damage from lightning spells. Being
  Wet will remove Grease/Burning.

Source: Magickapedia
Answer:
If you do a lightning spell while wet, you'll be damaged.
In co-op mode, you cannot resurrect your partner if you are wet since it requires lightning.
You'll freeze if you get hit by a cold spell.
Answer: Aside from the effects listed above, you'll also note that anytime your character (or an enemy) takes cold damage while being wet, they will be frozen solid and unable to move or take action. Some enemies are freeze-proof, however, some spoiler related bosses in particular.


Fuse detailed road mesh with regular grid terrain mesh

Question: I am experienced with C++ and know more embedded device related stuff but have absolutely no knowledge of computer graphics and its algorithms.
I would like to get a road mesh (based off of a spline) blended seamlessly into a terrain mesh, which is based on a regular grid, like in the picture below. How is this achieved?
Just looked at the CGAL documentation and I cannot even see which problem I am facing and which package to study. Delauney refinement maybe? But I only see a CGAL package for 2D. I'd like to generate a 3D mesh.
The road mesh should be unmodified, the terrain mesh can be altered to form a seamloss mesh.
Can you guide me to the kind of algorithms needed for this?
Kind regards
Max
Answer: I think the best way to tackle this problem would be to make an algorithm that works on a single triangle at a time.
You'd look at each terrain triangle individually that the road intersected and process it.
Looking at one triangle individually, you would have to chop that triangle into one or more meshes to make it contour to the road.
Here are some of the cases to consider in the image below.  I'm betting there is some triangle slicing algorithm that would be suited to this, and I'm not sure of a name off hand, but the main contribution I'm proposing here is that you deal with triangles individually.

When cutting the triangle on the x/y plane to make a hole for for the road, you would also want the terrain to take on the z value (height) of the road, for those vertices that touch the road.  This will make the terrain rise up to meet the road.
At this point, you'd have a terrain mesh which did conform to the road but it would be ugly.
Instead of having a nice even looking hill that went up to the road at reasonable slopes, you'd have some triangles that went very sharply up to the road, and others that had a very flat slope.
What you would need to do now is do some kind of "relaxation" algorithm to address this.
Basically, if something is too steep, because there wasn't enough triangle to make the height adjustment, you need to make your whole triangle closer in height to the road and bleed off some of the height adjustment to neighboring triangles.
If something was not steep enough for your liking, because there was a lot of triangle to make a small height adjustment, you may want to break the triangle up into more polygons where it gets closer to the road and have that smaller area handle the change in elevation.
During this second step, when you added a vertex to an edge between two triangles you would also need to adjust the triangle that shares the edge to prevent cracks from showing up in the terrain.
The details are a bit vague, but hopefully the two step approach will help you tackle the problem.

Make the terrain mesh adapt to the road, without caring about how it looks.
Refine the terrain mesh to make it appear to meet the road in a more organic man made way.
Answer: For a 3D terrain, you can triangulate using the points projected onto the XY-plane. This is easily implemented in CGAL using the Projection_traits_xy_3 class, as in this terrain triangulation example.
For the fusion of the road triangulation you can use a constrained Delaunay triangulation. You constrain the road mesh and insert the regular grid points of the terrain mesh to construct the full triangulation. See this code for an example of how to use CGAL's constrained Delaunay triangulation.
This should enable you to solve the problem without going into the details of the triangles.
If the result is not good enough, you can always refine the mesh by inserting additional points in problematic triangles.


trying to load php only once with jquery

Question: I have Jquery set up so when I click on a button it loads in the PHP from another page. Currently it loads this every time I click the button. I would like to have it so it only loads the content once.
Here is my code:
//initially hides all containers
$( document ).ready(function() {
    $('.aboutcontainer,.contactcontainer,.homecontainer,.portfoliocontainer,.musiccontainer').hide();
});

//home page must show as first page on arrival
$( document ).ready(function () {
    $(".homecontainer").show();
});

//load about page
//button to start animation
$( document ).ready(function() {
    $('#about').click(function () {

        //fades unwanted pages
        $('.homecontainer,.musiccontainer, .portfoliocontainer, .contactcontainer').fadeOut({queue: false, duration: 700});

        //animates up unwanted pages
        $('.homecontainer, .musiccontainer, .portfoliocontainer, .contactcontainer').animate({
            'margin-Top' : "-1000px",
        },400, 'easeInBack');

        //brings in selected page with a 0.7 second pause
        setTimeout(function() {
            $('.aboutcontainer ').fadeIn({
                queue: false,
                duration: 100
            });
            $(".aboutcontainer").animate({
                marginTop: "115px",
            },1200,'easeOutQuint');
        }, 700 );

        //loads in selected page content
        setTimeout(function() {
            $( ".aboutcontainer" ).load( "about.php" );
        }, 1200 );

    });
});

Also I am experiencing difficulty with the page not loading the change page functionality when I open it in incognito mode.
Here is a link to the site: http://benliger.webatu.com
Why would this be?
Comment: Have a variable set up which is empty to start with, on click check if the var is empty, if it is, get the page via AJAX and store it in the var, if the var isn't empty, return the var instead of running the AJAX.
Answer: To allow an event handler to run only once, use .one() rather than .click() (which is a shortcut to .on("click"...).
Documentation: http://api.jquery.com/one
Comment: hmmm but its only the .load function that I want to run only once. Your suggestion would mean the .animate features would no longer run either correct?
Comment: @BenLiger Correct. Either split that portion into its own event handler using `.one()` for the binding or set a flag that saves state (used to determine if the `.load()` function has run or not and if so, don't run it again).
Comment: ok, both good suggestions. The second option sounds more practical for what im after. Could you recommend how to set a flag that saves the state?
Comment: ok so i tried adding this to the script:$( document ).ready(function() {
   $('#about').one(function () {
   setTimeout(function() {
$( ".aboutcontainer" ).load( "about.php" );
}, 1200 );
});
}); but now it doesnt load it?
Comment: woops was missing the "click" part. Works fine now. My second question still stands though, why are my functions not loading at all in incognito?
Comment: @BenLiger Is JS running when you load the page in an incognito tab? Other than that I suggest using `$(function () { ... })` rather than `$(document).ready(function () { ... })` as the former will fire even after the `document.ready` event has fired.
Comment: thanks Jasper and yes JS is running in incognito. Will make the suggested changes :)


How do I use os.scandir() to return DirEntry objects recursively on a directory tree?

Question: Python 3.5's os.scandir(path) function returns lightweight DirEntry objects that are very helpful with information about files.  However, it only works for the immediate path handed to it.  Is there a way to wrap it in a recursive function so that it visits all subdirectories beneath the given path?
Comment: Take a look at [os.walk()](https://docs.python.org/3.5/library/os.html#os.walk). It may be a bit more heavy-handed than your looking for, but it should be more simple than creating your own solution.
Answer: You can scan recursively using os.walk(), or if you need DirEntry objects or more control, write a recursive function like scantree() below:
try:
    from os import scandir
except ImportError:
    from scandir import scandir  # use scandir PyPI module on Python < 3.5

def scantree(path):
    """Recursively yield DirEntry objects for given directory."""
    for entry in scandir(path):
        if entry.is_dir(follow_symlinks=False):
            yield from scantree(entry.path)  # see below for Python 2.x
        else:
            yield entry

if __name__ == '__main__':
    import sys
    for entry in scantree(sys.argv[1] if len(sys.argv) > 1 else '.'):
        print(entry.path)

Notes:

There are a few more examples in PEP 471 and in the os.scandir() docs.
You can also add various logic in the for loop to skip directories or files starting with '.' and that kind of thing.
You typically want follow_symlinks=false on the is_dir() calls in recursive functions like this, to avoid symlink loops.
On Python 2.x, replace the yield from line with:
for entry in scantree(entry.path):
    yield entry

Comment: os.walk vs os.scandir -- I ran these 2 functions against a directory with over 4 million directories and files.  os.walk took 34 min, 29 sec and os.scandir took 7 minutes, 46 sec. So, at least for my test, it appears os.scandir is about 4 1/2 times faster.
Comment: It's worth noting that as a part of PEP 471 os.walk was updated to use os.scandir under the hood.
Comment: @ShadowRanger Well, true, but this way it'll work for Python < 3.5 (including Python 2.x) using my [scandir](https://pypi.python.org/pypi/scandir) module. :-)
Comment: Given that `os.scandir` only exists in Python 3.5, the Python 2 fallback code probably isn't needed. :-) __Edit:__ Ah, you wrote it to import the PyPI module if `os.scandir` didn't exist, and I'm guessing the PyPI module is available for 2.7?
Comment: @ShadowRanger I've added a code comment to clarify.
Comment: you're the author of the backport! congrats it's a life saver
Comment: The [**`scandir`**](https://docs.python.org/3/library/os.html#os.scandir) documentation also recommends using a context manager, i.e. `with scandir(path) as entries:`