text:
Q: How to find $\int_0^\infty\frac{x!}{x^x}dx$ I wonder how I could evaluate $$\lim_{a\rightarrow0}\int_a^\infty\frac{x!}{x^x}dx$$Where $x!$ is defined for all complex numbers with a positive real part. This is inspired by a limit I found on BlackPenRedPen. I tried using the Residue theorem using the quarter circle contour on the complex plane with a singularity at the origin, but I don't know how to use it.This is the contour I am using. Consider the outer circle as a contour $\Gamma$. Let the smaller semicircle be $\gamma$. Let the radius of the big semicircle be $R$ and the radius of the smaller semicircle be $r$. Then $$\int_0^\infty f(z)dz=\lim_{(r,R)\rightarrow(0,\infty)}\left(\int_\Gamma+\int_\gamma+\int_r^Rf(z)dz+\int_{ri}^{Ri}f(z)dz\right)=2\pi i\sum_k\text{Res}(f, z_k)$$Where $f(z)=\dfrac{z!}{z^z}$, $0^0=1$, and $z_k$ are the poles of $f(z)$. After that I am stuck as I don't think $f(z)$ has any poles. Any ideas?

A: Not an answer, just two funny observations:
\begin{align}
\int_0^\infty\frac{x!}{x^x}\,dx&=\int_0^\infty\frac{dx}{(1+x\log x)^2};
\\\sum_{n=1}^\infty\frac{n!}{n^n}&=\int_0^1\frac{dx}{(1+x\log x)^2}.
\end{align}
The second one is shown using $(1-z)^{-2}=\sum_{n=1}^\infty nz^{n-1}$ and termwise integration.
For the first one,
\begin{align}
\int_0^\infty\frac{x!}{x^x}\,dx&=\int_0^\infty\int_0^\infty y^x e^{-y}\,dy\,\frac{dx}{x^x}
\\\color{gray}{[\text{exchange}]}\quad&=\int_0^\infty e^{-y}\int_0^\infty(y/x)^x\,dx\,dy
\\\color{gray}{[x=yz]}\quad&=\int_0^\infty ye^{-y}\int_0^\infty z^{-yz}\,dz\,dy
\\\color{gray}{[\text{exchange}]}\quad&=\int_0^\infty\int_0^\infty ye^{-y(1+z\log z)}\,dy\,dz
\\\color{gray}{[\text{do the inner}]}\quad&=\int_0^\infty\frac{dz}{(1+z\log z)^2}.
\end{align}


text:
Q: Angular Slickgrid column filter not working on formatted column data I am using Angular-Slickgrid 4.1.4, Angular 12
In my data source, I have an array collection of objects. I need to display values from that collection object using a formatter property. But column filter is not working on this formatted column.
this.columnDefinitions = [
  // ......
  {
    id: 'id', name: 'Customer First Name', field: 'customers',
    sortable: true, filterable: true, type: FieldType.string,
    formatter: (_row: number, _cell: number, value: any, columnDef: Column<any>, dataContext: any) => {
      return (value != null ) ? value?.firstName: 'NA'},
   },
   // ........
]

Need help on column filtering, searched in google but didn't get right solution

A: Find one solution @ slickgrid doc Using queryField: and formatter: properties in ColumnDef.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Existing package can not be found during configure I try to install icewm form this project. I have two computers, first with Centos 6.5, second with Centos 7. I installed icewm on Centos 6.5. But I can not install icewm on Centos 7.
./configure --disable-xfreetype --enable-corefonts --without-imlib --disable-xinerama

...
checking for XpmReadFileToPixmap in -lXpm... no
configure: error: libXpm can not be found

But package libXpm is installed. Centos 6.5 and Centos 7 have got this package in the same location :
/usr/lib64/libXpm.so.4.11.0
/usr/lib64/libXpm.so.4
/usr/lib64/libXpm.so

Also both centos have got xpm in pkg-config.
pkg-config --list-all | grep xpm
xpm                        Xpm - X Pixmap Library

So why I can not install icewm on Centos 7 ? How to solve it?
EDIT
U use --disable-xinerama because Xinerama also can not be found despite it is installed.
EDIT2
I installed all X library:
yum install xorg-x11*
yum install libX*

A: Try specifying the library to configure:
root> LDFLAGS="-L/usr/lib64" ./configure --disable-xfreetype --enable-corefonts --without-imlib --disable-xinerama

LDFLAGS is basically an Environment Variable.
UPDATE
Try running these before running the above command.
root> export LD_LIBRARY_PATH="/usr/lib64"

root> export PATH=$PATH:/usr/lib64

I am really not sure, why configure cannot take this default location.

A: You need to install the devel package for any library that you are compiling against.
In this instance, you need to install libXpm-devel:
# yum install libXpm-devel

A: I found following log in config.log file:
/bin/ld: cannot find -lsupc++
collect2: error: ld returned 1 exit status

I changed -lsupc++ to -lstdc++ in 9996 line in configure file.
It works now.


text:
Q: How to use a polygon grid to calculate statistics on line and point features What seems a simple task but I can't find the right tool to do it. I have a polygon grid cells and say a point feature class. I want to be able to create a table that contains the grid cell ID and for example the sum of points within that cell or the average of the value for those points. For a line feature I would like to simply have a 0/1 value if the line falls into a grid cell. I am doing this in ArcMap 10. This is like Zonal statistics but on a vector layer instead of a raster.

A: Your "question" probably evaluates to about 3 questions but the answer to each is roughly the same.
I think there are two tools to look at for transferring your polygon identifier to lines and points:

*

*Spatial Join which may also be able to do some/all of the statistics you are after using its merge rules

*Intersect which will need a post processing step using Summary Statistics (for stats) or the Field Calculator (for your 0/1)


text:
Q: Deploying to heroku play framework java I get this error when deploying my play 2.3 java project. This is my first time deploying
 [info] Set current project to scala_buildpack_build_dir (in build file:/tmp/scala_buildpack_build_dir/)
   [success] Total time: 0 s, completed Aug 4, 2014 1:29:13 AM
   [info] Updating {file:/tmp/scala_buildpack_build_dir/}scala_buildpack_build_dir...
   [info] Resolving org.scala-lang#scala-library;2.10.4 ...
   [info] Resolving org.scala-lang#scala-compiler;2.10.4 ...
   [info] Resolving org.scala-lang#scala-reflect;2.10.4 ...
   [info] Resolving org.scala-lang#jline;2.10.4 ...
   [info] Resolving org.fusesource.jansi#jansi;1.4 ...
   [info] Done updating.
   [success] Total time: 0 s, completed Aug 4, 2014 1:29:13 AM
   [error] Not a valid command: stage (similar: last-grep, set, last)
   [error] Not a valid project ID: stage
   [error] Expected ':' (if selecting a configuration)
   [error] Not a valid key: stage (similar: state, target, tags)
   [error] stage
   [error]      ^

!     Failed to build app with sbt


text:
Q: PHP/Zend Framework path issue I've been trying to get to grips with zend framework and a bit of php and am having problems with (I think) some sort of path setting.
Basically I'm having some problems with getting a simple page to work.
I have a standard directory structure from the zend quickstart sample. It has the structure:
app
->public
->library

etc.
When I create the following "hello.php" file in the public directory, I get an error from "require-once"

Warning: require_once(/../application/Zend/Rest/Server.php) [function.require-once]: failed to open stream: No such file or directory in /home/bestpubi/public_html/svc/public/hello.php on line 2
  Fatal error: require_once() [function.require]: Failed opening required '/../application/Zend/Rest/Server.php' (include_path='.:/usr/lib/php:/usr/local/lib/php') in /home/bestpubi/public_html/svc/public/hello.php on line 2

My hello.php file looks like this:
<?php
require_once '../application/Zend/Rest/Server.php';
/**
* Say Hello
*/
function sayHello()
{
return 'finally';
}
$server = new Zend_Rest_Server();
$server->addFunction('sayHello');
$server->handle();
?>

I could really do with some help as this is driving me a bit mad, and I'm sure it's something silly.

A: You are requesting the required library file as follows.
require_once '../application/Zend/Rest/Server.php';

The error message indicates that, there is no such file in the path specified.
Usuallay zend framework contains it 'Zend' library inside /library directory. If you have the Zend directory in your downloaded ZendFramework files, copy it to /library directory. So that the Zend directory structure would be as follows
/library/Zend

This is a simple way to get started. Once you are familiar with the environment, try to use include path in your setting.

A: Try
$new_include_path = "/home/www/app/library/";
set_include_path ( get_include_path() . PATH_SEPARATOR . $new_include_path); )

to define the include path of your ZF library. Put this on the top of your page, before Including any ZF file.
Edit:
I assumed you are on linux, if you are on windows, change path accourdingly
$new_include_path = "c:\\www\\app\\library";

A: Looking at your website it seems the index.php from /public works fine. So I would suggest copy pasting the code that's in there to set paths for zf into hello.php and it should work.

A: First thing is create your files in application folder.
And If You are using Linux follow the steps,
To use Zend library you can create a short cut to zend library from your library.
From terminal go to your 'library' directory run the command
ln -s 'path to your zend library'
It will create a shortcut.


text:
Q: Stop Input From Inheriting Another Input's Value On Button Click I'm creating a post slug input, so when editing post title input it'll inherit it's value to the disabled slug input amd there is a button when clicking it enables the disabled input. It is working good, but I want on clicking the button it'll stop Inheriting values.
Here is my code :
<input type="text" id="a"/>
<input type="text" id="b" disabled/>
<button id="btn">Stop</button>
<script>
    document.querySelector('#a').addEventListener('keyup', () => {
        document.querySelector('#b').value = document.querySelector('#a').value;
    });

    document.querySelector('#btn').addEventListener('click', () => {
        document.querySelector('#b').disabled = false;
    });
</script>

I've googled, but i haven't found.
Thank You

A: You can removeEventListener of the a element keyup after clicking the button.

    function onAKeyup() {
        document.querySelector('#b').value = document.querySelector('#a').value;
    }

    document.querySelector('#a').addEventListener('keyup', onAKeyup);

    document.querySelector('#btn').addEventListener('click', () => {
        document.querySelector('#b').disabled = false;
        document.querySelector('#a').removeEventListener('keyup', onAKeyup)
    });
<input type="text" id="a"/>
<input type="text" id="b" disabled/>
<button id="btn">Stop</button>


text:
Q: Not hitting controller in MVC In my submit of my login form which is in pop-up it is not hitting the controller even though I provided the code in beginform with post method. I need to send the username and password to my controller for verification. Unable to figure out why it is not hitting.
[HttpPost]
    public ActionResult LoginUser(UserInfo objUser)
    {

        int res = udaObj.CheckUser(objUser.UserName, objUser.Password);
        if (res >= 1)
        {
           return RedirectToAction("Appointment", "Home");
        }
        else
        {
            //For testing purpose
            return RedirectToAction("Appointment", "Home");
        }
    }

My view is as follows:
 @using (Html.BeginForm("LoginUser", "Home", FormMethod.Post, new { id = "loginForm" }))
                {

                        <fieldset>

                                Alias:

                                   @* <input required="" id="userid" name="userid" type="text" class="form-control" placeholder="JoeSixpack" class="input-medium" required="">*@
                                     @Html.TextBoxFor(x => x.UserName, new { @class = "form-control input-large", @placeholder = "Joek@irawath.com", @required = "" , @id="userid" })

                                Password:

                                    @*<input required="" id="passwordinput" name="passwordinput" class="form-control" type="password" placeholder="********" class="input-medium">*@
                                     @Html.TextBoxFor(x => x.Password, new { @class = "form-control input-large", @placeholder = "********", @required = "", @type = "password" , @id="passwordinput" })

                                        <input type="checkbox" name="rememberme" id="rememberme-0" value="Remember me" style="margin-left: 0px">
                                        Remember me

                            <button id="btnsignin" type="submit" name="signin" class="btn btn-success">Sign In</button>

                                    @* <button id="btnsignin" type="submit" name="signin" class="btn btn-success">Sign In</button>*@

                        </fieldset>

                }

A: Check if the object UserInfo is the same model you are using in your view. Try using a FormCollection instead and check.


text:
Q: Not able to get backcolor of textbox I am setting color of a textbox at client side using
id.style.backgroundColor = decode[1];

Here decode[1] contains colors depending on a condition.
I am able to set the color here, but i am not able to identify this color at server side.
What property should i use to retrieve this color.
TextBox.BackColor doesnot seem to work.
As of now I am setting text also in same way and i am able to retrieve the text at serverside but not color.
Thanks in Advance!

A: When you retrieve this color at server side do one thing you can set this color value in Hidden field and then can get hidden field value from server side which would be same as background color of text box.
Hope this will help.

A: There isn't such a property or method that reflect changes made on DOM (client side). Try to change BackColor at server side.


text:
Q: Installing CentOS 6.3 wrong hard drives order? I am trying to install CentOS 6.3 on new server that has 2xSSD and 1xHDD drives connected to mainboard's SATA ports by following order:
SSD1 -> SATA1
SSD2 -> SATA2
HDD1 -> SATA3

On the installation process CentOS shows me hard drives by this order:
/sda -> that is actually SSD2
/sdb -> HDD1
/sdc -> SSD1

It looks like CentOS assigns it randomly rather by the SATA connection order.
My question is: What the order of drives /sd* depending on? And how can I change it to be by the order it connected to SATA? Thank you in advance!

A: The reason they're out of order is that your system BIOS is configured to present them out of order. Unfortunately, this is all too common. Fortunately, it really doesn't matter much, since you will only rarely refer to the drives by their actual device names. As long as the (grub) bootloader got installed to the right place, you will be fine.

A: I just removed all drives and add them one by one after installation, strange but it was only the way to install them in proper order I have not found any fast way to fix it...


text:
Q: Drawing wind rose with QGIS from PostGIS? I am working on wind rose data. I have some points on lines (streets) in my Postgres/PostGIS DB. The sample data scenario is:

First, I computed street orientation of this line using PostGIS commands ST_StartPoint(), ST_EndPoint() and ST_Azimuth() like this:
Select
-- line_dir = line direction (orientation) in degrees
(degrees(ST_Azimuth(line_end_pt, line_start_pt)))::int As line_dir,
-- assign the line direction as the lower bound of sector 1 (of 30 degree)
(degrees(ST_Azimuth(line_end_pt, line_start_pt)))::int As   lower_bound_sector1,
-- add 30 degree to lower bound to get the upper bound as each sector is of 30 degree max.
(degrees(ST_Azimuth(line_end_pt, line_start_pt)))::int + 30 As upper_bound

from
(
Select
     pt_on_line.geom as pt,
     line.geom As line,
     ST_StartPoint(ST_LineMerge(line.geom)) As line_start_pt,
     ST_EndPoint(ST_LineMerge(line.geom)) As line_end_pt
from pt_on_line
Left join line on ST_DWithin(pt_on_line.geom, line.geom, 0.1)
)
As foo;

Now starting with this street orientation, I need to generate a wind rose of 12 sectors (each of 30 degree having its lower bound and upper bounds) as geometry around this point on line in a radius of 50 meter. In the above code, I have assigned street direction as lower bound of sector_1 and added 30 degree to the lower bound. This approach might be unrealistic though. The expected output could be something similar to this.

How can I draw these 12 wind sectors (geometry) around this point starting from line's orientation?

Using the answer of @MichalZimmermann, here is the screen shot of wind rose generation using PostGIS and visualized in QGIS.

A: CREATE OR REPLACE FUNCTION ST_WindRose(
    line geometry,
    directions int,
    radius numeric
)
RETURNS TABLE (
    id integer,
    geom geometry(LINESTRING)
)
AS $ST_WindRose$
BEGIN
    IF directions % 2 <> 0 THEN
        RAISE EXCEPTION 'Odd number of directions found, please provide even number of directions instead.';
    END IF;

    IF radius > ST_Length(line) THEN
        RAISE EXCEPTION 'Inner circle radius is bigger than the wind rose diameter, please make it smaller.';
    END IF;

    RETURN QUERY
    WITH rose AS (
        SELECT
            ST_Rotate(_line, radians(360) / directions * dirs.id, ST_Centroid(_line)) _line
        FROM (
            SELECT line _line
        ) a
        CROSS JOIN (
            SELECT generate_series(1, directions / 2) id
        ) dirs
    )
    SELECT
        row_number() OVER ()::integer id,
        _line geom
    FROM (
        SELECT _line FROM rose
        UNION ALL
        SELECT ST_ExteriorRing(ST_Buffer(ST_Centroid(line), radius, 30)) -- inner circle
        UNION ALL
        SELECT ST_ExteriorRing(ST_Buffer(ST_Centroid(line), ST_Length(line)/2, 30)) -- outer circle
    ) a;
END
$ST_WindRose$
LANGUAGE PLPGSQL;

Use it with
SELECT * FROM ST_WindRose(ST_MakeLine(ST_MakePoint(0,0), ST_MakePoint(0,1)), 12, 0.01);

Note it's half past 9pm here, it might not be the best solution ever, but it works.


text:
Q: iphone: local qr code generator can anybody suggest me some SDK or way of creating a local QR code generator for iphone? Please enlighten me on this I have referred zxing and several other qr code libraries but none of them support iphone for qr code generation
Thanks in advance

A: Another generator wrapped in a sample iPhone project.  This project was created in Xcode 4:
https://github.com/kuapay/iOS-QR-Code-Generator

A: here goes the solution
https://github.com/jverkoey/ObjQREncoder

A: The following tutorial demonstrates how you can easily generate QR Codes directly from within an iPhone app:
http://www.oscarsanderson.com/2013/08/12/implementing-a-qr-code-generator-on-the-iphone/


text:
Q: How to set previous state to html using jQuery The idea is I have "Modify" button, that expand <div> with select and checkboxes. Also I have 2 buttons on this <div>: "Update" and "Cancel". I want on "Cancel" press to revert all changes in checkboxes and select to the state, that was when I pressed "Modify".
My <div>:
<div class="accordion_box_inner accordion_box_leding">
.....
@Html.MaterialDropDownRadioListItemFor(x => x.Categories[i].Products[j].AccountUsedFor, values, Constants.OptionLabel,
                            new
                            {
                                @class = "accountUsedForSelection" + (productSelection.Product.IsProductFieldType(ProductType.Mortgage) ? " mortgage-switches" : ""),
                                data_evtname = eventPrefix + "-AccountUsedFor"
                            }, "w-100 mdldropDownWrap")
.....

My button:
@Html.MaterialButton("Cancel", attrs: new{@class = "cancel-product"})
js:
function modifySelectedProduct($items) {
    var $container = $items.closest('.accordion_box_inner');
    var $infoContainer = $container.find('.product-info-container');
...
    $infoContainer.slideDown();
    $container.parent().siblings().hide();
    $container.find('.add-product').removeClass('remove-button').text('update');
    $container.find('.cancel-product').show();
...

function cancelSelectedProduct($items) {
    var $container = $items.closest('.accordion_box_inner');
    var $infoContainer = $container.closest('.accordion_box_inner');
....
    $infoContainer.slideUp();
    $container.parent().siblings().show();
    $infoContainer.closest('.accordion_box_inner').find('.add-product').hide();
    $('.menu_accordion').find('.accordion_item_wrap').show();
....

What I tried:
Modify:
this.savedItem = $.extend(true, {}, $items.closest('.accordion_box_inner'));

Cancel:
var $container = $items.closest('.accordion_box_inner');

$container = this.savedItem;

but the HTML in this.savedItem has changed status.
UPDATED: added code.
P.S. Yes, I tried advices from answers but without result.


text:
Q: Incorporate a Makefile in Xcode? I have a Makefile set up, is there any way to "port" its settings to Xcode so all of my settings there will be applied to Xcode's build settings and dependencies?
I've tried looking it up online but i'm using Xcode 7.3.1 while all of what i've found was referring to older versions so i couldn't really find the matching settings.
Thanks!


text:
Q: Tensorflow Serving: get_model_status is missing the 'utils' I am trying to use some (presumably) standard features of tensorflow serving, but I am running into an odd problem. I am trying to implement some simple health-check for served models following https://www.tensorflow.org/serving/setup.
I did this by first creating a simple Docker image with Ubuntu 18.04 (also tried for 16.04) and then installing python3-dev (python3.6 as of this writing), before downloading and installing the necessary packages including gRPC as given above. As I am not interested in building it from source, I skipped Bazel.
Doing:
pip3 install tensorflow-serving-api
installs the tensorflow-serving-api (1.9.0 as of this writing) without a problem, but when I try to:
from tensorflow_serving.apis import get_model_status_pb2
to utilize the model status, I get the following error:
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/local/lib/python3.6/dist-packages/tensorflow_serving/apis/get_model_status_pb2.py", line 17, in <module>
    from tensorflow_serving.util import status_pb2 as tensorflow__serving_dot_util_dot_status__pb2
ImportError: No module named 'tensorflow_serving.util'

Looking at /usr/local/lib/python3.6/dist-packages/tensorflow_serving there is no util directory. Is anyone else experiencing this when just using pip to install tensorflow_serving and know of a fix to this? If I do build tensorflow serving from source I get the directory, so I suppose a fix to make a wheel out of this, but I am curious nevertheless.
Thanks in advance.

A: To solve this, download the wheel https://pypi.org/project/tensorflow-serving-api/#files from the given link. You either extract it using 7-zip extractor and use it as a source folder for imports or install the .whl file using pip.

A: This issue has been fixed, and should be out with the next release of the API.


text:
Q: Grafana, menu to get value and use in query I need a little help here with Grafana...
I am trying to make a single stat which will be showing result from the query. The challenge for me here is that part of the query must be one of the fixed values (numbers) which user would select from menu picture. If user select Current Shift, value to query would be for example today, from 6:00 - 14:00.
Then pass the value to variable that query would use to limit range of data (for example in flux datasource).
I use Grafana 6.5.2 and Influxdb 1.7.9.
Attching menu example

Attaching query, looking to input range
|> range(start:2018-05-22T23:30:00Z, stop: 2018-05-23T00:00:00Z)

Appreciate help,
Salvq


text:
Q: Find the projection of the curve of intersection between two solids $z=x^2+y^2$ and $z=\frac{1}{2}y$. I want to find the curve of intersection and its projection of the $xy$-plane of the solids $z=x^2+y^2$ and $z=\dfrac{1}{2}y$. Following my calculations it's given by the parametric equation:

$$\varphi(t)=(\frac{1}{4}\cos t,\frac{1}{4}+\frac{1}{4}\sin t,\frac{1}{8}+\frac{1}{8}\sin t)$$

where $0\le t\le 2\pi$.
If we disregard the $z$ part we get the projection on the $xy$-plane:
$$\alpha(t)=(\frac{1}{4}\cos t,\frac{1}{4}+\frac{1}{4}\sin t)$$
I would like to know if I'm right.

A: (+1) Right and you applied a good simple approach. Maybe someone interests more details.
Further details shows the curve of intersection $z=x^2+y^2$ and the plane $z=\dfrac{1}{2}y$
is an ellipse and we find it's apogee and perigee with $x=0$ in
$$\varphi(t)=\left(\frac{1}{4}\cos t,\frac{1}{4}+\frac{1}{4}\sin t,\frac{1}{8}+\frac{1}{8}\sin t\right)$$
which gives us $(0,0,0)$ and $(0,\dfrac12,\dfrac14)$ so $2a=\sqrt{(\dfrac12)^2+(\dfrac14)^2}$ or $\color{blue}{a=\dfrac{\sqrt{5}}{8}}$. The center of ellipse is $(0,\dfrac14,\dfrac18)$,
and contact between the line $8z=4y=1$ and $z=x^2+y^2$ are $(\pm\dfrac14,\dfrac14,\dfrac18)$ that shows $\color{blue}{b=\dfrac14}$ and then $c^2=a^2-b^2=\dfrac{1}{64}$ hence $\color{blue}{e=\dfrac{\sqrt{5}}{5}}$.
The projection of this ellipse on $xy$-plane, as you said is the planar curve
$$\alpha(t)=\left(\frac{1}{4}\cos t,\frac{1}{4}+\frac{1}{4}\sin t\right)$$

A: I've plot them. Not reputed as a rigorous way to check results, but to my understanding, it amounts almost the same as checking the equations for the curves into the equations for the surfaces.


text:
Q: remove or replace only the word after a specific word in column pandas using regex I'm trying to use regex to remove or replace only the word after specific word(s) in a column of strings in a dataframe. This means I don't want the spaces to be replace. Just the word the proceeds the specific word(s)
import pandas as pd

df = pd.DataFrame({'STRING': [r"THERE IS NO REASON WHY THIS SHOULDN'T WORK!", r"I AM WITHOUT DOUBT     VERY BAD AT REGEX", r"I CAN'T SOLVE A PROBLEM HAT HAS NO INTRINSIC VALUE"]})

df.STRING.str.replace(r'/(?<=NO|WITHOUT)(\s+)\w','', regex=True)  #this doesn't work

here's my output:
                                              String  \
0        THERE IS NO REASON WHY THIS SHOULDN'T WORK!
1           I AM WITHOUT DOUBT     VERY BAD AT REGEX
2        I CAN'T SOLVE A PROBLEM THAT HAS NO INT...

                                      desired_output
0              THERE IS NO  WHY THIS SHOULDN'T WORK!
1                I AM WITHOUT      VERY BAD AT REGEX
2         I CAN'T SOLVE A PROBLEM THAT HAS NO  VALUE

Again, i don't want the spaces between them to be removed. I only want the one word after NO or WITHOUT to be removed/replaced.

A: Note that your regex, /(?<=NO|WITHOUT)(\s+)\w, contains several issues:

*

*/ - is a typo, it was probably a regex delimiter that got into the pattern

*(?<=NO|WITHOUT) - is a lookbehind pattern where alternatives match strings of different length and Python lookbehinds patterns must be fixed-width

*\w - matches a single word char, not one or more. There must be some quantifier after \w, * (zero or more times) or + (one or more occurrences).

You can use
import pandas as pd
df = pd.DataFrame({'STRING': [r"THERE IS NO REASON WHY THIS SHOULDN'T WORK!", r"I AM WITHOUT DOUBT     VERY BAD AT REGEX", r"I CAN'T SOLVE A PROBLEM HAT HAS NO INTRINSIC VALUE"]})
pattern = r'\b((?:NO|WITHOUT)\s+)\w+'
df['STRING'] = df['STRING'].str.replace(pattern, r'\1', regex=True)

Output:
>>> print(df.to_string())
                                      STRING
0      THERE IS NO  WHY THIS SHOULDN'T WORK!
1        I AM WITHOUT      VERY BAD AT REGEX
2  I CAN'T SOLVE A PROBLEM HAT HAS NO  VALUE

See the regex demo. Details:

*

*\b - a word boundary

*((?:NO|WITHOUT)\s+) - Group 1 (\1 refers to this group value from the replacement pattern): NO or WITHOUT and then one or more whitespaces

*\w+ - one or more word chars (replace with \S+ if you plan to remove one or more non-whitespace chars, or even \S+\b to cut off trailing punctutation).


text:
Q: R : Two Different Methods of Webscraping Produce Two Different Results? I am trying to scrape the name, address and longitude/latitude coordinates for each name on a website (e.g. www.mywebsite.com). I used the following the code to get the address and name based on this SO post
library(tidyverse)
library(rvest)
library(httr)
library(XML)

# Define function to scrape 1 page
get_info <- function(page_n) {

  cat("Scraping page ", page_n, "\n")

  page <- paste0("mywebsite.com",
    page_n, "?extension") %>% read_html

  tibble(title = page %>%
           html_elements(".title a") %>%
           html_text2(),
         adress = page %>%
           html_elements(".marker") %>%
           html_text2(),
         page = page_n)
}

# Apply function to pages 1:10
df_1 <- map_dfr(1:10, get_info)

# Check dimensions
dim(df_1)
[1] 90

Since I did not know how to modify the above code to extract the coordinates, I wrote a separate script to scrape them:
# Recognize pattern in websites
part1 = "www.mywebsite.com"
part2 = c(0:55)
part3 = "?extension"
temp = data.frame(part1, part2, part3)

# Create list of websites
temp$all_websites = paste0(temp$part1, temp$part2, temp$part3)

# Scrape
df_2 <- list()

for (i in 1:10)

{tryCatch({

    url_i <-temp$all_websites[i]

    page_i <-read_html(url_i)

    b_i = page_i %>% html_nodes("head")

    listanswer_i <- b_i %>% html_text() %>% strsplit("\\n")

    df_2[[i]] <- listanswer_i

    print(listanswer_i)

}, error = function(e){})

}

# Extract long/lat from results

lat_long = grep("LatLng", unlist(df_2[]), value = TRUE)

 df_2 = data.frame(str_match(lat_long, "LatLng(\\s*(.*?)\\s*);"))

In the end, scraping the first 10 pages for name/address resulted in 90 entries, but scraping the same 10 pages for the longitude/latitude resulted in 96 entries:
dim(df_1)
[1] 90

dim(df_2)
[1] 96  3

Can someone please help me understand why this is happening and what can I do to fix this?
In the end, I would to make a final table (using df_1 and df_2) that looks something like this:
 id  name  address  long  lat
1  1 name1 address1 long1 lat1
2  2 name2 address2 long2 lat2
3  3 name3 address3 long3 lat3

Thanks!
Note: I understand that its possible that some names might be missing their latitude/longitudes, and it might not be possible to have the dimensions of "df_1" match the dimensions of "df_2". If this is the case, would it be somehow possible to find out which names are missing their latitude/longitudes (e.g. replace the latitude/longitude entries with NULL for those cases)? For example - suppose the latitude/longitude was not available for "name3":
 id  name  address  long  lat
1  1 name1 address1 long1 lat1
2  2 name2 address2 long2 lat2
3  3 name3 address3   NA   NA

A: The Problem
The problem is that your second code snippet is not filtering out strings that contain "LatLng" but do not provide coordinates.
After your second code snippet finished scaping the pages, you do the following:
lat_long = grep("LatLng", unlist(df_2[]), value = TRUE)

If you look at the output of this with print(lat_long), you would see a bunch of rows with coordinates. In fact, you'd see exactly 90 such rows because that's how many providers appeared on all those pages. However, you'd also see rows with the string "\t\t\t\tvar bounds = new google.maps.LatLngBounds();". If you go back to the raw HTML you grabbed, you'd see this appears occasionally. Accordingly, you need to remove these rows.
I thought that perhaps you accomplished this with the remaining code, but you never actually remove them. For example, the below code just produces an object filled with NA values. I don't think this does what you want:
as.numeric(gsub("([0-9]+).*$", "\\1", lat_long))

Additionally, the below retains those values as well:
data.frame(str_match(lat_long, "LatLng(\\s*(.*?)\\s*);"))

The Solution
You need to drop elements without coordinates. You'll notice that those elements all contain the substring "LatLngBounds();", so you can just filter them out once they're in a data.frame like below, or using regex.
df_2 %>% filter(X1 != "LatLngBounds();")

Note that this will actually produce 86 rows instead of 90. So, now we're actually short 4 rows. This is because you are not actually collecting all of the GPS coordinates for everyone on the provider page. You can know this because every provide has an address in df_1 and the coordinates are simply passing those addresses to the Maps API.
Why aren't you getting all of the coordinates? My guess is two reasons. First, you are scraping coordinate based on the marker substring. This marker indicates markers/pin on the map. Since the number of pins on the map need not equal the number of providers on the page, you will miss some providers. The less likely issue may have to do with the Google Maps API.  If you visit the URLs you create to scrape from (example], you'll see in the bottom left that the Google Maps widget contains the error "This page didn't load Google Maps correctly. See the JavaScript console for technical details". If you look at the JS console, you'll see that an invalid Google Maps API Key was provided. This seems like a likely issue since (a) there is one "LatLngBounds" row per page you are scraping and (b) the row after each of those rows contains coordinates that are not necessarily anywhere near the providers (mine initializes in the U.S. West Coast while the providers are in Canada). I don't know if this has any consequence, but it would explain it if the marker issue isn't the driver.
However, all of this is mostly irrelevant since you don't even need to scrape the coordinates in the first place. You have a list of addresses: you can GeoCode them yourself! There are different ways of doing this, but you can replicate what the site is doing by simply passing them to the Google Maps API! For step-by-step instructions on how to do this, see here.
Identifying the Problem
To provide a better idea of how to approach similar problems in the future, I'll show how I worked through this. One way to approach issue like this is to start by ruling out possible explanations.
Why the problem isn't "missing coordinates"
If the issue was that names are missing coordinates, we would expect nrow(df1) > nrow(df2). However, you reported the opposite: nrow(df2) > nrow(df1).
Why the problem isn't the first code snippet
Since each page contains 9 providers (at least until the last page) and you are scraping 10 pages, we expect to return 9*10 = 90 elements. As you noted, the first code snippet returns an object with 90 rows while the second code snippet returns an object with 96 rows. The second code snippet must be the issue.
Why the problem isn't the pages
Looking at your code, I noticed that you're scraping different pages. Your code to produce df1 iterates over the values of page_n in the interval 1:10. In contrast, your code to produce df2 iterates over the values of page_n in the interval 0:9. This is because the latter code extracts the values of all_websites at indices 1:10, which happen to be the value 0:9 since all_websites is simply the vector 0:55. Since page_n == 0 returns the same page as page_n == 1, your first code is scaping pages 1:10 and your latter code is scraping page c(1,1:9). This means that the values contained in df1 and df2 will differ.
However, this cannot explain the discrepancy in the dimensionality of the two objects since they would still be expected to return 90 rows!


text:
Q: Powershell script to pull info from file name from list of folders I have a list of files in a folder each are in this format: custID_invID_prodID. For every file I need to break it into sections based on '_'. Currently I have this code
$files = Get-ChildItem test *.txt
$Part = $files.Split(';')[$($files.Split('_').Count-1)]
Write-Host  "${Part}"

The problem is that it appears that $files is a list of all the files and I need it to run each file on its own. Can anyone offer some pointers on how to do this for the entire folder?

A: "The problem is that it appears that $files is a list of all the files and I need it to run each file on its own."
That is correct, running get-childitem on a folder will give you a list of all files (and subfolders). In order to go through them one by one, you need a loop:
$file = @()
$files = Get-ChildItem Test *.txt
foreach($f in $files)
{
    $file += ([String]$f).Split("_")
    $count = ([String]$f).Split("_") | Measure-Object | select count
}
if($count.count -eq 3) {
    for($i=2; $i -lt $file.length; $i+=3) {
        $file[$i] = $file[$i].trimend(".txt")
    }
}

A: I was able to fix this by using this code:
$Part = $file.name.Split('_')[$($file.name.Split('_').Count-1)]
Write-Host "${Part}"


text:
Q: Make clock running I would like the time to reset every second so the clock becomes a running one. I'm a javascript noob and I couldn't find any solution anywhere.
        <!--
        var currentDate = new Date()
        var day = currentDate.getDate()
        var month = currentDate.getMonth() + 1
        var year = currentDate.getFullYear()
        document.write("<b>" + day + "/" + month + "/" + year + "</b>")
        //-->
    <!--
var currentTime = new Date()
var hours = currentTime.getHours()
var minutes = currentTime.getMinutes()
var seconds = currentTime.getSeconds()

if (minutes < 10)
minutes = "0" + minutes

if (seconds < 10)
seconds = "0" + seconds

document.write(hours + ":" + minutes + ":" + seconds)

A: var myInterval = window.setInterval(function() {
  window.document.write(hours + ":" + minutes + ":" + seconds);
}, 1000);

Later you can stop it with
window.clearInterval(myInterval);

We assign the return value of setInterval (an ID in the form of a number) to a variable because we'll need it later to stop our particular interval using the clearInterval function. If we don't do that, there will be no way (without certain hacks) to stop the interval.

A: For that you need to use the window.setInterval method. Please look at this page for more information: http://www.w3schools.com/js/js_timing.asp


text:
Q: Boggle word checker logic I am trying to solve a boggle word checker problem, I am almost there but I need some help with the logic.
Boggle word checker takes a 2d array and a string and I want to determine whether that string is a valid boggle word returning either true or false. So valid guesses are strings which can be formed by connecting adjacent cells (horizontally, vertically, or diagonally) without re-using any previously used cells.
For example EAR is correct but EARS is not.
From what I can tell, it seems to work properly until it gets to the last letter and then I am having issues with it returning correctly T/F. I tried using an if statement so that it would stop the recursive call but it doesn't seem to be working. Any advice on how to figure it out would be amazing!
final private static char[][] board = {
        {'E','A','R','A'},
        {'N','L','E','C'},
        {'I','A','I','S'},
        {'B','Y','O','R'}
    }

public class Boggle {
    char[][] board;
    String word;

    public Boggle(final char[][] board, final String word) {
       this.board = board;
       this.word = word;
    }

    public boolean checkit() {
      //make string array
      //iterated through board
      //if word[0] == board value
      //check -> see if value above beloow left right is a match to word[1]
      System.out.println("word: "+word);
      char[] charArr = word.toCharArray();
      int index = 0;
      boolean valid = false;
      for(int row=0; row< board.length; row++) {
        for(int col=0; col<board[0].length; col++) {
          if(board[row][col] == charArr[index]) {
            return check(board, charArr, row, col, index);
          }
        }
      }
      return valid;
    }

    public boolean check(char[][] board, char[] charArr, int row, int col, int index) {
        index++;
        //while index< charArr.length, keep searching for matches
        System.out.println("index: "+index + " chararr.length: "+charArr.length);
        if(index >= charArr.length) return true;
        else if(index < charArr.length) {
          System.out.println("here");
          //check up
          if(row-1 >= 0) {
            if(board[row-1][col] == charArr[index]) {
              check(board, charArr, row-1, col, index);
            }
          }
          //check up/right (diagonal)
          else if((row-1  >= 0) && (col+1 < board[0].length)) {
            if(board[row-1][col+1] == charArr[index]) {
              check(board, charArr, row-1, col+1, index);
            }
          }
          //check right
          else if(col+1 < board[0].length) {
            if(board[row][col+1] == charArr[index]) {
              System.out.println("right");
              check(board, charArr, row, col+1, index);
            }
          }
          //check right/down (diagonal)
          else if((col+1 < board[0].length) && (row+1 < board.length)) {
            if(board[row+1][col+1] == charArr[index]) {
              check(board, charArr, row+1, col+1, index);
            }
          }
          //check down
          else if(row+1 < board.length) {
            if(board[row+1][col] == charArr[index]) {
              check(board, charArr, row+1, col, index);
            }
          }
          //check down/left (diagonal)
          else if((col-1 >= 0) && (row+1 < board.length)) {
            if(board[row+1][col-1] == charArr[index]) {
              check(board, charArr, row+1, col-1, index);
            }
          }
          //check left
          else if(col-1 >= 0) {
            if(board[row][col-1] == charArr[index]) {
              check(board, charArr, row, col-1, index);
            }
          }
          //check left/up (diagonal)
          else if((col-1 >= 0) && (row-1 >= 0)) {
            if(board[row-1][col-1] == charArr[index]) {
              check(board, charArr, row-1, col-1, index);
            }
          }
          //no match
          System.out.println("false section");
          return false;
        } //end while
        return false;

    }
}

A: Problems I see include:

*

*You don't look at the return result of check().

*You allow a word to use the same letter twice.

*The following code is redundant.
if(index >= charArr.length) return true;
else if(index < charArr.length) {
If it gets past the first line, we know the condition must pass, so there is no need to check it again.


text:
Q: seedstack Explicit bindings are required and MYOBJECT is not explicitly bound I am a newbe using seedstack the "Clean Java development" framework (seedstack.org).
My first action here was to create a singleton object and call it in my rest service. But seedstack throws an error...
/*** MY SINGLETON ***/
package com.opel.application.partmapping.domain.shared;
import javax.inject.Singleton;

@Singleton
public class AppSingleton {
private String aSingleStr = "Xxxxxxx Yyyyy @ Zzzz" ;
       public String getASingleStr() {
             this.aSingleStr = this.aSingleStr + "x" ;
             return this.aSingleStr;
       }
}

/* MY REST SERVICE */
    package com.opel.application.partmapping.interfaces.rest;
import javax.inject.Inject;
import javax.ws.rs.GET;
import javax.ws.rs.Path;

import org.seedstack.seed.Application;
import org.seedstack.seed.Configuration;
import org.seedstack.seed.Logging;
import org.slf4j.Logger;

import com.opel.application.partmapping.domain.shared.AppConfig;
import com.opel.application.partmapping.domain.shared.AppSingleton;

@Path("hello")
public class HelloResource {

    @Inject
    private Application application;

    @Inject
    private AppSingleton theAppSingle;

       @Logging
       private Logger logger;

       @Configuration
       private AppConfig theAppConfig;

    @GET
    @Path("hello1")
    public String hello1() {
       logger.info("Hello Xxxxxxx... in hello1() ");
        return "The author of this tool is ..."  ;
    }

    @GET
    @Path("hello2")
    public String hello2() {
        return "The author of this tool is ..." + theAppConfig.getTheAuthor();
    }

    @GET
    @Path("hello3")
    public String hello3() {
       AppConfig myConfig = application.getConfiguration().get(AppConfig.class);

        return "The author of this tool is ..." + myConfig.getTheAuthor();
    }

    @GET
    @Path("hello4")
    public String hello4() {

        return "The singleton ..." + theAppSingle.getASingleStr();
    }
}

Seedstack is throwing the ERROR message:
[ERROR] Failed to execute goal org.seedstack:seedstack-maven-plugin:2.7.1:watch (default-cli) on project PartMapper: An exception occurred while executing SeedStack application: [CORE] Unexpected exception: Unable to create injector, see the following errors:
[ERROR]
[ERROR] 1) Explicit bindings are required and com.opel.application.partmapping.domain.shared.AppSingleton is not explicitly bound.
[ERROR]   while locating com.opel.application.partmapping.domain.shared.AppSingleton
[ERROR]     for field at com.opel.application.partmapping.interfaces.rest.HelloResource.theAppSingle(HelloResource.java:22)
[ERROR]   at org.seedstack.seed.rest.internal.RestModule.configure(RestModule.java:41) (via modules: com.google.inject.util.Modules$OverrideModule -> io.nuun.kernel.core.internal.injection.KernelGuiceModuleInternal -> org.seedstack.seed.rest.internal.RestPlugin$1 -> org.seedstack.seed.rest.internal.RestModule)

I do not know what bindings are required and how and where to add them.
Can anyone help me to solve that issue?

A: This errors tells you that, when trying to inject an AppSingleton instance, the injector doesn't know how. The injector terminology for "how to inject something" is "a binding". Think of it as a rule of injection.
In your case, you can this error because the @Singleton annotation is not enough to create a binding: it just specifies the scope of the potential binding.
SeedStack does a lot of bindings for you by scanning the classpath and finding classes of interest (for instance @Path-annotated classes are JAX-RS resources automatically bound by the REST module). In your case, you want to create an arbitrary binding, so you have to use the @Bind annotation:
import javax.inject.Singleton;
import org.seedstack.seed.Bind;

@Singleton
@Bind
public class AppSingleton {
    private String aSingleStr = "Xxxxxxx Yyyy @ Zzzz" ;

    public String getASingleStr() {
        this.aSingleStr = this.aSingleStr + "x" ;
        return this.aSingleStr;
    }
}

Note that I kept the @Singleton annotation since you wanted a singleton in the first place. If you omit it, you will only have a binding without scope, meaning that everytime an instance must be injected, a new one will be created (good for statelessness).


text:
Q: PHP Ad Rotation Script Randomly Stops Working after updating a part of the code I had a PHP script that is supposed to automatically rotate advertisement banners, and it was working just fine before, but after i tried changing 1 piece of the code it stopped working. Even after i changed it back it still wouldn't work anymore. I don't get any errors, and no error_log files, the only part of the code i changed was just the url of the page its supposed to redirect you to. Here's my code (before the change):
<?php
$bCount = 1;
$bCode[$bCount] = '';
$bCount++;

$bTotals = $bCount -1;
if ($bTotals>1)
{
mt_srand((double)microtime() * 1234567);
$bPick = mt_rand(1, $bTotals);
}
else
{
$bPick = 1;
}
$ad = $bCode[$bPick];
?>

and here is the code after i made the small change (really not much of a difference, just a change in the URL):
    <?php
$bCount = 1;
$bCode[$bCount] = '';
$bCount++;

$bTotals = $bCount -1;
if ($bTotals>1)
{
mt_srand((double)microtime() * 1234567);
$bPick = mt_rand(1, $bTotals);
}
else
{
$bPick = 1;
}
$ad = $bCode[$bPick];
?>

After i made that change, the script wouldn't display the ad that was supposed to show up, it was just blank. So i rolled back the changes to how it was before when it was working, and it still will not show up anymore. What could have caused it to stop working?


text:
Q: Java servlet and persistence structure I have a java webapp that has a servlet doPost which accepts some json POST. Lets call it a "Person". So it receives something like { name: "Joe", age: 35 }. Then there's also a databind class for jackson that captures this... like
public class Person {
  public String name;
  public int age;
}

I currently have the DB stuff happening inside the Servlet class. So like the servlet receives the request, deserializes it to a Person object, and then takes that resultant object and creates a JDBC connection and runs an insert. What is the best way to structure this? Is this all right? I feel like the persistence should be more linked to the object itself than to the servlet. Should I put the DB functionality into the Person obj? Or create some new "thing" to handle it?

A:
I feel like the persistence should be more linked to the object itself
  than to the servlet.

Neither are correct, basically, we need to layer the application properly i.e, we should not mix up both Front end (user interface) concerns and business logic and check below for more explanation on layering the web application.

Should I put the DB functionality into the Person obj? Or create some
  new "thing" to handle it?

No, you need to handle the data access layer separately like using a DAO (Data Access Object) or Repository layer.
In general, the web application architecture works like this:
HTML/JSP -> Servlet & Controller classes -> Service Layer -> DAO Layer -> Database
Each one of these layers is meant for its own reasons and we should not mix the concerns.
Now specifically talking about the DAO layer (look here how DAO pattern works), there are various frameworks available to make things easier and ORM (Object Relational Mapping) is the concept you might be interested in. Just to name few, the popular ORM frameworks are Hibernate and Spring data JPA.

UPDATE:

So, the servlet accepts the request, deserializes the data to some
  data bind classes that match the JSON schema. Then it passes those to
  some "service layer" that does some kind of manipulation and generates
  DAO objects that match the table structures and saves it off?

You are almost there, the only thing you are missing is that DAO objects are singleton classes (they don't hold the data, just they provide methods to access the database) and the model/entity beans are really used to save the data.
You can refer the below simple example assuming that it is accessing the PRODUCT table in the database:
ProductDAOImpl class (singleton object):
public class ProductDAOImpl implements ProductDAO { //or ProductRepository

    public boolean save(Product product) {
        //add implementation
    }

    public List<Product> queryProducts() {
        //add implementation
    }

    public Product queryUniqueProduct(String productId) {
        //add implementation
    }

    //etc...any other methods you would like
}

Product class (one object for each request from client/user):
public class Product { //It is an Entity class

    private String id;

    private String name;

    private int price;

    //all other fields

    //getters and setters
}

What if you have a mismatch between request and data model?

Always, ensure that both presentation layer beans and entity (database) model beans should be separate i.e., it is not a good practice to share the beans across these two layers because one handles business logic and other is for user interface (frontend), both should be loosely coupled.


text:
Q: Net Core, generate RouteLink with html as linkText parameter I need to create an link with a svg icon and i need to use
RouteLink(this Microsoft.AspNetCore.Mvc.Rendering.IHtmlHelper htmlHelper, string linkText, string routeName, object routeValues, object htmlAttributes)

from Microsoft.AspNetCore.Mvc.Rendering.
If I do the following:
var link = html.RouteLink("<svg class=\"icon\"><use href=\"#chevron-left\"></use></svg>", model.RouteActionName, model.RouteValues, new { title = "Previous page" });

Then for example I get
<svg class="icon"><use href="#chevron-left"></use></svg>

So the string linkText is not being rendered at html. Does anyone know how can I overcome this? So I get regular html as the linktext like this:
<svg class="icon"><use href="#chevron-left"></use></svg>

A: Obtain the URL and render the HTML yourself:

    <svg class="icon">
        <use href="#chevron-left" />
    </svg>

A: You can use Html.Raw() method.
var link =Html.Raw(html.RouteLink("<svg class=\"icon\"><use href=\"#chevron-left\"></use></svg>", model.RouteActionName, model.RouteValues, new { title = "Previous page" }));

Edit:
var routelink =html.RouteLink("<svg class=\"icon\"><use href=\"#chevron-left\"></use></svg>", model.RouteActionName, model.RouteValues, new { title = "Previous page" });
var link = System.Net.WebUtility.HtmlDecode(routelink.ToHtmlString());


text:
Q: How do I put this into a working code to validate user input (Java)? I am beginner programmer. I am trying to write a code with this requirement that user input must be number 1-20 and also that it is not a letter.
Requirement on my code:

*

*while loop i.e while(true)

*isDigit()

I started with this code, but I don't know how to implement the isDigit method. I assume it has to be nested within the while loop.
    while(input < 1 || input > 20){
        System.out.println("Invalid number! Try again.");
        input = s.nextInt();
        s.nextLine();
    }
    return input;
}

I have tried using "if" statement and using another "while" loop but it didn't work. Much appreciated.

A: Your while condition is incorrect, while(input < 1 || input > 20) it is checking if number is less than 1 and greater than 20,
This problem has two parts, 1. check if input is valid number , 2. check if number is in range
public static void main(String[] args) {

        Scanner sc = new Scanner(System.in);
        boolean validInput = false;
        do
        {
            System.out.println("Enter valid number ");
            // get user input
            String input =  sc.nextLine();

            if(isDigit(input)) {
                int inputNumber = Integer.parseInt(input);
                //check if number is in the range of 1 to 20
                boolean isInRange = (inputNumber > 1) && (inputNumber < 20);
                validInput  = true;
                if(isInRange) {
                    System.out.println(input+" is valid Number and in the range of 1 to 20");
                }
                else {
                    System.out.println(input+" is valid Number But Not in the range of 1 to 20");
                }
            }
            else {
                System.out.println(input+" is invalid Number");
            }
        }
        while (!validInput ); // continues untill valid input is entered

    }

Here isDigit method uses regular expresssion [0-9] to check if character is in the range of 0 to 9, you can check more on regular expressions here https://www.w3schools.com/java/java_regex.asp

    //check if input is valid number
    public static boolean isDigit(String input) {

        if (input == null || input.length() < 0)
            return false;
        input = input.trim();
        if ("".equals(input))
            return false;
        if (input.startsWith("-")) {
            return input.substring(1).matches("[0-9]*");
        } else {
            return input.matches("[0-9]*");
        }
    }

A: I've extended your while() to have extra logic to check if entered input is numeric value using isNumeric() provided by StringUtils. This function checks if the CharSequence contains only Unicode digits and hence reducing the complexity of the code having to check numeric value explicitly.
import java.io.*;
import java.util.*;

import static org.apache.commons.lang3.StringUtils.isNumeric;

public class Solution {
    public static void main(String[] args) throws IOException {

        int result = isDigit();
        System.out.println("Result is: " + result);
    }

    public static int isDigit() {
        // Create a Scanner object
        Scanner s = new Scanner(System.in);
        System.out.println("Enter number");
        // Accept input in String
        String input = s.next();

        /**
         * Check if input is numeric and between 1 and 20.
         * Otherwise, accept new input from user.
         */
        while (!isNumeric(String.valueOf(input))
            || Integer.parseInt(input) < 1 || Integer.parseInt(input) > 20) {
            System.out.println("Invalid number! Range should be between 1 and 20. Try     again.");
            input = s.next();
            s.nextLine();
        }

        // Return numeric value which is between 1 and 20
        return Integer.parseInt(input);
    }
}

Output:
Enter number
30
Invalid number! Range should be between 1 and 20. Try again.
-10
Invalid number! Range should be between 1 and 20. Try again.
abc
Invalid number! Range should be between 1 and 20. Try again.
10
Result is: 10

A: I am using two static functions to

*

*Find the inputted number is integer or not [isInteger] and

*To force the user to input a number between 1 and 20.

As you are an beginner, I did not use regular expression while checking the user input is number.
Scanner scanner = new Scanner(System.in);

public static void main(String[] args) {
    System.out.println("Enter an integer number between 1 and 20");
    String userInput = scanner.nextLine();

    int requiredInput = validateAndGetNumber(userInput);

    /*
      Now, do whatever you want to do with this requiredInput
    */
}

public static int validateAndGetNumber(String input) {

    if (isInteger(input)) {
        int num = Integer.parseInt(input);

        if (num >= 1 && num <= 20)
            return num;
        else {
            System.out.println("Number is not in range 1-20. Please try again.");
            input = scanner.nextLine();
            return validateAndGetNumber(input);
        }
    }

    System.out.println("Input is not an integer number. Please try again.");
    input = scanner.nextLine();
    return validateAndGetNumber(input);
}

public static boolean isInteger(String str) {
    if (str == null) {
        return false;
    }
    int length = str.length();
    if (length == 0) {
        return false;
    }
    int i = 0;
    if (str.charAt(0) == '-') {
       System.out.println("Negative value is invalid for this property.");
       return false;
    }

    for (; i < length; i++) {
        char c = str.charAt(i);

        if ((c < '0' || c > '9') && c != '-') {
            return false;
        }
    }
    return true;
}


text:
Q: Android app hangs on getting post preview I've just tried to post a report about imposibility to see the inbox messages via Android app, but actually I'm unable to do more actions. In partucular:

*

*load an inbox page

*upload an image to the post

*get preview for the post

In the last case I'm actually unable to discard this endless operation.

Current bug has been posted via web site.


text:
Q: No New Mail Sound 10.6.7 This issue has been going on and off for years.  I still don't consistently get the new mail sound when new mail arrives.
Sometimes it happens, most of the time, never.
10.6.7

A: Since you mention this has been going on for years, this is likely related to a longstanding bug in Mail.app and fetching mail with IMAP. Try the instructions here and see if it helps:

In Mail, open Preferences and go to
  Accounts » Advanced in all your mail
  accounts and turn off the Use IDLE
  command feature. Next, go to the
  General section of Preferences, and
  set Check for New Mail to Every minute
  -- you can set a longer interval if you want, so long as you don't set it
  to Manual.
Now your mail alerts should play for
  every incoming message, but you will
  see your messages up to one minute
  later than you would with the IDLE
  mechanism.

A: I changed back and forth from classic view and the sound reappeared. Open Mail, select preferences, select view (check or uncheck to make it the opposite of what you have there). Close Mail...open and the sound returns.
You can then switch it back to the view you liked.


text:
Q: Skipping last column in r with read.csv I was on that post read.csv and skip last column in R but did not find my answer, and try to check directly in Answer ... but that's not the right way (thanks mjuarez for taking the time to get me back on track.
The original question was:

I have read several other posts about how to import csv files with
  read.csv but skipping specific columns. However, all the examples I
  have found had very few columns, and so it was easy to do something
  like:
 columnHeaders <- c("column1", "column2", "column_to_skip")
 columnClasses <- c("numeric", "numeric", "NULL")
 data <- read.csv(fileCSV, header = FALSE, sep = ",", col.names =
 columnHeaders, colClasses = columnClasses)

All answer were good, but does not work for what I entended to do. So I asked my self and other:

And in one function, does data <- read_csv(fileCSV)[,(ncol(data)-1)]
  could work?

I've tried in one line of R to get on data, all 5 of first 6 columns, so not the last one. To do so, I would like to use "-" in the number of column, do you think it's possible? How can I do that?
Thanks!

A: In base r it has to be 2 steps operation. Example:
> data <- read.csv("test12.csv")
> data
# 3 columns are returned
          a b c
1 1/02/2015 1 3
2 2/03/2015 2 4

# last column is excluded
> data[,-ncol(data)]
          a b
1 1/02/2015 1
2 2/03/2015 2

one cannot write data <- read.csv("test12.csv")[,-ncol(data)] in base r.
But if you know max number of columns in your csv (say 3 in my case) then one can write:
df <- read.csv("test12.csv")[,-3]
df
          a b
1 1/02/2015 1
2 2/03/2015 2

A: The right hand side of an assignment is processed first so this line from the question:
data <- read.csv(fileCSV)[,(ncol(data)-1)]

is trying to use data before it is defined.  Also note what the above is saying is to take only the 2nd last field.  To get all but the last field:
data <- read.csv(fileCSV)
data <- data[-ncol(data)]

If you know the name of the last field, say it is lastField, then this works and unlike the code above does not read the whole file and then remove the last field but rather only reads in fields other than the last.  Also it is only one line of code.
read.csv(fileCSV, colClasses = c(lastField = "NULL"))

If you don't know the name of the last field but you do know how many fields there are, say n, then either of these would work:
read.csv(fileCSV)[-n]

read.csv(fileCSV, colClasses = replace(rep(NA, n), n, "NULL"))

Another way to do it without first reading in the last field is to first read in the header and first line to calculate the number of fields (assuming that all records have the same number) and then re-read the file using that.
n <- ncol(read.csv(fileCSV, nrows = 1))

making use of one of the prior two statements involving n.

A: It's not possible in one line as the data variable is not yet initialized when you call it. So the command ncol(data) will trigger an error.
You would need to use two lines of code to first load your data into the data variable and then remove the last column by either using data[,-ncol(data)] or data[,1:(ncol(data)-1)].

A: Not a single function, but at least a single line, using dplyr (disclaimer: I never use dplyr or magrittr, so a more optimized solution must exist using these libraries)
library(dplyr)
dat = read.table(fileCSV) %>% select(., which(names(.) != names(.)[ncol(.)]))


text:
Q: how to pass all the dates between start date and end date for simple calendar gem i am using a booking system and i am using simple calendar gem ... i have a booking model which consist of start date and end date and the room ... now now if the customer selects to stay for 3 days and he select that same room i need to show in my simple calendar that he is staying from eg. 12-10-2016 13-10-2016 14-10-2016 and that particular room is selected.... but the problem here is it only shows the start date and the room booked for that day but it does not show the rest of the days rooms booked ...
how to i pass all the dates
class Booking < ApplicationRecord

alias_attribute :start_time, :start_date

has_many :booking_rooms, :dependent => :destroy, inverse_of: :booking
has_many :rooms, through: :booking_rooms
end

 class BookingRoom < ApplicationRecord
    belongs_to :room
    belongs_to :booking, inverse_of: :booking_rooms
 end

 class Room < ApplicationRecord

  has_many :booking_rooms
  has_many :bookings, through: :booking_rooms
end

A: You have the start_time alias:
alias_attribute :start_time, :start_date

You don't have end_time attribute, or alias, nor a setting for simple-calendar to override the default and so know what your end attribute is. Thus, simple-calendar thinks your Booking is a one-day event.

A: something like this should do the trick for u
 class BookingRoom < ApplicationRecord
 def start_time
   self.booking.start_date.to_datetime
 end

 def end_time
   self.booking.end_date.to_datetime
 end


text:
Q: Can I make a somewhat dynamic yes/no dropdown based on JSON file data? I have a JSON file that will be full of user information and in the admin page displaying all of the users I want a column for "Is Admin?" with a yes/no dropdown list. Can I make the list show Yes and have No as the other for admins and show No and have Yes as the other option for non-admins? The page is vanilla JavaScript as I'm still pretty new at this.
A sample of the user data is
{"id":"2",
"username":"david",
"password":"1234",
"user_id":"127",
"date":"2022-02-14 23:45:37",
"is_admin":"1"}

As simple as it is, the JavaScript to display the page is
function loadData(data) {

       let table = document.querySelector("#user-list");

       for (let i = 0; i < data.length; i++) {

           let row = `

           ${data[i].user_id}
           ${data[i].username}
           ${data[i].date}
           ${data[i].is_admin == 1 ? "Yes" : "No"}

           `;

           table.innerHTML += row;

       }

}

added screenshot for reference
The Admins yes/no should be
<select>
<option>Yes</option>
<option>No</option>
</select>

And the non admins should be
<select>
<option>No</option>
<option>Yes</option>
</option>

Also just realized the column names are wrong, but the Admin column is correct, other than not being a dropdown.

A: This is one way of doing it:

const data=[{"id":"1",
"username":"Harry",
"password":"5678",
"user_id":"112",
"date":"2022-02-11 13:45:37",
"is_admin":"0"},
{"id":"2",
"username":"david",
"password":"1234",
"user_id":"127",
"date":"2022-02-04 11:05:47",
"is_admin":"1"},
{"id":"3",
"username":"Molly",
"password":"9834",
"user_id":"187",
"date":"2022-01-21 08:15:00",
"is_admin":"0"}];

function loadData(data) {
document.querySelector("#user-list").innerHTML=data.map(d=>`

  ${d.user_id}
  ${d.username}
  ${d.date}
  <select><option value="1"${d.is_admin==1?" selected":""}>yes</option><option value="0"${d.is_admin==0?" selected":""}>no</option></select>
`).join("");
}

loadData(data);

id	name	date	admin

The callback function in the .map() call builds an HTML string for a
 element with all its content for each of the objects contained in the data-array. These individual HTML strings are the elements of the returned array and they are join("")-ed together at the end to become a single HTML string again.


text:
Q: How to convert a image (Texture2D) to tensor I have c# TensorFlow.NET working in Unity. But it using an image from the file system. I want to be able to use an image from memory (Texture2D).
I tried to follow some examples of people using TensorFlowSharp. But that didn't work.
What am I doing wrong?
Note: with both functions, I am using the same image. The image is 512x512. but the result of both pictures is different.
// Doesn't work
private NDArray FromTextureToNDArray(Texture2D texture) {
    Color32[] pixels = texture.GetPixels32();

    byte[] floatValues = new byte[(texture.width * texture.height) * 3];

    for (int i = 0; i < pixels.Length; i++) {
        var color = pixels[i];

        floatValues[i * 3] = color.r;
        floatValues[i * 3 + 1] = color.g;
        floatValues[i * 3 + 2] = color.b;
    }

    Shape shape = new Shape(1, texture.width, texture.height, 3);
    NDArray image = new NDArray(floatValues, shape);

    return image;
}

// Works
private NDArray ReadFromFile(string fileName) {
    var graph = new Graph().as_default();

    // Change image
    var file_reader = tf.read_file(fileName, "file_reader");
    var decodeJpeg = tf.image.decode_jpeg(file_reader, channels: 3, name: "DecodeJpeg");

    var casted = tf.cast(decodeJpeg, TF_DataType.TF_UINT8);
    var dims_expander = tf.expand_dims(casted, 0);
    using (var sess = tf.Session(graph)) {
        return sess.run(dims_expander);
    }
}

A: I ended up using this code from Shaqian: https://github.com/shaqian/TF-Unity/blob/master/TensorFlow/Utils.cs
Add this script to your project and then you could use it like this:
// Get image
byte[] imageData = Utils.DecodeTexture(texture, texture.width, texture.height, 0, Flip.VERTICAL);
Shape shape = new Shape(1, texture.width, texture.height, 3);
NDArray image = new NDArray(imageData, shape);

A: Use Barracuda as step in between.
var encoder = new Unity.Barracuda.TextureAsTensorData(your_2d_texture);


text:
Q: Clever way to find zero remainder with decreasing divisor I need to factorize a number starting from an initial divisor and going down by $1$ at each step. For example, starting from $99$ and decreasing it one by one
$$9779 = 99 \times 98 + 77$$
$$9779 = 98 \times 99 + 77$$
$$9779 = 97 \times 100 + 79$$
$$\vdots$$
$$9779 = 77 \times 127 + 0$$
I reach the zero remainder after $23$ steps.
I was wondering if there is a clever way to "predict" the first null remainder given the first division(s). I saw this question but mine has a particular pattern so maybe there is a better solution than brute force.
Thanks a lot


text:
Q: What do my first difference ACF/PACF show me? I am quite new to econometrics, so not sure how to intepret the following acf/pacf function on log financial time series after first differencing;

The level data showed a AR(1) process, how would I interpret this one?
thank you

A: if there are no pulses , level/step shifts , seasonal pulses ,local time trends ....white noise is my suggestion


text:
Q: Spring boot and Weblogic Log4j2CloudConfigLoggingSystem deployment issue I am updating application to avoid latest log4j vulnerability and rewriting our application to use logback instead of log4j. Local development I use tomcat and it works perfectly fine but when I deploy the same war file to weblogic I am getting the following error which never got using the same code before.
I am using latest springboot.
Error:
weblogic.application.ModuleException: java.lang.ClassNotFoundException: org.apache.logging.log4j.spring.boot.Log4j2CloudConfigLoggingSystem

Thanks for your help in advance.


text:
Q: Table Format in email body using Python Exchangelib library I am exploring in python to write email using exchangelib library with body content which contains a table content.
I have tried the code to add table in the body content.
    import pandas as pd
    import numpy as np
    from exchangelib import Account, Credentials, Message, Mailbox
    dfReport = pd.read_excel("test.xlsx")
    FilteredData = dfReport[dfReport["ColumnID"].str.contains('MyCharacter')]
    DataTable = pd.pivot_table(FilteredData ,index="Processor",values="TicketID",aggfunc=np.count_nonzero,margins=True)

    EmailAdd = 'XXX@YYY.Z'
    EmailPass = 'XXXXXX'
    MyAccount = Account(EmailAdd,credentials=Credentials(EmailAdd,EmailPass),autodiscover=True)

    MyMessage = Message(account=MyAccount, folder=MyAccount.sent,subject='Daily motivation', body=DataTable, to_recipients=[Mailbox(email_address='AAA@BBB.CC')])

    MyMessage.send_and_save()

below demonstration is expected in message body:
    Name    Count
    Item 1  53
    Item 2  38
    Item 3  123
    Item 4  175
    Item 5  212

but in outlook exchange email looks like this:
    Name
    Count
    Item 1         53
    Item 2                38
    Item 3     123
    Item 4    175
    Item 4            212

A: To properly control the format of your email body, you need to send the body as HTML.
The easiest is probably to convert the dataframe to a string, encapsulate it in <pre> tags and define a mono-spaced font.
You can read up on creating emails with an HTML body at https://github.com/ecederstrand/exchangelib#creating-updating-deleting-sending-and-moving


text:
Q: Regular expression between xml elements excluding a full element between similar elements I have the next elements:
    <Reference Include="Microsoft.AspNetCore.Sockets.Common.Http, Version=1.0.0.0, Culture=neutral, PublicKeyToken=adb9793829ddae60, processorArchitecture=MSIL">
      <HintPath>..\..\packages\LIB.XPTO.1.18.524.20\lib\net45\Microsoft.AspNetCore.Sockets.Common.Http.dll</HintPath>
    </Reference>
    <Reference Include="Microsoft.CSharp" />
    <Reference Include="Microsoft.Extensions.Configuration.Abstractions, Version=2.0.0.0, Culture=neutral, PublicKeyToken=adb9793829ddae60, processorArchitecture=MSIL">
      <HintPath>..\..\packages\LIB.XPTO.1.0.1.2\lib\net45\Microsoft.Extensions.Configuration.Abstractions.dll</HintPath>
    </Reference>

I want get all reference elements that contains the element HintPath or any other element, that is, I wan't that the <Reference Include="Microsoft.CSharp" /> don't be geted by my regex.
I'm using the partern /<Reference[\s\S]*?<\/Reference> but this can't exclude the <Reference Include="Microsoft.CSharp" />.
How to do that?
Edit
How result I want this on each match:
1:
<Reference Include="Microsoft.AspNetCore.Sockets.Common.Http, Version=1.0.0.0, Culture=neutral, PublicKeyToken=adb9793829ddae60, processorArchitecture=MSIL">
          <HintPath>..\..\packages\LIB.XPTO.1.18.524.20\lib\net45\Microsoft.AspNetCore.Sockets.Common.Http.dll</HintPath>
        </Reference>

2:
<Reference Include="Microsoft.Extensions.Configuration.Abstractions, Version=2.0.0.0, Culture=neutral, PublicKeyToken=adb9793829ddae60, processorArchitecture=MSIL">
          <HintPath>..\..\packages\LIB.XPTO.1.18.524.20\lib\net45\Microsoft.Extensions.Configuration.Abstractions.dll</HintPath>
        </Reference>

A: This should do the trick. Here's a demo.
<\/?Reference.*\/?>


text:
Q: How do you setup an Azure Pipeline such that it automatically updates and build after you push to github? I configured an azure pipeline with these sets:

*

*Create organization organization

*Create project project

*Go to repository tab and import my repository from my github account

*Click "build" and point azure at the azure-pipelines.yml file containing the build information.

What I want to happen is when I push to my github repository, github automatically pushes to azure to start the build. However this doesn't happen.
I have tried to associate my github account with my azure account by going to Settings > Boards > github connections, but this does not resolve my problem.
How do you setup an Azure Pipeline such that it automatically updates and build after you push to github?

A: Since you already have the yml build definition, you can configure your Pipeline to build and release continuously with CI/CD triggers.
Continuous integration (CI) triggers cause a pipeline to run whenever you push an update to the specified branches or you push specified tags.
You can control which branches get CI triggers with a simple syntax:
trigger:
- master
- releases/*

Next, Continuous deployment (CD) triggers allow you to create a release every time a new build artifact is available.

Here are some resources that explain these steps in greater detail:

*

*Azure DevOps Labs: GitHub integration with Azure Pipelines

*Azure DevOps YAML release pipeline


text:
Q: JavaFX GridPane - Configuring controls to grow and occupy all the available space Trying to achieve:

*

*Text Field 1 and Text Field 3 should occupy all the available free space

*Button 1 and Button 2 should have same width

Issue:
Text Field 1 and Text Field 3 are NOT occupying all the available free space (though they are growing once Label is completely displayed)
Here is the screen shot:

// Removed imports for brevity

public class GridPaneTest extends Application
{
  @Override
  public void start(Stage primaryStage)
  {
    primaryStage.setTitle("GridPane Test");

    GridPane gridPane = new GridPane();
    // gridPane.setGridLinesVisible(true);
    gridPane.setHgap(5);
    gridPane.setVgap(5);
    gridPane.setPadding(new Insets(5));

    TextField tf1 = new TextField("Text Field 1");
    GridPane.setHgrow(tf1, Priority.ALWAYS);
    gridPane.add(tf1, 0, 0);
    TextField tf2 = new TextField("Text Field 2");
    GridPane.setHgrow(tf2, Priority.NEVER);
    gridPane.add(tf2, 1, 0);
    Button button1 = new Button("Button 1");
    button1.setMaxWidth(140);
    GridPane.setHgrow(button1, Priority.NEVER);
    GridPane.setHalignment(button1, HPos.RIGHT);
    gridPane.add(button1, 2, 0);

    TextField tf3 = new TextField("Text Field 3");
    GridPane.setHgrow(tf3, Priority.ALWAYS);
    gridPane.add(tf3, 0, 1, 2, 1);
    Button button2 = new Button("Button 2 Button 2");
    button2.setMaxWidth(140);
    GridPane.setHgrow(button2, Priority.NEVER);
    GridPane.setHalignment(button2, HPos.RIGHT);
    gridPane.add(button2, 2, 1);

    Label label1 = new Label(
        "Label 1 Label 1 Label 1 Label 1 Label 1 Label 1 Label 1 Label 1 Label 1 Label 1 Label 1");
    GridPane.setHgrow(label1, Priority.ALWAYS);
    gridPane.add(label1, 0, 2, 3, 1);

    primaryStage.setScene(new Scene(gridPane));

    primaryStage.show();
  }

  public static void main(String[] args)
  {
    launch(args);
  }
}

A: According to GridPane documentation

if an application needs to explicitly control the size of rows or columns, it may do so by adding RowConstraints and ColumnConstraints objects to specify those metrics

gridPane.getColumnConstraints()
  .addAll(new ColumnConstraints(), new ColumnConstraints(),
    new ColumnConstraints(140) /* Control the third column size */);

Screen shot:


text:
Q: Remove autop from wordpress html widgets I'm getting unwanted  tags in my html code when I put it in an html widget block. I tried below methods but none of the seem to be working.
remove_filter('the_content', 'wpautop');
remove_filter('the_excerpt', 'wpautop');
remove_filter('widget_text_content', 'wpautop');
remove_filter('widget_custom_html_content', 'wpautop');

I entered this html code in the html widget box

text

And I get the below code after the widgets are saved. (There are some "p" & "br" tags which isn't needed.)

text

(Please click and see the screenshot attached) Screenshot
Please help?
Thanks!

A: autops are auto generated html
 tags around the wordpress content. If the "remove_filter" solution didn't work for you, then you could try something like this:
add_filter('widget_text_content', 'your_theme_removing_autop', 999);
add_filter('widget_custom_html_content', 'your_theme_removing_autop', 999);

function your_theme_removing_autop($content)
{
  $content = str_replace(['
', '
'], ['', ''], $content);
  return $content;
}

Tested and works on my end. Let me know if you could get it to work too!


text:
Q: mongodb $text with $near Ok, my goal is to perform a text search on my collection and then filter those results to ensure they fall within my "doughnut" geometry.  Example from mongo site:

Here's the tough part.  Mongo's documentation confirms that today you cannot combine the wonderfulness of $text and $near:

You cannot combine the $near operator, which requires a special geospatial index, with a query operator or command that uses a different type of special index. For example you cannot combine $near with the $text query.

Sooo.. Here is what I'm doing today.  Notice my current method does not achieve a "doughnut" geometry (it's is just a circle growing in diameter which return duplicate results as the user "zooms" out on the map).
    var vendorResponse = JSON.parse(body);
    var vendorPosts = vendorResponse.postings;

    //Get the location of the user
    var userLat = req.query.lat;
    var userLong = req.query.long;

    //Get the item that furthest away from the user
    var furthestitem = sortedVendorPosts[sortedVendorPosts.length - 1];

    //Calculate the radius of the area
    var radius = Math.sqrt( Math.pow((userLat-furthestitem.location.lat), 2) + Math.pow((userLong-furthestitem.location.long), 2) )

    PostModel.find({
        $text: { $search: heading, $language: 'english' },
        $or: mongoCategories,
        coordinates :
             { $geoWithin :
                 {
                     $centerSphere : [ [ userLong, userLat ] , radius ]
                 }
             }
        } , { score: {
                $meta: "textScore"
            }
        }, function (err, results) {

        });

I've attempted to use mongos $geoIntersects methods but I'm banging my head against the wall to formulate this query.  Detailed examples of how to workaround mongos current limitation would be a god-send!  Thanks guys!

A: Seems there are a couple solutions in my case scenario:

*

*Use Mongo Connect and integrate something like solr or elasticsearch

*Use Mongo's $in method to perform 'nested queries'.. this requires two queries to db

*Use Mongo's $regex method (as others described and I've demonstrated below).
PostModel.find({
    coordinates: { $near: {
        $geometry: { type: "Point", coordinates: [ userLong , userLat ] },
        $maxDistance: maxDistance,
        $minDistance: minDistance
        }
    },
    $or: mongoCategories,
    term: { "$regex": term, "$options": 'i' }
}, function (err, results) {
    //systematic error. Redirect user so they can report error.
    if (err) {
        console.log(err);
        callback(body);
    // if no result found
    } else if (!results) {
        callback(results);
    } else if (results) {
        callback(results);
    }
});

I've reached out to the Mongodb team to see when we will be able to perform searches across multiple indexes.  Hope this is helpful!


text:
Q: Neo4j cypher time interval histogram query of time tree I would like to build an histogram on time series stored as time tree in neo4j.
The data structures are event done by a user each has timestamp, say user purchases category.
What I need to have is the number of browsing on each category by each user between start and end time, with interval of (1 second to days)
My model feats graph db very nicely, as I read neo4j documentation I could not find any way to do it in one query, and I'm afraid that calling for each user would be very slow.

I am aware to cypher capabilities, but I have no idea how to create such query.
I am looking for something like this (not working)
MATCH startPath=(root)-[:`2010`]->()-[:`12`]->()-[:`31`]->(startLeaf),
endPath=(root)-[:`2011`]->()-[:`01`]->()-[:`03`]->(endLeaf),
valuePath=(startLeaf)-[:NEXT*0..]->(middle)-[:NEXT*0..]->(endLeaf),
vals=(middle)-[:VALUE]->(event)
WHERE root.name = 'Root'
RETURN event.name, count(*)
ORDER BY event.name ASC
GROUP BY event.timestamp % 1000*60*10 // 10 minutes histogram bar

Then I'd like to have a report, for how many users browse to each site category:
0-9 news 5, commerce 3 ; 10-19 news 6, commerce 19; 1 20-29 news 2, commerce 8;
Any idea if it is optional with neo4j time tree model?
if so how? :-)

A: Does this work?
MATCH
  startPath=(root)-[:`2010`]->()-[:`12`]->()-[:`31`]->(startLeaf),
  endPath=(root)-[:`2011`]->()-[:`01`]->()-[:`03`]->(endLeaf),
  valuePath=(startLeaf)-[:NEXT*0..]->(middle)-[:NEXT*0..]->(endLeaf),
  vals=(middle)-[:VALUE]->(event)
WHERE root.name = 'Root'
RETURN event.name, event.timestamp % 1000*60*10 AS slice, count(*)
ORDER BY slice ASC

Basically I just added the event.timestamp % 1000*60*10 into the return so that Neo4j will use that as a grouping criteria


text:
Q: How to find gradient of multiple variables at a given point? I need to find gradient of function (x**2+y) at point [2, 4].
import numdifftools as nd
import sympy as sym
from sympy import *

x, y = sym.symbols('x y')

def rosen(x, y):
    return (x**2 + y)
grad = nd.Gradient(rosen)([2, 4])
print("Gradient of is ", grad)

TypeError: rosen() missing 1 required positional argument: 'y'

A: Argument to function passed to nd.Gradient must be an array.
import numdifftools as nd

def rosen(xy):
    return (xy[0]**2 + xy[1])

grad = nd.Gradient(rosen)([2, 4])
print("Gradient of is ", grad)


text:
Q: Minimum path cost through a line segment Given point $A$, point $B$, and a line (segment), I am trying to find a point $I$ on the line so that the total cost of a path from $A$ to $I$ and then to $B$ is minimal. I can calculate this in a simple case when I am directly summing the Euclidean distances. However, I am not able to find a solution when the distance from $A$ to $I$ is weighted.
I have tried:

*

*I have defined the point on the line (segment) as: $I = P + D  t$, where $P$ is the origin of the line, $D$ is its direction, and $t \in [0,1]$.

*I am trying to minimize $cost = weight . Dist(A, I) + Dist(I, B)$ with respect to $t$, where $Dist$ is Euclidean distance. For 2D the cost to minimize is: $cost=weight.\sqrt{(A_x-I_x)^2+(A_x-I_x)^2}+\sqrt{(B_x-I_x)^2+(B_x-I_x)^2}$

*Calculating a differential of the cost gives an equation that I am not able to solve (using wxMaxima).
$$
0=
\frac{-2 D_y(-D_y t-P_y+A_y)-2 D_x (-D_x t-P_x+A_x)).weight}
{2\sqrt{(-D_y t-P_y+A_y)^2+(-D_x t-P_x+A_x)^2}}
+
\frac{-2 D_y (-D_y t-P_y+B_y)-2 D_x (-D_x t-P_x+B_x)}
{2\sqrt{(-D_y t-P_y+B_y)^2+(-D_x t-P_x+B_x)^2}}
$$
Is there any formula to find the point $I$?

A: Let $y=ax+b$ is the equation of the segment. Then the cost function is $f(x)=w\sqrt{(x_A-x)^2+(y_A-ax-b)^2}+\sqrt{(x_B-x)^2+(y_B-ax-b)^2}$. Taking the derivative: $f'(x)=-w\frac{x_A-x+a(y_a-ax-b)}{\sqrt{(x_A-x)^2+(y_A-ax-b)^2}}-\frac{x_B-x+a(y_B-ax-b)}{\sqrt{(x_B-x)^2+(y_B-ax-b)^2}}$. Solving $f'(x)=0$ will lead to $$w(x(1-a^2)+x_A+ay_A-ab)\sqrt{(x_B-x)^2+(y_B-ax-b)^2}=(x(a^2-1)-x_B-ay_B+ab)\sqrt{(x_A-x)^2+(y_A-ax-b)^2}$$ To solve the last equation, square both parts  which will lead to quartic equation for $x$. I do not think you'll be able to get a nice formula for it but it's definitely solvable.


text:
Q: latex compile error level Thinking of classical programming languages, many compilers support error levels.
Error levels let one specify the severity at which the compile process halts.
This is very handy. Once a project comes to an end, I typically enable a very pedantic error level, such that I can make sure that what I contribute is really free of all errors.
I am wondering is there something similar for Latex?
To give an example, I would find it desirable if there was a flag that halts compilation on undefined references, rather than having to forge my entire document for ???.
Note
I ended up using the accepted answer. Since references aren't present on the first run, I added a \pedantic flag to my Makefile.
$(FILE)_pedantic.pdf: *.tex
    pdflatex -synctex=1 -shell-escape "\def\pedantic{0} \input{$(FILE).tex}"
    pdflatex -synctex=1 -shell-escape "\def\pedantic{0} \input{$(FILE).tex}"
    bibtex $(FILE)
    makeglossaries $(FILE)
    pdflatex -synctex=1 -shell-escape "\def\pedantic{0} \input{$(FILE).tex}"
    pdflatex -synctex=1 -shell-escape "\def\pedantic{1} \input{$(FILE).tex}"

My root.tex file then sets
\if\pedantic1
   \MakeWarningsErrors
\fi

as suggested by the author of the accepted answer.

A: A simple solution to this problem is to redefine LaTeX's \GenericWarning macro with the more severe \GenericError:
\documentclass{article}

\newcommand\MakeWarningsErrors{%
    \renewcommand\GenericWarning[2]{%
        \GenericError{##1}{##2}{}{}%
    }%
}

\begin{document}
See section \ref{foo} ...

\MakeWarningsErrors
... and section \ref{bar}.
\end{document}

LaTeX will then report the first warning as normal but stop compilation on the second one:
LaTeX Warning: Reference `foo' on page 1 undefined on input line 11.

! LaTeX Warning: Reference `bar' on page 1 undefined.

Type  H <return>  for immediate help.


text:
Q: Loading a fixed width format file into R with different row / variable lengths I am attempting to load the following data into R - using read.fwf:
sample of data
20100116600000100911600000014000006733839
20100116600000100912100000019600005648935
20100116600000100929100000000210000080787
20100116600000100980400000000090000000000
3010011660000010070031144300661101000
401001166000001000000001001
1010011660000020016041116664001338615001338115150001000000000000000000000000010001000100000000000000000000162002117592200001051
20100116600000200036300000001000005692222
however the first number in the row indicates which variables are coded in that line and they have different lengths so the 'widths' vector for lines starting with 1 is different from the 'widths' vector for lines starting with 2 and so on.
Is there a way I can do this without having to read the data in four times? (Note that each case has differing numbers of rows too)
Thank you, Maria


text:
Q: How do I access My GRails Views pages in Browser In GRails My views page locations are in C:\Program Files\Apache Software Foundation\Tomcat 7.0\webapps\myapp\WEB-INF\grails-app\views\index.gsp
I used tomcat 7.0 server I deployed my application as .war extension in webapps
When I try to access my index.gsp page from browser
(URL is: localhost:8080/myapp/index.gsp)
it is showing the following error
HTTP Status 404 - "/index.gsp" not found.

A: check your urlMapping.groovy, it should be
"/"(view:"/index")
    "500"(view:'/error')
if this is same than hit just  localhost:8080/myapp
it should work


text:
Q: Работа скрипта в несколько потоков Как можно организовать работу PHP скрипта в несколько потоков?
A: ХАК: через сокеты, подзапросами на $_SERVER['PHP_SELF'] без ожидания ответа либо с синхронизацией (например, "echo serialize($result);" раз в секунду).
A: Никак, если речь об одном скрипте. Если о нескольких, то с помощью Exec().
A: Потоки PHP не поддерживает, т.ч. никак.
Однако в *nix возможно создать и взаимодействовать между несколькими процессами посредством разделяемой памяти. Хороший пример как управлять процессами, можно посмотреть в компоненте Zend Framework ZendX_Console_Process_Unix.


text:
Q: Execution is overlapped nodes created by docker selenium grid and distribution with testNG data provider how avoid this? I am using Docker selenium Grid.
Created multiple nodes and Success with launching my scripts in single node but when i use multiple nodes my execution statements has been passes to recent activated node.
Ex: I have login verification and this is managed with a dataprovider, and need to check run the test method for 6 user credentials.
In current situation up to the browser launch is running as expected i mean 6 nodes launched the browser but the first launched node is taking all the user credentials, In user name it is expected to type 'User001' but it is typing 'User001User002User003...'.
Please provide a solution for this...
Find the attached screen how i launching hub and nodes.


text:
Q: Deserialising JSON made up of various models C# I'm trying to work out how to deserialise a JSON response that can be made up of single or multiple models, so for instance, I have the following URL and Response from that endpoint:
https://api.site.com/products?query=fruit
Which would return something such as this:
{
    "fruit": [{ ... },{ ... }]
}

"Fruit" could be anything, but as an alternative, you can also do this:
https://api.site.com/products?query=fruit,pies
{
    "fruit": [{ ... }, { ... }],
    "pies": [{ ... }, { ... }]
}

So I know how to handle just one of the "selections" provided at a time, however how do I go about deserialising the response when there can be 2 separate models in the same response?

A: In case you know the json model before hand (also called data contract), then you can create a dedicated class. So, for the above scenario, the class would be
public class AnyClassName
{
    public List<Fruit> Fruit { get; set; }
    public List<Pie> Pie { get; set; }
}

And then use
Newtonsoft.Json.JsonConvert.DeserializeObject<AnyClassName>(jsonString)

In case you are not aware of the data-contract, then use
Newtonsoft.Json.JsonConvert.DeserializeObject(jsonString)

In this case you have to do a lot of coding to probe for the existence of an element and extract the value.


text:
Q: Can't Install pdfedit lubuntu 14.04 i386 I tried installing pdfedit on my machine can't complete the installation.
The screen is giving the following infos, I could not understand. I am new a new user of Lubuntu and still feeling my way around but learning in a slow pace.
~$ FILE=`mktemp`; wget http://us.archive.ubuntu.com/ubuntu/pool/universe/p/pdfedit/pdfedit_0.4.5-2_i386.deb -qO $FILE && sudo dpkg -i $FILE; rm $FILE
Selecting previously unselected package pdfedit.
(Reading database ... 243246 files and directories currently installed.)
Preparing to unpack /tmp/tmp.wsQUAOPX4D ...
Unpacking pdfedit (0.4.5-2) ...
dpkg: dependency problems prevent configuration of pdfedit:
 pdfedit depends on libqt3-mt (>= 3:3.3.8-b); however:
  Package libqt3-mt is not installed.

dpkg: error processing package pdfedit (--install):
 dependency problems - leaving unconfigured
Processing triggers for man-db (2.6.7.1-1ubuntu1) ...
Processing triggers for desktop-file-utils (0.22-1ubuntu1) ...
Processing triggers for mime-support (3.54ubuntu1) ...
Errors were encountered while processing:
 pdfedit

A: try executing
FILE='mktemp'; wget http://mirrors.kernel.org/ubuntu/pool/main/q/qt-x11-free/libqt3-mt_3.3.8-b-8ubuntu3_i386.deb -qO $FILE && sudo dpkg -i $FILE; rm $FILE
then try installing pdfedit again


text:
Q: Recursively remove object from nested array i've got array like this. Unlimited number of nesting possible
const myArray = [
  {
   id: 1,
   children: [
              {
                id: 3,
                children: []
              }
             ]
  },
  {
   id: 2, children: []
  }
]

Please, help me to remove any object by id and return new array without it.

A: Using array methods and recursive function:

function fn(arr, id) {
  return arr
    .filter((el) => el.id !== id)
    .map((el) => {
      if (!el.children || !Array.isArray(el.children)) return el;
      el.children = fn(el.children, id);
      return el;
    });
}

const myArray = [
  {
    id: 1,
    children: [
      {
        id: 3,
        children: [],
      },
    ],
  },
  {
    id: 2,
    children: [],
  },
];

console.log(fn(myArray,1))
console.log(fn(myArray,2))
console.log(fn(myArray,3))

A: The recursiveRemove  function will recursively remove the elements from the array and return the new list.
The map function creates copy of the items in the array, you can remove the map if you do not need to retain the original array's sanity.
function recursiveRemove ( list, id ) {
    return list.map ( item => { return {...item} }).filter ( item => {
        if ( 'children' in item ) {
            item.children = recursiveRemove ( item.children, id );
        }
        return item.id !== id;
    });
}
const test1 = recursiveRemove ( myArray, 1);
const test2 = recursiveRemove ( myArray, 2);
const test3 = recursiveRemove ( myArray, 3);

A: function removeFromArrayOfObj (array, idToRemove) {
  for (const [i, e] of array.entries()) {
    if (e.id === idToRemove) {
     array.splice(i, 1)
     continue
    }
   if (e.children) {
     removeFromArrayOfObj(e.children, idToRemove)
    }
 }
 return array
}

A: You could destructure the object and take id and children out of the object. Then get a new object with the rest of the former object and map the children.

const
    withoutId = ({ id, children, ...o }) => ({ ...o, children: children.map(withoutId) }),
    array = [{ id: 1, children: [{ id: 3, children: [] }] }, { id: 2, children: [] }],
    without = array.map(withoutId);

console.log(without);

A: It makes sense to me to separate out the recursive traversal and filtering from the actual details of removing a certain id.  So I would write a more generic filterDeep function which keeps only those objects where a predicate is true, recursing into children nodes.
Then we can supply a predicate to it that checks whether an item matches a specific id.  Or rather, since we're removing those that match, our predicate actually checks whether our node doesn't match the id.
This is an implementation of that idea:

const filterDeep = (pred) => (xs) =>
  xs .flatMap (x => pred (x)
    ? [{... x, children: filterDeep (pred) (x .children || [])}]
    : []
  )

const removeId = (id) =>
  filterDeep (x => x.id !== id)

const myArray = [{id: 1, children: [{id: 3, children: []}]}, {id: 2, children: []}]

console .log (removeId (1) (myArray))
console .log (removeId (2) (myArray))
console .log (removeId (3) (myArray))
console .log (removeId (42) (myArray))
.as-console-wrapper {min-height: 100% !important; top: 0}

This will include a children node even if the original didn't have one.  If we wanted to include it only if there was one to begin with we could change it to something like this:
const filterDeep = (pred) => (xs) =>
  xs .flatMap (x => pred (x)
    ? [{
        ... x,
        ... (x.children ? {children: filterDeep (pred) (x .children || [])} : {})
      }]
    : []
  )

Or with a little more sophistication, we could choose to include a children node only when it's available in the parent and the results are non-empty.  That's left as an exercise for the reader.  :-)

A: Ah, homework problems.

*

*write 'kill_entries_with_id(child_array, id_to_kill)'.  For each element of the child array, it should del the element if its id matches.  Otherwise, it should recursively call itself with the element's children.

*Note that you should walk the array backwards by index so you don't have to worry about deleting elements mucking up your loop.  Consider list(range(10,-1,-1)