text:
Q: What is the relationship between different definitions of Fourier transform? I always see various definitions of Fourier transform. A standard form is:
$$\hat{f}(\xi)=\int_{\mathbb{R}^d}f(x)e^{-2\pi ix\cdot\xi}dx$$
and its attached inversion is
$$f(x)=\int_{\mathbb{R}^d}\hat{f}(\xi)e^{2\pi ix\cdot\xi}d\xi$$
Another form is like this:
$$\hat{f}(\xi)=\int_{\mathbb{R}^d}f(x)e^{-ix\cdot\xi}dx$$
and the inversion formula is
$$f(x)=\frac{1}{(2\pi)^d}\int_{\mathbb{R}^d}\hat{f}(\xi)e^{ix\cdot\xi}d\xi$$
I believe they are actually the same and I try to find their relationship.
An article on ProofWiki says

There exist several slightly different definitions of the Fourier transform which are commonly used; they differ in the choice of the constant 2π inside the exponential and/or a multiplicative constant before the integral.
  Their properties are essentially the same, and by a simple change of variable one can always translate statements using one of the definitions into statements using another one.

So I tried change of variable:
$$ \int_{\mathbb{R}^d}f(x)e^{-ix\cdot\xi}dx=(2\pi)^d\int_{\mathbb{R}^d}f(2\pi x)e^{-2\pi ix\cdot\xi}dx$$
But then since the variable in $f$ is $2\pi ix$ rather than $x$, I don't know how to deal with it.
Can you please help? Thank you.
EDIT: According to James Edward Lewis, the change of variable should be $2\pi x$. I revised this.

A: The difference between the first and the second form is in the definition of $\xi$ (so you should change the name of the variables correspondingly). Let me introduce the new notation $\tilde\xi$ and $\tilde f(\tilde \xi)$ such that the confusion is (hopefully) lifted.
You want to proof that
$$ \hat{f}(\xi)=\int_{\mathbb{R}^d}f(x)e^{-2\pi ix\cdot\xi}dx \qquad
f(x)=\int_{\mathbb{R}^d}\hat{f}(\xi)e^{2\pi ix\cdot\xi}d\xi$$
is equivalent to
$$ \tilde{f}(\tilde\xi)=\int_{\mathbb{R}^d}f(x)e^{-ix\cdot\tilde\xi}dx \qquad
f(x)=\frac{1}{(2\pi)^d}\int_{\mathbb{R}^d}\tilde{f}(\tilde\xi)e^{ix\cdot\tilde\xi}d\tilde\xi.$$
Let's take the first form as given and try to derive the second form. The Fourier transform is by definition the same with $\tilde\xi = 2\pi \xi$ and $\tilde f(\tilde \xi) = \hat{f} (\xi)$. For the inversion formula, we have to work a bit harder (and use substitution).
$$f(x)=\frac{1}{(2\pi)^d}\int_{\mathbb{R}^d}\tilde{f}(\tilde\xi)e^{ix\cdot\tilde\xi}d\tilde\xi =
\frac{1}{(2\pi)^d}\int_{\mathbb{R}^d}\tilde{f}(\tilde\xi)e^{2\pi ix\cdot\xi}d(2 \pi \xi)
= \int_{\mathbb{R}^d}\hat{f}(\xi)e^{2\pi ix\cdot\tilde\xi}d\xi.$$

A: The correct change of variable is x=2pi*X, and in the end you actually will be using a different function; to put it another way, the first form of Fourier transform on a function f is the same as the second form on its pullback by the linear map consisting of multiplication by 2pi, divided by (2pi)^d.
The properties are essentially the same, but the transforms are not exactly the same; the trade-off is between simplicity and asymmetry of inversion.

A: Sorry Fabian, but i think James Edward Lewis II is absolutely right with his Statement, that $\tilde f(\tilde \xi) \neq \hat{f} (\xi)$ and there is an easy way of getting all definition of the Fourier transform:

*

*My favourite definition: $$  \hat f_1(k_1)=\int_{\mathbb{R}}f_1(x_1)e^{-i2\pi k_1 x_1}dx_1 \hspace{10mm} f_1(x_1)=\int_{\mathbb{R}}\hat f_1(k_1)e^{-i2\pi k_1 x_1}dk_1 \hspace{10mm} (1)$$

*Let $k_2=2\pi k_1$, so we can define for this new variable also the corresponding $\hat f_2(k_2)$, which is also a Fourier-transform of $f_1(x_1)$ with just other units, "radians/meter" if you like, in contrast to $\hat f_1(k_1)$, which has "circles/meter". The function $\hat f_2(k_2)$ is just a bit stretched, but with invariant area, therefore:
$$ \hat f_2(k_2)|dk_2|=\hat f_1(k_1)|dk_1| \hspace{5mm} => \hspace{5mm} \hat f_2(k_2) = \hat f_1(k_1) \left|\frac{dk_1}{dk_2}\right|=\frac{1}{2\pi}\hat f_1(k_1)$$
$$=> \hspace{5mm}\hat f_2(k_2)=\frac{1}{2\pi}\int_{\mathbb{R}}f_1(x_1)e^{-ik_2 x_1}dx_1 \hspace{10mm}f_1(x_1)=\int_{\mathbb{R}}\hat f_2(k_2)e^{-ik_2 x_1}dk_2 \hspace{5mm}(2)$$

*Let $x_3 = 2\pi x_1$, and with the same argument, we have a new $f_3(x_3)$ with
$$ f_3(x_3) = f_1(x_1) \left|\frac{dx_1}{dx_3}\right|=\frac{1}{2\pi} f_1(x_1)$$
$$=> \hspace{5mm}\hat f_1(k_1)=\int_{\mathbb{R}}f_3(x_3)e^{-ik_1 x_3}dx_3 \hspace{5mm}f_3(x_3)=\frac{1}{2\pi}\int_{\mathbb{R}}\hat f_1(k_1)e^{-ik_1 x_3}dk_1 \hspace{5mm}(3)$$

*Let $x_4 = \sqrt{2\pi} x_1$ and $k_4 = \sqrt{2\pi} k_1$, therefore we have a new function $f_4(x_4)$ and a new function $\hat f_4(k_4)$ with
$$ f_4(x_4) = f_1(x_1) \left|\frac{dx_1}{dx_4}\right|=\frac{1}{\sqrt{2\pi}} f_1(x_1)$$
$$ \hat f_4(k_4) = \hat f_1(k_1) \left|\frac{dk_1}{dk_4}\right|=\frac{1}{\sqrt{2\pi}} \hat f_1(k_1)$$
$$=> \hspace{5mm}\hat f_4(k_4)=\frac{1}{\sqrt{2\pi}}\int_{\mathbb{R}}f_4(x_4)e^{-ik_4 x_4}dx_4 \hspace{5mm}f_4(x_4)=\frac{1}{\sqrt{2\pi}}\int_{\mathbb{R}}\hat f_4(k_4)e^{-ik_4 x_4}dk_4 \hspace{5mm}(4)$$
The first definition of the Fourier transform is much more symmetric and pretty, and therefore i want to show you a little math joke:
$$ \hat f(k)=\int_{\mathbb{R}}f(x)e^{-i2\pi k x}dx \stackrel{?}{=} \int_{\mathbb{R}}f(x)\left(e^{-i2\pi}\right)^{k x}dx = \int_{\mathbb{R}}f(x)1^{k x}dx = \hat f(0)$$
Does anyone get it?


text:
Q: Windows 7 not genuine issue I have an HP mini 210 netbook which the OS is Windows 7 starter OEM. Yesterday, there was the pop up that said the Windows is not genuine anymore. As I remember before this thing happened, there's an update which is Windows update that prompted me there are updates for my computer.
My questions is:

*

*Do the OEM products have an expiry date?

*How do you reactivate the Windows / how do you retrieve the Windows product key?

A: Are you sure the copy of Windows you are using is genuine? If yes, did you change any hardware? This could cause the operating system to think it's in a different computer and report it as pirated. Here's a thread stating that changing the motherboard on an OEM is a violation of the agreement so in this situation it really wouldn't be genuine anymore.
Since the product key is encrypted and stored in the registry, you need a program to retrieve it. Belarc or Magical Jelly Bean Keyfinder can do it.

A: This sounds very unusual. Be careful this isn't a fake validation attempt which could result in a virus or malware being installed on your computer. Do not click anything or enter any information on this popup window until you know for sure.
Update and run a complete scan with your antivirus software. Then run a malware scanner like SUPERAntiSpyware or Malwarebytes (both are free).
Then to verify your Windows is Genuine, go to Genuine Windows Validation and follow the instructions.

A: *

*No, Windows license keys do not expire.

*Your Windows is already activated. Microsoft is telling you that the
key currently in use on the netbook is not valid. If you did not buy
the netbook new, it's possible a key generator was used, and you'll
have to buy a new, valid, key.

If you really want to try "re-activating", you can try re-entering the existing key in the Windows Activation dialog, most easily found on the System Properties dialog (I find to easiest to just right-click on the Computer link on the Start Menu and select Properties from the context menu).
The product key is found on the COA (Certificate of Authenticity) on the bottom of the netbook. If that is missing you could always try Magical Jelly Bean, but normally the OEM key used on the HP discs is not the same key as on the COA and will not activate manually.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to fix sound output devices not showing up on Ubuntu 16.04? I am running Ubuntu 16.04 LTS. On recent startup only a Dummy Output shows up under sound Output Devices.
This has been happening for a while but usually the command killall pulseaudio && pulseaudio --start was always able to fix the problem.
Not so any more. In fact the soundcards don't seem to be found at all by the system:
aplay -l

returns

aplay: device_list:268: no soundcards found...

Any thoughts on what I should do?
EDIT:
lspci -nnk | grep -A2 Audio returns nothing
pactl list short sinks returns 0 auto_null   module-null-sink.c  s16le 2ch 44100Hz   SUSPENDED
alsamixer returns
cannot open mixer: No such file or directory


text:
Q: create a single colored symbol with a newcommand I have created a symbol with
\newcommand{\redx}[1][x]{\color{red}{\boldsymbol{#1}}}

This correctly colors the symbol red, but annoyingly it also colors the symbols after it red. How do I ensure only one symbol is colored.

A: Hope that this will help you
\documentclass{article}
\usepackage{color}

\newcommand{\redx}[1]{{\color{red}#1}}

\begin{document}

    this is in \redx{red}.this is in black.

\end{document}

Its output is

A: The command \color{red} is a declaration. It tells LaTeX to start typesetting in red and bracing the following text does not delimit the red text; only a brace or other grouping before the declaration will define a scope for the declaration.
You want \textcolor{red}{whatever} which, despite the name, also works in math mode and continues math mode for its second argument.


text:
Q: Lookup, retrieve and merge values from SQL, based on entered information everyone.
I am trying to build a project to record production faults by test operatives.
I have a code which will retrieve operator ID's that worked on that specific job.

CODE:
Private Sub TextBox1_Leave(sender As Object, e As EventArgs) Handles TextBox1.Leave
        Dim sqlconn As New SqlClient.SqlConnection
        Dim CurSel As String = TextBox1.Text

        sqlconn.ConnectionString = "server = ESS/SQL;" &
       "Database = Maindb;integrated security=true"

        sqlconn.Open()

        Dim CurList3 As New SqlClient.SqlCommand("SELECT Employee_Clock_No FROM wip.WIP_Book_Trans WHERE WO_No ='" & CurSel & "'", sqlconn)

        Dim dt3 As New DataTable()
        dt3.Load(CurList3.ExecuteReader)

        DataGridView1.DataSource = dt3

        sqlconn.Close()
    End Sub

What I am trying to achieve is to add a second column to the DataGridView that will theoretically lookup and return the Employee name beside their code from a different SQL table
See image below Employee_Clock_No -> Employee_Name

Thanks in advance.
SQL to return datatable in datagridview and further return information to a different column based on values in the first column.

A: Welcome to the wonderful world of JOINs. These are a mainstay of SQL, so get comfortable with them. Also, you NEED to use parameterized queries rather than string concatenation to include user data with the SQL statement. Anything else will eventually get you in big trouble, usually sooner than later.
Private Const connectionString As String = "server = ESS/SQL;Database = Maindb;integrated security=true"

Private Sub TextBox1_Leave(sender As Object, e As EventArgs) Handles TextBox1.Leave
    Dim SQL As String = "
        SELECT bt.Employee_Clock_No, ed.Employee_Name
        FROM wip.WIP_Book_Trans bt
        INNER JOIN personnel.Employee_Details ed ON ed.Employee_Clock_No = bt.Employee_Clock_No
        WHERE bt.WO_No = @WorkOrder"

    Dim dt As New DataTable()
    Using conn As New SqlClient.SqlConnection(connectionString), _
          cmd  As New SqlClient.SqlCommand(SQL, conn)

        cmd.Parameters.Add("@WorkOrder", SqlDbType.VarChar, 8).Value = TextBox1.Text

        conn.Open()
        dt.Load(cmd.ExecuteReader())
    End Using
    DataGridView1.DataSource = dt

End Sub

Adjust accordingly if the WO_No column is really an integer.
Also, note the Using block. This handles closing the connection for, and does it in a much safer way than calling .Close() yourself. As it was, if an exception was thrown (which, given the lack of query parameters, can happen at any time) the .Close() line would never run, leaving the open connection hanging. Do that enough, and you can lock everyone out of the database.


text:
Q: How to recode missing genotype code is " '-' " in the ped file of plink I'm trying to impute genotype data from the public reference panels but my files fail the file sanity check on Sanger Imputation server and it gives the following error:
failed sanity check :

    of Non-ACGTN alternate allele at 1:4635556 .. REF_SEQ:'(null)' vs VCF:'-'

I have tried fixing this in the plink with the following command ./plink --bfile chr1 --recode vcf --out chr1_vcf --missing-genotype -
but then it gives error  Underscore(s) present in sample IDs.
--recode vcf to chr1_vcf.vcf ... done.
but I still see '_' in the new coded file.
I would appreciate any help, suggestions and comments.
Thanks
Jasdeep

A: You will have to replace _ with a different character in your PLINK files before running your code.
See below from PLINK manual
When using --recode vcf, sample IDs are formed by merging the FID and IID and placing an underscore between them. When the FID or IID already contains an underscore, this may make it difficult to reconstruct them from the VCF file; you may want to replace underscores with a different character in PLINK files (Unix tr is handy here).


text:
Q: Wildfly remotely access administration console doesnt work I am new to WildFly/JBOSS. I am using WildFly 8.2.0. I have installed it as a service on Linux using an installation script from http://sukharevd.net/wildfly-8-installation.html. Everything works fine. I connect to my Linux remotely using SSH. It doesnt have GUI. So I need to be able to remotely connect to administration console. I cannot connect and it shows the following message:
"An automatic redirect to the Administration Console is not currently available. This is most likely due to the administration console being exposed over a network interface different from the one to which you are connected to."
I see the same issue mentioned in the following link
https://github.com/jboss-dockerfiles/wildfly/issues/3
The link has solution to it but it uses "docker". How can I do it without using docker? I am using standalone configuration. What configuraiton do I need to change?

A: You should start WildFly using following command. Use of 0.0.0.0 will bind WildFly to all the available IP addresses on your linux box. If you want to bind to specific IP address; you can replace 0.0.0.0 with the relevant IP address.
$WILDFLY_HOME/bin/standalone.sh -b=0.0.0.0 -bmanagement=0.0.0.0
EDIT : Once the installation was complete using the script. We have to go to /etc/init.d/service and change JBOSS_SCRIPT=$JBOSS_HOME/bin/standalone.sh to JBOSS_SCRIPT="$JBOSS_HOME/bin/standalone.sh -b=0.0.0.0 -bmanagement=0.0.0.0"

A: The Second Possible Solution
As an alternative to adding parameters do your start command, you can edit your standalone.xml to enable remote access from any source. This approach is more useful if you need the remote access enabled most of the time, this way, you don't need to remember to pass additional parameters to the start command, as shown above.
First, go to your Wildfly configuration folder:
terminal
cd /opt/wildfly-8.2.0.Final/standalone/configuration

Next, edit the standalone.xml file using your preferred file editor and do the changes below:
Replace this:
standalone.xml
<interface name="management">
    <inet-address value="${jboss.bind.address.management:127.0.0.1}"/>
</interface>
<interface name="public">
    <inet-address value="${jboss.bind.address:0.0.0.0}"/>
</interface>

With this:
standalone.xml
<interface name="management">
    <any-address/>
</interface>
<interface name="public">
    <any-address/>
</interface>

Make sure to save your changes and restart your Wildfly:
on terminal
/opt/wildfly-8.2.0.Final/bin/jboss-cli.sh --connect --command=:reload

Done.

A: A better approach is edit JBOSS_HOME/standalone/configuration/standalone.xml editing the piece of code above and changing the address to 0.0.0.0.
<interfaces>
    <interface name="management">
        <inet-address value="${jboss.bind.address.management:127.0.0.1}"/>
    </interface>


text:
Q: How to find index in sorted array where occurs maximum value for the first time How to find index in sorted array where occurs maximum value for the first time?
Let's take for example this array:
1 2 3 4 5 6 7 8 9 ... 200 201 201 201 201 201 201 201 201 201 201 201 201 ...201

where 201 is the maximum value.
Let's say that 201 occurs 200 times in this array. So the answer is that the index equals 200.
The native solution would be to iterate it as long as we get sth that !=201. But I guess that it is possible to find more effective solution. What algorithm do you suggest?

A: Binary search is O(log n) which is better than your naïve approach which has a complexity of O(n). In c++, you'd use std::lower_bound.

A: Use Binary search.
Native binary search will return any one occurrence of your key. Its "find " criteria is:
if(a[mid]==key)
    return mid;

Make a binary search function where your "find" criteria is:
if(a[mid]==key && a[mid-1]<key)
    return mid;

Also, if its a simple array, you can use a c++ standard template library (STL) function, lower_bound.

A: You can use standard algorithm std::lower_bound declared in header <algorithm>
For example
#include <algorithm>
#include <iterator>

//...

size_t n = std::distance( std::begin( a ),
                          std::lower_bound( std::begin( a ),
                                            std::end( a ),
                                            *std::prev( std::end( a ) ) ) );

where a is the name of a sorted array.

A: Iterate from the end of the array, not the beginning.  The first occurrence of the maximum value is likely to be closer to the end than the beginning.
for (int i = array.length; i >=0; i--) {
     do stuff
}


text:
Q: Linking error in C++ I'm just putting the finishing touches on a project I've been working on to render a scene in OpenGL - I based some of it on some old code I wrote for a Camera class (since I didn't want to have to re-figure out the maths!), however I'd included the Camera class as part of main.cpp before, and I wanted to move it to it's own seperate .h/.cpp files for the sake of reusability/clarity/general good practice.
I also replaced a basic Struct to hold the x and y position of the mouse with a Mouse class that I wrote.
I changed some code in the Windows Message Handler to have the Camera update when the Left Mouse Button is released - however I am getting a strange linking error -

1>main.obj : error LNK2001: unresolved
  external symbol "public: void
  __thiscall Camera::moveCamera(int,int,int,int)"
  (?moveCamera@Camera@@QAEXHHHH@Z)

The code in the Windows Message Handler is -
    case WM_LBUTTONUP:
        Mouse.SetPos(lParam);
        x_mouse_end = Mouse.GetXPos();
        y_mouse_end = Mouse.GetYPos();
        Camera.moveCamera(x_mouse_start, y_mouse_start, x_mouse_end, y_mouse_end);
        SetCamera();
        break;

The parameters I'm passing to Camera.moveCamera() are integers as they are supposed to be.
The moveCamera() function is as follows -
//Moves the camera based on a user dragging the mouse
inline void Camera::moveCamera(int old_x, int old_y, int new_x, int new_y)
{
    //To store the differences between the old and new mouse positions
    int x_difference, y_difference;

    //If the mouse was dragged to the right, move the camera right
    if(new_x > old_x)
    {
        x_difference = new_x - old_x;
        x_difference = x_difference / 25;

        if(yaw > 350)
        {
            yaw = 0;
        }
        else
        {
            yaw = yaw + x_difference;
        }
    }

    //If the mouse was dragged to the left, move the camera left
    if(new_x < old_x)
    {
        x_difference = old_x - new_x;
        x_difference = x_difference / 25;

        if(yaw < 10)
        {
            yaw = 360;
        }
        else
        {
            yaw = yaw - x_difference;
        }
    }

    //If the mouse was dragged down, move the camera down
    if(new_y < old_y)
    {
        y_difference = new_y - old_y;
        y_difference = y_difference / 20;

        if(pitch < 10)
        {
            pitch = 360;
        }
        else
        {
            pitch = pitch - y_difference;
        }
    }

    //If the mouse was dragged up, move the camera up
    if(new_y > old_y)
    {
        y_difference = old_y - new_y;
        y_difference = y_difference / 20;
        if(pitch > 350)
        {
            pitch = 0;
        }
        else
        {
            pitch = pitch + y_difference;
        }
    }

    //Update the camera position based on the new Yaw, Pitch and Roll
    cameraUpdate();

}

"camera.h" is included as it should be, as is "mouse.h", and instances of both classes are set up -
Mouse Mouse;
Camera Camera;

I'm at a loss as to what could be missing.
Please let me know if you would like more information.

A: Maybe you included that definition of moveCamera() in a .cpp file with the "inline" keyword. This may be interpreted that this method is local to the .cpp in which it is defined. Try removing the inline.


text:
Q: Issue with custom attributes in child views when parent layout has specified own theme I'm trying to solve an odd problem where in my layout xml file a parent view (<LinearLayout>) has an attribute called android:theme="@style/blueTheme" and it's children (<TextView>) have android:background=?attr/backgroundColor.
The issue here is that the returned attribute has no value. I've expected that the value would be retrieved from it's parent theme (ie. @style/blueTheme) but can't just make it to work.
Is this feature supported at all?
edit-
<style name="blueTheme">
    <item name="backgroundColor">@color/blue</item>
</style>

and the backgroundColor is defined as
<attr name="backgroundColor" format="reference" />


text:
Q: Rails and Paperclip - resizing issue I know that the paperclip gem has an option to create several resized versions of an image.
Example:
class User < ActiveRecord::Base
  # Paperclip
  has_attached_file :photo,
    :styles => {
    :thumb => "100x100#",
    :small  => "150x150>",
    :medium => "200x200" }
end

I want the image to be resized to "500x500>" and only keep this resized version (discarding the original).
Is this possible? How?

A: class User < ActiveRecord::Base
  # Paperclip
  has_attached_file :photo,
    :styles => {
    :original => "500x500>", #this will resize the original directly
    :thumb => "100x100#",
    :small  => "150x150>",
    :medium => "200x200" }
end


text:
Q: Getting the "size" of a view in Redshift Essentially, I'm trying to figure out the size table foo will be after executing:
CREATE TABLE foo AS (
    SELECT * FROM my_view
);

My gut tells me that the easiest approach would be to SELECT count(1) FROM my_view and multiply by the column widths, but that won't help me with VARCHARs.
Is there a "right" way to do this?

A: I also think that size might be based on the type of view.
A normal view should not have size on disk since it's merely pulls the results from an underlying table.
But if its a materialized view, then it would have size on disk


text:
Q: tesseract ocr works terrible on ios (7) I don't know if something is wrong with me or tesseract library but it works terrible.
Tesseract* tesseract = [[Tesseract alloc] initWithDataPath:@"tessdata" language:@"eng"];

    [tesseract setVariableValue:@"0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZéèô" forKey:@"tessedit_char_whitelist"]; //limit search
    [tesseract setImage:[UIImage imageNamed:@"sampledoc.jpg"]]; //image to check
    [tesseract recognize];

    NSLog(@"%@", [tesseract recognizedText]);

    [tesseract clear];

This is the sample image I want to extract text from:

And this is what I get after running:
THE SILVER CHAIR
by r 5 Lawn
CHAPTER ow
BEHIND THE cm

lr W1C a dull aulumn day and llll Pole vmscrylng ulmo mo gym
She ms clymg because Illey had been bullymg her Hus Is not gmng In baa school oolyl se I
shall say 15 lane is poslble Ibvlll lllrs schwll which lsnol 1 plusinl subjzrl II was Tcr
eduummlr o sdsooV rm bolh boysuld glrlsl Mm used no he cnllcd o wmxodl schonll some
said on wax ml nculy so mixed as an mlndsohhe people whn an n These penple had um mu
m boyund glrlsshauld loeullma mdn who my mo And unlonunalcb mm ml or
mom aflhc hlggzsl bays mo girls liked best was bullying Ihe mm All suns orlllmgsl hound
mmgso went on Much u an nvdmlry saloon wnuld mm bum flwnd om ma snowed m lulfn
R1my hm al Ilus school xhcy vlucrfl Or mu Iflhcy mo mo people who am am wxc not
expellad m pomsloa The mm no they Mile lntntesilng psycholoycnl msxs mdsaul for
them and mm mlhem for hnun Mo Ifyml knew lhe nghl sorlofdnngxmsay In mo um
mo maul result wos um vou became mlhev 1 fmounlelhan olllnrwlsc
no mswmy ml Pole W crymg on ml dull autumn my on me dlmp Vmlc pith Much runs
bellman um um arm gym ma Ihe lhvubbezy mm ole mam nearly nmulea her ay whan
boy came round Ihz oomuonhogym Mxmlmg mm ms lnmlds m ms pocktu I12 mm In
lmo nu
 CuIV yuu look when yolfre gomw ma JIH Fob
Mu nglur sud me km won mam man a and am he mom hen rm ll WV Polef he
not was upv
ml only mndc lung the am you mm mo yodic llymg oo my somclhmg um um Ihn lfyou
spnk you1l smrl ctymg owl
 lfs mum I suww l as mualr sand me hwy Mlmlbx ouggmg ms hlnds nmm mm ms vovkals
ml waded Them wlsw moo forhurm sly llH1hVlIgoCVOllWiIE ooolo have Said u They both
knew
wow laok has said the beyl Wherek no gond us all r
He mezm WEIL am he am mlk mum mo mlnmne begmnmg n lecmne ml suddenly liew mm a
lmxpcr hvmdl Isqnllc Illkcly llllng Io hlppen Ifyou law been mmrupled in n cryl

I

What I am supposed to do?

A: He meant the pixel resolution (PPI), not the image dimension.
I rescaled the image (from 96 DPI) to 300 DPI and got almost all text recognized correctly. The image definitely needed pre-processing before OCR step.

A: Tesseract *tesseract = [[Tesseract alloc] initWithDataPath:@"tessdata" language:@"eng"];
[tesseract setImage:chosenImage];
[tesseract recognize];

NSLog(@"%@",[tesseract recognizedText]);


text:
Q: Execute a search on an input field using javascript I'm trying to write a sanity test. Given:

    <input type="text" class="search-widget" id="txt-search" placeholder="Search">

If I use either of these in the console, the text will be entered in the search box. If I manually click enter in the ui the search will be performed properly.
document.getElementById('txt-search').value='test'
$('#txt-search').val('test')

However, the following commands will fail to click and perform the search. I've tried to append \r\n to the text but to no avail. I've played around with keypress events too.
document.getElementById('txt-search').click()
 $('#txt-search').click()

A: Excuse me if I'm misunderstanding your issue, but it looks like there are two separate, but related, issues at play.
First, .click()
Your jQuery is valid, but click() needs a handler if you want something to actually happen.
$( "#target" ).click(function() {
  alert( "Handler for .click() called." );
});

[source: http://api.jquery.com/click/]
Second, HTML Forms
The input element doesn't actually have ability to perform a search. To do that, you'll need to build a form with a submit button.
See MDN's excellent documentation here: https://developer.mozilla.org/en-US/docs/Web/Guide/HTML/Forms
For a quick example, something like this:

<form action="getform.php" method="get">
    First name: <input type="text" name="first_name" />

     Last name: <input type="text" name="last_name" />

        E-mail: <input type="email" name="user_email" />

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

source: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input
Then you can call click on the submit input to run your search.
Hope that helps.


text:
Q: How to correctly enqueue the parent and child theme stylesheets in the creation of a child theme? I have to create a child theme to implement some changes to a WordPress theme and avoid that these changes are lost when the theme will be update.
So I have some doubt about how do it.
I am following this official tutorial: https://codex.wordpress.org/Child_Themes
So I have create the child theme directory (named accesspress-parallax-child because the directory of the original theme is accesspress-parallax) into the WordPress wp-content/themes/ directory of my WordPress installation and I
Into this new folder I have put the style.css* and the **functions.php file.
Into the style.css file I have put this commented code (as explained into the documentation):
/*
 Theme Name:   Accesspress Parallax Child
 Theme URI:    http://example.com/twenty-fifteen-child/
 Description:  Accesspress Parallax Child Theme
 Author:       Andrea Nobili
 Author URI:   http://example.com
 Template:     accesspress-parallax
 Version:      1.0.0
 License:      GNU General Public License v2 or later
 License URI:  http://www.gnu.org/licenses/gpl-2.0.html
 Tags:         light, dark, two-columns, right-sidebar, responsive-layout, accessibility-ready
 Text Domain:  accesspress-parallax-child
*/

Now, it say, that I have to enqueue the parent and child theme stylesheets putting into the functions.php file this code:
add_action( 'wp_enqueue_scripts', 'theme_enqueue_styles' );
function theme_enqueue_styles() {
    wp_enqueue_style( 'parent-style', get_template_directory_uri() . '/style.css' );

}

Now I have two doubts:
1) in the previous code snippet have I to referer my parent theme in some way or not? How it know what is the parent theme?
2) Into the documentation it say:

The following example function will only work if your Parent Theme
  uses only one main style.css to hold all of the css. If your theme has
  more than one .css file (eg. ie.css, style.css, main.css) then you
  will have to make sure to maintain all of the Parent Theme
  dependencies.

What exaclty means? Into my original theme I have more than a single .css file. Infact into the original theme I have a css directory that contains many css files.
What have I to do to solve this problem?
Tnx

A: Check this codex page.

In the event that a child theme is being used, the parent theme directory URI will be returned.

So if you want to include your other css files you just need to all your CSS files:
add_action( 'wp_enqueue_scripts', 'theme_enqueue_styles' );
function theme_enqueue_styles() {
    wp_enqueue_style( 'parent', get_template_directory_uri() . '/style.css' );
    wp_enqueue_style( 'custom-handler-one', get_template_directory_uri() . '/custom-css-one.css' );
    wp_enqueue_style( 'custom-handler-two', get_template_directory_uri() . '/custom-css-two.css' );
    ...
    wp_enqueue_style( 'custom-handler-n', get_template_directory_uri() . '/custom-css-n.css' );
}

Please note that some themes are coded in strange ways so this methodology may not always work. If you share the theme's name or how the styles are included more detailed description can be provided :).


text:
Q: spring adding external jar with controller not working I have made a Java project having spring controller that handle url
Here is the controller code
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;

@EnableWebMvc
@Controller
public class SmartContentValidator {

@RequestMapping(value = "/validate")
public String validate() {
    System.out.println("Yo");

    return "YO";
}
}

Then I exported above java project as jar file.
Then created a new web project and added the above jar in build path. Here is the web.xml and dispatcher-servlet.xml
web.xml
<?xml version="1.0" encoding="UTF-8"?>

<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
id="WebApp_ID" version="3.0">
<display-name>SmartContentValidatorTest</display-name>

<servlet>
    <servlet-name>dispatcher</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <load-on-startup>1</load-on-startup>
</servlet>

<servlet-mapping>
    <servlet-name>dispatcher</servlet-name>
    <url-pattern>/</url-pattern>
</servlet-mapping>

<welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
</welcome-file-list>

dispatcher-servlet.xml
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="

http://www.springframework.org/schema/beans
 http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
 http://www.springframework.org/schema/context
 http://www.springframework.org/schema/context/spring-context-4.0.xsd">

<context:component-scan base-package="com" />
<context:annotation-config/>

<bean
    class="org.springframework.web.servlet.view.InternalResourceViewResolver">
    <property name="prefix">
        <value>/WEB-INF/views/</value>
    </property>
    <property name="suffix">
        <value>.jsp</value>
    </property>
</bean>

Now when I try to hit http://localhost:8080/project_name/validate
it shows 404-not found on browser and
WARNING: No mapping found for HTTP request with URI [/SmartContentValidatorTest/validate/] in DispatcherServlet with name 'dispatcher'

in my eclipse console.
What is the issue? Am I missing something?
Edit
Project Structure

A: I am not sure if it helps with your case but I think that in standalone application there would be an issue as @EnableWebMvc should be used with Java config - class annotated with @Configuration, not with @Controller bean.
As you use xml config you can try put <mvc:annotation-driven />, see https://docs.spring.io/spring/docs/current/spring-framework-reference/html/mvc.html#mvc-config-enable for more details.
You would also need to provide your application context as dispatcher servlet param like in example http://docs.spring.io/spring-flex/docs/1.0.x/reference/html/ch02s02.html:
<servlet>
    <servlet-name>Spring MVC Dispatcher Servlet</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>/WEB-INF/config/web-application-config.xml</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
</servlet>

A: Normally this is caused by Spring not correctly finding your controller. If you enable DEBUG logging Spring will log what beans are registered when you start the application.
If it is correctly loading your controller then check that your root path is correct (I think this is your war name by default) which again should be displayed in the logging during startup.


text:
Q: Closing Android Game After 5 Seconds I'm tring to build an simple android game.
Users answer the questions, when the answer is correct, it is continue..
I want to add time control for each answer.
I tried to add handler function, but I didn't.
My Code;
import java.util.Collections;
import java.util.Arrays;
import java.util.List;
import java.util.Random;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
public class EasyGameActivity extends Activity {
public int score = 0;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    requestWindowFeature(Window.FEATURE_NO_TITLE);
    getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);

    setContentView(R.layout.activity_easygame);

    Handler handler = new Handler();
    handler.postDelayed(new Runnable() {
        public void run() {
            finishScreen();
        }
    }, 5000);

    startGame();
}

private void startGame() {
    // TODO Auto-generated method stub

    Button b1 = (Button)findViewById(R.id.answer_one);
    Button b2 = (Button)findViewById(R.id.answer_two);
    Button b3 = (Button)findViewById(R.id.answer_three);
    Button b4 = (Button)findViewById(R.id.answer_four);

    Random number = new Random();
    int first = number.nextInt(100)+1;
    int second = number.nextInt(100)+1;
    int answer = first + second;
    int rnd1 = answer + 1;
    int rnd2 = answer + 2;
    int rnd3 = answer - 1;

    final String a = Integer.toString(answer);
    String b = Integer.toString(rnd1);
    String c = Integer.toString(rnd2);
    String d = Integer.toString(rnd3);

    ((TextView) findViewById(R.id.display)).setText(Integer.toString(first) + '+' + Integer.toString(second));

    List<Button> buttons = Arrays.asList(b1, b2, b3, b4);
    List<String> texts = Arrays.asList(a, b, c, d);
    Collections.shuffle(texts);
    int i = 0;
    OnClickListener onClick = new OnClickListener() {
        public void onClick(View view) {
            Button button = (Button) view;
            String value = (String) button.getText();

            if(value == a) {
                checkTrue();
            } else {
                finishScreen();
            }
        }
    };
    for(Button button : buttons) {
        button.setText(texts.get(i++));
        button.setOnClickListener(onClick);
    }
}

private void checkTrue() {
    score++;
    ((TextView) findViewById(R.id.score)).setText(Integer.toString(score));
    startGame();
}

private void finishScreen() {
    score = 0;
    startActivity (new Intent("com.bsinternet.mathfast.RESTARTGAMESCREEN"));
    finish();
}

}
How can I add time control. Thanks.

A: This bit of code doesn't look right
if(value == a) {
   checkTrue();
} else {
   finishScreen();
}

You should be using equals() to check for String equality. At the moment you are checking only object equality, which will evaluate to False, and the code will never call checkTrue().
Do this instead:
if(value.equals(a) {
   checkTrue();
} else {
   finishScreen();
}


text:
Q: Run Code at Certain Time I'm building an app based around the user creating recurring 'events'. Each Event object has a day (stored as a typedef NS_ENUM), and a time (stored as an NSDate), and a duration (an NSInteger representing minutes). Each event always repeats weekly. Events are stored in a Core Data managed, cross device synchronised, database. And are designed to be reused such that they don't need to be recreated each week (hence the date independent weekdays). Once an event is finished, some user statistics are updated.
Take, for example, an event that starts on Monday at 10:00, and lasts for 25 minutes. In this case, I would want to get the NSDate representation of this Monday at 10:25 (which isn't a problem) and at this time, update the user statistics, which is the problem.
What is the best way of having code execute at a certain time?
I had originally thought of using [[NSDate alloc] initWithFireDate:interval:target:selector:userInfo:repeats:]. However, it would be difficult to ensure the target object was initialised, and to synchronise the timers between devices. That is to say, make sure each timer is set to fire at the same time (should the day, time, or duration change).
My second thought, was to update the statistics when the apps launched, using the current system time, and looking back at previous events. However, if the user has the app open, I want the statistics to update in real time.
Any help or ideas would be much appreciated. I am also open to ideas on how I might change my model to better solve this problem.
Thanks in advance.

A: There are two possible situations that your app can be in when the timer needs to fire - it's either in the foreground or not. NSTimer will only fire when the app is in the foreground (with a few minor exceptions, such as running in a background execution task).
You could handle the two situations as follows:

*

*Schedule the timer for the next required time, using initWithFireDate. You should set the target to an object that will exist while your app is running. You could use your UIApplicationDelegate or some other singleton class.

*When the app goes to background, invalidate the time.

*When the app returns to foreground, check if the timer should have fired since the app was last put to background. If so, run the statistics update. Schedule the next timer task.

*If the timer fires, the app is still in the foreground so run the statistics update task, then schedule the next timer task.


text:
Q: Best way to avoid nested ternary with form validation I'm trying to do form validation using react-form-hooks. I've set up the requirements for my form element like this:
<TextField
  label="Email"
  {...register("email", {
    required: true,
    pattern: emailRegex,
    maxLength: 60,
  })}
  error={errors.email}
  helperText={
    errors.email?.type === "required"
      ? "Email is required"
      : errors.email?.type === "pattern"
      ? "Invalid email"
      : errors.email?.type === "maxlength"
      ? "Email too long"
      : ""
  }
/>

It works, but it's far from readable. I use ternary quite often for choosing between text options for react component parameters and I think that previously it made sense as I always had 2 options so far, but here I have 3 and for some other I might even have 4.
I couldn't find examples with best practices for this scenario of filling helper text (or like of it) with different strings based on error. Here are 2 ways I've came up with to solve this:

*

*Using function and switch:

const getEmailHelperText = (errors) => {
  switch (errors.email?.type) {
    case 'required':
      return 'Email is required.'
    case 'pattern':
      return 'Invalid email'
    case 'maxlength':
      return 'Email too long'
    default:
      return ''
  }
}

/// ...

<TextField
  label="Email"
  {...register("email", {
    required: true,
    pattern: emailRegex,
    maxLength: 60,
  })}
  error={errors.email}
  helperText={getEmailHelperText(errors)}
/>

*Using useState() and useEffect()
const [emailHelperText, setEmailHelperText] = useState('')

useEffect(() => {
  switch (errors.email?.type) {
    case 'required':
      setEmailHelperText('Email is required.')
      break
    case 'pattern':
      setEmailHelperText('Invalid email')
      break
    case 'maxlength':
      setEmailHelperText('Email too long')
      break
    default:
      setEmailHelperText('')
  }
}, [errors]);

// ...

<TextField
  label="Email"
  {...register("email", {
    required: true,
    pattern: emailRegex,
    maxLength: 60,
  })}
  error={errors.email}
  helperText={emailHelperText}
/>

Is there a better, "right" way to do it? If not - which one of those two makes more sense? Is more efficient?


text:
Q: How to control reviewers in public repository I have a public repository on github and 2 collaborators. I created a branch rule for code review. I want to review PRs only by myself, but there is an ability to set other collaborators as reviewes. Which setting do i need to allow to set as as review only me?

A: If you protect your main branch by requiring pull request reviews before merging, you can select "Require review from Code Owners".

See "About code owners": that would be where you can specify additional collaborator to be reviewers.


text:
Q: Why does my output content output twice in the blade php? I am trying to implement live search bar. The live search is working but it however outputs the output content twice, which is annoying. Could you please have a look where the problem is? Thanks.
Here is my code for the search function.
public function search(Request $request)
    {
        if ($request->ajax()) {

            $output = "";
            $projects = Project::where('title', 'LIKE', '%' . $request->search . '%')
                        ->where('module_code',$request->module_code)
                        ->get();
            $count = count($projects);
            // $projects = array_unique($projects);
            if ($projects) {
                foreach ($projects as $project) {
                    $output .= '
' .
                        '' . $project->team_number . '	' .
                        // '' . $count . '	' .
                        '' . $project->lab . '	' .
                        '' . 'id . '" style="display:block;">' . $project->title . '' . '	' .
                        '' . $project-> latest_state. '	' .
                        '' . $project->team_member_1 . '	' .
                        '' . $project->latest_team_member_1_state . '	' .
                        '' . $project->team_member_1 . '	' .
                        '' . $project->latest_team_member_1_state . '	' .
                        '' . $project->team_member_1 . '	' .
                        '' . $project->latest_team_member_1_state . '	' .
                        '' . $project->ta . '	' .
                        '' . $project->created_at . '	' .
                        '' .
                        '<button class="btn-sm btn-info pull-left" onclick="location.href = \'/projects/' . $project->id . '\'">Project Details</button> ' .
                        '	' .
                        '
';
                }
                return Response($output);
            }
        }
    }

Here is the script for live search in php blade:

Here is the code for search bar in php blade

                        <input type="text"  class="form-control" id="search" name="search" placeholder="Search..."/>

Before searching:

After searching:

A: Damn, I just found out what's causing the problem. It's kind of silly. The original code is here: https://onecompiler.com/posts/3xy39rm78/php-blade-for-staff, the bug is still up there. The problem was that, I added an additional  tag that is unnecessary. The output is placed wherever there is a  tag as the script was:
        $('#search').on('keyup',function(){
        $value = $(this).val();
        $qString = getQueryParams('module', window.location.href);
        $queryString =
        $.ajax({
            type : 'get',
            url  : '{{URL::to('search')}}',
            data : {'search':$value, 'module_code': $qString},
            // data : {'search':$value},
            success:function (data) {
                //console.log(data);
                // alert(data);
                $('tbody').html(data);
            }
        });
    })

At the very last bit of the code, it tells html to print result at the  tag(I'm not sure if this is right). By deleting the additional tbody tag, the problem was solved.


text:
Q: Add filter when image is uploaded? I'm trying to use this code from another SO resopnse:
function ajx_sharpen_resized_files( $resized_file ) {

    $image = wp_load_image( $resized_file );
    if ( !is_resource( $image ) )
        return new WP_Error( 'error_loading_image', $image, $file );

    $size = @getimagesize( $resized_file );
    if ( !$size )
        return new WP_Error('invalid_image', __('Could not read image size'), $file);
    list($orig_w, $orig_h, $orig_type) = $size;

    switch ( $orig_type ) {
        case IMAGETYPE_JPEG:
            $matrix = array(
                array(-1, -1, -1),
                array(-1, 16, -1),
                array(-1, -1, -1),
            );

            $divisor = array_sum(array_map('array_sum', $matrix));
            $offset = 0;
            imageconvolution($image, $matrix, $divisor, $offset);
            imagejpeg($image, $resized_file,apply_filters( 'jpeg_quality', 90, 'edit_image' ));
            break;
        case IMAGETYPE_PNG:
            return $resized_file;
        case IMAGETYPE_GIF:
            return $resized_file;
    }

    return $resized_file;
}

add_filter('image_make_intermediate_size', 'ajx_sharpen_resized_files',900);

It works well but is only executing for when WP uses image_make_intermediate_size. Would there be a way to make this apply for every image that is uploaded?
Thanks


text:
Q: Number of terms in the expansion $(1+a^3+a^{-3})^{100}$ Find the number of terms in the expansion $(1+a^3+a^{-3})^{100}$
I used the concept $a^3+a^{-3}=T$, while using this I have 101 terms, from $T^2$ to $T^{100}$ how do i find the number of terms that do not intersect

A: Write $a^3=b$
Multinomial theorem says
The general term of $$(1+b+b^{-1})^{100}$$ is $$\dfrac{100!}{p!q!r!}b^{p-q}$$ with
$p+q+r=100$ and $p,q,r\ge0$
$\implies0\le p,q\le100$
So, $-100\le p-q\le100$
If $d=p-q,100=d+2q+r\iff d=100-2q-r$
If $r=0,p+q=100$
$d=100-2q,d$ can attain all the even integer values in $[-100,100]$
If $r=1,p+q=99$
$d=100-(2q+1)=99-2q$ can attain all the odd values in $[-99,+99]$
Clearly $p-q$ can attain all the possible $100-(-100)+1$ values

A: Well, note that
$$(a^{-3} + 1+a^3)^{100} = (a^{-3}+a^0+a^{3})^{100} = \sum_{i=-100}^{100} c_ia^{3i},$$
for some $c_i$ and each $c_i$ is strictly positive. In fact, each $c_i$
is precisely the number of ordered multisets $\{b_1,\ldots, b_{100}\}$;
$b_l \in \{-1,0,1\}$ such that $i=\sum_{l=1}^{100} b_l$.
[Make sure you see why]. This is at least 1 for each $i \in \{-100, -99,\ldots, -1, 0,1, \ldots, 100\}$; indeed if $i$ is positive let $b_l=1$ for each $l=1,2,\ldots, i$ and $b_l=0$ for each other $i$,
and if $i$ is negative let $b_l=-1$ for each $i=1,2,\ldots, |i|$, and $b_l=0$ for each other $l$. If $i$ is 0 then let all the $b_l$s are 0.
So, as each $c_i$ is positive this would be 201 terms.
Now with that said $(1+a^3)^{100}$ would have 101 terms. Do you see why?

A: It is equivalent to finding the number of terms in:
$$(1+a^3+a^{-3})^{100}=a^{-300}(a^6+a^3+1)^{100} \Rightarrow (a^6+a^3+1)^{100},$$
whose terms will have powers (since the signs are positive and exponents are multiples of $3$):
$$0,3,6,...,597,600$$
The number of terms of the arithmetic progression is:
$$n=\frac{a_n-a_1}{d}+1=\frac{600-0}{3}+1=201.$$


text:
Q: Reflection - Method::getGenericReturnType no generic - visbility Description
I have an odd issue in which Method::getGenericReturnType() is not able to retrieve the generic type information.
Here is the minimized version:
public class Test {
    public static void main(String[] args) {
        Method method = B.class.getMethods()[0]; // foo() method inherited from A
        System.out.println(method.getGenericReturnType());
    }

    static class A {
        public List<String> foo() { return null; }
    }

    public static class B extends A {}
}

Output is
java.util.List

without any generic type information. This seems odd to me.
However, changing As visibility to public and it correctly gives
java.util.List<java.lang.String>

Question
I do not know if this is a bug or actually expected behavior. If it is expected, what is the reasoning behind it?
I am using OpenJDK 15 from AdoptOpenJDK:
// javac
javac 15.0.1

// java
openjdk version "15.0.1" 2020-10-20
OpenJDK Runtime Environment AdoptOpenJDK (build 15.0.1+9)
OpenJDK 64-Bit Server VM AdoptOpenJDK (build 15.0.1+9, mixed mode, sharing)

A friend could also reproduce it in:

*

*JDK Zulu 8

*AdoptOpenJDK 10, 11, 14

Findings
I experimented a lot and figured out that the only visibility-combination between A and B that triggers this issue is when B is public and A is not public. Any other combination and it works as expected again. So only

*

*B public, A protected

*B public, A package-visible

*B public, A private
show weird behavior.
I tried moving the code around in different files, putting it into different packages, adding or removing static here and there and nothing changed.
I also checked the source code of the method, which is
public Type getGenericReturnType() {
  if (getGenericSignature() != null) {
    return getGenericInfo().getReturnType();
  } else { return getReturnType();}
}

where getGenericSignature() relies on a String signature that is set during construction of the Method instance. It appears that it is null for some reason in above situation.

Update 1
I was just checking out the bytecode of the classes and found this in B.class:
  public Test$B();
    descriptor: ()V
    flags: (0x0001) ACC_PUBLIC
    Code:
      stack=1, locals=1, args_size=1
         0: aload_0
         1: invokespecial #1                  // Method Test$A."<init>":()V
         4: return
      LineNumberTable:
        line 16: 0

  public java.util.List foo();
    descriptor: ()Ljava/util/List;
    flags: (0x1041) ACC_PUBLIC, ACC_BRIDGE, ACC_SYNTHETIC
    Code:
      stack=1, locals=1, args_size=1
         0: aload_0
         1: invokespecial #7                  // Method Test$A.foo:()Ljava/util/List;
         4: areturn
      LineNumberTable:
        line 16: 0

To me this looks like B, for some reason, created another method foo() that simply forwards the method call to As foo() and hence has no generic type information.
Moreover, when calling B.getDeclaredMethods() it actually returns a method, namely
public java.util.List Test$B.foo()

Even though this method is supposed to exclude inherited methods (from the documentation):

Returns an array containing Method objects reflecting all the declared methods of the class or interface represented by this Class object, including public, protected, default (package) access, and private methods, but excluding inherited methods.

Which would now make sense if B really created a wrapper-method.
However, why is it creating such a method? Is there maybe a JLS section that explains this behavior?

A: Let's take it slow here. First of all, here is why a bridge method is generated to begin with. Even if you drop generics, there will still be a bridge method. That is, this code:
static class A {
    public String foo() { return null; }
}

public static class B extends A {}

will still generate a foo method with ACC_PUBLIC, ACC_BRIDGE, ACC_SYNTHETIC. You can read the bug description and understand why that is needed.
On the other hand if you make A public, such a method will not be generated, the reason should be obvious, considering the previous bug explanation (I hope). So the idea is that if you have a non-public class, javac will generate a bridge method for the scenario above.

Now, if you add generics into that mix of synthetic methods, things start to shed some light. For example, you have this:
interface WithGeneric<T> {
    public WithGeneric<T> self(T s);
}

public class Impl implements WithGeneric<String> {

    @Override
    public WithGeneric<String> self(String s) {
        return null;
    }
}

There will be a bridge method generated too in Impl.class, but its declaration is going to be the erasure of the interface. In other words there will be two methods in Impl.class:
public WithGeneric<String> self(String) {...}

public WithGeneric self(Object) {...}

If you glue these two things:

*

*in case of non-public classes a bridge method will be created (so that reflection would work)

*in case of generics an erased bridge method will be created (so that erased calls would work)
things will make (somehow) sense.

A: When you declare A public, B.class.getMethods()[0] is not referencing B; It is referencing A.foo(), where the method is declared and the type is obtained because of the existance of the signature.

Declaring A non-public forces B.class.getMethods()[0] reference B.foo().
As there is no declaration of the inherited method, the type can't be obtained from the call to getGenericReturnType due to type erasure being applied to generics.
In compile time:
List<String> foo() becomes
List foo().
And that's all the information B could give to you regarding the method's return type, since the signature in B.foo() was just removed.

Both A and B hold the same return type for foo() : java.util.List (without parameter type)
This is A.foo()'s declared return type. The same than B.foo():

The difference is that A has a valid signature, so it will complete the result from the call to getGenericReturnType() by adding the parameter types.
In the case of B, it will only show what it knows: just the return type.

I suffered strong headaches trying to solve the visibility puzzle. For a complete explanation of why this happens, look up at Eugene's answer. Seriously, you can learn a lot from this type of guy.


text:
Q: Implementing a non abstract class from an abstract class A class called Patient contains 2 abstract methods namely getPatientdetails() and printPatientDetails. both methods should return nothing.
A class called OutPatient is a sub class of patient but is not abstract. Patient's details include PatientName(string) and DiseaseName(String). On outpatients, we also record the DateofVisit(String) and amount charged(Float).
Another class AdmittedPatient is also a sub class of patient calss and is not abstract. On admittedPatient, we also record wardName(string) and Bed Number(Int).
The challenge is to the Three classes and ensuring that these values are all captured from the user on runtime.
What would be the sudo code for this and then the explanation and java code for such an application to run?


text:
Q: How to get DIV index number based on click element I have following HTML structure

Now If user click to image tag

Inside of this div(fourth number of div)

 ...

I want to find that div index number which user click his child img tag.
Hope you understand what I am looking for.
Any Idea how to find click div index number?
Thanks.

A: You can use .index()
var $dics = $('.dz-image-preview img').click(function(){
    var index = $(this).closest('.dz-image-preview').index()
})

A: Try this:
$(document).on("click", "img.rotate", function () {
  // get parent div element, then use index() function
  alert(
    $($(this).parents("div.dz-image-preview")[0]).index()
  );
});

A: Use the index() method to return the index position of specified elements relative to other specified elements.
$('a.rotate-a').click(function(){
  var divIndex = $(this).closest('.dz-preview').index('.dz-preview');
  alert(divIndex);
});

Note: If the element is not found, index() will return -1


text:
Q: Using Appkit and Python to hide mouse cursor on OSX I'm trying to script hiding the mouse cursor on OSX 10.9.  I have Chrome starting and going full screen for a kiosk and I'd like to periodically run a script to hide the cursor.
Applescript no longer directly supports "call method" to call the objective C method, so I thought the simplest method would be to use AppKit from the provided python.
It crashes:
$ python
Python 2.7.5 (default, Mar  9 2014, 22:15:05)
[GCC 4.2.1 Compatible Apple LLVM 5.0 (clang-500.0.68)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import AppKit
>>> AppKit.NSCursor.hide()
Assertion failed: (CGAtomicGet(&is_initialized)), function CGSConnectionByID, file Services/Connection/CGSConnection.c, line 123.
Abort trap: 6

I suspect there is a pre-requisite call I need to make to initialize something,  but I haven't found anything yet while digging through docs/google.
What am I missing?

A: I've had luck with the Quartz included with PyObjC:
import Quartz
Quartz.CGDisplayHideCursor(Quartz.CGMainDisplayID())


text:
Q: Can a perfect insulator, i.e. matter devoid of all electrons conduct electricity? Few weeks ago an article on Nautilus was published on Neutron stars. After reading that, a question was asked by a friend of mine. He asked if matter in neutron star would be able to transfer electricity as he thought that since neutron stars have no electrons, they should not be able to conduct electricity. My answer based on whatever little I know about it was as follows:

IIRC, by definition if there is no charge (electrons i.e.), there will be no electric current, so there won't be any electrical conduction, however, you could transport other quantities such as spin. At a given point you should have a fermi gas (if diluted enough) or a fermi liquid depending on the number of protons of electrons at that specific time. However, let's assume you can apply a voltage in order to induce a current. You'll have two problems, the charges will radiate and lose kinetic energy and they will interfere with each other via coulomb interaction. In a solid, the electrons are not the charge carriers. The charge carriers are quasi-particle electrons that only exists due to the presence of the lattice and there is screening due to the core electrons and that is why in many cases you can consider them as a non-interacting electron/hole gas. In a real electron gas the coulomb interaction is long range and there will be radiation due to the voltage. So, if you sum this with the fact that the mean time this proton-electron pair is probably very small I would say the conduction should be close to zero on a bulk scale. But again they transport neutrons. Although, for me it is quite interesting neutron transport, because it can be related to spin-transport which is something I am interested in.
That is what I think matters should be, unless I don't remember some details or/and have some fundamental misunderstandings in this regard. I think this paper should clear up some doubts regarding this.

I would like to know from experts at Physics StackExchange if what I have replied as an answer to him is correct, or are there some or fundamental misunderstandings on my part (if any). Have I missed some points which should have been stated with lucidity? I apologize in advance if this question has been asked here before me. Regards!

A: Neutron stars are electrically conductive because the neutrons are able to decay into protons and electrons. An equilibrium is setup so that the Fermi energy of the neutrons is equal to the sum of the Fermi energies of the protons and electrons. At typical neutron densities inside a neutron star, the n/p ratio is around 50-100 (the numbers of protons and electrons are equal). e.g. see What stabilizes neutrons against beta decay in a neutron star?
The protons in the deep interior are likely to be both superfluid and superconducting once the neutron star has cooled for a few hundred years or so.
Degenerate electrons also have a very high conductivity because, despite what you say in your post, they are not susceptible to long range interactions or scattering since there are no free states for them to scatter into. The long mean free paths mean both a high thermal and electric conductivity. Degenerate electrons are present both in the deep interior of the neutron star and the crust, right up to very close to the surface.
The very high electrical conductivity of neutron stars combined with their strong magnetic fields forms the basis of the original Julian & Goldreich (1969 ) model for the pulsar phenomenon.


text:
Q: Opening up a CMYK PSD file in GImp (2.8) I am running Gimp 2.8 and tried to open up a CMYK psd file and got this error:

Opening 'homepage.psd' failed: Procedure 'file-psd-load' returned no return values

Am I missing a plugin? Is there a way to do this? My preference is not to use tools like imagemagick to convert the psd into many pngs but rather to open it directly in Gimp.

A: GIMP won't open CMYK PSD files, it simply doesn't have CMYK mode for images. It will convert and open CMYK TIFF files, however, via separate+ plug-in.


text:
Q: symfony4.3 can't use ValidatorInterface in controller when using ajax Im trying to validate a form submitted with ajax in my controller using the ValidatorInterface.
But i get this error:
Could not resolve argument $validator of "App\SocialStudio\AdminBundle\Controller\InfluencersController::addinfluencerajax()", maybe you forgot to register the controller as a service or missed tagging it with the "controller.service_arguments"?
This is my controller:
<?php
namespace App\SocialStudio\AdminBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
use App\Entity\Influencer;
use App\Form\Type\InfluencerType;

use Symfony\Component\Validator\Validator\ValidatorInterface;

class InfluencersController extends AbstractController
{
    public function Influencers(Request $request)
    {
        // Get all Inlfuencers
        $influencers = $this->getDoctrine()
            ->getRepository(Influencer::class)
            ->findAll();

        // create modal form
        $influencer = new Influencer();
        $addInfluencerForm = $this->createForm(InfluencerType::class, $influencer);

        return $this->render('@Admin/influencers.html.twig', [
            'menu' => 'influencers',
            'influencers' => $influencers,
            'addInfluencerForm' => $addInfluencerForm->createView(),
        ]);

    }

    public function addInfluencerAjax(Request $request, ValidatorInterface $validator)
    {

        ... form handling happens in this function ...

    }

}

This is my code for the ajax call:
$('#submitAddInfluencerForm').click(function(e){
           e.preventDefault();
            addInfluencerForm = $('#addInfluencerForm').serialize();

            $.ajax({
                url:'{{ path('AddInfluencerAjax') }}',
                type: "GET",
                dataType: "json",
                data: {
                    "influencer": addInfluencerForm
                },
                async: true,
                success: function (return_data)
                {
                    ...
                }
            });

        });

services.yaml
services:
  _defaults:
    autowire: true
    autoconfigure: true

  App\:
    resource: '../src/*'
    exclude: '../src/{DependencyInjection,Entity,Migrations,Tests,Kernel.php}'

  App\Controller\:
    resource: '../src/Controller'
    tags: ['controller.service_arguments']

and i put this in my framework.yaml
framework:
   validation: { enable_annotations: true }

`

A: Wtih the help of Leprechaun I found a way that works.
Add to controller class:
private $validator;
    public function __construct(
        ValidatorInterface $validator
    ) {
        $this->validator = $validator;
    }

and get the validator in the function like this:
$validator = $this->validator;


text:
Q: Are there several performance penalties for using Objects with functions and mixins, rather than prototypes? One common way to do OOP in JavaScript involves using objects with functions attached to them, instead of using the built-in prototypes, constructors and the new operator. Mixins are often used to combine 2 objects by pasting member-variables, simulating inheritance.
Measuring whether that kind of practice has consequences for performance is hard, because specific benchmarks don't tell much in this case. Are there such performance penalties, and how severe are them?

A: If you do OOP using constructors, prototypes, news, etc, this is something V8 (JS engine in Chrome and Node.js) specially optimizes for. Your user properties will be even stored side by side with their internal properties, like in C++ or Java objects.
One of the benchmarks used to tune V8 is heavily object oriented like this http://octane-benchmark.googlecode.com/svn/latest/deltablue.js
If you attach properties dynamically or do some other sleazy tricks, you will of course confuse the heuristics for this and probably set yourself back.
This is of course engine specific.
I should also mention the general disclaimer that if you are doing UI code like "click handler shows an text area", then this doesn't matter. You could be collecting stack traces on every method call and not notice any perf issue.

A: If you're worried about this you could mix in on the prototype but as Bergi says; when calling a method many times it actually has a shorter look up if you have the method on the instance instead of on it's prototype.
Here is how to mixin on the prototype:
function mixin(source, target){
  for(thing in source){
    if(source.hasOwnProperty(thing)){
      target[thing]=source[thing];
    }
  }
};
var canSpeak = function(){
  //initialize instance specific values
  this.canSpeakMessage="Hello World";
  this.someArrayThatNeedsToBeInitialized=[];
};
canSpeak.prototype.speak = function(){
  console.log(this.canSpeakMessage);
}
var Test= function(){
  //init instance specific values for canSpeak
  canSpeak.apply(this,arguments);
};
mixin(canSpeak.prototype,Test.prototype);

var t = new Test();
t.speak();//=Hello World


text:
Q: Check if shutdown schedule is active and when it is I have been trying to determine if a shutdown has been scheduled in my system (Ubuntu 17.10). If I input via terminal "shutdown 100", it confirms that system will shut down at a time. But later on, how can I check which time it was if I have that terminal close already.
I found several solutions but none of them works:
ps -ef | grep shutdown

It shows shutdown all the time, even if shutdown has been cancelled.
systemctl status systemd-shutdownd.service

It seems it does not work anymore
cat /run/systemd/shutdown/scheduled

It returns the same either if there is shutdown pending or not.

A: A very simple solution:
date -d @`cat /run/systemd/shutdown/scheduled | head -n 1 | cut -c6-15`

A: I've had success using
$ busctl get-property org.freedesktop.login1 /org/freedesktop/login1 org.freedesktop.login1.Manager ScheduledShutdown

For example:
$ sudo shutdown -h +30
Shutdown scheduled for Wed 2018-10-10 09:33:44 UTC, use 'shutdown -c' to cancel.
$ busctl get-property org.freedesktop.login1 /org/freedesktop/login1 org.freedesktop.login1.Manager ScheduledShutdown
(st) "poweroff" 1539164024057786
$ sudo shutdown -c
$ busctl get-property org.freedesktop.login1 /org/freedesktop/login1 org.freedesktop.login1.Manager ScheduledShutdown
(st) "" 0


text:
Q: Which reflects more sunlight energy, aluminum or silver mirrors? I am building a solar oven.
I intend to use mirrors.
however I am uncertain how to determine which will reflect more sunlight, Aluminum or Silver mirrors. How to go about this?

A: At the infrared wavelengths where you will get most energy there is very little difference in reflectivity.
Aluminium mirrors are generally cheaper and will last longer. Silver mirrors quickly tarnish unless they are protective over-coated.

A: The use of silver as the reflective layer is claimed to lead to higher efficiency levels, because it is the most reflective metal.
https://en.wikipedia.org/wiki/Solar_mirror


text:
Q: NDSolve: How to perform a reverse integration consistency check? Let there be the following NDSolve code:
s = NDSolve[{y'[x] == y[x] Cos[x + y[x]], y[0] == 1}, y, {x, 0, 30}]

I think it may be a usefull idea to use as a constistency check the "reverse" NDSolve i.e.  define
fy[x_]:=First[Evaluate[y[x]/.s]

then integrate backwords
revs = NDSolve[{ry'[x] == ry[x] Cos[x + ry[x]], ry[30] ==fy[30] }, ry, {x, 30, 0}]

and finally check whether one is back at the initial point
  revfy[x_]:=First[Evaluate[ry[x]/.revs]

  error=Abs[revf[0]-1]/1

However this is a time consuming approach.
Can NDSolve  do this automatically (integrate from 0 to 30 and then backwords form 30 to 0)? Is there an equivalent error estimate?

A: Is this what you want?
NDSolve[{y'[x] == y[x] Cos[Sign[30 - x] x + y[x]], y[0] == 1}, y, {x, 0, 60}]
%[[1, 1, 2]][0] - %[[1, 1, 2]][60]
(* 0.0662557 *)

A: Might be simpler to just use a high working precision and very small step size to assure accuracy:
s = NDSolve[{y'[x] == y[x] Cos[x + y[x]], y[0] == 1}, y, {x, 0, 30},WorkingPrecision->50,MaxStepSize->1/5000]

Bet that's pretty close to the actual value at x=30.  I've solved them with precision=120 and step size=1/1000000 and accurate upwards to 50 decimal places but takes a while and of course to use high precision, need to input all data to NDSolve likewise with higher precision like changing 0.5 to 1/2 and so forth if possible.


text:
Q: Quantum transitions In an atom, an electron absorbs a photon and jumps to a higher energy state. Thus the wavefunction for electron changes.
1.How does the photon interact with the initial wavefunction? How does this energy transfer take place?
2.Does the wavefunction change instantaneously or is there some time delay?


text:
Q: How to set custom font to a html loaded with a WebView in Android? I am trying to load a custom font into a webview. I know there are several solutions but non worked for me.
I am loading the data into the webview with this:
webview.loadDataWithBaseURL("file:///android_asset/", setHTML(it), "text/html", "utf-8", null)

private fun setHTML(text: String): String {
    return "${text}ffff"
}

And my text is i.e  test
Here are my fonts which I'd like to use:

Anybody got an idea what I'm doing wrong?

A: Try this solution:
String text = "";
String pas = "";
String myHtmlString = text+ YourTxext + pas;
wv.loadDataWithBaseURL(null,myHtmlString, "text/html", "UTF-8", null);


text:
Q: FolioReader-Android Здравствуйте, подскажите пожалуйста почему приложение при старте падает
Вот мой класс
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    Intent intent = new Intent(getApplicationContext(), FolioActivity.class);
    intent.putExtra(FolioActivity.INTENT_EPUB_SOURCE_TYPE, FolioActivity.EpubSourceType.RAW);
    intent.putExtra(FolioActivity.INTENT_EPUB_SOURCE_PATH, R.raw.niga);
    startActivity(intent);
}

Вот логи..

A: Скорее всего, у ридера не получается прочитать Вашу книгу. Если посмотреть в исходники, вероятнее всего не инициализируется поле mBook в 164й строке. Советую покопаться в классе FileUtil, начав с метода saveEpubFile. Попробуйте сделать то же самое с вашим ресурсом, возможно Вам удастся выяснить, из-за чего не удаётся получить к нему доступ.


text:
Q: Chrome Extension Login Security I have a website where users can signup and I want to provide some features using a chrome extension, I'm a bit concerned about security:
My idea is to show a login form in a popup and then send an ajax request to my server with username/password (using HTTPS) and then store a token into localStorage that is used for following ajax calls.
Is this insecure? Why? I don't understand how this is more insecure then using a form on my website for example or logging sending an ajax request from a client side js framework

A: This is secure, as long as you handle the token properly on the client side (i.e. only submit it to your site, and no other sites).  The danger is that you are essentially going around the work that Google and the open source community has done to secure Chrome/Chromium from XSS, CSRF, and other token stealing attacks.  Make sure that no other sites can request the token from your extension (this is done in the browser through same-domain enforcement).  You will need to use certificate signing to verify the origination of the request (you should be able to reuse the private certificate that you use for SSL).
It is important that you treat all client requests as malicious even if they originate from your extension.  The server must perform all secure processing as if the client were completely compromised.  On the server side, you shouldn't even know if the user is using your extension or a regular browser, because security wise it doesn't matter.
As for the storing of the login credentials on the client side, you should never store the password in plain text.  You should salt and hash it, and submit that hash to the server.  Based on your question, it sounds like you wouldn't store the user's credentials anyway, just a token.  If that is the case, and the token doesn't contain anything sensitive, you should have no problem storing it.  Make sure though that you expire tokens on the server side and force re-authentication periodically.
Answer was edited for clarification and typos


text:
Q: Trying to calculate a Win/Loss ratio based on specific cells I'm trying to have a W:L ratio calculated into my Google sheet based on specific cells.
B2:M2 are manually updated to be either W or L
I would like O1 and P1 to reflect. So if there are 7 W's and 5 L's between B2:M2, I would like cell O1 to show (7)W and have cell P1 show (5)L
Any help would be appreciated. I'm relatively noobish to Google sheets
Image below!
B2:M2 are manually updated to be either W or L

A: W → ="("&COUNTIF(B2:M2,"=W")&") W"
L → ="("&COUNTIF(B2:M2,"=L")&") L"
To calculate just the number of W or L, just remove the text extras, it would look like this:
W → =COUNTIF(B2:M2,"=W")
L → =COUNTIF(B2:M2,"=L")


text:
Q: Cron Job not triggered by config.xml settings I have a local module with a cron job configured in config.xml to run once per day at 10:30am:
<sc_followup>
    <schedule>
        <cron_expr>30 10 * * *</cron_expr>
    </schedule>
    <run>
        <model>followup/cron::processFollowupEmails</model>
    </run>
</sc_followup>

I also have the system's crontab set up to run cron.php every 5 minutes:
*/5 * * * * php -f /abspath/mysite/cron.php > abspath/mysite/var/log/cron.log

The admin cron settings are:

Lastly, I have cleared the caches.
My issue is that processFollowupEmails() is running once every 5 minutes instead of once per day at 10:30am. What do I need to change in my configuration to achieve that?

A: It turned out that the above configuration does work for me. My mistake was in not accounting for the time between when the last cron schedule was generated and when the new schedule is generated.
When I was testing processFollowupEmails(), I had the config.xml settings at */5 * * * *. I updated it, but it kept running every 5 minutes until the "generate schedules"/"schedule ahead" settings came around again.
I'm leaving this answer here intead of deleting the question in case any one else forgets about the scheduling ahead.


text:
Q: Como fazer uma query que consulte apenas o DIA de uma data? Tenho um banco MYSQL e preciso de um SQL que consulte o DIA DE PAGAMENTO no campo DIA (este campo terá apenas o DIA do mês que o cliente escolheu para efetuar o pagamento, este campo é do tipo INT) e me exiba algum registro sempre que faltar menos de 5 dias para o dia de pagamento. Claro que este campo DIA se baseará no dia da data atual.
Tenho este código:
Select * from conta where DAYOFMONTH(CURDATE()) - 5 = dia;

Só que não funciona, pois ele mostra apenas os registros que faltam 5 dias para o vencimento, ou seja, se faltar 4 dias, 03 dias, 02 dias, 01 dia ele não mostra nada. Preciso de algo que sempre exiba algum resultado quando restar menos de 5 dias para o vencimento.

A: Select * from tabela where DAYOFMONTH(CURDATE())-5 = colunaDia;

A: beleza ?
Cara, não sei como está sua estrutura de base, mas só utilizando o dia do pagamento fica bem mais complicado validar. Olha só uma situação, hoje é dia 29, se eu for considerar todo mundo que tem menos de 5 dias para vencer teria que pegar todo mundo que vai de hoje até o dia 3 de abril. Então se o teu cliente marcou que o dia 1 é o dia de pagamento dele você terá que considerar que "29" - "1" vai atender a sua regra de 5 dias, pois você está passando na sua dúvida que tem opção para trabalhar apenas com a data atual e um campo inteiro de dia.
Porém...
Se você quer controlar os vencimentos, seria interessante ter uma tabela com todos os lançamentos com seus respectivos vencimentos para frente.
Ex:

Cliente deseja pagar algo, hoje dia 29/03, em 3x e o dia de pagamento dele será todo dia 10.

logo

Tenho uma tabela onde vou lançar três movimentos para cobrança futura com vencimento de: 10/04/2016, 10/05/2016 e 10/06/2016.

Assim fica mais fácil e simples tirar a diferença das datas e verificar se a quantidade de dias é menor que os 5 que você deseja.
Qualquer coisa explica um pouco mais como está sua estrutura de tabela, sem conhecer o banco é um pouco mais complicado ajudar.
Se a minha sugestão foi útil, sinaliza ai!
Valeu!

A: Você pode usar o DATEDIFF para fazer isso.
Na função você tem que usar a data atual no primeiro parâmetro no segundo você adiciona o total de dias que você que verificar a data atual ou seja 5 . DATEADD(day,5, getdate()) com os dias adicionados basta fazer o DATEDIFF
DATEDIFF(day, GETDATE() , DATEADD(day,5, getdate()))

declare @Usuario table
(
  nome varchar(20),
  diapagamento int
)

insert into @Usuario values
( 'zé', 5),
( 'fulano', 15),
( 'manoel', 25),
( 'joao', 30),
( 'carlos', 5),
( 'zpauloé', 2)

select *  from @Usuario
where diapagamento <= DATEDIFF(day, GETDATE() , DATEADD(day,5, getdate()))

diapagamento <= -- aqui retornará todos os usuários que onde falte 5
  ou menos dias para o dia do pagamento.

Bom, isso está em sql server mais a ideia é a mesma.
Select * from conta
where dia <= DATEDIFF(DATE_ADD(CURDATE(),INTERVAL 5 DAY), CURDATE())
--where DAYOFMONTH(CURDATE()) - 5 = dia;


text:
Q: Memory Management in perl I have facing a weird issue of handling  memory in perl.
I am working in a perl application which uses pretty big hash-structures. I am assigning the has ref to and fro objects. But at the end it seems even if I am deallocating the object and the hash, the memory usage is remaining same.
Here is a sample of the problem:
 my $hash = {};
 .............
 this ds gets populated with a lot of data ...
 .......
 {
      my $obj = new Class("data"=>$hash);
 .......
 .......
 ......

 }

 #even undefing the $hash
 undef $hash;

 # I can expect some improvement in Memory Utilization, but its not happening

I think I am doing some very basic mistakes. Can any one suggest?

A: Generally speaking, Perl memory management does what you need to do, and you needn't worry about it.  For example, what is the harm of keeping a huge chunk of memory allocated for the rest of your program?  Probably none.  Perl will release it if your OS is in danger of running  out of memory.
Suppose you had some special case, like a script that runs constantly in the background, but occasionally needs to do a memory-intensive task.  You could solve this by separating it into two scripts: background.pl and the memory-intensive-task.pl.  The background.pl would execute memory-intensive-task.pl when needed.  The memory would be freed when this program completed and exited.

A: You can't really return memory back to the OS. Perl will usually keep it in order to reallocate it later, though it will garbage collect occasionally.
See http://learn.perl.org/faq/perlfaq3.html#How-can-I-free-an-array-or-hash-so-my-program-shrinks-
and
http://clokwork.net/2012/02/12/memory-management-in-perl/


text:
Q: Is Windows Store app PurchaseResults.TransactionId the same as receipt's ProductReceipt->Id? Do somebody happen to know, when you do:
var purchase_result = await CurApp.RequestProductPurchaseAsync(product_id);
string transaction_id= purchase_result.TransactionId.ToString();

is transaction_id the same as ProductReceipt->Id in purchase_result.ReceiptXml:
...
<ProductReceipt Id="c5318bba-4c8b-47f7-a6d5-f373f31c8b91" ProductId="mytestid1" PurchaseDate="2016-10-25T18:17:55Z"
        ExpirationDate="9999-12-31T23:59:59Z" ProductType="Durable" AppId="myappid1"/>
...

(I can't check it currently in my environment, but I'd like to know it before all code will be written.)

A: Tested on debug environment, looks like it's true.


text:
Q: MySQL UPDATE records referenced by another table I need to update a specific column of all records whose primary key is referenced by a specific column in another table.  (The foreign key relationship is already set up.)
An analog to what I'm trying to do would be this:
Table 1: Sandwiches

Sandwich(varchar) [Primary Key]
Requested(bool)

Salami
1

Pastrami
Null

Ham
0

Turkey
1

Table 2: Requests

Character(varchar)
Sandwich (varchar) [Foreign Key to Sandwiches]

Charlie
Ham

Linus
Turkey

Marcy
Ham

Lucy
Salami

Snoopy
Pastrami

I want every null value in sandwiches.requested updated to 1 if there is a record in requests referencing it's primary key.  E.g., since Pastrami has a null value for sandwiches.requested and Snoopy requested Pastrami, I want sandwiches.requested updated to 1  for Pastrami, so that Sandwiches looks thus:
Table 1: Sandwiches

Sandwich(varchar) [Primary Key]
Requested(bool)

Salami
1

Pastrami
1

Ham
0

Turkey
1

I know how to:
SELECT SANDWICHES.SANDWICH, SANDWICHES.REQUESTED FROM SANDWICHES INNER JOIN REQUESTS ON SANDWICHES.SANDWICH = REQUESTS.SANDWICH WHERE REQUESTED = NULL

which returns:

Sandwich
Requested

Pastrami
Null

telling me which ones I want to update, but say my data set were too large to manually perform all the updates.  How would I create an update command to update every match?

A: Update SANDWICHES JOIN REQUESTS ON SANDWICHES.SANDWICH = REQUESTS.SANDWICH set SANDWICHES.REQUESTED = 1 WHERE SANDWICHES.REQUESTED = NULL

A: Most straightforwardly, just:
update Sandwiches
set Requested=1
where Sandwich in (select distinct Sandwich from Requests)


text:
Q: After calling setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT) screen is not roating for the second time This question may look similar but it's not the kind of.
I was developing an android app that streams video from the internet and there I had to implement the fullscreen button which toggles screen landscape(full screen) and portrait.
From portrait mode when I need to go to landscape I called the method setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
but next time when I click the button instead of calling the method setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT); the screen is not coming in portrait mode back.
NOTE: I cant use two separate layouts for portrait and landscape
UPDATE
The screen rotation button works this was
  mScreenRotateButton.setOnClickListener(new OnClickListener() {
   @Override
   void onClick(View v){
        if (inPortrait) {
          setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
       } else {
           setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR_PORTRAIT);
       }
   }});

After doing this for once when I am physically rotating the device the screen is not rotating.

A: You can use Boolean to check the status and revert back. Here is the snippet which I did using switch button.
aSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
    @Override
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
        if (isChecked){
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
        }else {
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        }
    }
});


text:
Q: Not able to get client IP address on server in NodeJS I am working on nodeJS project in this project I want to get client IP address. For this I am using public IP package, I'm using
the following code, and installed the package accordingly.
'npm install --save public-ip

and following code
publicIp.v4().then(ip => {

});'

The above code is working fine locally, but when deployed on the server(AWS server), it's giving the AWS server IP.
Help me resolve the issue.


text:
Q: Configure multiple entry points that created multiple files in angular.json I have earlier worked on angular 5 with webpack where webpack supports multiple entry points that created multiple files
  entry: {
    app: 'src/app.ts',
    vendor: 'src/vendor.ts'
  }

Link to refer: https://v5.angular.io/guide/webpack
However now I started working on angular 7 which has CLI. I dont find a way this can be handled in angular cli. What is the better of way splitting files into chunks? Should we go ahead and use webpack instead of cli or can it be done using CLI? Any help is greatly appreciated.

A: Angular CLI is a nice wrapper around some default Webpack settings (among other things). And by default, ng build will create the following JS files:

*

*main.js

*polyfills.js

*runtime.js

*styles.js

*vendor.js

(These files may be suffixed with a hash if you configured it with "outputHashing": "all", which is the default for production)
Also, if you take advantage of lazy-loading for your features modules. Angular CLI may split the app.js into chunks named like 1.chunk.js, 2.chunk.js, etc.

A: If you want to create chunks of each node modules in vendor js you can do simply configure in webpack.config.js as below:
module.exports = {
  //...
  optimization: {
    splitChunks: {
      cacheGroups: {
        commons: {
          test: /[\\/]node_modules[\\/]/,
          name: 'vendors',
          chunks: 'all'
        }
      }
    }
  }
};


text:
Q: How to update mongodb document Hi i'm really mongodb newbie.
I have a document like this:
{
    "_id": ObjectId("53182e32e4b0feedb1dea751"),
    "solutions": [
        [
            {
                "solution": "Double Room Economy (Without Breakfast)",
                "board": "Room Only",
                "id": "HK-15501871",
                "price": 5000,
                "available": "1",
                "CXL": "[]",
                "unique": 0
            },
            {
                "solution": "Double Room Economy (With Breakfast)",
                "board": "Room Only",
                "id": "HK-15501871",
                "price": 4600,
                "available": "1",
                "CXL": "[]",
                "unique": 1
            },
            {
                "solution": "Double Room Economy (Room Only)",
                "board": "Room Only",
                "id": "HK-15501871",
                "price": 5500,
                "available": "1",
                "CXL": "[]",
                "unique": 2
            }
        ]
    ]
}

And i need to update the field CXL inside the second array of solutions.
so solutions.1.CXL
This is how i take document:
$collection = $this->getCollection();
$query      = array("_id"=>new MongoId($id));
$document   = $collection->findOne($query);

now i need to update that field without touch the other.
How can i do?
Thanks!
SOLVED THANKS TO @Sammaye
i solved in this way:
$collection->update(
    array('_id' => new MongoId('..')),
    array('$set' => array('solutions.0.1.CXL' => 'something'))
);

A: Edit
To actually update by the first index then you can do:
$db->collection->update(
    ['_id' => new \MongoId($id)],
    ['$set' => ['solutions.0.1.CLX' => 'whatever']]
);

I misread the question in posting the information below:
So what you wanna update all CXL fields in the document (since you are only searching by top level document _id)?
That isn't possible without manually pulling this document out and iterating the subdocuments in the solutions field and then resaving it.
This is becausde there is currently no way of saying, "Update all that match"
This, however, is most likely the JIRA you would want to look for: https://jira.mongodb.org/browse/SERVER-1243

A: As long as you know you are going to update the second element then use the index of the array to do so. But that problem next. First you need the $set operator in order not to blow away your document and just set the field value:
db.collection.update(
    { _id: ObjectId("53182e32e4b0feedb1dea751") },
    { $set: { "solutions.0.1.CXL": [ 1, 2, 3 ] } }
)

If you just want to add to the array rather than replace the whole thing, then just use $push instead:
db.collection.update(
    { _id: ObjectId("53182e32e4b0feedb1dea751") },
    { $push: { "solutions.0.1.CXL": 4 } }
)

If you are paying attention to the notation, then you will notice that the array index values are present in the field to be updated. There is a very good reason for this, which can be read on the documentation for the positional $ operator.
The issue is that you have a nested array, which as the documentation refers to, causes a problem if you try to match items within that nested array. That problem is, if you try to use the "positional" operator to find the matched index of something you look for in a query, then it will contain the value of the first array index match that it finds.
In this case that would be your "top level" array and the "found" index is 0 and not 1 as you may expect.
Please be aware of this issue if you intend to use nested arrays.

A: You can update like this:
update({
       _id: ObjectId("53182e32e4b0feedb1dea751"),
       solutions.id: HK-15501871,
       solutions.CLX: "Whatever!",")
   },{
       $set: {"comments.$.type": abc}
   }, false, true
);

You may want to go through this once
http://docs.mongodb.org/manual/reference/method/db.collection.update/


text:
Q: NoSuchFileException thrown while creating a symlink using Files.createSymbolicLink() method I have a created a gradle project HERE to experiment with the symbolic link creation. I have written a gradle task runScript that in turn executes a groovy script myscript.groovy that has the logic for symbolic link creation.
NOTE : valid_symlink branch makes use of  SNIPPET 1 and invalid_symlink makes use of SNIPPET 2. So instead of uncommenting the SNIPPETS and running the task, you can just switch to respective branch and run the task.
With SNIPPET 1 of myscript.groovy
Whenever I try executing the task runScript by uncommenting the SNIPPET 1 in myscript.groovy(when in master branch) I can see that teh symlink is created successfully under the symlinkTEstFiles directory but the gradle build fails with below exception :
Exception in thread "main" java.nio.file.NoSuchFileException: D:\git-repos\test-cloning-symlink-demo-mcve\symlink-demo-mcve\..\..\..\symlinkTestFiles\toSymlink.groovy
        at sun.nio.fs.WindowsException.translateToIOException(WindowsException.java:79)
        at sun.nio.fs.WindowsException.rethrowAsIOException(WindowsException.java:97)
        at sun.nio.fs.WindowsException.rethrowAsIOException(WindowsException.java:102)
        at sun.nio.fs.WindowsFileSystemProvider.createSymbolicLink(WindowsFileSystemProvider.java:585)
        at java.nio.file.Files.createSymbolicLink(Files.java:1043)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at java.lang.reflect.Method.invoke(Method.java:497)
        at org.codehaus.groovy.reflection.CachedMethod.invoke(CachedMethod.java:98)
        at groovy.lang.MetaMethod.doMethodInvoke(MetaMethod.java:325)
        at org.codehaus.groovy.runtime.callsite.StaticMetaMethodSite.invoke(StaticMetaMethodSite.java:46)
        at org.codehaus.groovy.runtime.callsite.StaticMetaMethodSite.call(StaticMetaMethodSite.java:91)
        at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCall(CallSiteArray.java:47)
        at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:116)
        at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:136)
        at myscript.run(myscript.groovy:23)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at java.lang.reflect.Method.invoke(Method.java:497)
        at org.codehaus.groovy.reflection.CachedMethod.invoke(CachedMethod.java:98)
        at groovy.lang.MetaMethod.doMethodInvoke(MetaMethod.java:325)
        at groovy.lang.MetaClassImpl.invokeMethod(MetaClassImpl.java:1225)
        at groovy.lang.MetaClassImpl.invokeMethod(MetaClassImpl.java:1034)
        at org.codehaus.groovy.runtime.InvokerHelper.invokePogoMethod(InvokerHelper.java:947)
        at org.codehaus.groovy.runtime.InvokerHelper.invokeMethod(InvokerHelper.java:930)
        at org.codehaus.groovy.runtime.InvokerHelper.runScript(InvokerHelper.java:428)
        at org.codehaus.groovy.runtime.InvokerHelper$runScript.call(Unknown Source)
        at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCall(CallSiteArray.java:47)
        at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:116)
        at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:136)
        at myscript.main(myscript.groovy)

FAILURE: Build failed with an exception.

With SNIPPET 2 of  myscript.groovy
Running gradle task runScript by uncommenting SNIPPET 2(when in master branch) does not create  symlink and the build fails with below esxception :
Exception in thread "main" java.nio.file.NoSuchFileException: ..\..\..\symlinkTestFiles\toSymlink.groovy
        at sun.nio.fs.WindowsException.translateToIOException(WindowsException.java:79)
        at sun.nio.fs.WindowsException.rethrowAsIOException(WindowsException.java:97)
        at sun.nio.fs.WindowsException.rethrowAsIOException(WindowsException.java:102)
        at sun.nio.fs.WindowsFileSystemProvider.createSymbolicLink(WindowsFileSystemProvider.java:585)
        at java.nio.file.Files.createSymbolicLink(Files.java:1043)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at java.lang.reflect.Method.invoke(Method.java:497)
        at org.codehaus.groovy.reflection.CachedMethod.invoke(CachedMethod.java:98)
        at groovy.lang.MetaMethod.doMethodInvoke(MetaMethod.java:325)
        at org.codehaus.groovy.runtime.callsite.StaticMetaMethodSite.invoke(StaticMetaMethodSite.java:46)
        at org.codehaus.groovy.runtime.callsite.StaticMetaMethodSite.call(StaticMetaMethodSite.java:91)
        at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCall(CallSiteArray.java:47)
        at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:116)
        at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:136)
        at myscript.run(myscript.groovy:22)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at java.lang.reflect.Method.invoke(Method.java:497)
        at org.codehaus.groovy.reflection.CachedMethod.invoke(CachedMethod.java:98)
        at groovy.lang.MetaMethod.doMethodInvoke(MetaMethod.java:325)
        at groovy.lang.MetaClassImpl.invokeMethod(MetaClassImpl.java:1225)
        at groovy.lang.MetaClassImpl.invokeMethod(MetaClassImpl.java:1034)
        at org.codehaus.groovy.runtime.InvokerHelper.invokePogoMethod(InvokerHelper.java:947)
        at org.codehaus.groovy.runtime.InvokerHelper.invokeMethod(InvokerHelper.java:930)
        at org.codehaus.groovy.runtime.InvokerHelper.runScript(InvokerHelper.java:428)
        at org.codehaus.groovy.runtime.InvokerHelper$runScript.call(Unknown Source)
        at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCall(CallSiteArray.java:47)
        at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:116)
        at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:136)
        at myscript.main(myscript.groovy)

I am just not able to figure out the cause of exception. Whats wrong with my code ?
If I just execute the myscript.groovy, I do not get any exception and the symlinks are created in both cases i.e. SNIPPET 1 and SNIPPET 2. But the symlink created by SNippet 2 doesnot open.
Why does my groovy script runs fine when executed directly but throws exception when executed through gradle task.
Please guide me.