text:
Q: Why is that crashing ? (buffer overflow) #include <stdio.h>
#define N 100

int main()
{
 int n,c,d,a[N],b[N];

printf("Insert elements numbers in the array\n");
 scanf("%d ", n);

printf("Insert the elements in the array\n");

for (c = 0; c < n ; c++)
scanf("%d", a[c]);

for (c=n-1,d = 0;d < n; c--,d++)
b[d]= a[c];

for(c = 0; c <n; c++)
a[c] = b[n];

printf("The array inverted is\n");

for(c=0; c<n;c++)
printf("%d\n",a[c]);

return 0;
}

why is that crashing ? i've tried even if with values ( N < 100 ) but that still crashes , i don't know how to fix it ? can someone help me please ? thanks !

A: This:
scanf("%d ", n);

invokes undefined behavior. scanf() needs a pointer to where the number should be stored, it should be:
scanf("%d ", &n);

The same goes for the rest of your scanf() calls. Also, you should check the return value to know that it succeeded in reading the data in, before relying on the variables containing valid values.

A: scanf needs the address to write to, not the actual value.
Do this instead:
scanf("%d", &a[c]);

A: What they said about scanf needing an address.  But also, what is this doing?
for(c = 0; c <n; c++)
  a[c] = b[n];

n is the number of elements in each array, so calling b[n] will give you a (possibly unannounced) problem.  The compiler tends to not warn about that kind of out-of-bounds access (see this post).
I suspect you intended to copy b into a anyway, and not copy one value to every element of a, but that's purely speculation since you haven't declared what the expected input or output is.

A:
why is that crashing ?

Wiki says:

A crash (or system crash) in computing is when a computer or a program (such as a software application or an operating system) stops functioning properly. Oftentimes, it will then exit after encountering these errors. The program responsible may appear to freeze until a crash reporting service documents the details of the crash. If the program is a critical part of the operating system kernel, the entire computer may crash, often resulting in a fatal system error. This behavior is called "crashing".
Typical errors that result in application crashes include:

*

*attempting to read or write memory that is not allocated for reading or writing by that application (segmentation fault) or x86 specific (general protection fault)

*attempting to execute privileged or invalid instructions

*attempting to perform I/O operations on hardware devices to which it does not have permission to access

*passing invalid arguments to system calls

*attempting to access other system resources to which the application does not have permission to access (bus error)

*attempting to execute machine instructions with bad arguments (depending on CPU architecture): divide by zero, operations on denorms or NaN values, memory access to unaligned addresses, etc.

In your program, the statements
scanf("%d ", n);

and
scanf("%d", a[c]);

causing your program to crash.
As others suggested place & operator before the scanf arguments
scanf("%d ", &n);
scanf("%d", &a[c]);


text:
Q: Download large files with PHP I'm using jQuery with PHP.
I've written a simple download function with PHP:
function downloadFile($sFile){
        #Main function
        header('Content-Type: '.mime_content_type($sFile));
        header('Content-Description: File Transfer');
        header('Content-Length: ' . filesize($sFile));
        header('Content-Disposition: attachment; filename="' . basename($sFile) . '"');
        readfile($sFile);
    }

I can download a file through this script, but if it's a large files(like 1GB), the readfile function needs his time until the download start. So i have to wait about a minute or something, until the download really starts.
Any idea how to optimze my script, so the download starts immediately?

A: You could configure Apache to set the proper headers in your .htaccess file. Then, you could link directly to the file instead of the PHP page. This will also reduce server load.
Of course, if the PHP script performs functions other than just setting headers (such as authentication) then this is not an option. You will have to pass the file through PHP in chunks as @N.B. mentions in his comment.

redpajama_set_name: RedPajamaStackExchange


text:
Q: i wanna know how to find phonegap icon on my toolbar even i install phonegap plugin on luna eclipse I don't know why I can't find that Evne I installed plugin.
Already I tried to uninstall this plug in n reinstalled but that didn't work.
anybody knows how to handle this ?
Plz help me .

A: Install cordova using cmd and use that will be better:
install node js, then try :
npm install -g cordova

then create new project using cmd:
    cordova create hello com.example.hello Hello

Please refer this


text:
Q: Reshape Pandas Dataframe Say I have the following dataframe where I have counts of some variable at 2 different seasons in 2 different years and in 3 different locations. The data is currently structured where each row is a Season / Location combination and there are columns for the count in each year. It looks something like this:
>>> df=pd.DataFrame([['Summer', 'A', 1, 2],
                     ['Winter', 'A', 3, 4],
                     ['Summer', 'B', 5, 6],
                     ['Winter', 'B', 7, 8],
                     ['Summer', 'C', 9, 10],
                     ['Winter', 'C', 11, 12]],
                    columns=['Season', 'Location', 'Count_2014', 'Count_2015'])
>>> df
   Season Location  Count_2014  Count_2015
0  Summer        A           1           2
1  Winter        A           3           4
2  Summer        B           5           6
3  Winter        B           7           8
4  Summer        C           9          10
5  Winter        C          11          12

I want to restructure the data so that I have a row for each Season, Location, and Year combination (meaning I would have 2 x 3 x 2 = 12 rows). My current approach to doing so is certainly not the most efficient (see below). Any suggestions on the best way to restructure this dataset?
df.set_index(['Season', 'Location'], inplace=True)
ListOfDFs = []
for Year in [x[-4:] for x in df.columns]:
    SubD = df[['Count_' + Year]]
    SubD.columns = ['Count']
    SubD['Year'] = Year
    SubD.set_index('Year', append=True, inplace=True)
    ListOfDFs.append(SubD)

df2=pd.concat(ListOfDFs)
>>> df2
                      Count
Season Location Year
Summer A        2014      1
Winter A        2014      3
Summer B        2014      5
Winter B        2014      7
Summer C        2014      9
Winter C        2014     11
Summer A        2015      2
Winter A        2015      4
Summer B        2015      6
Winter B        2015      8
Summer C        2015     10
Winter C        2015     12

A: You are looking for the melt functionality, which will allow you to do this in basically one line:
df_new = pd.melt(df,id_vars=['Season', 'Location'], value_vars=['Count_2014', 'Count_2015'],
        var_name='Year',
        value_name='Count')

Then you can use apply (or there probably is something better), to get the output you have above:
df_new['Year'] = df_new['Year'].apply(lambda x: x[-4:])

Output:
    Season Location  Year  Count
0   Summer        A  2014      1
1   Winter        A  2014      3
2   Summer        B  2014      5
3   Winter        B  2014      7
4   Summer        C  2014      9
5   Winter        C  2014     11
6   Summer        A  2015      2
7   Winter        A  2015      4
8   Summer        B  2015      6
9   Winter        B  2015      8
10  Summer        C  2015     10
11  Winter        C  2015     12

A: And as another option, it looks like stack() also gets the job done:
>>> df=pd.DataFrame([['Summer','A',1,2],['Winter','A',3,4],['Summer','B',5,6],['Winter','B',7,8],['Summer','C',9,10],['Winter','C',11,12]], columns=['Season','Location','Count_2014','Count_2015'])
>>>
>>> df.set_index(['Season','Location'], inplace=True)
>>> df.columns=pd.MultiIndex.from_tuples([(col[-4:],col[:-5]) for col in df.columns], names=['Year','Count'])
>>> df=df.stack(level=0)
>>> df
Count                 Count
Season Location Year
Summer A        2014      1
                2015      2
Winter A        2014      3
                2015      4
Summer B        2014      5
                2015      6
Winter B        2014      7
                2015      8
Summer C        2014      9
                2015     10
Winter C        2014     11
                2015     12
>>>


text:
Q: Legal aspects of Java specification implementations in other programming languages I am planning to implement an official Java specification in a different programming language. Would this be a copyright violation?
Hypothetical examples:

*

*a JMX "wrapper" library for C++ which can control a Java application over JMX, and uses similar concepts and class/method names as the Java implementation

*a JavaMail API and implementations (for different .Net network libraries) for C#

A: Implementing to APIs and the like probably isn't a copyright violation in the USA.  If you need actual legal advice, find a lawyer of the proper specialty in the jurisdiction you're in.  It'll be a lot cheaper than defending a lawsuit if you guess wrong.
Please note that asking legal advice on an international forum primarily composed of non-lawyers is not completely reliable, particularly when you neglect to tell us where you live.  Laws do vary from country to country, even relatively consistent ones like copyright.


text:
Q: Recursive function to counting specific digit I need to create a recursive function that counts the 2 and 6 from the number a user inputs.
For example if the user enters 26827 the count is 3.
It works with certain numbers and certain numbers it doesn't. Can someone please modify my function making sure its recursive and using very basic C++ language as I have used. Thank you! (I believe something is wrong with return type.)
int count(int n) {
    static int count = 0;
    if (n == 2 || n == 6) count++;
    if ((n % 10 == 2) || (n % 10 == 6)) {
        count++;
        count(num / 10);
    }
    else return count;
}

A: One liner for fun.
int f(int n) {
  return n == 0 ? 0 : (n%10==2 || n%10==6) + f(n/10);
}

A: int count(int n) {
    if(n <= 0) return 0;  // Base Condition
    int countDig = 0;       // Initalizing Count of digits
    if(n % 10 == 2 || n % 10 == 6)  // Checking whether the LSB is 2 or 6
        countDig ++; // If it is then incrementing the countDig
    countDig += count(n / 10);  // Calling the recurive function by sending the number except its LSB
                        //And incrementing counter according to it
    return countDig;    // Returning the final count
}

you don't need to have a static value counter. It can be easily done as above. Please refer to comments given. Second the error in your code is you only calling the recursion if the LSB is 2 or 6. The recursion should be put outside the if condition in your code. Why are you using num variable. I think it should be n

A: You don't need statics
This should work (note return c + count(n / 10) line. That's the main recursion here)
int count(int n)
{
    int c = 0;
    if(n % 10 == 2 || n % 10 == 6)
        c = 1;
    if(n < 10)
        return c;
    return c + count(n / 10);
}

A: If you want to make it with recursion , another procedure you can apply using string manipulation.
PseudoCode:
Function ( int n):
     1. Make n as a string. ( Convert Number to string)
     2. Collect the first character (char C) of the string and remove the character from the string.
     3. Make the main string again as a number n. ( Convert String to Number).
     4. Check the character C , which is number 2 or 6 or not, count it with a flag.
     5. Enter base case for which the recursion will stop.
     6. return the number n , inside the Function (n) for recursion.


text:
Q: Bash redirect stdout and stderr to seperate files with timestamps Want to log all stdout and stderr to seperate files and add timestamp to each line.
Tried the following, which works but is missing timestamps.
#!/bin/bash

debug_file=./stdout.log
error_file=./stderr.log

exec > >(tee -a "$debug_file") 2> >(tee -a "$error_file")

echo "hello"
echo "hello world"

this-will-fail
and-so-will-this

Adding timestamps. (Only want timestamps prefixed to log output.)
#!/bin/bash

debug_file=./stdout.log
error_file=./stderr.log

log () {
  file=$1; shift
  while read -r line; do
    printf '%(%s)T %s\n' -1 "$line"
  done >> "$file"
}

exec > >(tee >(log "$debug_file")) 2> >(tee >(log "$error_file"))

echo "hello"
echo "hello world"

this-will-fail
and-so-will-this

The latter adds timestamps to the logs but it also has the chance of messing up my terminal window. Reproducing this behavior was not straight forward, it only happend every now and then. I suspect it has to with the subroutine/buffer still having output flowing through it.
Examples of the script messing up my terminal.
# expected/desired behavior
user@system:~ ./log_test
hello
hello world
./log_test: line x: this-will-fail: command not found
./log_test: line x: and-so-will-this: command not found
user@system:~ # <-- cursor blinks here

# erroneous behavior
user@system:~ ./log_test
hello
hello world
user@system:~ ./log_test: line x: this-will-fail: command not found
./log_test: line x: and-so-will-this: command not found
# <-- cursor blinks here

# erroneous behavior
user@system:~ ./log_test
hello
hello world
./log_test: line x: this-will-fail: command not found
user@system:~
./log_test: line x: and-so-will-this: command not found
# <-- cursor blinks here

# erroneous behavior
user@system:~ ./log_test
hello
hello world
user@system:~
./log_test: line x: this-will-fail: command not found
./log_test: line x: and-so-will-this: command not found
# <-- cursor blinks here

For funs I put a sleep 2 at the end of the script to see what would happen and the problem never occurred again.
Hopefully someone knows the answer or can point me in the right derection.
Thanks

Edit
Judging from another question answered by Charles Duffy, what I'm trying to achieve is not really possible in bash.
  Separately redirecting and recombining stderr/stdout without losing ordering

A: The trick is to make sure that tee, and the process substitution running your log function, exits before the script as a whole does -- so that when the shell that started the script prints its prompt, there isn't any backgrounded process that might write more output after it's done.
As a working example (albeit one focused more on being explicit than terseness):
#!/usr/bin/env bash
stdout_log=stdout.log; stderr_log=stderr.log

log () {
  file=$1; shift
  while read -r line; do
    printf '%(%s)T %s\n' -1 "$line"
  done >> "$file"
}

# first, make backups of your original stdout and stderr
exec {stdout_orig_fd}>&1 {stderr_orig_fd}>&2
# for stdout: start your process substitution, record its PID, start tee, record *its* PID
exec {stdout_log_fd}> >(log "$stdout_log"); stdout_log_pid=$!
exec {stdout_tee_fd}> >(tee "/dev/fd/$stdout_log_fd"); stdout_tee_pid=$!
exec {stdout_log_fd}>&- # close stdout_log_fd so the log process can exit when tee does
# for stderr: likewise
exec {stderr_log_fd}> >(log "$stderr_log"); stderr_log_pid=$!
exec {stderr_tee_fd}> >(tee "/dev/fd/$stderr_log_fd" >&2); stderr_tee_pid=$!
exec {stderr_log_fd}>&- # close stderr_log_fd so the log process can exit when tee does
# now actually swap out stdout and stderr for the processes we started
exec 1>&$stdout_tee_fd 2>&$stderr_tee_fd {stdout_tee_fd}>&- {stderr_tee_fd}>&-

# ...do the things you want to log here...
echo "this goes to stdout"; echo "this goes to stderr" >&2

# now, replace the FDs going to tee with the backups...
exec >&"$stdout_orig_fd" 2>&"$stderr_orig_fd"

# ...and wait for the associated processes to exit.
while :; do
  ready_to_exit=1
  for pid_var in stderr_tee_pid stderr_log_pid stdout_tee_pid stdout_log_pid; do
    # kill -0 just checks whether a PID exists; it doesn't actually send a signal
    kill -0 "${!pid_var}" &>/dev/null && ready_to_exit=0
  done
  (( ready_to_exit )) && break
  sleep 0.1 # avoid a busy-loop eating unnecessary CPU by sleeping before next poll
done

So What's With The File Descriptor Manipulation?
A few key concepts to make sure we have clear:

*

*All subshells have their own copies of the file descriptor table as created when they were fork()ed off from their parent. From that point forward, each file descriptor table is effectively independent.

*A process reading from (the read end of) a FIFO (or pipe) won't see an EOF until all programs writing to (the write end of) that FIFO have closed their copies of the descriptor.

...so, if you create a FIFO pair, fork() off a child process, and let the child process write to the write end of the FIFO, whatever's reading from the read end will never see an EOF until not just the child, but also the parent, closes their copies.
Thus, the gymnastics you see here:

*

*When we run exec {stdout_log_fd}>&-, we're closing the parent shell's copy of the FIFO writing to the log function for stdout, so the only remaining copy is the one used by the tee child process -- so that when tee exits, the subshell running log exits too.

*When we run exec 1>&$stdout_tee_fd {stdout_tee_fd}>&-, we're doing two things: First, we make FD 1 a copy of the file descriptor whose number is stored in the variable stdout_tee_fd; second, we delete the stdout_tee_fd entry from the file descriptor table, so only the copy on FD 1 remains. This ensures that later, when we run exec >&"$stdout_orig_fd", we're deleting the last remaining write handle to the stdout tee function, causing tee to get an EOF on stdin (so it exits, thus closing the handle it holds on the log function's subshell and letting that subshell exit as well).

Some Final Notes On Process Management
Unfortunately, how bash handles subshells created for process substitutions has changed substantially between still-actively-deployed releases; so while in theory it's possible to use wait "$pid" to let a process substitution exit and collect its exit status, this isn't always reliable -- hence the use of kill -0.
However, if wait "$pid" worked, it would be strongly preferable, because the wait() syscall is what removes a previously-exited process's entry from the process table: It is guaranteed that a PID will not be reused (and a zombie process-table entry is left as a placeholder) if no wait() or waitpid() invocation has taken place.
Modern operating systems try fairly hard to avoid short-term PID reuse, so wraparound is not an active concern in most scenarios. However, if you're worried about this, consider using the flock-based mechanism discussed in https://stackoverflow.com/a/31552333/14122 for waiting for your process substitutions to exit, instead of kill -0.


text:
Q: TypeScript map intersection type to overloads I have a type that is an intersection of types that represents a list of method signatures:
type query =
    | ((query: getAuthorizationState) => AuthorizationState)
    | ((query: setTdlibParameters) => Ok)
    | ((query: checkDatabaseEncryptionKey) => Ok)
    | ((query: setAuthenticationPhoneNumber) => Ok)
    | ((query: resendAuthenticationCode) => Ok)
    | ((query: checkAuthenticationCode) => Ok)
    | ((query: checkAuthenticationPassword) => Ok)
    | ((query: requestAuthenticationPasswordRecovery) => Ok)
    | ((query: recoverAuthenticationPassword) => Ok)
    | ((query: checkAuthenticationBotToken) => Ok)
    | ((query: logOut) => Ok)
    | ((query: close) => Ok)
    | ((query: destroy) => Ok)
// ...

This goes on for 301 lines, and is meant to serve as a mapping between parameters and results. Then, I created a series of types that perform some gymnastics in order to transform the query type:
type ParamDistribute<T> = T extends (q: infer U) => infer V ? U : never;
type ReturnDistribute<T> = T extends (q: infer U) => infer V ? V : never;
type QueryDistribute<T> = T extends (q: infer U) => infer V ? (q: U) => V | error | null : never;
type PromiseDistribute<T> = T extends (q: infer U) => infer V ? (q: U) => Promise<V> : never;
type FutureDistribute<T> = T extends (q: infer U) => infer V ? (q: U) => Future<Error, V> : never;

export type Query = ParamDistribute<query>;
export type QueryResult = ReturnDistribute<query>;
export type QueryFunc = QueryDistribute<query>;
export type QueryFuncPromise = PromiseDistribute<query>;
export type QueryFuncFuture = FutureDistribute<query>;

QueryFunc is the same as query, except all of the return types are intersected with error (not Error, but a custom interface that I have) and null. QueryFuncPromise is the same as query, except all of the return types are promises, etc.
Now, I have a class that has a function that implements this type signature. I've tried to apply the query type using an interface and made the function generic:
interface TDClientFunctions
{
    query: TDL.QueryFuncFuture;
}

export class TDClient extends EventEmitter implements TDClientFunctions
{
    // ...

    public query<T extends TDL.Query, V extends TDL.QueryResult>(query: T):
        Fluture.FutureInstance<TDL.error, V>
    {
        // ...
    }
}

However, I still don't get the correct type validation when I try to use the method:

There is only one interface in the query intersection that fits the parameter I passed:

export type testCallEmpty = {
   _: "testCallEmpty",
}

// ...

type query =
    // ...
    | ((query: testCallEmpty) => Ok)
    // ...

So why does the return type not resolve to Ok? Why is the type parameter V not properly inferred?
In other words, I'm trying to provide function overload signatures without actually writing them as overloads because there are 300 of them, and my class is going to have more than one method that follows this pattern (hence QueryFunc, QueryFuncPromise, QueryFuncFuture, etc.). Is this possible in TypeScript?


text:
Q: Should 'cursor' property be defined in '.class' or '.class:hover'? Since both of the following have the same effect:
.class {
    cursor:pointer;
}

.class:hover {
    cursor:pointer;
}

Regarding best practices, which one should you use and why?

A: The two selectors are for distinctly separate purposes, despite the fact that- at least in practice they appear to accomplish the same thing.
I would tend to say it would be best practice to define the hover state using :hover (at least on non-touchscreen devices, see below), because:

*

*It makes finding and understanding your styling more apparent in larger blocks of  CSS

*It utilizes a specifically designated selector (which may be extended in the spec at a later date, what would then happen to your functionality?)

*If you later add to the default styling for .class your states are clearly separated appropriately

*What happens if you hand over responsibility of your CSS to another individual? Having :hover specific functionality defined under the correct selector makes understanding code a heck of a lot easier.

*If you have more complex CSS its likely you'll be using :hover elsewhere, so should use it for the purposes of consistency

*The two selectors represent the same element but in different states, semantically you should use :hover
But hang on a minute.. you may notice that if you set the cursor style for an a element to default then the usual hand icon wont appear on hover...this indicates that there is baked-in prior evidence for not specifically styling :hover states (see this in action here)
In summary, there is no game breaking reason not to use simply .class in some circumstances- it certainly uses less bytes and if you have a fairly simple setup then only under development by you...then why not, but be wary it is probably best avoided if you want to adhere to the strict rules and better support ongoing development.
In addition..lets not forget touchscreen devices MDN makes an important point here

on touch screens :hover is problematic or impossible. The :hover
  pseudo-class never matches, or matches for a short moment after
  touching an element. As touchscreen devices are very common, it is
  important for web developer not to have content accessible only when
  hovering over it, as this content would be hidden for users of such
  devices.

As such depending on your requirement, it may not be best to use :hover as if you have it in your CSS for a touch screen device it may bake in reliance on unsupported or flakey functionality.

A: IE6 and lower only recognises the :hover pseudo class on a tags. :hover on a div or other tag will not be interpreted by those browsers.
If compatibility is a consideration, use the :hover else I believe there is no difference.

A: First, for your "same effect", it depends on what do you apply to.
Because some elements by default have "cursor: pointer" property such as

anchor tag

While the following elements by default have "cursor: default"(no pointer)

input type: submit

Take stackoverflow.com "Post your answer" as an example, it is a submit button with "cursor:default" by default, user's perception might think a clickable object is displaying "pointer", so it is styled with "cursor:pointer"
As a quick conclusion with my experience, there is no best practice, but rather, depends on the purpose. For clickable object but it is not display as "pointer" by default, you may style them with "pointer".
When you disabled something, eg when you activate something then enable an anchor link, you may use something like
/* the a is only for illustrative purpose */
a.disabled{
   cursor: default;
}

a.enabled{
   cursor: pointer;
}

Because cursor is a matter of visual presentation, related to user experience design(UX).


text:
Q: basic auth on 2 different folders I have nginx installed, and I want to use the built-in auth-basic module to authenticate on 2 different folders. Each folder should have its own user & password lists.
For this i created 2 locations in the nginx config, and specified auth_basic_user_file for each of the defined locations.
Ex: /torrents/ is a proxy for a local install of transmission, and /admin/ is an administration interface developed by me.
The problem is that if i authenticate in one location it will log me out from the other location.

A: Using chromium and the following nginx configuration, I get a basic auth prompt the first time I visit each location, but after that, I can switch between them freely.
    location /torrents/ {
        auth_basic "transmission";
        auth_basic_user_file /tmp/transmission;
        alias /tmp/transmission/ ;
        autoindex on;
    }
    location /admin/ {
        auth_basic "administration";
        auth_basic_user_file /tmp/administration;
        alias /tmp/administration/ ;
        autoindex on;
    }

Note: tested on nginx/1.4.4


text:
Q: Is there a good place to learn how to compute limits rigorously? There's lots of statements involving limits in basic real analysis that I don't know how to justify properly. For example: $$\lim_{x \rightarrow \infty} e^{-x} = 0, \qquad \lim_{x \rightarrow \infty} xe^{-x} = 0$$
$$\lim_{x \rightarrow \infty}\frac{x^3+3x-1}{2x^3-5x^2} = \lim_{x \rightarrow \infty}\frac{x^3}{2x^3}$$
I don't actually know why these kinds of statements are true, I just have a vague sense that some functions are more "powerful" than others.
Further to this, I get the feeling that big-O notation is relevant here but I've never managed to learn that properly. Also it seems to throw away too much information; if $O(x^3) = O(2x^3)$, then computing the above limit by a big-O argument seems to be impossible.

Question. How does one learn this stuff properly?

A: A readable introduction is given in section 3.7: The Order of Magnitude of Functions in R.Courants Classic Introduction to Calculus and Analysis, Vol. 1.

There he proves following

*

*Theorem: If $a$ is an arbitrary number greater than one, then the qutient $\frac{a^x}{x}$ tends to infinity as $x$ increases.

He provides two different proofs explicitly indicating the importance of this theorem. From this theorem he derives the next two theorems:

*

*The exponential function becomes infinite of a higher order of magnitude than any power of $x$.

*The logarithm becomes infinite of a lower order of magnitude than any arbitrarily small positive power of $x$.

He continues:

On the basis of these results we can construct functions of an order of magnitude far higher than that of the exponention function and other functions of an order of magnitude far lower then that of the logarithm.
For example, the function $e^{\left(e^x\right)}$ is of a higher order than the exponential function, and the function $\log \log x$ is of a lower order than the logarithm; moreover we can iterate these processes as often as we like, piling up the symbols $e$ or $\log$ to any extent we please.

Together with the section 1.6 The Limit of a Sequence which covers some of your examples and the section 1.7 Further Discussion of the Concept of Limit you should have pretty much all the information you are looking for.
After reading this material the following statement in section 9.1. A Hierarchy from Concrete Mathematics by R.L. Graham, D.E. Knuth and O. Patashnik
might become  more and more familiar:

We formalize this by saying that
  \begin{align*}
  f \prec g\quad\Longleftrightarrow \quad \lim_{n\to\infty}\frac{f(n)}{g(n)}=0
  \end{align*}
  we have
  \begin{align*}
  1\prec \log\log n\prec \log n\prec n^{\varepsilon}\prec n^c\prec n^{\log n}\prec c^n\prec n^n\prec c^{c^{n}}
  \end{align*}
  Here $\varepsilon$ and $c$ are arbitrary constants with $0<\varepsilon <1<c$.

A:
How does one learn this stuff properly?

That is actually a fairly difficult and subjective question, because some learning methods work for some better than for others.
My personal opinion is not just reading a book about a certain topic, but doing the exercises, too. This may seem trivial to most readers, but I remember, as a beginner it's easy to think that "reading is enough". When you are able to prove most exercises in a book but a few, these may be worth looking up here on MSE, and asking them if no one else did.

Now, a part of me reads your above-cited question as

How does one learn this stuff rigorously?

Mizar is a proof assistant that can be used to let your proofs be verified by a computer, there you have to do it really rigorously and cannot mark something as "obvious", the checker would complain. You could learn Mizar and work with it to learn looking for the details, if that helps. The Mizar Mathematical Library already holds many theorems related to your topic where you could verify them in most detail, if wanted. The drawback is that it takes some time to learn Mizar and get used to it. The theory of Big Oh-Notation starts here. Results include $\mathcal O(\log_2 n)\subsetneq\mathcal O(\sqrt{n})$, $\mathcal O(n\log_2 n)\subsetneq \mathcal O(n^{1+\varepsilon})$, $\mathcal O(n^{\log_2 n})\subsetneq \mathcal O(n^\sqrt{n})$, $k\leq m \implies \mathcal O(n^k)\subsetneq\mathcal O(n^m)$, to name a few. My current research doesn't has so much to do with limits, so I'm afraid I can't provide a guide for the Mizar Mathematical Library in this regard (yet), but at least I could point you to where to start looking.

On a site note, regarding Big $\mathcal O$-Notation: it can be defined like this
$$g\in\mathcal O(f) :\iff \lim_{n\to\infty}\frac{f(n)}{g(n)}=c\in\mathbb R$$
So we get $g\prec f \iff g\in\mathcal O(f) \land f\notin\mathcal O(g)$, if you compare it the answer from Markus.


text:
Q: How can I stream a file to a server using Retrofit or alike? I can upload a file without any issues to my server using Retrofit's MultiPart annotation.
However, what I want is to stream a file which is still being written into disk to server. Is it possible using Retrofit?

A: Retrofit for multipart requests uses okhttp3.RequestBody. So you have to create your own RequestBody that generates data.
Here is example that was taken from OkHttp recipes (https://github.com/square/okhttp/wiki/Recipes#post-streaming)
public static final MediaType MEDIA_TYPE_MARKDOWN
  = MediaType.parse("text/x-markdown; charset=utf-8");

RequestBody requestBody = new RequestBody() {
  @Override public MediaType contentType() {
    return MEDIA_TYPE_MARKDOWN;
  }

  @Override public void writeTo(BufferedSink sink) throws IOException {
    sink.writeUtf8("Numbers\n");
    sink.writeUtf8("-------\n");
    for (int i = 2; i <= 997; i++) {
      sink.writeUtf8(String.format(" * %s = %s\n", i, factor(i)));
    }
  }

  private String factor(int n) {
    for (int i = 2; i < n; i++) {
      int x = n / i;
      if (x * i == n) return factor(x) + " × " + i;
    }
    return Integer.toString(n);
  }
};


text:
Q: No operations defined in spec! error on swagger UI I am working on to migrate the version of spring boot. I am using spring boot with jersey. After upgrade the version of spring boot and other dependencies, swagger is not working for me. I did not modified any configuration.
Dependencies in pom:
<parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.6.10</version>
    </parent>

<dependencyManagement>
        <dependencies>
            <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-dependencies</artifactId>
                <version>Finchley.SR1</version> <type>pom</type> <scope>import</scope> </dependency> -->
            <!-- Jersey -->
            <dependency>
                <groupId>org.glassfish.jersey</groupId>
                <artifactId>jersey-bom</artifactId>
                <version>${jersey.version}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>

<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jersey</artifactId>
        </dependency>

<dependency>
            <groupId>io.swagger</groupId>
            <artifactId>swagger-jersey2-jaxrs</artifactId>
            <version>1.6.6</version>
        </dependency>

Swagger configuration:
private void configureSwagger() {
        register(SwaggerSerializers.class);
        register(ApiListingResource.class);

        BeanConfig beanConfig = new BeanConfig();
        beanConfig.setTitle("API documentation");
        beanConfig.setVersion(api.name());
        beanConfig.setSchemes(new String[] {
                "https", "http"
        });
        beanConfig.setBasePath("/api" + api.getPath());

        // ConfigId and ScannerId must also be set as init parameters
        // during servlet configuration
        beanConfig.setConfigId(api.name());
        beanConfig.setScannerId(api.name());
        beanConfig.setUsePathBasedConfig(true);

        beanConfig.setResourcePackage("com.api.v1.priv.resources");
        beanConfig.setPrettyPrint(true);
        beanConfig.setScan(true);
    }

Changes in migration:
Spring boot version upgraded from 2.0.5.RELEASE => 2.6.10
swagger-jersey2-jaxrs upgraded from 1.5.18 => 1.6.6
Note - Swagger configuration was already existing. No changes has been done.
I am able to run the project successfully after migration. All api end points are working fine. But unfortunately swagger stopped working.
Swagger error:

I have gone through the lot of tutorials/blogs but not able to find the solution. Thanks everyone in advance.

A: In my case, it was due to conflict of org.reflections library. switched from 0.10 back to 0.9.12 fixed the issue.
Recommendation for migration:
Actually the problem was in technique of migration. We should not jump to latest version directly. We should continue version by version by considering the release notes. If you want to switch from spring 2.0.0 to 2.7.0, don't directly jump into it. Just move first 2.1.0..2.2.0.. etc. Clean and Build the project on each and every step of the migration.
Thanks!!!


text:
Q: Can't access my WordPress website after changing the domain name at domain/ WP-admin Basically, I was in charge of changing the domain of a WordPress site. While doing some testing, I ended up changing the domain in mydomain/wp-admin and now I'm getting the following error whenever I try to access the site:
enter image description here
Also, I can't access the wp-admin page either. Whenever I try it, I get the following error:
enter image description here
Since I have almost no experience with these tools (wordpress, docker, ubuntu), I don't know what to do. My goal is just to reverse this domain change and go back to the old.
To try to solve this problem I already tried some things:

*

*Inside the server, in home/ubuntu/site-docker/src, I already changed the wp-config.php file and added define( 'WP_SITEURL', 'http://mydomain' ) and define( 'WP_HOME', 'http://mydomain' );

*In home/ubuntu/site-docker/src/wp-content/themes, I already entered the folders of all themes (since I didn't remember which theme I was using) and changed the functions.php file, adding update_option('siteurl', 'https://mydomain') and update_option('home', 'https://mydomain');

In the end, nothing really worked.

A: First I can't reach links you sent. Did you replace your old website domain in your database with new domain address?


text:
Q: Switch JDK version in Windows 10 cmd Is there a way to change JDK version easily in cmd? like the version on mac.
 Change Default JDK on Mac.

A: I created scripts for every version of Java that I have installed on my PC, and use those whenever I need to change the Java version through the command line. Here is an example of one, should be self-explanatory really:
@echo off
echo Setting JAVA_HOME
set JAVA_HOME=C:\Program Files\Java\jdk-10
echo setting PATH
set PATH=C:\Program Files\Java\jdk-10\bin;%PATH%
echo Display java version
java -version

A: Here's my guide for Windows 10.
Step 1. Go to System Properties. Click on Environment Variables
Step 2. Add new variables, such as JAVA_8_HOME

*

*JAVA_8_HOME:%ProgramFiles%\Java\jdk1.8.0_152\bin

*JAVA_9_HOME:%ProgramFiles%\Java\jdk-9.0.1\bin

*JAVA_HOME:%JAVA_8_HOME%
In my case, JAVA_8_HOME(JDK8) is pointing to C:\Program Files\Java\jdk1.8.0_152\bin. You can replace this with your own path to javac. %JAVA_HOME% has a default value pointing to JAVA_8_HOME, which is the path for JDK8. That's my preference, feel free to adjust accordingly.
Step 3. Select PATH and click on Edit. PATH
Step 4. Click on New and add %JAVA_HOME%. %JAVA_HOME% will be added to PATH automatically every time you launch a command prompt.

In order to switch JDK version in cmd, here's the trick.
Step 5. I created a batch file with
@echo off
:: Switch JDK version
DOSKEY java8=SET PATH=%JAVA_8_HOME%;%PATH%;
DOSKEY java9=SET PATH=%JAVA_9_HOME%;%PATH%

Basically, it disables echo and creates two alias. In batch file any string after :: is the comments. Every time, java8 or java9 is called, it re-exports %PATH% with the new JDK path. Save it as profile.bat. You can name it whatever you want.
Step 6.
Search for regedit (Registry Editor). Click on Edit > New > String Value. Give AutoRun as the Value name and %USERPROFILE%\profile.bat as the Value data. Here, please put your actual path value to the profile.bat we just created. So, whenever a command prompt is opened, it automatically loads profile.bat, which creates those two alias in the script.
Step 7. Close any command prompt you're using or just open a new command prompt. This is because your changes will not affect opened cmd window. Environment changes only happens to new CMD.
Step 8. Verify your results here.
If you're using different Python versions, same trick applies, too. Find my python environment settings here.

A: Create a folder (in my case it is in C:\devenv) and create a batch file and name it after the version (jdk8.bat, jdk9.bat, jdk10.bat, jdk11.bat etc..) then add this commands. You just need to change the set JAVA_HOME to the location of the jdk version. Add the location of the batch files (C:devenv) to the path on the environment variables
@echo off
set JAVA_HOME=C:\Program Files\Java\jdk-11.0.9
set PATH=%JAVA_HOME%\bin;%PATH%
@echo Display Java Version
java -version

You can run it on cmd by just typing the batch name (e.g jdk11)

A: Found a single batch file to be a simpler solution. Adding batch file location path to system environmental variables will allow you to execute it from cmd.
Batch file (javaVer.bat):
@echo off
echo.

IF "%1" == ""       GOTO NoParams
IF "%1" == "8"      GOTO J8
IF "%1" == "11"     GOTO J11
IF "%1" == "latest" GOTO latest

IF "%1" == "-h"         GOTO help
IF "%1" == "--help"     GOTO help

:NoParams
    echo Enter Java version
    GOTO options

:help
    echo Usage: javaVer [java version]
    GOTO options

:: available java versions
:options
    echo options: 8, 11, latest.
    GOTO exit

:: java 8
:J8
    set JAVA_HOME=C:\Program Files\Java\jdk8u282-b08
    GOTO activate

:: java 11
:J11
    set JAVA_HOME=C:\Program Files\Java\jdk-11.0.10+9
    GOTO activate

:: latest java version
:latest
    set JAVA_HOME=C:\Program Files\Java\jdk-15.0.2+7
    GOTO activate

:: activates the selected java version
:activate
    set Path=%JAVA_HOME%\bin;%Path%
    echo Java %1 activated.
    GOTO exit

:: prints java version
:exit
    echo.
    echo Current Java version:
    java -version

Usage: javaVer [java version]
exp: javaVer 8

A: In "System Properties" window, click "Environment Variables…" and select PATH by click on Edit, then "New" and type ;%JAVA_HOME%\bin
It will write the JAVA_HOME defined. Just to edit one time.
And after you define JAVA_HOME by the cmd commande : set JAVA_HOME = path_of_jdk_or_jre whenever you want.

A: I been doing this by replacing JAVA_HOME variable in Environment variables - System Properties only.
Login as admin user if you are a domain user.
Edit Environment variables -> Advanced -> System Variables -> NEW:
a) Add multiple entries for JAVA_HOME as below:-
 JAVA_HOME (in my case, its version 11 is by default),
 JAVA_HOME_6 (for version 6),
 JAVA_HOME_7 (for version 7),
 JAVA_HOME_8 (for version 8)

b) now edit Path under same System variables and add NEW path for java as below. Remove any existing java path entries.

Suppose I need to change java version to 8, then i change the key value of JAVA_HOME.
i.e, JAVA_HOME renamed to JAVA_HOME_11
and JAVA_HOME_8 renames to JAVA_HOME
You need to close existing CMD and open new CMD to verify this change.
I admit its still a GUI solution only
If some appliations are still not taking new java path set, then you need to check java configuration in start up
c) Click Configure Java App in windows start up. Here you can enable required path via checkbox. This elminates path issues.

Thanks

A: Since I use powershell for day to day tasks, here is a function I added to my profile available for usage.  I just have two specific versions.
function JavaSetVersion([string] $v)
{
  $jre8 = 'C:\Program Files\Eclipse Adoptium\jre-8.0.322.6-hotspot'
  $jdk8 = 'C:\Program Files\Eclipse Adoptium\jdk-8.0.322.6-hotspot'
  $jdk11 = 'C:\Program Files\Eclipse Adoptium\jdk-11.0.14.101-hotspot'
  $jdk17 = 'C:\Program Files\Eclipse Adoptium\jdk-17.0.2.8-hotspot'
  $arrToConcatToPath

  # I *think* 8 requires both JRE & JDK
  if ($v -eq '8')
  {
    [System.Environment]::SetEnvironmentVariable('JAVA_HOME', $jdk8, [System.EnvironmentVariableTarget]::User)
    $arrToConcatToPath = "$jre8\bin","$jdk8\bin"
  }
  elseif ($v -eq '11') {
    [System.Environment]::SetEnvironmentVariable('JAVA_HOME', $jdk11, [System.EnvironmentVariableTarget]::User)
    $arrToConcatToPath = "$jdk11\bin"
  }
  elseif ($v -eq '17') {
    [System.Environment]::SetEnvironmentVariable('JAVA_HOME', $jdk17, [System.EnvironmentVariableTarget]::User)
    $arrToConcatToPath = "$jdk17\bin"
  }
  else
  {
    Write-Host 'Unsupported version'
  }

  # Add to path while not continually growing path
  $newPath = [Environment]::GetEnvironmentVariable('PATH', [System.EnvironmentVariableTarget]::User) -split ";" | Where-Object {$_ -notlike '*Eclipse Adoptium*'} | Where-Object {$_ -ne ''}
  # Add appropriate version back to array
  $newPath += $arrToConcatToPath
  # Join array and reset path
  [System.Environment]::SetEnvironmentVariable('PATH', $($newPath -join ";"), [System.EnvironmentVariableTarget]::User)
}

Usage:
JavaSetVersion '11'


text:
Q: For Loop not printing correctly just practicing doing some c++ exercises.
In my code I do not understand why my for loop is not printing the array from highest to lowest. It just prints 0.
int main()
{
    int num[2];
    int* ptr = num;

    cin >> *ptr;
    cin >> *(ptr + 1);

    for (int i = 1; i <= 2; i- -)
        cout << *(ptr + i) << endl;
}

A: Is this correct from what I tried to understand?
for(int i=1; i<=2; i--)
cout << *(ptr+i);
Variable i will decrement past 0 to negative -
Then it will keep decrement and testing? -1<=2 , -2<=-2, -3<=2 , making the loop never ending?

A: printing the array from highest to lowest.
You did it almost correctly, except the loop condition. You should iterate indexes from the highest to the lowest, 1, then 0. In other words, starting from the index 1, decreasing the index until 0, and exit the loop if index violates the condition.
for (int i = 1; i >= 0; i--)
    cout << *(ptr + i) << endl;


text:
Q: Does a Silverlight 3 out of browser (OOB) application support Bing Maps or Virtual Earth Maps? Is it possible to use any Microsoft Map component / control to integrate a map in a Silverlight 3 out of browser (only) application?

A: Microsoft has the Bing Maps Silverlight Control that allows you to implement Bing Maps within a Silverlight application. And, yes you can use this control in a Silverlight 3 "out of browser" application.
Here's a "Getting Started" tutorial on using the control:
http://pietschsoft.com/post/2009/03/Getting-Started-Virtual-Earth-Silverlight-Map-Control-SDK-CTP.aspx
One thing to note is that the current release of the Bing Maps Silverlight Control (at the time of posting this) is a CTP (Community Tech Preview) and can not be used in a production application. Microsoft is moving forward with Silverlight and Bing Maps, so I suspect that there will be a "Final" release sometime in the future; however, Microsoft has yet to announce when it will be available.

A: The Silverlight Bing Maps control is now 1.0 and can be used in production applications.
Bing Maps Silverlight Control


text:
Q: IE8 div width float:right issue for responsive site I have a div, #cont3, containing another div, div.banner. #cont3 has a background image. div.banner is just a white floating div with text in it. It works everywhere but IE8 - of course. This is what it's meant to look like:

This is what it does in IE8:

The div doesn't float and is super-skinny. Here's the relevant html (div.container is directly within body tags):

Contact us

Blah blah

And the CSS:
html {
  box-sizing: border-box;
  font-family: "Noto serif", serif;
  color: dimgray;
  font-weight: 100;
  height: 100%;
width: 100%;
}

*, *:before, *:after {
  box-sizing: border-box;
}

body {
    margin: 0;
    padding: 0;
    height: 100%;
    font-size: 100%;
width: 100%;
}

h1 {
    font-size: 55px;
    font-size: 3.2em;
    font-size: 350%;
    font-size: 4.5vw;
    color:  #C9494D;
    font-family: "Noto serif", serif;
    font-weight: 100;
    text-align: left;
    margin-left: 3%;

}

p {
    display: block;
    clear: both;
    float: left;
    text-align: left;
    margin-bottom: 10px;

}

div.container {
    display: block;
    float: left;
    width: 100%;
    height: 100%;

}

div#cont3 {
    display: block;
    float: left;
    width: 100%;
    height: 100%;
    background-image: url("images/london_1920.jpg");
    background-size: cover;
    -ms-behavior: url('backgroundsize.htc');
    background-repeat: no-repeat;
    position: relative;
}

div#cont3 div.banner {
    display: block;
    float: right;
    font-size: 12px;
    font-size: 70%;
    font-size: 1.1vmax;
    width: 90%;
    max-width: 60%;
/*  height: 80%; */
    margin-right: 5%;
    margin-top: 5%;
    background-color: white;
    background-color: rgba(255,255,255,0.9);
    padding-bottom: 20px;

}

I've been fiddling with height, and adding dimensions to the parent container, as per other questions on this forum. I've also been trying to tackle the oversized headings but no joy. IE8 stubbornly makes them too big!
Can anyone spot what I've done wrong?
Thanks

A: add this in your  and see if it works


text:
Q: How to use hitTestPoint correctly AS3 Hey everyone so I am just trying to understand this function and how to use it properly. I have read a good amount of information on it, with such methods being holding points of the object that you are using for the hitTestPoint in an array etc...
But I know there has to be an easier way correct?
I have my code setup like this so far but I don't get any trace:
private function checkPlayerHitBottom():void
    {

        if (_Player.hitTestPoint(bottom.x, bottom.y, true))
        {
            trace("hit");
        }
    }

So the _Player is a ship Movie Clip and the bottom is the obstacle that is a square but I extrude this square up so it looks like a hill. Now I can't use the hitTestObject because trying to do it with a hill the boundary box would mess everything up since the sides of the hill are lower and the highest point of the hill is where the boundary box will make its outline if you understand what I am saying.
So how can I use the hitTestPoint to check the whole outline of the bottom or its exact pixels I guess you can say.


text:
Q: How do i turn underscrore to find the model in ruby on rails Ok i have this in what i have
user.rb  //user model
OPTION = ['none', 'all', 'partial']
ANOTHER = ['true', 'false', 'neither']
YET_ANOTHER = ['something', 'another']

application_helper.rb
 def my_method(information, name)
   #this is where i need help
   User::OPTIONS

index.html.erb
my_method('information', :option)
my_method('information', :another)
my_method('information', :yet_another)

How do i in the my_method view helper grab the correct array so for example if i send in
my_method('information', :another)

in the my_method view helper i should execute
   User::ANOTHER

I was thinking i could upcase but how to i execute this ....
I tried this below
User::name.upcase
NoMethodError: undefined method `name' for #<Class:0x000d001078cd9c8>

A: You just need to do the following.
User.const_get(name.to_s.upcase)

While this works, make sure you aren't passing user-submitted params into const_get. This would be a security vulnerability, allowing user to essentially execute unintended code. Instead you should simply use a condition.
info = case params[:something]
when 'foo'; User::FOO
when 'bar'; User::BAR
end


text:
Q: applying StringFormat to DateTime column of WPF 4.0 DataGrid I need to apply a StringFormat to DateTime Column of a DataGrid (WPF4.0) at run time. I have used the column template to create a column of a data grid. The value of format is set at run time by applying setting in the application.
Any one knows that how we can apply StringFormat to DateTime Colum(Column Template) at run time.
I am waiting for positive response from side.
Thanks & Regards,
Deepak


text:
Q: How to solve No parameterless constructor defined for this object error in Mvc? I am creating one demo application to learn how to use repository pattern  for performing Insert operation.I am using Nop Commerce**(http://www.nopcommerce.com) **code for repository pattern
Error:No parameterless constructor defined for this object
I have seen this link:MVC: No parameterless constructor defined for this object
This is my Structure:
My Repository interface:
public partial interface IRepository<T>
    {
        void Insert(T entity);
     }

My Service Layer:
 public partial interface IEmployeeService
    {
        void InsertCategory(EmployeeMaster employeeMaster);
    }

My Class which will implement that interface(service):
public partial class EmployeeService : IEmployeeService
    {
        #region Fields
        private readonly IRepository<EmployeeMaster> _employeeMasterRepository;
        #endregion

        #region Ctor
        public EmployeeService
            (
            IRepository<EmployeeMaster> employeeMasterRepository
            )
         {
             this._employeeMasterRepository = employeeMasterRepository;
         }

        #endregion

public virtual void InsertCategory(EmployeeMaster employeeMaster)
        {
            if (employeeMaster == null)
                throw new ArgumentNullException("employeeMaster");

            _employeeMasterRepository.Insert(employeeMaster);
}

This is my controller:
public class HomeController : Controller
    {
        #region Fields
        private readonly IEmployeeService  _employeeService;
        #endregion

 #region Constructors
        public HomeController
        (
            IEmployeeService employeeService
        )
        {
            this._employeeService = employeeService;
        }
        #endregion

Getting Error:No parameterless constructor defined for this object
I have studied regarding this error and all the sources are saying that use Dependency injection to solve this error.
Can anybody guide me how to use dependency injection to solve this error??

A: Maybe you're taking as a sample a project that is too complex for you at this moment. Nopcommerce is a big and full featured product that has a lot of elements, so it easy to get lost. Not the best sample to learn how the repository pattern works, but I certainly recommend you to check it again once you have the basic concepts clear to see them used in a real scenario.
NopCommerce uses Autofac for dependency injection, a very popular IoC container. You can look for a class called DependencyRegistrar in the project Nop.Web.Framework to see how it is used, if you're curious about it. You can get more examples on how to use dependency injection with Autofac in their repository and their getting started guide.
My recommendation is to look for an easier to follow example. For starters, any of the popular IoC containers will be OK until you have your own criteria to choose one. For instance you can follow the Autofac's guide for MVC

A: You're correct - you'll need to use something like Unity, Ninject or Autofac to get this running.
Essentially - the steps are roughly the same regardless of the tech used.
Using unity as an example:
1) In your MVC project, use NuGet to add "Unity Bootstrapper for MVC". (right click references, manage nuget packages, search for unity online, select "Unity Bootstrapper for MVC"
This will add a few things to your project - the most interesting is the unityConfig.cs in App_start.
2) In unityConfig.cs - find RegisterTypes method
RegisterTypes is where you tell the unity container "when you need one of X, use implementation Y" - in your case "when you need an IEmployeeService, use EmployeeService"
3) In register types - add your type mappings - for example, in your case:
container.RegisterType<IEmployeeService, EmployeeService>();

AND
4)  Bit more complicated: as you have IRepository and you need this to resolve your employeeService correctly you'll also have to register a generic type against a generic implementation (it's a little odd).  Looking at your types, it's going to be something like:
container.RegisterType(typeof(IRepository<>), typeof(Repository<>));
(You'll need to resolve the namespaces according to your projects).
So - what this is saying is...

Right MVC - when you need an IEmployeeService use employeeService, and
  when you need an IRepository<>, use Repository<>

Now - because of the webActivator that was added during the NuGet installation (right next door to UnityConfig.cs), that should be it - the webActivator sets the DependencyResolver.Current to something that uses this unityContainer.
Beacause of this, MVC will now use this new unityContainer whenever it tries to instantiate your controllers, resolving the type mappings on the way.
The webActivator and unityConfig classes do alot of the heavy-lifting for you, just elaborate registerTypes and you should at least have a foot-hold in the solution.
HTH - good luck.
PS - DI itself is a massive subject - far too much for here, you'll bump into all sort of weird and wonderful things (supplying Ctor args for resolutions, lifetime management just for a start!) - it's fun, but not trivial, so you'll have to excuse me if this doesn't work "out of the box" (it's almost impractical to think it would) - this is merely just a vague attempt to give you a foothold in the subject!
For more info on unity - I suggest you read up here (Dev guide to using Unity on MSDN)


text:
Q: How combine min and max with date I want my code combine the date like (Format is 2/4/19) but I em using min  in TimeIn I don't know how to solve this (this is the example that I want to display 2/4/19 8:00)
Select  A.EmpID [X_TMSHT_EMPID],
        A.[RecordDate] [X_TMSHT_APPLY],
        CONCAT(A.[RecordDate], (MIN(IIF(ISNULL(CHARINDEX('I', A.[Entries], 0), -1) > 0, SUBSTRING(A.[Entries], LEN(A.[Entries]) - 5, 5), NULL)))) AS [X_TMSHT_TIMEIN]
FROM Employees  [B]
inner JOIN [DTR Upload] [A] ON B.EmployeeNo = A.EmpID
where B.LastName + ','+B.FirstName + ','+ B.MiddleName LIKE 'CRUZ,MA. KIMBERLY,CASTILLO%'
GROUP by B.LastName, B.FirstName, B.MiddleName,A.EmpID, A.[recordDate]
order by A.[recordDate] asc, B.LastName + ','+B.FirstName + ','+ B.MiddleName asc

this is my result
..X_TMSHT_EMPID.......||..X_TMSHT_APPLY..............||......X_TMSHT_TIMEIN........
001693............... ||    2019-05-03 00:00:00.000..||May  3 2019 12:00AM12:08

but I want is
..X_TMSHT_EMPID.......||..X_TMSHT_APPLY..............||......X_TMSHT_TIMEIN........
001693............... ||    2019-05-03 00:00:00.000..||05/03/2019  12:00:00


text:
Q: react-router-dom - how to use query params as path? I'm currently got an issue with URL including query params hitting the 404 error page. I need the query params due to this URL is a redirect from a 3rd Party application.
My router switch:
export default function App() {
    return (
        <React.Suspense fallback={Loading...}>
            <Router>
                <ReactNotification />

                <React.StrictMode>
                    <Switch>
                        <Route exact path="/" component={Home} />

                        {singleRouting.map((route, i) => (
                            <RouteWithSubRoutes key={i} {...route} />
                        ))}

                        <Route path="*">
                            <Error />
                        </Route>
                    </Switch>
                </React.StrictMode>
            </Router>
        </React.Suspense>
    );
}

const RouteWithSubRoutes = (route) => {
    return (
        <Route
            exact={route.exact || undefined}
            path={route.path}
            render={(props) => (
                // pass the sub-routes down to keep nesting
                <route.component {...props} />
            )}
        />
    );
}

My routes:
import FinanceBody from '../main/finance/FinanceBody';

const singleRouting = [{
    path: "/finance?:applicationId&:status&:supplierOrderReference",
    exact: true,
    component: FinanceBody
}];

export { singleRouting };

A: After continuous trail and error, I found that the answer was very basic.
Previous path:
path: "/finance?:applicationId&:status&:supplierOrderReference"

Updated path:
path: "/finance"

You can access the query params as normal within location.search


text:
Q: Set custom properties for  for filtering? I have an array of agm-markers displayed on an agm-map like this:

<agm-map [latitude]="mapCenterLatitude" [longitude]="mapCenterLongitude" [zoom]="getMapZoom()" [mapTypeId]="'hybrid'">
    <agm-marker-cluster maxZoom="13" imagePath="https://raw.githubusercontent.com/googlemaps/v3-utility-library/master/markerclustererplus/images/m">
        <agm-marker *ngFor="let marker of markers" [latitude]="marker.latitude" [longitude]="marker.longitude" [iconUrl]="marker.iconUrl">
            <agm-info-window>

{{marker.title}}

                Details
            </agm-info-window>
        </agm-marker>
    </agm-marker-cluster>
</agm-map>

Now I want to be able to filter them by a category. Clicking a category-checkbox should make all markers invisible, which don't belong to that category.
How can I add this category to the marker? Is there a way to add custom properties (which is possible in the pure Google Maps API)?

A: I think you could just add a new property to your marker object. You have an array of markers, those objects have the properties latitude, longitude, iconURL...
You can add new properties to those markers:
for (let marker of markers) {
    marker.customProperty = 'my value'
}
And afterwards filter them in your html template. You can do this using the filter function for example or creating another array that you can filter in your TypeScript file. I'll go with the first option:
<agm-map [latitude]="mapCenterLatitude" [longitude]="mapCenterLongitude" [zoom]="getMapZoom()" [mapTypeId]="'hybrid'">
    <agm-marker-cluster maxZoom="13" imagePath="https://raw.githubusercontent.com/googlemaps/v3-utility-library/master/markerclustererplus/images/m">
        <agm-marker *ngFor="let marker of markers.filter(item => item.customProperty === 'desiredProperty)" [latitude]="marker.latitude" [longitude]="marker.longitude" [iconUrl]="marker.iconUrl">
            <agm-info-window>

{{marker.title}}

                Details
            </agm-info-window>
        </agm-marker>
    </agm-marker-cluster>
</agm-map>

And that would do.
P.D.
If you cannot create a custom property because you are explicitly using the agm-marker class, you can either not define the type of the markers array (set it to any) or create your custom class that extends the agm-marker class.
Hope this will help!

A: As zolastro pointed out, you can simply add properties to marker. Then I made an condition on the [visible] property of the marker to make it invisible if filters do not match.

<agm-map [latitude]="mapCenterLatitude" [longitude]="mapCenterLongitude" [zoom]="getMapZoom()" [mapTypeId]="'hybrid'">
    <agm-marker-cluster maxZoom="13" imagePath="https://raw.githubusercontent.com/googlemaps/v3-utility-library/master/markerclustererplus/images/m">
        <agm-marker *ngFor="let marker of markers"
          [latitude]="marker.latitude"
          [longitude]="marker.longitude"
          [iconUrl]="marker.iconUrl"
          [visible]="marker.category == 'categoryA'">
            <agm-info-window>

{{marker.title}}

                Details
            </agm-info-window>
        </agm-marker>
    </agm-marker-cluster>
</agm-map>


text:
Q: how to run a hive query on multiple dir's with multiple files I want to run a count hive query on multiple directories which have multiple files in them. Path to files looks like this
'2011/01/01/file20110101_01.csv
 2011/01/01/file20110101_02.csv
 2011/01/02/file20110201_01.csv
 2011/01/02/file20110201_02.csv'

and so on.
I created an external table with following partition
 'create external table table1(col1,col2...)
  partitioned by (year string,month string)
  STORED AS TEXTFILE'

and tried to add partition just till the month.
'ALTER TABLE partition_test_production1 ADD PARTITION(year='2011', month='01')
LOCATION 'blob path/2011/01/*/file201101*.csv';'

Tried this query
'select count(1) from table1 where year='2011' AND month='01';'

But the count is showing as zero. Any suggestions on how to do this?

A: You don't have to add all of the files individually, but you do have to add all of the bottom-level directories individually. When you add a directory, Hive reads all files in that directory, but not any files in sub-directories. For example:
create external table table1(col1,col2...)
partitioned by (year string, month string, day string)
STORED AS TEXTFILE

ALTER TABLE table1 ADD PARTITION(year='2011', month='01', day='01')
LOCATION 'hdfs:///path/2011/01/01/';

ALTER TABLE table1 ADD PARTITION(year='2011', month='01', day='02')
LOCATION 'hdfs:///path/2011/01/02/';

etc

Usually you would have a bash script or something do this. Loop over all the directories in hdfs and generate the hive statement to add that partition. I'm not a bash expert, but as an example:
hadoop fs -ls hdfs:///path/*/* | while read line; do
  year="$(echo "$line" | awk -F/ '{print $(NF-2)}')"
  month="$(echo "$line" | awk -F/ '{print $(NF-1)}')"
  day="$(echo "$line" | awk -F/ '{print $(NF)}')"
  hive -e "alter table table1 add partition(year='$year', month='$month', day='$day') location 'hdfs:///path/$year/$month/$day'"
done

There seems to be some old jira tickets about having table/partition locations be more flexible, but they're all unresolved.

A: You don't really need to create partitions manually. If you have created an external table and data resides in this directories, you can run the msck repair table table_name and it will automatically load all the partitions.


text:
Q: Azure Maps SDK popup does not open after initial load I am using Azure Maps SDK in a Blazor Server app which uses JavaScript interop. The map works well and renders perfectly.
On initial load of the map component the popup displays correctly when clicking a pin on the map. However, when the data source changes via an API call datasource.importDataFromUrl(organisationDataFeed); it correctly brings back the filtered data, but when I click on one of the pins again the popup does not display. The click event handler (for the pin) is being called, but the popup does not open.
(function () {

    var map, datasource, popup;

    // Global export
    window.azuremaps = {
        initMap: function (organisationDataFeed) {
            // Create an instance of the map control and set some options.

            map = new atlas.Map('map', {
                // center: [-97, 39],

                // center: [18.424095, -33.925000],
                center: [26.157981, -29.083937],
                zoom: 4,
                pitch: 50,
                style: 'night',
                view: 'Auto',

                // Add your Azure Maps subscription key to the map SDK. Get an Azure Maps key at https://azure.com/maps
                authOptions: {
                    authType: 'subscriptionKey',
                    subscriptionKey: ''
                }
            });

            map.controls.add([
                new atlas.control.ZoomControl(),
                new atlas.control.CompassControl(),
                new atlas.control.PitchControl(),
                new atlas.control.StyleControl()
            ], {
                position: "top-right"
            });

            // Wait until the map resources are ready.
            map.events.add('ready', function () {

                // Create a data source and add it to the map.
                datasource = new atlas.source.DataSource(null, {
                    //Tell the data source to cluster point data.
                    cluster: true,

                    //The radius in pixels to cluster points together.
                    clusterRadius: 45,

                    // The maximium zoom level in which clustering occurs.
                    // If you zoom in more than this, all points are rendered as symbols.
                    clusterMaxZoom: 15
                });
                map.sources.add(datasource);

                //Create a bubble layer for rendering clustered data points.
                var clusterBubbleLayer = new atlas.layer.BubbleLayer(datasource, null, {
                    //Scale the size of the clustered bubble based on the number of points inthe cluster.
                    radius: [
                        'step',
                        ['get', 'point_count'],
                        20,         //Default of 20 pixel radius.
                        100, 30,    //If point_count >= 100, radius is 30 pixels.
                        750, 40     //If point_count >= 750, radius is 40 pixels.
                    ],

                    //Change the color of the cluster based on the value on the point_cluster property of the cluster.
                    color: [
                        'step',
                        ['get', 'point_count'],
                        'rgba(0,255,0,0.8)',            //Default to green.
                        100, 'rgba(255,255,0,0.8)',     //If the point_count >= 100, color is yellow.
                        750, 'rgba(255,0,0,0.8)'        //If the point_count >= 100, color is red.
                    ],
                    strokeWidth: 0,
                    filter: ['has', 'point_count'] //Only rendered data points which have a point_count property, which clusters do.
                });

                //Add a click event to the layer so we can zoom in when a user clicks a cluster.
                map.events.add('click', clusterBubbleLayer, clusterClicked);

                //Add mouse events to change the mouse cursor when hovering over a cluster.
                map.events.add('mouseenter', clusterBubbleLayer, function () {
                    map.getCanvasContainer().style.cursor = 'pointer';
                });

                map.events.add('mouseleave', clusterBubbleLayer, function () {
                    map.getCanvasContainer().style.cursor = 'grab';
                });

                // Create a layer to render the individual locations.
                var individualSymbolLayer = new atlas.layer.SymbolLayer(datasource, null, {
                    filter: ['!', ['has', 'point_count']], //Filter out clustered points from this layer.

                    textOptions: {
                        textField: ['get', 'name'],
                        color: "#FFFFFF",
                        offset: [0, -2.2]
                    },
                });

                map.events.add('click', individualSymbolLayer, symbolClicked);

                //Add the clusterBubbleLayer and two additional layers to the map.
                map.layers.add([
                    clusterBubbleLayer,

                    // Create a symbol layer to render the count of locations in a cluster.
                    new atlas.layer.SymbolLayer(datasource, null, {
                        iconOptions: {
                            image: 'none' //Hide the icon image.
                        },
                        textOptions: {
                            textField: ['get', 'point_count_abbreviated'],
                            offset: [0, 0.4]
                        }
                    }),

                    individualSymbolLayer

                ]);

                // Create a popup but leave it closed so we can update it and display it later.
                popup = new atlas.Popup({
                    pixelOffset: [0, -18],
                    closeButton: true
                });

                // Retrieve a GeoJSON data set and add it to the data source.
                datasource.importDataFromUrl(organisationDataFeed);
            });
        },
    };

    function clusterClicked(e) {
        if (e && e.shapes && e.shapes.length > 0 && e.shapes[0].properties.cluster) {
            // Get the clustered point from the event.
            var cluster = e.shapes[0];

            // Get the cluster expansion zoom level. This is the zoom level at which the cluster starts to break apart.
            datasource.getClusterExpansionZoom(cluster.properties.cluster_id).then(function (zoom) {

                //Update the map camera to be centered over the cluster.
                map.setCamera({
                    center: cluster.geometry.coordinates,
                    zoom: zoom + 2,
                    type: 'ease',
                    duration: 200
                });
            });
        }
    }

    function symbolClicked(e) {
        // Make sure the event occured on a point feature.

        var popupTemplate = '

{name}

{description}

Contact: {contact}

Web: {website}

';

        if (e.shapes && e.shapes.length > 0) {
            var content, coordinate;

            // Check to see if the first value in the shapes array is a Point Shape.
            if (e.shapes[0] instanceof atlas.Shape && e.shapes[0].getType() === 'Point') {
                var properties = e.shapes[0].getProperties();
                content = popupTemplate.replace(/{name}/g, properties.name).replace(/{description}/g, properties.description).replace(/{contact}/g, properties.contact).replace(/{website}/g, properties.website);
                coordinate = e.shapes[0].getCoordinates();
            }
            else if (e.shapes[0].type === 'Feature' && e.shapes[0].geometry.type === 'Point') {

                // Check to see if the feature is a cluster.
                if (e.shapes[0].properties.cluster) {
                    content = '
Cluster of ' + e.shapes[0].properties.point_count + ' symbols
';
                } else {
                    // Feature is likely from a VectorTileSource.
                    content = popupTemplate.replace(/{name}/g, properties.name).replace(/{description}/g, properties.description).replace(/{contact}/g, properties.contact).replace(/{website}/g, properties.website);
                }

                coordinate = e.shapes[0].geometry.coordinates;
            }

            if (content && coordinate) {
                // Populate the popupTemplate with data from the clicked point feature.

                console.log("JB content");
                console.log(content);

                console.log("JB coordinate");
                console.log(coordinate);

                popup.setOptions({
                    //Update the content of the popup.
                    content: content,

                    //Update the position of the popup with the symbols coordinate.
                    position: coordinate
                });

                console.log("JB: logging map variable");
                console.log(map);

                popup.open(map);
            }
        }
    }

})();

content and coordinate are populated with values and evaluate to true, the options are correctly set, but just the last line: popup.open(map); does not work if the data source changes bringing back new data into the map. It works perfectly on initial load.
Any ideas what I could do to get this working? Thanks

A: A couple of things to try:

*

*Double check the values of coordinate and content. The coordinates should be an array with [longitude,latitude] numbers (make sure they aren't string values of numbers). The content should either be a DOMElement (i.e. div), or a string. If it is anything else, it may not display anything.

*Double check the "map" variable is a map the second time around. If the reference is lost for some reason, that function won't work.

*It looks like you are create a new popup all the time. Often apps only want to display a single popup at a time. In that case it is more efficient to create a single popup and reuse it as shown in this example: https://azuremapscodesamples.azurewebsites.net/index.html?sample=Reusing%20Popup%20with%20Multiple%20Pins


text:
Q: MongoDB track which user mande changes We're running a microservice architecture with multiple systems having access to shared collections in a MongoDB (yes, questionable design, but we're in the transition to get out of this.)
We're trying to find a way to track which change within the oplog was done by which "user"/service (each microservice is using different credentials) actually made this change. If we find any invalid changes in our DB this would make it super easy to find out which system is bugging out.
Any ideas?
The only ones I came up with so far would always have to change client side code, which I would like to avoid.

A: If you can maintain a column editors such that every operation would have an { $addToSet: { editors: { by: userId, at: new Date() } } }, then the corresponding oplog entries would have this information that you can cross-check with your access control list.
Note: you might have to change inserts to upserts, or account for another case: .insert({ ..., editors: [{ by: userId, at: new Date() }] })


text:
Q: Coordinates of every node in a binary tree? I have the following function for calculating coordinates for every node in a binary tree.
//x & y parameters should be untouched
//root assumed to be 0,0
function nodeCoordinates(node, x, y)
{

    if (x === undefined && y === undefined ) {x = 0; y = 0;}
    if (!node) {return;}

    console.log("Node: " + node.value + " x: " + x + " y: " + y);
    nodeCoordinates(node.left, --x, --y);
    nodeCoordinates(node.right, x+=2, y--);

}

Node and Tree(BST):
//Nodes for BST
function Node(val) {
    this.value = val;
    this.left = null;
    this.right = null;
}

//Binary Search Tree
function BST() {

    this.root = null;

}

For x, it should decrement if it goes left.  increment if it goes right.
For y, it should decrement as it goes down a level.
Example test code and output:
my_BST.insert(50);
my_BST.insert(60);
my_BST.insert(55);
my_BST.insert(20);
my_BST.insert(70);
my_BST.insert(80);
my_BST.insert(10);
my_BST.insert(30);
my_BST.insert(65);
nodeCoordinates(my_BST.root);

*

*Node: 50 x: 0 y: 0

*Node: 20 x: -1 y: -1

*Node: 10 x: -2 y: -2

*Node: 30 x: 0 y: -2

*Node: 60 x: 1 y: -1

*Node: 55 x: 0 y: -2

*Node: 70 x: 2 y: -2

*Node: 65 x: 1 y: -3

*Node: 80 x: 3 y: -3

The output is correct but this was the result of fiddling with how the parameters are passed in with recursion and it feels unintuitive.  Can someone help me clarify what's going on?  Is there a more intuitive way to go about this?

A: I would change the parameter handling, without using assignment or increment operators.
function nodeCoordinates(node, x, y) {
    x = x || 0;
    y = y || 0;
    if (!node) {
        return;
    }
    console.log("Node: " + node.value + " x: " + x + " y: " + y);
    nodeCoordinates(node.left, x - 1, y - 1);
    nodeCoordinates(node.right, x + 1, y - 1);
}

Basically y is the level of the tree, with goes below zero.
x is misleading, because nodes can have the same "coordinates", like

Node: 30 x: 0 y: -2
Node: 55 x: 0 y: -2


text:
Q: Swift Dictionary.reduce() - different number of iterations reported using full vs. short syntax I'm trying to get the hang of Swift, and am looking to understand why the following two method calls on a Dictionary, though they produce the same output, are reported as undergoing a different number of iterations by the Swift Playground.
var chocolates = ["Ram's Bladder Cup": 1, "Spring Surprise": 2, "Crunchy Frog": 3]

let chocolatesString = chocolates.reduce("", combine: {$0 + "\($1.0), "})
// The Playground says (4 times)

let newerChocolatesString = chocolates.reduce("") { (var sum: String, keyValue: (String, Int)) -> String in
return sum + "\(keyValue.0), "
// The Playground says (3 times)

print(chocolatesString)
print(newerChocolatesString)
// The output from both is however identical and as expected...

I'd be very grateful to understand this - I can see obviously that there is no difference in the result, but I would like to understand why the Playground reports a difference.

A: Playgrounds use the "n times" notation whenever a line of code is "visited" more than once during execution. This happens in lieu of showing a result because a line that has executed more than once — or a line that has executed more than one statement — can have more than one result.
When the closure body is on its own line, the playground reports that said line executed 3 times. When the closure body is in the same line as the reduce call to which it's passed, it says "4 times" because that line of code was "visited" 4 times during execution — once for the reduce call itself, and three more times for the closure body.
Note this happens regardless of which closure syntax you use — it's entirely a matter of where you put line breaks.
chocolates.reduce("", combine: {
    $0 + "\($1.0), "  // (3 times)
})

chocolates.reduce("") { (var sum: String, keyValue: (String, Int)) -> String in
    return sum + "\(keyValue.0), "  // (3 times)
}

chocolates.reduce("", combine: {$0 + "\($1.0), "})
// (4 times)

chocolates.reduce("") { (var sum: String, keyValue: (String, Int)) -> String in return sum + "\(keyValue.0), "}
// (4 times)

I don't have Xcode in front of me, but IIRC you'll see this even when you put multiple statements on one line with ;. It has nothing to do with closure syntax and everything to do with line breaks vs statements:
let a = 1 // 1
let b = a + 1 // 2

let a = 1; let b = a + 1 // (2 times)

A: var chocolates = ["Ram's Bladder Cup": 1, "Spring Surprise": 2, "Crunchy Frog": 3]

let chocolatesString = chocolates.reduce("", combine: {
    $0 + "\($1.0), "        // (3 times)
})
let newerChocolatesString = chocolates.reduce("") { (var sum: String, keyValue: (String, Int)) -> String in
    return sum + "\(keyValue.0), "
    // The Playground says (3 times)
}

    print(chocolatesString)
    print(newerChocolatesString)
// The output from both is however identical and as expected...

.. the number doesn't reflect number of iterations, it reflects number of expression evaluation


text:
Q: Separating grid cells from an image and cropping them I've been trying to take a weekly menu pdf and separate it into grid boxes for cropping and later OCR each with TesseractOCR.
I've seen lineJunctions which might be helpful here, but wasn't able to find them in imagemagick php documentation. I've also seen Hough Lines in a similar stackoverflow question, but again wasn't able to find them in the php documentation.
//read the image
$im = new Imagick();
$im->readimage('menu.png');

//resize and contrast
$im->resizeImage($im->getImageWidth()/6, $im->getImageHeight()/6 , 9, 1);
$im->thresholdImage( 0.65 * Imagick::getQuantum() );;

//remove "noise"
//this is done by creating two new images where only horizontal lines, then vertical are preserved using morphology and then combined into one
$horizontalLines = clone $im;
$verticalLines = clone $im;

$horizontalLineKernel = \ImagickKernel::fromBuiltIn(\Imagick::KERNEL_RECTANGLE, "19x1");
$horizontalLines->morphology(\Imagick::MORPHOLOGY_CLOSE, 1, $horizontalLineKernel);

$verticalLineKernel = \ImagickKernel::fromBuiltIn(\Imagick::KERNEL_RECTANGLE, "1x15");
$verticalLines->morphology(\Imagick::MORPHOLOGY_CLOSE, 1, $verticalLineKernel);

$horizontalLines->compositeimage($verticalLines, 5, 0, 0);

$im = clone $horizontal;

$horizontalLines->clear();
$horizontalLines->destroy();
$verticalLines->clear();
$verticalLines->destroy();

// Create boxes at corners
// These are at points from which I intent to create the individual grid boxes
$plusKernel = \ImagickKernel::fromBuiltIn(\Imagick::KERNEL_PLUS, "4");
$im->morphology(\Imagick::MORPHOLOGY_OPEN, 1, $plusKernel);

$squareKernel = \ImagickKernel::fromBuiltIn(\Imagick::KERNEL_SQUARE, "2");
$im->morphology(\Imagick::MORPHOLOGY_CLOSE, 1, $squareKernel);

By doing this I end up with a image with boxes which if I can get a x,y,width and height, I should be able to get the coordinates, however it misses the bottom right corner and is very messy. I'm sure there has to be a better approach.
The image is downscaled and then I'm planning to upscale the coordinates by 6 as seen at $im->resizeImage(). Is there a better way I should go about this?

A: One way to do this (assuming the lines are horizontal and vertical) in ImageMagick is to scale to one row and to one column, threshold, and filter txt: output for black pixels.
xlist=`convert cells.png -scale x1! -auto-level -threshold 27% -negate -morphology Thinning:-1 Skeleton -negate txt:- | grep "black" | cut -d, -f1`
echo "$xlist"
38
109
180
251
322
394
465
536

ylist=`convert cells.png -scale 1x! -auto-level -threshold 27% -negate -morphology Thinning:-1 Skeleton -negate txt:- | grep "black" | cut -d: -f1 | cut -d, -f2`
echo "$ylist"
45
141
256
381

The combination of all x values and all y values gives you the array of intersections.
xArr=($xlist)
yArr=($ylist)
numx=${#xArr[*]}
numy=${#yArr[*]}
pointlist=""
for ((j=0; j<numy; j++)); do
for ((i=0; i<numx; i++)); do
pointlist="$pointlist ${xArr[$i]},${yArr[$j]}"
done
done
echo "pointlist=$pointlist"
pointlist= 38,45 109,45 180,45 251,45 322,45 394,45 465,45 536,45 38,141 109,141 180,141 251,141 322,141 394,141 465,141 536,141 38,256 109,256 180,256 251,256 322,256 394,256 465,256 536,256 38,381 109,381 180,381 251,381 322,381 394,381 465,381 536,381

You can visualize by:
convert cells.png -scale x1! -scale 550x50! -auto-level -threshold 27% tmp1.png

convert cells.png -scale 1x! -scale 50x425! -auto-level -threshold 27% tmp2.png

Without the thinning, the top horizontal line is thicker than one pixel.


text:
Q: Site content being cut off I want the height of the page to be unlimited if the content requires this. Can anyone help me here. Here is the page with content being cut off at the bottom and the bottom of the div not showing:
http://comparetranslations.com/index.php?page=4&authorini=p
Here is a page showing the bottom of the div:
http://comparetranslations.com/index.php?page=4&authorini=l

A: Just change:
.page4authorwork {
   position: relative;
and add
.main {
   height: auto;

A: I hope, that's what you're looking for: min-height, to set the minimum height of a div.
Example:
<div style="min-height: 100px;">
... your content ....
</div>

A: I see a closing head on line 9,  but your head opening tag is on 317.
Looks like you could clean up your head element, and maybe your body element will build as it should.
it's failing in the html validation. http://validator.w3.org/


text:
Q: Passing the value from a checked radio button into a python GET function for evaluation I am trying to pass the value of the selected (checked) radio button into a GET function I later want to evaluate in Python that is used to display an alert.
If I include .checked in my variable definition nothing is passed, without it, only the first element is passed.
I am guessing my problem is either in the variable definition
let genera = document.querySelector("#myform input[type='radio']");

or
in the passing of the argument to the GET function.
$.get('/test?genera=' + genera.value,

I appreciate the advise.
Thanks in advance
Here is a part of my code
index.html
<div class="form-group">
        <input autocomplete="off" class="form-control" id="genera" name="genera" placeholder="Genera" type="text">
    </div>
    <input type="submit" id="submit" name="submit" value="Play" class="btn btn-primary">
</form>
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<script>

    let genera = document.querySelector("#myform input[type='radio']");

    document.querySelector("#submit").onclick = function() {
            $.get('/test?genera=' + genera.value, function(data) {
            if (data==true){
                    alert($("#myform input[type='radio']:checked").val()+" is correct");
                    return true;
                }
            else{
                    alert($("#myform input[type='radio']:checked").val()+ " is wrong answer, better luck next time!");
                    return true;
                }
            })
    };
</script>

applycation.py file
from flask import jsonify

selection = request.args.get("genera")

cont = db.execute("SELECT * FROM contributions WHERE id_contribution = :id_contribution AND genera= :genera",
                  id_contribution=active,
                  genera=selection)
if len(cont) != 0:
    return jsonify(True)

else:
    return jsonify(False)

Solved by directly referencing the checked radio button in the get function arguments
$.get('/test?genera=' + $("#myform input[type='radio']:checked").val(), function(data) {

Still do not know why it did not take it as a variabe


text:
Q: difference between maximumFramesPerSlice , inNumberFrames and buffer duration I am confused on these three concepts
I am working on audio project on ios eventhough I am newbee on objective c and c.
I am trying to get realtime fft of the audio data .
During the process I have come to the point where I am very confused on these three concepts.
-maximumFramesPerSlice,
-inNumberFrames variable on rendering function
-preferred I/O hardware buffer duration which is set on AVAudioSession
I set buffer duration to 100 ms. while I expect InNumberFrames to come 4410 samples/frames on 44.1khz sampling rate, it always brings 470-471 frames on each render(callback) . while I am confused on both of these, now another variable comes out. maximumFramesPerSlice ?
it's default value is 4096.
in coreAudio glossary it says
"slice: The number of frames requested and processed during one rendering cycle of an audio unit"
so why it comes 470 frames in each render.
I will be very thankful for any help

A: Buffer duration in iOS is only a preferred duration.  The OS may try to use a value close to this configured preference, but is free to use a different duration (based on the current device hardware capabilities, the state of the device, other running audio apps, and the OS version, etc.), and even change this duration while the app is running (such as increasing it when the display "locks").
So iNumberOfFrames divided by the sample rate is the actual duration of the audio data rendered in the current callback.  This duration can change between successive callbacks.  The OS chooses this duration, not the app.  The app only suggests a preference.
If the actual buffer size is greater than maximumFramesPerSlice, the Audio Unit will return an error, so maximumFramesPerSlice is best left at 4096 to prevent your app from crashing when the display is locked and/or other things happen involving the OS outside your app.
470 to 471 samples per frame suggests that the actual hardware ADC chip is running at 48000 sps and DMAing buffers of 512 samples to the processor, which the OS is resampling to 470.x samples at 44100 before handing the result to your app.


text:
Q: New to Angular JS - Not working I am trying to execute a very simple program to return addition of 2 numbers.
<!DOCTYPE html>

<meta charset="ISO-8859-1">
<title>Insert title here</title>

First Name: <input type="number" ng-model="firstName">

Last Name: <input type="number" ng-model="lastName">

Full Name: {{firstName + lastName}}

This code is working in one of the tutorial site, but when I try to run in my machine, it displays {{firstName + lastName}}. Do I need to download any specific jar or lib before coding angular?

A: myApp module is not defined in your code. You need to define or just remove it.

<!DOCTYPE html>

  <meta charset="ISO-8859-1">
  <title>Insert title here</title>

  First Name:
  <input type="number" ng-model="firstName">

Last Name:
  <input type="number" ng-model="lastName">

Full Name: {{firstName + lastName}}

or define module using angular.module('myApp', []);

var myAppModule = angular.module('myApp', []);
<!DOCTYPE html>

  <meta charset="ISO-8859-1">
  <title>Insert title here</title>

  First Name:
  <input type="number" ng-model="firstName">

Last Name:
  <input type="number" ng-model="lastName">

Full Name: {{firstName + lastName}}

A: You have two options here:
First, remove myApp:

Second, include the file that has myApp defined inside:

and your myApp should look something like this:
var myApp = angular.module('myApp', [function()...])

A: Pranav C Balan's answer is correct but I would like to add that the inputs should be set to type="text".
<input type="number" ng-model="firstName">

should be:
<input type="text" ng-model="firstName">

Or you won't see results if you type in letters into the number input.


text:
Q: iPhone app crash when post images in progress and interrupt by phone call In my application, when I add image in the image view and start posting images on the server in a synchronous way, at that time if I receive any call then my application is crash with following Logs :
2012-12-14 11:13:19 +0000 Test_Phone_Call URL : https://app.factorlab.com/mvc/media
2012-12-14 11:13:19 +0000 Test_Phone_Call Response Message : HTTP/1.1 200 OK
2012-12-14 11:13:24 +0000 Test_Phone_Call URL : https://app.factorlab.com/mvc/media
2012-12-14 11:13:24 +0000 Test_Phone_Call Response Message : HTTP/1.1 200 OK
2012-12-14 11:13:28 +0000 Test_Phone_Call URL : https://app.factorlab.com/mvc/media
2012-12-14 11:13:28 +0000 Test_Phone_Call Response Message : HTTP/1.1 200 OK
2012-12-14 11:13:32 +0000 Test_Phone_Call URL : https://app.factorlab.com/mvc/media
2012-12-14 11:13:38 +0000 backboardd Forcing crash report of Test_Phone_Call[4610]...
2012-12-14 11:13:38 +0000 backboardd com.factorlab.grow.stage failed to resume in time
2012-12-14 11:13:39 +0000 backboardd Application'UIKitApplication:com.factorlab.grow.stage[0xe310]' exited abnormally with signal 9: Killed: 9
2012-12-14 11:13:39 +0000 backboardd Finished crash reporting.

Can we fix this crash or there is no way to fix it. I am testing on iPhone 4 with iOS 6.0.1

A: If you make network requests on the main thread you are guaranteed to run into these kinds of problems. You should move your network requests to a background thread or else do them asynchronously.


text:
Q: Test POST request on PlayFramework 2.4.x Good morning,
I'm trying to test some POST requests on my controllers.
I have no problems with GET request :
@Test
public void testGetAll() {
    TestModel test = new TestModel();
    test.done = true;
    test.name = "Pierre";
    test.save();

    TestModel test2 = new TestModel();
    test2.done = true;
    test2.name = "Paul";
    test2.save();

    Result result = new controllers.ressources.TestRessource().get(null);
    assertEquals(200, result.status());
    assertEquals("text/plain", result.contentType());
    assertEquals("utf-8", result.charset());
    assertTrue(contentAsString(result).contains("Pierre"));
    assertTrue(contentAsString(result).contains("Paul"));
}

But when I have to test a POST request, i can't give POST params to the controller.
here is the method I want to test :
public Result post() {
    Map<String, String> params =     RequestUtils.convertRequestForJsonDecode(request().queryString());

    T model = Json.fromJson(Json.toJson(params), genericType);
    model.save();

    reponse.setData(model);
    return ok(Json.prettyPrint(Json.toJson(reponse)));
}

I've try several solutions, but I can't find a proper one :

*

*Try to use FakeRequest

*Try to Mock the Http.Request object

So, what is the best way to write tests for my controllers ?
I'm using Play Framework 2.4.6 with Java.
Junit 4 and Mockito.

A: For tests of an POST action I use the RequestBuilder and the play.test.Helpers.route method.
For one with JSON data it could look like this (I use Jackson's ObjectMapper for marshaling):
public class MyTests {

  protected Application application;

  @Before
  public void startApp() throws Exception {
    ClassLoader classLoader = FakeApplication.class.getClassLoader();
    application = new GuiceApplicationBuilder().in(classLoader)
            .in(Mode.TEST).build();
    Helpers.start(application);
  }

  @Test
  public void myPostActionTest() throws Exception {

    JsonNode jsonNode = (new ObjectMapper()).readTree("{ \"someName\": \"sameValue\" }");
    RequestBuilder request = new RequestBuilder().method("POST")
            .bodyJson(jsonNode)
            .uri(controllers.routes.MyController.myAction().url());
    Result result = route(request);

    assertThat(result.status()).isEqualTo(OK);
  }

  @After
  public void stopApp() throws Exception {
    Helpers.stop(application);
  }
}


text:
Q: Nested Touchables in React Native I experience a problem, where double-touches (to simultaneous touches) within nested Touchables arrive at the parent Touchable instead.
In the example below, Touchables are nested three layers deep. When I press the deepest touchable (coloured blue), the console correctly prints "blue". It also behaves correctly when I press the other layers printing "green" and "red" respectively.
The weird behaviour arises when I do something with two simultaneous touches and release - then the touched layer's onPress does not get called at all. Instead the parent Touchable receives just a single touch when both touches are over.
Furthermore when i perform two simultaneous touches on the outermost layer (red with no parent touchable)- that layer will receive the touch. That seems more correct from my perspective, but deviates from the weird behaviour within the nested Tocuables described above.
<View style={{flex:1, backgroundColor:"#666666"}}>

    <TouchableHighlight onPress={()=>{console.log("red")}}>
      <View style={{backgroundColor:"#FF0000", height:300}}>
        <TouchableHighlight onPress={()=>{console.log("green")}}>
          <View style={{backgroundColor:"#00FF00", height:200}}>
            <TouchableHighlight onPress={()=>{console.log("blue")}}>
              <View style={{backgroundColor:"#0000FF", height:100}} />
            </TouchableHighlight>
          </View>
        </TouchableHighlight>
      </View>
    </TouchableHighlight>
</View>

A: I copied your code and I'm a bit clueless whether it actually looks like something you're trying to achieve: https://snack.expo.io/@zvona/onpressin
Snack doesn't allow using multiple touches, but I make a long shot: use onPressIn instead of onPress.


text:
Q: Route with PHP F3 matching an "http://..." adress I am working with PHP F3. I have some issues with their routing engine.
Let say my website is www.test.com, I would like to have a special handler when I enter this url : www.test.com/https://www.google.com/
I want to get the "https://www.google.com/" part and store it in a database.
For now I have this route:
GET /*=Page->myHandler
which is not working when there are :, ., ?, etc symbols
My guess is to rewrite a special routing function for this case but how to bypass the existing one ?

A: Yeah it's directly working against how the regex for the routing engine is parsing things in the Base->run() method. If I were to make a recommendation I would put your endpoint as something like myapp.com/incoming-url?url=[the url encoded URL you want to save in the database] If it's not URL encoded, even the browser will have a tough time figuring out what you want to do.


text:
Q: Where is the Wrapper Assembly Key File setting in VS 2008? I'm trying to build an application that is strongly named.  It is referencing a COM interop library that I add via the Add References dialog.  It's been a while, but I seem to recall that in older versions of visual studio, there was a project setting for Wrapper Assembly Key File.  I can't seem to find it in Visual Studio 2008?

A: I came across your post looking for the same thing, but found a different route on my own to get around the issue of strong naming a COM Interop referenced assembly.
You can sign the imported type library assembly with the key file before you reference it in Visual Studio by using the /keyfile:<key.snk> parameter:
tlbimp MyCOMService.tlb /out:Interop.MyCOMService.dll /keyfile:MyKeyFile.snk