text:
Q: Is it possible to change the keyboard layout when no operating system is installed on the computer? I installed ubuntu on my pc. I think there was a bug and it opened GNU GRUB command line. I can't write commands there because I am a dvorak user. If this happens to me in future again, I want to change my system keyboard layout. Is there a thing like that?

A: In theory, it could potentially be done with an extra computer(call it computer A). So, the keyboard is plugged into Computer A, and a USB cable plugs Computer A i into computer B's USB(your computer B is your computer with no OS). Computer A would run software that would read input from the keyboard, and change it in memory, and send it down the USB cable to Computer B. And so as far as computer B was concerned, a keyboard is attached. And you'd have full control over the layout of it.
Now for in practise
I looked up "hardware key remapper". And somebody did something with an arduino,
https://forum.colemak.com/topic/1561-arduinobased-hardware-keyboard-remapper/   but that is a very strange use of an arduino and it's not entirely clear to me how he managed to read from a USB keyboard or write to USB with it, but in theory it's possible and it seems he did it.  More typical basic uses of Arduino involve inputting from and outputting to little electronic components that one might put in a breadboard, so maybe he chopped up a USB cable and found a way to correctly interpret data coming from a keyboard. And a way to write in a way that suits writing to USB and in a way that emulates a keyboard.  He has linked to his code, so that may help.  There is a video here https://www.youtube.com/watch?v=RoG_-9lAnSI  Where somebody shows what to do on the hardware level to get an Arduino to act as a keyboard. His video shows that it seems he managed to get a USB 'B type socket soldered onto his Arduino. And he may have cut open a USB cable too.  There are probably many other videos on youtube of Arduino reading or writing to USB.  If you used a computer, even a small computer like a Raspberry Pi then it'd already have a USB socket on there for reading and writing, so it'd be easier, then you'd just need to know how to read and write to USB in your programming language. And how to interpret keyboard input. And how to send data down USB in a way that emulates a keyboard. But from a hardware perspective, i'd think things would be easier with a computer rather than an Arduino.
This guy has done keyboard input or writing  / emulation, with a Raspberry Pi(basically a very small computer), you see the hardware is much easier than with an Arduino, as a Raspberry Pi has one or even two USB connectors (And if it only had one then you can probably use a USB hub). The Raspberry Pi in the video has 2 USB connectors which is perfect for you  https://www.youtube.com/watch?v=-tC7nL7rVRE   Still a project though as you have to program it (which might not be that hard as lots of code is available online) and you'd have to get your Pi set up, that part is standard. But all the hardware is there for you unlike the Arduino that is more barebones.


text:
Q: During apachectl start getting open shared object file: No such file or directory After successfully installation of Apache2(2.4.4) i tried to start https server but i am getting below error
bimlesh@server:/usr/local/apache2/bin$ ./apachectl start
httpd: Syntax error on line 71 of /usr/local/apache2/conf/httpd.conf: Cannot load modules/mod_authn_core.so into server: /usr/local/apache2/modules/mod_authn_core.so: cannot open shared object file: No such file or directory
bimlesh@server:/usr/local/apache2/bin$

I looked at /usr/local/apache2/modules/ and really those .so files are not available.
Can anyone please help that how to get rid off.
if i look at /usr/local/apache2/modules/ folder then i see:(no .so files available)
bimlesh@server:/usr/local/apache2/bin$ ls ../modules/
httpd.exp             mod_authn_file.a        mod_cache_disk.a   mod_file_cache.a            mod_logio.la           mod_ratelimit.a        mod_socache_dbm.la
mod_access_compat.a   mod_authn_file.la       mod_cache_disk.la  mod_file_cache.la           mod_mime.a             mod_ratelimit.la       mod_socache_memcache.a
mod_access_compat.la  mod_authn_socache.a     mod_cache.la       mod_filter.a                mod_mime.la            mod_remoteip.a         mod_socache_memcache.la
mod_actions.a         mod_authn_socache.la    mod_cgid.a         mod_filter.la               mod_negotiation.a      mod_remoteip.la        mod_socache_shmcb.a
mod_actions.la        mod_authz_core.a        mod_cgid.la        mod_headers.a               mod_negotiation.la     mod_reqtimeout.a       mod_socache_shmcb.la
mod_alias.a           mod_authz_core.la       mod_dav.a          mod_headers.la              mod_proxy.a            mod_reqtimeout.la      mod_speling.a
mod_alias.la          mod_authz_dbd.a         mod_dav_fs.a       mod_include.a               mod_proxy_ajp.a        mod_request.a          mod_speling.la
mod_allowmethods.a    mod_authz_dbd.la        mod_dav_fs.la      mod_include.la              mod_proxy_ajp.la       mod_request.la         mod_status.a
mod_allowmethods.la   mod_authz_dbm.a         mod_dav.la         mod_info.a                  mod_proxy_balancer.a   mod_rewrite.a          mod_status.la
mod_auth_basic.a      mod_authz_dbm.la        mod_dbd.a          mod_info.la                 mod_proxy_balancer.la  mod_rewrite.la         mod_substitute.a
mod_auth_basic.la     mod_authz_groupfile.a   mod_dbd.la         mod_lbmethod_bybusyness.a   mod_proxy_connect.a    mod_sed.a              mod_substitute.la
mod_auth_digest.a     mod_authz_groupfile.la  mod_deflate.a      mod_lbmethod_bybusyness.la  mod_proxy_connect.la   mod_sed.la             mod_unique_id.a
mod_auth_digest.la    mod_authz_host.a        mod_deflate.la     mod_lbmethod_byrequests.a   mod_proxy_express.a    mod_session.a          mod_unique_id.la
mod_auth_form.a       mod_authz_host.la       mod_dir.a          mod_lbmethod_byrequests.la  mod_proxy_express.la   mod_session_cookie.a   mod_unixd.a
mod_auth_form.la      mod_authz_owner.a       mod_dir.la         mod_lbmethod_bytraffic.a    mod_proxy_fcgi.a       mod_session_cookie.la  mod_unixd.la
mod_authn_anon.a      mod_authz_owner.la      mod_dumpio.a       mod_lbmethod_bytraffic.la   mod_proxy_fcgi.la      mod_session_dbd.a      mod_userdir.a
mod_authn_anon.la     mod_authz_user.a        mod_dumpio.la      mod_lbmethod_heartbeat.a    mod_proxy_ftp.a        mod_session_dbd.la     mod_userdir.la
mod_authn_core.a      mod_authz_user.la       mod_env.a          mod_lbmethod_heartbeat.la   mod_proxy_ftp.la       mod_session.la         mod_version.a
mod_authn_core.la     mod_autoindex.a         mod_env.la         mod_log_config.a            mod_proxy_http.a       mod_setenvif.a         mod_version.la
mod_authn_dbd.a       mod_autoindex.la        mod_expires.a      mod_log_config.la           mod_proxy_http.la      mod_setenvif.la        mod_vhost_alias.a
mod_authn_dbd.la      mod_buffer.a            mod_expires.la     mod_log_debug.a             mod_proxy.la           mod_slotmem_shm.a      mod_vhost_alias.la
mod_authn_dbm.a       mod_buffer.la           mod_ext_filter.a   mod_log_debug.la            mod_proxy_scgi.a       mod_slotmem_shm.la
mod_authn_dbm.la      mod_cache.a             mod_ext_filter.la  mod_logio.a                 mod_proxy_scgi.la      mod_socache_dbm.a
bimlesh@server:/usr/local/apache2/bin$

A: Run
find / -type f -name mod_authn_core.so

or install updatedb ( mlocate, slocate, findutils or sth ) if needed and run
updatedb

and then ( or before )
locate mod_authn_core.so

To find out if these files are somewere else than they should be, and possibly fix location with symbolic link or moving files where they're expected to be.
If there is no file you need, you may need to comment it in httpd.conf ( if it's specific module ), or (re)install apache package(s). I believe mod_authn_core should be in basic package, not in separate module though. Possibly someone removed it blindly or accidentally, or some intruder messed up with system, or disk got broken or whatever else.
PS. Modules usually are under "lib" e.g. /usr/local/lib/apache2 or /usr/lib/apache2, or /usr/lib/apache2/modules or similar, not in /usr/local/apache2/modules, though it usually depends on compilation of package..
You might also run
apache2ctl -t -D DUMP_VHOSTS

to find out what modules were compiled as shared or static. You should also include information about distribution, and note you're building/installing from source.
Also, have look here: http://httpd.apache.org/docs/2.4/install.html#configure

redpajama_set_name: RedPajamaStackExchange


text:
Q: $r:\mathscr{S'}\rightarrow\mathscr{D'}$, $u\mapsto u|_{\mathscr{D}}$ is not a topological embedding Show that $r:\mathscr{S'}\rightarrow\mathscr{D'}$, $u\mapsto u|_{\mathscr{D}}$ is not a topological embedding.
For this problem, would it suffice to construct a sequence $\{u_n\}$ in $\mathscr{D'}$ such that $u_n\rightarrow 0$ in $\mathscr{D'}$, but $r(u_n)\nrightarrow 0$ in $\mathscr{S'}$. In that case, what would be an example of such a sequence?

A: First of all, this depends on the topologies, I assume you mean the weak$^*$ topologies $\sigma(\mathscr S',\mathscr S)$ and  $\sigma(\mathscr D',\mathscr D)$. Note that $r$ has dense range (it is the transposed of the inclusion $\mathscr D \hookrightarrow \mathscr S$) and $r$ is injective (because the inclusion  $\mathscr D \hookrightarrow \mathscr S$ has dense range). If $r$ were a topological embedding this would imply that $\mathscr S'$ and $\mathscr D'$ have the same dual. But, for any locally convex space $X$, we have $(X',\sigma(X',X))'=X$. Hence $\mathscr D \neq \mathscr S$ yields a contradiction.
EDIT. Here is a "concrete" argument as you wanted to have: Define $u_n\in \mathscr S'$ by $u_n(f)=e^n f^{(n)}(n)$. These are distributions with compact support hence they are tempered. For all $\varphi \in\mathscr D$ you have $u_n(\varphi)=0$ for all $n$ large enough (larger than an upper bound of the support of $\varphi$), hence $u_n\to 0 $ in $\mathscr D'$.
Using a smooth "cut-off" function you easily construct $f\in \mathscr S$ with $f(x)=e^{-x}$ for all $x\ge 0$. But then $u_n(f)=(-1)^n \not\to 0$, hence $u_n$ does not converge to $0$ in $\mathscr S'$.
Of course, the existence of such a sequence implies that $r$ is not a topological embedding. But one has to be careful with the converse implication: Two locally convex topologies on a vector space may have the same convergent sequences although they are different. A classical example is $\ell^1$ endowed with the norm and the weak topology ("Schur's lemma").


text:
Q: struct and struct-type function in header file I am new to C and I want to include my struct in a header file however I am not sure if what I did below is correct or not. I am sure that I need the struct to be declared in the header file, just not sure about if it is the right way to declare the struct type function search()
#ifndef BTREE_H_INCLUDED
#define BTREE_H_INCLUDED

struct bin_tree {
    char serial[30];
    int socket;
    struct bin_tree * right, * left;
};

typedef struct bin_tree node;

node* search(node ** tree, char *val);

#endif

A:
"I am not sure if what I did below is correct or not"

It is. Just note that passing an address of pointer (i.e. search function taking node ** tree) makes sense in situations when you want your function to change the pointer. Semantically, search doesn't seem to be one of those functions :)
And the small (rather cosmetic) improvement might be changing:
struct bin_tree {
    char serial[30];
    int socket;
    struct bin_tree * right, * left;    // <-- avoid declaring pointers this way
};

typedef struct bin_tree node;

into a single typedef:
typedef struct node {
    char serial[30];
    int socket;
    struct node * right;
    struct node * left;
} node;


text:
Q: Can a water vortex (whirlpool) be used to efficiently store energy? Either a large, constrained cylinder of water or a large volume of open water (perhaps in the ocean) could be persuaded to form a vortex by pumping energy in. The body of water would be acting as a fluid version of a flywheel, storing energy.
If one then removed the input energy, would the vortex continue for a significant time or would it quickly lose all its energy by heating up the water? Would storing energy in the rotational kinetic energy of a fluid be horribly inefficient compared to pumped-hydro storage?

A: As mentioned by other writers, water viscosity will rapidly convert any kinetic energy into heat. However, efficient energy storage could be attainable with superfluids. Superfluids are related to Bose-Einstein condensates. (but they are not always interchangeable) Their special property is having absolutely no viscosity, so a whirlpool of superfluid will rotate indefinitely.
The primary issue with this is the cryogenic temperatures required. Helium-4, for example, requires temperatures below 2.17K to reach superfluidity. The energy required to create and maintain such temperatures could exceed the amount of energy stored, making the system useless. Harvesting the energy could prove problematic. Since there isn't viscosity, a turbine would experience no drag. (to be precise, very little drag from residual viscosity)

A: Yes, this would be horribly inefficient compared to pumped hydro or even a regular flywheel.
With a rotating fluid, there's a lot of viscosity.  This viscosity generates heat and slows the fluid down.  You would be able to offset this somewhat if you kept the container for the fluid moving with the fluid itself; but even then I believe there would still be significant losses from internal viscous effects.  You would then also just have what is essentially a fluid filled flywheel, at which point you have to ask yourself why you didn't go with a solid material of higher density and likely better strength/stability.
The advantage of pumped hydro over this vortex system would be because a pumped hydro system doesn't require constant motion.  It stores the energy as potential, so it only loses energy to viscosity when it is moving the fluid to the storage tanks.  The less you have to move the fluid, the less you will convert energy to heat through viscosity.
It's an interesting idea, but I don't think it would be practical.


text:
Q: How would I find the solutions for $AX = 0?$ \begin{pmatrix}4&-6&2&-6\\ \:-2&3&-1&3\end{pmatrix}
Am I supposed to move the $0 $ to the other side of the equation and find the inverse of the matrix above or is there another way?

A: You are solving for the kernel of the matrix
\begin{pmatrix}4&-6&2&-6\\ \:-2&3&-1&3\end{pmatrix}
which is the same as solving the augmented system
$$
\begin{pmatrix}4&-6&2&-6&0\\ \:-2&3&-1&3&0\end{pmatrix}\rightarrow
\begin{pmatrix}0&0&0&0&0\\ \:-2&3&-1&3&0\end{pmatrix}
$$
from which we find that we have 3 degrees of freedom. Namely, we need only to make sure
$$
x=\frac32w-\frac32y-\frac12z
$$
and any input of $w,y,z$ will do. Encoding this, we name $y=s,z=t,w=r$ and find that
$$
\begin{pmatrix}3/2r-3/2s-1/2t\\s\\t\\r\end{pmatrix}=
r\begin{pmatrix}3/2\\0\\0\\1\end{pmatrix}+s\begin{pmatrix}-3/2\\1\\0\\0\end{pmatrix}+t\begin{pmatrix}-1/2\\0\\1\\0\end{pmatrix}
$$
and the vectors with the coefficients $r,t,s$ span your kernel.

A: A $4\times 2$ matrix can not have an inverse. You are searching for the kernel of $A$. With a few Gauss moves on the rows of $A$ you can simplify the sistem $A·x = 0$ getting the solutions. In this case the solution set, $\ker{A}$, is a subspace of dimension $2$, a plane, in $\mathbb{R}^4$.

A: Simply row reduce the coefficient matrix and let your independent variables (columns without leading ones) be your parameters. Being a homogenous system with 2 equations and 4 variables you will have infinite solutions (since every homogenous system has at least the trivial solution)

A: You have 4 variables and 2 equations. This implies that you have infinitly many solutions.


text:
Q: What is the syntax to instantiate a structured dtype in numpy? If I have a dtype like
foo = dtype([('chrom1', '<f4', (100,)), ('chrom2', '<f4', (13,))])

How can I create an instance of that dtype, as a scalar.
Background, in case There's A Better Way:
I want to efficiently represent arrays of scalars mapping directly to the bases in a genome, chromosome by chromosome.  I don't want arrays of these genomic arrays, each one is simply a structured set of scalars that I want to reference by name/position, and be able to add/subtract/etc.
It appears that dtype.type() is maybe the path forward, but I haven't found useful documentation for correctly calling this function yet.
So suppose I have:
chrom1_array = numpy.arange(100)
chrom2_array = numpy.arange(13)
genomic_array = foo.type([chrom1_array, chrom2_array])

That last line isn't right, but hopefully it conveys what I'm currently attempting.
Is this a horrible idea?  If so, what's the right idea?  If not, what's the correct way to implement it?
This sort of works, but is terrible:
 bar = np.zeros(1, dtype=[('chrom1', 'f4', 100), ('chrom2', 'f4', 13)])[0]

A: try this:
foo = np.dtype([('chrom1', '<f4', (100,)), ('chrom2', '<f4', (13,))])
t = np.zeros((), dtype=foo)


text:
Q: UTC Conversion to User Timezone with Daylight Savings Time OK I got my mySql timezone package installed from http://dev.mysql.com/downloads/timezones.html
I'm also storing all my times with UTC_TIMESTAMP();
And my little tidbit of code:
$_SESSION['user_tz'] = 'America/New_York';
$last = "CONVERT_TZ(p.posted_on, 'UTC', '{$_SESSION['user_tz']}')";

I get back UTC/GMT -5 hours which is an hour ahead because of daylight savings time (DST)
I've been checking searching stack overflow and google for a few hours now, still not quite sure how to work around this. I'm really confused as to how to work around this? Help is greatly appreciated.

A: write
 date_default_timezone_set('America/New_York');

Reference


text:
Q: Evaluation of this definite integral I want to obtain the symbollic expression for this integral:
$\int^\infty_{-\infty} \, dx \, \left(\frac{y - x}{R^2 + (y-x)^2}\right)\, e^{-\frac{(x - \mu)^2}{4 s^2} - \frac{i k (y - x)^2}{2 R}}$,
where $i$ is the imaginary unit and all other variables are real. With symbolic, I just want to make clear that the answer should maintain the form of all the variables, but $x$ in the final form of the result.
I have typed the following into Mathematica to try to get it to evaluate:
Integrate[Exp[-((x[i] - μ[i])^2/(4 s^2)) - (I k (y[i] - x[i])^2)/(2 R)]
          ((y[i] - x[i])/(R^2 + (y[i] - x[i])^2)), {x[i], -∞, ∞}]

I have also tried to simplify the expression first in terms of $x$ and then substitute it into the integral but the Mathematica returns the input after a long time.
What could be done to determine the result of this?

A: The integral probably can be evaluated analytically, but the answer will not be simple. Let $u$ be the integrand function.
u = Exp[-((x - \[Mu])^2/(4 s^2)) - (I k (y - x)^2)/(2 R)] ((y -
  x)/(R^2 + (y - x)^2))

After the substitution
v = u /. {y - x -> z, x -> y - z} /. y - \[Mu] -> \[Nu]

we obtain
$\frac{z}{R^2+z^2} \exp\left[-\frac{(\nu -z)^2}{4 s^2}-\frac{i k z^2}{2 R}\right]$
If $\nu$ is zero the integral is zero. This suggests to expand this expression in terms of $\nu$ to see if the integral is computable. For instance the term proportional to $\nu$ is given by
Assuming[{R > 0, \[Nu] > 0, k > 0, s > 0},
 Integrate[(E^(-((I k z^2)/(2 R)) - z^2/(4 s^2)) z^2 \[Nu])/(
2 s^2 (R^2 + z^2)), {z, -\[Infinity], \[Infinity]}]]

$\frac{\nu}{2 s^2}\left\{\frac{2 \sqrt{\pi } s}{\sqrt{1+\frac{2 i k s^2}{R}}}-\pi  R \exp\left[\frac{R \left(R+2 i k s^2\right)}{4 s^2}\right] \text{erfc}\left(\frac{1}{2} R \sqrt{\frac{1}{s^2}+\frac{2 i k}{R}}\right)\right\}$
Third and higher order terms are more complicated, but they can be computed suggesting that the original integral can be computed as well.


text:
Q: How to handle OnBackKeyPress correctly? To make it simple, I create a new app, which contains MainPage, and Page2.
MainPage has a button, which navigates to Page2. Also override MainPage.OnBackKeyPress:
    protected override void OnBackKeyPress(System.ComponentModel.CancelEventArgs e)
    {
        if (MessageBox.Show("Quit?", "Confirm", MessageBoxButton.OKCancel) == MessageBoxResult.Cancel)
            e.Cancel = true;
        else
            base.OnBackKeyPress(e);
    }

Page2 is empty, except override OnNavigateFrom, to simulate a long time operation when back from Page2 to MainPage:
    protected override void OnNavigatedFrom(NavigationEventArgs e)
    {
        System.Threading.Thread.Sleep(1000);
        base.OnNavigatedFrom(e);
    }

Everything is ok, but when I am at Page2, and press Back key 3-4 times very quickly, then I see the message box popup twice.
I expect the message box not shown, or at least show and hide. Is there anything wrong in my code? Thanks.

A: It depends on what you mean by very quickly...
The code looks OK (apart from the Thread.Sleep which is presumably to simulate a long operation on the UI thread).
I expect this is because while the UI thread is busy (or "sleeping") the back key presses are still registering and being sent to the app, and when the UI thread is available again it will process them one after the other.
This is a good example of why you should avoid blocking the UI thread.


text:
Q: Calculating cart total using jQuery I'm trying to do something I thought would be simple (!), but having trouble. Every time a user updates the form below, I want to update the cart total by multiplying the quantity (input values) by the data attribute unit-price.
I thought I would just need to loop through each input and grab the value and unit-price so I can multiply them together to create a total, but I'm the subtotal is returning '0'... any ideas of what I'm doing wrong?
JS FIDDLE
http://jsfiddle.net/wy5hy42x/
HTML
<form action="" id="form">

Product name

        Quantity:
        <input type="number" name="updates[]" value="2" min="0" data-unit-price="18.00" class="cart-variant--quantity_input">

        £18 each

Product name

        Quantity:
        <input type="number" name="updates[]" value="4" min="0" data-unit-price="31.00" class="cart-variant--quantity_input">

        £31 each

Product name

        Quantity:
        <input type="number" name="updates[]" value="4" min="0" data-unit-price="12.00" class="cart-variant--quantity_input">

        £12 each

    <input type="submit" value="submit" />
</form>

JQUERY
// Update final price on quantity change
$('.cart-variant--quantity_input').on("change", function() {
  var st            = 0;
  $('.cart-row').each(function() {
    var i           = $('.cart-variant--quantity_input');
    var up          = $(i).data('unit-price');
    var q           = $(i).val();
    var st          = st + (up * q);
  });
  // Subtotal price
  alert('Cart updated. Subtotal : ' + st + 'GBP');
});

A: You just need to remove var keyword from this line:
var st = st + (up * q);
// ^-- remove var in fron of st

otherwise you create a local variable inside a $.each callback and never update outer st value.
UPD. (credits to Dustin Hoffner for this catch) The second problem is that you need to find .cart-variant--quantity_input elements within current .cart-row container. For example, by providing a context for selector:
var i = $('.cart-variant--quantity_input', this);

All together it will become
$('.cart-variant--quantity_input').on("change", function () {
    var st = 0;
    $('.cart-row').each(function () {
        var i = $('.cart-variant--quantity_input', this);
        var up = $(i).data('unit-price');
        var q = $(i).val();
        st = st + (up * q);
    });
    // Subtotal price
    alert('Cart updated. Subtotal : ' + st + 'GBP');
});

Demo: http://jsfiddle.net/wy5hy42x/9/

A: First answer is not complete:
$('.cart-row').each(function(k) {
        var i           = $('.cart-variant--quantity_input')[k];
        var up          = parseFloat($(i).data('unit-price'));
        var q           = parseInt($(i).val());
        st          += (up * q);
      });

Edit: Changed parseInt to parseFloat (thanks to War10ck) (see his comment for the reason)
I removed the 'var' because you would overwrite in each loop.
Furthermore you will not calculate correctly:
var i           = $('.cart-variant--quantity_input');

This will always give you the first element. But you have more than one, so you need to get only the actual one from the returned array.
$('.cart-row').each(function(k) {
        var i           = $('.cart-variant--quantity_input')[k];

You can do this by taking the counter 'k' from your loop and get the right element with '[k]'.

A: In your each loop you need to take the current input, instead of the first one:
$('.cart-row').each(function(e) {
    var i           = $('.cart-variant--quantity_input').eq(e); // get item in the e position
    var up          = $(i).data('unit-price');
    var q           = $(i).val();
    st          = st + (up * q);
});

Also you need to remove the var keyword before st, as its creating a new st variable instead of updating the outer one.
See this fiddle


text:
Q: Add an unique class to every wp block on save How can I add a unique class name to every gutenberg block on save?
I tried doing this with php using a combination of wp_after_insert_post, parse_blocks, wp_update_post and something like (simplified):
$block['attrs']['className'] = $block['attrs']['className'] .' ' . substr(md5(uniqid(rand(1,6))), 0, 8);

But even though the classes are saved in the db, they don't show in neither the front end or the block editor.


text:
Q: Rails routing, matching short urls? I'm having an issue where I've created a route I'm using to match short token like urls, like this:
myapp.com/a2c3b

I'm doing that by using a route like this:
match '/:id' => 'items#show', :as => "show_item", :via => :get, :constraints => { :id => /[a-z0-9]{5}/ }

But the issue is that now my other routes like /admin don't work because that also has 5 characters, how can I work around this, and have both kinds of routes work?

A: Put all of your routes that would match before this route in the file... that is...
match '/admin'....
match '/login'....
match '/:id' => 'items#show', :as => "show_item", :via => :get, :constraints => { :id => /[a-z0-9]{5}/ }


text:
Q: Integrity constraint violation: 1452 Cannot add or update a child row: I am trying to insert values into my comments table and I am getting a error. Its saying that I can not add or update child row and I have no idea what that means.
my schema looks something like this
-- ----------------------------
-- Table structure for `comments`
-- ----------------------------
DROP TABLE IF EXISTS `comments`;
CREATE TABLE `comments` (
  `id` varchar(36) NOT NULL,
  `project_id` varchar(36) NOT NULL,
  `user_id` varchar(36) NOT NULL,
  `task_id` varchar(36) NOT NULL,
  `data_type_id` varchar(36) NOT NULL,
  `data_path` varchar(255) DEFAULT NULL,
  `message` longtext,
  `created` datetime DEFAULT NULL,
  `modified` datetime DEFAULT NULL,
  PRIMARY KEY (`id`),
  KEY `fk_comments_users` (`user_id`),
  KEY `fk_comments_projects1` (`project_id`),
  KEY `fk_comments_data_types1` (`data_type_id`),
  CONSTRAINT `fk_comments_data_types1` FOREIGN KEY (`data_type_id`) REFERENCES `data_types` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION,
  CONSTRAINT `fk_comments_projects1` FOREIGN KEY (`project_id`) REFERENCES `projects` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION,
  CONSTRAINT `fk_comments_users` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION
) ENGINE=InnoDB DEFAULT CHARSET=utf32;

-- ----------------------------
-- Records of comments
-- ----------------------------

-- ----------------------------
-- Table structure for `projects`
-- ----------------------------
DROP TABLE IF EXISTS `projects`;
CREATE TABLE `projects` (
  `id` varchar(36) NOT NULL,
  `user_id` varchar(36) NOT NULL,
  `title` varchar(45) DEFAULT NULL,
  `description` longtext,
  `created` datetime DEFAULT NULL,
  `modified` datetime DEFAULT NULL,
  PRIMARY KEY (`id`),
  KEY `fk_projects_users1` (`user_id`),
  CONSTRAINT `fk_projects_users1` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION
) ENGINE=InnoDB DEFAULT CHARSET=utf32;

-- ----------------------------
-- Records of projects
-- ----------------------------
INSERT INTO `projects` VALUES ('50dcbc72-3410-4596-8b71-0e80ae7aaee3', '50dcbc5c-d684-40bf-9715-0becae7aaee3', 'Brand New Project', 'This is a brand new project', '2012-12-27 15:24:02', '2012-12-27 15:24:02');

and the mysql statement I am trying to do looks something like this
INSERT INTO `anthonyl_fbpj`.`comments` (`project_id`, `user_id`, `task_id`, `data_type_id`, `message`, `modified`, `created`, `id`)
VALUES ('50dc845a-83e4-4db3-8705-5432ae7aaee3', '50dcbc5c-d684-40bf-9715-0becae7aaee3', '1', '50d32e5c-abdc-491a-a0ef-25d84e9f49a8', 'this is a test', '2012-12-27 19:20:46', '2012-12-27 19:20:46', '50dcf3ee-8bf4-4685-aa45-4eb4ae7aaee3')

the error I get looks like this

SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or
  update a child row: a foreign key constraint fails
  (anthonyl_fbpj.comments, CONSTRAINT fk_comments_projects1
  FOREIGN KEY (project_id) REFERENCES projects (id) ON DELETE NO
  ACTION ON UPDATE NO ACTION)

A: Make sure you have project_id in the fillable property of your Comment model.
I had the same issue, And this was the reason.

A: I hope my decision will help. I had a similar error in Laravel. I added a foreign key to the wrong table.
Wrong code:
Schema::create('comments', function (Blueprint $table) {
$table->unsignedBigInteger('post_id')->index()->nullable();
...
$table->foreign('post_id')->references('id')->on('comments')->onDelete('cascade');
    });

Schema::create('posts', function (Blueprint $table) {
    $table->bigIncrements('id');
    ...
    });

Please  note to the function on('comments') above. Correct code
 $table->foreign('post_id')->references('id')->on('posts')->onDelete('cascade');

A: that means that the value for column project_id on table comments you are inserting not only doesn't exist on table projects BUT  also  project_id probably doesn't have default value. E.g. in my case I set it as NULL.
As for  Laravel you can consider this expressions as a chunk of code of a  migration php file, for example:
class ForeinToPhotosFromUsers extends Migration

{ /** * Run the migrations. * * @return void */
public function up()
{
    Schema::table('users', function (Blueprint $table) {
    $table->unsignedBigInteger('photo_id')->nullable();// ! ! ! THIS STRING ! ! !
    $table->foreign('photo_id')->references('id')->on('photos');
});
}

}
Obviously you had to create the Model class(in my case it was Photo) next to all these.

A: First delete the constraint "fk_comments_projects1" and also its index. After that recreate it.

A: You also get this error if you do not create and populate your tables in the right order. For example, according to your schema, Comments table needs user_id, project_id, task_id and data_type_id. This means that Users table, Projects table, Task table and Data_Type table must already have exited and have values in them before you can reference their ids or any other column.
In Laravel this would mean calling your database seeders in the right order:
class DatabaseSeeder extends Seeder
{
    /**
     * Seed the application's database.
     *
     * @return void
     */
    public function run()
    {
        $this->call(UserSeeder::class);
        $this->call(ProjectSeeder::class);
        $this->call(TaskSeeder::class);
        $this->call(DataTypeSeeder::class);
        $this->call(CommentSeeder::class);
    }
}

This was how I solved a similar issue.

A: Maybe you have some rows in the table that you want to create de FK.
Run the migration with foreign_key_checks OFF
Insert only those records that have corresponding id field in contents table.

A: Issue could be because of no project record found in database with project_id you are trying to add...

A: If you are adding new foreign key to an existing table and the columns are not null and not assigned default value, you will get this error,
Either you need to make it nullable or assign default value, or delete all the existing records to solve it.

A: In case someone is using Laravel and is getting this problem. I was getting this as well and the issue was in the order in which I was inserting the ids (i.e., the foreign keys) in the pivot table.
To be concrete, find below an example for a many to many relationship:
wordtokens <-> wordtoken_wordchunk <-> wordchunks
// wordtoken_wordchunk table
Schema::create('wordtoken_wordchunk', function(Blueprint $table) {
        $table->integer('wordtoken_id')->unsigned();
        $table->integer('wordchunk_id')->unsigned();

        $table->foreign('wordtoken_id')->references('id')->on('word_tokens')->onDelete('cascade');
        $table->foreign('wordchunk_id')->references('id')->on('wordchunks')->onDelete('cascade');

        $table->primary(['wordtoken_id', 'wordchunk_id']);
    });

// wordchunks table
Schema::create('wordchunks', function (Blueprint $table) {
        $table->increments('id');
        $table->timestamps();
        $table->string('text');
    });

// wordtokens table
Schema::create('word_tokens', function (Blueprint $table) {
        $table->increments('id');
        $table->string('text');
});

Now my models look like follows:
class WordToken extends Model
{
   public function wordchunks() {
      return $this->belongsToMany('App\Wordchunk');
   }
}

class Wordchunk extends Model
{

    public function wordTokens() {
        return $this->belongsToMany('App\WordToken', 'wordtoken_wordchunk', 'wordchunk_id', 'wordtoken_id');
    }
}

I fixed the problem by exchanging the order of 'wordchunk_id' and 'wordtoken_id' in the Wordchunk model.
For code completion, this is how I persist the models:
private function persistChunks($chunks) {
    foreach ($chunks as $chunk) {
        $model = new Wordchunk();
        $model->text = implode(' ', array_map(function($token) {return $token->text;}, $chunk));
        $tokenIds = array_map(function($token) {return $token->id;}, $chunk);
        $model->save();
        $model->wordTokens()->attach($tokenIds);
    }
}

A: It just simply means that the value for column project_id on table comments you are inserting doesn't exist on table projects. Bear in mind that the values of column project_id on table comments is dependent on the values of ID on table Projects.
The value 50dc845a-83e4-4db3-8705-5432ae7aaee3 you are inserting for column project_id does not exist on table projects.

A: Also make sure that the foreign key you add is the same type of the original column, if the column you're reference is not the same type it will fail too.

A: I had this issue when I was accidentally using the WRONG "uuid" in my child record. When that happens the constraint looks from the child to the parent record to ensure that the link is correct. I was generating it manually, when I had already rigged my Model to do it automatically. So my fix was:
$parent = Parent:create($recData); // asssigning autogenerated uuid into $parent

Then when I called my child class to insert children, I passed this var value:
$parent->uuid

Hope that helps.

A: I had the same error, the problem was that I was trying to add role_id foreign to the users table, but role_id did not have a default value, so the DB did not allow me to insert the column because I already had some users and it didn't know how to add the column to them.
Since I was in development I just used migrate:fresh, but if I was on production, I would probably set a default value to the role_id and not make it not constrained until I had the corresponding role on the DB.

A: Could be you are inserting a foreign key value that does not match with that of the primary key.

A: In my case it didn't work because I was leaving a space in one of the names of in the model.

A: I had a table fulfilled with some entries that has dead foreigners keys.
once i cleaned the table, i was able to add a new constraint.
DELETE FROM `table_with_bad_entries` WHERE `expected_foreign_key` not in (select `id` from `the_referenced_table`);

A: I just exported the table deleted and then imported it again and it worked for me. This was because i deleted the parent table(users) and then recreated it and child table(likes) has the foreign key to parent table(users).


text:
Q: LeakCanary Dependency with Cordova - Could not find method debugCompile() I am not an Android developer and have a build in Cordova I'd like to check for memory leaks using LeakCanary... (I have no idea how the actual Android build environment works and have been picking through this).
For installation, LeakCanary states, "In your build.gradle":
 dependencies {
   debugCompile 'com.squareup.leakcanary:leakcanary-android:1.5'
   releaseCompile 'com.squareup.leakcanary:leakcanary-android-no-op:1.5'
   testCompile 'com.squareup.leakcanary:leakcanary-android-no-op:1.5'
 }

I am receiving the following error after copying and pasting the above into the build.gradle (Module: android):

4:41:15 PM Gradle sync failed: Could not find method debugCompile()
  for arguments [com.squareup.leakcanary:leakcanary-android:1.5] on
  object of type
  org.gradle.api.internal.artifacts.dsl.dependencies.DefaultDependencyHandler.
             Consult IDE log for more details (Help | Show Log)

and in the error Log

Error:(35, 0) Could not find method debugCompile() for arguments [com.squareup.leakcanary:leakcanary-android:1.5] on object of type org.gradle.api.internal.artifacts.dsl.dependencies.DefaultDependencyHandler.

Any ideas about how to fix this? I have been researching with limited success.
Thank!

A: With some fiddling around, I have LeakCanary working, although I can't speak to whether it's functioning in it's entirety (it runs, and provides some leakage data in my application).
I also don't understand why it wasn't working...

*

*Use File > Project Structure > Modules: CordovaLib (not "android") >
Dependencies tab

*Add the following:

Debug Compile: com.squareup.leakcanary:leakcanary-android:1.5
Release Compile: com.squareup.leakcanary:leakcanary-android-no-op:1.5
Test Compile: com.squareup.leakcanary:leakcanary-android-no-op:1.5

*

*build.gradle (Module: CordovaLib) should now have at the very bottom:
dependencies {
  debugCompile 'com.squareup.leakcanary:leakcanary-android:1.5'
  releaseCompile 'com.squareup.leakcanary:leakcanary-android-no-op:1.5'
  androidTestCompile 'com.squareup.leakcanary:leakcanary-android-no-op:1.5'
}

*In CordovaActivity.java:
public void onCreate(Bundle savedInstanceState) {
     super.onCreate(savedInstanceState);
     if (LeakCanary.isInAnalyzerProcess(this)) {
      // This process is dedicated to LeakCanary for heap analysis.
      // You should not init your app in this process.
       return;
}
LeakCanary.install(getApplication());
...
}

I believe it should now work.
Interesting note is that it did seem like Ionic/Cordova has very minimal leakage if I installed LeakCanary correctly (3.2 kb) with switching screens, rotating phone, backing in and out of app.


text:
Q: Show or hide div based on selected value I have a few blocks that I want to be visible based on selected option.

div {
  display: none;
}
select[value="test1"] ~ #targ1 {
  display: block;
}
select[value="test2"] ~ #targ2 {
  display: block;
}
select[value="test3"] ~ #targ3 {
  display: block;
}
Dropdown list:
<select>
  <option value="test1">Test a</option>
  <option value="test2">Test b</option>
  <option value="test3">Test c</option>
</select>

Test 1

Test 2

Test 3

I have also tried other selectors, such as select[selected] ~ div or
option:focus #targ1.
I even tried to add an ::after pseudo element on the select element, but
divs inside the option tag are ignored or act weird. It seems like select and option tags have kind of their own rules which I didn't find on w3schools.
How can I show and hide the div elements based on the currently selected option using only HTML and CSS?
Edit:
Simpliest way to solve this is inline-js, but I'm looking for a no js solution.

[data-value=test1] ~ #test1 {
    color: red;
}
[data-value=test2] ~ #test2 {
    color: green;
}
[data-value=test3] ~ #test3 {
    color: blue;
}
<select onchange="this.dataset.value = this.value" data-value="test1">
  <option value="test1" checked>Test a</option>
  <option value="test2">Test b</option>
  <option value="test3">Test c</option>
</select>

Target 1

Target 2

Target 3

A: The bad news
In order to detect which option is currently selected with CSS, you would need to apply the :checked pseudo-class to the option element, not to the select element. See the question "CSS :selected pseudo class similar to :checked, but for  elements" for more info.

option:checked {
  font-weight: bold;
}
<select>
  <option>Choice 1</option>
  <option>Choice 2</option>
</select>

Combining that with CSS combinators (the adjacent sibling selector +, the general sibling selector ~, the child selector >, and the descendent selector) is frustratingly ineffectual. The combinators can be combined to select any sibling or descendant, but can never select a parent or cousin... and since the HTML spec for the select element says that its allowed content is "zero or more option or optgroup elements", you simply can't affect a div using the value of a select element with CSS alone.
Using a drop-down with JavaScript
The example below monitors the select element for changes. When a change occurs, it grabs the newly-selected option element and reads the targets for that option from a data attribute (this is a nice convenience, because it allows you to specify the filter targets right in the HTML -- thereby keeping your model and control logic separate). Then it goes through all valid targets and either adds or removes the .hidden class based on whether that target is in the list provided by the data attribute.

var filter = document.getElementById('filter');

filter.addEventListener('change', function() {
  var option = this.options[this.selectedIndex];
  var targets = option.dataset.targets.split(/(\s+)/);
  for (var target of document.getElementsByClassName('target')) {
    if (targets.indexOf(target.id) >= 0)
      target.classList.remove('hidden');
    else
      target.classList.add('hidden');
  }
});
.target {
  display: block;
}

.target.hidden {
  display: none;
}
<select id="filter">
  <option data-targets="">Show no targets</option>
  <option data-targets="t1">Show target 1</option>
  <option data-targets="t2">Show target 2</option>
  <option data-targets="t1 t2">Show targets 1 and 2</option>
</select>

Thsi is the first target.

This is the second target.

Using radio buttons without JavaScript
Unlike drop-down elements, radio buttons don't need to be nested inside a wrapping element. Because of this, you can structure your HTML so that the div elements are general siblings of the radio buttons, and you can use the :checked class to affect their visibility.

.target {
  display: none;
}

#f1:checked ~ #t1 {
  display: block;
}

#f2:checked ~ #t2 {
  display: block;
}

#f3:checked ~ #t1,
#f3:checked ~ #t2 {
  display: block;
}
<input type="radio" name="filter" id="f0" checked>Show no targets

<input type="radio" name="filter" id="f1">Show target 1

<input type="radio" name="filter" id="f2">Show target 2

<input type="radio" name="filter" id="f3">Show targets 1 and 2

This is the first target.

This is the second target.

A: @Woodrow Barlow actually has a good answer,
but question is more related to JS free code
Therefore the following snippet is a good example,
I actually used technique into a few pages:

<!DOCTYPE html>

        <meta charset="UTF-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <title>Document</title>

        <input id="rad1" type="radio" name="targ" value="1" hidden checked />
        <input id="rad2" type="radio" name="targ" value="2" hidden />
        <input id="rad3" type="radio" name="targ" value="3" hidden />

Dropdown list:

Test 1

Test 2

Test 3

        Test 1
        Test 2
        Test 3

For a regular dropdown which has only 2 states, can be used input type="checkbox"

First answer summary using url hash:

<!DOCTYPE html>

            show item1
            show item2
            show item3

item1

item2

item3


text:
Q: Trouble parsing elif using PLY I'm continuing my journey into parsing using PLY. I've run into a problem when parsing IF and ELSE IF statements.
Here is my code, I've stripped out the irrelevant bits and just left it with the basics (this will run on Python 2.7).
from ply import lex, yacc

tokens = [
    'ELSE',
    'IF',
    'LPAREN',
    'RPAREN',
    'LCURLY',
    'RCURLY'
    ]

t_IF = r'IF'
t_ELSE = r'ELSE'
t_LPAREN = r'\('
t_RPAREN = r'\)'
t_LCURLY = r'\{'
t_RCURLY = r'\}'
t_ignore = '\r\t '

def t_error(t):
    print t

def t_newline(t):
    r'\n+'
    t.lexer.lineno += len(t.value)

def p_error(p):
    print ('error', p)

def p_empty(p):
    'empty :'
    p[0] = None

def p_if_statement(p):
    'if_statement : IF LPAREN RPAREN LCURLY RCURLY elif_statements_or_empty else_statement_or_empty'
    p[0] = ('if_statement', (p[6]))
    print p[0]

def p_else_statement(p):
    'else_statement : ELSE LCURLY RCURLY'
    p[0] = ('else_statement')

def p_else_statement_or_empty(p):
    '''else_statement_or_empty : else_statement
                               | empty'''
    p[0] = p[1]

def p_elif_statement(p):
    'elif_statement : ELSE IF LPAREN RPAREN LCURLY RCURLY'
    p[0] = ('elif_statement')

def p_elif_statements_1(p):
    'elif_statements : elif_statement'
    p[0] = [p[1]]

def p_elif_statements_2(p):
    'elif_statements : elif_statements elif_statement'
    p[0] = p[1] + [p[2]]

def p_elif_statements_or_empty(p):
    '''elif_statements_or_empty : elif_statements
                                | empty'''
    p[0] = p[1]

lexer = lex.lex()

s = 'IF(){}ELSE IF(){}ELSE{}'

parser = yacc.yacc(start='if_statement')
parser.parse(s)  # ('error', LexToken(LCURLY,'{',1,21))

Essentially, the problem is that I'm searching for an infinite amount of elif_statements. When it encounters an ELSE {, it thinks that there is a parsing error because it expected an IF after the ELSE.
Is this what's called a "shift/reduce error"? What are some ways that I can resolve this?
Any help is greatly appreciated!

A: Yes, that is the result of a shift/reduce conflict. PLY warns you that you have two of these, and they are both somewhat related to the else clauses.
However, the problem has nothing to do with the potentially infinite sequence of else if clauses. That is not a problem. The problem is more subtle and has to do with your use of empty productions.
The most important aspect of LR(1), from the point of view of figuring out issues, is that every non-terminal needs to be reduced (that is, created from its right-hand side) before the immediately following token is shifted. With that in mind, let's take a look at the grammar for if_statement:
if_statement : IF LPAREN RPAREN LCURLY RCURLY
               elif_statements_or_empty
               else_statement_or_empty

and let's suppose that we have seen IF(){}, so the next token is ELSE. At this point in the right-hand side (which is the only active item in the parse at this point) we know that the next token must be either ELSE or the end of the input. In the latter case, it's clear what must be done: an empty must be reduced and then an elif_statements_or_empty must reduced from that empty; next another empty must be reduced and an else_statement_or_empty must be reduced from that empty. That all works.
But suppose the next token is ELSE. Now what? Since we cannot see any further than the ELSE, we don't know whether it is followed by IF or (. But we have to decide between two options:

*

*Reduce an empty and then an elif_statements_or_empty. That will be correct if the ELSE is the beginning of else_statement_or_empty (which in this case cannot be empty).

*Shift the ELSE, which can then only be the start of elif_statements_or_empty, which cannot be empty and thus must be elif_statements. That will be correct if the ELSE is part of an ELSE IF clause.
So that's one shift/reduce conflict. Bison always chooses the shift in a shift/reduce conflict, so it will assume that the first ELSE following the IF is the start of an ELSE IF clause. Let's continue with that assumption (which happens to be correct in the case of the provided input), and continue until we reach the following ELSE. We've now seen IF(){}ELSE IF(){} and we're again staring at an ELSE.
At this point, it is absolutely clear that ELSE IF(){} must be reduced to else_if_statement and it is also clear that else_if_statement must be reduced to else_if_statements. So far, so good. But now comes the problem. If there will be another ELSE IF, that's enough reducing and we should shift the ELSE to be part of the following else_if_statement. But if the ELSE is the start of the final else_statement, then we need to reduce the else_if_statements we just created into an else_if_statements_or_empty, since that reduction will be needed before we can shift the ELSE which starts else_statement_or_empty.
Again, bison always goes for the shift. But that means that it cannot ever decide to start an else_statement_or_empty.

So, what to do?
The first thing to note is that the elif_statements_or_empty production really is not adding any value at all. (Indeed, neither is the empty production, which I was going to just eliminate silently, but I'll leave this parenthetic obituary.) If we just put elif_statements in the if_statement, then we would not need to decide between elif_statements and elif_statements_or_empty. Of course, we would need elif_statements to match an empty string, but that's trivial: we just provide an empty right-hand side for the recursive base case. That is, instead of
elif_statements: elif_statement | elif_statements elif_statement

we will use
elif_statements: | elif_statements elif_statement

Instead of matching any number but at least one elif_statement, we will now match any number including zero elif_statements. Which is exactly what we want.
Now that the elif_statements base case is empty, we no longer need to decide after the IF(){} whether or not we will have an empty set of elif_statements. We can just reduce an empty elif_statements and then see whether what comes next is an elif_statement or an else_statement. So with that simplification, we have actually eliminated both shift-reduce conflicts.
In summary, the new PLY file: (parser rules only, nothing else has changed):
def p_error(p):
    print ('error', p)

# Fixed to return both elif and else statements
def p_if_statement(p):
    'if_statement : IF LPAREN RPAREN LCURLY RCURLY elif_statements else_statement'
    p[0] = ('if_statement', (p[6] + p[7]))
    print p[0]

# This needs to return a list because it could be empty
def p_else_statement(p):
    'else_statement : ELSE LCURLY RCURLY'
    p[0] = ['else_statement']

def p_elif_statement(p):
    'elif_statement : ELSE IF LPAREN RPAREN LCURLY RCURLY'
    p[0] = 'elif_statement'

def p_elif_statements(p):
    'elif_statements : elif_statements elif_statement'
    p[0] = p[1] + [p[2]]

# This handles both empty elif_statements and an empty else
# by reducing to an empty list
def p_empty(p):
    '''elif_statements :
       else_statement  :'''
    p[0] = []


text:
Q: JQuery submit() function not submitting HTML form from button triggered in Twiiter-Bootstrap 3 Modal I am creating an unsubscribe page that contains a form element followed by a twitter-bootstrap 3 modal, currently it is just HTML/JQuery. The modal is triggered when clicking on a button element within the bottom of the form (type button).
Within the modal is a confirmation button (also type button) which has a handler attached to submit the form. The handler is being triggered when clicking the button, but the submit function does not appear to be firing. If I change the handler to trigger on the form button, then submit works. It appears to be just because the confirmation button is within the modal. I would greatly appreciate any help getting submit() to trigger on the modal button, thanks!
JQuery Script:

Twitter-Bootstrap 3 Modal:

                <button type="button" class="close" data-dismiss="modal"></button>

Please feel free to contact us at:   mail@email.com.au
or give us a call at:   555 555 555
 during office hours if you wish to re-subscribe to our emails or just have a chat...

have an Amazing day!

                <button id="unsub" type="button" onclick="form_submit()" class="btn btn-danger" data-dismiss="modal">Unsubscribe</button>

HTML Form:
<form id="unsub_form" name="unsub_form" action="success.html" method="GET" enctype="multipart/form-data" >

        *Please unsubscribe the below address from email notifications
        <input id="email" name="email" type="email" class="form-control input-sm" required/>

        Reason for unsubscribing
        <select id="reason" name="reason" class="form-control input-sm">
            <option value="0" selected>- Please select an option</option>
            <option value="to many">I recieve to many emails</option>
            <option value="not relevant">The information is not relevant to me</option>
            <option value="badly coded">They don't display or open correctly</option>
            <option value="other">Other (please explain below)</option>
        </select>

        Feedback

        <textarea maxlength="300" id="feedback" name="feedback" class="form-control" rows="5"></textarea>

    <button id="submit" type="button" class="btn btn-warning pull-right">Unsubscribe</button>
    <button id="cancel" type="button" class="btn btn-success pull-right" onclick="window.location.href='cancel.html'">Cancel</button>

</form>

A: I'm not sure why, but the unsubscribe button with id 'submit' is messing up the form submit. If you change that button to an id of 'sub', the code will work.
I have created a jsfiddle -
https://jsfiddle.net/bbs5tffz/
$("#sub").click(function(e){
    //isValid = validateForm();
    if(true)
    {
        $('#unsubModal').modal('show');
    }
});

I had to remove the isValid() reference.

A: From Mozilla MDN:

If a form control (such as a submit button) has a name or id of submit it will mask the form's submit method.

https://developer.mozilla.org/en-US/docs/Web/API/HTMLFormElement/submit
Basically you are overriding submit property in the Form Object.
To avoid this I would name the submit button like 'unsub_form_submit' or something coherent


text:
Q: C# / JSON.NET Deserialize Timezone issue I have a web app and I am using a custom ValueProviderFactory that deserializes all the values for me using JSON.NET, described here: https://json.codeplex.com/discussions/347099, hoping to utilize DateTimeZoneHandling of the JSON.NET library.
The problem is, I have a user on the east coast, but the server is on the west coast.  So for example, when an east coast user selects a time on the website, let's say 09/02/2016 6:00:00-0400 (10AM UTC time).  It comes into the value provider factory as "09/02/2016 10:00:00Z", however, all the different options of the DateTimeZoneHandling (Local, Unspecified, UTC, RoundtripKind), don't work because I get these results:

*

*Local converts it to west coast time because that's where the server is (3AM)

*Unspecified keeps it at 10AM

*UTC keeps it at 10AM

*RoundtripKind is also 10AM

Does anyone know how I can keep it at 6AM because that is what the user selected?  Using the default MVC ValueProviderFactory basically gives me the same results, it's either saved as UTC or 3 hours too early.
I'm trying to avoid using DateTimeOffset because all my date fields are of type DateTime.
Any help would be greatly appreciated!!


text:
Q: matplotlib: custom month names (for translation when locale doesn't work) I'm looking for a way to rename the months printed in the plot, that is, map each month to a custom label. I need my plots to be in a language that is not installed in my system, so I want to manually set the names.
If I try
locale.setlocale(locale.LC_TIME, 'pt_BR.UTF-8'), I get Error: unsupported locale setting.

A: Ingredients:

*

*FuncFormatter

*num2date
Method:
from datetime import datetime, timedelta
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
from matplotlib.dates import num2date
from matplotlib.ticker import FuncFormatter

months_names = [None, 'Jan', 'Fev', 'Mar','Abr', 'Mai', 'Jun', 'Jul', 'Ago', 'Set', 'Out', 'Nov', 'Dez']

# Generate some random date-time data
numdays = 500
base = datetime.today()
date_list = [base - timedelta(days=x) for x in range(0, numdays)]
y = np.random.rand(numdays)

# Set the locator
locator = mdates.MonthLocator(bymonth=(1, 4))  # every January and April

plt.scatter(date_list,y)
X = plt.gca().xaxis
X.set_major_locator(locator)
X.set_major_formatter(FuncFormatter(lambda x, i: months_names[num2date(x).month]))
plt.show()

Output:


text:
Q: Invalid Cast Exception, Stored Procedure, LINQ TO SQL 9 months later, the same problem shows up again. I've tried everything I can think of:

*

*I cast as varchar(max) on the stored procedure;

*I changed the mapping;

*tried to find the collection linq works with, but couldn't find anywhere;

I have been running this stored procedure for some time Mapping it to my objects using LINQ to SQL, and now, all of the sudden, LINQ is trying to cast the field 'value' as double.

the error:
specified cast is not valid
   System.Data.SqlClient.SqlBuffer.get_Double()
   System.Data.SqlClient.SqlDataReader.GetDouble(Int32 i)
   Read_Field(ObjectMaterializer`1 )
   System.Data.Linq.SqlClient.ObjectReaderCompiler.ObjectReader`2.MoveNext()
   System.Linq.Enumerable.Single[TSource](IEnumerable`1 source)
   CmsCsharp.BL.FieldManager.FindContentField(Int32 id_content, Int32 id_fieldType, String fieldName)

the methods
public static Field FindContentField(int id_content, int id_fieldType, string fieldName)
            {
                using (DbBase conn = new DbBase())
                {
                    try
                    {
                        return conn.ClientDB.sprocFindContentField(id_content, id_fieldType, fieldName).Single();
                    }
                    catch (Exception e)
                    {
                        return null;
                    }
                }
            }

[Function(Name = "dbo.sprocFindContentField")]
        public ISingleResult<Field> sprocFindContentField([Parameter(DbType="Int")] System.Nullable<int> id_content, [Parameter(DbType="Int")]System.Nullable<int> id_fieldType, [Parameter(DbType="Varchar(255)")]string fieldName)
        {
            IExecuteResult result = this.ExecuteMethodCall(this, ((MethodInfo)(MethodInfo.GetCurrentMethod())), id_content, id_fieldType, fieldName);
            return ((ISingleResult<Field>)(result.ReturnValue));
        }

the field:
public class TextField : Field
{
   private string _Value;

    [Column(Storage="_Value", DbType="VarChar(MAX) NOT NULL", Name="value", CanBeNull=true)]
    public string Value
    { //get and set }
}

the procedure:
  SELECT
         type = 'textField',
         fieldLabel.id_fieldEditor,
         fieldLabel.id_fieldType ,
         fieldLabel.description,
         fieldLabel.id ,
         sessionField.id  AS relationId,
         fieldLabel.name ,
         fieldText.content AS value,
         fieldText.id  AS valueId,
         cf.id as contentRelationId
  FROM
         fieldLabel
  INNER JOIN
         sessionField
  ON
         sessionField.id_fieldLabel = fieldLabel.id
  INNER JOIN
        cms_contentField AS cf
  ON
        cf.id_sessionField = sessionField.id
  INNER JOIN
         fieldText
  ON
         fieldText.id = cf.id_fieldValue
  INNER JOIN
        fieldType
  ON
        fieldLabel.id_fieldType = fieldType.id
  INNER JOIN
        fieldTable
  ON
        fieldTable.id = fieldType.id_fieldTable
  WHERE
         cf.id_content = @id_content
  AND
        fieldTable.id = 1

A: My guess is that you have a value in your table that is triggering SQL Server's conversion through the "numeric" data type. i.e. your value is being converted into an imprecise data type (float or real) and causing LINQ to SQL to attempt a double. See the caution in SQL Server's help file for int

A: I've changed the 9th line in the stored procedure to fieldText.content,
SELECT
     type = 'textField',
     fieldLabel.id_fieldEditor,
     fieldLabel.id_fieldType ,
     fieldLabel.description,
     fieldLabel.id ,
     sessionField.id  AS relationId,
     fieldLabel.name ,
     fieldText.content AS value, //this line
     fieldText.id  AS valueId,
     cf.id as contentRelationId

then I changed the mapping accordingly:
[Column(Storage="_Value", DbType="VarChar(MAX) NOT NULL", Name="content", CanBeNull=true)]
public string Value
{ //get and set }

and it worked!
Have no idea why it worked. Does the labeling (as value) could be the cause?
Thank you

A: I'm arriving late with the same error message in the same context.
The problem was an unamed column in my Proc Stock result. No problem to excute it in management studio. No problem to register it in my dbml, but invalid cast at runtime.
Hope that helps


text:
Q: How many adjunctions are there between (infinite) categories? The title is a little bit imprecise. Consider "typical" categories $\mathcal{A},\mathcal{B}$, let's say infinite and locally small. A pair of adjointable functors $(F,G$) is a pair of functors $(F : \mathcal{A} \to \mathcal{B}, G : \mathcal{B} \to \mathcal{A})$, such that $F$ is left-adjoint to $G$. We consider $(F,G)$ and $(F',G'$) the same, if $F\cong F'$ or $G\cong G'$.

How many pairs of adjointable functors are there between $\mathcal{A}$
  and $\mathcal{B}$?

I mean this very broadly: finitely many, infinitely many, possibly a proper class? If one cannot say anything generally, then what about important examples like $\mathcal{A},\mathcal{B}$ being categories of universal algebras or one being the category of small categories?

A: Let $A, B$ both be $\text{Set}$. For any set $X$ there is an adjunction between the functors $(-) \times X$ and $[X, -]$ (here I mean the set of functions from $X$ into some other set). So in this case there is a proper class of adjunctions, even up to isomorphism. I expect that this is typical. (Note that $F \cong F'$ is equivalent to $G \cong G'$.)
More generally in this argument we can replace $A, B$ with a closed monoidal category which is not essentially small. There are many examples, such as $(\text{Ab}, \otimes)$ or, for that matter, $(\text{Cat}, \times)$.
Edit: It's sometimes possible to classify all left adjoints $F : A \to B$. For example, if $A$ is the category $[C^{op}, \text{Set}]$ of presheaves on an essentially small category $C$, then the category of left adjoints $A \to B$ is equivalent to the category of functors $C \to B$. If $B$ itself is the category $[D^{op}, \text{Set}]$ of presheaves on another essentially small category $D$, then this is in turn the category $[C \times D^{op}, \text{Set}]$ of bimodules over $C$ and $D$.


text:
Q: Given an urn of $k$ distinct balls. Do $n$ drawings with replacement. What is the probability that every ball is drawn at least once? The space of outcomes is $k^n$ since for each of the drawings, there are $k$ outcomes. Deciding the numerator seems harder. Originally the problem was "What is the probability that every ball is not drawn at least once?", but it seems easier to think of the complement, all different balls drawn at least once. I am thinking of employing the stars and bars method, which gives that there are $\frac{(n-1)!}{(k-1)!(n-k)!}$ different ways for each ball to come out at least once.
This gives the answer to my original question as $1- \dfrac{\dfrac{(n-1)!}{(k-1)!(n-k)!}}{k^n}$. I think this is the exact answer, but I'm not sure. In my notes, my teacher just did something fancy and said we just need it to be $\leq \frac{k (k-1)^n}{k^n}$. Can someone help explain what approximation my teacher made?

A: if you write down the inclusion-exclusion principle then the number of ways in which a given ball is not drawn is $ {(k-1)^n}$. you have $k$ balls from which you can pick the one that's not drawn which gives you $ k(k-1)^n$ so you're done. the probability that some ball is not drawn is less than the sum of probabilities that the $i$-th ball is not drawn which according to our calculations is $$ \frac{k(k-1)^n}{k^n}$$ cause we divided over the total number of possibilities $k^n$
in fact it's not so much an inclusion-exclusion kind of argument the way it's written now. I was first thinking about computing the probability of the event {all balls are drawn}. Here it's just something like that: let $A_i$ denote the event [$i$-th ball was not drawn] and let $A$ denote the event [some ball was not drawn]. then $$A \subset \bigcup_{i=1}^k A_i$$
so
$$ P(A) \leq \sum_{1}^k P(A_i)$$
and
$$ P(A_i) = \frac{(k-1)^n}{k^n} $$ which ends the argument

A: Let our $k$-element set be $K=\{1,2,3,\dots,k\}$. Let $N=\{1,2,3,\dots,n\}$.
Imagine that we have done $n$ draws. Let $f(i)$ be the ball drawn on the $i$-th trial. Then $f$ is a function from $N$ to $K$. We want the probability that the function $f$ is onto.
There are $k^n$ equally likely functions. The number of onto functions is $k!S(n,k)$, where $S(n,k)$ is the Stirling Number of the Second Kind. There is a wide variety of recurrences for $S(n,k)$, but no simple closed form.
The required probability is therefore $\dfrac{k!S(n,k)}{k^n}$.


text:
Q: How to Create a Virtual Network Adapter in .NET? I would like to create/add a virtual network adapter to a client operating system at runtime (via code), preferably in C#. Something similar to that of what VirtualBox/VMware/Himachi creates when you install their software. I am guessing this will require some C/C++ shenanigans for the driver integration, but if it is doable with only C#, all the better.
I am aware of OpenVPN, their stuff is primarily in C, and I am also aware of the TUN/TAP drivers floating around, I just didn't know if these were the only solutions not requiring me creating a fully loaded network driver for Windows.

A: If you need simple funcionality then you can use Microsoft Loopback Adapter. To install it use devcon tool. Here is some info about it http://support.microsoft.com/kb/311272.
devcon -r install %WINDIR%\Inf\Netloop.inf *MSLOOP After that you can use WMI query with C# to obtain new connection name and then netsh to configure it (ie. netsh int ip set address name="Local Area Connection 2" static 192.168.0.3 255.0.0.0)


text:
Q: Change the background color of my theme widgets On the Widget screen I would like widgets that I have created specifically for my theme to have a different background color, how can the be achieved.

A: Your widgets will get an ID based on the class name you specify.
You can then write a CSS selector based on those values. Say that you prefix your widget classes with 'foo_', then you can select them with:
div[id*="foo_"] {
    background-color: red;
}

To add that to the admin pages add something like this to your functions.php:
add_action('admin_head', 'custom_widget_css');

function custom_widget_css() {
    echo '<style>
        div[id*="foo_"] {
             background-color: red;
        }
  </style>';
}


text:
Q: How to Pass EventData to Durable Functions? I want to run durable function from EventHubTrigger azure function.
        public async Task<bool> Activities(
            [EventHubTrigger(EventHubName, Connection = EventHubConnStrName)] EventData[] events,
            [DurableClient] IDurableOrchestrationClient durableClient,
            ILogger logger)
        {
                // chaining pattern durable function
                 await durableClient.StartNewAsync<string>(
                       FunctionNames.BatchEvents,
                       JsonConvertUtil.SerializeObject(events));

        }

        [FunctionName(FunctionNames.BatchEvents)]
        public static async Task<bool> Run(
           [OrchestrationTrigger] IDurableOrchestrationContext context,
            ILogger logger)
        {
            try
            {
                var events =
                    JsonConvertUtil.DeserializeObject<EventData[]>(context.GetInput<string>()));

                ....
            }
            catch (Exception ex)
            {
                logger.LogError(ex.Message);
                throw;
            }
        }

Let me know how can i pass events to durable function or i can design it better way ?

A: I believe the way you written the workflow to pass Event data in Azure Durable Functions makes sense after reading this event-based-workflows-with-durable-function.
 var events =
             JsonConvertUtil.DeserializeObject<EventData[]>(context.GetInput<string>()));

In your code, as you have used context.GetInput<string> Method unpacks the event data you passed and also with deserialization to JSON.
In the above article, there is some information regarding the workflows usage of Event based Triggered Data using in Azure Durable Functions which might help you.


text:
Q: Example of a function in $L^1[0,1]$ I am trying to find an example of a sequence $f_n$ in $L^1[0,1]$ (Lebesgue integrable functions) such that

*

*$ f_n \rightarrow 0 \forall x \in [0,1]$,

*$\int_0^1 |f_n(x)| dx=1 \forall n \in \mathbb{N}$

*the sequence $\{ f_n \}$ does not have  a limit in $L^1[0,1]$
I have thought of the following example:
$f_n(x)= n$ if  $0\leq x<1/n$ and $f_n(x)= 0$ otherwise.
steps 1 and 2 are easy to prove, but I m struggling with step number 3. Can anyone help?
Thanks!

A: The most direct way to prove that this sequence does not converge is to prove that it is not Cauchy. By a direct computation, you can calculate that, when $n > m$, $\|f_n - f_m\|_{L^1} = 2 - \frac{2m}{n}$. Let $N$ be arbitrary. By setting $m = N$ and $n \gg m$, $\|f_n - f_m\|_{L^1} \approx 2$, so the sequence is not Cauchy.


text:
Q: Javascript: How to retrieve a value from a popup after a click event is fired I have a page where clicking on a link will open a popup window. The popup window will contain some value. Now when user clicks on a div tag, I want to copy the text of that div into a text box of the main window.
I have used following code to open a popup -
popup = window.open(location, "popup","menubar=1,resizable=1,scrollbars=1,width=650,height=450");

How can I do that?

A: You can use opener to reference the parent window from your child window.  Here's an example from W3 Schools...
... and here's a working example from me:
Parent Window
Script

HTML
Open Window

Child Window
Script

HTML

Clickable Div

A: You tagged your question as jquery. There is one thing to look out for, if you want to use jquery inside the pop-up from the main window. It works something like this:
window.opener.$(selector, window.opener)

So, you are using the jquery of the pop-up and specify a context as well (2nd parameter). I am not completely sure, that 2nd step is necessary as well.


text:
Q: Why my PWA doesn't work on Safari and opera? It shows "can't establish a secure connection to the server" I'm making a PWA and is hosted on Firebase. I can see my page in Chrome, IE and other browsers. But I have problems with Safari and Opera.  I have SLL certificade and TLS 1.2 (both from firebase) with nginx as server.
I tested my page on browsers and  I  get errors like:
"Safari can't open the page -url- besause safari can't establish a
   secure connection to the server -url-"
"Can't establish
   communication    with protocol SSL/ TLS"
"Fatal Error (70) from
   server "    (Opera/Debian)
And in htbridge I got:

*

**HTTPS protocol, failed CSP status
*Many "The header was not sent by the server."
*I don't have have a Certification Authority Authorization (CAA) record.
*No support of TLSv1.3
*Server doesn't provide HPKP

So, I guess is something about security. But I don't know why it can be the main problem.
I tried to correct some stuff  some commands on the server (nginx) but I don't know where is that or what I need to do. I am new to these things and I need someone to guide me a little at this point.
What should I do or is something I don't know?

A: Opera is exactly following the footsteps of Chrome, so if it works on Chrome shouldn't be problem on Opera, i would say just uninstall the Opera and re-install it. Also, check what versions you have got? to get he maximum of both browsers you need latest versions. Also, there are certain restrictions on Safari regarding PWA and service worker. Although, both Safari and MS Edge working on it and all the main browsers are getting into the same page on the issue of PWA (i.e. Service worker, Cache Api and IndexedDB).

A: It turns out that I was testing on obsolete versions of Safari and Opera for Windows. For some reason it did'nt work on a specific iphone and hence my confusion. Thank you for your help!


text:
Q: uuidjs creating repeated ids I have a function that will get two unique tasks from a static array of ten items (it won't change). The action is triggered manually by the user from a React component.
The id assigned is repeated if the same task is selected on different user actions. I need the ids to be always different.
I have tried with uuidjs and with uuid-random libraries, and the behaviour is similar.
The function randomly selects two tasks:
import uuid from'uuid-random';
import ITask, { TaskStatus } from "../../models/ITask";
import tasks from "../../statics/tasks";

export const getTasks = (): ITask[] => {
    const selectedTasks = [];
    const tasksCopy: ITask[] = [...tasks];

    for (let i = 0; i < 2; i++) {
        const index = randomIndex(tasksCopy.length);
        const task = tasksCopy.splice(index, 1);
        task[0].id = uuid();
        task[0].status = TaskStatus.processing;
        selectedTasks.push(task[0]);
    }

    return selectedTasks;
}

The component from where the user perform the action:
import { useState, FC } from 'react'
import { Button, Stack, ThemeProvider } from "@mui/material";
import { v4 as uuidv4 } from 'uuid';

import theme from "../../theme/PaletteModule";
import Modal from '../Modal/Modal';
import { getTasks } from '../utils/utils';
import ITask from '../../models/ITask';
import IBot from '../../models/IBot';

const Controls: FC<{ handleAddNewBot: any, socket: any }> = ({ handleAddNewBot, socket }) => {
    const [open, setOpen] = useState(false);

    const handleModalOpenClose = (status: boolean) => {
        setOpen(status);
    };

    const createBot = (name: string) => {
        const tasks: ITask[] = getTasks();
        const newBot: IBot = {
            id: uuidv4(),
            name,
            tasks,
        }
        handleAddNewBot(newBot);
        handleModalOpenClose(true);

        socket.emit(newBot);
    }

    return (
        <div>
            <Stack
                spacing={2}
                direction="row"
                className="bot_actions"
                sx={{ padding: 3, borderBottom: "2px solid #2C2F37" }}
            >
                <ThemeProvider theme={theme}>
                    <Button
                        variant="contained"
                        onClick={() => handleModalOpenClose(true)}
                        color="primary">New Bot</Button>
                    <Button variant="outlined" color="secondary">List of Actions</Button>
                </ThemeProvider>
            </Stack>
            <Modal open={open} handleClose={handleModalOpenClose} handleCreateBot={createBot}/>
        </div>
    );
}

export default Controls;


text:
Q: Labeling two different parts of one equation with two arrows with different start and end points I want to write a formula, like the attachment picture, with two different arrows for two parts of the formula. I could write the below code by \xymatrix finally. But the starting point of the second arrow is not correct.
%
%%-------------------------------------------------------------
%% Modern Particle Physics, Mark Thomson, Cambridge University, 2013
%%-------------------------------------------------------------
%
\documentclass[openany,11pt]{book}

\usepackage{amsthm,amsmath,amssymb,mathrsfs,amsfonts}
%\usepackage[cmex10]{amsmath}
\usepackage[all]{xy}
\usepackage{setspace}
\usepackage{makeidx}
\usepackage{colortbl}
\usepackage{tikz}
\usepackage{graphicx}
\usepackage{graphics}

\begin{document}

%-----------------
\begin{eqnarray}
\xymatrix{
    |K_L\rangle=\frac{1}{\sqrt{2(1+|\epsilon^2|)}}[(1+\varepsilon)\mkern-25mu&\mkern-25mu|K^0\rangle \ar[rd]%
    +/d:(1,1) 5pt/\mkern-25mu&\mkern-25mu - (1 - \varepsilon)\mkern-25mu&\mkern-25mu|\bar{K^0}\ar[rd]%
    +/d:(1,1) 5pt/\rangle]. \\\nonumber
    \mkern-25mu&\mkern-25mu&\mkern-25mu\pi^-e^+\nu_e \mkern-25mu&\mkern-25mu \mkern-25mu&\mkern-25mu \pi^+e^-\bar{\nu}_e}\mkern-25mu \nonumber
\end{eqnarray}
%-----------------

\end{document}

A: \documentclass{article}
\usepackage{tikz}
\usetikzlibrary{tikzmark}

\begin{document}

    \[
    |K_L\rangle=\frac{1}{\sqrt{2(1+|\varepsilon^2|)}}\left[(1+\varepsilon)|
    \tikzmarknode{K1}{K^0}\rangle- (1 - \varepsilon)|
    \tikzmarknode{K2}{\overline{K}^0}\rangle\right]
    \]

    \begin{tikzpicture}[
        overlay,remember picture,
        arr/.style={-stealth,shorten <=5pt}]

        \draw[arr] (K1.south) |-++ (.5,-1) node[at end,right] {$\pi^-e^+\nu_e$};
        \draw[arr] (K2.south) |-++ (.5,-.5) node[at end,right] {$\pi^+e^-\overline{\nu}_e$};

    \end{tikzpicture}

\end{document}

A: Final complete code with your help:
\documentclass{article}
\usepackage{amsmath}
\usepackage{tikz}
\usetikzlibrary{tikzmark}

\newcommand{\tikzmarknode}[1]{\tikz[baseline,remember picture] \coordinate (#1) {};}

\begin{document}

    \begin{align*}
    |K_L\rangle =\frac1{\sqrt{2(1 + \lvert\varepsilon^2\rvert)}}
    \Bigl[(1 + \varepsilon)
    {|K\tikzmarknode{K1}^0\rangle} - (1 - \varepsilon)
    {|\bar K\tikzmarknode{K2}^0\rangle} \Bigr].
    \end{align*}

    \begin{tikzpicture}[overlay,remember picture,
    arr/.style={-stealth,shorten <=5pt}]

    \draw[arr] (K1.south) |-++ (.5,-1) node[at end,right] {$\pi^-e^+\nu_e$};
    \draw[arr] (K2.south) |-++ (.5,-.5) node[at end,right] {$\pi^+e^-\overline{\nu}_e$};

    \end{tikzpicture}

\end{document}

enter code here


text:
Q: How to change "base" HEAD tag, from php? From php, I make a POST request which returns in HTML code:
<html>
<head>
<link rel="stylesheet" href="/css/footer.css">
</head>
<body>
</body>
</html>

the problem is, the result looks like it has no CSS, because it tries to load from www.mysite.com/css/footer.css. But I did to "externalsite.com", and if that HTML is loaded on the other site, it looks fine. If I edit the result HTML and add "base" meta, it works, but I dont think editing-and-replacing-HTML-code direct way is ok.

A: I think, most likely, you have access to resources on one page with both relative paths (/css/footer.css) and with the full domain name (www.mysite.com/css/footer.css) of the site, and in this case XSS protection is triggered in the browser. When you specify the base tag, the browser considers that all loaded resources with relative paths should be downloaded only from the site specified in this tag, and ignored with the full domain name, this is considered safe and the protection does not work.


text:
Q: Emacs24 not rendering fonts properly I would like to know how to get similar font rendering in GNU Emacs as in GVim as shown in the screenshot below. It seems Emacs has an inferior way of rendering fonts by default. I've tried installing the Infinality font patches but I got the same results. I am running GNU Emacs 24.3 on my Arch Linux virtual machine. I have no Desktop Environment and am using OpenBox as my window manager.
A lot of forum posts I dug up seemed to hint at the libxft library that Emacs uses needing patching in the past, but not anymore. According to Emacs it has been compiled --with-xft so that shouldn't be an issue. Below is a screenshot from both applications and a zoomed in view to highlight the difference in rendering.

A: In my experience, Emacs does not reliably read font settings from font config or from Gnome, so you may need to change Emacs' font rendering settings.
Notably, the colored pixels around the font in GVim indicate that GVim uses subpixel rendering, whereas the absence of these pixels in Emacs shows that it only uses hinting.  The absence of subpixel rendering often makes fonts look blurry.
Find out GVims preferences
Find out what font rendering settings GVim uses.  I presume it takes the standard ones from Gnome, so install Gnome Tweaktool to inspect the font settings from Gnome.
Tell Emacs about your font preferences
Now create an .Xresources file that tells Emacs about these settings.  The following is represents my font settings, adapt it according to what you have found out in Gnome Tweaktool:
Xft.antialias:  1
Xft.hinting:    1
Xft.hintstyle:  hintfull
Xft.lcdfilter:  lcddefault
Xft.rgba:       rgb

As far as I know, the lcdfilter setting isn't available in Gnome Tweaktool, so just leave it on lcddefault.  After creating the file

*

*Exit Emacs with C-x C-c

*Load these settings with:
$ xrdb -merge ~/.Xresources

*Verify that the settings were loaded:
$ xrdb -query | grep Xft
Xft.antialias:  1
Xft.hinting:    1
Xft.hintstyle:  hintfull
Xft.lcdfilter:  lcddefault
Xft.rgba:       rgb

*Restart Emacs
Now check whether the fonts look the same now.  Note that GVim may use a different font renderer (e.g. Cairo, Harfbuzz or whatever), so expect some slight differences anyway.
Check that the settings are permanent

*

*Log out of your desktop

*Log in again

*Use above xrdb -query command to verify the presence of your font settings


text:
Q: beginner iOS core data - model is nil Using Xcode 4.2, I created a new app using the tab bar template. For some reason this template does not give you the option to include Core Data, so I had to add it manually, which I did by following this tutorial:
http://www.theappcodeblog.com/2011/06/30/iphone-development-tutorial-add-core-data-to-a-tab-bar-application-and-save-user-data/
When I run the app however, I get this error:
Cannot create an NSPersistentStoreCoordinator with a nil model

How do I make the model not nil? I have created Model.xcdatamodeld and added an entity (Cat) with attributes.
Also, I want to have the app begin with 5 cats for example, but the user will be able to create more cats. Where/How do I create the original 5 cats? It doesn't seem logical to create them every time the app starts, but how can you create them in the first place?

A: *

*You'll need to instantiate a model before you try to create a persistent store coordinator. You can do that with one of the methods of NSManagedObjectModel, such as + mergedModelFromBundles:. Note that if you pass nil to that method, it'll search the main bundle for models, which is probably what you want.

*To populate the store with some initial data, you have a few options. When your app starts up and you're setting up your Core Data stack, you'll probably look for an existing persistent store file. If you find it, you can just create the persistent store, add it to the coordinator, and proceed. If you don't find it, one option is to create a new store and add some objects programmatically. Another options is to keep a pre-populated persistent store file in your bundle which you can copy to the app's documents folder and then open. A third might be to read the default data from a server on the network and use that to populate a new store.

A: Fixed with this line:
NSURL *modelURL = [[NSBundle mainBundle] URLForResource:@"Model" withExtension:@"momd"];

"Model" was "TEMP".
I still don't know how to create the 5 objects though.


text:
Q: Array instance variable must be initialized in ctor(), must have array elements a[] passed from main I look everywhere and cannot find an answer or a hint to my problem. I'm sure it has probably something to do with arrays being passed by reference and me having to possibly copy the elements and pass them to my instance variable, but I just can't figure it out.
to just keep things simple
We create Wallet class that represents a wallet that can hold up to 10 bills. We are specifically told to not use Array Lists and to work with arrays.
Wallet has two instance variables, but the only one I have problems on is this one
private int contents[ ];

my main is creating new Wallet object by the following calls
int a[ ] = {100, 50, 20, 1};

Wallet myWallet = new Wallet(a);

in my constructor, I have to allocate memory for the contents[ ] instance variable and then grab the elements from a[] and have them inside of the contents array.
public Wallet(int a [ ])

System.out.println("Constructor #2 called.");

//allocate memory for contents[]

contents = new int[MAX]   //supposed to be of size 10, given info

//initialize contents[] from a[]

stuck here, how to I assign them to each other?
how do I copy 100,50,20,1 to contents at i = 0 - 3, and have reset of elements = 0?

A: You could use Arrays.copyOf(int[], int) and something like
public Wallet(int[] a) {
    System.out.println("Constructor #2 called.");
    this.contents = Arrays.copyOf(a, 10);
}


text:
Q: How to debug Server-Side JavaScript Activity I have created a server-side javascript activity as follows.  I also have a automation created via automation studio which executes the server-side script.  It is succeeding each time however I don't see the update being done on the data extension.  How can I debug to see the error msg?
<script  runat="server">

Platform.Load("core","1");

    try {

var caslDE = DataExtension.Init("6C119FFD-0EF5-476A-8127-E2E70D80ED04");

caslDE.Rows.Update({Source:"EXACT"}, ["Prospect Type"], ["A"]);

} catch (ex) {
    Write("An error has occurred: " + Stringify(ex));
}

</script>

A: I would put your code on a landing page, and test it that way.  Like so:
%%[
    VAR @Result
]%%

<script  runat="server">

    Platform.Load("core","1");

    try {

    var caslDE = DataExtension.Init("6C119FFD-0EF5-476A-8127-E2E70D80ED04");

    caslDE.Rows.Update({Source:"EXACT"}, ["Prospect Type"], ["A"]);

    } catch (ex) {
        Write("An error has occurred: " + Stringify(ex));
        Variable.SetValue("@Result", Stringify(ex));  //sets above ampscript variable
    }

</script>
//// some basic page html goes here/////
%%=v(@Result)=%%

A: I did not know how to create a landing page, then I will share a complete solution of the problem.

*

*Go to your sales force marketing cloud interface

*Click on "Web Studio" -> "Cloud Pages"

*Click on "Create Collection"

*Click on "Create" -> "Landing Page"

*Click on "Code View"

*Insert your script as Timothy Said
%%[
    VAR @Result
]%%

<script  runat="server">

    Platform.Load("core","1");

    try {

    var caslDE = DataExtension.Init("6C119FFD-0EF5-476A-8127-E2E70D80ED04");

    caslDE.Rows.Update({Source:"EXACT"}, ["Prospect Type"], ["A"]);

    } catch (ex) {
        Write("An error has occurred: " + Stringify(ex));
        Variable.SetValue("@Result", Stringify(ex));  //sets above ampscript variable
    }

*Click "save"

*Click "schedule/publish" and wait until your preview is ready.


text:
Q: WPF Resource Dictionary Build Action I have a ResourceDictionary in a xaml file called SylesResourceDictionary.xaml in a Class Library Project.
This ResourceDictionary is used in different views by Merging.
I'm new to ResourceDictionary and not sure if I'm doing it the right way. Different article suggest different Build Action Like Page and Custom Tool Like XamlIntelliSenseFileGenerator

*

*What should be the Build Action for this xaml file ? I have it set to Resource

*What should be the Custom Tool? I have it set to MSBuildCompile

*Should I delete the xaml.cs file for this xaml file ?

A: *

*The Build Action of a ResourceDictionary should be set to Page.

*XamlIntelliSenseFileGenerator. Only the XAML compiler knows how to compile the XAML file to BAML.

*Yes, unless you have any custom code defined in the code-behind file. A ResourceDictionary may have a code-behind file but by default it's XAML only.

You may also want to consider creating a project using either the WPF Custom Control Library template or the WPF User Control Libary template instead of using the Class Library template. This will make it easier working with WPF and XAML specific types in Visual Studio. You will still be able to add any other types to the project as well.

A: In general:

*

*Page

*XamlIntelliSenseFileGenerator

*No!


text:
Q: Configuring Web Config For Oracle Managed Data Access After extensive Googling I can't seem to find a solution to this issue. In a nutshell I'm using Oracle Managed Data Access client with EF 6 in a MVC/Web API application.
When I run locally I can make successful calls to various operations in the Web API 2 controllers. No problems.
When I publish to our staging server, I immediately get this error:
"Message:The underlying provider failed on Open.-Inner:Oracle.ManagedDataAccess.Client.OracleException (0x80004005): ORA-01017: invalid username/password; logon denied\r\n   at OracleInternal.ConnectionPool.PoolManager
Obviously the username/password are fine when I run locally so I feel that I'm missing putting them into a location in my web.config.
Here is my web config, you can see I'm using the entire TNS string for the Datasource value in the connection string. When I don't do that, the staging site shows an error of - TNS:could not resolve the connect identifier specified
<configuration>
  <configSections>

</configSections>
<connectionStrings>
<add name="EISContext" connectionString="metadata=res://*/EISModel.csdl|res://*/EISModel.ssdl|res://*/EISModel.msl;provider=Oracle.ManagedDataAccess.Client;provider connection string="DATA SOURCE=(DESCRIPTION = (ADDRESS = (PROTOCOL = TCP) (HOST = 123.west.dc) (PORT = 1540)) (CONNECT_DATA = (SERVER = DEDICATED) (SERVICE_NAME = tst)));PASSWORD=password;USER ID=username"" providerName="System.Data.EntityClient" />
</connectionStrings>
<appSettings>
<add key="webpages:Version" value="3.0.0.0" />
<add key="webpages:Enabled" value="false" />
<add key="ClientValidationEnabled" value="true" />
<add key="UnobtrusiveJavaScriptEnabled" value="true" />
</appSettings>
<system.data>
<DbProviderFactories>
  <remove invariant="Oracle.DataAccess.Client" />
  <add name="Oracle Data Provider for .NET" invariant="Oracle.DataAccess.Client" description="Oracle Data Provider for .NET" type="Oracle.DataAccess.Client.OracleClientFactory, Oracle.DataAccess" />
  <remove invariant="Oracle.ManagedDataAccess.Client" />
  <add name="ODP.NET, Managed Driver" invariant="Oracle.ManagedDataAccess.Client" description="Oracle Data Provider for .NET, Managed Driver" type="Oracle.ManagedDataAccess.Client.OracleClientFactory, Oracle.ManagedDataAccess" />
</DbProviderFactories>
</system.data>
<system.web>
<compilation debug="true" targetFramework="4.5.1" />
<httpRuntime />
<pages controlRenderingCompatibilityVersion="4.0" />
</system.web>
<system.webServer>
<handlers>
  <remove name="ExtensionlessUrlHandler-Integrated-4.0" />
  <remove name="OPTIONSVerbHandler" />
  <remove name="TRACEVerbHandler" />
  <add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="*" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
  </handlers>
  </system.webServer>
  <runtime>
  <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
  <dependentAssembly>
    <assemblyIdentity name="Newtonsoft.Json" culture="neutral" publicKeyToken="30ad4fe6b2a6aeed" />
    <bindingRedirect oldVersion="0.0.0.0-6.0.0.0" newVersion="6.0.0.0" />
  </dependentAssembly>
  <dependentAssembly>
    <assemblyIdentity name="System.Web.Optimization" publicKeyToken="31bf3856ad364e35" />
    <bindingRedirect oldVersion="1.0.0.0-1.1.0.0" newVersion="1.1.0.0" />
  </dependentAssembly>
  <dependentAssembly>
    <assemblyIdentity name="WebGrease" publicKeyToken="31bf3856ad364e35" />
    <bindingRedirect oldVersion="0.0.0.0-1.5.2.14234" newVersion="1.5.2.14234" />
  </dependentAssembly>
  <dependentAssembly>
    <assemblyIdentity name="System.Web.Helpers" publicKeyToken="31bf3856ad364e35" />
    <bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="3.0.0.0" />
  </dependentAssembly>
  <dependentAssembly>
    <assemblyIdentity name="System.Web.WebPages" publicKeyToken="31bf3856ad364e35" />
    <bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="3.0.0.0" />
  </dependentAssembly>
  <dependentAssembly>
    <assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35" />
    <bindingRedirect oldVersion="1.0.0.0-5.2.3.0" newVersion="5.2.3.0" />
  </dependentAssembly>
  <dependentAssembly>
    <publisherPolicy apply="no" />
    <assemblyIdentity name="Oracle.ManagedDataAccess" publicKeyToken="89b483f429c47342" culture="neutral" />
  </dependentAssembly>
   </assemblyBinding>
  </runtime>
  <oracle.manageddataaccess.client>
   <version number="*">
   <dataSources>
    <dataSource alias="SampleDataSource" descriptor="(DESCRIPTION = (ADDRESS = (PROTOCOL = TCP) (HOST = 123.west.dc) (PORT = 1540)) (CONNECT_DATA = (SERVER = DEDICATED) (SERVICE_NAME = tst)))" />
  </dataSources>
  <settings>
    <setting name="DbNotificationPort" value="-1" />
    <setting name="NAMES.DIRECTORY_PATH" value="(TNSNAMES, EZCONNECT)" />
    <setting name="TNS_ADMIN" value="C:\Oracle\product\11.2.0\client_2\network\admin"/>
    <setting name="FetchSize" value="1048576" />
    </settings>
    </version>
    </oracle.manageddataaccess.client>
    <system.codedom>
    <compilers>
    <compiler language="c#;cs;csharp" extension=".cs" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.CSharpCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warningLevel="4" compilerOptions="/langversion:6 /nowarn:1659;1699;1701" />
     <compiler language="vb;vbs;visualbasic;vbscript" extension=".vb" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.VBCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warningLevel="4" compilerOptions="/langversion:14 /nowarn:41008 /define:_MYTYPE=\"Web\" /optionInfer+" />
    </compilers>
   </system.codedom>
   <entityFramework>
   <defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework" />
   <providers>
    <provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
  <provider invariantName="Oracle.ManagedDataAccess.Client" type="Oracle.ManagedDataAccess.EntityFramework.EFOracleProviderServices, Oracle.ManagedDataAccess.EntityFramework, Version=6.121.2.0, Culture=neutral, PublicKeyToken=89b483f429c47342" />
</providers>
</entityFramework>
</configuration>

A: The fix was to set the FIPSSecurityPolicy in the reg equal to 0 instead of the default value of 1.
Thanks to this thread: Oracle.ManagedDataAccess and ORA-01017: invalid username/password; logon denied


text:
Q: How to create Gitlab webhook to receive post or get request from other webapp I am trying to receive a call back to run a gitlab runner script from third party webapp which I can register a webhook URL, but I cannot find any documentation about it.
I am wondering if this is even possible to create a webhook address to receive post request and process the request body.
Where can I find the documentation or implementation sample?

A:
run a gitlab runner script from third party webapp

If by runner script you mean project pipeline then you can use API triggers
You can add trigger in Project Settings -> CI/CD -> Pipeline triggers


text:
Q: ios - First section of tableView not moving with the rest of tableView I'm new to iOS programming so maybe my question is dumb but I have a tableView which doesn't bounce and when I scroll downwards the first section of my tableView stays in place while the section and all the content scrolls.
I don't know what to do in order to have the first section moving as well...
Edit : Actually it's the first header that doesn't move with the rest.

A: The only reason this is happening, from what i've seen is because your first, cell will be more appropriate word, instead of section, is because it is a header of the section,if i'm wrong, some code will be helpful


text:
Q: How to access https in Android Application I am trying to access Vimeo Player within my PhoneGap/Android App. Here is my HTML:
var sVidFile = document.getElementById("popupVideo");
var sLink = "82299487";
sVidFile.innerHTML = '<iframe src="https://player.vimeo.com/video/' + sLink + '" ' + 'seamless></iframe>';
$.mobile.changePage("#VideoPage");

It runs OK in the emulator but when I run it on my Android Phone it gives this error:
Application Error
There was a network error (https://player.vimeo.com/video/82299487)

Can anyone please tell me what I am doing wrong (or need to do right!)?
Thanks
EDIT:
I have tried other Video IDs also with the same result.
I have partially solved the problem by adding this to config.xml:
<access origin="https://player.vimeo.com/*" />

However only a window appears but No video shows up. Even the Video controls are not visible.


text:
Q: Docker container not connecting to any networks I am trying to containerize a python script (I didn't write the script and know very little python) so it can easily interact with one of my containers. I want this script to run on the same docker network as my other containers, which in this case is a user-defined bridge network called my_network. When using docker-compose, I am able to easily specify the network with Networks: - my_network. However, when I try to do that for this image, it does not seem to connect to my_network. I've also tried manually changing the network with docker network connect my_network container1 but docker inspect container still returns this:
"Networks": {
                "host": {
                    "IPAMConfig": null,
                    "Links": null,
                    "Aliases": null,
                    "NetworkID": "4cdc5abac597941053605ec4edd4ffff39038e154987d7aa6ad6265ea4d1cb3b",
                    "EndpointID": "",
                    "Gateway": "",
                    "IPAddress": "",
                    "IPPrefixLen": 0,
                    "IPv6Gateway": "",
                    "GlobalIPv6Address": "",
                    "GlobalIPv6PrefixLen": 0,
                    "MacAddress": "",
                    "DriverOpts": null
                }
            }

docker-compose.yml
Dockerfile
Why is this happening? Do I have to configure something in either the script or the Dockerfile in order to enable networking? I have never created or modified an image before, nor do I know very much python, so I will need a somewhat spoonfed answer if possible. Thanks!