text:
Q: Linear Algebra - Hyperplane and a linear mapping I'm doing some problems in Linear Algebra and this is the one I just have no idea how to start with. We are given a linear transformation $ f \in L(\mathbb R^{6\times1} , \mathbb R^{4\times1}) $ with its coordinate matrix:
$$
        \begin{pmatrix}
        -1 & -2 & -2 & -1 & -5 & 0 \\
        1 & 1 & 1 & 1 & 3 & 0 \\
        1 & 3 & 2 & 2 & 5 &1 \\
        1 & 2 &1 & 1 &3 &0 \\
        \end{pmatrix}
$$
And besides that, a hyperplane $ \mathbf H \subset \mathbb R^{4\times1}$ with the equation $ y_1 + y_2 + y_3 + y_4 = 0$
We are supposed to find a linear equation with 6 unknown variables $ x_1, ... , x_6$ that have a solution set matching with $f^{-1}(\mathbf H)$. We are also supposed to find a basis of the subspace $f^{-1}(\mathbf H)$.
I'm not very clear with the fact that they can build an inverse of a function that isn't bijective (or am I wrong for concluding that just because I can't build an inverse of the coordinate matrix)?
There was a tip given: we should use a transpose $f^T$ for solving the fist part of the question.
Any kind of help/tip is welcome, at least how to approach or start the problem!

A: Remember the handy-dandy formula
$$A^\top z\cdot x = z\cdot Ax \quad\text{for $A\in L(\Bbb R^n,\Bbb R^m)$, $x\in\Bbb R^n$, $z\in\Bbb R^m$}.$$
You are given the hyperplane $\mathbf H = \{y\in\Bbb R^4: z\cdot y=0\}$, where $z=\begin{bmatrix} 1\\1\\1\\1 \end{bmatrix}$. Then $f^{-1}(\mathbf H) = \{x\in\Bbb R^6: z\cdot f(x) = 0\} = \{x\in\Bbb R^6: f^\top(z)\cdot x = 0\}$.


text:
Q: How does a capacitive multi-touch screen capture multiple triggers? On which principles does a capacitive touch screen work to enable detection of multiple triggers?
I understand that there are two layers; a driving layer and a sensing layer (with x or driving and y or sensing lines) that form a grid that when touched causes a trigger of some-sort.
How can it determine multiple touches, and what if your multiple touches effect the same driver or sensing line, how does it determine where those touches originated from?

A: If you are familiar with the keyboard matrix circuits, and know how it works. You can understand this kind of capacitive sensor well.

You know, in a 2-D map, any points are determined by (x,y). Points with same 'x' (or 'y') but different 'y' (or 'x') are recognized as different points.
Refs:

*

*Combining Self- & Mutual-Capacitive Sensing for Distinct User Advantages

redpajama_set_name: RedPajamaStackExchange


text:
Q: adding a custom method to Meta class in django I have an AbstractBase model class that gets inherited by several models in their respective apps. I want the user to be able to set a name that will be used in the verbose_name field in the Meta class. If a user provides a name in one of the fields in the AbstractBase model, then that field will be used as the verbose name
this is what I have tried so far
class AbstractBase(models.Model):
   ......
   custom_name = models.CharField(blank=True)

   class Meta(object):
      abstract = True

      def update_verbose_name(self, custom_name):
          if self.project_setting is not None:
              return verbose_name == self.custom_name

when I run this it gives me TypeError: 'class Meta' got invalid attribute(s): update_verbose_name
is there another way that I solve this?

A: How about changing the indentation like this:
class AbstractBase(models.Model):
   ......
   custom_name = models.CharField(blank=True)

   def update_verbose_name(self, custom_name):
       if self.project_setting is not None:
           return verbose_name == self.custom_name

   class Meta(object):
      abstract = True


text:
Q: Find number of distinct paths by which a string can be derived There is a secret message that is a string of length at least 2 containing only the characters A..Z.
Apply a sequence of "operations" to it. An Operation is shown in the example.
Given the final encrypted string, count the number of possible ways you could have produced this string using one or more repeated operations applied to a source string.  Operations are distinct even if they give the same encryption of your secret message.  I.E. : There are four distinct separate ways to obtain AAA from AA.
Here is an example:
The encrypted string is: ABABA. The output would be: 8. Here are the different ways you could have produced ABABA:

*

*Start with AB -> AB+A -> AB+ABA

*Start with AB -> AB+A -> ABA+BA
3.Start with ABA -> AB+ABA

*Start with ABA -> ABA+BA

*Start with BA -> A+BA -> AB+ABA

*Start with BA -> A+BA -> ABA+BA

*Start with ABAB -> ABAB+A

*Start with BABA -> A+BABA

Could you please help suggest an algorithm to solve this. I thought of trying recursion but on bigger inputs my code runs way to slow.

A: Notice that, at each step of your derivation, you wind up with a substring of the "encrypted" string.  There are quadratically many (i.e. O(n^2)) such substrings.
You can find the number of ways to derive the final string from each of its suffixes and prefixes straightforwardly.
So, you have quadratically many possible subproblems, and you can break a problem down into a complete set of subproblems, do the counting on each subproblem, and add the results up.
You get a dynamic programming algorithm out of this by solving each subproblem only once.  This dynamic programming algorithm can be made to run in cubic time.

A: Not sure if this is correct, but here's a recursive attempt in JavaScript:
function f(str){
    var total = 0

    function g(ptr,len){
        for (var i=1; i<= (len%2 == 0 ? len/2 - 1: (len - 1)/2); i++){
            var left = str.substr(ptr,len - i),
                suffix = str.substr(ptr + len - i,i),
                right = str.substr(ptr + i,len - i),
                prefix = str.substr(ptr,i),
                recurseL = false,
                recurseR = false

            if (suffix == left.substr(-i)){
                total++
                recurseL = true
            }
            if (suffix == left.substr(0,i)){
                total++
                recurseL = true
            }
            if (prefix == right.substr(-i)){
                total++
                recurseR = true
            }
            if (prefix == right.substr(0,i)){
                total++
                recurseR = true
            }

            if (recurseR)
                g(ptr + i,len - i)
            if (recurseL)
                g(ptr,len - i)
        }
        return total
    }

    return g(0,str.length)
}

f("ABABA")

Output:
8


text:
Q: Windows: Automated PDF compression (Hot folder) In Windows, is there a way to monitor a folder and automatically compress a PDF that is placed in it?
(by compression, I mean make a PDF smaller (I.e. not zip it), similar to using the reduce file size command in Acrobat).
I know Acrobat has a tool for compressing PDFs which can be batched, but I need it to run automatically when a PDF is added to a folder.

A: There is a product that will do that: http://www.neuxpower.com/products/nxpowerlite-file-server/features/ (not affiliated). To the best of my knowledge, there's no native way to do that in Windows.
It's not the only product. A google search for automated PDF compression should reveal more software that can do that.


text:
Q: Create a new Pootle translation project and upload templates Testing the old 2.5 version of pootle i was quickly able to upload my csv files as Templates.
Hugely impressed by the new features of pootle 2.7 i took 2 days to learn how to publish it on an Apache2 web server on Ubuntu 14. Now that i managed to deploy 2.7 I'm unable to upload the templates as i was able to do in 2.5...
Am I missing something? I somewhere read that it could be currently unsupported but i wish to be sure before taking action.


text:
Q: Is $ \prod\limits_{k=0}^\infty \left(1 + \frac{1}{k!}\right) = \mathrm e^2 $? I was playing around and I came up with this product, which I believe to be equal to $\mathrm e^2$.
$$ \prod_{k=0}^\infty \left(1 + \frac{1}{k!}\right) \stackrel{?}{=} \mathrm e^2 $$
After calculating $1000$ terms of this product, I got approximately $7.36431$ (compare: $\mathrm e^2 \approx 7.38906 $, so convergence is very slow if existent).
I tried looking at some product definitions of $\rm e$, but none deal with the product I want.
I know that the product converges since $\sum_{k=0}^\infty 1/k!$ and $\sum_{k=0}^\infty 1/k!^2 $ converge as well.

A: Fairly close, but as your computation shows, not close enough. The logarithm of the "rest" is not hard to estimate, and is far too close to $0$ to make up the gap.
Remark: For small positive $x$, by an alternating series argument or otherwise, we have $\log(1+x)\lt x$. So the logarithm of the infinite product $\displaystyle\prod_{k=n}^\infty \left(1+\frac{1}{k!}\right)$ is less than $\displaystyle\sum_{k=n}^\infty \frac{1}{k!}$.
By bounding the tail with a geometric series, we find this is $\lt \dfrac{n+1}{n\cdot n!}$.  The exponential of this, for large $n$, is much too close to $1$. A computation of the partial product to $n=8$ is more than  sufficient to show that we cannot have equality.
The convergence of this infinite product is fast, in the same ballpark as the convergence of $\displaystyle \sum\dfrac{1}{k!}$.

A: Calculating the first 10 million terms of the product with a working precision of 2000 digits gives the result
  7.36430827236725725637277250963105

At the moment I calculate less terms with a higher working precision but I would be surprised if the result would change a lot.


text:
Q: Should we ever NOT use EventHandler for our custom .NET events? Reading the official guidelines on publishing events in .NET it says:

Although events in classes that you define can be based on any valid delegate type, even delegates that return a value, it is generally recommended that you base your events on the .NET Framework pattern by using EventHandler, as shown in the following example.

The documentation also mentions that The .NET Framework 2.0 introduces a generic version of this delegate, EventHandler.
It then goes on to show an example using EventHandler, but also an example using a custom delegate type.
Given that it looks like the custom delegate pattern is not strongly discouraged (it even has an official example), is it ever beneficial to create our custom delegates instead of subclassing EventArgs and using EventHandler<CustomEventArgs>?


text:
Q: How to extract details from an mp3 file? How to extract details like the location of the song,artist,album,bitrate,year,genre.. etc using linux command?
I have tried mp3info, but it didn't give much information.
Please Help. Thank you!

A: Did you read man mp3info? It says, in part:
     -p "FORMAT_STRING"

          Print MP3 attributes according to FORMAT_STRING.  FORMAT_STRING is similar to a printf(3) format string in that it is printed verbatim except  for  the
          following conversions and escape sequences. Any conversion specifier may optionally include the various alignment, precision, and field width modifiers
          accepted by printf(3).  See the EXAMPLES section below for examples of how format strings are used in mp3info.

          Conversion Specifiers

             %f     Filename without the path [string]
             %F     Filename with the path [string]
             %k     File size in KB [integer]
             %a     Artist [string]
             %c     Comment [string]
             %g     Musical genre [string]
             %G     Musical genre number [integer]
             %l     Album name [string]
             %n     Track [integer]
             %t     Track Title [string]
             %y     Year [string]
             %C     Copyright flag [string]
             %e     Emphasis [string]
             %E     CRC Error protection [string]
             %L     MPEG Layer [string]
             %O     Original material flag [string]
             %o     Stereo/mono mode [string]
             %p     Padding [string]
             %v     MPEG Version [float]
             %u     Number of good audio frames [integer]
             %b     Number of corrupt audio frames [integer]
             %Q     Sampling frequency in Hz [integer]
             %q     Sampling frequency in kHz [integer]
             %r     Bit Rate in kbps (type and meaning affected by -r option)
             %m     Playing time: minutes only [integer]
             %s     Playing time: seconds only [integer] (usually used in conjunction with %m)
             %S     Total playing time in seconds [integer]
             %%     A single percent sign

A: Also from man mp3info
Display the Title, Artist, Album, and Year of all MP3 files in the cur‐ rent directory. We include the labels File, etc. and insert newlines (\n) to make things more readable for humans:
mp3info -p "File: %f\nTitle: %t\nArtist: %a\nAlbum: %l\nYear: %y\n\n" *.mp3

More options
-p "FORMAT_STRING"

    Print MP3 attributes according to FORMAT_STRING.  FORMAT_STRING
    is similar to a printf(3) format string in that it is printed
    verbatim except for  the following conversions and escape sequences.
    Any conversion specifier may optionally include the various
    alignment, precision, and field width modifiers accepted by
    printf(3).
    See the EXAMPLES section below for examples of how format
    strings are used in mp3info.

Conversion Specifiers
     %f     Filename without the path [string]
     %F     Filename with the path [string]
     %k     File size in KB [integer]
     %a     Artist [string]
     %c     Comment [string]
     %g     Musical genre [string]
     %G     Musical genre number [integer]
     %l     Album name [string]
     %n     Track [integer]
     %t     Track Title [string]
     %y     Year [string]
     %C     Copyright flag [string]
     %e     Emphasis [string]
     %E     CRC Error protection [string]
     %L     MPEG Layer [string]
     %O     Original material flag [string]
     %o     Stereo/mono mode [string]
     %p     Padding [string]
     %v     MPEG Version [float]
     %u     Number of good audio frames [integer]
     %b     Number of corrupt audio frames [integer]
     %Q     Sampling frequency in Hz [integer]
     %q     Sampling frequency in kHz [integer]
     %r     Bit Rate in kbps (type and meaning affected by -r option)
     %m     Playing time: minutes only [integer]
     %s     Playing time: seconds only [integer] (usually used in conjunction with %m)
     %S     Total playing time in seconds [integer]
     %%     A single percent sign

Escape Sequences
     \n Newline
     \t Horizontal tab
     \v Vertical tab
     \b Backspace
     \r Carriage Return
     \f Form Feed
     \a Audible Alert (terminal bell)
     \xhh Any arbitrary character specified by the hexidecimal number hh
     \ooo Any arbitrary character specified by the octal number ooo
     \\ A single backslash character

A: You can use mediainfo:
sudo apt-get update && sudo apt-get install mediainfo

You can extract all sorts of informations using the --inform='<category>;%<parameter1>%[%<parameter2>%, ...]' option; <category> is a string representing a category of parameters and <parameterN> is a string representing a parameter in that category; both categories and parameters available can be listed by running mediainfo --Info-Parameters; for example, to extract the album and the title of a track in an Album - Title format:
mediainfo --Inform='General;%Album% - %Title%' track01.mp3

A: ffprobe <themp3file.mp3>


text:
Q: Passing Generic Quick sort I am very confused with passing. I have created a Quick sort algorithm in eclipse. The class is an abstract class. Here is the Interface class.
public interface ArraySort<T extends Comparable<T>>
{
    /**
     * Sort the array
     */
    public void sort(T[] array);

}

This is the class in which the Quick sort has been created.
public class QuickSort <T extends Comparable<T>> extends ArraySortTool<T>{
    public <T> void quickSort(T[] array, Comparator<T>com, int a, int b) {
        if(a >= b) return;
        int left = a;
        int right = b-1;
        T pivot = array[b];
        T temp;

        while (left <= right){

            //Look for element larger or equal to the pivot
            while(left <= right&&com.compare(array[left], pivot)<0)left++;
            //Look for element smaller or equal to pivot
            while(left <= right&&com.compare(array[right], pivot)>0)right--;
            if(left <= right){
                temp = array[left]; array[right]=array[right]=temp;
                left++; right--;
            }
        }

        //place pivot into its final location marked by left index
        temp = array[left]; array[left] = array[b]; array[b] = temp;

        quickSort(array, com, a, left - 1);
        quickSort(array, com, left + 1,b);

    }

    @Override
    public void sort(T[] array) {
        quickSort(array, int, 0, 0);

    }
}

In order to pass the references I have also tried this method but had no luck.
@Override
    public void sort(T[] array, Comparator<T>com, int a, int b) {
        int left = a;
        int right = b-1;
        T pivot = array[b];
        T temp;

I was getting an error here
public class QuickSort <T extends Comparable<T>> extends ArraySortTool<T>{

I am trying to do this without interfering with the interface class.
Here is the code for the ArraySortTool
public abstract class ArraySortTool<T extends Comparable<T>> implements ArraySort<T>
{
    /**
     * @param inArray an array to be sorted
     * @return the time, in milliseconds, taken to sort the array
     */
    private double timeTakenMillis(T[] array) {
        double startTime = System.nanoTime();
        sort(array);
        return ((System.nanoTime()-startTime)/1000000.0);
    }

    /**
     * Run a sequence of tests on sets of arrays of increasing size, reporting the average time taken for each
     * size of array. For each size of array, <tt>noPerSize</tt> tests will be run, and the average time taken.
     * Timings will be generated for array sizes 1,2,...,9,10,20,...,90,100,200,...,900,1000,2000,...until the
     * maximum time is exceeded.  Times are reported in milliseconds.
     * @param generator an array generator for generating the random arrays
     * @param noPerSize the number of timings per array size set
     * @param maxTimeSeconds the cut-off time in seconds - once a timing takes longer than this the timing sequence will be terminated
     */
    public void timeInMillis(RandomArray<T> generator,int noPerSize,int maxTimeSeconds)
    {
        int size = 1;  // initial size of array to test
        int step = 1;  // initial size increase
        int stepFactor = 10; // when size reaches 10*current size increase step size by 10
        double averageTimeTaken;
        do {
            double totalTimeTaken = 0;
            for (int count = 0; count < noPerSize; count++) {
                T[] array = generator.randomArray(size);
                totalTimeTaken += timeTakenMillis(array);
            }
            averageTimeTaken = totalTimeTaken/noPerSize;
            System.out.format("Average time to sort %d elements was %.3f milliseconds.\n",size,averageTimeTaken);
            size += step;
            if (size >= stepFactor*step) step *= stepFactor;
        } while (averageTimeTaken < maxTimeSeconds*1000);
        System.out.println("Tests ended.");
    }

    /**
     * Check whether a given array is sorted.
     * @param array the array to be checked
     * @return true iff the array is sorted - either ascending or descending
     * The first non-equal neighbouring elements will determine the expected
     * order of sorting.
     */
    public boolean isSorted(T[] array) {
        int detectedDirection = 0; // have not yet detected increasing or decreasing
        T previous = array[0];
        for (int index = 1; index < array.length; index++) {
            int currentDirection = previous.compareTo(array[index]); // compare previous and current entry
            if (currentDirection != 0) { // if current pair increasing or decreasing
                if (detectedDirection == 0) { // if previously no direction detected
                    detectedDirection = currentDirection; // remember current direction
                } else if (detectedDirection * currentDirection < 0) { // otherwise compare current and previous direction
                    return false; // if they differ array is not sorted
                }
            }
            previous = array[index];
        }
        // reached end of array without detecting pairs out of order
        return true;
    }
}

I am trying to pass the quicksort method into the sort method as it is in the interface class. Please let me know how to do this as I am new to passing by reference. An example using my code will be great. Kind regards.

A: try this:
public class QuickSort <T extends Comparable<T>> implements ArraySort<T>{...}

(edited to match revised code in the question)


text:
Q: Cómo refrescar la UI y luego seguir con las tareas "Pesadas" C# Cómo hacer para que aparezca la primer "leyenda1" luego se ejecute todoelcodigo() y por último se vea la "leyenda2".
Ya que una vez que se presiona el botón, no se ve el primer texto.
private void botEnviar_Click(object sender, RoutedEventArgs e)
{
    string leyenda1 = "Enviando archivo comprimido...";
    string leyenda2 = "El archivo fue enviado con éxito!";

    try
    {
        lbLeyenda.DataContext = leyenda1;
        //Acá quiero mostrar el texto y
        //que luego siga con las otras tareas...

         todoelcodigo(); //Se queda haciendo esto...

         lbLeyenda.DataContext = leyenda2;
         //Lo único que se ve es el texto de la leyenda2
    }
    catch (Exception ex)
    {
        ControlDatos.mensajeError(ex);
        deleteAllDirectoryes();

    }

    private void todoelcodigo()
    {
        copyFilesToTempDirectory();
        compressFile();
        uploadFile(@"C:\windows\Temp\tmpExport\ZIP\", "SIS" + mes + año +
         ".zip");
        deleteAllDirectoryes();
    }

}

A: Eso es porque estás trabajando en el mismo hilo de la UI, para que tu código trabaje en un hilo diferente a la UI y esta no se te 'congele' al ejecutar una tarea debes usar programación asíncrona, y eso además te permitirá asignar valores a los controles y que se reflejen cuando corresponda y esas instrucciones no se solapen.
Podrías probar algo así:
string leyenda1 = "Enviando archivo comprimido...";
string leyenda2 = "El archivo fue enviado con éxito!";

private void CallEnviar()
{
    var tsk = EnviarAsync();
}

async Task EnviarAsync()
{
    try
    {
        lbLeyenda.Content = leyenda1;
        await Task.Run(() => todoelcodigo());
        lbLeyenda.Content = leyenda2;
    }
    catch(Exception ex)
    {
        ControlDatos.mensajeError(ex);
        deleteAllDirectoryes();
    }
}

private void todoelcodigo()
{
    copyFilesToTempDirectory();
    compressFile();
    uploadFile(@"C:\windows\Temp\tmpExport\ZIP\", "SIS" + mes + año +
    ".zip");
    deleteAllDirectoryes();
}

Si te fijas el "await" hace que el proceso "espere" y luego hace lo que viene en la linea que continúa, eso permitirá que tu Label muestre los valores que le asignas antes y después de la ejecución de "todoelcodigo()" sin necesidad de que tú refresques la UI.
Espero te sirva, un saludo.


text:
Q: Regex number range prasing I am trying to parse out a specific number range, and can't seem to get it right.  I am looking to extract specific browser versions from user agent strings.  For example, I want to parse Chrome 1-42 and Firefox 1-40, but I can't figure out the syntax.
What I have so far is this, which kind of works, but it grabs the first number it sees and doesn't respect the 2 digit range:
Gecko..Chrome/([1-9].|[1-4][1-2].)
Sample:
Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/34.0.1847.137 Safari/537.36
Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/38.0.1847.137 Safari/537.36
Firefox 29: Mozilla/5.0 (Android; Mobile; rv:29.0) Gecko/29.0 Firefox/23.0
Mozilla/5.0 (Macintosh; Intel Mac OS X 10.9; rv:29.0) Gecko/20100101 Firefox/29.0
Any ideas?  TIA.

A: ((?:(?:Mozilla\/(?:[1-9]|[1-3][0-9]|40))|(?:Chrome\/(?:[1-9]|[1-3][0-9]|4[0-3])))\.[^ ]+)

Is this what you would like? /Edited/
Demo:
    https://regex101.com/r/gH1nU9/2

A: Because regex is text matching only and number are treated as text, to do something like 1 to 41 you would have to something like this:
\b[1-9]\b|\b[1-3][0-9]\b|4[0-2]\b

This is matching 1 to 9 or 10 to 39 or 40 to 42. I have added the boundries \b so that nothing except thes numbers are matched.


text:
Q: Transmitter and Receiver antennas in mobile phones I understand that in old cellular systems where FDD were employed, we used to have same antenna at the mobile phone (User equipment) for transmission and reception.Moreover, a duplexer was used to separate them.
In modern cellular systems (Say, 4G and above), do we have separate antennas for transmission and reception in the mobile phone. If no, do we still use duplexers for isolation?

A: One antenna is used for both receiver and transmitter. In many cases the antenna is designed so that it can be used in all the bands the phone supports. (There can be more antennas for MIMO / spatial diversity purposes, but I will not go into details of those)
The same antenna is used for Rx and Tx in LTE FDD (frequency division duplexing), LTE TDD, WCDMA, CDMA, GSM, you name it. LTE FDD is the most used technology for data. A frequency diplexer is used in LTE FDD, as both Rx and Tx occur at the same time but in different frequencies.
LTE TDD (time division duplexing) uses an RF switch to switch between Tx and Rx, as the transmitting and receiving does not happen simultaneously.
Below you'll find very simplified drawings of todays mobile phones RF front end for a single band. Pretty much all use a frequency diplexer, because LTE FDD is the most dominant technology. A switch is used for LTE TDD.


text:
Q: How to use spring boot java to properly use axios.post from React So I am using axios.post on React
here is my code
React GenService.jsx
import axios from "axios";
import { Route, withRouter } from "react-router-dom";

const COURSE_API_URL = "http://localhost:8080";

class GenService {
  retrieveAll() {
    return axios.get(`${COURSE_API_URL}`);
  }
  pAll() {
    return axios.post(`${COURSE_API_URL}` + "/user", {
      firstName: "Fred",
      lastName: "Flintstone"
    });
  }
}

export default new GenService();

But I can't figure out how to call firstName and lastName in backend java using spring boot
SpringBootLd2nlApplication.java
package com.ld2nl.springbootld2nl;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

@SpringBootApplication
@CrossOrigin(origins = { "http://localhost:3000", "http://localhost:4200" })
@RestController

public class SpringBootLd2nlApplication {

    public static void main(String[] args) {
        SpringApplication.run(SpringBootLd2nlApplication.class, args);
    }
    //works
    @RequestMapping(value = "/")
    public String say() {
        return "Sending Hello To React";
    }

//not work
    @RequestMapping(value = "/user")
    public String reply(@RequestParam String firstName) {
        return firstName;
    }

}

As you can see  can't get the area marked as "//not work" to properly call firstName and lastName
Currently giving error
Required String parameter 'firstName' is not present
....

A: Instead of trying to directly fetch the parameter which won't work as POST sends data as a payload/JSON object rather than split parameter-wise, below should work:
  @PostMapping(value = "/user")
   public String reply(@RequestBody Map<String, Object> payLoad) {
       return (String)payLoad.get("firstName");
   }

A: Instead of passing firstname like that, try creating a const for firstname.
const firstName = "Fred";
...
...
pAll(){
     return axios.post(http://localhost:8080/users/${firstname});
}

And in the Springboot, add these lines in the reply() function
@GetMapping("/users/{firstname}
public String reply(@PathVariable String firstName) {
    return firstName;
}

A: The best way (production way) is to provide separate DTO.
   public class SendMessageDto {
     @NotBlank @Length(min=4)...
     private String userName;
     public String getUserName() {return this.userName} ;
   }

In controller
   @PostMapping(value = "/user")
   public String reply(@Valid @RequestBody SendMessageDto) { //
       return payLoad.getUserName();
   }

*

*@RequestBody - is optional in this context.

*@Valid - needed for request validation


text:
Q: Using static strings to define input field names in JSPs - good idea or not? I've just be asked to work on a large portal project and have been looking through the established code. I keep finding this in the jsps:
<input class="portlet-form-button"
    name="<%=ModifyUserProfile.FORM_FIRST_TIME_LOGIN_SUBMIT%>" type="submit" ...

The authors are using static strings defined in classes to define the names of input fields and buttons in jsp forms.
I've never seen this done before and was wondering if this is common practice. I'm inclined to think not, but I'm asking because, apart from centralising names which I would have thought are not likely to change, I can't see the reason why.
Any thoughts on this?

A: As you've determined, the advantage of this approach is that the compiler ensures the identifier used in the page always matches the one in your Java code (e.g.  the portlet processAction method that reads the submitted field). Changing the value of the String constant automatically updates the view. It may also help identify usage of String constants.
The downside is that it makes for pretty ugly view code and I would avoid scriptlet-style code wherever possible.
Whether I'd change this would probably depend on the cleanliness of the code. If the String identifiers are mixed in with a mess of other constants and the views are thousand line script jungles, I'd probably leave them alone.
Since these are portlets, if I was feeling completely anal about code cleanliness, I'd namespace that input name with an EL function.

A: The practice is right.
Like you said, it helps in centralizing the messages.
The other more helpful advantage is for Internationalization. YOu have multiple properties file, each specific for a locale/language. Use the one specific to the user's locale and you have internationalized messages without changing your jsp.


text:
Q: How to keep readme from being web accessible I have a plain text readme file that is in the root directory of my website which is version controlled with Git. I like to have the readme there because GitHub will display it when viewing that repo.
However, when I go to mysite.com/readme.md, I get the readme file back. I do not want this file to be accessible to the public.
What is the best way to effectively disallow the public from accessing this readme file without moving the file away from the root of the project?

A: Many different ways depending on how github accesses this, you'd add some stuff to the htaccess file in your document root (or where your readme file is).
Using mod_authz:
<Files "readme.md">
    Order Deny,Allow
    Deny from all
</Files>

This will return a 403 forbidden for all requests to /readme.md. If you want to whitelist a specific IP, You can add this right above the Deny from all line:
Allow from 12.34.56.78

which will whitelist requests sent from the 12.34.56.78 IP.
Using mod_rewrite (which gives you a couple of options)
RewriteEngine On
RewriteRule ^readme\.md$ - [L,F]

This does the same thing. To whitelist an IP, add this before the RewriteRule line:
RewriteCond %{REMOTE_ADDR} !^12\.34\.56\.78$

You can also return a 404 instead of a 403 Forbidden by replacing the F in the rewrite flags to R=404. If you need to whitelist a referer, you can add a condition (right above the rewriterule line) like this:
RewriteCond %{HTTP_REFERER} !^https?://github\.com/ [NC]

which will allow people to access the readme.md file if the link was embedded on a page from github.com.


text:
Q: db.create_all() doesn't create tables defined in separate file I am trying to create the tables for my models, which are defined in a separate module from my app.  I call db.create_all(), but no tables are created and there are no errors.  I've defined the models and imported them before calling create_all.  Why doesn't this work?
from flask import Flask
from flask.ext.sqlalchemy import SQLAlchemy

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'postgresql+psycopg2://postgres:123@localhost/flask'
db = SQLAlchemy(app)

from models import User

db.create_all()
db.session.commit()

models.py:
from flask.ext.sqlalchemy import SQLAlchemy

db = SQLAlchemy()

class User(db.Model):
  __tablename__ = 'users'
  uid = db.Column(db.Integer, primary_key = True)

A: You created two separate db instances, one along with the app and one along with the models.  Each instance has it's own metadata that stores the tables defined on it.  The one you're using to issue the create table statement was not the one that the models were defined on.  You should use only one instance of the extension, importing it when needed.
myapp/__init__.py:
from flask import Flask
from flask_sqlalchemy import SQLAlchemy

app = Flask(__name__)
db = SQLAlchemy(app)

# import the models *after* the db object is defined
from myapp import models

myapp/models.py:
from myapp import db

class User(db.Model):
    ...

create_tables.py:
from myapp import app, db

with app.app_context():
    db.create_all()

Other things to note:

*

*You should structure your app as a package, so that everything is importable under one location.

*flask.ext is deprecated, import the extension directly from its package name.

*Flask-SQLAlchemy automatically generates __tablename__ from the class name, you don't need to define it yourself.

*You do not have to call commit after create_all.


text:
Q: UIScrollView Setting contentoffset in viewwillappear not working I was wondering if it is possible to set contentoffset for uiscrollview in viewwillappear method.
-(void) viewWillAppear:(BOOL)animated{

    [self.scrollView setContentOffset:CGPointMake(320, 0) animated:YES];
    NSLog(@"CALLED");
}

I can see viewwillappear is running but unfortunately it is not setting offset.
Thank you

A: I have an alternative option that should work better:
Instead of overriding viewDidLayoutSubviews, you can manually set the layout:
override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)
    view.layoutIfNeeded()
    // Do something here
}

This way you get a fresh layout that should match your expectation

A: you should call [super viewWillAppear:animated]; before attempting to set the offset.
However, it is possible you are trying to set the offset too early in the view lifecycle.
it might be good to override -(void)viewDidLayoutSubviews;, and set the offset there.
as your view's frames should all be set appropriately by that time. (remember to call super there too)

A: I have tested with your scrollView's contentSize & contentOffset in viewWillAppear. It is working fine to me. So, Please check weather your scrollView object is properly bound to your scrollView or not.


text:
Q: jQuery: How to traverse / Iterate over a list of object I'm using asp.net MVC4 for web app development.
I would like to traverse a list of objects from a ViewModel.
Below is the class of the object:
public class User
{
        public int Id {get; set;}
        public string Name {get; set;}
        public string Address {get; set;}
        public string Department {get; set;}
}

Below is my ViewModel class:
public class UserViewModel
{
      public List<User> AllUsers {get; set;}
      public bool IsDeleted {get; set;}
}

As seen in the UserViewModel class, I have a list of objects of type User. Now i would like to iterate through each of the user object in AllUsers list using Jquery and fetch data from them.
In order to do so, I tried doing something like the following:
$(@Model.AllUsers).each( function(){ .... });

I have tried different combination using the above approach, but couldn't succeed. Can anyone suggest a solution for the same.
Thanks in advance.

A: <script type="text/javascript">

    var UsersList = @Html.Raw(Json.Encode(Model.AllUsers))

    for (var i = 0; i < UsersList.length; i++) {
        alert(UsersList[i].Id);
        alert(UsersList[i].Name);

    }
 </script>

A: Assign your collection to a javascript variable using
var users = @Html.Raw(Json.Encode(Model.AllUsers))

which you can then iterate over
$.each(users, function(index, item) {
  // access the properties of each user
  var id = item.Id;
  var name = item.Name;
  ....
});

A: JavaScript generally is unhappy with razor components although if the above is part of an CSHTML file it will work.
The other approaches are:

*

*Display the collection using razor @foreach ...

*Pass the collection as a parameter from you webpage into a JavaScript function on some event

How are you calling this function and what does it do?

A: In My Case, I fixed by this way :
 @for(int i=0;i<Model.AllUsers.Count;i++)
 {
   @: var name = '@Html.Raw(@Model.AllUsers[i].Name)';
   @:alert(name);
 }


text:
Q: How to use cscope with paths that contain spaces There are some folder that contains space, and as a result, those folders can not be indexed using cscope.
Can i ask you for help to solve this,or any suggestion.
thanks
Julius

Thanks for your reply.
My steps to use cscope like the following

*

*find . -name '*.scala'>cscope.files

*cscope -b
at this step. i see the message indicates that can not find file:
cscope: cannot find file /work/project/copy
cscope: cannot find file of
cscope: cannot find file  fp/src/main/jav....
Actually copy of fp is a folder.so i think cscope can  not recognize the folder contains space.

I encountered this problem when i tried to use vim with cscope.maybe i need move this question to other tag.

A: You can do it simply using GNU find at least, you can use the -printf or -fprintf options for that:
find . -type f -fprintf cscope.files '"%p"\n'

A: pydave's answer is very slow. This way took 0.10s where pydave's answer took 14s:
find . -name "*.scala" | awk '{print "\""$0"\""}' > cscope.files

A: You can use find's -exec to force quotes around your output:
find . -name "*.scala" -exec echo \"{}\" \; > cscope.files

You might need to mess around with quoting/escaping if you're doing this from a script.

A: Double quoting the files names works in cygwin, where as escaping with backslash does not.
$ find $PWD -name "*.scala" | sed -e 's/^/"/g' -e 's/$/"/g' > cscope.files


text:
Q: Show $Ax = e_{m+1}$ is consistent. $A = \binom{C}{a^{T}}$. $C$ is $mxn$ matrix. $a$ is $n$-vector that is lin. indep. of rows of $A$. $C$ is an $mxn$ matrix of any shape, shape, rank, etc.  $a$ is a $n$-vector that is linearly independent of the rows of $C$. Let $A = \binom{C}{a^{T}}$.  Let $e_{m+1}$ denote the $m+1$ Identity vector.  Show that $Ax=e_{m+1}$ is consistent.
I don't know where to start.

A: Note that $Ax=e_{m+1}$ means that you should find an $x$ with $Cx=0$ and $a^Tx=1$. Because you can scale $x$ appropriately if necessary, it suffices to find $x\in \operatorname{ker}(C)$ with $x\notin \operatorname{ker}{a^T}$. This is possible because $\operatorname{ker}(C)\subseteq \operatorname{ker}{a^T}$ implies that $a^T$ is linearly dependent to the rows of $C$, see e.g. this math.stackexchange question with $L_i$ taken to be the functionals given by multiplying with the rows of $C$ and $L$ is taken to be the functional given by multiplying with $a^T$.

A: This is going to be hard to prove because it is false.
Consider
$$
C = \left( \begin{array}{ccc} 2 & 2 & 2 \\ 1 & 1 & 1
\end{array}\right) \\
a^T = ( -1, 0, 1 )
$$
which is not linearly dependent on the rows of $C$.
Then
$$
A = \left( \begin{array}{ccc} 2 & 2 & 2 \\ 1 & 1 & 1 \\ -1 & 0 & 1
\end{array}\right)
$$ and $ Ax = e_3$ is
$$
2x_1 + 2x_2 + 2x_3 = 1 \\x_1 + x_2 + x_3 = 1 \\ -x_1 + x_3 = 1
$$
and those first two equations are inconsistent with each other.


text:
Q: laravel 7 Get Sum From eloquent relation column  $user = User::with(['affiliateCode','rewardPoints','orders'=>function($query){
        $query->where('order_status_id','!=',1);
    }])
    ->withCount(['orders'=>function($q){
        $q->where('order_status_id','!=',1);
    }])
    ->where('id',$userId)->first();

The above code is working fine.. I also want to return sum of all amount from orders table where order_status_id !=1 with this response..
i have tried withSum() but its not working since its laravel 7,
can anyone help to to return the sum also.? Thank You

A: You can use withCount method with callback like this.
$user = User::with(['affiliateCode','rewardPoints','orders'=>function($query){
        $query->where('order_status_id','!=',1);
    }])
    ->withCount(['orders'=>function($q){
        $q->where('order_status_id','!=',1);
    }])
    ->withCount(['orders as orders_amount'=>function($q){
        $q->where('order_status_id','!=',1)->select(DB::raw('sum(amount)'));
    }])
    ->where('id',$userId)->first();


text:
Q: Extract text from the left of "-" but ignore cells that do not contain "-" I am trying to extract some values from a cell.
I have figured out how to extract the value of a cell to the left of "-" but I come across an error when the cell does not have a "-" at all.
How do I ignore these cells / error?.
Any help would be much appreciated or ways to improve what I have made.
Also if it helps there are roughly 20000 rows on average.
    Dim r As Long
    Dim Location As Long
    Dim m As Long
    Dim ws As Worksheet

    Set ws = Worksheets("NHBRSummary")

        Set ws = Worksheets("Sheet1")
        m = ws.Cells(ws.Rows.Count, "F").End(xlUp).Row
        For r = 2 To m
            Location = InStr(1, Cells(r, 1), "-")
            Cells(r, 2).Value = Left(Cells(r, 1), Location - 1)
        Next

End Sub

A:         Set ws = Worksheets("Sheet1")
        with ws
             m = .Cells(.Rows.Count, "F").End(xlUp).Row
             For r = 2 To m
                 if InStr(1, .Cells(r, 1), "-") > 0 then
                     .Cells(r, 2).Value = split(.Cells(r, 1).value)(0)
                 end if
             Next
        end with

You set ws to a sheet, then immediately change it, you should remove the first set if you aren't using it.
You can still use left() and location if you would like, this is just another way of doing it. The important part is the if statement using instr()


text:
Q: remote-server authorized_keys already has my macOS's id_rsa.pub, but still can not login without password I want to implement the password-free login from my Mac to remote-server.
In my mac, there have several pairs of keys.
dele-MBP:.ssh ldl$ ls
authorized_keys         github_rsa_172653569
config              github_rsa_172653569.pub
github_172653569        id_rsa
github_rsa          id_rsa.pub
github_rsa.pub          known_hosts

I chosen the id_rsa.pub to send to remote-server:
$ ssh-copy-id -i .ssh/id_rsa.pub root@192.168.1.253

the remote-server already have the pub-key:
[root@remote-server ~]# more .ssh/authorized_keys
ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQCvZzEsVmMvx06dj8jw7ivzISndINGcscm98EHpTmpGlA4CHSrUL1DJ9VOLSUap1Ginl0V8IF8Q873WbsbAuDAEHKEqM8ynmKpS3iz
yUBmT8lmQ0Gqm+XzuK43uyfKkV9PL+xuxYct4BKykCFu1vhluceC+Q8pgrM6LzrVZsC88CamJsFLbXnhcbOLwgNI2mAZZXtpSsaptszyLp6+OCT5+Wyp5rpQdtwNBOcmqdmheiN0AQz
8YrEVX3Te2BxYdnNKV9nfMtl4AhkrsZ0pSaxL0AOZI5mkyK6OhkgKNI0vh+sRCfEaZBd86H9u/Hn/ycMBARHpK/VjHEYSTUHcpGoJn dele123@gmail.com

but now when I login, there still needs manually input password.

remote-server version is CentOS 7.2, and my macOS is 10.15.2 (19C57).

EDIT-01
When display the detail logs, there get this information
we did not send a packet, disable method.
$ ssh -Tvv root@192.168.1.253
OpenSSH_7.9p1, LibreSSL 2.7.3
debug1: Reading configuration data /Users/luowensheng/.ssh/config
debug1: /Users/luowensheng/.ssh/config line 1: Applying options for *
debug1: Reading configuration data /etc/ssh/ssh_config
debug1: /etc/ssh/ssh_config line 51: Applying options for *
debug2: resolve_canonicalize: hostname 192.168.1.253 is address
debug2: ssh_connect_direct
debug1: Connecting to 192.168.1.253 [192.168.1.253] port 22.
debug1: Connection established.
debug1: identity file /Users/luowensheng/.ssh/github_rsa_726535609 type 0
debug1: identity file /Users/luowensheng/.ssh/github_rsa_726535609-cert type -1
debug1: Local version string SSH-2.0-OpenSSH_7.9
debug1: Remote protocol version 2.0, remote software version OpenSSH_6.6.1
debug1: match: OpenSSH_6.6.1 pat OpenSSH_6.6.1* compat 0x04000002
debug2: fd 3 setting O_NONBLOCK
debug1: Authenticating to 192.168.1.253:22 as 'root'
debug1: SSH2_MSG_KEXINIT sent
debug1: SSH2_MSG_KEXINIT received
debug2: local client KEXINIT proposal
debug2: KEX algorithms: curve25519-sha256,curve25519-sha256@libssh.org,ecdh-sha2-nistp256,ecdh-sha2-nistp384,ecdh-sha2-nistp521,diffie-hellman-group-exchange-sha256,diffie-hellman-group16-sha512,diffie-hellman-group18-sha512,diffie-hellman-group14-sha256,diffie-hellman-group14-sha1,ext-info-c
debug2: host key algorithms: ecdsa-sha2-nistp256-cert-v01@openssh.com,ecdsa-sha2-nistp384-cert-v01@openssh.com,ecdsa-sha2-nistp521-cert-v01@openssh.com,ecdsa-sha2-nistp256,ecdsa-sha2-nistp384,ecdsa-sha2-nistp521,ssh-ed25519-cert-v01@openssh.com,rsa-sha2-512-cert-v01@openssh.com,rsa-sha2-256-cert-v01@openssh.com,ssh-rsa-cert-v01@openssh.com,ssh-ed25519,rsa-sha2-512,rsa-sha2-256,ssh-rsa
debug2: ciphers ctos: chacha20-poly1305@openssh.com,aes128-ctr,aes192-ctr,aes256-ctr,aes128-gcm@openssh.com,aes256-gcm@openssh.com
debug2: ciphers stoc: chacha20-poly1305@openssh.com,aes128-ctr,aes192-ctr,aes256-ctr,aes128-gcm@openssh.com,aes256-gcm@openssh.com
debug2: MACs ctos: umac-64-etm@openssh.com,umac-128-etm@openssh.com,hmac-sha2-256-etm@openssh.com,hmac-sha2-512-etm@openssh.com,hmac-sha1-etm@openssh.com,umac-64@openssh.com,umac-128@openssh.com,hmac-sha2-256,hmac-sha2-512,hmac-sha1
debug2: MACs stoc: umac-64-etm@openssh.com,umac-128-etm@openssh.com,hmac-sha2-256-etm@openssh.com,hmac-sha2-512-etm@openssh.com,hmac-sha1-etm@openssh.com,umac-64@openssh.com,umac-128@openssh.com,hmac-sha2-256,hmac-sha2-512,hmac-sha1
debug2: compression ctos: none,zlib@openssh.com,zlib
debug2: compression stoc: none,zlib@openssh.com,zlib
debug2: languages ctos:
debug2: languages stoc:
debug2: first_kex_follows 0
debug2: reserved 0
debug2: peer server KEXINIT proposal
debug2: KEX algorithms: curve25519-sha256@libssh.org,ecdh-sha2-nistp256,ecdh-sha2-nistp384,ecdh-sha2-nistp521,diffie-hellman-group-exchange-sha256,diffie-hellman-group-exchange-sha1,diffie-hellman-group14-sha1,diffie-hellman-group1-sha1
debug2: host key algorithms: ssh-rsa,ecdsa-sha2-nistp256,ssh-ed25519
debug2: ciphers ctos: aes128-ctr,aes192-ctr,aes256-ctr,arcfour256,arcfour128,aes128-gcm@openssh.com,aes256-gcm@openssh.com,chacha20-poly1305@openssh.com,aes128-cbc,3des-cbc,blowfish-cbc,cast128-cbc,aes192-cbc,aes256-cbc,arcfour,rijndael-cbc@lysator.liu.se
debug2: ciphers stoc: aes128-ctr,aes192-ctr,aes256-ctr,arcfour256,arcfour128,aes128-gcm@openssh.com,aes256-gcm@openssh.com,chacha20-poly1305@openssh.com,aes128-cbc,3des-cbc,blowfish-cbc,cast128-cbc,aes192-cbc,aes256-cbc,arcfour,rijndael-cbc@lysator.liu.se
debug2: MACs ctos: hmac-md5-etm@openssh.com,hmac-sha1-etm@openssh.com,umac-64-etm@openssh.com,umac-128-etm@openssh.com,hmac-sha2-256-etm@openssh.com,hmac-sha2-512-etm@openssh.com,hmac-ripemd160-etm@openssh.com,hmac-sha1-96-etm@openssh.com,hmac-md5-96-etm@openssh.com,hmac-md5,hmac-sha1,umac-64@openssh.com,umac-128@openssh.com,hmac-sha2-256,hmac-sha2-512,hmac-ripemd160,hmac-ripemd160@openssh.com,hmac-sha1-96,hmac-md5-96
debug2: MACs stoc: hmac-md5-etm@openssh.com,hmac-sha1-etm@openssh.com,umac-64-etm@openssh.com,umac-128-etm@openssh.com,hmac-sha2-256-etm@openssh.com,hmac-sha2-512-etm@openssh.com,hmac-ripemd160-etm@openssh.com,hmac-sha1-96-etm@openssh.com,hmac-md5-96-etm@openssh.com,hmac-md5,hmac-sha1,umac-64@openssh.com,umac-128@openssh.com,hmac-sha2-256,hmac-sha2-512,hmac-ripemd160,hmac-ripemd160@openssh.com,hmac-sha1-96,hmac-md5-96
debug2: compression ctos: none,zlib@openssh.com
debug2: compression stoc: none,zlib@openssh.com
debug2: languages ctos:
debug2: languages stoc:
debug2: first_kex_follows 0
debug2: reserved 0
debug1: kex: algorithm: curve25519-sha256@libssh.org
debug1: kex: host key algorithm: ecdsa-sha2-nistp256
debug1: kex: server->client cipher: chacha20-poly1305@openssh.com MAC: <implicit> compression: none
debug1: kex: client->server cipher: chacha20-poly1305@openssh.com MAC: <implicit> compression: none
debug1: expecting SSH2_MSG_KEX_ECDH_REPLY
debug1: Server host key: ecdsa-sha2-nistp256 SHA256:DqAKjbw7po5n2Jr8Q8M2RntwO5nTSTyxyhpPnfPdJy4
debug1: Host '192.168.1.253' is known and matches the ECDSA host key.
debug1: Found key in /Users/luowensheng/.ssh/known_hosts:385
debug2: set_newkeys: mode 1
debug1: rekey after 134217728 blocks
debug1: SSH2_MSG_NEWKEYS sent
debug1: expecting SSH2_MSG_NEWKEYS
debug1: SSH2_MSG_NEWKEYS received
debug2: set_newkeys: mode 0
debug1: rekey after 134217728 blocks
debug1: Will attempt key: /Users/luowensheng/.ssh/github_rsa_726535609 RSA SHA256:JSG4qxcRvp52EQl5hebdR23Nf7LwcDxwUAXXpxCpNk4 explicit
debug2: pubkey_prepare: done
debug2: service_accept: ssh-userauth
debug1: SSH2_MSG_SERVICE_ACCEPT received
debug1: Authentications that can continue: publickey,gssapi-keyex,gssapi-with-mic,password
debug1: Next authentication method: publickey
debug1: Offering public key: /Users/luowensheng/.ssh/github_rsa_726535609 RSA SHA256:JSG4qxcRvp52EQl5hebdR23Nf7LwcDxwUAXXpxCpNk4 explicit
debug2: we sent a publickey packet, wait for reply
debug1: Authentications that can continue: publickey,gssapi-keyex,gssapi-with-mic,password
debug2: we did not send a packet, disable method
debug1: Next authentication method: password

A: Start with ssh -Tvv root@192.168.1.253 to check it does try and offer your id_rsa key.
Also make sure it does ask for root  password, and not for your private key passphrase (if said key was created with a passphrase)
I would also create, for testing, a new key with the old PEM format instead of the current OpenSSH one:
ssh-keygen -t rsa -m PEM -f ~/.ssh/test

Copy the test.pub, and try ssh -i ~/.ssh/test root@192.168.1.253


text:
Q: Is it fine to store i18n data in the database? I'm building a multilingual web application and I'm struggling to decide, how to store i18n data.
On the one hand, I could go with a traditional way of saving phrases into a JSON file and loading it from there. But for my application I'm using create-react-app and firebase, which makes this pretty inconvenient (It's fine to load phrases, but I would also like my i18n library to save missing translations into files, which is not so easy, because I have to setup a small express server which would handle file modifications).
On the other hand, I could just store everything in the database. That would make this process much simpler, but is it fine to do it? Are there any pitfalls or maybe security issues? (I know no one probably cares about stealing translated text, but if it's changed somehow, that wouldn't be nice for the users)

A: I prefer to use JSON format. In the cases of you can't upload a ".json" file you can use a ".js" file without inconvenient. For example:
en.js
module.exports = {
    "sayHi": "hello",
};

es.js
module.exports = {
    "sayHi": "hola",
};

If you don't want to miss any translation text of any language you can create a little script who alerts you if there is a missing text. In another hand, you can create another script to fill the incomplete languages and generate new .js files.


text:
Q: How to get information from two database tables at once? (MySQL) I want to show top rated articles on one of my website pages, but there is an issue.
I have all article text, author, date, time etc. in one table called stories,
and I have vote results in another table called votes.
The problem is that, when I get article info from database I need to order it by votes that correspond with it (in votes table I have vote value and id of article that it corresponds to).
So how can I display articles from stories table, but order it by vote value from votes table that corresponds to the article?
Pseudo code of this could be:
SELECT * FROM stories ORDER BY //Votes from votes table where article_id corresponds to this article

A: We don't see your table structure, but assuming your relationship is stories.article_id = votes.article_id this is a very simple JOIN with an ORDER BY.  You should review basic SQL JOIN syntax, as this is sort of a SQL 101 question. If your article identifier column in votes is different than votes.article_id, substitute it below.
SELECT
  stories.*,
  votes.votes
FROM stories JOIN votes ON stories.article_id = votes.article_id
ORDER BY votes.votes DESC

A: Assuming you have a field such as vote_story_id corresponding to story_id use this :
SELECT stories.*, vote.vote_number FROM stories, votes WHERE vote_story_id = story_id ORDER BY vote.vote_number DESC

A: Will this help you?
SELECT stories.* FROM stories JOIN votes on votes.article_id = stories.id WHERE ...

A: You are probably storing one row for each vote, so you can track which user made the vote. In that case, you can do:
select s.*, vc.Count
from Stories s
left outer join (
    select StoryID, count(*) as Count
    from Votes
    group by StoryID
) vc on s.StoryID = vc.StoryID
order by vc.Count desc


text:
Q: Open the attachment in the subheading in agenda view I am wondering if I can open the attachment which is attached to the father heading in agenda view. I think it will be very convenient to open as the way above. I really  do not want to attach the same file to all of the subheadings.
I have turned on the inheritance of the properties, but it seems like that the subheadings does not inherit the attachment properties.
Is there anyway to solve this problems?

A: About my question, I finally found the solution which offered by org-attach.
Pressing C-c C-a in your father heading, you will see a list of org-attach options. At the bottom, the i command gives the function that is described as:
Make children of the current entry inherit its attachment directory.
After pressing i, everything will work.
Cheers!

A: Property inheritance is not on by default, you need to enable if for specific properties.
If you set org-use-property-inheritance is to t, then "every property is inherited" as stated by the doc string.  If not, that's a bug you should report.


text:
Q: MySQL - selecting near a spatial point I've based my query below to select points near a spatial point called point on the other SO solution, but I've not been able to get it to return any results, for the past few hours, and I'm a bit edgy now...
My table lastcrawl has a simple schema:

 id (primary int, autoinc)
 point (spatial POINT)

(Added the spatial key via ALTER TABLE lastcrawl ADD SPATIAL INDEX(point);)

$query = sprintf("SELECT * FROM lastcrawl WHERE
     MBRContains(LineFromText(CONCAT(
        '('
        , %F + 0.0005 * ( 111.1 / cos(%F))
        , ' '
        , %F + 0.0005 / 111.1
        , ','
        , %F - 0.0005 / ( 111.1 / cos(%F))
        , ' '
        , %F - 0.0005 / 111.1
        , ')' )
        ,point)",
        $lng,$lng,$lat,$lng,$lat,$lat);
$result = mysql_query($query) or die (mysql_error());

I've successfully inserted a few rows via:
$query = sprintf("INSERT INTO lastcrawl (point) VALUES( GeomFromText( 'POINT(%F %F)' ))",$lat,$lng);
But, I'm just not able to query the nearest points to get a non-null result set. How do you get the query to select the points nearest to a given spatial point?

After inserting $lat=40, $lng=-100, trying to query this returns nothing as well (so, not even exact coordinates match):
SELECT * FROM lastcrawl WHERE MBRContains(LineFromText(CONCAT( '(' , -100.000000 + 0.0005 * ( 111.1 / cos(-100.000000)) , ' ' , 40.000000 + 0.0005 / 111.1 , ',' , -100.000000 - 0.0005 / ( 111.1 / cos(40.000000)) , ' ' , 40.000000 - 0.0005 / 111.1 , ')' )) ,point)

A: I've corrected the formula a little.
This one works for me:
CREATE TABLE lastcrawl (id INT NOT NULL PRIMARY KEY, pnt POINT NOT NULL) ENGINE=MyISAM;

INSERT
INTO    lastcrawl
VALUES  (1, POINT(40, -100));

SET @lat = 40;
SET @lon = -100;

SELECT  *
FROM    lastcrawl
WHERE   MBRContains
                (
                LineString
                        (
                        Point
                                 (
                                 @lat + 10 / 111.1,
                                 @lon + 10 / ( 111.1 / COS(RADIANS(@lat)))
                                 ),
                        Point    (
                                 @lat - 10 / 111.1,
                                 @lon - 10 / ( 111.1 / COS(RADIANS(@lat)))
                                 )
                        ),
                pnt
                );


text:
Q: How to make connections between listview and the activity that calls it I am currently trying to make a shopping list activity. My activity consisted of a listview and a textview (showing the total price of all items).
For the item names, quantity, and subtotal prices will be inside the listview, and the user can change the number of quantity which I want to change the subtotal and the total price as well.
I have succeeded in changing the subtotal price in the listview, but the problem is how to change the total price that is "outside" of the listview.
I do the logic for changing the subtotal price inside the listview adapter class, is there any way that I can detect the change of a listview item from outside of the adapter class?

A: A solution could be to pass the instance of Total TextView through the constructor of the adapter.
Adapter myAdapter = new (context, txtTotal, ...);

Then, in the getView method of the adapter, when you write the quantity, currently you are changing the subtotal textview. with the total textview instance firstly get the value in a double, add or subtract the change. finally put result in the total textview.
Another solution could be to use LocalBroadcastManager when you change the subtotal TextView you could send an action(From the adapter class).
example:
Intent intent = new Intent("change-total-event");
 intent.putExtra("xxxx", "20.50");//add data if you need
 LocalBroadcastManager.getInstance(this).sendBroadcast(intent);

Then, in your Activity you need to register the broadcastreceiver, please follow the tutorial if you want to do this option. Finally, change the value of the textview in your broadcastreceiver.
// handler for received Intents for the "change-total-event" event
private BroadcastReceiver mMessageReceiver = new BroadcastReceiver() {
  @Override
  public void onReceive(Context context, Intent intent) {
    // Extract data included in the Intent
    String value = intent.getStringExtra("xxxx");
    //change the total textview
  }
};


text:
Q: Сконевертировать весь массив $_POST День добрый.
Начал изучать php, написал небольшой скрипт для отправки почтовой формы! Для отправки использую Ajax, форма работает, но при получении на почту сообщения кириллицей приходя кракозябрами! Нашел решение через, iconv! Но если добавлять какие-то поля, то не очень удобно каждый раз прописывать строук iconv для каждого поля! Можно ли как то сконевертировать весь массив $_POST а не конвертировать каждый его элемент?!
Спасибо!
<?php
header('Content-Type: text/html; charset=windows-1251');

$t_post = date('d.m.Y');
$name =  trim(substr(htmlspecialchars($_POST['user_name']),0,200));
$surename = trim(substr(htmlspecialchars($_POST['user_surename']),0,300));
$subject = trim(substr(htmlspecialchars($_POST['user_subject']),0,300));
$message = trim(substr(htmlspecialchars($_POST['user_message']),0,3000));

if($name == ''){
    die("имя не указано");
};

if($surename == ''){
   die("Тема не может быть пустой");
};

if ($subject == ''){
    die("Тема сообщения не может быть пустой");
};

if ($message == ''){
    die("Сообщение не может быть пустым");
};

$to = "******@mail.ru";
$from = "vasya@pupkin.com";

$name_p = iconv('UTF-8','WINDOWS-1251', $name);
$surename_p = iconv('UTF-8','WINDOWS-1251', $surename);
$subject_p = iconv('UTF-8','WINDOWS-1251', $subject);
$message_p = iconv('UTF-8','WINDOWS-1251', $message);
$messag_combine ="Имя отпрваителя: $name_p \r\nФамилия:$surename_p
    \r\nТема: $subject_p \r\nTекст сообщения: $message_p \r\nВремя отправки формы: $t_post";

if(
mail($to,$subject_p,$messag_combine)
  )
{
  die("Сообщение отправленно");
};

die ("Какое-то дерьмо с отправкой");

A: Вы можете в вашей форме все поля называть как-то так:
Form[user_name], Form[user_surname] и тд. Выглядеть это должно примерно так:
<form>
<input type="text" value="" name="Form[user_name]" />
<input type="text" value="" name="Form[user_surname]" />
</form>

После этого в вашем php коде Вы можете получить массив Form и пройтись циклом (foreach например) по полям этого массива. Пример:
foreach($_POST['Form'] as $name => $value)
{
   $_POST['Form'][$name] = iconv('UTF-8','WINDOWS-1251', $value);
}

После такой манипуляции у вас все поля должны быть в нужной вам кодировке (не забудьте что поля лежат в массиве $_POST['Form']).
НУ А САМЫЙ ПРАВИЛЬНЫЙ ВАРИАНТ ЭТО ВСЕ ЖЕ ПОМЕНЯТЬ КОДИРОВКУ В ФАЙЛЕ С ФОРМОЙ :)


text:
Q: Text won`t render using path in react rendered SVG. How can I use this textPath correctly? Can anyone help me identify why my text is not rendering in the defined path #textPath03 ? The path is rendered as supposed, but when I put it inside a <defs> and try to use it, it doesn`t work.
    <svg version="1.1" height="700" width="700" viewBox="-5 -5 110 110" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" data-reactid="13">
  <defs data-reactid="14">
    <path id="#textPath03" d="M95,50 A45,45 0 0 0 50,5" data-reactid="15"></path>
  </defs>
  <line x1="50" y1="50" x2="100" y2="50" stroke="black" data-reactid="16"></line>
  <line x1="50" y1="50" x2="50" y2="0" stroke="black" data-reactid="17"></line>
  <path d="M90,50 A40,40 0 0 0 50,10" fill="none" stroke="green" data-reactid="18"></path>
  <use xlink:href="#textPath03" fill="none" stroke="red" data-reactid="19"></use>
  <text x="2" y="40%" font-size="20" data-reactid="20">
    <textPath xlink:href="#textPath03" data-reactid="21">Teste</textPath>
  </text>
</svg>

This is a REACT rendered SVG.
Thanks!!

A: The path id contains an extraneous # character. Only the reference to the path should have that. Removing it fixes your example...

<svg version="1.1" height="700" width="700" viewBox="-5 -5 110 110" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" data-reactid="13">
  <defs data-reactid="14">
    <path id="textPath03" d="M95,50 A45,45 0 0 0 50,5" data-reactid="15"></path>
  </defs>
  <line x1="50" y1="50" x2="100" y2="50" stroke="black" data-reactid="16"></line>
  <line x1="50" y1="50" x2="50" y2="0" stroke="black" data-reactid="17"></line>
  <path d="M90,50 A40,40 0 0 0 50,10" fill="none" stroke="green" data-reactid="18"></path>
  <use xlink:href="#textPath03" fill="none" stroke="red" data-reactid="19"></use>
  <text x="2" y="40%" font-size="20" data-reactid="20">
    <textPath xlink:href="#textPath03" data-reactid="21">Teste</textPath>
  </text>
</svg>


text:
Q: how to speed retrieving data from big table data when select from it? Problem
I have table have 20 columns when make select data from new SQL query computer hangs ?
what suggestion to make quickly read data from this table and make performance good ?
What I Try
==========
select * from table where 1=1
take 45 minutes

after minimize column number as
select column 1,column 2,column 3 from table

also hangs but take less time as 42 minutes .
when make select data from tables not other programs open only SQL server opened new query.
table have 1 million records .
Computer Capability
==============
i work on SQL server 2012.
select data from this table hangs computer although my computer capability not bad
ram 8 GIGA and processor core I 5 .
I try same Backup of data on another computer it take too much time as above ?
==============
if possible what suggestions to select data quickly from table and best performance ?

A: If data is inserting/updating in this tables at the time of select query you may face deadlock issues.
Try with(nolock) and check if table has proper indexes.
select * from table with(nolock) where 1=1

Rebuild the indexes.


text:
Q: Not able to use mongo-hadoop connector in Hive query in HDP I am new to hadoop. I have installed hortonworks sandbox 2.1.
I am trying to execute Hive script using Hive UI. I want to access mongo collection inside Hive. I used following query for that:
CREATE TABLE individuals
(
  id INT,
  name STRING,
  age INT,
  city STRING,
  hobby STRING
)
STORED BY 'com.mongodb.hadoop.hive.MongoStorageHandler'
WITH SERDEPROPERTIES('mongo.columns.mapping'='{"id":"_id"}')
TBLPROPERTIES('mongo.uri'='mongodb://<hostIP>:27017/test.test');

I have added mongo-java-driver-2.12.2.jar, mongo-hadoop-core-1.3.0.jar and mongo-hadoop-hive-1.3.0.jar as File Resources.
But when I execute the query, it fails with following error:
15/03/11 04:38:24 INFO exec.DDLTask: Use StorageHandler-supplied com.mongodb.hadoop.hive.BSONSerDe for table individuals
15/03/11 04:38:24 ERROR exec.DDLTask: java.lang.NoClassDefFoundError: com/mongodb/util/JSON
    at com.mongodb.hadoop.hive.BSONSerDe.initialize(BSONSerDe.java:107)
    at org.apache.hadoop.hive.metastore.MetaStoreUtils.getDeserializer(MetaStoreUtils.java:339)
    at org.apache.hadoop.hive.ql.metadata.Table.getDeserializerFromMetaStore(Table.java:283)
    at org.apache.hadoop.hive.ql.metadata.Table.getDeserializer(Table.java:276)
    at org.apache.hadoop.hive.ql.metadata.Table.getCols(Table.java:626)
    at org.apache.hadoop.hive.ql.metadata.Hive.createTable(Hive.java:593)
    at org.apache.hadoop.hive.ql.exec.DDLTask.createTable(DDLTask.java:4194)
    at org.apache.hadoop.hive.ql.exec.DDLTask.execute(DDLTask.java:281)
    at org.apache.hadoop.hive.ql.exec.Task.executeTask(Task.java:153)
    at org.apache.hadoop.hive.ql.exec.TaskRunner.runSequential(TaskRunner.java:85)
    at org.apache.hadoop.hive.ql.Driver.launchTask(Driver.java:1504)
    at org.apache.hadoop.hive.ql.Driver.execute(Driver.java:1271)
    at com.cloudera.beeswax.BeeswaxServiceImpl$RunningQueryState.execute(BeeswaxServiceImpl.java:349)
    at com.cloudera.beeswax.BeeswaxServiceImpl$RunningQueryState$1$1.run(BeeswaxServiceImpl.java:614)
    at com.cloudera.beeswax.BeeswaxServiceImpl$RunningQueryState$1$1.run(BeeswaxServiceImpl.java:603)
    at java.security.AccessController.doPrivileged(Native Method)
    at javax.security.auth.Subject.doAs(Subject.java:356)
    at org.apache.hadoop.security.UserGroupInformation.doAs(UserGroupInformation.java:1537)
    at com.cloudera.beeswax.BeeswaxServiceImpl$RunningQueryState$1.run(BeeswaxServiceImpl.java:603)
    at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:471)
    at java.util.concurrent.FutureTask.run(FutureTask.java:262)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
    at java.lang.Thread.run(Thread.java:744)

Can somebody please help to let me know what I am missing over here?
Thanks in advance.

A: You need to map all the items in your mongodb collection not only the "_id" :
CREATE TABLE individuals
(
  id INT,
  name STRING,
  age INT,
  city STRING,
  hobby STRING
)
STORED BY 'com.mongodb.hadoop.hive.MongoStorageHandler'
WITH SERDEPROPERTIES('mongo.columns.mapping'='{"id":"_id","name":"<corresponding name in your collection>", "age":"<same here>", etc...}')
TBLPROPERTIES('mongo.uri'='mongodb://<hostIP>:27017/test.test');


text:
Q: Not outputting Opus raw audio I'm currently writing a small script that coverts an MP4 to Opus audio on the fly and sends it to Discord in golang. Initially my script would pass an MP4 as it was downloading to ffmpeg through stdin and then pass stdout to an Opus encoder, then to Discord (exactly like this). After learning I could build ffmpeg with Opus, I'd like to cut out the opus encoder I previous had and pass ffmpeg's output directly to Discord.
Previous, my ffmpeg command looked like this (with using the second opus encoder)
ffmpeg -i - -f s16le -ar 48000 -ac 2 pipe:1

Now, without the encoder and letting ffmpeg do all the work, this is what I've come up with so far.
ffmpeg -i - -f s16le -ar 48000 -ac 2 -acodec libopus -b:a 192k -vbr on -compression_level 10 pipe:1

With this command however the audio doesn't get accepted by Discord's server, meaning I'm suspecting opus audio isn't coming out the other end. No errors outputted. Have I done something wrong with ffmpeg that could of caused this?

A: Try
ffmpeg -i - -sample_fmt s16 -ar 48000 -ac 2 -acodec libopus -b:a 192k -vbr on -compression_level 10 -f opus pipe:1

You can't use -f s16le as that specifies an uncompressed output format (of a specific sample type), whereas you need a compressed data stream of a certain codec. Instead, you can use sample_fmt and -f opus


text:
Q: A construction of sigma-algebras - surely not new, right? I know no descriptive set theory. I've stumbled on something that must be well known, being so simple. But it contradicts something I've been told by smart people; the question is whether it's well known (or at least known).
A complete version of this post would be a little long. It seems clear to me that anyone who knows the answer is going to understand what I mean by the standard this and the usual that; if not I can clarify.
Context. Say $G$ is a group and $S\subset G$. There are at least three ways to say what $H$, the subgroup of $G$ generated by $S$, is:

*

*Let $S_0=S$, and let $S_{n+1}$ be $S_n$ together with all the $xy$ and $x^{-1}$ for $x,y\in S_n$. Then $H=\bigcup_{n=0}^\infty S_n$. (I call this the bottom-up construction.)

*$H$ is the set of all words in the elements of $S$.

*$H$ is the intersection of all the subgroups of $G$ containing $S$ (this I tend to think of as "top-down".)
Not that anyone would ever use (1) in this context. But now let's say $S\subset P(X)$, the powerset of $X$, and we want to describe $A$, the sigma-algebra generated by $S$. The analogue of (3) is what you see in every book on measure theory; some books include the transfinite-recursion analogue of (1) when they want to show that the Borel sets on the line have cardinality $c$. For some time I've speculated on whether there was something like (2) here.
There is.
(2') The elements of $A$ are exactly the roots of the trees $T$ such that $T$ is well-founded, every node of $T$ is a subset of $X$, every terminal node is an element of $S$, and every other node has either one or countably many subnodes; if a node $E$ has one subsnode $F$ then $E$ is the comlement of $F$, while if $E$ has countably many subnodes it is the union of the subnodes. (Taking advantage of the arity to avoid coloring the nodes to say which operation we're using is probably in poor taste, sorry.)
The proof that this works is totally elementary and straightforward from the definition of $A$ as the intersection of all sigma-algebras containing $S$ - no need to confuse the poor students with ordinals. And one can use it to show, for example, that the Borel sets on the line have cardinality $c$.
I'd be certain that this was perfectly well known except that smart people have told be that the only way to show the Borel sets have cardinality $c$ is transfinite induction.  Hence the question: This actually is standard, those guys were just unaware of it as I was until yesterday, right?

A: First, a small technical point: in order to count them it's best to look at trees which are subsets of $\omega^{<\omega}$, explicitly. This actually matters if the axiom of choice fails: just because each successor set is countable, and the tree is well-founded, doesn't mean the tree is countable if the countable union of countable sets isn't countable! In fact, there are models of ZF in which every set of reals is Borel. See also Arnold Miller's wonderful paper "Long Borel Hierarchies" (http://arxiv.org/abs/0704.3998)
Your trees are Borel codes. Since a lot of descriptive set theory really does use transfinite induction in an essential way, we often don't talk about Borel codes; however, they are intuitively fundamental, even if often just implicit, and there are also many times when explicitly talking about codes is invaluable, such as effective descriptive set theory (https://en.wikipedia.org/wiki/Borel_hierarchy#Lightface_hierarchy), reverse mathematics (as in https://math.berkeley.edu/~antonio/papers/Delta4Det.pdf), and algebras of sets beyond the Borel (analytic sets - which contain the Borel sets - are defined in terms of tree representations, finding tree representations for classes of sets is a big tool in descriptive set theory, and als see https://en.wikipedia.org/wiki/Infinity-Borel_set).
As far as showing that Borel codes really do code the Borel sets, I think there is a bit of a subtlety actually: how do you show that there is no proper subset of $A$ which is the class of Borel sets? That is, you need to show that every countable well-founded tree yields a set which must be Borel; to do this it seems to me you need to use induction on the rank of the well-founded tree.
This can be done in a way which does not seem to use transfinite induction: given a well-founded tree, if the root is not Borel then we can find some node which is not Borel, but all of whose successors are Borel (otherwise we could build a path through the tree). This is of course a contradiction.
I would argue, though, that this is transfinite induction in disguise.

A: For a set of reals $X$, define $ord(X)$ to be the length of Borel hierarchy on $X$. What are the possible values of $ord(X)$? Arnold Miller proved a lot of interesting results on this in his thesis. In particular, he showed that for each $\alpha < \omega_1$ it is consistent to have a set of reals $X$ with $ord(X) = \alpha$. To construct this model, he made use of what he called $\alpha$-forcing to add a generic $\mathbf{\Pi}^0_{\alpha}$-set. See his book especially Section 7.


text:
Q: Controling alignment in JPanel I have a JList with Strings that when put in panel with the default format, as expected, is aligned in the center of the panel. Is there a way to control this alignment with any of the other formats, or something like that?

A:
Is there a way to control this alignment

Yes, but you haven't given a specific requirement so we can't give a specific answer.
The default layout for a JPanel is the FlowLayout with center alignment.
If you want a different layout then you can:

*

*change the FlowLayout to be either right or left aligned. Read the FlowLayout API for the proper parameters

*change the panel to use a different layout manager. Read the Swing tutorial on Layout Managers for working examples of the other layout managers.


text:
Q: issue related to upload a file through PHP script Following kind of errors I am getting while try to upload a file on server using PHP script:
Notice: Undefined index: fileToUpload in C:\xampp\htdocs\PHP-Practice-file1\upload.php on line 3
Notice: Undefined index: fileToUpload in C:\xampp\htdocs\PHP-Practice-file1\upload.php on line 8
Warning: getimagesize(): Filename cannot be empty in C:\xampp\htdocs\PHP-Practice-file1\upload.php on line 8
File is not an image.
Notice: Undefined index: fileToUpload in C:\xampp\htdocs\PHP-Practice-file1\upload.php on line 23
Sorry, only JPG, JPEG, PNG & GIF files are allowed.Sorry, your file was not uploaded.
This is my html code:

Upload a file

            <form action="upload.php" method="post" enctype="multipart/form-data">
                Select image to upload:
                <input type="file" name="fileToUpload" id="fileToUpload">
                <input type="submit" name="submit" value="UPLOAD IMAGE">
            </form>

And this is my upload.php file:

<?php
$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));
// Check if image file is a actual image or fake image
if(isset($_POST["submit"])) {
    $check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
    if($check !== false) {
        echo "File is an image - " . $check["mime"] . ".";
        $uploadOk = 1;
    } else {
        echo "File is not an image.";
        $uploadOk = 0;
    }
}
// Check if file already exists
if (file_exists($target_file)) {
    echo "Sorry, file already exists.";
    $uploadOk = 0;
}
// Check file size
if ($_FILES["fileToUpload"]["size"] > 500000) {
    echo "Sorry, your file is too large.";
    $uploadOk = 0;
}
// Allow certain file formats
if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg"
&& $imageFileType != "gif" ) {
    echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
    $uploadOk = 0;
}
// Check if $uploadOk is set to 0 by an error
if ($uploadOk == 0) {
    echo "Sorry, your file was not uploaded.";
// if everything is ok, try to upload file
} else {
    if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
        echo "The file ". basename( $_FILES["fileToUpload"]["name"]). " has been uploaded.";
    } else {
        echo "Sorry, there was an error uploading your file.";
    }
}
?>


text:
Q: Project to have an API to get a list of prices and name along with python I am novice to the API field and want to learn the basics of API. I am also learning python. Can I use python along with API to achieve the goal provided below?
My ULTIMATE goal is to identify the price of a product from all the Big retailers and compare the price list.
Also kindly advise what are the tools, programing language that I need to have/learn apart from python and API.
[
    {
        name: xxx,
        id: xxx,
        price: xxx,
        Shop Name: xxx
    },
    {
        name: xxx,
        id: xxx,
        price: xxx,
        Shop Name: xxx
    },
]

A: There are 3 major steps with 2 main 'programs'
step 1
create a basic server
the two good frameworks I have experience in python are Django and Flask. Another that I don't have experience in but have heard good things about is fastAPI
Going through a tutorial for any to get a basic 'hello world' API endpoint running would be a good first step.
note
For this purpose, it won't make much of a difference if your api is REST, SOAP, or RPC. If none of these mean anything to you right now, that's ok. You'll learn more as you follow tutorials.
step 2
Create a webscraper to get prices for a product from a company site
Realistically, you'll probably want to create a list of all the companies / sites you'll want to include in your search for best prices.
It'll be best to try and get your webscraper functioning for a single site, and then expand it to each other site.
two decent tutorials for doing this are here
and here
After you're able to run your script and get best prices from a single site, expand it to be able to scrape all the sites in your list.
Each site will likely need it's own method, as the site layout and keywords to search for in the html/xml will be different per site.
Once you're able to run your script by giving it some product name and you get the best prices from an assortment of sellers, you're ready for step 3
step 3
put it all together
once you have a basic api endpoint, and your script to get best prices from sellers, all you need to do is format your script as a module in django or flask, then import and call the methods in your api endpoint.
In order to optimize (there are probably going to be a ton of sites in the list eventually), you'll want to look into threading and asynchronous tasks. Django is better for multithreading than flask if this is something you think you'll definitely want to implement
notes
the 2 major components of this are and api endpoint to serve your information, and a webscraper to gather the information.
Either of these pieces can be done in most programming languages
Python is a fine language for this, but I would personally recommend TypeScript and nextjs or a nodejs based framework for the api endpoint.
Another great option is Go, as Go inherently has amazing support for threading via Channels that would make calling python scripts at the same time and waiting for all to finish a fairly simple task
Python is still a great use case for webscraping, so if you go with a nodejs or Go based server, you'll want to have each site's webscraping in separate scripts, so that distinct programs can be called to run concurrently.
recap
you need a server and a webscraper. any language and framework is acceptable for either.


text:
Q: hover срабатывает не на весь блок У меня есть вот такой свитчер, и я хочу чтобы если я навожу на него, то та часть, которая не закрыта белым блоком, меняла свой background-color.

Я реализовал это следующим образом:
HTML

   <input type="checkbox">

2,5 кг

25 кг

LESS
.product-switcher {
            display: flex;
            position: absolute;
            width: 180px;
            height: 24px;
            background: #E6F3D9;
            border-radius: 40px;
            left: 50%;
            transform: translateX(-50%);
            bottom: 8px;
            :hover {
                background: #81C341;
                border-radius: 40px;
                height: 100%;
                width: 100%;
            }
            input {
                display: none;
            }
            .product-switcher-current {
                position: absolute;
                left: 0;
                top:0;
                background: #FFFFFF;
                width: 94px;
                height: 24px;
                border-radius: 40px;
                border: 1px solid #81C341;
                transition-duration: .2s;
            }
            input:checked + .product-switcher-current {
                transform: translateX(86px);
        }
        .product-switcher-left, .product-switcher-right {
            flex-basis: 50%;
            text-align: center;
            color: @primary60;
            z-index: 1;
            &.active {
                color: @black;
            }
        }

Но в итоге имею вот такой результат:

Что я делаю не так?

A: .product-switcher {
  display: flex;
  position: absolute;
  width: 180px;
  height: 24px;
  background: #E6F3D9;
  border-radius: 40px;
  left: 50%;
  transform: translateX(-50%);
  bottom: 8px;
    &:hover {
      background: #81C341;
    }
  input {
    display: none;
  }
  .product-switcher-current {
    position: absolute;
    left: 0;
    top:0;
    background: #FFFFFF;
    width: 94px;
    height: 24px;
    border-radius: 40px;
    border: 1px solid #81C341;
    transition-duration: .2s;
  }
  input:checked + .product-switcher-current {
    transform: translateX(86px);
  }
  .product-switcher-left, .product-switcher-right {
    flex-basis: 50%;
    text-align: center;
    color: @primary60;
    z-index: 1;
    &.active {
      color: @black;
    }
  }
}


text:
Q: Invariant Violation: Objects are not valid as a React child (found: object with keys {_40, _65, _55, _72}) I have one Flatlist and in flat list each item has geolocation.
I am calling {this.getitemlocation(item.location)} from inside of Flatlist. Here getitemlocation() is function and item.location is longitude and latitude.
My getitemlocation():
 async getitemlocation(item) {
   let locationstring = item.split(",");
    if(locationstring[0]!="None"&&locationstring[1]!="None"){
    let location = {
      latitude: Number(locationstring[0]),
      longitude: Number(locationstring[1]),
    };
    itemloacation = await Location.reverseGeocodeAsync(location);
    return (
      <Text style={styles.itemLocation} key={item}>
        {itemloacation.name} {"\u2022"} 2.3 km
      </Text>
    );
    }
    else{
      return (
        <Text style={styles.itemLocation}>
          No Location
        </Text>
      );
    }
  }

Error I am getting:

Invariant Violation: Objects are not valid as a React child (found: object with keys {_40, _65, _55, _72}). If you meant to render a collection of children, use an array instead.

A: You can't return on async function like that. You can use Promise like this:

getitemlocation(item){
  return new Promise(async (resolve) => {
    let locationstring = item.split(",");
    if(locationstring[0]!="None"&&locationstring[1]!="None"){
      let location = {
        latitude: Number(locationstring[0]),
        longitude: Number(locationstring[1]),
      };
      itemloacation = await Location.reverseGeocodeAsync(location);
      resolve(
        <Text style={styles.itemLocation} key={item}>
          {itemloacation.name} {"\u2022"} 2.3 km
        </Text>
      )
    }else{
      resolve (
        <Text style={styles.itemLocation}>
          No Location
        </Text>
      );
    }
}


text:
Q: Isomorphism in the case of real symmetric matrices I'm looking for clarification of the following problem: it's known that determining which graphs are uniquely determined by their spectra is in general a very hard problem.
But what about more general problem - real symmetric square matrices?
1) Do we have the same problem when two cospectral matrices can be non-isomorphic?
And a related question: 2) is there any simple method to test isomorphism of two arbitrary real symmetric square matrices?
Many Thanks


text:
Q: How to append a textbox to a table row with jQuery? How to append a textbox to a table row with jQuery?

A: Use the append() function.
var tr = getItSomehow();
var textbox = $('<input type="text" id="foo" name="foo">');
tr.append(textbox);

See also:

*

*jQuery append() documentation

A: How can you append an input type to a table row? You have to append it to a table cell, if not you can position it absolute at the position of the table row. You can't append it to a row via the DOM,
Seeing your other question, why don't you add an input type hidden to the first cell of the row? You could easily do this like this:
$('tr#id td:first').append($('<input type="hidden" id="hidden_field" name="hidden_field" value="your value" />'));

A: Give the destination element and ID.  Then:
$('#destinationId').append('<input type="text" name="newBox" />');


text:
Q: iOS - Difference Between Offset And Inset When Setting UIView Shadow? So I wanted to put a 5 pixel shadow on my UIView on the top, left, and right of it. After much trial and error, this code seems to do the trick for me:
self.layer.shadowColor = [[UIColor purpleColor] CGColor];
self.layer.shadowOffset = CGSizeMake(0.0f,-5.0f);
self.layer.shadowOpacity = 1.0f;
self.layer.shadowRadius = 0.0f;
CGRect shadowRect = CGRectInset(self.bounds, -10, -5);  // inset top/bottom
self.layer.shadowPath = [[UIBezierPath bezierPathWithRect:shadowRect] CGPath];

It gives me this results, which seems correct:

Since this came with a lot of trial and error, I still don't quite understand how insets and offsets work. I've looked on the internet, but all the definitions are so general (ex. offset is the amount of space by which something is offset...what?).
Can someone explain to me the difference between insets and offsets when drawing shadows? I want to KNOW how it works so next time I won't have to spend so long with trial and error. Thanks!

A: Offset is the amount by which the shadow is moved relative to the object that is being shadowed, so how far to the left or right, top or bottom the shadow is.
The inset is the size of the shadow relative to the object.  So if you have an inset of (-10,-10) then the shadow will be 10 pixels wider and 10 pixels higher than the object.  Note than a negative inset makes the shadow larger.  A positive inset reduces the size of the shadow.


text:
Q: FMDatabaseQueue is not surviving a class init() I've been trying to put together the code initializer into the init() function of model class I have like this:
 init?() {
    let docsDir =     NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] as String
    let dbPath = docsDir.stringByAppendingPathComponent("app.sqlite")
    let dbQueue = FMDatabaseQueue(path: dbPath)

    if dbQueue == nil {
        NSLog("%@ : %@", "Problem connecting to the db at", __FUNCTION__)
        return nil
    } else {
        NSLog("%@", "Successfully connected to the db")
    }
}

when I try to use dbQueue from another function of that class it the dbQueue always amount to nil like
 func anotherFunction() {
   dbQueue?.inDatabase{ db in .... }
 }

So when I try to initialize:
 let db = dbConnector()
 db.anotherFunc() // Zilch!

My questions is WHY this is happening and how to fix it. Please help, I'll ask Thor to bless you

A: I found the solution. I was using let dbQueue on a the class property dbQueue which was actually creating a local variable inside the init() with the same name, leaving the property uninitialized, hence the nil


text:
Q: Laravel Unexpected Data found I'm trying to calculate time difference in minutes via Laravel and Carbon.
My query: $findPauseWorky = ClockingSystemHours::where('total_time','=', null)->where('worky_id','=',$id)->whereNotNull('end_time')->get();
When I get my collection from my query the result looks like this:
Collection {#407
  #items: array:1 [
    0 => ClockingSystemHours {#408
      #dates: array:3 [
        0 => "start_time"
        1 => "end_time"
        2 => "total_time"
      ]
      #original: array:8 [
        "id" => 2
        "start_time" => "16:21:29"
        "end_time" => "23:20:52"
        "total_time" => null
        "worky_id" => 2
        "employee_id" => 1
        "created_at" => "2019-01-24 16:21:29"
        "updated_at" => "2019-01-24 16:21:29"
      ]

As you can see in the result I've set my $dates in my model.
If i execute this dd($findPauseWorky->first()->start_time); it results in this:
Unexpected data found.
    ↵Unexpected data found.
    ↵Data missing

When i execute this: dd($findPauseWorky->first()->worky_id); it results in this :
2
What am I doing wrong? Or is there a reason why I cant access the data?


text:
Q: AngularJS's $http.post() sends each time two AJAX requests, one without the data and one with I have a weird problem with AngularJS's $http service which, as far as I can see, no one else has.
Every time I use $http.post() to sent cross domain requests, I can see in the developer tools (network pane) that two different requests are being sent: one, without any data, and immediately after that another one is sent which has all the data and returns with the correct response from the server.
Here's an example:
$http.post(url+'getSiteList.php', {session_id: $scope.session_id(), withCredentials: true})
        .success(function(data, status, headers, config) {
            console.log(data);
....

Does anyone know what's causing this? I checked the code, and the $http.post method is only being called once.

A: It's all about how browsers manage CORS. When making a cross-domain request in angular, the browser will automatically make a HTTP OPTIONS request to the specified URL/URI it is called as "pre-flight" request or "promise".
As long as the remote source returns a HTTP status code of 200 and relevant details about what it will accept in the response headers, then the browser will go ahead with the original JavaScript call.


text:
Q: Unable to copy the end portion of one file to another using BufferedWriter Edited:
Actual mistake was that File1 contents are completely copied into File2 + with some other lines of text. The file was huge. So the question has to be rephrased accordingly. But, the answer is correct. It solves the problem. Extra lines are removed.

Code Snippet:

 public class ReadAFile {
    public static void main(String[] args) throws IOException {
        File file = new File("primes.txt");
        FileReader reader = new FileReader(file);
        BufferedReader bufferedReader = new BufferedReader(reader);

        BufferedWriter writer = new BufferedWriter(new FileWriter(new File("primesFile.txt")));
        char[] buffer = new char[1024];
        int read;
        while ((read = bufferedReader.read(buffer)) > 0) {
            writer.write(buffer, 0, buffer.length);
        }
        writer.close();
        bufferedReader.close();
    }
}

A:     while ((read = bufferedReader.read(buffer)) > 0) {
        writer.write(buffer, 0, buffer.length);
    }

Usual mistake. You're assuming that read() fills the buffer. Se the Javadoc. You need to use the read count in the write method:
    while ((read = bufferedReader.read(buffer)) > 0) {
        writer.write(buffer, 0, read);
    }

But unless you know for sure that the file is text you should be using streams, not readers and writers.


text:
Q: Can't decide which drive to choose to install Ubuntu Ubuntu 20.04.2.0 LTS This is my first time trying to install Ubuntu on my PC. I am using Windows 10.
I have two identical NVME SSDs installed (both 1 TB - Western Digital), one of them is newly installed and completely empty.
I downloaded the Ubuntu 20.04.2.0 LTS and made bootable flash drive. Everything is good until I reach Installation type window.
Now, I have three options. I would like to keep Windows and install Ubuntu on the 2nd Hard Disk, so the operating systems don't share a drive. When I click on 'something else' type installation I get so many different volumes and I am so confused which one to choose.

The only difference I see is nvme0n1 and nvme1n1. Which one exactly should I choose? And I don't want to have a lot of weird partitions. Two simple Drives for each operating system.
If I click 'Erase disk and Install Ubuntu' I see this.

That would mean it will erase the content if I click on the one I already have windows on. I have no way of telling which one's the right one.
So! for now I quit the installation and looking for an advice. I am sorry if this is a long post and also if this is a stupid question. I would really appreciate if someone could help me and solve this mystery for me.

A: Here is what I would suggest:

*

*BACKUP ANY IMPORTANT DATA, JUST TO BE ON THE SAFE SIDE

*Make note of which nvme drive is in exactly which slot on your motherboard

*Remove the recently installed nvme drive from your computer (make sure you can boot into Windows, to be sure you removed the correct drive)

*With the newly added drive removed, reboot the computer into the Ubuntu live USB

*Make your way through the installer until you reach the Something else option (same section as, for example, Erase disk and install Ubuntu)

*With Something else selected, click Continue

*When you reach the partitioning screen, make note of the name of the nvme drive listed towards the top (either nvme0n1 or nvme1n1), This will be the drive Windows is installed on, and should retain it's drive name even after replacing the second nvme drive (take a picture of the partition layout just to be on the safe side)

*Power down your computer, reinstall the second nvme drive, and once again boot into the Ubuntu live USB

*Repeat steps 3 and 4, although this time with the intention of installing Ubuntu

*Double check that the drive you noted from before (i.e. nvme1n1) still has the same drive layout (that you took a picture of)

*Once you are as sure as you can be, click Back and install Ubuntu however you intend to, on your secondary nvme drive (i.e. nvme0n1)

*Grab a cup of, I dunno, tea? and let the installer do it's thing

*Reboot your computer

*Enjoy using Ubuntu!

*Check out OMG! Ubuntu's 10 Things to do After Installing Ubuntu 20.04 LTS  article for some tips and ideas

A: Install Ubuntu on Second Drive
You can't mess up Windows drive if it is not plugged in.

*

*Remove Windows drive.

*Plug in new drive.

*Boot Live USB in same mode as Windows uses, (Legacy or UEFI).

*Install Ubuntu.

*Shut down, remove Live USB, plug in Windows drive.

*Boot new Ubuntu drive and in Terminal run sudo update-grub to add Windows to Ubuntu's boot menu.

A: I was able to find out in Windows disk manager which drive had windows installed and which one had unallocated space. So in my case nvme1n1 had windows installed and nvme0n1. I realised this after @eastingNerd's answer. Thank you so much.
After I was sure in which drive I could install Ubuntu. I followed the steps and it's running perfectly fine. I think I like the User interface and after a couple of days/weeks/months hopefully I'd get used to it.


text:
Q: mdDatepicker broken with AngularJS 1.5.9 and 1.6 Angular 1.5.9 introduced very interesting performance upgrades:
$compileProvider.commentDirectivesEnabled( false ); // disable comment directives
$compileProvider.cssClassDirectivesEnabled( false ); // disable css class directives

I updated version of Angular in my app to 1.5.9-build.5158+sha.cc92da0 and later to 1.6.0-rc.1 to use above features. Everything except one detail works fine.
The thing which is broken is Angular Materials datepicker (1.1.1).
When you open datepicker it appears empty, but when you scroll it up a little all information appears. DEMO
I spent some time fiddling around but I can't find the direct reason of such behavior.
Any help with fixing this bug will be appreciated.

A: The problem was caused by $compileProvider.preAssignBindingsEnabled set to false by default in Angular 1.6.
More info.
To fix that problem I changed it to true:
.config( [ '$compileProvider', function ( $compileProvider ) {
  /* ... */
  $compileProvider.preAssignBindingsEnabled( true );
} ] )


text:
Q: How to get parent table attributes from child model var ParentModel = bookshelf.Model.extend({ });
var ChildModel = ParentModel.extend({ });

new ChildModel().fetch().then(function(child){
    console.log(child.get('parentAttribute')); //undefined
});

How can I get the inherited table attributes from the child object ?

A: Unfortunately inheritance relationships are not supported by Bookshelf. In my post at the bookshelf forum I was suggested to use a plugin called Virtuals to simulate this behavior by adding getters and setters to the children models.
https://github.com/tgriesser/bookshelf/issues/612