Iptables: Selective PPTP VPN routing

Question: I've been able to set up TomatoUSB firmware with Ipredator via PPTP, the configuration is as follows:

However, I don't want to use Ipredator PPTP VPN for every machine on my network, how to only use PPTP VPN for one MAC/IP?
Upon further investigation, I have the following iptables output:
root@unknown:/tmp/home/root# iptables -L
Chain INPUT (policy DROP)
target     prot opt source               destination
DROP       all  --  anywhere             somehostname.vpn.ipredator.se
DROP       all  --  anywhere             my.personal.isp.hostname.com
DROP       all  --  anywhere             anywhere            state INVALID
ACCEPT     all  --  anywhere             anywhere            state RELATED,ESTABLISHED
shlimit    tcp  --  anywhere             anywhere            tcp dpt:ssh state NEW
shlimit    tcp  --  anywhere             anywhere            tcp dpt:telnet state NEW
ACCEPT     all  --  anywhere             anywhere
ACCEPT     all  --  anywhere             anywhere
ACCEPT     udp  --  anywhere             anywhere            udp spt:bootps dpt:bootpc
ACCEPT     tcp  --  anywhere             unknown             tcp dpt:ssh

Chain FORWARD (policy DROP)
target     prot opt source               destination
ACCEPT     all  --  anywhere             anywhere
DROP       all  --  anywhere             anywhere            state INVALID
TCPMSS     tcp  --  anywhere             anywhere            tcp flags:SYN,RST/SYN TCPMSS clamp to PMTU
restrict   all  --  anywhere             anywhere
restrict   all  --  anywhere             anywhere
ACCEPT     all  --  anywhere             anywhere            state RELATED,ESTABLISHED
wanin      all  --  anywhere             anywhere
wanout     all  --  anywhere             anywhere
ACCEPT     all  --  anywhere             anywhere
wanin      all  --  anywhere             anywhere
wanout     all  --  anywhere             anywhere

Chain OUTPUT (policy ACCEPT)
target     prot opt source               destination

Chain rdev00 (1 references)
target     prot opt source               destination
DROP       all  --  anywhere             anywhere            MAC 00:19:C5:7B:84:89

Chain restrict (2 references)
target     prot opt source               destination
rdev00     all  --  anywhere             anywhere

Chain shlimit (2 references)
target     prot opt source               destination
           all  --  anywhere             anywhere            recent: SET name: shlimit side: source
DROP       all  --  anywhere             anywhere            recent: UPDATE seconds: 60 hit_count: 4 name: shlimit side: source

root@unknown:/tmp/home/root# ifconfig
br0        Link encap:Ethernet  HWaddr 10:DF:21:DF:1B:C5
           inet addr:192.168.1.1  Bcast:192.168.1.255  Mask:255.255.255.0
           UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1
           RX packets:37083400 errors:0 dropped:0 overruns:0 frame:0
           TX packets:36007047 errors:0 dropped:0 overruns:0 carrier:0
           collisions:0 txqueuelen:0
           RX bytes:2111526714 (1.9 GiB)  TX bytes:893920689 (852.5 MiB)

eth0       Link encap:Ethernet  HWaddr 10:DF:20:CE:1B:B2
           UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1
           RX packets:73849311 errors:0 dropped:0 overruns:0 frame:0
           TX packets:71651191 errors:0 dropped:0 overruns:0 carrier:0
           collisions:0 txqueuelen:1000
           RX bytes:1860166371 (1.7 GiB)  TX bytes:4061112643 (3.7 GiB)
           Interrupt:4 Base address:0x2000

eth1       Link encap:Ethernet  HWaddr 10:BF:20:DF:1A:B8
           UP BROADCAST RUNNING ALLMULTI MULTICAST  MTU:1500  Metric:1
           RX packets:2167739 errors:1 dropped:0 overruns:0 frame:14874409
           TX packets:2691377 errors:108 dropped:0 overruns:0 carrier:0
           collisions:0 txqueuelen:1000
           RX bytes:1449581768 (1.3 GiB)  TX bytes:2683796769 (2.4 GiB)
           Interrupt:3 Base address:0x1000

lo         Link encap:Local Loopback
           inet addr:127.0.0.1  Mask:255.0.0.0
           inet6 addr: ::1/128 Scope:Host
           UP LOOPBACK RUNNING MULTICAST  MTU:16436  Metric:1
           RX packets:1005 errors:0 dropped:0 overruns:0 frame:0
           TX packets:1005 errors:0 dropped:0 overruns:0 carrier:0
           collisions:0 txqueuelen:0
           RX bytes:156929 (153.2 KiB)  TX bytes:156929 (153.2 KiB)

ppp0       Link encap:Point-to-Point Protocol
           inet addr:126.96.36.199  P-t-P:22.214.171.124  Mask:255.255.255.255
           UP POINTOPOINT RUNNING MULTICAST  MTU:1400  Metric:1
           RX packets:1738332 errors:0 dropped:0 overruns:0 frame:0
           TX packets:2089007 errors:0 dropped:0 overruns:0 carrier:0
           collisions:0 txqueuelen:3
           RX bytes:756439075 (721.3 MiB)  TX bytes:1167050907 (1.0 GiB)

vlan1      Link encap:Ethernet  HWaddr 20:CF:30:CE:0A:B6
           UP BROADCAST RUNNING ALLMULTI MULTICAST  MTU:1500  Metric:1
           RX packets:36136587 errors:0 dropped:0 overruns:0 frame:0
           TX packets:34736222 errors:0 dropped:0 overruns:0 carrier:0
           collisions:0 txqueuelen:0
           RX bytes:2237528696 (2.0 GiB)  TX bytes:4119244159 (3.8 GiB)

vlan2      Link encap:Ethernet  HWaddr 10:BF:10:DE:1A:A7
           inet addr:126.96.36.199  Bcast:22.214.171.124  Mask:255.255.254.0
           UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1
           RX packets:37693742 errors:0 dropped:0 overruns:0 frame:0
           TX packets:36914969 errors:0 dropped:0 overruns:0 carrier:0
           collisions:0 txqueuelen:0
           RX bytes:2587444201 (2.4 GiB)  TX bytes:4236835780 (3.9 GiB)

root@unknown:/tmp/home/root# ip route flush table 3
Nothing to flush.
root@unknown:/tmp/home/root# ip route add 192.168.1.0/24 dev br0 table 3
root@unknown:/tmp/home/root# ip route add 127.0.0.0/8 dev lo table 3
root@unknown:/tmp/home/root# ip route add default via 10.0.0.1 table 3
RTNETLINK answers: No such process
root@unknown:/tmp/home/root# ip rule add from 192.168.1.112 table 3

vlan2 has my actual ISP IP, I masked it to 220.127.116.11 for privacy reasons
ppp0 has my actual PPTP IP, I masked it to 188.8.131.52 for privacy reasons
How can I only route certain machines via VPN?
Answer: I do the exact same thing to only route certain machines across a VPN. In my case, I run this script in conjuction with the openvpn option --up /etc/rc.usvpn:
#!/bin/bash

TUNDEV=$1
LOCALIP=$4
REMOTEIP=$5

# Send certain machines' traffic via the US VPN.
ip rule del pref 200
ip rule add from 192.168.1.22 table usvpn pref 200
ip route add default dev tun0 table usvpn

# MASQ anything heading out of tun0
iptables -t nat -F POSTROUTING
iptables -t nat -A POSTROUTING -s 192.168.1.0/24 -o $TUNDEV -j MASQUERADE

Comment: Hi MikeyB, I'll try this asap, many thanks. You have a few variables in your script, can you please give me more insight what these mean in my case?
Comment: The tunnel device, the local IP and the remote IP :) openvpn passes those into any scripts that it calls with the `--up` option.
Comment: Sorry, I probably wasn't clear enough. I meant that I noticed hardcoded devices (tun0 for example) and ips in your ip routes; are these different from your variables? Also, I dont see $LOCALIP or $REMOTEIP being used anywhere.
Comment: Hey MikeyB, I just got home and tried these commands. Basically it works for the host that I want over vpn; it routes the traffic for 192.168.1.112 to ppp0. However, all the other hosts in my network are not able to reach anything, what gives? Thanks!
Comment: Oops - yeah `tun0 == $TUNDEV`. Those rules are for a machine that is *not* the default gateway in my case, you'll need to adapt this for your situation. Such as not flushing `POSTROUTING` which is likely clobbering connectivity for all your other machines.
Comment: Excellent! I most figured out. Last question: 192.168.1.112 (now routing via ppp0) is also an https webserver; how can I make sure that I can still reach this from my public ip? Thanks!
Comment: Exclude traffic coming *from* the https port from being routed over the VPN.
Comment: I meant route requests that come in over ports 443, 22 to my public ip, which routes it over to the machine (192.168.1.112) that uses vpn
Comment: browser --> https --> public ip --> router --> machine 192.168.1.112 (ppp0)

Iptables: Selective PPTP VPN routing


How to determine the area of a rotated ellipse?

Question: The ellipse $6x^2+4xy+5y^2+8x+8y+1=0$ is neither expressed in terms of $x$; like $y=\pm\sqrt{a^2-x^2}$, nor in terms of $y$; like $x=\pm\sqrt{a^2-y^2}$.
Separation of $x$ (or $y%$) may be impossible.
I was thinking to let $x=r\cos(\theta)$, and $y=r\sin(\theta)$, and then integrating, but finding the limits of integration [with respect to $\theta$] is difficult, or may be impossible.
How to determine the area of the ellipse shown below?
Comment: Hint: Complete the Squares, Shift the centre to the origin and then convert to polar coordinates and integrate
Comment: Following David's comment, if you know how to classify quadratics with matrices and etc., say, you can use that to "make" your ellipse a canonical one (i.e. with center at the origin)  and then integrate there.
Comment: @DavidG, when completing the squares, the term $4xy$ disturbs. I have reached to $6(x+\frac{2}{3})^2+5(y+\frac{4}{5})^2=-4xy+\frac{73}{15}$
Answer: Consider the ellipse $Ax^2 + 2Hxy + By^2 + 2Gx + 2Fy + C = 0$. It is well known that (1) this conic is an ellipse iff $AB - H^2 > 0$, so that we can assume $A > 0$; and (2) assuming $A > 0,$ the ellipse has real points iff $L > 0$, where
$$L = AF^2 + BG^2 + CH^2 - ABC - 2FGH.$$
To find area of the ellipse, one can apply an affine transformation that doesn't change the area. Such a transformation is $x = \lambda y + z$ where $\lambda$ is any constant.
This gives
$$(A\lambda^2 + 2H\lambda + B)y^2 + 2(A\lambda + H)yz + Az^2 +2(G\lambda + F)y + 2Gz + C = 0.$$
Get rid of $yz$ by choosing $\lambda = -H/A.$ Then
$$(AB - H^2)y^2 + 2(FA - GH)y + A^2z^2 + 2GAz + AC = 0,$$
that is
$$(AB - H^2)\left(y - {{(AF - GH)}\over{AB - H^2}}\right)^2 + (Az + G)^2 - {{(AF - GH)^2}\over{AB - H^2}} - G^2 + AC = 0.$$
Moving the centre of the ellipse to the origin, this can be put as
$$(AB - H^2){y_1}^2 + A^2{z_1}^2 - K = 0,$$
where
$$K = {1\over{(AB - H^2)}}\left[ (AF - GH)^2 + (AB - H^2)(G^2 - AC)\right],$$
which reduces to $K = LA/(AB - H^2)$ (with $L$ as above). Hence the semi-axes of the transformed ellipse are
$a = \sqrt{K/(AB - H^2)}$ and $b = \sqrt{K}/A,$ and the required area is $\pi ab = \pi L/(AB - H^2)^{3/2}.$
In particular, the ellipse in the question has area $86\pi/26^{3/2}.$
Answer: Write the equation as:
$$\begin{pmatrix}x & y & 1\end{pmatrix}
\left(\begin{array}{ccc|c} \\&Q& &P \\ \\ \hline &P^T& &R \end{array}\right)
\begin{pmatrix}x \\ y \\ 1\end{pmatrix}
=\begin{pmatrix}x & y & 1\end{pmatrix}
\left(\begin{array}{cc|c}6 & 2 & 4 \\ 2 & 5 & 4 \\ \hline 4&4&1 \end{array}\right)
\begin{pmatrix}x \\ y \\ 1\end{pmatrix} = 0$$
Set the gradient equal to zero to find the translation (same as solving $Qx=-P$):
$$\nabla(6x^2+4xy+5y^2+8x+8y+1)=0 \Rightarrow \begin{cases}12x+4y+8=0\\4x+10y+8=0\end{cases} \Rightarrow x=-\frac 6{13}, y=-\frac 8{13}$$
So the translation vector $t=-\frac 1{13}\begin{pmatrix}6\\8\end{pmatrix}$.
Divide the equation by $-(P\cdot t + R)$ to normalize it. The resulting $Q'$ is:
$$Q'=-\frac{1}{P\cdot t + R}Q$$
Its determinant is the product of the eigenvalues, which are $\frac 1{a^2}$ and $\frac 1{b^2}$.
So:
$$\det Q' = \frac{1}{a^2b^2}$$
The area of an ellipse is $\pi a b$ so that:
$$\text{Area} = \pi a b = \frac{\pi}{\sqrt{\det Q'}} = \frac{\pi\cdot |P\cdot t+R|}{\sqrt{|\det Q|}}
=\frac{\pi\cdot |-\frac 1{13}(4\cdot 6 + 4\cdot 8)+1|}{\sqrt{|6\cdot 5-2\cdot 2|}}
=\frac{43\pi}{13\sqrt{26}}$$
The general formula is:
$$\text{Area}=\frac{\pi|P^TQ^{-1}P-R|}{\sqrt{|\det Q|}}$$
Comment: What is the original equation of the ellipse in terms of $Q,P,R,x,y$?
Comment: @TymaGaidash, let $\mathbf x=(x,y)$, then it is $\mathbf x^TQ\mathbf x+2P\mathbf x + R=0$.
Answer: The simplest way to compute the area is that of using the formulas given here to find semi-axes $a$ and $b$ and then area $=\pi ab$.
If you insist on using an integral, you can of course solve for $y$ to find two solutions
$$
y_\text{up/down}={1\over5}\left(
-2x-4\pm\sqrt{-26x^2-24x+3}
\right)
$$
and then compute the area as
$$
\int_{x_\text{left}}^{x_\text{right}}(y_{up}-y_{down})\,dx,
$$
where $x_\text{left/right}$ are the values of $x$ giving a vanishing square root.
Answer: For an ellipse rotated by the angle $\theta$, this should work.
$$I (\theta) = Ixx Cos^2(\theta) + Iyy Sin^2(\theta)$$
Comment: Welcome to MSE. For some basic information about writing mathematics at this site see, *e.g.*, [basic help on mathjax notation](/help/notation), [mathjax tutorial and quick reference](//math.meta.stackexchange.com/q/5020), [main meta site math tutorial](//meta.stackexchange.com/a/70559) and [equation editing how-to](//math.meta.stackexchange.com/q/1773).


How to shrink the padding of a  element to zero before shrinking the content?

Question: I'm trying to wrap my head around creating responsive web pages and currently try to understand how the HTML layouting engine decides which areas to shrink when.
My goal is to have two nested DIVs, the outer one using a padding at both sides for readability, and the inner one showing the actual content:

.section {
  padding-left: 10%;
  padding-right: 10%;
  background-color: red;
}

.content {
  background-color: blue;
}

    Hello, World!

Now, when shrinking the browser window, I'd like to first collapse the padding (i.e. the red area) and only actually have the content area become smaller once the padding is gone. Does anyone know how to get this working?
Comment: else you could write specific media queries, that first shrink the sections padding, and another query that shrink the content
Comment: the use of padding isn't the solution in this case ... what you want is to use max-width with the blue div and center it
Comment: if you need to check if the padding is zero - I would use jQuery. on window resize.
Answer:

.section {
  background-color: red;
}

.content {
  background-color: blue;
  margin: 0 auto;
  width: 300px;
}

    Hello, World!

I don't know if this what you wanted. I simply gave the content a fixed width and centered it.
In order for this to become responsive I suggest you play around with content's width property on different @media queries to be able to adjust on all kinds of devices.
Comment: This is exactly what I was looking for! I guess if I choose the content width as a breakpoint, I could have a media query which switches the width of the content to 100% as soon as I hit 300px.
Comment: @FrerichRaabe no need media query simply replace width with max-width
Answer: You can achieve this with use of css media queries. Here is the basic codepen.
I've just added following media query to the existing css. You can change the width in media query as you want. Here is the media query related stuff that can help.
   @media only screen and (max-width: 900px) {
    .section {
        background-color: lightblue;
        padding-left: 5%;
        padding-right: 5%;
    }
}

@media only screen and (max-width: 600px) {
    .section {
        background-color: lightblue;
        padding-left: 0;
        padding-right: 0;
    }
}

Comment: I like this solution! The only downside seems to be that you get a slight 'jump' in the layout, I guess: if I read this right (I'm still somewhat new to CSS media queries) you'll see a jump in the padding from 45 pixels to 0 pixels once you move the browser width from 900px to 899px, right?
Comment: Yes. You are right there will be sudden change in padding once the width goes above 900px and above 600px respectively.


iOS Text in label is hidden vertically

Question: I really don't know what is causing this, I added a label and when it is showing on the iPhone, it appears like this:

I'm really clueless on that one...
Comment: Check your title font size.
Comment: I have to reduce it really small in order for the text to appear. I tried to increase the label size with a larger font size but it didn't work.
Answer: Auto layout is messing with it. In Interface Builder, set the label's vertical content compression resistance priority to 1000.
Comment: Sorry, I don't always understand why auto layout makes the decisions it does. I know only how to tell it what's important to me.

iOS Text in label is hidden vertically


Diophantine equation

Question: There were 63 equal piles of plantain fruit put together and 7 single fruits. They were divided evenly among 23 travelers. What is the number in each pile. Consider the Diophantine equation 63x+7=23y
So I found one solution: -7= 6(-28)+23(7)
so then I plugged it into the formula to find all solutions and got
x=-28-23t and y=-28-6t
so then I got t<-1.2 and t<-4.7 but this range is huge.. where did I go wrong?
Answer: If you run the Extended Euclidean Algorithm on $63$ and $23$, you'll find that $63(-4)+23(11)=1$. This means that $63(-28)+23(77)=7$ and so $63(28)+7=23(77)$
This means that $63(28)+7=1771$ plantains were split among the $23$ travelers (each got $77$ fruits).
Where did you go wrong? I'm not sure. You didn't provide enough work to answer that. However, $6(-23)+23(7)=23 \not=7$. Next, your answer of a range "$t<-1.2$ and $t<-4.7$" just doesn't make sense. The given problem is clearly looking for an integer solution - not a range of real numbers.
Answer: 23y = 63x + 7 becomes 23y = 7(mod 63) which reduces to y = 14(mod 63).
So y = 14 + 63t. Substituting this y into the original equation you get
x = 5 + 23t. All possible answers are given by x = 5 + 23t and y = 14 + 63t.
If you use the Extended Euclidean Algorithm you get x = 28 + 23t and
y = 77 + 63t which is the same as above if you substute t = 1.

Diophantine equation


Is it possible to append Media's file browser to a certain node type?

Question: I have a certain node type with a canvas on it, allowing users to draw on the node. Basic functionality such as lines are working, but I'd like to allow people to upload images to it as well. Since the rest of the site is using the Media module (V2 dev), allowing users to browse the library and their personal uploads... I was hoping to be able to use it here as well.
The same question was posted as a support request in Media issue queue as well but so far there is no reponse: https://www.drupal.org/node/2423415
What I am looking for is a way to embed the media browser on the node and catch the path of the returned file so the JavaScript and the canvas can read it.
So far I've managed to add the media widget to the node with:
function mymodule_node_view($node, $view_mode, $langcode) {
  if($node->type == 'mytype') {
    $form = drupal_get_form('mymodule_media_form');

    // append a new field to the content
    $node->content['imageupload'] = array(
      '#markup' => drupal_render($form), // and render the form there
      '#weight' => 10,
    );
  }
}

function mymodule_media_form($form, &$form_state) {
  $form['file'] = array(
    '#type' => 'media-widget',
    '#title' => t('Image'),
    '#description' => t('Upload a file'),
  );
  return $form;
}

It shows the Media file upload button, but the dialog does not popup (due to missing JavaScripts I suppose). Is there a better way to load this field with all required JS etc? I do suppose I need to at least use hook_form() assuming I can't display a form field outside form context.
Answer: It appeared I had been using the wrong form element. My custom form was created as below:
function mymodule_file_upload_form($form, &$form_state) {
  $form['file'] = array(
    '#type' => 'media',
    '#title' => t('Choose an image'),
    '#description' => t('Choose an image'),
    '#tree' => TRUE,
    '#input' => TRUE,
    '#media_options' => array(
      'global' => array(
        'file_extensions' => 'gif jpg jpeg png',
        'file_directory' => 'conferences',
        'types' => array(
          'image',
        ),
        'schemes' => array(
          'private' => 'private',
        ),
        'enabledPlugins' => array(
          'upload',
          'media_default--media_browser_my_files',
        ),
      ),
    ),
  );

  return $form;
}

And then with some javascript I manged to get the fid of the file
$("form").on("change", "input.upload", function() {
  var val = $(this).val();
  $.ajax({
    url: Drupal.settings.basePath + 'draw/file/' + val,
    success: function(data) {
      src = data
    }
  });
});

That path was registered in hook_menu() to return the path of the private file as per:
function mymodule_menu() {
  $items['draw/file/%file'] = array(
    'page callback' => 'mymodule_page_file',
    'page arguments' => array(2),
    'access arguments' => 'view own private files',
  );
  return $items;
}

function mymodule_page_file($file) {
  global $user;
  if($user->uid == $file->uid) {
    echo file_create_url($file->uri); // Use echo to prevent theme to appear.
  }
}


jQuery Variables as Key in Key:Pair CSS attributes

Question: Is it possible to take something like:
$("div").css({
    "top": var1,
    "height": var2,
     etc.
});

And turn it into:
var dir = "top";
var length = "height";

$("div").css({
    dir: var1,
    length: var2,
     etc.
});

So far, the only way I can get it to work is by repeatedly declaring the lines separately, such as:
$("div").css(dir, var1);
$("div").css(length, var2);
$("div").css(etc.);

Does anyone have any other ideas? The reason I'm bothering with this is because I would like to be able to flip my module by 90 degrees (aka, have it go left to right or top to bottom), and to do that I'd have to have a universal variable for direction.
Answer: { "top": var1, "height": var2 } creates a JavaScript Object that has two user-defined properties. Unfortunately, JavaScript does not allow you to use variables as property names when defining an Object in this way.
You should be able to do it like this:
var o = {};
o[dir] = var1;
o[length] = var2;
$("div").css(o);

Comment: This is a really interesting solution. I'm going to have to give it more thought, but it definitely answers the question. Thanks!
Answer: Try this...
var myCss = {};
myCss[dir] = var1;
$("div").css(myCss);


Change Local Group Policies remotely on Windows workstations outside Windows domain

Question: Is it possible to change Local Group Policies on Windows workstations remotely outside a Windows domain? Furthermore, can a script be written that would change GP on several workstations one by one?
Thanks!
Answer: Assuming you have admin rights on that local computer or access to an account you could do the following:

launch an mmc (if you have to change accounts, then use runas from a cmd line to launch the mmc)
You can add the Group Policy snap-in from File, Add/Remove Snap-in
Choose `Group Policy Object Editor" and click Add
Change it from Local Computer by clicking "Browse" and then clicking "Another Computer" and typing in the name of the remote computer

As far as running a script...sure, but you'd have to be a lot more specific as to how you want to connect to the computers, whether you want it to run once remotely or at login, scheduled, etc. etc. etc.
Answer: You haven't said which version of Windows the workstations are running, but the easiest thing to do is to launch Group Policy editor to create the policies (like TheCleaner described).  Then copy the user and computer folders from the first machine's %systemroot%\system32\grouppolicy\ to the new machine's same location, then either reboot or run gpupdate /force.  This should work fine for both XP and 7.
As for running these remotely, you could either use PSExec to run gpupdate force, or you could use shutdown /r /m \\computername.  Both of these assume that you're running the command/script from a local account with credentials that have administrative rights on the target machine, or have specified those credentials for PSExec.


Prediction Accuracy - Another Measurement than MAPE

Question: I have the question for my prediction model, which estimates used car prices. For example:

Car: 20.000 km, real price: 32.000 Euro, prediction: 27.000 Euro --> MAPE: 15,6% , absolute difference : 5000 Euro
Car: 300.000 km, real price: 5.000 Euro, prediction: 3.000 Euro --> MAPE: 40,0% , absolute difference: 2.000 Euro

You see, everyone would say ok the second prediction is better but if you use MAPE, it says, the first prediction is better. So my question is, if there is a good measurement for measuring the prediction accuracy.
Comment: http://www.robjhyndman.com/papers/forecast-accuracy.pdf
Comment: Note that you have a sample size of 2.  You calculate the APE per observation and then take the mean of the 2.  Then you can say your model has a MAPE of 27.8%.  But you need more observations than 2 to calculate a reliable mean.  Often the median is used instead of the mean if the distribution is skewed (i.e. a few extreme values can significantly affect the mean).  Then compare MAPE of 2 models to select one.
This is well worth a read and is less involved than the previous link:
https://www.otexts.org/fpp/2/5
Answer: There are many, many, many ways of assessing forecast or prediction accuracy. This chapter in a very much recommended free online forecasting textbook gives a few of them.
Unfortunately, as you have found, different accuracy measures can give different answers to the question which forecast (or forecasting method) is better. Here, the first prediction has a lower Absolute Percentage Error (APE), but a higher Absolute Error (AE)... and the other way around for the second prediction. Scientific publications in forecasting will usually use multiple accuracy measures and hope that a consistent picture emerges.
Unfortunately, there is no "right" accuracy measure. You will need to think about what you actually want to do with your forecast. Which decision will you base on the forecast? Why are you forecasting the price of used cars? What are the consequences of a wrong forecast?

Do the consequences depend on the absolute error of the forecast? If so, use MAE.
Or do they depend on the percentage of the error? If so, use MAPE.
Do you need to get an interval or quantile forecast so you have enough "safety stock" in cash? If so, assess interval coverage.

However, note in particular that MAPE has a couple of serious problems. It is bounded for underforecasts, because you (probably) will never forecast below zero, so an underforecast cannot have a worse APE than 100%. But there is in principle nothing to keep you from forecasting too high - the car you predicted to cost 27,000 EUR could end up only costing 3,000 EUR, yielding an 800% error. Thus, the MAPE incentivizes you to forecast too low, that is, to bias your forecast. This effect is stronger if your actuals have a larger spread - as they seem to do in your case. Here is a simple illustration of this effect (full disclosure: I wrote that article.).
Bottom line: think about what you want to do with your forecast. Think carefully about whether your accuracy measure incentivizes you to get a "good" forecast. Consider looking at multiple accuracy measures.
Answer: MAPE is Mean Absolute Percent Error.
It makes sense to compare two models on their MAPE values. Since the errors are averaged out and it gives a measure of the overall model performance.
Ideally you should be comparing two models on the MAPE value and not two predictions.
When it comes to individual predictions higher the percentage error worse the prediction.
eg:
<code>Case 1: Real - $40,000 Pred - $39,000  Dev- $1000 PE - 2.5%
Case 2: Real - $2,000  Pred - $1,000   Dev- $1000 PE - 50%
</code>
The absolute deviations are the same ($1000).
It makes a bigger business impact if your predictions are off by $1000 in the second case than in the first.


Views SQL-query slow with big dataset and exposed filters

Question: I have a problem with a Drupal 6 site working with many nodes.
This is the SQL given by Views:
https://gist.github.com/ranbogmord/79bfa50e40db1322c9e0
The query takes 5-10s to run through and the specific content-type has 30 fields bound to itself. 21 of those are exposed.
Imagine this as orders in a business system.
Thanks!
Comment: Is your MySQL instance optimized?
Comment: @MPD fine tuning MySQL to his webapp is possible. Honestly I think the next lowest hanging fruit is a simple `EXPLAIN` diagnostic of what the query is doing.

Drupal is built to be good for 80%+ of use cases. I find I need to add additional indexes to tables when i start building my own queries or using EFQ. His Views search is no different -- it's a query builder; not a _smart_ query builder.
Answer: Try denormalising the database by storing the relevant node objects in a single caching table. You can model your database schema on that of the core caching tables. That should speed up the query by reducing the amount of joins. Also, put indexes on any columns used in where clauses. If you insert/update rows in your caching table on update/insert of nodes using hook_nodeapi, your caching table should remain fresh. You could then either replace the view with a db_query in a custom module, or you could expose your table to views.
I haven't tried it, but you may be able to achieve this using the D6 object cache module.


OS X: c++ xcode ncurses resize terminal

Question: with ncurses.h, i can create a c++ project in OS X.
Here is an example:
int main(int argc, char *argv[])
{
    // resizeterm(50, 50);
    initscr();
    // resizeterm(50, 50);
    move(10, 10);
    printw("%c", 'x');
    return 0;
}

I compile it in the terminal:
g++ -std=c++11 main.cpp -o main.o
g++ -std=c++11 -lncurses main.o

Then I get an executable file: a.out.
Now if I type ./a.out in the terminal, the terminal will will print x at the position (10, 10).
Now I want to change the size of the terminal. Meaning that when I run ./a.out, I can immediately get a terminal with the size that I set. Google gave me a function: resizeterm(int, int). But it doesn't work.
When I open a terminal, its size is 80 * 24 by default.
Then I execute ./a.out, the size of the terminal isn't changed. It's always 80 * 24.
Comment: I believe `resizeterm` only works with X11 windows.
Answer: ncurses responds to window-resizing events, i.e., SIGWINCH.  It does not resize the terminal (see manual page for resizeterm).
xterm and some other terminal emulators respond to an escape sequence which tells it to resize.  You can exercise that with the utility program resize, e.g.,
resize -s 40 80

to make 40 rows of 80 columns.  On OSX, Terminal.app responds to this escape sequence.  iTerm 2 does not.

OS X: c++ xcode ncurses resize terminal


Maximum given a list of integers, and any combination of the operators $( ) ,+, *$

Question: Given a list of integers, insert the operations $( ) +$ and $*$ to yield the maximum value.
Examples:
$2$ $1$ $1$ $2$ is maximized with $(2 + 1)  * (2 + 1) = 9,$ and $1$ $1$ $1$ $1$ $1$ $1$ is maximized with $(1 + 1 + 1) * (1 + 1 + 1) = 9.$
Is there an algorithm that works every time to solve this problem?
Comment: Start with the product of all numbers > 1. If there are ones, replace smaller int by it+1. Continue until no more 1 free
Comment: @RossMillikan: The links you include talks about partition of a single integer, in this problem the partitions are already fixed. If we have 4,1, then 2*3 is not a valid solution, even if 4+1=2+3. I do not think it is a duplicate of it.
Comment: That is true, but as I said in the comment you just keep all the numbers 3 and above solo in the product.  Then you group the $2$s and $1$s as the other questions say.
Answer: First, we will proof an optimal constructive method, next proof that constructive methods gives the best solution.
a)
Let $a=a_0a_1a_2\cdots$ the optimal solution found until now (where $a_i$ can be an addition of numbers). Let $x=a_0$ and $y=a_1a_2\cdots$, $a=xy$.
Now, we must include number $z$ in the solution. It can be included as new factor $xyz$ or as an addition to one of the already existing ones $(x+z)y$. The inequality to consider is:
$xyz \ge (x+z)y$
that concludes that:
if $z \ge 2$ then $xyz \ge (x+z)y$
if $z = 1$ then $xyz \lt (x+z)y$
in conclusion, new number must included multiplying all expression except if number is 1.
b) In case of new number equal to 1, add it to which existing factor?. The inequality is now:
$(x+1)y \ge x(y+1)$
with solution $y \ge x$, thus, add 1 to the smaller factor.
(initial case with $a=a_0$ is straightforward).
c) sequence to use in the constructive method.
Assume we must include two numbers $z_1$ and $z_2$. If both are greater than 1, the method will include both multiplying $a$, thus, same result if be include $z_1$ and next $z_2$ than if we include $z_2$ next $z_1$.
If both numbers are equal to one, obviously sequence is the same.
Finally, if we must include 1 and $z>1$, the sequences to consider are (assuming $x<y$ and $z<x$, $z<y$, remainder cases are straightforward):
$(x+1)yz \ge xy(z+1)$
with no solution, thus, include first $z$ next the 1.


Override default language via URL parameter

Question: With the Internationalization module, is there any way to override the default language selection?
We have a site with two languages, EN and FR, and we'd like to send out an email newsletter that has various links to the secondary (non-default) language content.
The Language Negotiation is set to "Path prefix with language fallback", and directs them to the default language, even if we use the full language prefixed URL, ie:
www.example.com/fr/content
--gets sent to--
www.example.com/en/content

What would be ideal is if we could pass an argument like this:
www.example.com/fr/content?force_language=FR

Any solutions out there?
Answer: It's been more than a few years since I've done this in Drupal 6, so things may be a bit vague and hazy. I do remember there being an order menu for this, where you could say that language gets selected first by cookie, then browser language, then user preference, then path prefix, or change the order entirely.


(Classical Guitar) How to play artificial harmonic chords

Question: I am currently learning the second and third bagatelles from William Walton's 'Five Bagatelles'. In the second bagatelle, there are chords played as artificial harmonics. Is there any specific technique for doing this? Here is what the sheet music says:

I am having difficulty re-creating the sound which i have heard in other performances of the piece. Is there a specific method for playing these chords?
Answer: The "o" above the chord indicates a harmonic as you've said. But I'm sure it means only the top note of the chord should ring out as a harmonic, not the whole chord.
I would finger the three (or so) notes of each chord with the left hand in the usual way, i.e. as the notes are written. Then when sounding the chords with the right hand, hold the index or middle finger lightly against the first string at its midpoint. Sound the notes together and lift the whole hand away as one action - you'll have a chord with one high octave chiming "above" it.
So your left hand will be playing chords as normal, the right hand will be plucking chords but with one finger reaching to around the 12-15th fret gently stopping the top string each time. (It is important to perform this without looking in any way flustered or distressed...)
This will be a demanding bit of technique. I've only used this in simpler ways by playing one bass or accompaniment line plus a melody line above it, picked out in harmonics. On the right hand the thumb plays the bass or accompaniment, the index finger stops melody note harmonics around the upper frets and the little/pinky finger plucks those harmonics nearer the bridge. (Think "Albatross".)
Comment: Perhaps playing the harmonics with your index finger, and plucking with the nail of the middle or ring finger?
Comment: While you may discover many examples, you can certainly find youtube videos of Steve Morse utilizing the technique that @Aric describes, including this instruction video on artificial harmonics. See https://www.youtube.com/watch?v=qadApQ6_K48 for details. I should add that while he illustrates a pick plus finger, he also uses exclusively fingers in some fingerstyle pieces.
Comment: Looking at the direction of the note stems i think you are right. The highest note is a different voice to the other two, indicating the harmonic only applies to the top note.
Comment: @AricFowler good point about the note stems - I hadn't noticed those. Just watched a performance of this [by Bream on youtube](https://www.youtube.com/watch?v=Wk4RsE7VJ7I) and his fingers are partly hidden, but it looks like his picking hand is a little further up the strings, with his index finger lightly stopping the harmonics around frets 12-15, and the rest of picking hand is at his (relatively) normal picking angle. I guess his little fingernail is picking the top string quite firmly to get that sound.
Comment: Yes I suppose you would use any finger that's nearest the string you want to sound. With chords like this you'll probably need to experiment to find which finger works best... Looking at the ease with which Bream played it, I've just lowered my opinion of my own technique :)
Comment: Bream has that effect on most guitarists, i think. Now that I know about the note stems and voices, i'm sure i will be able to come up with something.
Comment: that is a great video
Answer: With the right hand I would position the index over the harmonic note and use the middle, ring, and pinky to pluck the chord.
Ps. Be sure to grow the pinky nail. :)


application of vectors: parachute in the wind

Question: Parachute in the wind. In still air, a parachute with a payload would fall vertically at terminal speed of 4 m/s. Find the direction and magnitude of its terminal velocity relative to the ground if it falls in a stead wind blowing horizontally west to east at 10 m/s.
So I went about this problem by drawing a right triangle. I had 10 m/s be the horizontal component and 4 m/s be the vertical component. I applied the pythagorean theorem and found the magnitude of its terminal velocity relative to the ground to be 10.8 m/s.
Then to find the direction I did intense tangent for the horizontal and vertical components and got 21.8 degrees. I am just now very confused how I find the direction like is it North of east, South of east..etc. Can someone please explain step by step?
Answer: We are adding two vectors which are perpendicular to each other; one with magnitude $4$ and direction downwards and the other with magnitude $10$ and direction eastward.
You are correct in drawing the right triangle and the magnitude calculation, but perhaps it would help to understand where the triangle is drawn to find the direction. Let us examine the right triangle with the eastward vector and a translation of the downward vector east as legs. Using basic trigonometry, we find the angle is $\arctan\left(\frac{4}{10}\right),$ which is about $21.8$ degrees. Looking at the triangle, we see that this angle is below east, since the parachute is losing altitude.
Our final answer is $\boxed{21.8^{\circ}}$ below east at a speed of $\boxed{10.8\frac{\text{m}}{\text{s}}}.$


Android: UUID and Licensing

Question: I am looking to find the most efficient way to create an application that has a 30 day trial and then forces the user to buy the full paid version if they like the demo's features.
I was looking for suggestions as the best way to implement a license for the app. Here were some thoughts I had:
-Sharedprefs - This would work until the user uninstalled and reinstalled the app. The trial period would essentially start over.
-Use Device ID - I thought I could get a device serial number and upload the data to a server. Then I came accross http://android-developers.blogspot.com/2011/03/identifying-app-installations.html that showed the issues with trying to get a user id for a device.
UUID- It seemed like this was the best option. However, would someone be able to give me an overview of how to implement this and how it works. Also what are the limitations.
Answer: A sample implementation is  already presented in the blog that you have cited.
Limitations: For your case, UUID won't work. Since, the user can actually delete whatever file/UUID you use for tracking (not easy, but doable)
Your requirement is to track devices. So, perhaps, go for telephony ID, Mac ID or a combination of both.
Comment: I would recommend generating a hash of the tel-id or mac-id. For Security Reasons :-)
Comment: You probably don't even want to track *devices* but *users*, as in the *google account's* user name.
Comment: What can you get the MAC ID of? Wifi and Bluetooth may be disabled so it is hit or miss to get that. Is there something else that is standard to be able to easily get the MAC address of?
Comment: Nope. If the devices are switched off you have to fall back on something else. You could perhaps use the ANDROID_ID in this case.

Android: UUID and Licensing


a little confusion over celery terminology

Question: hi I am a little confused over celeryd and celeryd_multi - what is the difference between this two? I mean, so far I have been using python manage.py celeryd, but i came across celeryd_multi today and couldn't find any explanation. According to the docs, -c indicates Number of child processes processing the queue, so if thats the case, whats celeryd_multi's usage?
Answer: celeryd command launches single celery worker. celeryd_multi command manages multiple celery workers. With celeryd_multi you can start/stop/restart multiple celery workers.
celeryd_multi can be used to manage multiple celeryd workers listening to different queues:
$ celeryd-multi start image video data -c 3

This command is equivalent to:
$ celeryd -n image.myhost -c 3
$ celeryd -n video.myhost -c 3
$ celeryd -n data.myhost -c 3


Is there a possibility to ignore words in Microsoft Text To Speech using SAPI?

Question: I'm developing a Text-To-Speech application using Microsoft SAPI. The ISpVoice::Speak works great, however some special characters are spoken aloud and shouldn't be. These spoken characters are (/, * _)
I have found out that it is possible to create rules, but only using Speech Recognition (source). I wonder if it is possible to implement it in Text-To-Speech. Here is some code if it helps.
int ttsSpeak( const char* text ) //Text to Speech speaking function
{
   if( SUCCEEDED(hr) )
   {
      hr = SpEnumTokens( SPCAT_VOICES, NULL, NULL, &cpEnum );

      cpEnum->Item( saveVoice, &cpVoiceToken ); //get saveVoice token defined at line 136
      cpVoice->SetVoice( cpVoiceToken ); //Initialization of the voice

      int wchars_num = MultiByteToWideChar( CP_ACP, 0, text, -1, NULL, 0 );
      wchar_t* wstr = new wchar_t[ wchars_num ];
      MultiByteToWideChar( CP_ACP, 0, text, -1, wstr, wchars_num );

      //skip characters ( /, *, _ )

      printf( "Text To Speech processing\n" );
      hr = cpVoice->Speak( wstr, SPF_DEFAULT, NULL );

      saveText = text;

      cpEnum.Release();
      cpVoiceToken.Release();
      delete new wchar_t[ wchars_num ];
   }
   else
   {
      printf( "Could not speak entered text\n" );
   }

   return true;
}

Is it possible to skip characters being spoken aloud? For example, I create an XML file where I can define what the engine can say, and cannot.
Comment: Why don't you just preprocess the text before speaking it?
Comment: When you say "preprocess the text" you mean modify it? Your question put me back on track and I managed to solve my problem :)
I will post my solution.
Answer: I managed to solve my issue thanks to Eric's comment. If you modifiy the text before the engine speaks it, you can remove the characters you want. Here is the code which allows to preprocess the text
  string strText( text ); //transform the const char* text into string
  string specialChars = "/*_"; //define the characters you want to skip
  string::iterator it; //declare iterator
  for( it = strText.begin(); it < strText.end(); it++ ) //loop through the sentence
  {
     bool found = specialChars.find( *it ) != string::npos;
     if( found )
     {
        *it = ' ';
     }
  }


Firestore then() function not executing after set()

Question: I am creating a new document in the firestore using set function. I want to use the document data after the set function pushes data into the database.
            // Add each record to their respective heads
        let docRef = headCollectionRef.doc(data.headSlug).collection(recordsCollection)
            .doc(String(data.recordData.sNo))
        docRef.set(data).then(docSnap => {
            agreementData.push(
                docSnap.get().then(data => {
                    return data
                })
            )
        })

Nothing written in the then() is being executed.
Any help is much appreciated
Answer: set returns Promise<void>, so you don't have access to the doc data inside then.
This is a situation where async/await will make your code much easier to read.
async function cool() {
  const docRef = headCollectionRef.doc(...)

  await docRef.set(data)

  const docSnap = await docRef.get()

  agreementData.push( docSnap.data() )

}

https://firebase.google.com/docs/reference/js/firebase.firestore.DocumentReference#set
Comment: This is not working. As the question says 'then' is not working, it's not about the data being there inside 'then'. So the problem is basically the set method doesn't get resolved anytime. So whatever code you will write past await won't get executed. Atleast this is not working for me.


Why is R^2 negative in my multiple linear regression model in python?

Question: i want to evaluate the organization based on the number of satisfied customers
and the r^2 is negative
this is the original data
    SECTOR  price   profit  INSPECTION  licenses    PR  CS(S)   CS(NOT S)   A(s)    A (nonS)
0   A   3809    1643    6834.0  499.0   4053    203.0   45.0     NaN        NAN
1   B   18608   16270   6828.0  2815.0  10923   35.0    5.0      1980.0     200
2   C   3814    1861    2375.0  509.0   2107    99.0    43.0     NaN        NaN
3   A   15869   20293   2595.0  2206.0  5285    30.0    5.0      1150.0     NaN
4   B   5663    1881    3629.0  734.0   5667    220.0   55.0     NaN        565.0

and A(s) stands for the number of satisfied customers for the whole sectors meaning 200 include the services provided by sector A B and C
i foucused on sector B and does it affect A(s) or not
converted Sector so dummy and then deleted A and C sectors
this is what i have now
df1.corr()

price        profit     INSPECTION  licenses        PR       A(s)
CLEARANCE   1.000000    0.376304    0.211653    -0.044924   0.397780 0.389236
PERMITS     0.376304    1.000000    -0.021812   -0.158237   0.089504    0.373245
INSPECTION  0.211653    -0.021812   1.000000    0.573478    0.438797    0.245204
Facilities licenses     -0.044924   -0.158237   0.573478    1.000000    0.050931    -0.164353
PR  0.397780    0.089504    0.438797    0.050931    1.000000    0.497360

x = np.array(df1.drop(['A(s)'], axis=1))
y = df1['A(s)'].values
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(x, y, test_size = 1/3, random_state = 0)

from sklearn.linear_model import LinearRegression
regressor = LinearRegression()
regressor.fit(X_train, y_train)

# Predicting the Test set results
y_pred = regressor.predict(X_test)

from sklearn.metrics import r2_score

r2_score(regressor.predict(X_test), y_test)

the result of r^2
-0.6052320362843366
i do not know why the sign is negative
please help and thank you
Answer: It means that your sum of squared residuals is greater than the sum of squared residuals of a model that always predicts the out-of-sample mean. This can be regarded as a baseline, "must beat" model. That you cannot achieve stronger performance than this baseline model means that your model is not doing a good job of predicting. While this might seem disappointing, you do out-of-sample testing to catch when you have such a model, so not all is lost.
I dislike the sklearn implementation of out-of-sample $R^2$ and find it to lack motivation. However, I would expect your training and testing means to be similar, so the $R^2$ you've reported is unlikely to differ much from what I would get from my preferred calculation.
Note that a linear regression, fitted using ordinary least squares, is guaranteed to have a non-negative in-sample $R^2$ as long as the model contains an intercept. Deviating from that situation, however, either because you use a nonlinear model, a linear model estimated by a method other than minimizing the sum of squared residuals, excluding an intercept, or measuring out-of-sample $R^2$, removes such a guarantee, as you have seen from your result.
Comment: can you please tell me how to fix this problem and should i use another model?
Comment: It's a matter of the usual strategies for predictive modeling. Beyond that, your question is essentially asking how to do machine learning. Do you have a more specific question? If so, please consider posting a new question to ask.
Answer: This looks like a bug.
If you get negative r^2 on your test data (IIRC) with linear regression, it means your test data has a diff mean from your training data (or you are lacking an intercept).
sklearn defaults to using intercept.
Since you are doing a train test split and nothing else, you would not expect the data sets to differ.
I suspect that changing the random state to a non zero number might help.maybe 0 means that it doesn't shuffle the data and your data is ordered somehow?
Comment: Sorry, this is not correct. It is fine to get $R^2<0$ on test data. That does not indicate a bug, just a poor model. This applies whether the out-of-sample data have the same mean as the in-sample data or not. // Just splitting the data randomly would cause the means of the train and test sets to be equal *in expected value*, yes, but not necessarily equal in any given split. (In fact, it would be quite surprising for the observed train and test means to be exactly equal.)
Comment: yes it is a "poor" model, because it cannot even fit the mean of the test data. *assuming* that the data is randomly split, this should not happen.  which is why I suggest a bug.
Comment: What do you mean by fitting the mean of the test data, and why do you have to be able to do this?


Como centralizar texto na DIV fazendo com que as linhas se alinhem à esquerda?

Question: Eu tenho uma
 com a propriedade text-align: center; para que o texto fique centralizado, porém eu quero que as linhas do textos comecem sempre à esquerda.
Abaixo está um exemplo do que eu quero:

-----------------------------
|                           |
|      Olá pessoal          |
|      Este é um exemplo.   |
|      Do que eu quero.     |
|                           |
-----------------------------

Como posso fazer isso? É possível? O código que eu estou utilizando é este:

#myDiv {
    text-align: center;
}

        Dado 1: 334
Dado 2: 192.2
Dado 3: 3455.234

Answer: Pode simplesmente criar um sub-elemento que seja display: inline-block;, o elemento com inline-block não vai ocupar "100%", não especifique medida, apenas deixe que o texto o ajuste, então deverá ficar assim:

#myDiv {
    text-align: center;
}

#info {
    text-align: left;
    display: inline-block;
}

        Dado 1: 334
Dado 2: 192.2
Dado 3: 3455.234

Se realmente vai usar outros elementos antes do #info você pode usar um simples
 para separar:

#myDiv {
    text-align: center;
}

#info {
    text-align: left;
    display: inline-block;
}

foo

bar

baz

        Dado 1: 334
Dado 2: 192.2
Dado 3: 3455.234

Ou pode criar um "sub-div" dentro de #info e aplicar nela o display: inline-block; ao invés de aplicar no #info
Comment: @LuizFelipe sim, devo ressaltar que usar flex para algo tão trivial assim é como contratar um engenheiro hidráulico para dar descarga no seu vazo por você. Flex e grid são coisas que tem uma série de caracteristicas, inclusive afetam o elemento pai, o que já é outro problema, tem que entender o comportamento do box-model (https://www.w3.org/TR/css-box-3/) que é algo que se perdemos pode complicar bastante em uma falha dificil de detectar, acaso ocorra uma falha.
Comment: Devo concordar. :-)


Getting only needed elements form array in MongoDb Schema

Question: I want to get only those element from notes Array that match the given tag from tags array in notes.
For example : If I want to get only those notes from notes Array having lrn tag in tags array but I am getting either the whole object or only the first matching note.
My Schema :
const mongoose = require('mongoose');

const noteSchema = new mongoose.Schema({
   user : {
       type: String,
       required: true,
       unique : true
   },

   notes : {
       type : [{
            title : {
                type: String,
                required: true
            },
            tags : {
                type : [String],
                required: true
            },
            note: {
                type: String,
                required: true
            }
        }],
       required: true
   }
});

const Notebook = mongoose.model('NOTEBOOK', noteSchema);
module.exports = Notebook;

My sample data :
{ _id: ObjectId("621c3a41fa2fe3c07f43edc9"),
  user: '620c81434d8a65c1aa36e0d4',
  notes:
   [ { title: 'Eraning',
       tags: [ 'ern', 'lrn', 'dik', 'pik', 'sik' ],
       note: 'Prior to his return, Craig worked at NeXT, followed by Apple, and then spent a decade at Ariba, an internet e-commerce pioneer where he held several roles including chief technology officer.\nPrior to his return, Craig worked at NeXT, followed by Apple, and then spent a decade at Ariba, an internet e-commerce pioneer where he held several roles including chief technology officer.\n',
       _id: ObjectId("62205a32bab7aed6315195e9") },
     { title: 'Lerningngs',
       tags: [ 'lrn', 'eat', 'drink' ],
       note: 'Prior to his return, Craig worked at NeXT, followed by Apple, and then spent a decade at Ariba, an internet e-commerce pioneer where he held several roles including chief technology officer.\n',
       _id: ObjectId("6220583cbab7aed63151958b") },
     { title: 'Learning',
       tags: [ 'learn', 'eran', 'buy', 'sell' ],
       note: 'Prior to his return, Craig worked at NeXT, followed by Apple, and then spent a decade at Ariba, an internet e-commerce pioneer where he held several roles including chief technology officer.Solving DSA from Maths.in and SolveMaths.org using great techniques by INDIA and RUSSIA.\n',
       _id: ObjectId("6220532dbab7aed631519531") },
     { title: 'Biology',
       tags: [ 'tissue', 'cell', 'myto', 'energy', 'glycogen', 'hydrogen' ],
       note: 'Prior to his return, Craig worked at NeXT, followed by Apple, and then spent a decade at Ariba, an internet e-commerce pioneer where he held several roles including chief technology officer.Solving DSA from Maths.in and SolveMaths.org using great techniques by INDIA and RUSSIA.\n\n',
       _id: ObjectId("621f88d4c189c6b5501c3d5f") },
     { title: 'Chemistry',
       tags: [ 'this', 'is', 'great', 'thing', 'to', 'do', 'by', 'time' ],
       note: '          Prior to his return, Craig worked at NeXT, followed by Apple, \n          and then spent a decade at Ariba, an internet e-commerce pioneer \n          where he held several roles including chief technology officer.\n',
       _id: ObjectId("621f85e9c189c6b5501c3d49") },
     { title: 'Physics',
       tags:
        [ 'newtonlawsofmotion',
          'ktg',
          'thermo',
          'fluid',
          'mechanice',
          'bernaulii' ],
       note: 'P\' + hrg + 1/2rv^2 = constant',
       _id: ObjectId("621f8520c189c6b5501c3d3f") },
     { title: 'Maths',
       tags: [ 'trignometry', 'llp', 'continuity', 'tags', 'circle' ],
       note: 'Solving DSA from Maths.in and SolveMaths.org using great techniques by INDIA and RUSSIA.',
       _id: ObjectId("621f84d7c189c6b5501c3d37") },
     { title: 'DSA from Net',
       tags: [ 'dp', 'stack', 'queue', 'heaps', 'sorting' ],
       note: 'Solving DSA from Leetcode.in and GeeksforGeeks.org',
       _id: ObjectId("621c3a41fa2fe3c07f43edca") } ],
  __v: 7 }

Answer: You can use $filter to get documents of given tag as shown below:
Notebook.findOne({
  user: "620c81434d8a65c1aa36e0d4" // user ID
},
{
  notes: {
    $filter: {
      input: "$notes",
      as: "note",
      cond: {
        $in: [
          "ern", // Tag to search
          "$$note.tags"
        ]
      }
    }
  }
})

Mongo Playground


In regression, what is the likelihood

Question: Notation for regression,
$$
  y = f_w(x)
$$
The regression function f() takes $x$ as input and is parameterized by $w$.
The posterior is $p(w|x,y)$.
Is the likelihood is then $p(x,y|w)$?
Or is it $p(y|x,w)$.
The first choice $p(x,y|w)$ would seem correct in that we have just switched the order of things across the conditional.
On the other hand, it also feels wrong, in that the regression input $x$ does not depend on $w$,
whereas $y$ does depend on $x$.
Answer: I think you mess together two things here. For the purpose of inference of weights of your regression model, you want to compute the posterior $p(w|x,y)$ which is proportional to the product of the likelihood and the prior, $p(x,y|w)p(w)$. In this context, the likelihood refers to your first proposal and evaluates how likely is a pair $(x,y)$ to appear according to your model with weights set to some particular $w$.
The other thing you talk about is the predictive distribution: given a new sample $x'$, what is the distribution of $f(x')=y'$ according to the model? This is denoted $p(y'|x',x,y)$: it depends on the current input $x'$ and the training data $x, y$. It can be further expanded to $\int p(y'|x',w)p(w|x,y)\,\mathrm dw$.
This video provides some more explanation on the matter.
Answer: If I have read the question correctly, then you are right that $x$ does not depend on $w$. $x$ is the data that we are trying to learn from.
The likelihood is the probability of observing a given set of observations, given the value of the parameters, that is $p(x,y|w)$
Comment: It feels wrong to have x conditioned on w, since x does not depend on w.  Does this simplify then? Like p(x|w)=p(x), so  p(y,x|w) = p(y|x,w) p(x|w)  = p(y|x,w) p(x) ?

In regression, what is the likelihood


Wrong SID for Administrator account

Question: In researching my problem for this question, I discovered that the SID for the account in the domain named "Administrator" account is:
S-1-5-21-2025429265-492894223-1708537768-1124
That's got to be wrong, because real Administrator SID's end in 500.  Using the same domain key and looking for SID S-1-5-21-2025429265-492894223-1708537768-500 turns up nothing — the built-in Administrator account just isn't there.
I don't know when or how this happened and I'm still looking, but I'm pretty sure it's been like this long enough that I don't even have a backup I could restore that would address this.
Does anyone have any ideas for how to put it right?

Since the account I'm talking about apparently isn't clear, I mean the account referred to in the 2nd bullet point under the "Causes" heading in this knowledge base article:
http://support.microsoft.com/kb/248079

The Administrator account Well-Known Security Identifier, or SID (the account name can be renamed)
Comment: This is what I get for asking questions at 9:30 on a Saturday evening :/
Comment: Or 1pm on a beautiful Sunday Afternoon if you're in Sydney... so hang on, why am I here then?
Comment: Or on a Sunday morning at 4am in Central Europe.
Answer: Hmm... that's decidedly a "not supposed to happen" scenario. The RID 500 Administrator account is stamped with the "isCriticalSystemObject" attribute set to true, and to my knowledge LSASS is supposed to return an ERROR_DS_UNWILLING_TO_PERFORM error (0x80072035) if you were to try and delete it. (I don't have a scratch AD sitting around in any of my VMs right now to give it a shot. Maybe later...)
How are you searching AD, anyway?
From AD Users and Computers, do a "Find" at the root of the domain, choose a "Custom Search" in the "Find" dropdown, go to the "Advanced" tab, and enter the LDAP search filter "(objectSid=S-1-5-21-2025429265-492894223-1708537768-500)". That'll give you a subtree search of the domain from the root of the directory.
If you really have deleted your RID 500 Administrator account somehow I'd stronly consider contacting Microsoft Product Support Services. They can probably have something coded to re-create the account (if they don't already have such a tool). I can't imagine how you managed to delete it anyway, because the only way I could think to do that would be direct interaction with the database through ESE. I really didn't think there was any publicly-exposed API that would let you delete an object marked with "isCriticalSystemObject" set to True, and I don't think you can set it to False on the RID 500 Administrator, either. Hmmm...
You've got an interesting situation there. Let us know what the subtree search above returns.
Comment: Accepted because "it's not supposed to happen" is the right answer.  It ended up being easier to build a new domain.
Comment: "No items match the current search"
Comment: I was using a WMI query in a vbs script to do the lookup.
Comment: Zow! I wonder how you managed that. I'd get on the phone w/ PSS. That's utterly strange. Any idea how you think it might've happened?
Answer: That looks like a user SID; the only SID which ends in -500 is for the built-in account specifically named Administrator. (By default -- it can be renamed via group policy.)
You're a bit unclear with the phrase 'my Administrator account' -- if you mean your personal domain admin account, what you're seeing is correct. If you mean the account named Administrator, then I'd start checking group policy to find out what's happened to the built-in Administrator account -- perhaps someone has renamed it, then created another account named Administrator?
Comment: I mean the built-in account named Administrator whose SID is supposed to end with 500.  It's just gone.  There is no account with the proper SID and nothing remotely close in the Built-in group in AD Users and Computers.
Answer: Built-in account for what and where? A domain administrator account is not "built-in" as far as I know as it's a domain account - the built-in local administrator on a domain controller is only available in directory services restore mode or if you demote it back to a member server. At least that's my guess, but it may be wrong ^^
Anyhow, if it is gone and it should indeed exist a sid 500 administrator in a domain (beats me, someone else knows I guess ;) have you checked the Deleted Objects if it's been deleted?
Answer: What version of Windows?  Vista/2008 and later disable the built-in Administrator account by default.  I'm also not sure, from your description, whether you are looking at AD (domain) or SAM (non-domain).  You won't find that SID in AD for any domain=joined 2008 machine.
Comment: Check question I point to in the first link for more details.

Wrong SID for Administrator account


Preencher células com NA por uma sequencia lógica anual no R

Question: Eu tenho um dataframe com 25 pessoas e as respectivas idades de 2012 a 2015, mas em alguns anos as idades não foram preenchidas.
id<-c(1:25)
idade_2012<-c(21, 18, 19, 25, 20, 12, 12, 13, 14, 29, 40, 11, 15, 14, 24, 16, 14, 12, 13, 14, 12, 21, 14, 16, 13)
idade_2013<-c(22, NA, 20, NA, NA, 13, 13, 14, 15, 30, 41, 12, 16, 15, 25, NA, 15, 13, 14, 15, 13, 22, 15, NA, NA)
idade_2014<-c(NA, NA, NA, NA, NA, NA, 14, 15, 16, 31, NA, 13, 17, 16, 26, 18, NA, 14, 15, NA, 14, 23, 16, NA, NA)
idade_2015<-c(NA, NA, NA, 28, NA, 15, 15, 16, 17, NA, NA, 14, NA, 17, 27, 19, NA, 15, 16, NA, NA, 24, 17, NA, 16)

df<-data.frame(id, idade_2012, idade_2013, idade_2014, idade_2015)
df

df
Eu gostaria de obter como resultado um df todo preenchido com a sequencia lógica de idade, conforme imagem.
Answer: Eu não entendi o que você pretende com isso, mas parece que toda a informação que você precisa está em idade_2012
Para preencher as outras colunas basta fazer
id<-c(1:25)
idade_2012 <- c(21, 18, 19, 25, 20, 12, 12, 13, 14, 29, 40, 11, 15, 14, 24, 16, 14, 12, 13, 14, 12, 21, 14, 16, 13)
idade_2013 <- idade_2012 + 1
idade_2014 <- idade_2012 + 2
idade_2015 <- idade_2012 + 3

df<-data.frame(id, idade_2012, idade_2013, idade_2014, idade_2015)
df

Para um caso mais geral você pode obter o ano de nascimento de cada id com a biblioteca dplyr
library(dplyr)
df %>%
   gather(idade_ano, idade, -id) %>%
   filter(!is.na(idade)) %>%
   separate(idade_ano, c("prefix", "ano"), sep = "_") %>%
   mutate(ano = as.integer(ano)) %>%
   mutate(nascimento = ano - idade) %>%
   select(id, nascimento) %>%
   distinct()

Você deveria considerar eliminar as colunas idades e ficar apenas com o ano de nascimento, se possível.
Comment: Sim, mas em alguns casos eu não tenho 2012, 2013, 2014, dessa forma com esse script não daria certo.


Any good spell checkers for source code?

Question: I am constantly putting typos in my projects (google has officially ruined my spelling). Does anybody know of a plugin for VS or a general spell checker that will check string values that are in quotation marks (double and single), preferably free?
Answer: A google search yielded this VS Spell Check Add-on


convert original URL to friendly URL

Question: In my website there is a link to registered tutors. That link is something like this
http://www.myweb.com/profiles/tutors/index.php?tutorCode=1285&tutorName=Robert%20Sakoo&city=Sidny
So I need to rewrite this link something like this:
www.myweb.com/1285/Rober Sakoo

Can anybody tell me is it possible to rewrite above original URL to my expected URL?
Answer: You seem to be confused with how URLs and rewriting works. The notion that "I need to rewrite this2 to this1 " means:

Someone either enters this2 in their address bar or clicks on a this2 link.
Server sees a request for this2
Server has a set of rules to internally rewrite the request from this2 to this1
this1 is served to the browser

Note that the important concept in all of this is that the browser requests for the "this2" link, and the server internally rewrites the request to "this1". But this is probably not what you want at all, because then you'd be taking the ugly URLs and rewriting them to the nice looking URLs, sort of missing the point of friendly looking URLs.
Too often, especially around here, people ask for stuff like "I want to change this url to this url", or asking for rewrite when there's a 2 step redirect process. This is the 2nd step (which you are not asking for at all) which takes this1 and redirects the browser to this2 so that the url address bar changes to this2:

Someone either enters this1 in their address bar or clicks on a this1 link.
Server sees a request for this1
Server has a set of rules to externally redirect the browser to this2.
The browser's address bar now says this2
The browser requests this2
Server sees a request for this2
Server has a set of rules to internally rewrite the request from this2 to this1
this1 is served to the browser

So this whole round-about convolution is just so when the browser tries to go to this1, it gets redirected to this2 but still actually gets served the content from this1.
So I assume this must be what you want. Try putting this in your htaccess file:
RewriteEngine On

# check if the actual request if for "this1"
RewriteCond %{THE_REQUEST} ^[A-Z]{3,9}\ /profiles/tutors/index.php\?tutorCode=([0-9]+)&tutorName=([^&]+)&?([^\ ]+)
# redirect to "this2"
RewriteRule ^profiles/tutors/index\.php /%1/%2/?%3 [R=301,L,NE]

# now rewrite "this2" back to "this1"
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([0-9]+)/(.+)/$ /profiles/tutors/index.php?tutorCode=$1&tutorName=$2 [L,QSA]

Note that the city parameter is never being encoded in the friendly URL, so it's left as part of the query string. You could change this so that the friendly URL looks like: /id/name/city/ instead of just /id/name/, that modification should be trivial.
Comment: @user1543817 Of course, I mentioned that it would do exactly that in the last paragraph
Comment: now my profile/tutor/index.php file can't identify my css file. I placed it into this 'profile/styles/file.css'. can you tell me what is the reason for it?
Comment: @user1543817 That's a absolute/relative URI issue. Try adding a `` somewhere in your headers.
Comment: can I get some help from you?
Answer: That would be somewhere near:
RewriteEngine on
RewriteRule ^([0-9]+)/(.+)$ /profiles/tutors/index.php?tutorCode=$1&tutorName=$2 [NC,QSA]

Since you're not specifying what to do about it, i didn't take your city parameter into account, thus added QSA (Query String Append) to the rule so parameters in GET are still passed on to the script.
Comment: Well it's normal that it still displays the original URL in your browser's task bar, that's what "friendly URLs" are for. But if you place a script physically in /profiles/tutors/index.php then it should be executed. And yes the htaccess must be placed just in your root directory.
Comment: i just tested it and it's working, what does your browser show (+http status) when you enter www.lankainstitute.com/1285/Shamdhi in the task url ?
Comment: No it still display original url. Tell me where I need to place this .htaccess file. I just placed it in my root directory and Checked URL.
Comment: I tried.. But it is not working.. actually where I have gone wrong..??
Comment: i can only ask again : what does your browser show (+http status) when you enter www.lankainstitute.com/1285/Shamdhi in the url task bar ?
Comment: When I type www.lankainstitute.com/1285/Shamdhi in my browser's address bar I can get this error message 'This page has been accessed in error.' This messege come from my tutor profile index.php page.
Comment: Well if it comes from your /profiles/tutors/index.php script then it IS working, only your script generates an error but the rewrite actually seems to work.
Comment: Why this pretty url not display in browser's address bar??
Comment: You must be misanderstanding what you're doing here : the "pretty" URL is www.lankainstitute.com/1285/Shamdhi and when you enter it in the address bar it should remain there, we're not talking here about a visible redirect (!!) but about executing a certain script behind the scene. On the other hand, if you try to enter your script's URL directly i.e. www.lankainstitute.com/profiles/tutors/index.php?tutorCode=1285&tutorName=Shamdhi it will obviously just execute this script you requested from the browser.
Comment: Thanks for your comments. Dear darma tell me how can I change visible URL like unvisible scene.
Comment: Change the flags at the end of the rewrite rule to [NC,QSA,R] or [NC,QSA,R=301]. The second will tell the browser that it's a permanent redirection.

convert original URL to friendly URL


showModalBottomSheet handler and dismissble

Question: isDismissible: true, //not work
showDragHandle:true, //is outside BottomSheet container
this two feature dont worked for this
bottomsheet
<code>void _showBottomSheet(BuildContext context) {
    showModalBottomSheet<void>(
    context: context,
    isScrollControlled: true,
    isDismissible: true,
    showDragHandle:true,
    backgroundColor: Colors.transparent,
    builder: (BuildContext context) {
      return DraggableScrollableSheet(
        initialChildSize: 0.5,
        maxChildSize: 0.7, // Set the maximum height to 70% of the screen height
        minChildSize: 0.2,
        expand: false,
        builder: (BuildContext context, ScrollController scrollController) {
          return Container(
            color: Colors.white, // Background color of the bottom sheet
            child: SingleChildScrollView(
              controller: scrollController,
              child: Column(
                children: [
                  // Your content here
                ],
              ),
            ),
          );
        },
      );
    },
  );
}
</code>
Comment: It looks fine. How do you use this function?
Answer: By Default the isDismissable: true
check the documentation [https://api.flutter.dev/flutter/material/showModalBottomSheet.html]
Also check how do you use this function


New GPO not being applied, still overwritten by existing

Question: I created a new GPO to apply to a specific AD security group. This was created on a top-level OU "Org Users". There are 4 existing GPOs on this OU, so creating this was the 5th one. This new GPO "S_Pilot_GPO" was adjusted to be 1 in the link order.
This GPO sets: User Configuration->Administrative Templates->DP AD Client->Managed applications->PWM, "Managed logons" to Enabled.
(One of the existing GPOs, "DPKioskSettings", also applies the above User Configuration. Thus why I made the link order 1 for the new GPO)
The scope is applied to an AD security group "S_Pilot".
I have a user within "S_Pilot", but when they login to a device with said user this new GPO does not get applied. It is stuck getting applied with the original GPOs. rsop.msc indicates that "DPKioskSetting" is still being applied instead.
S_Pilot_GPO is linked to the OUs "Org Computers", and "Org Users". And "DPKioskSetting" is linked to "Org Computers", "Org Users", "Students", "Training Servers", and "View Desktops".
None of these GPOs are enforced.
What am I missing? Shouldn't the link order force this new GPO to override "DPKioskSetting"?
I attempted to make the new GPO Enforced, no difference.
Comment: If a GPO has only user settings (or only computer settings), it should only be linked to an OU containing users (or computers, as the case may be). Generally it's helpful for each GPO to only apply user **or** computer settings to keep things from getting confusing.
Comment: @ToddWilcox It started off linked to just "Org Users" (a user OU) and was still not being applied.
Comment: Is the user who is in the **S_Pilot** group also inside the **Org Users** OU?
Comment: @ToddWilcox Yes, they are part of that.
Comment: Is **S_Pilot** the only entity listed in the security filtering? You probably have to allow read permissions for **Authenticated Users** or the computer account cannot read the GPO for the user. You can grant read permissions without giving permission to apply the GPO.
Comment: @ToddWilcox That might be it!
Comment: Any errors in: Event Viewer -> Application and Services Logs -> Microsoft -> Windows -> GroupPolicy/Operational ? Get-WinEvent -ProviderName Microsoft-Windows-GroupPolicy -MaxEvents 100 | FL
Answer: Did you added the 'computer' read access to your GPO in the delegation tab ? As having a filter with a security group for the GPO without the everyone's user on it break the GPO from working, as the computer can't read that filtering before it's applied or not to the user.
Comment: Are you talking about say adding Authenticated Users in there?
Comment: @Zeno Technically, you can check my answer there for a full detail, same thing; https://serverfault.com/questions/784615/gpos-fail-to-apply-reason-inaccessible-empty-or-disabled-server-2012-r2-and/784630#784630
Comment: Yes, the delegation tab is set up just like all the other GPOs that are functioning just fine.
Comment: @Zeno You dont answer me if comuputer is there in read. As other GPO can be cached on the computer if they were working before the MS hotfix that changed that way of working with the GPO.
Comment: @Zeno Yes, or adding computer read only in the delegation tab, as you applied the GPO to a group only, and that block the gpo to be read when the computer check it
Comment: @Zeno You don't have to use **Authenticated Users** specifically, but when you create a new GPO, **Authenticated Users** is there by default, and it's usually easiest to leave it there and perhaps remove the rights to apply the GPO but leave the rights to read the GPO.
Answer: If any of these are set to enforced, they will take precedence regardless of order. Set the one you want to override defaults to enforced and make sure it's actually applied to the host they are logging into.
Comment: None of these are enforced. Shouldn't that mean I don't need to set the new one to enforced?
Comment: Yep, that is what I would try.
Comment: No luck. I did that, ran a gpupdate on the client, and no difference.
Comment: That sucks, something else is going on here then.


Como deve ser feito o backup perfeito do blog wordpress?

Question: Já faz um tempo que venho procurando na internet como fazer backup do tema que estou desenvolvendo no wordpress e do banco de dados.
Eu uso o xampp e o banco de dados no phpMyAdmin.
Eu encontrei diversos tutoriais, mas eu não estou sentindo segurança nesses tutoriais, pois quero um backup completo, com todas as configurações de plugins e todo o resto salvo, para que se um dia eu tiver um problema no site e eu perder tudo, eu possa pegar a ultima versão do backup e apenas coloca-lo no ar novamente. Sem grande esforço de procurar todos os plugins, fazer todas as configurações tudo de novo, pois apesar de eu ter pego um tema pronto, eu mudei muita coisa nele direto no php.
Quando digo backup perfeito, digo tudo, desde o banco de dados, plugins, posts, páginas criadas, configurações do tema, configurações dos plugins...
OBS: Estou usando o tema Oblique, segue o link:
https://wordpress.org/themes/oblique/
Como deve ser feito o backup desse modo? É possível? Se sim, por favor, me digam quais são as ferramentas que posso usar e como implementá-las?
Answer: Um "backup completo" do WordPress pode ser realizado guardando os seguintes dados:

Banco de Dados: Os estarão as informações de seus posts, páginas, configurações do sistema e também de alguns plugins e temas.
Arquivos do Diretório: Todos os arquivos que normalmente já vem na instalação padrão do WordPress (que como você informou, deve ter modificado) e também o diretório de temas e plugins.

Para realizar o backup do Banco de Dados, o próprio phpMyAdmin é uma boa alternativa, pois ele realiza a extração sem precisar ter muito conhecimento em SQL. Para os arquivos, qualquer cópia via FTP garante que seus dados estarão seguros localmente.
Se estiver lidando com mais de um site, e achar esse processo trabalhoso, recomendo utilizar uma plataforma de gerenciamento, como o InfiniteWP ou o ManageWP, por exemplo. Ambos facilitam esse processo de Backup dos sites para uma restauração rápida.
Comment: Felipe, o InfiniteWP ou o ManageWP, ele faz o backup do site(tema) + o banco de dados? Ou ele faz o backup só do tema WP mesmo?
Comment: Marcielli, conheço o InfiniteWP com propriedade para informar que ele realiza o backup completo (banco de dados + arquivos -- tema, plugins, etc ). Facilmente restaurável se necessário.
Comment: @FellipeSoares Cara tudo bem, seguinte estou tentando achar uma solução para fazer um backup completo de uma loja em wordpress/wooecommerce hospedada na hostgator e transferir para digitalocean, como se trata de um host compartilhado os recursos sao limitados vc sabe me dizer se esse InfiniteWP força muito o servidor podendo tirar o site do ar?   PQ eu nao to conseguindo por nada nesse mundo copiar a pasta wp-content do hostgator, nem o backup geral do site resolveu pois a pasta veio vazia.
Comment: @Erick, na configuração você define a quantidade de requisições que são feitas no servidor. Basta ajustar para algo que a HostGator aguente.


Trouble with conditional probabilities

Question: What would be the right way (if there is any) to calculate P(A|B1 and B2 and ... Bn), given that B1...Bn are independent and we know:

P(Bi) for i=1..n
P(A|Bi) for i=1..n
P(A)
Answer: Take a really simple case. Suppose $n=2$, $p(A)=p(B_1)=p(B_2)=\frac{1}{2}$, $p(B_1\cap B_2)=\frac{1}{4}$, $p(A\cap B_1)=p(A\cap B_2)=\frac{1}{4}$. Unfortunately, that does not determine $p(A|B_1\cap B_2)$. It could, for example, be (1) 0 or (2) $\frac{1}{2}$. Draw a Venn diagram. Case (1) is achieved by having no chance of $A$ unless we have just one of $B_1,B_2$. Case (2) is achieved by the opposite - no chance of $A$ unless we have either both or neither of $B_1,B_2$.

Trouble with conditional probabilities


sprite image leaving a shadow/tail while moving on screen

Question: My android game program has sprites moving on the screen, but they are leaving a trace/tail/shadow behind. I have tried different FPS unsuccessfully also tried canvas.drawARGB(100,0,0,0); which other thread suggested, it removes the tail but dims other sprites. Here'e the code
public class GameView extends SurfaceView {

    public GameView(Context context) {
        super(context);
        gameloopThread = new GameLoopThread(this);
        holder = getHolder();
        holder.addCallback(new Callback() {

            @Override
            public void surfaceChanged(SurfaceHolder holder, int format,
                    int width, int height) {
                // TODO Auto-generated method stub

            }

            @Override
            public void surfaceCreated(SurfaceHolder holder) {
                createSprites();
                gameloopThread.setRunning(true);
                gameloopThread.start();
                }

            @Override
            public void surfaceDestroyed(SurfaceHolder holder) {
                // TODO Auto-generated method stub
                boolean retry = true;
                gameloopThread.setRunning(false);
                while (retry) {
                       try {
                             gameloopThread.join();
                             retry = false;
                       } catch (InterruptedException e) {
                       }
                }
            }
        });

    }

    @Override
    protected void onDraw(Canvas canvas)
    {
        canvas.drawColor(color.black);
        for (int i = temps.size() -1; i>=0; i--) {
            temps.get(i).onDraw(canvas);
        }
        for (Sprite sprite : sprites) {
        //  canvas.drawARGB(8,8,8,8);  // mine
        sprite.onDraw(canvas);
        }
    }

    }
}

Heres the class for game loop
public class GameLoopThread extends Thread {
    static final long FPS = 10;

    @Override
    public void run(){
        long ticksPS = 1000/FPS;
        long startTime;
        long sleepTime;
        while (running) {
            Canvas c = null;
            startTime = System.currentTimeMillis();
            try {
                  c = view.getHolder().lockCanvas();
                  synchronized (view.getHolder())
                  {

                      view.onDraw(c);
                  }
            } finally {
                if (c != null) {
                    view.getHolder().unlockCanvasAndPost(c);
                }
            }
            sleepTime = ticksPS-(System.currentTimeMillis()-startTime);
            try {
                  if (sleepTime > 0)
                         sleep(sleepTime);
                  else
                      sleep(10); // sleep causes it to change speed and jerk, hi sleep hi jerk
            } catch (Exception e) {}
        }

    }

and the sprite class ....
public class Sprite {

     private GameView gameView;

    protected void onDraw(Canvas canvas)
    {
        update();
        int srcX = currentFrame * width;
        int srcY = getAnimationRow() * height;
        Rect src = new Rect(srcX, srcY, srcX+width, srcY + height);
        Rect dst = new Rect(x, y, x + width, y + height);

        canvas.drawBitmap(bmp, src, dst, null);
    }
    // direction = 0 up, 1 left, 2 down, 3 right
    // animation = 3 back, 1 left, 0 front, 2 right
    private int getAnimationRow() {

        return DIRECTION_TO_ANIMATION_MAP[direction];
    }

}

I can't find any method to recreate canvas after sprite change position. Help would be appreciated.
Answer: The problem is because of the frequency at which you call the onDraw() method. You need to increase the frames per second by either changing the value passed to the constant FPS in static final long FPS = 10; or to long ticksPS = 1000/FPS;
The side effect of increasing this value is that it will take more processor power and  your bitmaps will move faster and to reduce their speed, you need to change the rate at which x and y change in Rect dst = new Rect(x, y, x + width, y + height);
Comment: changed FPS, didn't help, i think its related to sleeptime but different processor will need different sleep before redraw, depending upon speed?
Answer: just add  canvas.drawColor(Color.BLACK);
or any color
i encountered the same problem and that code save my me


How to set hostname.domainname from dhcp

Question: Running Centos 6.x using dhcp, we want to set the hostname to be FQDN that's obtained from a combination of dhcp options.
As an example if I have two dhcp options
  option host-name "foobar";
  option domain-name "mydomain.com";
When a client obtains those options via dhcp I would like the hostname to show "foobar.mydomain.com".
Any idea on how to accomplish this?
Answer: For that you need to define this "ddns-hostname"
Like this:
host foobar {
  hardware ethernet c0:18:85:e3:13:31;
  fixed-address 10.1.1.129;
  option domain-name "example.org";
  option host-name "foobar";
  ddns-hostname "foobar.mydomain.com";
}

Comment: Would be great if you can accept it as an answer. will help others who are looking for same thing :)
Comment: Where does this code go?  does it go in `dhcpd.conf` ?
Answer: Assuming you're using ISC DHCPd (the most popular on *nix platforms by far)
For each host add:
host workstation101 {
    hardware ethernet 01:02:03:04:05:06;
}

To configure the domain name:
option domain-name "example.org";

These can go in a subnet directive, or out in the global configuration, in your dhcpd.conf file.
Comment: Looking in the file /var/lib/dhclient/dhclient-eth0.leases I see that both the host-name and domain-name are set, but when I type the command 'hostname' on the dhcp client, all I see is the hostname. The only place where I see the domain setting is in my /etc/resolve.conf as a search domain. This still doesn't answer the question on how to make the hostname command respond with the hostname.domainname.
Comment: Are you running CentOS on the client as well? Did you install a different DHCP Client than the one that comes with the OS?
Comment: The server and the client are on a different flavor of linux, but what difference does that make if the client picks up the option domain-name.
Answer: Beware, isc dhcpclient (at least on Linux Mint 18) does not appear to be able to be forced in to setting the hostname from the server.  I've spent hours trying to convince it to do so, and even when the server sends the hostname (and dhclient prints it in syslog!) dhclient ignores it.
Solution:  Install dhcpcd5 and run dhcpcd instead.  That's what I just did, and it worked perfectly.


Best labeler for the server room?

Question: Right now, I've got a Brother P-touch labeler that prints four or five sizes of text on one long label. It has features such as italics and bold. It's...non-ideal.
What do you use in your server room? I have heard of labelers that will print vertically as well as horizontally, or which can produce labels for cable management as well. I also think it would be great to be able to produce barcodes for my tapes (LTO-3).
So basically, I would like a labeler that prints normal, can print cable labels, and can print barcodes. Unicorn optional.
Any ideas, or could you even suggest the best labeler for each solution?
Answer: We use a P-Touch PT-1600 for our labeling.  It has just about every label format we have ever required and works well for servers, patch panels and cables.  My only complaint is that P-Touch tape is expensive.
The barcode format supported on the PT-1600 are: Code 39, I-2/5, EAN13, EAN8, UPC-A, UPC-E, CODABAR, EAN128, CODE128.
Comment: Now it's discontinued...
Comment: I've got one of these too!
Answer: I use the DYMO RhinoPRO 5000. It is hand held. It has a wire wrap mode and a very flexible nylon tape to allow labeling cat 5 cables and other wires. It also does the standard labels up to 3/4" wide. They also have heat shrink tubing labels for very hard to remove wire labeling. I have been using it for 6 months and have had good results.
Answer: I've used the Brother P-Touch 9500C which is a PC-connected label printer and have been very happy with it.

If you need to be able to also do one-off labels then the P-Touch 9600 also has a built-in keyboard.
The advantage of a computer-connected model is that they are extremely versatile and can be very handy when a lot of labels need to be printed.
Answer: We use this one, largely because the contractors we hire to run our wire (roughly 15k runs so far), use them to do all of their labeling. It's nice because it outputs labels more suitable for wiring, but can also print "normal" labels.
Comment: We use the Brady IDXPERT QUERTY model as it was what was recommended to us by our cable installers. It's great for wiring labels but there are enough different label types available for it to handle everything we want to do. I haven't hooked it up to a PC yet but that's on my endless to-do list...

http://www.bradyid.com/bradyid/pdv/100230/BRADYID_US_XPERT-KEY/Handheld-Labelers-and-Supplies/Handheld-Labelers/IDXPERT-Labeling-Printers/Overview.html
Answer: It has been a while since I've had to use one of these things myself, but I remember using one of the lower-end P-Touch models and those wobbly rubber keys that only worked 50% of the time drove me nuts.
You probably want to take a look at Brother's Telco page for their recommendations.  The PC-connectable printers have Windows printer drivers that can be used from just about any application, but in particular, they have very good integration with software that you may already be using for asset management (like D-Tools System Integrator 4.x/5.x, Simply Reliable Software SmartOffice, Holbrook Enterprises WireCAD, JDSU/Test-Um Plan-Um & Plan-Um AP, or Colorado vNetBuilder).
Answer: I have always found the Handheld P-touch to be the best solution for labeling a Data Center. It's Portable and versatile with it's functions of sequential and numbered labels.
I find that important because of the pattern we use.

DNS Name on Box Front
U-Number on Rear Rails
Cables always two lines. Top line is current connection. Bottom line is the destination (other end).

[Room / Data Center] - [Row Number] - [Rack Number] - [U-Number] - [PCI Slot / Device / Peripheral / Blade] - [Port]

The labels have always stuck in hot centers and cold centers. They don't easily rub off. They don't scratch easily. And with the available sizes and convention I listed above we know instantly what is what and where it is going.
Answer: Regardless of brand, a good hand-held should have a QWERTY keyboard. Commonly used symbols such as hyphen and underscore should be easy to find, not buried in a menu.
Answer: You need a label printer that you connect to your computer,
I don't have one right now but the last one could even print pictures.
(And those pictures could have been barcodes etc etc)
However the software was the limiting factor....
But is was a funny little thing to play with.
Maybe something like this???
alt text http://www.superwarehouse.com/images/products/brother_ql570.jpg
Answer: I use a P-Touch also. It will print up to 4 lines of text per label, either horizontal or vertical. Being PC connected there is almost no limit, as it can do graphics as well. If there is anything that the P-Touch won't do it's not a problem. It just happens that I work for a printing company that specialises in labels and we have a special machine for short runs which is perfect even for single labels.
Answer: We have both the P-Touch PT-9500PC and P-Touch PT-1600.
The PT-9500PC is handy for doing large batches of labels, like when rewiring a cabinet.  It has some nice software that allows imports from various sources, so if you have a rack management software that records ports and what not and does exports, it makes life a lot easier.
The PT-1600 is handy as a quick one time labeler.
As for the LTO tapes, the PT-9500PC software has a bunch of media related templates, you might find this site handy too.  It'll dump out PDF file with a various format labels and barcode stuff that prints on standard Avery label stock.

Best labeler for the server room?


replace a partial substring in notepad++

Question: I need to find a certain pattern in notepad++ and delete all of it. So the lines might be something like:
1,2,c(0,9,3),5,7,9,2
2,3,c(4,7,2),5,4,3,1

and I want to get back:
1,2,5,7,9,2
2,3,5,4,3,1

how should I do this?
Thanks
Comment: 1. Please include your current regex 2. What is the pattern? You want to strip out `,c(` something `)` ? Can there also be other letters than `c` ? ...
Comment: It is specifically ,c( something)
Answer:
Open the replace dialog
Select the radio button for regular expressions
Use the search pattern

^(.*?),c\(.*?\)(.*?$)

Replace it by

$1$2

This should match your lines and the both capture groups capture the parts you want to keep. Then we replace by the content of the both capture groups $1$2
Comment: @seb I think she wants to get `1,2,5` and not `1,2,3` (slipped over myself almost). So if I understood right, the `,c(1,2,3)` should be removed but unclear from what criteria. At least to me.
Comment: Changed my solution.
Comment: for some reason your code goes all the way to the end of the line and does stop at the next ")"  I found this solution, instead (?<=This is)(.*)(?=sentence). although this does not include the c( or ) just the stuff in between
Comment: My pattern is based on the 2 lines you provided. If the actual data is different, then the pattern would be different as well. The $ at the end of the pattern marks the end of the line. Feel free to experiment with it until it matches your actual data.
Comment: Oh, wow, what an oversight. My answer is totally wrong. Good catch, bobble bubble.
Comment: Yes sorry i should have added some values at the end to make it more noticeable sorry
Comment: Should work with my updated solution. Did you try it?


Divisibility rule of 7

Question: Prove that a positive integer is divisible by 7 if and only if the integer obtained by alternately adding and subtracting the three digit integers formed from the successive blocks of three decimal digits beginning with adding the block containing the units digit and working to the left is divisible by 7.
I tried using $10\equiv 3\pmod 7$ like the other divisibility rule proofs, but I don't think it works the same way for 7. A hint given in the book says 1001=(7)(11)(13)
Comment: $1 \equiv 1 \pmod {7}.$ $1000 \equiv -1 \pmod {7}.$  $1000000 \equiv 1 \pmod {7}.$  $1000000000 \equiv -1 \pmod {7}.$
Comment: @DERPYPENGUIN "if the integer obtained by alternately adding and subtracting the three digit integers formed from the successive blocks of three decimal digits beginning with adding the block containing the units digit and working to the left is divisible by 3." = **HEADACHE**... can you provide an example please?
Comment: Another manner: All integer $N$ can be written as $$N=\sum_{k=0}^n a_k7^k$$ where $a_k\in \{0,1,2,3,4,5,6\}$ (representation of $N$ in base $7$). This way you have $$N\text{ divisible by }\space 7\iff a_0=0$$.
Comment: See http://math.stackexchange.com/questions/328562/divisibility-criteria-for-7-11-13-17-19
Answer: Let $b=\overline{a_1a_2....a_n}$ be an n-digit number. We can break $b$ into parts, as follows:
$$
b= \overline{a_{n-2}a_{n-1}a_{n}} + 1000(\overline{a_{n-5}a_{n-4}a_{n-3}}) + 1000000(\overline{a_{n-8}a_{n-7}a_{n-6}}) + \ldots
$$
Al you do now, is note that $1001=7 \times 143$ and $999999=7 \times 142857$. Similarly, you can prove that $10^{6n+3} \equiv -1 \mod 7$ (which means that $10^{6n+3}$ leaves a remainder of $-1$ (or $6$) when divided by $7$) and $10^{6n} \equiv  1 \mod 7$. Thus, when we take remainders above:
$$
b \equiv \overline{a_{n-2}a_{n-1}a_{n}} + (-1)(\overline{a_{n-5}a_{n-4}a_{n-3}}) + (1)(\overline{a_{n-8}a_{n-7}a_{n-6}}) + \ldots \mod 7
$$
Thus, you can see where the pattern comes from. I'll leave the rigorous details to you.
By the way, I have simpler rule for division by $7$:

Take your number $\overline{a_1a_2\ldots a_n}$, remove the digit $a_n$, subtract $2a_n$ from the rest of the number namely $\overline{a_1a_2\ldots a_{n-1}}$. repeat this until you get a small number. If this number is divisible by $7$, then your number is divisible by $7$.

Note: instead of subtracting $2a_n$, we can even add $5a_n$, and the result remains.
I will leave it to you  to test this method out and to prove it.
Comment: @LalbahadurSahu That's easy. Suppose that your number is $10x+y$, where $y$ is the last digit and $x$ is the rest of the digits. Suppose that $10x+y$ is divisible by $7$. Then, $(10x+y)-21y = 10x - 20y = 10(x-2y)$ is also divisible by $7$. As $10$ is coprime to $7$, we get that $x-2y$ is a multiple of $7$, but that is exactly the rule I wrote (subtract $2a_n$ from the rest of the number). If you replace "divisible" by "not divisible", the argument is exactly the same. This proves the divisibility rule. You get the "add $5a_n$" part if you replace $-21y$ with $+49y$ instead.
Comment: How to work on the proof of the other rule you have given?
Comment: The advantage of the second rule over the first is that adding or subtracting a one digit number is really easy. If I'm not wrong (I need to check this), you can even "mix and match" : subtract twice the last digit whenever you want, and add five times it whenever you want. That makes the rule very versatile as well.
Comment: Thank you so much.
Comment: @LalbahadurSahu You are welcome!
Answer: Instead of divisible by $3$ it should be divisible by $7$.  The hint means that if you have $123456789=123 \cdot 10^6 + 456 \cdot 10^3 + 789 \cdot 1$ you can use that $10^6 \equiv 1 \pmod 7$ and $10^3 \equiv -1 \pmod 7$ to write $123456789=123 \cdot 10^6 + 456 \cdot 10^3 + 789 \cdot 1\equiv 123 + 456(-1) + 789 \pmod 7$

Divisibility rule of 7