text:
Q: CasperJS tester module output to csv instead of command line Using a CasperJS test module, is there a way to output the assert outputs to a CSV instead of a command line?

A: Sure, you can write your own assertion serializer. You can collect the information using the events "success", "skipped" and "failed". Then you can append it directly to your CSV file using PhantomJS' fs module (fs.write()).
var fs = require('fs');
casper.test.on("success", function(result){
    fs.write("file", "success;"+result.message+"\n", "a");
});
casper.test.on("skipped", function(result){
    fs.write("file", "skipped;"+result.message+"\n", "a");
});
casper.test.on("fail", function(result){
    fs.write("file", "fail;"+result.message+"\n", "a");
});


text:
Q: If dropdown option value is "day" submit can't work PHP MYSQL I want if a dropdown option is selected my dropdown can't work if you click submit.
So the other things on my dropdown filled in, can not be added to MySQL.
How do I do this? I tried several options what I found on the internet but it won't work.
So if the value day is selected it can't work
and if the value month is selected it can't work
and if the value year is selected it can't work.
All the other options can work!
This is my form:
<form action="e2admin.php" method="post">

             <select name="dag">
                    <option value="day">Dag</option>
                    <option value="1">1</option>
                    <option value="2">2</option>
                    <option value="3">3</option>
                    <option value="4">4</option>
                    <option value="5">5</option>
                    <option value="6">6</option>
                    <option value="7">7</option>
                    <option value="8">8</option>
                    <option value="9">9</option>
                    <option value="10">10</option>
                    <option value="11">11</option>
                    <option value="12">12</option>
                    <option value="13">13</option>
                    <option value="14">14</option>
                    <option value="15">15</option>
                    <option value="16">16</option>
                    <option value="17">17</option>
                    <option value="18">18</option>
                    <option value="19">19</option>
                    <option value="20">20</option>
                    <option value="21">21</option>
                    <option value="22">22</option>
                    <option value="23">23</option>
                    <option value="24">24</option>
                    <option value="25">25</option>
                    <option value="26">26</option>
                    <option value="27">27</option>
                    <option value="28">28</option>
                    <option value="29">29</option>
                    <option value="30">30</option>
                    <option value="31">31</option>
                    </select>
                    <select name="Month">
                    <option value="maand">Maand</option>
                    <option value="1">Januari</option>
                    <option value="2">Februari</option>
                    <option value="3">Maart</option>
                    <option value="4">April</option>
                    <option value="5">Mei</option>
                    <option value="6">Juni</option>
                    <option value="7">Juli</option>
                    <option value="8">Augustus</option>
                    <option value="9">September</option>
                    <option value="10">Oktober</option>
                    <option value="11">November</option>
                    <option value="12">December</option>
                    </select>
                    <select name="year">
                    <option value="jaar">Jaar</option>
                    <option value="1">2014</option>
                    <option value="2">2015</option>
                    <option value="3">2016</option>
                    <option value="4">2017</option>
                    </select>

                <select name="thuisteam1">
                    <option value=""></option>
                    <?php
                        mysql_data_seek($result, 0);

                        if(mysql_num_rows($result) > 0){
                            while($row = mysql_fetch_array($result)) {
                               echo '<option value="' . $row['Team'] . '">' . $row['Team'] . '</option>';
                            }
                        }
                     ?>

                </select>
                <input onKeyPress="return alpha(event)" style="width:20px; text-align:center;" type="text" maxlength="2" class="form-control" name="scorethuis1" placeholder="0" />
                -
                <input onKeyPress="return alpha(event)" style="width:20px; text-align:center;" type="text" maxlength="2" class="form-control" name="scoreuit1" placeholder="0" />
                <select name="uitteam1">
                    <option value=""></option>
                    <?php
                        mysql_data_seek($result, 0);

                        if(mysql_num_rows($result) > 0){
                            while($row = mysql_fetch_array($result)) {
                               echo '<option value="' . $row['Team'] . '">' . $row['Team'] . '</option>';
                            }
                        }
                     ?>
                </select>

                <select  name="thuisteam2">
                    <option value=""></option>
                    <?php
                        mysql_data_seek($result, 0);

                        if(mysql_num_rows($result) > 0){
                            while($row = mysql_fetch_array($result)) {
                               echo '<option value="' . $row['Team'] . '">' . $row['Team'] . '</option>';
                            }
                        }
                     ?>

                </select>
                <input onKeyPress="return alpha(event)" style="width:20px; text-align:center;" type="text" maxlength="2" class="form-control" name="scorethuis2" placeholder="0" />
                -
                <input onKeyPress="return alpha(event)" style="width:20px; text-align:center;" type="text" maxlength="2" class="form-control" name="scoreuit2" placeholder="0" />
                <select name="uitteam2">
                    <option value=""></option>
                    <?php
                        mysql_data_seek($result, 0);

                        if(mysql_num_rows($result) > 0){
                            while($row = mysql_fetch_array($result)) {
                               echo '<option value="' . $row['Team'] . '">' . $row['Team'] . '</option>';
                            }
                        }
                     ?>
                </select>

                <select name="thuisteam3">
                    <option value=""></option>
                    <?php
                        mysql_data_seek($result, 0);

                        if(mysql_num_rows($result) > 0){
                            while($row = mysql_fetch_array($result)) {
                               echo '<option value="' . $row['Team'] . '">' . $row['Team'] . '</option>';
                            }
                        }
                     ?>

                </select>
                <input onKeyPress="return alpha(event)" style="width:20px; text-align:center;" type="text" maxlength="2" class="form-control" name="scorethuis3" placeholder="0" />
                -
                <input onKeyPress="return alpha(event)" style="width:20px; text-align:center;" type="text" maxlength="2" class="form-control" name="scoreuit3" placeholder="0" />
                <select name="uitteam3">
                    <option value=""></option>
                    <?php
                        mysql_data_seek($result, 0);

                        if(mysql_num_rows($result) > 0){
                            while($row = mysql_fetch_array($result)) {
                               echo '<option value="' . $row['Team'] . '">' . $row['Team'] . '</option>';
                            }
                        }
                     ?>
                </select>

                <select name="thuisteam4">
                    <option value=""></option>
                    <?php
                        mysql_data_seek($result, 0);

                        if(mysql_num_rows($result) > 0){

                            while($row = mysql_fetch_array($result)) {
                               echo '<option value="' . $row['Team'] . '">' . $row['Team'] . '</option>';
                            }
                        }
                     ?>

                </select>
                <input onKeyPress="return alpha(event)" style="width:20px; text-align:center;" type="text" maxlength="2" class="form-control" name="scorethuis4" placeholder="0" />
                -
                <input onKeyPress="return alpha(event)" style="width:20px; text-align:center;" type="text" maxlength="2" class="form-control" name="scoreuit4" placeholder="0" />
                <select name="uitteam4">
                    <option value=""></option>
                    <?php
                        mysql_data_seek($result, 0);

                        if(mysql_num_rows($result) > 0){
                            while($row = mysql_fetch_array($result)) {
                               echo '<option value="' . $row['Team'] . '">' . $row['Team'] . '</option>';
                            }
                        }
                     ?>
                </select>

                <select name="thuisteam5">
                    <option value=""></option>
                    <?php
                        mysql_data_seek($result, 0);

                        if(mysql_num_rows($result) > 0){
                            while($row = mysql_fetch_array($result)) {
                               echo '<option value="' . $row['Team'] . '">' . $row['Team'] . '</option>';
                            }
                        }
                     ?>

                </select>
                <input onKeyPress="return alpha(event)" style="width:20px; text-align:center;" type="text" maxlength="2" class="form-control" name="scorethuis5" placeholder="0" />
                -
                <input onKeyPress="return alpha(event)" style="width:20px; text-align:center;" type="text" maxlength="2" class="form-control" name="scoreuit5" placeholder="0" />
                <select name="uitteam5">
                    <option value=""></option>
                    <?php
                        mysql_data_seek($result, 0);

                        if(mysql_num_rows($result) > 0){
                            while($row = mysql_fetch_array($result)) {
                               echo '<option value="' . $row['Team'] . '">' . $row['Team'] . '</option>';
                            }
                        }
                     ?>
                </select>

                <select name="thuisteam6">
                    <option value=""></option>
                    <?php
                        mysql_data_seek($result, 0);

                        if(mysql_num_rows($result) > 0){
                            while($row = mysql_fetch_array($result)) {
                               echo '<option value="' . $row['Team'] . '">' . $row['Team'] . '</option>';
                            }
                        }
                     ?>

                </select>
                <input onKeyPress="return alpha(event)" style="width:20px; text-align:center;" type="text" maxlength="2" class="form-control" name="scorethuis6" placeholder="0" />
                -
                <input onKeyPress="return alpha(event)" style="width:20px; text-align:center;" type="text" maxlength="2" class="form-control" name="scoreuit6" placeholder="0" />
                <select name="uitteam6">
                    <option value=""></option>
                    <?php
                        mysql_data_seek($result, 0);

                        if(mysql_num_rows($result) > 0){
                            while($row = mysql_fetch_array($result)) {
                               echo '<option value="' . $row['Team'] . '">' . $row['Team'] . '</option>';
                            }
                        }
                     ?>
                </select>

                <input style="margin-left:330px;" type="submit" class="form-control" value="Toevoegen" />

            </form>

A: Something like this?
<select name="dag" style="">
      <option disabled="" selected="">Dag</option>
      <option value="1">1</option>
      <option value="2">2</option>
      <option value="3">3</option>

</select>

Even it might look like they are disabled , they are still shown but you can't select them. And that means, that the user is forced to select something.
The rest has to be in JS or you validate your form before you write it into the database.
Somethin like:
if(empty($_POST['month']) || empty($_POST['day'])){
     echo "ERROR AT DATE";
}else{
     //HANDLE POST REQUEST
}

An example can be found here: http://jsfiddle.net/Ye88R/

A: You can always use the disabled with value="", it won't let you send.
    <form method="POST">
        <select required>
            <option disabled value="">Day</option>
            <option>1</option>
            <option>2</option>
        </select>
        <button type="submit">Send</button>
    </form>

A: try this
Use jquery like this
$("#check").click(function(e){
 if($("[name=dag]").val() == "day")
{
alert("day is selected");
return false;
}
 else if($("[name=Month]").val() == "maand")
{
alert("maand is selected");
return false;
}
});

add this line in  of html

Demo

redpajama_set_name: RedPajamaStackExchange


text:
Q: Custom Body Class from URI I'm working on how to get a custom class into my body tag. I'd like to parse the URI and drop each part of the URI into the class as a separate string. This is a far as I've gotten. I've got the URI parsed and placed into the body class, but as a single string separated by /'s instead of spaces.
Also, I need the IF statement to add "home" if the URI is simply "/". Unfortunately, my current IF statement blows up the whole page. :-(
<?
    $url = $_SERVER['REQUEST_URI'];
    $url = trim($url, '/');
    if $url = '' {
        $url = 'home';
    }
    endif;
?>
<body class="<?=$url?>">

A: try this
<?
  $url = $_SERVER['REQUEST_URI'];
  $url = trim($url, '/');
  $url = str_replace ("/", " ", $url);
  if ($url == '') {
    $url = 'home';
  }
?>
<body class="<?=$url?>">

A: I suggest you to use regular expressions.
<?php
    $url = $_SERVER['REQUEST_URI'];
    $url = trim($url, '/');
    if (preg_match("/^\\/?$/", $url)) {
        $url = 'home';
    }
    endif;
?>

"/^\\/?$/" this is regular expression

*

*^ - means beggining of string

*$ - means end of string

*\\/ - it's / sign, but it has to be escaped by \\

*? means that sign before is optional

It will make match when REQUEST_URI will be empty, or it would contain only / sign.


text:
Q: Concentration (card game) with Latex I would like to create a concentration card game (Matching Pairs) with Latex.
On one side, there should be a function and the matching graph. On the otherside should be a logo.
I would like to print it so that the front and back match. I.e. after printing I would only have to cut out the cards.
I have a MWE with a tabular, but:

*

*Is there a better solution?

*For example, if a graph is accidentally too big, the front and the back don't match anymore.

*The graph is not centered.

*Is there maybe an existing setup?

\documentclass[11pt, a4paper, parskip=half]{scrartcl}
\usepackage{tikz}
\usepackage{pgfplots}
\usepackage{array}
\pgfplotsset{compat=1.12}

\begin{document}

\renewcommand\arraystretch{7}
{\centering
\begin{tabular}{|*{4}{>{\centering\arraybackslash}m{0.25\textwidth}|}}\hline
$f(x)=\frac{1}{x}$ &  \begin{tikzpicture}[scale=1,>=latex,font= \footnotesize]
\begin{axis}[axis lines = middle,domain=-2.3:2.3,xmin=-5.3,xmax=5.3,ymin=-5.3, ymax=5.3,x=.25cm,y=.25cm]
\addplot[very thick,blue ] {1/x};
\end{axis}
\end{tikzpicture} & & \\ \hline
& & & \\ \hline
& & & \\ \hline
& & & \\ \hline
& & & \\ \hline
& & & \\ \hline
\end{tabular}
}

\newpage

\renewcommand\arraystretch{7}
\begin{tabular}{|*{4}{p{0.25\textwidth}|}}\hline
\includegraphics[width=1\linewidth]{example-image-1x1} & & & \\ \hline
& & & \\ \hline
& & & \\ \hline
& & & \\ \hline
& & & \\ \hline
& & & \\ \hline
\end{tabular}
\end{document}


text:
Q: jQuery IE8 - Firefox problem I have a big problem with IE8 where I use the jQuery framework.
What works on Firefox, it doesn't work as well in IE8. I am not even checking IE7 :).
Basically, I have simple animations that show/hide div layers and also that move top/down - left/right some of the div layers. Nothing special, just adding some movement to the page. So when you click on contact, instead of the navigation moving up and showing the contact, the contact moves down and breaks the layout which is not so big problem, but when you press on the client area and than press contact - it totally breaks the layout - BIG problem.
Please help.
You can view the site here

A: +1 Daniel: caused by margin-collapsing issues. Margin collapsing is confusing enough even without the IE issues, and is generally best avoided. Changing the animation to use only paddings and positioning will make it more reliable.
Also, you need to return false from your event handlers to stop the # link being followed, causing the browser to jump back to the top of your page.
Finally, give every element that has position (relative or absolute) an explicit z-index property to avoid the bug where IE7 defaults them, causing mis-stacking that makes the contact address invisible.

A: Don't understand what "it totally breaks the layout" means. I only see that in IE the page shocks when you visit the client area. This is due to the height and the "automatic" scrollbar. Having a fixed y-scrollbar is less or more a good workaround.
But clicking the contact link after visiting the client area doesn't show something different as from in FF.
After having a quick glance at the HTML source I can only tell that you really need to get rid of the HTML transitional DTD and to get a HTML strict DTD. It will fix most of the CSS related problems. Learn more here.

A: I have noticed that the code relies on the marginTop property to animate elements.
e.g. The handler for the click event of the contact information:
$("#moveContact").click(function(){

Makes use of the marginTop property:
marginTop: "167px",

This is buggy in Internet Explorer, and may result in unexpected behaviour.  See this article about margin-top for more information.
This isn't a problem with jQuery, it's to do with the way Internet Explorer interprets the value of margin-Top.  I'm not sure if this is the reason why the animation isn't working, but it would be a good place to start looking.

A: Some observations.  First, the IE8 behavior on you describe on "#moveContact" is for normal mode only.  If you hit "compatibility mode", the broken page icon to the right of the URL box, you get a different (and still wrong) behavior.
Second, the way you include jquery is like this:
http://ajax.googleapis.com/ajax/libs/jquery/1.3/jquery.min.js

I would encourage you to supply your own copy of jQuery.  You can do that here.  I would go for the latest 1.3.2.  That may fix your problem.  I notice that the release notes for 1.3 show testing against IE7 as the latest IE.


text:
Q: Displaying motd with Ubuntu 14 I'm trying to display on a motd user's detail (the user and the actual date)
Here is the step i take so far:
sudo nano /etc/update-motd.d/00-welcome   #(script)
#!/bin/sh
echo "Welcome user: ${USER}. Today is $(date)"  #(save the file)

sudo chmod +x /etc/update-motd.d/00-welcome
But after a successful login the motd do not appear. What should i try instead?

A: Did you read ALL of man update-motd? Near the end, it says:
   Scripts should emit a blank line before output, and end with a  newline
   character.  For instance:

So, change your script to:
#!/bin/sh
echo
echo "Welcome user: ${USER}. Today is $(date)"


text:
Q: Added a custom framework, now Swift can't unarchive data I have a pretty trivial Swift app that has a model class named DemoNote. An array of DemoNote instances is read/written via keyed archiving. This worked fine while DemoNote was included in the app.
But then I moved DemoNote.swift to a new custom framework called DemoSharedCode. Aside from making sure Xcode was using the framework in the app target, I made sure to

*

*Mark DemoNote and its vars and methods as public so they'd be visible outside of the framework

*Add import DemoSharedCode to any classes that want to use DemoNote
So now the compiler is happy. But at run time the unarchiving fails with this error:
2015-02-17 12:12:53.417 DemoNotesSwift[70800:16504104] *** Terminating app due to
uncaught exception 'NSInvalidUnarchiveOperationException', reason:
'*** -[NSKeyedUnarchiver decodeObjectForKey:]: cannot decode object of class
(DemoNotesSwift.DemoNote)'

In the above, DemoNotesSwift is the app name, DemoNote is the class name, and the line of code is attempting to unarchive objects from an NSData blob:
let savedObjects = NSKeyedUnarchiver.unarchiveObjectWithData(savedData) as? [(DemoNote)]

I'm guessing that moving DemoNote to the framework means its module name has changed, which breaks unarchiving, but I'm not sure of that. I'm also not sure what to do about it-- maybe I need to call +setClass:forClassName: on the unarchiver, but if so I don't know what the arguments would be.

A: Moving DemoNote from the app to a framework did change the module name, which meant that NSKeyedUnarchiver couldn't find instances of the archived class due to a name mismatch. The fix was to add this line before unarchiving:
NSKeyedUnarchiver.setClass(DemoNote.self, forClassName: "DemoNotesSwift.DemoNote")

In this case, DemoNote.self gets the current full class name, and DemoNotesSwift.DemoNote is what the class used to be called when it was part of the app.
This was only necessary because I had previously existing data that I wanted to keep.


text:
Q: Covariant Derivative in Spherical Coordinates $\nabla_\theta \theta$ Given a spherical metric $ds^2 = dr^2 + r^2(d\theta^2 + \sin^2(\theta) d\phi^2)$.
Is it correct that $\nabla_\theta \theta = 1$? Or do I need to consider the metric?

A: Yes it is right. Here, we have a certain open set $U\subset\Bbb{R}^3$, which is the domain of the spherical coordinate system, and on this domain, we have the spherical coordinate maps $(r,\theta,\phi):U\to (0,\infty)\times (0,\pi)\times (0,2\pi)$, and $r,\theta,\phi$ are each smooth functions so we can consider their exterior derivatives $dr,d\theta,d\phi$, which are thus $1$-forms on $U$. We also have the coordinate-induced vector fields on $U$, $\frac{\partial}{\partial r}, \frac{\partial}{\partial \theta}, \frac{\partial}{\partial \phi}$. Now,
\begin{align}
\nabla_{\theta}\theta\equiv\nabla_{\frac{\partial}{\partial \theta}}(\theta):=(d\theta)\left(\frac{\partial}{\partial \theta}\right):=\frac{\partial\theta}{\partial\theta}=1.
\end{align}
The first is simply notation. The second is because $\theta$ being a smooth function means by definition that $\nabla\theta:=d\theta$. The third equality is again a definition (of the exterior derivative acting on functions). The last should be clear.
The only thing I would caution you is to not confuse $\nabla_{\theta}\theta$ (which, again, really means $\nabla_{\frac{\partial}{\partial \theta}}(\theta)$) with $\nabla_{\frac{\partial}{\partial \theta}}\frac{\partial}{\partial\theta}$. The former is a smooth real-valued function on $U$, while the latter is a vector field on $U$.

More generally, on any smooth manifold $M$ with a connection $\nabla$ on the tangent bundle (which is then extended in the usual way to all tensor bundles, in particular to the smooth functions), if you take any coordinate chart $(U,x=(x^1,\dots, x^n))$, then we have $\nabla_{\mu}(x^{\nu})=dx^{\nu}\left(\frac{\partial}{\partial x^{\mu}}\right)=\delta^{\nu}_{\mu}$.
And no this doesn't depend on the metric because a connection $\nabla$ really refers to a connection on the tangent bundle $TM$. We then extend this to all the tensor bundles, and in particular to the space of smooth functions, where by definition we set $\nabla f=df$. At this point, I should again caution you that $\nabla f$ does not refer to the gradient vector field you may have seen in multivariable calculus courses; here, $\nabla f=df$ is a $1$-form/covector field. The usual gradient vector field is something which depends on the metric tensor, and is defined as $\text{grad}_g(f):=g^{\sharp}(df)=g^{\sharp}(\nabla f)$ (see this for a related question).


text:
Q: Add executable file to lubuntu menu I would like to add the gapminder executable file to the lubuntu menu, with as little terminal use as possible... Is there any way to do this? Here is an attached image of the file:

A: The easiest way in my opinion is this:
Open directory /usr/share/applications with sudo rights (easiest way with command 'gksu pcmanfm', gksu must be installed) and create the file appname.desktop and put this inside:

[Desktop Entry]
Name='appname'
Exec=/'path-to-app'/'appname'
Terminal=false
Type=Application

The menu will detect it automatically (a reboot may be needed).


text: Q: Vary keyboard region per device I'm UK based running Windows 10 on multiple devices, one of which has a US keyboard; all the other devices have UK keyboards. Changing the keyboard to US affects all my devices and changing it back to UK on any other device (including Windows phone) sets all devices to UK, including the one with a US keyboard attached to it. It's almost as if the setting is per user rather than per device which is annoying in my case: does anyone know how to configure the keyboard per device on Windows 10?


text:
Q: Discard changes not working properly when IDE is Open There was a problem on all the computers of the team about a month ago.Discard changes(git) not working properly when IDE is open.We have different IDE in the team( web storm, visual studio code).When Ide is open i cannot do revert change,but when i close ide -all work fine.I work with smart git and get following message when i discard change
Discard: unable to create file src/app/pipes/transform-email/transform-email.pipe.ts: Permission denied

any ideas?


text:
Q: How to write a for loop in R when a variable is defined within `` I am trying to write a loop for pulling residuals after fitting a multilevel model using rstan. However, one of the variables is contained within `` and I don't think the loop is able to go through this:
For example, this works:
# pull residuals
strata_residuals = extract(model, pars = paste("b[", 1:16, "]", sep=""))
summary_residuals <- matrix(0, nrow = n_strata, ncol = 3)
summary_residuals[1,] = quantile(strata_residuals$`b[1]`, prob = c(0.5, 0.025, 0.975))
summary_residuals[2,] = quantile(strata_residuals$`b[2]`, prob = c(0.5, 0.025, 0.975))
summary_residuals[3,] = quantile(strata_residuals$`b[3]`, prob = c(0.5, 0.025, 0.975))
summary_residuals[4,] = quantile(strata_residuals$`b[4]`, prob = c(0.5, 0.025, 0.975))
summary_residuals[5,] = quantile(strata_residuals$`b[5]`, prob = c(0.5, 0.025, 0.975))
summary_residuals[6,] = quantile(strata_residuals$`b[6]`, prob = c(0.5, 0.025, 0.975))
summary_residuals[7,] = quantile(strata_residuals$`b[7]`, prob = c(0.5, 0.025, 0.975))
summary_residuals[8,] = quantile(strata_residuals$`b[8]`, prob = c(0.5, 0.025, 0.975))
summary_residuals[9,] = quantile(strata_residuals$`b[9]`, prob = c(0.5, 0.025, 0.975))
summary_residuals[10,] = quantile(strata_residuals$`b[10]`, prob = c(0.5, 0.025, 0.975))
summary_residuals[11,] = quantile(strata_residuals$`b[11]`, prob = c(0.5, 0.025, 0.975))
summary_residuals[12,] = quantile(strata_residuals$`b[12]`, prob = c(0.5, 0.025, 0.975))
summary_residuals[13,] = quantile(strata_residuals$`b[13]`, prob = c(0.5, 0.025, 0.975))
summary_residuals[14,] = quantile(strata_residuals$`b[14]`, prob = c(0.5, 0.025, 0.975))
summary_residuals[15,] = quantile(strata_residuals$`b[15]`, prob = c(0.5, 0.025, 0.975))
summary_residuals[16,] = quantile(strata_residuals$`b[16]`, prob = c(0.5, 0.025, 0.975))
colnames(summary_residuals) = c("Med", "LCI", "UCI")
summary_residuals

However, this does not:
# pull residuals
strata_residuals = extract(model, pars = paste("b[", 1:16, "]", sep=""))
summary_residuals <- matrix(0, nrow = n_strata, ncol = 3)
for(i in 1:n_strata){
  summary_residuals[i,] = quantile(strata_residuals$`b[i]`, prob = c(0.5, 0.025, 0.975))
}
colnames(summary_residuals) = c("Med", "LCI", "UCI")
summary_residuals

Any help is appreciated!


text:
Q: Cannot load module after updating php to 5.5 after updating php and restarting the apache2 i get this error:
Cannot load /usr/lib/apache2/modules/mod_R.so into server: /usr/lib/apache2/modules
/mod_R.so: undefined symbol: ap_log_rerror

This module is the rApache. Before that update everything was fine on my ubuntu 12.04. I am very new to ubuntu.
Can anybody help?

A: that's not a problem with php5, but the php5.5 PPA also updates apache2 package from apache2.2 to apache2.4, so you will probably need to update your rApache as well.
Ondrej.


text:
Q: Debugging a simple Javascript error I am trying to move down a div container with Id( topleft) using java script, but my java script code has a problem. Logically, it should work, can someone check?
HTML code

    <title>Test</title>

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

CSS code
#container {
    width: 400px;
    height: 400px;
    background-color: red;
    margin: 0 auto;
    position: relative
}
#topright, #topleft,#bottomright, #bottomleft {
    width: 50px;
    height: 50px;
    background-color: black;
    position: absolute;
}
#bottomright, #bottomleft {
    bottom:0;/*175*/
}
#topright, #topleft {
    top:0; /*175*/
}
#bottomleft, #topleft {
    left:0; /*175*/
}
#bottomright, #topright {
    right:0; /*175*/
}

JavaScript code
mt=0;
function move(){
    topleft=document.getElementById("topleft");
    for (n=0;n<=175;n++){
        topp=topleft.style.top;
        topp=parseInt(topp);
        topp++
        topleft.style.top=topp+"px"
    }
}

function start(){
    setInterval("move()",1);
}

Can anybody rectify it?

A: There are several issues with that code, I suspect #4 and #7 are causing you the most immediate problem:

*

*setInterval("move()"1); is a syntax error, and so that would be why it's not running. You need a comma before the 1: (you've edited the question to fix this)
setInterval("move()", 1);
// Comma -----------^

*You're falling prey to The Horror of Implicit Globals by not declaring your mt, n, topleft, and topp variables. Always declare your variables, and declare them in the innermost scope in which they make sense.

*Passing strings into setInterval is poor practice; it requires the engine to do an implicit compilation and the scope of that compilation is probably not what you expect it to be (although with your code as quoted — e.g., if move really is a global — it would work). Just use the function reference:
setInterval(move, 1);

*You're using parseInt on topleft.style.top (indirectly), but the topleft element doesn't have any style attribute, and therefore topleft.style.top is "". So you're getting NaN, which isn't useful. The style property on elements does not reflect CSS, it only reflects what's in the style attribute of the element. Look at getComputedStyle (for standards-based browsers) or currentStyle (for older IE).

*It's almost always best to use a radix with parseInt, e.g.: parseInt(topp, 10) rather than just parseInt(topp).

*FWIW, if the setInterval works, that code will run really, really frequently (though not every millisecond; the specification says engines should treat values below 4 as being 4, and in any case it's subject to the implementation and the single JavaScript UI thread not being busy with other things).

*Making a series of changes to elements in a loop without yielding to the browser won't animate those elements. Instead of looping, remember n and move the element just one bit on each call. Each time move returns, that gives the browser a chance to update the UI.
Here's an example with the minimal modifications I'd make (doesn't handle older IE's currentStyle): Live Copy | Live Source
<!doctype html>

  <title>Test</title>

Notes:

*

*I put the code inside a scoping function to avoid creating globals.

*I put the code at the end, just before the closing  tag, so all elements exist as of when it runs.

*I used a chained series of setTimeout rather than setInterval (optionaly, in this case it's really a matter of preference).

*Various things from the list at the beginning of the answer.

*I only make one change per callback, so the browser has time to do the animation.

*I made the delay between animation frames a variable (delay) and set it to 10. You can use whatever value suits you, note #6 on the list above if you use values below 4.

*I used addEventListener to hook up the event rather than using an onclick attribute. Using onclick attributes in the markup requires that you create global functions, which isn't generally a good idea. (On older versions of IE -- including IE8 -- you'll have to use attachEvent instead. Or you can do topleft.onclick = function() { ... }; but that's fairly limiting [you can only have a single handler].)

A: As say T.J. Crowder replace the
function start(){
    setInterval("move()"1);
}

to
function start(){
    setInterval(move, 1);
}


text:
Q: How can I set up this query? I'm trying to set up a query for the website's student database, but I have difficulties putting together a complete query. This would be the description of the data that must be obtained from the tables:
# Student data
TABLE: wp_users
Student ID -> column: ID
Student name -> column: display_name
Student email -> column: user_email
Campaign Url -> column: user_url

# Course data
TABLE: wp_comments
Student ID -> column: user_id
Course ID -> column: comment_post_ID
Course status -> column: comment_approved
in-progress
complete
Show course type status -> column: comment_type 'sensei_course_status'
Record ID -> column: comment_ID

TABLE: wp_commentmeta
Registration date -> column: meta_key 'start'   |
Note percentage -> column: meta_key 'percent'   | meta_value (result of the meta_key column)
Assisted classes -> column: meta_key 'complete' |
Record ID -> column: comment_id

# Purchase Data
TABLE: wp_post
for products, coupons and orders.
Order Id -> Column: ID
Order date -> column: post_modified_gmt
record type -> column: post_type 'shop_order'
Order status -> column: post_status

TABLE: wp_postmeta
Order Id -> column: post_id
User Id -> column: meta_value
meta_key = '_customer_user'

TABLE: wp_woocommerce_order_items
coupon -> column: order_item_name
order_item_type = 'coupon'
Product name -> column: order_item_name
    order_item_type = 'line_item'
Order id -> column: order_id
record for product id -> column: order_item_id

TABLE: wp_woocommerce_order_itemmeta
record for the product id -> column: order_item_id
Product id -> column: meta_value
meta_key = '_product_id'

I was able to set up the query using only the student data and the course, but the second part I can't include
SELECT wu.display_name,
       wc.comment_post_ID,
       wc.comment_type,
       wc.comment_approved,
       wm.meta_key,
       wm.meta_value

FROM   wp_comments wc,
       wp_users wu,
       wp_commentmeta wm

WHERE  wc.comment_type = 'sensei_course_status'
       AND wc.user_id = wu.ID
       AND wm.comment_id = wc.comment_ID

How can I include purchase data (order id, product name and coupon used for purchase)?
I tried to use inner Joining a query works but it doesn't return any data. What am I doing wrong?
  SELECT  wu.ID,
          wu.display_name,
          wc.comment_post_ID,
          wc.comment_approved,
          wcm.meta_key,
          woi.order_id,
          woi.order_item_name

  FROM wp_posts wpo
  INNER JOIN wp_users wu ON wu.ID = wpo.ID
  INNER JOIN wp_comments wc ON wc.user_id = wu.ID
  INNER JOIN wp_commentmeta wcm ON wcm.comment_id = wc.comment_ID
        AND wcm.meta_value = wcm.meta_key
  INNER JOIN wp_postmeta wpm ON wpm.post_id = wpo.ID
        AND wpm.meta_value = wu.ID
        AND wpm.meta_key = '_customer_user'
  INNER JOIN wp_woocommerce_order_items woi ON woi.order_id = wpo.ID
  INNER JOIN wp_woocommerce_order_itemmeta wom ON wom.order_item_id = woi.order_item_id
        AND wom.meta_key = '_product_id'


text:
Q: Detecting Filename Patterns for Creating RegEx When using a string to define a RegEx, I'd like to know if there is a way to get my code to recognize a pattern in the files contained within a directory.
The goal is to rename these files using our naming conventions, so I'm writing something to try to create the expression to use in RegEx.
I've started something here, but I don't think it is the best, and I'm not sure how to fill in the "{0}" portion of my RegEx expression.
    private Regex m_regex;

    public string DirPattern(string path, string[] extensions) {
        string result = null;
        int endPos = 0;
        int resLen = 0;
        int startLen = 0;
        var dir = new DirectoryInfo(path);
        foreach (var file in dir.GetFiles()) {
            if (extensions.Contains(file.Extension)) {
                if (!String.IsNullOrEmpty(result)) {
                    int sL = 0;
                    int fileLen = file.Name.Length;
                    string one = null;
                    for (int i = 0; i < resLen && i < fileLen; i++) {
                        if (result[i] == file.Name[i]) {
                            sL = i + 1;
                            if (String.IsNullOrEmpty(one)) {
                                one = file.Name;
                            } else {
                                break;
                            }
                        }
                    }
                    if (!String.IsNullOrEmpty(one)) {
                        int eP = 0;
                        int oneLen = one.Length;
                        for (int i = fileLen - 1; -1 < i; i--) {
                            if (result[i] == file.Name[i]) {
                                eP = i - 1;
                            } else {
                                break;
                            }
                        }
                        if ((0 < endPos) && (eP == endPos)) {
                            if ((0 < startLen) && (sL == startLen)) {
                                result = one.Substring(0, startLen) + "{0}" + one.Substring(endPos);
                            } else if (0 < sL) {
                                startLen = sL;
                            }
                        } else if (0 < sL) {
                            startLen = sL;
                        }
                    }
                } else {
                    result = file.Name;
                    resLen = result.Length;
                }
            }
        }
        return result;
    }

    public bool GenerateRexEx(string path, string[] extensions) {
        var pattern = DirPattern(path, extensions);
        if (!String.IsNullOrEmpty(pattern)) {
            m_regex = new Regex(pattern);
            return true;
        }
        return false;
    }

Here is an example of a list of files that would be most like our company files (which I am not allowed to post):

UPDATE:
The goal is to take files with names like this:
FOLDER_PATTERN_1 + MixedContent + FOLDER_PATTERN_2

and rename them using our format:
OUR_PATTERN_1 + MixedContent + OUR_PATTERN_2

That way, our software will be able to search the files more efficiently.

A: I think that in your case you need just to find count of characters in the prefix pattern and postfix pattern. Then you can simply replace some count of characters with your pattern. I wrote a simple code which I tested and works. You can inspire yourself and use the same method I think. Anyway there are areas to make this better, but I hope it is enough to answer your question.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;

namespace ConsoleApplication1
{
    static class Program
    {
        static void Main()
        {
            var inputFilenames = new string[]
            {
                "mtn_flint501-muxed",
                "mtn_flint502-muxed",
                "mtn_flint503-muxed",
                "mtn_flint504-muxed",
                "mtn_flint505-muxed",
                "mtn_flint506-muxed",
                "mtn_flint507-muxed",
                "mtn_flint508-muxed",
                "mtn_flint509-muxed",
                "mtn_flint510-muxed",
                "mtn_flint511-muxed",
                "mtn_flint512-muxed",
            };
            var replacedFilenames = ReplaceFileNames(inputFilenames);

            for (int i = 0; i < inputFilenames.Length; i++)
            {
                Console.WriteLine("{0} >> {1}", inputFilenames[i], replacedFilenames[i]);
            }
            Console.ReadKey();
        }

        private const string OurPrefixPattern = "Prefix_";
        private const string OurPostfixPattern = "_Postfix";

        /// <summary>
        /// Method which will find the filename's pattern and replace it with our pattern
        /// </summary>
        /// <param name="fileNames"></param>
        /// <returns></returns>
        public static string[] ReplaceFileNames(params string[] fileNames)
        {
            //At first, we will find count of characters, which are same for
            //all filenames as prefix and store it to prefixCount variable and
            //we will find count of characters which are same for all filenames
            //as postfix and store it to postfixCount variable
            var prefixCount = int.MaxValue;
            var postfixCount = int.MaxValue;
            //We will use first filename as the reference one (we will be comparing)
            //all filenames with this one
            var referenceFilename = fileNames[0];
            var reversedReferenceFilename = referenceFilename.ReverseString();
            //Lets find the prefixCount and postfixCount
            foreach (var filename in fileNames)
            {
                if (filename == referenceFilename)
                {
                    continue;
                }
                //Check for prefix count
                var firstDifferenceIndex = referenceFilename.GetFirstDifferentIndexWith(filename);
                if (firstDifferenceIndex < prefixCount)
                {
                    prefixCount = firstDifferenceIndex;
                }
                //For postfix count we will do the same, but with reversed strings
                firstDifferenceIndex = reversedReferenceFilename.GetFirstDifferentIndexWith(filename.ReverseString());
                if (firstDifferenceIndex < postfixCount)
                {
                    postfixCount = firstDifferenceIndex;
                }
            }
            //So now replace given filnames with our prefix and post fix.
            //Our regex determines only how many characters should be replaced
            var prefixRegexToReplace = string.Format("^.{{{0}}}", prefixCount);
            var postfixRegexToReplace = string.Format(".{{{0}}}$", postfixCount);
            var result = new string[fileNames.Length];
            for (int i = 0; i < fileNames.Length; i++)
            {
                //Replace the prefix
                result[i] = Regex.Replace(fileNames[i], prefixRegexToReplace, OurPrefixPattern);
                //Replace the postfix
                result[i] = Regex.Replace(result[i], postfixRegexToReplace, OurPostfixPattern);
            }
            return result;
        }

        /// <summary>
        /// Gets the first index in which the strings has different character
        /// </summary>
        /// <param name="value"></param>
        /// <param name="stringToCompare"></param>
        /// <returns></returns>
        private static int GetFirstDifferentIndexWith(this string value, string stringToCompare)
        {
            return value.Zip(stringToCompare, (c1, c2) => c1 == c2).TakeWhile(b => b).Count();
        }

        /// <summary>
        /// Revers given string
        /// </summary>
        /// <param name="value">String which should be reversed</param>
        /// <returns>Reversed string</returns>
        private static string ReverseString(this string value)
        {
            char[] charArray = value.ToCharArray();
            Array.Reverse(charArray);
            return new string(charArray);
        }
    }
}

The console output looks like this

mtn_flint501-muxed >> Prefix_01_Postfix
mtn_flint502-muxed >> Prefix_02_Postfix
mtn_flint503-muxed >> Prefix_03_Postfix
mtn_flint504-muxed >> Prefix_04_Postfix
mtn_flint505-muxed >> Prefix_05_Postfix
mtn_flint506-muxed >> Prefix_06_Postfix
mtn_flint507-muxed >> Prefix_07_Postfix
mtn_flint508-muxed >> Prefix_08_Postfix
mtn_flint509-muxed >> Prefix_09_Postfix
mtn_flint510-muxed >> Prefix_10_Postfix
mtn_flint511-muxed >> Prefix_11_Postfix
mtn_flint512-muxed >> Prefix_12_Postfix


text:
Q: NestedScroll view detect scroll state I am trying to detect scroll state whenever is it STATE_IDLE or DRAGGING. For the reference i found this answer:
https://stackoverflow.com/a/37667686/1108519
which has helped me to get the basic idea, i implemented it but its just detecting STATE_IDLE and forcing method
@Override
public void stopNestedScroll() {
    super.stopNestedScroll();
    dispatchScrollState(RecyclerView.SCROLL_STATE_IDLE);
}

other two methods onStartNestedScroll and startNestedScroll are never called, so because of checking state in dispatchScrollState i never get my method called where i extend interface.
The only additional thing i added is i extended my class with
NestedScrollingView.NestedScrollViewScrollStateListener

and set the scrollListener in this class as:
nestedScrollView.setScrollListener(this);

So what could be causing that its not calling start methods?


text:
Q: Async/await vs Task.Run in C# I am just new to this world of asynchronous stuff.
Please bear with my lack of knowledge.

*

*It is said when a method encounters await ... "It tells the awaitable to run the remainder of the method when it completes, and then returns from the async method."
I did not get this part.
So does it mean the method still keeps on running synchronously and waits till the awaitable returns and then proceeds with the rest of the method?
If not please explain then why Task.Run is needed to run a method in the background or in a fire and forget manner. I could still be achieved via await also right? i.e.
The method keeps on executing the rest of the statements without waiting for the await to return.
I hope that is similar to a background run approach. Or is not it? I am confused.

*If a method is marked with async and await and that in turn calls another method asynchronously in a separate layer that's also marked with async and await ..
then how the the call of the first method that's marked with async and await from a separate method say name ABC should look like?
I do not want to annotate that method to be async/await. So
Task.Run(() => DoWork());

from ABC () is fine without marking it async/await?
Or is it against the principle of asynchrony?
Here is what I am trying to achieve ...
   public IList<CreateCaseOutput> ABC(CreateCaseInput CreateCaseInput,SaveCaseSearchInput SaveCaseSearchInput)
    {
        CaseSQL.getABCParameters(CreateCaseInput, RequestType, out strSPQuery, out listParam);
        var AcctLst = rep.ExecuteStoredProcedure<CreateCaseOutput>(strSPQuery, listParam).ToList();

        if (!string.IsNullOrEmpty(AcctLst.ElementAt(0).o_case_seq.ToString()))
        {
            Task.Run(async () =>
            {
                await DEF(SaveCaseSearchInput, AcctLst.ElementAt(0).o_case_seq);
            }).ConfigureAwait(false);
        }
        console.writeLine("After Async called");
        return AcctLst;
    }

    public async Task<SaveCaseSearchOutput>> DEF(SaveCaseSearchInput SaveCaseSearchInput,Int64? case_key)
    {

            CaseSQL.getDEFParameters(SaveCaseSearchInput, case_key, out strSPQuery, out listParam);
            var AcctLst = await rep.ExecuteStoredProcedureAsync<SaveCaseSearchOutput>(strSPQuery, listParam);
            return AcctLst;
    }

DEF which is async/await needs to be called in the background in fire and forget approach from ABC and once fired I want to continue with rest of ABC and run DEF in the background. What's wrong in this fire and forget approach ? If I call
only
DEF(SaveCaseSearchInput, AcctLst.ElementAt(0).o_case_seq);

instead of
 Task.Run(async () =>
                {
                    await DEF(SaveCaseSearchInput, AcctLst.ElementAt(0).o_case_seq);
                }).ConfigureAwait(false);
            }
            return AcctLst;

then this code runs synchronously in debugger.
Am I doing something wrong ?

A:
So does it mean the method still keeps on running synchronously and waits till the awaitable returns and then proceeds with the rest of the method?

No. The awaitable has a "callback" mechanism. So, the method just registers itself with the awaitable. When the awaitable completes, it will execute its callbacks, which include the continuation of the async method.
In the meantime, the async method returns an incomplete task.

If not please explain then why Task.Run is needed to run a method in the background or in a fire and forget manner.

If you want to run on a background thread, then use Task.Run. Task.Run just schedules work to the thread pool.

I could still be achieved via await also right? i.e.
  The method keeps on executing the rest of the statements without waiting for the await to return.
  I hope that is similar to a background run approach. Or is not it? I am confused.

Well, you could "forget" the task by just not awaiting it:
MyMethod()
{
  SomeMethodAsync(); // Note: no await; we just ignore the task.
}

You almost never want to do "fire and forget", though. Easily >90% of the time people ask for it, it's actually a design error.

I do not want to annotate that method to be async/await... Or is it against the principle of asynchrony?

That's against the principle. If you think about it, it doesn't really make sense to block on asynchronous code. You want to go through the trouble of making a method asynchronous (meaning it doesn't block a thread), and then block a thread on it? Why, exactly? Sometimes in practice, the code will temporarily end up in this kind of state during a transition to asynchronous code, but it's a tricky place to be.
For more information, see my article on async best practices, particularly "async all the way".

A: 'It is said when a method encounters await ... "It tells the awaitable to run the remainder of the method when it completes, and then returns from the async method."'
So let's say you have a method A that calls a method B.  Method B has the "async" keyword in its declaration.  In method B there is a time-consuming call to LongMethod, which ultimately returns a string.
What we want here is for method A to not have to wait for ages for method B's LongMethod to complete.  So we write in Method B:
string newVariable = await Task.Run(()=>LongMethod());
If LongMethod itself is also async, then LongMethod can only return a void, a non generic Task or a generic Task.  Therefore we would have to change the return type in the LongMethod declaration to Task<string>
So back to our story, the LongMethod task has started...  At this point method A resumes from the next line of code after the call to method B, and method B continues to wait for the LongMethod to finish, so there are now two threads running.  Eventually, the LongMethod completes and method B runs to the end, meanwhile method A has continued to run, or has maybe even finished running.
I hope this gives you a picture of the relationship between Async/Await and Tasks.
Now for question 2:
I think your question is basically asking if Method A in my example needs to be marked "async" because it makes a call to a method marked "async", and no it does not. Also please note that ABC() just needs to have
DoWork()
Not
Task.Run(() => DoWork());
ABC will then stop running until the DoWork method arrives at an 'await' statement.
If DoWork just needs to be run as its own task, and you don't want ABC() to stop at all, then just do
Task.Run(() => DoWork());
There is no benefit marking DoWork as async in this case, because there is no point having any await statements in DoWork.
I hope this helps, sorry if I've misinterpreted your questions!

A: From what you said in your comment (I'll assume you need the result in ABC)
You just need to write
Task<SaveCaseSearchOutput> t = Task.Run(() =>DEF(SaveCaseSearchInput,AcctLst.ElementAt(0).o_case_seq));
in ABC, instead of the current Task.Run call.
Then at the line in ABC when you require the result write
t.Wait();
SaveCaseSearchOutput g = t.Result;
DEF must remain async but you can remove the await statement in DEF.


text:
Q: Listing a company as the copyright holder of an R package What's the best way to give copyright to a company for an R package? Hadley points to some options, but I'm still uncertain of the best practice. In the DESCRIPTION, I would prefer to write something like
Authors@R: c(
    person(given = c("First", "Middle"), family = "Family", email = "me@company.com", role = c("aut, cre")),
    person(given = "Company", role = "cph"))

but this is awkward because corporations are not people. Another option:
Authors@R: person(given = c("First", "Middle"), family = "Family", email = "me@company.com", role = c("aut, cre"))
License: GPL (>=3) + file LICENSE

where LICENSE contains
Copyright <My Company>. All rights reserved.

But can I really do that with GPL?

A: Briefly:

*

*Copyright and License are two different and separate concepts. The DESCRIPTION file allows for both, and the official manual has things to say about both.

*Many existing CRAN packages deal with that.  For the use of assigned copyright, packages by RStudio employees can sometimes serve as examples.  See for example this line from dplyr.

*Legal stuff is hard. And boring. Don't take StackOverflow answers as binding either.


text:
Q: Registering 2 handlers to same route but different query params I am trying to add 2 handlers to my REST API on the same route but with different query params. I want the /getStudents route to return all students while the /getStudents?studentName=SomeName should only return the details for the given student. But when I run this, only the second function is run even if I go on the /getStudents route. I have the following code:
@Produces(MediaType.APPLICATION_JSON)
public class StudentService {

    private StudentDAO studentDAO;

    @GET
    @Path("getStudents")
    public List<Student> getStudents() {
        return studentDAO.getStudents();
    }

    @GET
    @Path("getStudents")
    public Student getStudentById(@QueryParam("studentName") String studentName) {
        return studentDAO.getStudentsById(studentName);
    }

    public void setStudentDAO(StudentDAO studentDAO) {
        this.studentDAO = studentDAO;
    }

    public StudentDAO getStudentDAO() {
        return studentDAO;
    }

}

I'm new to Java and J2EE.

A: You can change getStudentById as follows:
@GET
@Path("getStudents/{studentName}")
public Student getStudentById(@PathParam("studentName") String studentName) {
    return studentDAO.getStudentsById(studentName);
}

which will allow JAX-RS to disambiguate the method calls.
This means the client will need to GET
http://somehost/somecontext/getStudents/Fred%20%Bloggs

instead of
http://somehost/somecontext/getStudents?studentName=Fred%20%Bloggs

A: I agree with Steve, you should uniquely identify your resources, but if you really want it you can inject @Context under same path and return all or just one student based on query param:
@GET
@Path("getStudents")
public Response getStudents(@Context HttpServletRequest request){

           if (request.getParameterMap().isEmpty()) {
               // return all students in Reponse
           } else {
               String queryParam = request.getQueryString();
               // check queryParam and return on student in Response
           }

    }


text:
Q: How to find a topology for $\mathbb{R}$ and a sequence that only converges to $x_1,\ x_2$? I'm asked to find  a topology for $\mathbb{R}$ and a sequence that only converges to 1 and 2. Regardless of the solution, is there a way to think of it in a general way? This is, how can find a topology for $\mathbb{R}$ and a sequence that only converges to $x_1,\ x_2 \in \mathbb{R}$?
Thank you

A: Consider the topology $\tau=\{A\subset\Bbb R\mid 1,2\in A\text{ or }A\cap\{1,2\}=\emptyset\}$. Then the sequence $1,1,1,1,\ldots$ converges to $1$ and $2$ and only to those two numbers. Can you check it?


text:
Q: Exchange data between Angular component and js script I hope my question as not asking before.
I'm working with Angular9 and a JS plugin (A-Frame).
I prepared a script is get data and I want to return this data in my component angular for managing his after.
AFRAME.registerComponent('cursor-listener', {
  init: function () {
      this.el.addEventListener('click', function (evt) {
          console.log('I was clicked at: ', evt.detail.intersection.object);
      });
  }
});

In the script you see above, the console log returns information that is useful to me. I would like to be able to return them in my angular component to process the information later.
I'm beginner with this framework, so excuse me for my ignorance.
Thank you for your futur response, I waiting to read you.

A: You could use arrow function notation to refer to the class member variables using this keyword. In a conventional JS function, this keyword refers to the scope of the function.
intersectionObj: any;

AFRAME.registerComponent('cursor-listener', {
  init: () => {         // <-- arrow function here
    this.el.addEventListener('click', (evt) => {       // <-- and here
      console.log('I was clicked at: ', evt.detail.intersection.object);
      this.intersectionObj = evt.detail.intersection.object;
    });
  }
});


text:
Q: Store multiple results from one field in new columns in SQL Current query returns 3 lines for one invoice if there are 3 denial codes and more if there are multiple denial codes and multiple denial dates. I am trying to create a column for each denial code so all results can be on one line. The requirements from the client is for each denial to be in its own column so I am unable to use the listagg function.
The results should looks like the below:
office, invoice, denial date, denial code 1, denial code 2, denial code 3, denial date2, denial code 1...etc
Oracle database. Current code:
                 SELECT
                 A.OFFICE_NBR,
                 A.INV_NBR,
                 TO_DATE(A.CRTD_DT,'MM/DD/YYYY') AS CARC_DT,
                 A.CLM_ID,
                 A.CLM_LN_ID,
                 A.RSN_CD

                 FROM DENIALS A
                 WHERE A.OFFICE_NBR = '1234'
                 AND A.INV_NBR = '123456'

A: I took a guess at some test data but this should get you going.  Please add some before and after data, that helps a lot to understand what you are trying to do, and allows for building a more realistic solution.
Anyway the caveat is you have to define ahead of time a DENIAL_CD_X column for each possible denial code. I will be interested to see if someone can come up with a dynamic solution for the denial_cd columns.
SQL> with DENIALS(OFFICE_NBR, INV_NBR, CRTD_DT, RSN_CD) as (
  2  select '11', '1111', '07/31/2015', '1' from dual
  3  union
  4  select '11', '1111', '07/31/2015', '99' from dual
  5  union
  6  select '11', '1111', '07/31/2015', '50' from dual
  7  union
  8  select '11', '1113', '06/01/2014', '34' from dual
  9  union
 10  select '11', '1113', '06/01/2014', '71' from dual
 11  union
 12  select '32', '3232', '06/21/2015', '34' from dual
 13  union
 14  select '32', '3232', '07/31/2015', '99' from dual
 15  )
 16  select OFFICE_NBR, INV_NBR, TO_DATE(CRTD_DT,'MM/DD/YYYY') AS CARC_DT,
 17         DENIAL_CD_1, DENIAL_CD_2, DENIAL_CD_3
 18  from
 19  (
 20    select OFFICE_NBR, INV_NBR, CRTD_DT, rsn_cd,
 21      row_number() over(partition by OFFICE_NBR, INV_NBR, CRTD_DT order by OFFICE_NBR, INV_NBR, CRTD_DT, rsn_cd) rn
 22    from DENIALS
 23  )
 24  pivot
 25  (
 26    max(rsn_cd)
 27    for rn in ('1' as DENIAL_CD_1, '2' as DENIAL_CD_2, '3' as DENIAL_CD_3)
 28  )
 29  order by OFFICE_NBR, INV_NBR, CRTD_DT;

OFFICE_NBR INV_NBR CARC_DT    DENIAL_CD_1 DENIAL_CD_2 DENIAL_CD_3
---------- ------- ---------- ----------- ----------- -----------
11         1111    31-JUL-15  1           50          99
11         1113    01-JUN-14  34          71
32         3232    21-JUN-15  34
32         3232    31-JUL-15  99

SQL>


text:
Q: DynamoDB get the lasted row by date I have a table that has an article a day and it looks like this.

I set date as a primary key and post_id as sort key. I want to make a query that gets the one latest row by date. Is it possible to do it with Query? or I have to use Scan and filter that out?

A: Firstly, DynamoDB doesn't have aggregate functions such as min and max like RDBMS aggregate function. However, it does have one feature to get the latest date from table. In order to use that option, the attribute should be defined as SORT key. Also, the latest date can be found for the specific partition key only i.e. it does not apply for the whole table, just the chosen partition key.
ScanIndexForward can be used to get the latest item for the specific partition key.

ScanIndexForward — (Boolean) Specifies the order for index traversal:
If true (default), the traversal is performed in ascending order; if
false, the traversal is performed in descending order.

In order to use the above option, the table design has to be changed.

post_id - partition key
date - sort key


text:
Q: Unable to connect to university wifi on Ubuntu 18.04 LTS I've been trying for the past few days to connect to my university wifi and can't do it no matter what I try. I have tried these:
Ubuntu 16.04 problems connecting to eduroam
How to connect to WPA2/PEAP/MSCHAPv2 enterprise wifi networks that don't use a CA_Certificate, like Eduroam
Cannot connect to WPA2/WPA Enterprise (PEAP and MSCHAP)
HOWTO: Wireless Security - WPA1, WPA2, LEAP, etc.
and a couple of others that got lost in my browsing history. I can connect normally on windows and on my smartphone. I also can connect to my home network perfectly (on Ubuntu). I've got no clue on what exactly the problem is and being a linux novice certainly doesn't help. What I know for sure (because I can see on the Android configuration) is that the network uses PEAP and I don't need a CA certificate or Anonymous identity.
Edit: Let me clarify. I enter my credentials or edit the network configuration. The network appears as remembered. If I double click it will start connecting and after some time it will ask for my username and password again, like the first time. No error message or anything.

A: A workaround using your smartphone
While it may not be working for all smartphones, here is a workaround that works for my LG G5.

*

*Connect your smartphone with the university WiFi

*Share your smartphone's internet (Setting>Network>Tethering)

*Choose either USB tethering or Bluetooth tethering.

*Do not choose Wi-Fi hotspot as your smartphone cannot connect to a WIFI network and act as hotspot at the same time.

A: This was a bug in Ubuntu 18.04 as is explained in this thread - https://bugs.launchpad.net/ubuntu/+source/network-manager/+bug/1748839
It has been fixed in the upstream of Ubuntu 18.04. So if you have been keeping your Ubuntu updated, the fix must be present in your system.
Just go to Wifi settings and click on Forget Connection for the network in consideration. Start afresh and you should be all good.


text:
Q: What does 'SEL' mean and how can it be fixed? I have a situation with my php code. In a previous page the user enters in their username. Now when they submit the form, the username is posted and echo on the current page.
E.G if the teacher entered in 'j.lu' as the username, it posts 'j.lu' on the current page.
But what I want to do is that I want the insert the teacher's Id in the database. To do this I set up a query to select the teacher's Id by finding it's username. So 'j.lu' has a TeacherId 'T1' but it does not display this is the field when inserted. Instead it states 'SEL' in the field.
So my question is that what does 'SEL' mean and how can I fix it so instead of saying 'SEL' it will state the teacher's id which in this example is 'T1'.
Below is code of the query, insert and the echo:
$teacherid = "SELECT TeacherId FROM Teacher WHERE (TeacherUsername = '".mysql_real_escape_string($_SESSION['teacherusername'])."')";

echo $_SESSION['teacherusername'];

$sql="INSERT INTO Session (TeacherId)
VALUES
(' ". mysql_real_escape_string( $teacherid ) . "')";

mysql_query($sql);

A: SEL are the first three chars of the word SELECT as the query you run is
INSERT INTO Session (TeacherId) VALUES ('SELECT TeacherId FROM Teacher WHERE ...

You need to change the $teacherid content:
$teacherid =mysql_real_escape_string($_SESSION['teacherusername']);

// the escape is already done
$sql = "INSERT INTO Session (TeacherId) VALUES ('$teacherid')";

mysql_query($sql);

As far you have a table called Session ...
edit
Instead of using the username as is, the you have to execute the first query:
$sql = "SELECT TeacherId FROM Teacher WHERE (TeacherUsername = '"
     . mysql_real_escape_string($_SESSION['teacherusername'])."')";
$rs = mysql_query($sql);
$record = mysql_fetch_array($rs);
$teacherid = $record['TeacherId'];

$sql = "INSERT INTO Session (TeacherId) VALUES ('$teacherid')";
mysql_query($sql);

A: You're setting $teacherid to the string "SELECT TeacherId FROM Teacher WHERE (TeacherUsername = 'mysql_real_escape_string($_SESSION['teacherusername'])')" and not the result of the query.


text:
Q: Adding redirect to Ruby on Rails webpage using .htaccess or Virtualmin Thanks in advance for any help you can provide on this issue! I manage a Ruby on Rails website that uses Apache and lives on Joyent's Cloud Server. Right now I have a pdf located at http://example.com/docs/mydoc.pdf . I'd like for this url to 301 redirect visitors to http://example.com/mydoc , which will be a webpage with the same content (instead of a pdf.)
I've tried a couple of methods for getting the redirect to take place, but neither are working.

*

*I went into VirtualMin and into the Apache server. Then, I chose Aliases / Redirects. Finally, I went under Permanent URL redirects and entered: FROM http://example.com/docs/mydoc.pdf TO http://example.com/mydoc and applied the changes.

*Since that didn't work, I went looking for an .htaccess file in my /public folder. None existed. So, I created an .htaccess file and added it to the /public folder. The only code in the file is

Redirect 301 /docs/mydoc.pdf http://example.com/mydoc
The problem? When I go to http://example.com/docs/mydoc.pdf, the redirect doesn't work.
I'm looking for the simplest way to add this 301 redirect and future 301 redirects to my website. Thanks again for your advice!

A: Rails 3 introduced an easy way to perform 301 redirects from config/routes.rb
match "/oldpath", :to => redirect "/newpath"

This site has a somewhat cumbersome solution for 301 redirects in Rails 2.
However, if I were you I would put all my redirects in an apache config file. This maintains a helpful degree of modularity: you don't have to mix your routes with your redirects, you don't have to mix artifacts of your old website into your new app.


text:
Q: Iterate through PHP Object to mutate properties if they match a condition I have an array of objects [Article(), Article(), Article()]
Each Article() have plenty of protected properties.
I want to be able to identify which property is an instance of PersistentCollection in order to call ->initialize() method on it.

At the end, I want my new array of 3 objects Array() on which I called the initialize() method only if the property is an instance of PersistentCollection
Do you know an efficient way of doing it dynamically ?
Or is it too expansive in terms of performance and then I should call the methods on the fields I know it is a PersistentCollection ?
Thanks.

A: Assuming $articles is your initial array you want to process, something like this should do the trick
$closure = function() {
  foreach($this as $fieldValue) {
      if($fieldValue instanceof PersistentCollection) {
          $fieldValue->initialize();
      }
  }
};

foreach ($articles as $article) {
    $initCollections = Closure::bind($closure, $article, get_class($a));
    $initCollections();
}

$initCollections = Closure::bind($closure, $a, get_class($a));
$initCollections();

Not sure about perfomance, but don't see any issue with it


text:
Q: Pears in Doctor Who When and where did the idea come from that the Doctor hates pears?
As seen in this answer, in series 3 the Tenth Doctor (or possibly David Tennant - he was 'out of character' immediately after this bit, and I can't remember if this part actually appeared in the episode or was fast-forwarded over) said the following instruction was 'very important', even among other instructions which, if violated, might lead to people's deaths or the end of the universe:

Don't let me eat pears. I hate pears. John Smith is a character I made up, but I won't know that. I'll think I am him, and he might do something stupid like eat a pear. In three months, I don't want to wake up and be human and taste that.

Then a few years later in series 9, the Twelfth Doctor's final piece of advice to Clara was:

Never eat pears. They're too squishy and they always make your chin wet. That one's quite important. Write it down.

Does this anti-pear meme have a longer history? Have there been other references in the show to the Doctor's aversion to pears?
I dread to say it, but any level of canon is acceptable.

A: The anti-pear comment in the television episode Human Nature comes from Paul Cornell's novel of the same name.
The novel features the Seventh Doctor, and formed the basis for the television episode. The Doctor turns himself into a human, and leaves his companion (Bernice Summerfield) a list of instructions:

Things Not To Let Me Do
1: Commit suicide, if for some reason I want to.
2: Do physical harm to anyone, if you're aware of it.
3: Eat meat, if you can.
4: Eat pears. I hate pears, I don't want to wake up and taste that.
5: Leave the area, or you, behind.
6: Get involved in big sociopolitical events.
7: Hurt animals, especially owls.
8: Develop an addiction.
9: Anything impossible.
— Human Nature, chapter 3 (Boudiccan Destruction Layer)

That's where this particular line comes from. I don't think pears have a greater significance in the Doctor Who universe. The TARDIS Wikia entry only lists one other mention of pears, in another of the New Adventures novels.

A: The 12th Doctor at the end of Twice Upon a Time, also told the 13th Doctor, "Never eat pears." Right after he said that they can never share their name. That people wouldn't understand it. Except for children. Some children can hear it.


text:
Q: PepperMount Write operation fails Am trying to store files in NACL using PepperMount library. But I've some problem in writing files to the persistent storage.
struct stat st;
char data1[1000];
for (int i = 0; i < 1000; i++)
    data1[i] = 'a';

if(0 == ppMount->Creat("ccda.txt", 0, &st)) {
    fprintf(stderr, "File opened");
    ppMount->Ref(st.st_ino);

    ssize_t n = ppMount->Write(st.st_ino, 0, data1, 1000);
    fprintf(stderr, "Wrote %d bytes", n);

    ppMount->Unref(st.st_ino);
} else {
    fprintf(stderr, "File open failed");
}

I tried it in Pepper_20 and Pepper_21, in 20 it failes in open file, and in 21 it fails in write operation.
Let me know if this is a known bug or am doing something wrong with my code.

A: The problem was actually not with the code. Seems like I've to request storage quota from html as well.
window.webkitStorageInfo.requestQuota(PERSISTENT, 20*1024*1024);


text:
Q: Why does a user get updated using Spring Security and Grails without calling save()? Overview:

*

*User, UserRole and Role are pretty much the standard model from
SpringSecurity plugin in grails

*One thing that I ensure (in the controller) is that there is only 1 role per user

*There are 3 roles created in my bootstrap: Admin, Manager and User

*

*Admins can do all actions

*Manager can update other managers and users

*Users can only update themselves (but not their roles)

In my controller I use annotations to generally control most of the security but for the update and save actions I add the logic for more advance checking:
@Transactional
def update(User userInstance) {
    User currentUser = User.get(springSecurityService.currentUser?.id)
    Role currentRole = currentUser.getAuthorities().getAt(0)    // There is only 1 role per user, so give the first

    Role roleInstance = Role.get(params['role.id'])

    // SECURITY LOGIC -> Move to service
    if (currentRole.authority.equals("ROLE_USER")) {

        if (userInstance != currentUser || !roleInstance.authority.equals("ROLE_USER")) {
            notAllowed(userInstance)
            return
        }
    } else if (currentRole.authority.equals('ROLE_MANAGER')) {
        ...
    }
    ...
    // REST OF CODE - User is saved here
}

Now here is where I get a weird problem. If I log in as a ROLE_USER and update an ROLE_ADMIN I get the notAllowed error message as I should and the action returns right after so it doesn't continue to the REST OF CODE where the User is actually saved.
If I look at the admin it actually has been updated (persisted). Why is this the case since it never got to the save() call?
Thanks!

A: This has nothing to do with Spring Security - it's just a coincidence that it's happening when working with domain classes that are used by the plugin.
By default Grails uses the "open session in view" pattern, which is common when using Hibernate. At the beginning of each request a Hibernate Session is created and stored in a ThreadLocal and the persistence code uses that if it's available, and at the end of the request the session is flushed and closed.
This is particularly helpful when working with lazy-loaded instances and collections. If there isn't an existing Hibernate Session available, the persistence code creates one and uses it to retrieve instances from the database, but since it created the session, it closes it after the query finishes. This leaves the instances disconnected from any session and there's no auto-reattach logic, so if you attempt to access a non-initialized lazy-loaded instance or collection after the object is disconnected you get an exception. But if there was an open session already, the persistence code uses it but doesn't close it, so loaded instances are attached and lazy loading will work.
What you're seeing is Hibernate detecting that a persistent instance has been modified, and by default when the session is closed it will detect the changes and helpfully flush them to the database for you. This happens with or without a save() call, so in effect the only time you typically need to call save() is when inserting new instances.
You can disable the open session in view support, but you lose a lot by doing this and it's in general not a good idea. You can also customize how it works, when flushing happens, etc. But in general you should disconnect attached instances that you don't want to be auto-flushed. There's a GORM method for that - discard() - and if you call it on a modified instance Hibernate won't be aware of it when the flush happens and nothing will be saved.
Unrelated - this line
User currentUser = User.get(springSecurityService.currentUser?.id)

should just be
User currentUser = springSecurityService.currentUser

since the getCurrentUser() method retrieves the User instance from the database using the cached id from the security authentication. You're using that User instance to get its id and then throwing it away, and using the id to load the same User again.


text:
Q: Is there an option to replace output of PsExec error code with another output? I'm running a code that waits for WinSCP Process to run and then waits for it to close automatically.
Now I'm trying to replace the regular output of psexec:
cmd exited on <Host> with error code 0

With the output,
WinSCP has been downloaded the files successfully.

Some code that I'm using Psexec with:
psexec \\<Host> -u <User> -p <Password> powershell Wait-Process WinSCP

I've tried to throw any of the output commands using the
| Out-Null and still it doesn't work

A: You would need to capture the response and check the error codes of the it.
$response = & psexec \\<Host> -u <User> -p <Password> powershell Wait-Process WinSCP

switch -regex ($response) {
    'error code 0' { $output = "WinSCP has been downloaded the files successfully." }
    'error code 1' { $output = "Something else"
    # Add other error codes from your application
    default { $output = "Unknown error" }
}

return $output


text:
Q: Visually testing unusual code paths in ASP.NET WebForms Website I have a large complex ASP.net WebForm website that I'm working on a visual redesign and am trying to think of good ways to exercise all the code paths in the website so I can see how things look with the redesign.
For example lets say I have a message that only gets displayed if there is an error which rarely happens. Here is an example of what my code might look like:
if (someErrorCondition) {
    someControl.Visible = true;
} else {
    someOtherControl.Visible = true;
}

This might not be a good way of doing things, but this is a good example of my existing code base I have to work with.
Let us assume for the sake of simplicity that I already have a way of testing one part of the if. The problem is exercising the other part without going through a lot of trouble to setup my environment to create an error.
One idea I had was to extract someErrorCondition into a method and in that method check for some session or request key to see if I want to fake a failure. Maybe wrap it in an #if DEBUG block so that it won't be compiled for production.
Any other ideas for how I might go about testing unusual code blocks on an ASP.net website so I can make sure nothing got left out in the redesign?

A: I believe the best solution is always the most simple. Since you obviously have access to the code, do a search for the Visible property for each form element within Visual Studio and set each one to true to see how it looks. Once you make the design change then un-comment the original code.
Example:
if (someErrorCondition) {
    someControl.Visible = true;
} else {
    someOtherControl.Visible = true;
}

TO
/* if (someErrorCondition) {
    someControl.Visible = true;
} else {
    someOtherControl.Visible = true;
}*/ someControl.Visible = true;

This is not good for testing proper behavior of the form, but will let you see how each element looks for visual design purposes.


text:
Q: Beating binary search using CPU cache line For educational purposes, I am trying to beat binary search using CPU cache line.
https://github.com/nmmmnu/beating_binsearch/blob/master/improved.h
If you uncomment #define EXIT_ONLY, the search works like normal binary search, except if there are few elements, the search became linear search.
As expected this performs faster than binary search.
However I want to improve future, so if you comment #define EXIT_ONLY, then "small" linear search is made instead of accessing just the "middle" element.
In theory the values for linear search must be in CPU cache line and access must be "free of charge".
However in practice this search is way too slow than the normal binary search.
If I hardcode CACHE_COUNT_2 to be equal to 1, then speed is comparable, but still slower.
Note I never tried to unroll the for cycle in _linear().
What could be explanation of the slower execution?
Repo with all files is here:
https://github.com/nmmmnu/beating_binsearch

A: There are some problems in your code.  For example, this code does not consider cache line boundaries.
while (end - start > CACHE_COUNT_MIN){
//  uint64_t mid = start + ((end - start) /  2);
uint64_t mid = start + ((end - start) >> 1);

etc...
char cmp = _linear(mid - CACHE_COUNT_2, mid + CACHE_COUNT_2, data, key, mid);

Cache lines are allocated on addresses modulo the line size.  So, to scan an entire cache line you would want to mask out the relevant bits of the address.  Even if it is a cache hit though, you will still spend cycles accessing the line (more the higher it is in the hierarchy).
Binary search is already one of the more cache efficient algorithms for comparison based search though so improving it through cache awareness may be difficult.  You eliminate half the search space at each iteration, which already avoids most cache misses, and it's a linear space, and you increase locality with each search.  Prediction can even hide some of the misses.
You may want to use perf to sample performance events in your code.  Also, to get an idea of how cache awareness is sometimes used to optimize algorithms, you might also want to take a look at some of the existing aware ones like hopscotch hashing.

A: I did unrolled version of the search,
https://github.com/nmmmnu/beating_binsearch/blob/master/improved_unroll.h
here is code in question:
char search(uint64_t const start1, uint64_t const end1, const T *data, const T key, uint64_t &index) const{
    /*
     * Lazy based from Linux kernel...
     * http://lxr.free-electrons.com/source/lib/bsearch.c
     */

    uint64_t start = start1;
    uint64_t end   = end1;

    char cmp = 0;

    //while (start < end){
    while (start < end){
    //  uint64_t mid = start + ((end - start) /  2);
        uint64_t mid = start + ((end - start) >> 1);

        //char cmp = _linear(mid - CACHE_COUNT_2, mid + CACHE_COUNT_2, data, key, mid);

        #define _LINE_HALF_SIZE 7
        #define _LINE(i)                        \
        if (i >= end){                          \
            start = mid + _LINE_HALF_SIZE + 1;  \
            continue;                           \
        }                                       \
                                                \
        cmp = comp.cmp(data[i], key);           \
                                                \
        if (cmp == 0){                          \
            index = i;                          \
            return 0;                           \
        }                                       \
                                                \
        if (cmp > 0){                           \
            end = i + 1;                        \
            continue;                           \
        }

        _LINE(mid - 7);
        _LINE(mid - 6);
        _LINE(mid - 5);
        _LINE(mid - 4);
        _LINE(mid - 3);
        _LINE(mid - 2);
        _LINE(mid - 1);
        _LINE(mid    );
        _LINE(mid + 1);
        _LINE(mid + 2);
        _LINE(mid + 3);
        _LINE(mid + 4);
        _LINE(mid + 5);
        _LINE(mid + 6);
        _LINE(mid + 7);

        #undef _LINE

        start = mid + _LINE_HALF_SIZE + 1;
    }

    index = start;
    return cmp;
}

Seems there are too many branch miss-predictions, because if I remove following if statement:
        if (i >= end){                          \
            start = mid + _LINE_HALF_SIZE + 1;  \
            continue;                           \
        }                                       \

speed "magically" became same or even better than classical binary search - of course, because I eliminated the branch the algorithm did not really worked correctly, but this is clear indication why the algorithm is slower than classical binary search.


text:
Q: Can we create a HQL query with same name but different Parameters? Can we create a HQL query with same name but different Parameters,
and call it using findByNamedQueryAndNamedParam() method.
But the hibernate implementation of this metod is as follows.
public List findByNamedQueryAndNamedParam(
        final String queryName, final String[] paramNames, final Object[] values)
        throws DataAccessException {

    if (paramNames != null && values != null && paramNames.length != values.length) {
        throw new IllegalArgumentException("Length of paramNames array must match length of values array");
    }
    return executeWithNativeSession(new HibernateCallback<List>() {
        public List doInHibernate(Session session) throws HibernateException {
            Query queryObject = session.getNamedQuery(queryName);
            prepareQuery(queryObject);
            if (values != null) {
                for (int i = 0; i < values.length; i++) {
                    applyNamedParameterToQuery(queryObject, paramNames[i], values[i]);
                }
            }
            return queryObject.list();
        }
    });
}

So is it possible to create a HQL Query with same name but different parameters and call the query on the basis of Parameters dynamically?

A: As far as I know you cannot have multiple named queries with same name. You can write a dynamic query for this. Check this answer to see how to do this in HQL. Its showing how the Criteria API makes it simpler and is sounding better for your scenario.
Also this answer shows a unconventional way of doing something similar to your query.


text:
Q: In CPLEX OPL I want to create a condition using a variable forall(b in PitBlocks,d in DumpBlocks,t in TimePeriods)
      {
    //NonNegative waste:
if ((Xbdt[b][d][t]) != 0) { (Xbdt[b][d][t]) >= 10};
      }

Here Xbdt is a positive continuous variable. And I do not want its value to be between 0 and 10, otherwise it creates very small decimal numbers.
A variable is not allowed inside the if condition. Any suggestions on how could I achieve this differently ?

A: What you are looking for is called 'semi-continuous' variables. Erwin Kalvelagen has a nice succinct summary here:
http://yetanothermathprogrammingconsultant.blogspot.com/2016/08/semi-continuous-variables.html
I don't know if OPL has direct support for semi-continuous variables yet. This post from a while ago suggests ways to implement this:
https://www.ibm.com/support/pages/modeling-semi-continuous-variables-opl

A: forall(b in PitBlocks,d in DumpBlocks,t in TimePeriods)
      {
    //NonNegative waste:
 (Xbdt[b][d][t] == 0) || (Xbdt[b][d][t] >= 10);
      }

will work.
Full example in https://github.com/AlexFleischerParis/zooopl/blob/master/zoosemiinteger.mod
int nbKids=300;
float costBus40=500;
float costBus30=400;

dvar int+ nbBus40;
dvar int+ nbBus30;

minimize
 costBus40*nbBus40  +nbBus30*costBus30;

subject to
{
 (nbBus40==0) || (4<=nbBus40<=20);
 (nbBus30==0) || (4<=nbBus30<=20);

 40*nbBus40+nbBus30*30>=nbKids;
}

A: Thank you Alex
the solution you suggested worked perfectly :
forall(b in PitBlocks,d in DumpBlocks,t in TimePeriods)
      {
    //NonNegative waste:
 (Xbdt[b][d][t] == 0) || (Xbdt[b][d][t] >= 10);
      }


text:
Q: MultipeerConnectivity issue with Podspec I've been trying to add a library with MultiPeerConnectivity framework but when I check podspec is ok I get the following issue:
'MultipeerConnectivity/MultipeerConnectivity.h' file not found
And the podspec
Pod::Spec.new do |s|
  s.name         = 'MagicMP'
  s.license      = 'MIT'
  s.platform = :ios, '7.0'
  s.version      = '1.0.3'                                                                  # 1
  s.summary      = 'MultiPeer framework done better' # 2
  s.author       = { 'Pedro Piñera' => 'pepibumur@gmail.com' }                            # 3
  s.homepage     = "https://github.com/pepibumur/PPiShowtime-Google-iOS-Library"
  s.source       = { :git => 'https://github.com/pepibumur/MagicMP.git' , :tag => '1.0.3'}      # 4
  s.ios.deployment_target = '7.0'
  s.source_files = 'MagicMP/*'
  s.requires_arc = true
  s.frameworks = 'MultipeerConnectivity'
end


text:
Q: Remove gradient on UINavigationController Is there a way to remove the gradient on the navigationBar on UINavigationController in iOS6.
I have tried making a subclass of UINavigationController then set the navigationBar of it to the subclass though it says that the navigationBar is a readOnly variable

A: In storyboard I did remove gradient by unchecking Translucent property of UINavigationBar inside UINavigationController.

A: how about -[setBackgroundImage: forBarMetrics] , you can use a single pixel image with the color of your choice.
but, to set the class of the navBar of your UINavController use -[ initWithNavigationBarClass:toolbarClass:] ,
or, just set it on the navigationBar object on the storyboard or nib if your using one.


text:
Q: How to make a file hidden in python I want to make my txt file hidden cross platform,but everything I found didn't work for me. Can someone help me in my situation please.
file = open("helloworld.txt","a")
file.write("HELLO WORLD")
file.close()
return

so thats a simple version of my code,how do I make helloworld.txt hidden,with something like a file format.


text:
Q: Setters and Getters python I've looked around but everything I tried didn't seem to get any result. I just need to set a custom setter and getter for a class that converts a number to string and viceversa. Since python doesn't support which I'm using a dictionary.
class Ship(object):
    def __init__(self, type):
        self.fixed = define_direction()

        self.row = random_row(board, self)
        self.col = random_col(board, self)
        self.type = self.set_type(type)
        print "Type:", str(self.type)

    def set_type(self, type):
        return {
            0 : "Patrol boat",#2
            1 : "Destroyer",#3
            2 : "Submarine",#3
            3 : "Battleship",#4
            4 : "Aircraft carrier",#5
            }.get(type, "Patrol boat")
    def get_type(self):
        return {
            "Patrol boat" : 0,#2
            "Destroyer" : 1,#3
            "Submarine" : 2,#3
            "Battleship" : 3,#4
            "Aircraft carrier" : 4,#5
              }.get(self.type, 0)
    def __repr__(self):
        return "Ship. Type: ", self.get_type()

Not really sure that self.type = self.set_type(type) is legit, but it seems the only way to call a function from inside the class.
In __init__(self, type) -> "type" gets passed as a number and it should get converted and stored as a string, than should get reconverted to a number while the getter is called. (maybe there's a better way to do it - using external dictionary to do the conversion and just store the number..?

*

*PS1: Is it legit to call an external function random_row(board, self) and random_col passing self even if it's not properly initialized or should I move the function inside the class as another setter?

*PS2: calling __repl__:
def __repr__(self):
  return "Ship. Type: ", str(self.get_type()), str(self.type())

returns:
Traceback (most recent call last):
  File "/Users/xx/Documents/python/battleship/battleship.py", line 85, in <module>
    print ship.__repr__()
  File "/Users/xx/Documents/python/battleship/battleship.py", line 74, in __repr__
    return "Ship. Type: ", str(self.get_type()), str(self.type())
TypeError: 'str' object is not callable

Calling it only on get_type()
def __repr__(self):
    return "Ship. Type: ", str(self.get_type())

returns:
Type: Submarine
('Ship. Type: ', '2')

Hope it's clear enough.

A: You can use a @property decorator to manager your type attribute:
class Ship(object):
    def __init__(self, type):
        self.fixed = define_direction()

        self.row = random_row(board, self)
        self.col = random_col(board, self)
        self.type = type
        print "Type:", str(self.type)

    @property
    def type(self):
        return {
            "Patrol boat": 0,
            "Destroyer": 1,
            "Submarine": 2,
            "Battleship": 3,
            "Aircraft carrier": 4,
        }.get(self._type, 0)

    @type.setter
    def type(self, type):
        self._type = {
            0: "Patrol boat",
            1: "Destroyer",
            2: "Submarine",
            3: "Battleship",
            4: "Aircraft carrier",
        }.get(type, "Patrol boat")

    def __repr__(self):
        return "Ship. Type: " + self._type

Your __repr__ should always return a string; you were returning a tuple instead. Your error was caused by your self.type() call; since self.type stores a string in your code, you were trying to treat that string as a callable.
It is fine to call other functions (outside of the class) from __init__; it is just another method on your instance really, just take into account what attributes have and haven't been set yet. However, if the function relies on information on self and has no uses outside the class, I'd move it into the class with a _ prefix to indicate that it is internal to the class implementation.


text:
Q: Smallest sigma-algebra on which difference of measurable functions is measurable? Let's assume that $f,g$ are $\mathcal{A},\mathcal{B}(\mathbb{R}^n)$ measurable. Then we know by the usual theorem that $f-g$ is also $\mathcal{A},\mathcal{B}(\mathbb{R}^n)$ measurable. But what's the smallest sigma-algebra $\mathcal{A}$ on which the $f-g$ is measurable?
Motivation: This question comes from reading on book an example of a random variable $Y_n:=X_{2n}-X_{2n-1}$. The author states that $Y_n$ is $\sigma(X_{2n},X_{2n-1}),\mathcal{B}(\mathbb{R}^n)$ measurable. And I wondered why...
Also have another question, related to this. Is $(f-g)^{-1}(\mathcal{B}(\mathbb{R}^n)) \subset \sigma\{f^{-1}(\mathcal{B}(\mathbb{R}^n))\cup g^{-1}(\mathcal{B}(\mathbb{R}^n))\}$?

A: Well, it depends. For instance, consider $f,g : (\mathbb{R},\mathcal{B}) \to (\mathbb{R},\mathcal{B})$, $f(x) = x+1$, and $g(x) = x$. $f(x) - g(x)=1$, which is measurable with respect to any $\sigma$-algebra, in particular, you can take $F = \{\emptyset, \mathbb{R}\}$.


text:
Q: remap default keybinding in tkinter I am adding a keybinding to my root window (a Tk() instance, which contains a Text widget) :
root.bind("Control-o", setconnpanelopen)

The problem is that it seems that control-o is bound by default to "insert newline", so that my procedure fires, but it also inserts a newline!
This happens even if I put a return 'break' at its end - so it fires before, so it seems.
1) how can I remap this behaviour?
2) I didnt find anywhere a list of the default keybindings of the text widgets - they are available somewhere?

A: You want to read up on "bindtags" -- tkinter's binding mechanism.
Widgets have a set of bind "tags" (or "bindtags") that are processed in order. For example, a text widget has four tags: the tag for the widget, the tag for the widget class (which is an internal class name, not the python class), a tag for the toplevel window, and a tag for "all".
Most default bindings are on the class bindings. That means that any specific bindings you create on a widget happen before the default bindings. In this particular case, since you are binding to the root window, your binding is happening after.
At any time, you can create a binding that stops the propagation of the event up the bindtag chain. You do this by returning the literal string "break" from your binding. Thus, if your binding was on the text widget itself you could prevent the default behavior by having setconnpanelopen return "break". Since your original binding is on the root window this won't help, since the default binding happens before your binding.
You have a couple of solutions: one, place the binding on the widget rather than on the root window. Or, leave it on the root window so it will fire no matter which widget has focus, and then add a binding to the text widget that does nothing but return "break" to prevent the default binding from occurring.
For a definitive list of the bindings, see http://tcl.tk/man/tcl8.5/TkCmd/text.htm#M162 -- this points to tcl/tk, but that is what powers tkinter and it is the final authority when it comes to tkinter documentation.

A: Create your own widget that inherits from the text widget. You may want to put your callback function as a method of your widget as well.
class MyTextWidget(Text):
    def __init__(self, master, **kw)
        Text.__init__(self, master, **kw)
        self.bind('<Control-O>', setconnpanelopen)

Make sure that your setconnpanelopen function returns 'break'.
You may want to have a look at this: http://effbot.org/tkinterbook/tkinter-events-and-bindings.htm