text:
Q: Как вырезать определенные ссылки из текста? Есть некий список разрешенных ссылок, если они есть то нужно их найти и сделать активными, если ссылки нет в списке то нужно удалить ее. Пошаманил тут немного, вот что вышло
$text = 'привет, моя ссылка http://ya.ru, google.ru ну и www.site.org/page.php?id=133.';
$links = file('link.txt');

$regex = "/((http:\/\/|https:\/\/)?([a-z0-9\-\.]+)?[a-z0-9\-]+(!?\.[a-z]{2,4}))/";
preg_match_all($regex, $text, $text_link);

for ($i = 0; $i < count($text_link[0]); $i++) {
    for ($a = 0; $a < count($links); $a++) {

        if (trim($text_link[0][$i]) == trim($links[$a])) {

            $text = preg_replace('/(http:\/\/|https:\/\/)?' . trim($links[$a]) . '/',
                '' . $links[$a] . '', $text);
        } else {

            $text = preg_replace('/(http:\/\/|https:\/\/)?' . trim($links[$a]) . '/',
                '[error]', $text);
        }
    }
}

echo $text;

работает оно не правильно, заменяет не так как нужно, помогите справиться с проблемой
A: Попробуйте заменить:
$regex = "@(https?://)?(([a-z0-9.-]+)?[a-z0-9-]+(!?\.[a-z]{2,4}))@";

И подумайте на тему использовать preg_ replace _callback
$links = array(
        'ya.ru'         => "",
        'yandex.ru'     => "",
        'google.ru'     => "",
        'google.com'    => "",
);

function replace_link( $matches ) {
        global $links;

        if (isset($matches[2]) and !empty($matches[2])) {
                if (isset($links[$matches[2]])) {
                        $rc = '';
                        $rc .= $matches[2];
                        if (isset($matches[3])) {
                                $rc .= $matches[3];
                        }
                        $rc .= '';

                        $matches[0] = $rc;
                }
                else {
                        $matches[0] = "[error]";
                }
        }
        return $matches[0];
}

$text = 'привет, моя ссылка http://ya.ru, google.ru ну и www.site.org/page.php?id=133.';
$regex = "@(https?://)?([a-z0-9.-]{3,})(/[^\s]*)?@";

echo "Before:\n", $text, "\n";
$text = preg_replace_callback( $regex, 'replace_link', $text );
echo "After:\n", $text, "\n";


text:
Q: How to mix/fix IComparable and IComparable mess I have a helper function, which basically calls CompareTo on two objects, but does some special corner case checking, converting, etc.
Originally I wrote the function as such:
public static bool BetterCompare(IComparable lhs, IComparable rhs, out retCode)
{
    ...
    retCode = lhs.CompareTo(rhs);
    ...
}

But the problem is that if I have a class AwesomeClass : IComparable<AwesomeClass>. In fact I have several as some older IComparable classes have gone IComparable<T>. Yet the compiler gets angry because it can't convert these new objects to IComparable. I don't know if this makes it worse, but some of them are abstract (though the abstract class does provide an implementation).
How can I convey "I want two objects that I can call CompareTo on" and not have the compiler give me any lip. Preferably, the new function should NOT look like BetterCompare<AwesomeClass>(this, that, out retCode);,  but just "do the right thing". Or is there a better way to do this without touching every class making them both IComparable and IComparable<T>?

A: You can either make AwesomeClass implement the nongeneric IComparable interface as well as IComparable<T>, or you can write a generic BetterCompare method:
public static bool BetterCompare<T>(T lhs, T rhs, out retCode)
    where T : IComparable<T>
{
    ...
    retCode = lhs.CompareTo(rhs);
    ...
}

(Note that this can live alongside your existing method.)

A: You could always change the variables to an object type and then use reflection to see if they  implement one of the interfaces and then cast them to the correct interface.
NOTE: Reflection is crazy slow, so use it with caution.

A: You could have a look at Comparer<T>, that implements both IComparer<T> and IComparer, and use that in the appropriate places. It may require some refactoring of your code though.

A: The documentation says:
The object returned by the Default property uses the System.Collections.Generic.IComparable<T> generic interface to compare two objects. If type T does not implement the IComparable<T> generic interface, the Default property returns a Comparer<T> that uses the System.Collections.IComparable interface.

redpajama_set_name: RedPajamaStackExchange


text:
Q: DNS_PROBE_FINISHED_NOINTERNET About 2 weeks ago I decided to move to Ubuntu instead of Windows 10.
After that problems in network appeared, suddenly the web page show 'DNS_PROBE_STARTED'
then it changes to 'DNS_PROBE_FINISHED_NOINTERNET'.
This problem happened most of the time when I first open the laptop (It happened suddenly sometimes), especially when the network that I connect to on the startup is different from the one that I was connected to before I close my laptop.
Restarting my laptop solves the problem.
The problem is not in the router since it appears on every router I tried, and it's not on the browser only (I've tested it in terminal).
Also I tried restarting the network manager but it does not help.
Does anyone know what I should do?
#Edit:
I tried to ping my router and it fails.

A: First, you should make sure you are in fact connected to a network, and that your computer is getting an ip. Press CTRL + ALT + T to open a terminal, and then type ping . Common router ips are 10.0.0.1, 192.168.0.1, and 192.168.1.1 If it outputs lots of messages starting with "64 bytes from", then you are connected. If it gives a message that starts with "Request timeout for", than you aren't connected to a network, and you may want to look at your DHCP settings, or look up common problems when connecting ubuntu to the internet.
If you are connected to a network, than you most likely have a DNS configuration problem. In your terminal, type sudo nano /etc/resolv.conf and enter your password. Note that you won't be able to see your password as you type it. After you can see the file, you will want to modify a few things. Look for lines that start with nameserver. If there are lines that start with nameserver, delete them. Once there are none, add these two to the bottom of the file: nameserver 8.8.8.8  and nameserver 8.8.4.4 Then press CTRL + X, then y, and then enter. Then type this command: sudo service network-manager restart That should fix your problem if it was a dns issue.
If this doesn't solve it, you may want to look up how to clear firewall rules in linux.


text:
Q: Need help in simplifying this $y=\frac{\sqrt[3]{\sqrt{7}i-3}+\sqrt[3]{-\sqrt{7}i-3}}{2\sqrt[3]{2^2}}$ Need help in simplifying this:$$y=\frac{\sqrt[3]{\sqrt{7}i-3}+\sqrt[3]{-\sqrt{7}i-3}}{2\sqrt[3]{2^2}}$$
This has real and imaginary parts, at first glance, but after a numerical evaluation in mathematica, $y$ is effectively real, as shown by:
$$y=0.692184 + 0. i\Rightarrow y=0.692184 $$
But I have no idea how to simplify this.

A: Note that every complex number $z=x+iy$ can be written as $z=re^{i\varphi}$. Also, $e^{i\varphi}=\cos\varphi+i\sin\varphi$.
Thus, with $z=-3+i\sqrt{7}$ we can write:
$$y=\frac{\sqrt[3]{\sqrt{7}i-3}+\sqrt[3]{-\sqrt{7}i-3}}{2\sqrt[3]{2^2}}\\
= \frac{1}{2\sqrt[3]{2^2}}\left(z^{\frac{1}{3}}+\left(z^*\right)^{\frac{1}{3}}\right)\\
= \frac{1}{2\sqrt[3]{2^2}}\left(r^{\frac{1}{3}}e^{i\frac{\varphi}{3}}+r^{\frac{1}{3}}e^{-i\frac{\varphi}{3}}\right)\\
=\frac{r^{\frac{1}{3}}}{2\sqrt[3]{2^2}}\left(\cos\left(\frac{\varphi}{3}\right)+i\sin\left(\frac{\varphi}{3}\right)+\cos\left(\frac{\varphi}{3}\right)-i\sin\left(\frac{\varphi}{3}\right)\right)\\
=\frac{r^{\frac{1}{3}}}{\sqrt[3]{2^2}}\cos\left(\frac{\varphi}{3}\right)\in\mathbb{R}$$


text:
Q: Exit from Command prompt after running r script I am running one R script through command prompt (CMD window) but CMD window staying open after executing all batch command. I want to close it (CMD window) after executing R Script.
@ECHO OFF
START cmd.exe /k "cd C:\ABCD\" & Rscript working.r & exit

I am running above code for it but last commands exit doesn't work for me.
Did I miss something on the above code?

A: 1. Meaning of the Windows command processor option /k
The Windows command processor option /K is for running a command line and then keeps running the Windows command processor cmd.exe for interactive use by a user or just seeing the output of the executed command line.
The option /C is for running a command line and then the Windows command processor closes itself which means the console window with the output is closed too.
That is explained by the usage help of cmd.exe which can be read by opening a command prompt and running cmd /?. There is also the Microsoft documentation page for cmd explaining these two options.
2. Meaning of the Windows command processor operator &
There is single line with multiple commands using Windows batch file explaining in full details the unconditional command operator & as well as the conditional command operators && and || on being recognized by the Windows command processor outside a double quoted argument string.
The unconditional command operator & is for specifying multiple commands on one command line to execute one after the other by cmd.exe independent on success or failure of the previous executed command.
So the command line
START cmd.exe /k "cd C:\ABCD\" & Rscript working.r & exit

is interpreted by cmd.exe processing the batch file as it would be written in the batch file:
START cmd.exe /k "cd C:\ABCD\"
Rscript working.r
exit

The goal of the batch file is to change the current directory to C:\ABCD\, run Rscript.exe with the argument working.r to process this R script in the directory C:\ABCD\ and keep the console window opened for viewing the output while the console window opened on starting the batch file should be closed automatically after starting Rscript.exe. But the used command line does something completely different as explained in full details in chapter 5 below.
3. Solutions to run R script working.r in C:\ABCD
The goal to run R script working.r in directory C:\ABCD with keeping the console window opened with the output of the R script could be achieved with:
@echo off
title Run R script working.r
cd /D "C:\ABCD\"
if not errorlevel 1 Rscript.exe working.r
pause

These command lines do following:

*

*The CMD internal command ECHO is used to turn off command echo mode which is enabled by default on execution of a batch file resulting in displaying a command line to execute after parsing and processing it immediately before execution.
@ at beginning of this line results in not printing this first command line of the batch file to the console window after processing and before executing it.

*The CMD internal command CD changes the current directory for the running Windows command process to the specified directory with using option /D to change also the current drive if that is necessary too.
That works for all directory paths with a drive letter and a colon at the beginning, but not for a UNC path starting with \\ServerName\ShareName\ because of cmd.exe does not permit by default making a directory accessed with a UNC path the current directory for compatibility with executables not supporting such a directory path as current directory.

*If the execution of command CD was successful indicated with exit value 0, the Windows command processor searches for a file with name Rscript.exe in current directory and next in the directories listed in environment variable PATH using the file extensions listed in environment variable PATHEXT and if that file is really found, runs Rscript.exe using its fully qualified file name (drive + path + name + extension) with passing working.r as argument to the executable.
The search for Rscript.exe and its execution is not done on CD exits with value 1 indicating an error, for example if the directory C:\ABCD was deleted in the meantime. CD outputs in this case an error message to handle STDERR (standard error) which can be seen in the console window.

*The command PAUSE halts processing of the batch file until the user presses any key so that all output written to the console window can be viewed by the user even on having started the execution of the batch file by double clicking on it in Windows File Explorer.

For understanding the used commands and how they work, open a command prompt window, execute there the following commands, and read entirely all help pages displayed for each command very carefully.

*

*cd /?

*echo /?

*if /?

*pause /?

*title /?
See also:

*

*How does the Windows Command Interpreter (CMD.EXE) parse scripts?

*Single line with multiple commands using Windows batch file

*What is the reason for "X is not recognized as an internal or external command, operable program or batch file"?
There are also multiple other solutions possible.
A shorter version of above:
@echo off
title Run R script working.r
cd /D "C:\ABCD\" && Rscript.exe working.r
pause

Another single line solution starting one more command processor:
@start "Run R script working.r" /D "C:\ABCD" %ComSpec% /D /K Rscript.exe working.r

This single command line results in

*

*starting the Windows command processor cmd.exe using its fully qualified file name as defined by the system environment variable ComSpec

*with option /D to ignore the AutoRun command in Windows registry if existing at all and

*with option /K as explained in chapter 1

*as separate task in a new console window with the window title Run R script working.r and

*with C:\ABCD as current directory for the started cmd.exe which has to

*search for file Rscript.exe and if found execute it with R script file name working.r as first and only argument with current directory C:\ABCD as defined for cmd.exe.

For help on command START run in a command prompt window start /?.
One more single line solution is:
@start "Run R script working.r" /D "C:\ABCD" %SystemRoot%\System32\cmd.exe /D /K Rscript.exe working.r

This is the same as the single command line version above with just the small difference that %SystemRoot%\System32\cmd.exe is used instead of %ComSpec% which in fact is defined by default with exactly that string as system environment variable.
Last but definitely not least can be used also the single command line:
@start "Run R script working.r" %SystemRoot%\System32\cmd.exe /D /S /K "cd /D "C:\ABCD" && Rscript.exe working.r"

This solution becomes a nightmare if the directory path of file working.r contains itself the character & as in this case the ampersand in directory path must be escaped with ^ left to & as the command line is processed by two cmd.exe. The cmd.exe instance processing the batch file has to interpret all ampersands on the command line as literal characters while & in directory path has to be interpreted as literal character and && as conditional AND operator by the second cmd.exe.
Example of last solution with & in directory path:
@start "Run R script working.r" %SystemRoot%\System32\cmd.exe /D /S /K "cd /D "C:\Temp\Development ^& Test" && Rscript.exe working.r"

That is much more complex than:
@start "Run R script working.r" /D "C:\Temp\Development & Test" %SystemRoot%\System32\cmd.exe /D /K Rscript.exe working.r

4. Alternative solution not using a batch file at all
The execution of an executable like Rscript.exe with one or more arguments in a specific directory used as current directory with using the Windows command processor to see the output can be done also using a Windows .lnk shortcut file instead of a batch file which has multiple advantages in comparison to the batch file solution.
The shortcut file for executing Rscript.exe with working.r as argument in directory C:\ABCD can be created using the following steps:

*

*Browse in Windows File Explorer to the directory System32 in the Windows directory containing cmd.exe which is usually C:\Windows\System32.

*Click with secondary (right) pointing device (mouse) button on the file cmd.exe to open the context menu and click in submenu Send to on the menu item Desktop (create shortcut).

*Switch to the Windows desktop which has now an additional shortcut file with name cmd.exe.lnk whereby the file extension .lnk is not visible, just the file name cmd.exe.

*Click with secondary (right) pointing device (mouse) button on cmd.exe and click in opened context menu on menu item Rename to change the file name for example  to Run R Script resulting in shortcut file being rename to Run R Script.lnk.

*Click with secondary (right) pointing device (mouse) button on Run R Script and click in opened context menu on last menu item Properties.

*There is opened the Properties dialog window with by default selected tab Shortcut. On this tab must be modified first the property Target on which to append a space character and the string /D /K Rscript.exe working.r. Well, even better would be appending after a space the string /D /K "C:\Full Path\Rscript\Rscript.exe" working.r so that cmd.exe does not need to search for file Rscript.exe with using the environment variables PATH and PATHEXT.

*There must be next modified the property Start in where C:\ABCD must be entered as this is the directory which should be the current directory on starting first cmd.exe and next Rscript.exe because of containing the R script file working.r. The Start in directory path should be defined always without double quotes even on containing a space or one of these characters &()[]{}^=;!'+,`~ as this string is not processed by the started cmd.exe as explained below in chapter 5.

There can be modified also other properties of the shortcut file. There can be defined a Shortcut key like Ctrl + Alt + R to able to execute the R script working.r in C:\ABCD by pressing this combination of keys independent on which application has currently the input focus. There can be added a Comment like Run R script working.r in C:\ABCD displayed as tooltip when the pointing device pointer is positioned over the shortcut on Windows desktop. A nice icon can be selected for this shortcut and a different font or font size can be set, etc.
The last step is clicking on button OK to save the changed shortcut properties.
The shortcut file can be kept on Windows desktop, but could be moved or copied also into the Windows start menu or pinned on the Windows taskbar as it can be done with any shortcut file.
So with usage of a shortcut file the execution of the R script can be simplified, especially on having a shortcut key defined too. The font and font size can be changed to see output larger than usually in a command prompt window. A nice icon could be selected displayed in the Windows taskbar while the R script is running, etc.
5. How is the batch file processed as posted in the question?
The batch file as posted in the question is most likely executed by double clicking on it. For that reason explorer.exe is most likely the first executable processing the batch file.
5.1 Processing of the batch file by explorer.exe
A batch file with file extension .bat or .cmd is a text file and does not contain itself CPU instructions. Therefore the Windows File Explorer has to find out first what to do with the double clicked batch file. So it searches in the Windows registry under various keys how to open a file with file extension .bat or .cmd depending on which file extension the batch file has.

*

*The Windows File Explorer finds the key HKEY_CLASSES_ROOT\.bat with the default string batfile of type REG_SZ.

*There is next looked for registry key HKEY_CLASSES_ROOT\batfile\shell\open\command with the default string "%1" %* of type REG_SZ.
Batch files are registered different to other file extensions. There is usually configured for the Windows shell command open of a file extension the fully qualified file name of the executable to use with %1 as placeholder for the fully qualified name of the double clicked file enclosed in double quotes.
Example for .txt file extension: HKEY_CLASSES_ROOT\.txt has the default string txtfile and referencing therefore HKEY_CLASSES_ROOT\txtfile\shell\open\command with the default string %SystemRoot%\system32\notepad.exe %1 of type REG_EXPAND_SZ instead of REG_SZ as containing an environment variable reference.

The above sequence of registry accesses is extremely simplified as otherwise it would be really too long to list all registry accesses made by explorer.exe to find out what to do with the double clicked batch file.
There is called finally by explorer.exe the Windows library function CreateProcess. This function has multiple parameters and it is really worth for any programmer working on Windows to read the documentation of this function and of the structure STARTUPINFO.
Most of the properties of a shortcut file just define how CreateProcess is called by explorer.exe with which data set in the structure STARTUPINFO.
Most of the options supported by the CMD internal command START just define the data to pass to CreateProcess by cmd.exe.
Some examples:

*

*Function parameter lpCurrentDirectory is a long pointer to a string with the current directory to set for the process to create. If this pointer is a null pointer, CreateProcess uses the current directory of the process which creates the new process. Otherwise the specified string is interpreted as path of the current directory for the new process. The shortcut property Start in is the string passed by explorer.exe using lpCurrentDirectory to function CreateProcess. The string after option /D of command START of CMD is the string passed without the double quotes by cmd.exe using lpCurrentDirectory to function CreateProcess.

*The structure STARTUPINFO has the element dwFlags which is a bitfield with one bit being STARTF_USESHOWWINDOW. cmd.exe runs a Windows console application like Rscript.exe specified in a batch file by default using CreateProcess with this bit in dwFlags in STARTUPINFO passed with a pointer to CreateProcess with the value 0. So no new console window is opened on running Rscript.exe. But on using command START the flag STARTF_USESHOWWINDOW has always the value 1 on CreateProcess being called by cmd.exe to run the application always with a new window. explorer.exe sets always STARTF_USESHOWWINDOW.

*The structure STARTUPINFO has the elements hStdInput, hStdOutput and hStdError which are defined by cmd.exe depending on a console application like Rscript should use the standard input, standard output and standard error streams of cmd.exe or new streams should be created by CreateProcess for this application which is one more difference between running Rscript.exe directly from within a batch file or using the command START.

Every Windows executable capable of running one more Windows executable calls CreateProcss in the Windows kernel library kernel32.dll. So it is really useful for every Windows programmer to have knowledge about this function, which data can be passed to it and how it works.
So finally explorer.exe uses CreateProcess to run, for example:
C:\Windows\System32\cmd.exe /c ""C:\Users\UserName\Desktop\RunRscript.bat" "

A new console window is opened by CreateProcess as requested by explorer.exe by using by default the options as stored under registry key HKEY_CURRENT_USER\Console on starting cmd.exe with option /c to process the double clicked batch file and then close itself.
5.2 Processing of the batch file by cmd.exe
The Windows command processor first parses the argument strings passed to it by explorer.exe which are /c and a command line to execute enclosed in " whereby the first and the last " are removed to have finally just the fully qualified file name of the batch file enclosed in double quotes.
For that reason the Windows command processor opens the batch file, reads the first line, parses it, finds out that no more line must be read, closes the batch file and executes the first command line which is @ECHO OFF resulting in turning off the command echo mode.
Next cmd.exe opens the batch file again, sets the file pointer to beginning of second line, reads that line, parses it, finds out that no more line must be read, closes the batch file and splits up internally the command line
START cmd.exe /k "cd C:\ABCD\" & Rscript working.r & exit

to the following commands added to its internal command queue:
START cmd.exe /k "cd C:\ABCD\"
Rscript working.r
exit

So there are three commands to execute next independent on the execution results of each previous command.
5.2.1 Starting one more cmd.exe as separate task
The first command to execute is the internal command START. So cmd.exe parses the arguments as described for the command START.
There is defined neither a window title string nor any other START specific option. So the first argument cmd.exe is the application name to pass to CreateProcess. But the path is missing and for that reason cmd.exe processing the batch file has to search first for this file.
There is most likely no cmd.exe in current directory. So the first folder path from the environment variable PATH  is used next to search for cmd.exe. The Windows default is %SystemRoot%\System32 as first folder path of PATH and this directory contains indeed cmd.exe. So the search for the fully qualified file name of cmd.exe could be finished quickly and the application name string passed to function CreateProcess by using the function parameter lpApplicationName is defined completely.
All other arguments after cmd.exe are to pass to CreateProcess as string with using the pointer lpCommandLine.
Therefore cmd.exe processing the batch file now calls CreateProcess with C:\Windows\System32\cmd.exe as application name, the string /k "cd C:\ABCD\" as command line, a null pointer for the current directory, a null pointer for the environment, etc. to start one more cmd.exe running parallel to current cmd.exe process with its own console window and its own standard input, standard output and standard error streams.
The cmd.exe process processing the batch file gets back from CreateProcess a nonzero value for successful creation of the process. So it continues with the next command in its internal command queue while the started cmd.exe is running now parallel.
5.2.2 Calling Rscript with the argument working.r
The next command in internal command queue of cmd.exe processing the batch file is:
Rscript working.r

Rscript is not an internal command of CMD. So this string is interpreted as executable or script file name which must be first found at all as specified with just the file name without full path and without file extension. Therefore cmd.exe uses again the environment variables PATH and PATHEXT to find a program/script file with that name and finds most likely indeed Rscript.exe in right directory.
There is to call again CreateProcess, but this time the application name is Rscript.exe with its full path, the command line is the string working.r, lpEnvironment is again a null pointer (as used always with a null pointer by cmd.exe), lpCurrentDirectory is a null pointer, etc. The difference is that this time Rscript.exe is not started as separate task with its own window, standard streams, etc. Rscript is called by cmd.exe.
Therefore Rscript.exe runs now and processes the command line. If the file working.r is found at all, cannot be determined by the provided information in the question. If the R script file is in same directory as the batch file, then the inheritance of the current working directory as defined by explorer.exe starting cmd.exe to process the batch file and cmd.exe on starting Rscript.exe to process the R script file results in a by chance working execution of the R script file now. Otherwise Rscript.exe exits most likely with an error as the file working.r could not be found in the current directory.
After Rscript.exe finished without or with execution of working.r, the Windows command processor instance processing the batch file continues with its internal command queue.
5.2.3 Exiting the Windows command processor
The remaining command in the internal command queue is exit which is an internal command of CMD. It instructs to immediately exit itself without further processing the batch file. So cmd.exe processing the batch file closes itself now.
5.3 Processing of second started cmd.exe
The cmd.exe process started by cmd.exe processing the batch file processes first its arguments.
There is the option /k to instruct cmd.exe to execute the command line specified with the next argument(s) and then to keep running.
The command line to execute is cd C:\ABCD\ whereby CD is recognized as internal command of CMD and C:\ABCD\ as the directory path.
The command CD is executed and if the current drive is the drive C:, the current directory is changed now for the second cmd.exe process while the first cmd.exe process is searching parallel for Rscript.exe.
There is nothing more to do for second cmd.exe, but it keeps running for user interactions.
The console window of second cmd.exe remains open with a prompt indicating C:\ABCD as current directory and waiting for user input.

A: *

*You only enclosed cd C:\ABCD in "; you have to double-quote the whole sequence of commands.

*Use the && operator, so that the script will fail if path C:\ABCD doesn't exist.

cmd /k option (run, and keep the cmd open):
start cmd.exe /k "cd /d C:\ABCD\ && Rscript working.r"

cmd /c option (run, then close the cmd window):
start cmd.exe /c "cd /d C:\ABCD\ && Rscript working.r"

The cd's /d option is used to change drive (if that's needed) in addition to the folder.
Reference: CMD.exe on SS64.


text:
Q: Does $\sum_{n=3}^\infty \frac {1}{(\log n)^{\log(\log(n)}}$ converge? Does the following series converge:
$$\sum_{n=3}^\infty \frac {1}{(\log n)^{\log(\log(n)}}$$
I've tried all test I know... Any ideas ?

A: Note that $(\log n)^{-\operatorname{loglog} n}=e^{-(\operatorname{loglog} n)^2}$, since $\log n=e^{\operatorname{loglog} n}$.
For large $n$, we have $(\operatorname{loglog} n)^2\lt \log n$, so for large $n$ the $n$-th term is greater than $\frac{1}{n}$.
The fact that $(\operatorname{loglog} n)^2$ is eventually dominated by $\log n$ is just the familiar fact that $e^x\gt x^2$ for large enough $x$.
Remark: In dealing with convergence of series, it is often better to ask oneself first: How fast are the terms approaching $0$? Looking instead for a test to use tends to distance us from the concrete reality of the series.


text:
Q: Android down loading html file The html program i down load is on a thread.
I am using this program to down load
    try {
        URL data = new URL("http:......../daily.htm");
        URLConnection conexion = data.openConnection();
        InputStreamReader input = new InputStreamReader(conexion.getInputStream());
        StringBuilder sb = new StringBuilder();
        char[] buffer = new char[60000];//4*1024];
        int n = 0;
          while(n >= 0) {
            n = input.read(buffer, 0, buffer.length);
            if (n > 0) {
                sb.append(buffer, 0, n);
            }
        }

My html TEXT is about 46k of data.
ON STARTING THE PROGRAM sometimes the download is incomplete and the data is much less than what I need (46k). It seems like the download is not finished.
However when the program is already running it never fails!!. Only on startup.
Any idea how to debug in such a case. Or can I use a ROCK SOLID another program?

A: Spend some time learning how threading works.
http://developer.android.com/resources/articles/painless-threading.html
http://indyvision.net/2010/01/android-threads-tutorial
http://www.vogella.de/articles/AndroidPerformance/article.html
And increase your acceptance rate by accepting answers!


text:
Q: Finite State Machine for Synchronous Circuit Using the diagram below I have to fill out the state table for Q1+, Q0+, G, and F.

Assuming Q0+ and Q1+ are the inputs to the left and right flip-flops, respectively, fill out the following state table for the circuit above:
Q1: 0 0 1 1
Q0: 0 1 0 1
Q1+: 0 1 0 1
Q0+: 1 0 1 0
G: 0 0 1 1
F: 0 1 0 1
Based on the diagram and the values of Q1 and Q0, would my values be correct for Q1+, Q0+, G, and F?  Thank you!

A: Assuming:

*

*Q0 is the output of the DFF on the left,

*Q1 is the output of the DFF on the right,

*Q0+ = Q0* = Q0 next,

*Q1+ = Q1* = Q1 next

We can derive expressions for the values Q0*, Q1*, F and G from observations of the circuit.

*

*F = Q0 (connected to output of Q0 DFF)

*G = Q1 (connected to output of Q1 DFF)

*Q1* = Q0 (connected to output of Q0 DFF)

*Q0* = ~Q1 (connected to inverted output of Q1 DFF)

You may notice that all of the above equations only depend on the Q0 and Q1 state registers. This means this is a Moore FSM since the output depends only on the present state. We can build the entire truth table from just the Q0 and Q1 states on the left side:
Truth Table
Q1 Q0 | Q1* Q0* G F
-------------------
0  0  | 0   1   0 0
0  1  | 1   1   0 1
1  0  | 0   0   1 0
1  1  | 1   0   1 1


text:
Q: Variable in event I got this code:
<script>window.onload = function () {
    var container, i;

    for (i = 0; i < 10; i ++) {
        container = document.createElement ("div");
            container.innerHTML = i;

            container.style.border = "1px solid black";
            container.style.padding = "10px";

            container.onclick = function () {
                alert (i);
            }

        document.body.appendChild (container);
    }
}</script>

Just would like to know why I get the wrong number when I click on element :(
Thanks

A: This is the classic scoping problem with anonymous functions.
The variable i in the function is the same for every event handler you add - so they'll all alert the same value.
You want to create a new scope for each variable: something like:
function createAlertFunction(i) {
    return function() {
        alert(i);
    }
}

//...

container.onclick = createAlertFunction(i);

A: You need to create for each iteration its own function. Try this instead:
container.onclick = (function(i) {
    return function() {
        alert(i);
    };
})(i);

Here the outer function (function(i) { … }) is used to return a new function with the value of i. When this function is called ((function(i) { … })(i)) the i is passed to that function and gets embedded into the function that gets returned.

A: It's not displaying the wrong value, it's displaying the value of i when the inner anonymous function is called. I think you're expecting it to display the value of i when the function was bound to the respective divs' onclick events.

A: Similar to Gumbo's and Anon's answers, although I personally find it slightly easier to read (just my opinion).
window.onload = function () {
        var container, i;

        for (i = 0; i < 10; i ++) {
            (function() {
                container = document.createElement ("div");
                container.innerHTML = i;

                container.style.border = "1px solid black";
                container.style.padding = "10px";

                container.onclick = function () {
                                        alert (i);
                                    };

                document.body.appendChild (container);
            })();
       }
}

A: Here you're attempting to create something called "closure". It closes the last known context with the value of the variable "i". So to obtain a correct value inside of a closure, you have to create a new context by passing the variable value to new local scope of inner function. More about closures: http://www.jibbering.com/faq/faq%5Fnotes/closures.html

A: Rather than create a large number of virtually identical functions using closures, why not try something like this:
function containerOnClick () {
    alert(this.index);
}

window.onload = function() {
    var container, i;
    for (i = 0; i < 10; i++) {
        // -- snip --
        container.index = i;
        container.onclick = containerOnClick;
    }
};

Depending on the size of the onclick handler, as well as the number of containers you'll have in total, this could reduce the memory footprint quite a bit.

A: You can use with
var container, i;
for (i = 0; i < 10; i ++) {
    with ({ locali: i }) {
        container = document.createElement ("div");
        container.innerHTML = i;
        container.style.border = "1px solid black";
        container.style.padding = "10px";
        container.onclick = function () {
            alert(locali);
        }
    }
    document.body.appendChild(container);
}

Compared to the anonymous function solution mentioned before, it's a little less performant (which only matters if you call it 10s of 1000s of times), and works a lot better with the Visual Studio debugger (and probably others as well).


text:
Q: The Existence of "Simple" Prime Generating Functions Obviously, we do not know an explicit and easily manipulable formula for finding every prime - that is, a function $f(n)$ which yields the $n^{th}$ prime. I've seen plenty of formulas that "cheat" in some way (e.g. encode trial division in a sum and floor functions) or only yield a very sparse set of primes (e.g. Mills' formula).
I'm curious about results of the existence or non-existence of $f$ satisfying certain "sanity" conditions. What is clear to me is that:

*

*There is no suitable rational function, because they are all in $O(x^k)$ for integer $k$, which is the wrong asymptotic.

*There is an analytic function giving primes, because any sequence can be given by an analytic function.
However, these are really trivial observations, and they leave a very wide gap of functions for which we don't know much. Could there be any $f$ writable in terms of integrals of rational functions? Could there be an $f$ with some power series which converges quickly? Could there be some $f$ defined by an (algebraic) differential equation? I'd be interested in any (non-trivial*) result of existence or non-existence of such functions - or even about functions which always yields primes, but don't yield every prime.
(*i.e. "trivial" being a result that would hold for any sequence in $O(n\log(n))$)


text:
Q: Trying to get row position correctly I currently have a question about this but I don't think it's receiving the attention it deserves, probably because of its extension and editions throughout the time. With this one I'll try to be as concise as I possibly can, lets go!
I am trying to get the row position of a specific table, in this SQLFiddle
I currently have 2 queries on it: one that lists all rows ordering them by column rank (which is a COUNT() of other rows); and other that gets the info for a specific row.
In this screenshot of the SQLFiddle, I have the current results, and in yellow (right next to the position column) I have the desired result. You can see that "position" is probably referring to column id, not to column rank, as it should be:

How can I achieve the desired result?
In case Fiddle doesn't loads, here's all the DLLs:
Schema:
CREATE TABLE IF NOT EXISTS `site_users` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `username` varchar(255) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM  DEFAULT CHARSET=latin1 AUTO_INCREMENT=6 ;

INSERT INTO `site_users` (`id`, `username`) VALUES
(1, 'Mateus'),
(2, 'Marco'),
(3, 'John'),
(4, 'Luke'),
(5, 'Wall');

CREATE TABLE IF NOT EXISTS `site_articles_comments` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `user_id` int(11) NOT NULL,
  `data` int(11) NOT NULL,
  `comment` text NOT NULL,
  PRIMARY KEY (`id`),
  KEY `user_id` (`user_id`)
) ENGINE=MyISAM  DEFAULT CHARSET=latin1 AUTO_INCREMENT=12 ;

INSERT INTO `site_articles_comments` (`id`, `user_id`, `data`, `comment`) VALUES
(1, 1, 1492101324, 'Too good to be true'),
(2, 1, 1492101392, 'It\'s so, not very.'),
(3, 1, 1492106262, 'I loved it!'),
(4, 3, 1492107619, 'Seems fishy'),
(5, 1, 1492108002, 'Don\'t blame it on her'),
(6, 2, 1492108433, 'As I highly doubt it'),
(7, 2, 1492200402, 'This is just a test'),
(8, 2, 1492267629, 'Another test'),
(9, 2, 1492267684, 'No sht'),
(10, 4, 1492267766, 'WTF?'),
(11, 2, 1492267796, 'Pics, pleaseee!');

Test queries:
/* This simply order users on rank (rank being number of comments) */
/* This query tries to get the row position of user based on rank */

SELECT x.id,
       x.username,
       x.rank,
       x.position
  FROM (SELECT u.id,
               u.username,
               @rownum := @rownum + 1 AS position,
               (SELECT COALESCE(COUNT(DISTINCT(c.id)),0) AS rank
                  FROM site_articles_comments c
                  WHERE u.id = c.user_id ORDER BY rank DESC) AS rank
          FROM site_users u
          JOIN (SELECT @rownum := 0) r
        ORDER BY rank DESC) x;

/* Based on the list above, user (Marco) should have a position number of 1 */

SELECT x.id,
       x.username,
       x.rank,
       x.position
  FROM (SELECT u.id,
               u.username,
               @rownum := @rownum + 1 AS position,
               (SELECT COALESCE(COUNT(DISTINCT(c.id)),0) AS rank
                  FROM site_articles_comments c
                  WHERE u.id = c.user_id ORDER BY rank DESC) AS rank
          FROM site_users u
          JOIN (SELECT @rownum := 0) r
        ORDER BY rank DESC) x
  WHERE x.id = 2

A: What you are looking for might be this:
SET @rowno2=0;

SELECT x.id,
       x.username,
       x.rank,
       x.position,
       @rowno2:=@rowno2+1 AS rowno
  FROM (SELECT u.id,
               u.username,
               @rownum := @rownum + 1 AS position,
               (SELECT COALESCE(COUNT(DISTINCT(c.id)),0) AS rank
                  FROM site_articles_comments c
                  WHERE u.id = c.user_id ORDER BY rank DESC) AS rank
          FROM site_users u
          JOIN (SELECT @rownum := 0) r
        ORDER BY rank DESC) x;

SET @rowno2=0;

SELECT x.id,
       x.username,
       x.rank,
       x.position,
       @rowno2:=@rowno2+1 AS rowno
  FROM (SELECT u.id,
               u.username,
               @rownum := @rownum + 1 AS position,
               (SELECT COALESCE(COUNT(DISTINCT(c.id)),0) AS rank
                  FROM site_articles_comments c
                  WHERE u.id = c.user_id ORDER BY rank DESC) AS rank
          FROM site_users u
          JOIN (SELECT @rownum := 0) r
        ORDER BY rank DESC) x
  WHERE x.id = 2

So you can use a MySQL variable to keep track of the row number.
I haven't looked at the rest of your SQL.


text:
Q: Formatting the ArgParse help menu I am trying to create a more attractive menu for ArgParse mainly just consistent formatting when the help menu is displayed. I understand how to use various attributes to make something required or not, but am not sure how to format the text so that they are consistent.
My current code that is relevant is shown below
import argparse

parser = argparse.ArgumentParser(prog='myprogram', description='Select which files to parser and where to save them.')

parser.add_argument('-f', metavar='--file', type=str, help='select a single file to process', required=False)
parser.add_argument('-d', metavar='--dir', type=str, help='filepath directory', required=False)

args = parser.parse_args()

The output of this code is when running the command filename.py -h is

What I would like to do is simply add a comma between -f and --file as well as any additional commands. I understand this is fairly small detail, but what can I say I like to format things consistently.
I am running Python v3.8.2 on my machine and Argparse v1.4.0

A: This should illustrate the main help formatting possibilities (without subclassing the helpformatter):
In [1]: import argparse
In [2]: parser=argparse.ArgumentParser()
In [3]: parser.add_argument('-f','--foo',action='store_true', help='a store true
   ...: ');
In [4]: parser.add_argument('-b','--bar',help='basic store');
In [5]: parser.add_argument('-x','--xxx', metavar='',help='blank metavar');
In [6]: parser.print_help()
usage: ipython3 [-h] [-f] [-b BAR] [-x]

optional arguments:
  -h, --help         show this help message and exit
  -f, --foo          a store true
  -b BAR, --bar BAR  basic store
  -x , --xxx         blank metavar


text:
Q: Why should an API return 'void'? When writing an API or reusable object, is there any technical reason why all method calls that return 'void' shouldn't just return 'this' (*this in C++)?
For example, using the string class, we can do this kind of thing:
string input= ...;
string.Join(input.TrimStart().TrimEnd().Split("|"), "-");

but we can't do this:
string.Join(input.TrimStart().TrimEnd().Split("|").Reverse(), "-");

..because Array.Reverse() returns void.
There are many other examples where an API has lots of void-returning operations, so code ends up looking like:
api.Method1();
api.Method2();
api.Method3();

..but it would be perfectly possible to write:
api.Method1().Method2().Method3()

..if the API designer had allowed this.
Is there a technical reason for following this route? Or is it just a style thing, to indicate mutability/new object?
(x-ref Stylistic question concerning returning void)

EPILOGUE
I've accepted Luvieere's answer as I think this best represents the intention/design, but it seems there are popular API examples out there that deviate from this :
In C++ cout << setprecision(..) << number << setwidth(..) << othernumber; seems to alter the cout object in order to modify the next datum inserted.
In .NET, Stack.Pop() and Queue.Dequeue() both return an item but change the collection too.
Props to ChrisW and others for getting detailed on the actual performance costs.

A:
Is there a technical reason for following this route?

One of the C++ design guidelines is "don't pay for features you don't use"; returning this would have some (slight) performance penalty, for a feature which many people (I, for one) wouldn't be inclined to make use of.

A: The technical principal that many others have mentioned (that void emphasizes the fact the function has a side-effect) is known as Command-Query Separation.
While there are pros and cons to this principle, e.g., (subjectively) clearer intent vs. more concise API, the most important part is to be consistent.

A: I'd imagine one reason might be simplicity. Quite simply, an API should generally be as minimal as possible. It should be clear with every aspect of it, what it is for.
If I see a function that returns void, I know that the return type is not important. Whatever the function does, it doesn't return anything for me to work with.
If a function returns something non-void, I have to stop and wonder why. What is this object that might be returned? Why is it returned? Can I assume that this is always returned, or will  it sometimes be null? Or an entirely different object? And so on.
In a third-party API, I'd prefer if that kind of questions just never arise.
If the function doesn't need to return anything, it shouldn't return anything.

A: If you intend your API to be called from F#, please do return void unless you're convinced that this particular method call is going to be chained with another nearly every time it's used.
If you don't care about making your API easy to use from F#, you can stop reading here.
F# is more strict than C# in certain areas - it wants you to be explicit about whether you're calling a method in order to get a value, or purely for its side-effects. As a result, calling a method for its side-effects when that method also returns a value becomes awkward, because the returned value has to be explicitly ignored in order to avoid compiler errors. This makes "fluent interfaces" somewhat awkward to use from F#, which has its own superior syntax for chaining a series of calls together.
For example, suppose we have a logging system with a Log method that returns this to allow for some sort of method chaining:
let add x y =
    Logger.Log(String.Format("Adding {0} and {1}", x, y)) // #1
    x + y                                                 // #2

In F#, because line #1 is a method call that returns a value, and we're not doing anything with that value, the add function is considered to take two values and return that Logger instance. However, line #2 not only also returns a value, it appears after what F# considers to be the "return" statement for the function, effectively making two "return" statements. This will cause a compiler error, and we need to explicitly ignore the return value of the Log method to avoid this error, so that our add method has only a single return statement.
let add x y =
    Logger.Log(String.Format("Adding {0} and {1}", x, y)) |> ignore
    x + y

As you might guess, making lots of "Fluent API" calls that are mainly about side-effects becomes a somewhat frustrating exercise in sprinkling lots of ignore statements all over the place.
You can, of course, have the best of both worlds and please both C# and F# developers by providing both a fluent API and an F# module for working with your code. But if you're not going to do that, and you intend your API for public consumption, please think twice before returning this from every single method.

A: Methods that return void state more clearly that they have side effects. The ones that return the modified result are supposed to have no side effects, including modifying the original input. Making a method return void implies that it changes its input or some other internal state of the API.

A: If you had Reverse() return a string, then it wouldn't be obvious to a user of the API whether it returned a new string or the same-one, reversed in-place.
string my_string = "hello";
string your_string = my_string.reverse(); // is my_string reversed or not?

That is why, for instance, in Python, list.sort() returns None; it distinguishes the in-place sort from sorted(my_list).

A: Besides the design reasons, there is also a slight performance cost (both in speed and space) for returning this.


text:
Q: Diferencia entre dos formatos en xml Quiero saber la diferencia entre estos dos formatos en XML
<Producto Cod=5"/>

Y
<Producto> <Cod>"5"</Cod> </Producto>

y como podria generar un xml a partir de un objeto con el primer formato en C#
Gracias.

A: La diferencia está en que en la primera línea:
<Producto Cod=5"/>

Estás definiendo un atributo "Cod" para un elemento "Producto".
y en la segunda:
<Producto> <Cod>"5"</Cod> </Producto>

Estás definiendo un elemento "Cod" dentro del elemento "Producto".
Para leerlo y asignarlo a un objeto en C# tienes diferentes alternativas, te propongo una (no es la única ni la mejor). Obviamente no tiene validaciones de tipo/cast.:
using System;
using System.Xml.Linq;

public class Program
{
    public static void Main()
    {
        var doc = XDocument.Parse(@"<Producto Cod='5' />");
        var producto = new Producto{
            Cod = (int)doc.Root.Attribute("Cod")
        };
    }
}

public class Producto{
    public int Cod{get;set;}
}

Por si quieres jugar un poco con el ejemplo, te dejo el fiddle: https://dotnetfiddle.net/KyZ1an
UPDATE:
Teniendo en cuenta el último comentario, en este caso ya es un poco más teórica la pregunta. Se trata de dos "enfoques" diferentes para el tratamiento de XML:
a) Centrado en atributos (primer código)
b) Centrado en elementos (segundo código)
Para el primer caso:
<Producto Cod="5"/>

"Cod" es un atributo del elemento "Producto".
Para el segundo caso:
<Producto>5</Producto>

"5" es el valor para el elemento "Producto".
Incluso se podría tener una combinación de los 2:
<Producto Cod="5">5</Producto>

Que se leería más o menos: Producto "tiene" un atributo "Cod = 5" y el valor de Producto es 5.
Todo depende del "significado" que le quieras dar al XML.
Quizás este articulo explique mejor la diferencia: https://decipherinfosys.wordpress.com/2007/09/08/attribute-centric-and-element-centric-xml/


text:
Q: Laravel Eloquent (A Model attribute won't show) I have a Stat Class :
class Stat extends Model
{
    public static function getByKey($key)
    {
        return Stat::where("key", "=", $key)->first();
    }

    public function getDates()
    {
        return json_decode($this->content);
    }
}

In my database the Table stats contains only two columns (key, content)
When I execute this function in my view an error occurs
{!! \App\Stat::getByKey("ORDERS-DATA")->getDates() !!}

and this makes this error :
Exception message: Undefined property: App\Stat::$content

So I added these two lines to the getDates() to debug the error :
public function getDates()
{
    dd($this->content);//This shows the same error
    dd($this->attributes["content"]);//This works fine and show me what I want
    return json_decode($this->content);
}

then I executed dd($this) and it shows this :
Stat {#486
  #connection: "mysql"
  #table: "stats"
  #primaryKey: "id"
  #keyType: "int"
  +incrementing: true
  #with: []
  #withCount: []
  #perPage: 15
  +exists: true
  +wasRecentlyCreated: false
  #attributes: array:5 [
    "id" => 8
    "key" => "ORDERS-DATA"
    "content" => """
      [
      {
      \t"day": "2019-04-01",
      \t"count": "5"
      }
      ]
      """
    "created_at" => "2019-04-01 14:09:00"
    "updated_at" => "2019-04-01 14:11:02"
  ]
  #original: array:5 [
    "id" => 8
    "key" => "ORDERS-DATA"
    "content" => """
      [
      {
      \t"day": "2019-04-01",
      \t"count": "5"
      }
      ]
      """
    "created_at" => "2019-04-01 14:09:00"
    "updated_at" => "2019-04-01 14:11:02"
  ]
  #changes: []
  #casts: []
  #dates: []
  #dateFormat: null
  #appends: []
  #dispatchesEvents: []
  #observables: []
  #relations: []
  #touches: []
  +timestamps: true
  #hidden: []
  #visible: []
  #fillable: []
  #guarded: array:1 [
    0 => "*"
  ]
}

And What I want is to get my content by $this->content, and I don't understand why it doesn't works ??
Please Help

A: The error is occurring because I have overrided one of the Laravel functions.
the name getDates OR getByKey OR getCounts is used by Laravel.

This is so weird this error happened to me two times in the same
  day, Today's morning I created a function called getAttributes() and
  showed me a total diferrent error. Why the community don't create a
  list of functions names that we are not allowed to use, or use more
  unique names ???


text:
Q: SSRS Charting - Display Legend and Percent I'd like to display Day (Percentage) eg Fri (22%) on the chart
Can do each individually:
Series Label Properties, Label data:  #PERCENT{p0}
or:  =Fields!DayOfWeek.Value
Problem: How to display both?

A: Here goes the expression:
=Fields!DayOfWeek.Value+"(#PERCENT{p0})"


text:
Q: How to create a reorderable (draggable) gridview with animations As title said, I want to create a gridview that can do the following:

*

*add items with animations (like how animatedList pushes the lower items down with animation)

*can hold and drag a grid to reorder it

*hovering a grad item in between 2 will create a space for it (like how you reorder apps on a mobile phone

So far I have tried these methods:

*

*GridView.builder with SlideTransition (animation didnt trigger when adding items)

*Stack with AnimatedPosition (animations didnt trigger)

*Animated Grid (no animation for reordering)

I know there is libraries out there but I wanted to try implementing it myself, i would be appreciated if there is some sort of guidance to making my own custom GridView.


text:
Q: Data columns on reputation page with repeated numbers On the reputation page, what does the first column represent?

What are these numbers [3,2,3,2,3,2,16,...] for, highlighted in the image?

A: It's the ID of the type of "vote" you received:

Id Name
-- ---------------------
1  AcceptedByOriginator
2  UpMod
3  DownMod
4  Offensive
5  Favorite
6  Close
7  Reopen
8  BountyStart
9  BountyClose
10 Deletion
11 Undeletion
12 Spam
15 ModeratorReview
16 ApproveEditSuggestion

See the VoteTypes table on the Data Explorer.
To be complete, the second column is the ID of the post the "vote" applies to and the third is the amount of reputation gained (minus rep is a negative gain) from the "vote".

A: Those numbers correspond to the type of event that caused the reputation change (i.e., whether it was due to an upvote, downvote, bounty, etc.).
That page is mostly defunct though, with everything on it being covered by the regular account reputation page.


text:
Q: Error converting CFML arguments to Java classes for web service invocation I am trying to consume a WSDL from ColdFusion using cfinvoke tag and I am having problems passing arguments. If it's a simple STRING or NUMERIC argument, it works good. The problem is when I need to pass this argument:
<part name="options" type="soap-enc:Array"/>

Well, I tried different ways: pass a ColdFusion ARRAY, STRUCT, simple string, etc. Nothing works. In some cases I got a response from the web service telling that the parameter is missing and when I pass a structure, I am getting this error:

Error converting CFML arguments to Java classes for web service
  invocation. Unable to create web service argument class
  [Ljava.lang.Object;. Error: java.lang.InstantiationException:
  [Ljava.lang.Object;. Often this is because the web service defines an
  abstract complexType as an input to an operation. You must create an
  actual instance of this type in Java.

You can see the script in action here:
cf wsdl web service test
There you have the link to the web service definitions.
What should I do? How do I pass simple Array objects to WSLD from ColdFusion?

A: The lack of transparency around complex SOAP objects like you see here are a big reason why JSON is much preferred as a data format these days. I've written Java components to deal with this kind of thing. You need to know the specific format of the options variable (the second argument), which is an array of Objects, though it gives no details. I don't have a completely working solution for you, but this code should get you most of the way there.
<cfscript>
    ws = createObject("webservice", "https://api.iritravel.ro/?wsdl");
    res = ws.getCountries(token = "137e8f1a094-1031");
    country = createObject( "java", "java.util.HashMap" ).init();
    country.put( 'CountryId', 2 );
    res2 = ws.getTowns( token = "137e8f1a094-1031", options=[ country ] );
    writedump( res2 );
    writedump( country );
</cfscript>

If I get it working I will post an update, but you might be able to get it done using what I have here. I have created a HashMap (basic Java object) and added a key "CountryId" with a value of 2. See the way I formatted the options argument as an array and passed the country HashMap object to it as the first element of the array. That bit of the code works, so you just need to know the specific format of the Object the service is expecting.
Update
I have included a SOAPUI-generated request for getTowns() which shows the problem is the same whether using webservices calls or cfhttp. In this case, I have added a CountryId parameter to the request, and what I get back is the same response I got from the previous call - param CountryId is missing. So the issue is the same - the format of the Object Array that the service is expecting to consume is incorrect.
http://pastebin.com/ZXBS2e2r


text:
Q: Ionic3/Angular 4 Set Focus Is there a "best" practice for setting focus either on page load or after an event.
I've tried the following but getting really inconsistent results with focus setting or not setting. I would need it to set focus to different types of inputs too (buttons, text, etc) either on load or after an event, etc.
I'm just looking to find if there is a solid way to set focus as to this point I haven't found a great way to accomplish this.
ionViewDidLoad() {
    this.setFocusToInput('employeeIdInput');
  }

  setFocusToInput(inputName) {
    setTimeout(() => {
      this[inputName].setFocus();
    }, 1000);
  }


text:
Q: Vector of smart pointers destructor call Why does the Node destructor get called only once instead of 5 times in the code below?
#include <iostream>
#include <vector>
#include <memory>

struct Node {
    ~Node() {std::cout << "Node destructor called.\n";}
};

void foo() {
    std::vector<std::shared_ptr<Node>> nodes(5, std::make_shared<Node>());
}

int main() {
    foo();
    std::cout << "foo() ended.\n";
}

A: Your vector contains five copies of the original shared pointer, all sharing ownership of the one single pointee.
To create five separate objects, each owned by one shared pointer, write it like this:
std::vector<std::shared_ptr<Node>> nodes;
for (int i = 0; i != 5; ++i) nodes.push_back(std::make_shared<Node>());

A: Kerrek SB explained the situation well, but to do what you want to do in a different way, you could also the std::generate_n algorithm:
std::vector<std::shared_ptr<Node>> nodes;
std::generate_n(
    std::back_inserter(nodes),
    5,
    std::make_shared<Node>);

This is more along the lines of what you thought you were doing originally.
Or, similarly:
std::vector<std::shared_ptr<Node>> nodes(5);
std::generate(nodes.begin(), nodes.end(), std::make_shared<Node>);


text:
Q: trying to make an "OS" in batch     @echo off
:load
rem imitation of loading the os
color 70
ver
title boot
echo please wait...
ping localhost -n 3 >nul
cls
systeminfo
rem in here user types name he wants to be his account name
:login
title login
cls
date
cls
echo welcome to windows 71
echo before we bigen please type your name
set /P_name=here:
if %name%=admin goto admin
if not goto ms
rem ms=menu start
:ms
echo %time%
echo hello %name%
echo type HELP for list to commands
set /P_command=here:
if %command%=help goto help
if %command%=exit goto exit
if %command%=calendar goto cal
if not goto wc
rem wc=wrong command
:admin
echo hello %name% to the admin panel
echo type HELP for list to commands
set /P_command=here:
if %command%=help goto help
if %command%=exit goto exit
if %command%=calendar goto cal

So the problem is that it crashes after the :LOGIN part and I don't know what to do!
I'm trying to make an OS batch (something like MS-DOS), but it crashes after the "login" part.
I tried everything I could think of and it didn't work, also I want to make a save file so users can set a password for their "account".

A: As mentioned in above comments, you need to correctly use your variables, you can however use choice instead of set /p for your commands.
@echo off
:load
rem imitation of loading the os
color 70
ver
title boot
echo please wait...
timeout /t 3 >nul
cls
systeminfo
rem in here user types name he wants to be his account name
:login
title login
cls
date /t
timeout /t 2>nul
cls
echo welcome to windows 71
echo Before we begin please type your name
set /P "_name=here:"
if /i "_%name%"=="admin" goto admin
rem ms=menu start
:ms
echo %time%
echo hello %_name%
echo type HELP for list to commands
CHOICE /C HEC /M "Press H for Help, E to exit C for Calender."
goto opt%errorlevel%

:admin
echo hello %_name% to the admin panel
echo type HELP for list to commands
CHOICE /C HEC /M "Press H for Help, E to exit C for Calender."
goto opt%errorlevel%

:opt1
echo Help stuff goes here

goto :eof
:opt2
exit

:opt3
echo Calenders stuff goes here

Some things to note. You do not require to goto ms is the user is not admin as the statement for not being admin will not be met, we will automatically faal through into the ms label.
Notice where the problems were in your code. i.e if %name%=admin should be if "%_name%"=="admin" with double equal sign and the underscore in the name. It is also double quoted to ensure that we do a match without unwanted whitespace. Lastly /I option to catch ADMIN in any case.
See if /?, choice /? from command line for more help around these functions.

A: Okay this code is quite wrong.
I fixed it.
@echo off
:load
rem imitation of loading the os
color 70
title boot
echo please wait...
ping localhost -n 3 >nul
cls
rem in here user types name he wants to be his account name
:login
title login
cls
echo Welcome to Microsoft Windows 7!
echo Before we begin, please type your name.
set /p name=here:
if "%name%"=="admin" goto admin
if not "%name%"=="admin" goto ms
rem ms=menu start
:ms
echo %time%
echo Hello %name%
echo Type HELP for list to commands
set /p command=here:
if "%command%"=="help" goto help
if "%command%"=="exit" goto exit
if "%command%"=="calendar" goto cal
goto ms
rem wc=wrong command
:admin
CLS
echo hello %name% to the admin panel
echo type HELP for list to commands
set /P command=here:
if "%command%"=="help" goto help
if "%command%"=="exit" goto exit
if "%command%"=="calendar" goto cal

GOTO :ADMIN

Okay but you don't need to start systeminfo and all that.


text:
Q: Hibernate Relational one to many Mapping Issue I have a issue regarding one to many mapping in hibernate 4.x and I am using mysql5.6.
First Let show you my 2 entities,
first user entity,
package com.project.entities;

import java.util.ArrayList;
import java.util.Collection;

import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.Table;

@Entity
@Table(name="UserBookingEntryTable")
public class UserBookingEntryClass {

    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
    private int uid;
    private String ubmobile_no;
    private String ubname;
    @OneToMany(cascade = {CascadeType.ALL},mappedBy="user")
    private Collection<BookingServicesClass> bookings=new ArrayList<BookingServicesClass>();

    public Collection<BookingServicesClass> getBookings() {
        return bookings;
    }
    public void setBookings(Collection<BookingServicesClass> bookings) {
        this.bookings = bookings;
    }
    public int getUid() {
        return uid;
    }
    public void setUid(int uid) {
        this.uid = uid;
    }

    public String getUbmobile_no() {
        return ubmobile_no;
    }
    public void setUbmobile_no(String ubmobile_no) {
        this.ubmobile_no = ubmobile_no;
    }
    public String getUbname() {
        return ubname;
    }
    public void setUbname(String ubname) {
        this.ubname = ubname;
    }

}

Second Entity -Booking Class
package com.project.entities;

import java.util.Date;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;

@Entity
@Table(name = "BookingServiceTable")
public class BookingServicesClass {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private int booking_id;

    private String first_name;

    private String last_name;

    private String mobile;

    private String location;

    private String booking_address;

    private String booking_type;

    private String landmark;
    private int booking_pincode;
    private Date booking_date;
    @ManyToOne
    @JoinColumn(name="usid")
    private UserBookingEntryClass user;
    public Integer getBooking_id() {
        return booking_id;
    }

    public void setBooking_id(Integer booking_id) {
        this.booking_id = booking_id;
    }

    public String getFirst_name() {
        return first_name;
    }

    public void setFirst_name(String first_name) {
        this.first_name = first_name;
    }

    public String getLast_name() {
        return last_name;
    }

    public void setLast_name(String last_name) {
        this.last_name = last_name;
    }

    public String getMobile() {
        return mobile;
    }

    public void setMobile(String mobile) {
        this.mobile = mobile;
    }

    public String getLocation() {
        return location;
    }

    public void setLocation(String location) {
        this.location = location;
    }

    public String getBooking_address() {
        return booking_address;
    }

    public void setBooking_address(String booking_address) {
        this.booking_address = booking_address;
    }

    public String getLandmark() {
        return landmark;
    }

    public void setLandmark(String landmark) {
        this.landmark = landmark;
    }

    public Integer getBooking_pincode() {
        return booking_pincode;
    }

    public void setBooking_pincode(Integer booking_pincode) {
        this.booking_pincode = booking_pincode;
    }

    public Date getBooking_date() {
        return booking_date;
    }

    public void setBooking_date(Date booking_date) {
        this.booking_date = booking_date;
    }

    public String getBooking_type() {
        return booking_type;
    }

    public void setBooking_type(String booking_type) {
        this.booking_type = booking_type;
    }

    public UserBookingEntryClass getUser() {
        return user;
    }

    public void setUser(UserBookingEntryClass user) {
        this.user = user;
    }

}

    // to add booking from a user:
    public String addService(String fname, String lname, String mob,
            String ser, String loc, String add, String lm, int pc, String bd) {
        String res = "failure";
        SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy");
        Date convertedCurrentDate = null;

        try {
            convertedCurrentDate = sdf.parse(bd);
        } catch (ParseException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }
        BookingServicesClass bs = new BookingServicesClass();
        UserBookingEntryClass ubs = new UserBookingEntryClass();
        Session session = HibernateUtil.getSessionFactory().openSession();

        session.beginTransaction();
        System.out.println("dddd");
        try {

            **//userid is auto generated**
            ubs.setUbmobile_no(mob);
            ubs.setUbname((fname + " " + lname));
            // bs.setBid(1);
            bs.setFirst_name(fname);
            bs.setLast_name(lname);
            bs.setMobile(mob);
            bs.setLocation(loc);
            bs.setBooking_type(ser);
            bs.setBooking_address(add);
            bs.setLandmark(lm);
            bs.setBooking_pincode(pc);
            bs.setBooking_date(convertedCurrentDate);
            bs.setUser(ubs);
            session.save(ubs);
            session.save(bs);

            // Commit the transaction
            session.getTransaction().commit();
            /*session.close();*/
            res = "success";
            System.out.println("ajax");

        } catch (Exception e) {
            System.out.println(e);
            session.getTransaction().rollback();
            res = "failure";
            // success=false;
        }

        return res;
    }

Now the issue is that one user can do more than one booking.
So the code create a foreign key in booking table which is users key who is booking.
but when the one user books more than one booking the Unique constraint Error is given.
So i made the userid auto genrate which is not according to my needs,
becuase if same user books two booking then userid should be same but when i do this it gives me unique constraint error.
Please  tell how should I implement it.
Thanks

A: First thing - id of User should not be auto generated, maybe the mobilenumber which will definitely be unique should be the identifier
Second thing - When you add the booking you will check if the user exists , if it exists add the booking to the user ,otherwise create the user and add the bookings, and then commit the user.
Try these and let me know.
BookingServicesClass  booking = new BookingServicesClass ()
if(ubmobile_no!=null) {
    UserBookingEntryClass user= session.get(UserBookingEntryClass .class, ubmobile_no);
    if (user!= null) {
          booking.setUser(user);
          user.getBookings().add(booking);
       } else {
          //do nothing
       }
   }


text:
Q: SQL injection en PHP con un midleware CodeIgniter Estoy con una duda  con una función para prevenir SQL injection:
public function f_LIMPIARINPUT($a_variable) {
    $valor = $a_variable;
    $valor = str_ireplace("SELECT", "", $valor);
    $valor = str_ireplace("FROM", "", $valor);
    $valor = str_ireplace("TABLE", "", $valor);
    $valor = str_ireplace("COUNT(*)", "", $valor);
    $valor = str_ireplace("(", "", $valor);
    $valor = str_ireplace(")", "", $valor);
    $valor = str_ireplace("INSERT", "", $valor);
    $valor = str_ireplace("INTO", "", $valor);
    $valor = str_ireplace("VALUES", "", $valor);
    $valor = str_ireplace(",", "", $valor);
    $valor = str_ireplace("COPY", "", $valor);
    $valor = str_ireplace("DELETE", "", $valor);
    $valor = str_ireplace("DROP", "", $valor);
    $valor = str_ireplace("DUMP", "", $valor);
    $valor = str_ireplace(" OR ", "", $valor);
    $valor = str_ireplace("%", "", $valor);
    $valor = str_ireplace("LIKE", "", $valor);
    $valor = str_ireplace("--", "", $valor);
    $valor = str_ireplace("^", "", $valor);
    $valor = str_ireplace("[", "", $valor);
    $valor = str_ireplace("]", "", $valor);
    $valor = str_ireplace("\\", "", $valor);
    $valor = str_ireplace("!", "", $valor);
    $valor = str_ireplace("¡", "", $valor);
    $valor = str_ireplace("?", "", $valor);
    $valor = str_ireplace("=", "", $valor);
    $valor = str_ireplace("&", "", $valor);
    $valor = str_ireplace("'", "", $valor);
    $valor = str_ireplace("AND", "", $valor);
    $valor = str_ireplace("IS", "", $valor);
    $valor = str_ireplace("NULL", "", $valor);
    $valor = str_ireplace(";", "", $valor);
    $valor = str_ireplace("C:fakepath", "", $valor);
    return $valor;
}

¿Les parece que podría ser de esta manera?

A: CodeIgniter escapa y sanea las variables que se le pasen a $this->db->query si se pasan mediante bindings. Pero no las escapa si lo que haces es generar una sentencia SQL dinámica concatenando cadenas (aunque dispone de algunos métodos para sanear/limpiar entradas como $this->db->escape(), $this->db->escape_str() o $this->db->escape_like_str()).
El método de los  bindings es mejor, porque es como usar consultas preparadas (son consultas preparadas). Tu función parece que sería para pasársela a los input en consultas dinámicas y eso no es recomendable porque la función no es segura, y es una mala idea por varios motivos:

*

*Existen maneras de saltarse la validación rompiendo y componiendo las palabras prohibidas. A no ser que pases esta función hasta que el resultado de dos veces consecutivas sea el mismo, puedes tener problemas. Por ejemplo, al quitar las palabras no válidas una vez, se podría pasar una cadena como:
SELSELECTECT * FRFROMOM tabla -&-

que tras la función se quedaría en:
SELECT * FROM tabla --

permitiendo inyección.

*Considera peligrosas palabras que no lo son y que serían válidas. Por ejemplo, imagina que la variable que quieres limpiar es el nombre de una persona (un dato bastante común en un formulario) y esa persona se llama "Andy", tras pasar el valor a tu función, por esta regla:
$valor = str_ireplace("AND", "", $valor);

la persona que te contacto ahora se llama "y" a secas.

*No considera peligrosas palabras que sí lo son. Esto es un problema al usar listas negras: si por el motivo que sea no se añade una palabra/término peligroso, esa palabra/término se salta la validación.
Y no todo en inyección SQL es alguien intentando leer tus datos. ¿Qué pasa si lo que se busca es obtener acceso a tu cuenta? ¿o crear una nueva cuenta? Las reglas de validación que has puesto no limpiarían estas palabras: CREATE, USER, @, IDENTIFIED BY; ni tampoco estas otras: GRANT, ALL, PRIVILEGES, ON, *.*, TO... que podrían permitir crear un usuario y darle acceso total al sistema.


text:
Q: Guardar un registro sin posibilidad de error while true, try createview Espero no ser un poco paranoica pero estoy tratando de hacer que cuando exista un registro o número de cliente igual el próximo registro sea diferente al anterior, el motivo por el que lo hago así es porque va haber mucha mucha gente capturando datos al mismo tiempo todos los días y lo que no quiero que les arroje un error 404 o algo por el estilo sino todo lo contrario, en caso de que ya exista un registro en la base de datos volver a intentar y volver a internar y volver a intentar.
Este es un ejemplo que necesito concluir para terminar bien mi script, obvio antes hace una petición a la base de datos para verificar el último registro.
Ya sé que es posible hacerlo con vistas basadas en funciones pero en este momento estoy probando vistas basadas en clases, llevo varias horas con esto. Cualquier ayuda es muy importante para mí.
Gracias chicos.
models.py
from django.db import models

# Create your models here.

class Empresa(models.Model):
    nombre = models.CharField(max_length=20)
    numero = models.IntegerField(unique=True)

views.py
from dataclasses import field
from django.shortcuts import render
from django.views.generic import *

from aplicacion.models import Empresa

# Create your views here.

class CrearEmpresa(CreateView):
    model = Empresa
    template_name = 'crearempresa.html'
    success_url  = '/crear/'
    fields = ['nombre', 'numero']

    valor = 0

    def form_valid(self, form):
        x = form.save(commit=False)
        x.numero = self.valor

        while True:
            try:
                x.save()
                return super().form_valid(form)
                break

            except:
                self.valor = self.valor + 1
                pass


text:
Q: repeat rows depending upon course duration in years I have a dataframe that needs to repeat itself.
from io import StringIO
import pandas as pd

audit_trail = StringIO('''
course_id AcademicYear_to months TotalFee
260 2017 24 100
260 2018 12 140
274 2016 36 300
274 2017 24 340
274 2018 12 200
285 2017 24 300
285 2018 12 200
''')

df11 = pd.read_csv(audit_trail, sep=" "  )

For the course id 260 there are 2 entries per year. Year 2017 and Year 2018. I need to repeat the years for the month groups.
I will get 2 more rows, 2018 for months 24 and 2017 for months 12. The final dataframe will look like this...
audit_trail = StringIO('''
course_id AcademicYear_to months TotalFee
260 2017 24 100
260 2018 24 100
260 2017 12 140
260 2018 12 140
274 2016 36 300
274 2017 36 300
274 2018 36 300
274 2016 24 340
274 2017 24 340
274 2018 24 340
274 2016 12 200
274 2017 12 200
274 2018 12 200
285 2017 24 300
285 2018 24 300
285 2017 12 200
285 2018 12 200
''')

df12 = pd.read_csv(audit_trail, sep=" "  )

I tried to concat the same dataframe twice, but that does not solve the problem. I need to change the years and for 36 months, the data needs to be repeated 3 times.
pd.concat([df11, df11])

The group by object will return the years. I simply need to join the years in each group with the original dataframe.
df11.groupby('course_id')['AcademicYear_to'].apply(list)

260          [2017, 2018]
274    [2016, 2017, 2018]
285          [2017, 2018]

Simple join can work if the records match with the number of years. For e.g. course id 274 has 48 months and 285 has duration of 24 months and there are 3, 2 entries respectively. The problem is with course id 260 which is 24 months course but has only 1 entry. The join will not return the second year for that course.
df11=pd.read_csv('https://s3.amazonaws.com/todel162/myso.csv')

df11.course_id.value_counts()
274    3
285    2
260    1

df=df11.merge(df11[['course_id']], on='course_id')

df.course_id.value_counts()
274    9
285    4
260    1

Is it possible to write a query that will also consider the number of months?

The following query will return the records where simple join will not return expected results.
df11=pd.read_csv('https://s3.amazonaws.com/todel162/myso.csv')
df11['m1']=df11.groupby('course_id').course_id.transform( lambda x: x.count() * 12)
df11.query( 'm1  !=  duration_inmonths')

df11.course_id.value_counts()
274    3
285    2
260    1

df=df11.merge(df11[['course_id']], on='course_id')

df.course_id.value_counts()
274    9
285    4
260    1

The expected count in this case is
274    6
285    4
260    2

This is because even if there are 3 years for id 274, the course duration is only 24 months. And even if there is only 1 record for 260 since the duration is 24 months, it should return 2 records. (once for current year and the other current_year + 1)

A: Not Pretty!
def f(x):
    idx = x.index.remove_unused_levels()
    idx = pd.MultiIndex.from_product(idx.levels, names=idx.names)
    return x.reindex(idx)

df11.set_index(['months', 'AcademicYear_to']) \
    .groupby('course_id').TotalFee.apply(f) \
    .groupby(level=[0, 1]).transform('first') \
    .astype(df11.TotalFee.dtype).reset_index()

    course_id  months  AcademicYear_to  TotalFee
0         260      24             2017       100
1         260      24             2018       100
2         260      12             2017       140
3         260      12             2018       140
4         274      12             2016       200
5         274      12             2017       200
6         274      12             2018       200
7         274      24             2016       340
8         274      24             2017       340
9         274      24             2018       340
10        274      36             2016       300
11        274      36             2017       300
12        274      36             2018       300
13        285      24             2017       300
14        285      24             2018       300
15        285      12             2017       200
16        285      12             2018       200

A: IIUC we can merge df11 to itself:
In [14]: df11.merge(df11[['course_id']], on='course_id')
Out[14]:
    course_id  AcademicYear_to  months  TotalFee
0         260             2017      24       100
1         260             2017      24       100
2         260             2018      12       140
3         260             2018      12       140
4         274             2016      36       300
5         274             2016      36       300
6         274             2016      36       300
7         274             2017      24       340
8         274             2017      24       340
9         274             2017      24       340
10        274             2018      12       200
11        274             2018      12       200
12        274             2018      12       200
13        285             2017      24       300
14        285             2017      24       300
15        285             2018      12       200
16        285             2018      12       200


text:
Q: Proving that the boundary of all compact $1-$ manifolds have an even number of points. It is well-known that if $M$ is a connected $1-$ manifold, then it is diffeomorphic to either $[0,1]$, $[0,1)$, $(0,1)$, or $\mathcal{S}^{1}$.
It is often stated as a trivial corollary that if, in addition, $M$ is compact, then the boundary $\partial{M}$ has an even number of points. My question is how this follows from the above statement.
It is clear that if $M$ is compact, then that limits the choices which $M$ can be diffeomorphic to to either $[0,1]$ or $\mathcal{S}^{1}$. So let's suppose that it is the case where $M$ is diffeomorphic to $[0,1]$ through the map $\phi:[0,1] \rightarrow M$.
Now, it's clear that $(\phi, [0,1])$ is not sufficient to be a chart for every point in $M$, because $[0,1]$ is not open in either $\mathbb{R}$ nor the halfspace $H^{1}$. Regardless, $M$ is a $1-$manifold by way of some charts by assumption, and hence we can talk about $int(M)$ and $\partial{M}$. We know from standard results that $int(M)$ is open in $M$ and $\partial{M}$ is closed in $M$, and that both sets are disjoint from each other, so we can say that
$$\phi: [0,1] \rightarrow int(M) \cup \partial{M}$$
is a diffeomorphism. But at this point I am a bit stuck. I feel like we should be able to prove that $\partial{M}=\phi(\{0,1\})$, and hence $\partial{M}$ consists of $2$ points, an even number, but I can't seem to make any headway here.
Can anybody point me in the right direction? Thanks!

A: I think I'm probably repeating what is said in the comments. We know that a compact connected manifold (with boundary) of dimension $1$ is diffeomorphic to either $[0,1]$ or $S^1$. Note also that diffeomorphisms of manifolds with boundary preserve the boundary, i.e. if $f:M\to N$ is a diffeomorphism of manifolds with boundary $f(\partial M)=\partial N$. So, if $\#\partial M$ is finite, then so is $\#\partial N$ and $\#\partial M=\#\partial N$ when $M\cong N$.
It is not too hard to see that $\partial([0,1])=\{0\}\cup \{1\}$, and hence that $\#\partial [0,1]=2$. On the other hand, $\partial S^1=\varnothing$, so that $\#\partial S^1=0$. So, we have proven the result in dimension $1$.
The classification of compact connected $1-$dimensional manifolds with boundary extends to the disconnected case, so that a compact $1-$dimensional manifold is diffeomorphic to
$$ M(k,\ell)=\bigg(\coprod_{i=1}^k [0,1]\bigg)\sqcup\bigg(\coprod_{j=1}^\ell S^1\bigg)$$
for some $k,\ell\ge 0$.
Then, we see that $\#\partial M(k,\ell)=2k$. So, the result follows.


text:
Q: Avg used on count I have a two tables that have following attributes
DOCTORS                  OPERATIONS
D_ID                       DATE
Name                       TYPE
Specialiation              DOCTORS_D_ID
                           PACIENTS_PACIENT_ID

I want to return name and ID of doctores that operated more than the average number of operations per doctor.
I have created following SQL command
  SELECT Name D_ID,COUNT(*) FROM DOCTORS
    JOIN OPERATION
      ON D_ID = DOCTORS_D_ID
      GROUP BY D_ID,Name
      HAVING COUNT(*) > ( SELECT AVG(COUNT(DOCTORs_D_ID))
                          FROM OPERATIONS GROUP by DOCTORS_D_ID )

this result in following table
D_ID        COUNTS(*)
Dr. Martin        3

In column D_ID is name instead of ID = only one of two attributes is returned in table. How can I return both - name and D_ID from this command?

A: I am not a fan of nested aggregation functions.  I would just do this by calculating the average directly:
SELECT Name, D_ID, COUNT(*)
FROM DOCTORS JOIN
     OPERATION
     ON D_ID = DOCTORS_D_ID
GROUP BY D_ID, Name
HAVING COUNT(*) > (SELECT COUNT(*) / COUNT(DISTINCT DOCTORs_D_ID))
                   FROM OPERATIONS
                  );

A: There is an issue of not counting doctors who do no operations in the average (in which case the average from just using the operations table [or an inner join with the operations table] will be higher than the actual answer from taking the number of operations in the operations table and the number of doctors in the doctors table).
To compensate for this you can do:
SELECT Name,
       D_ID,
       num_operations
FROM   ( SELECT Name,
                D_ID,
                COUNT( 1 ) OVER () AS num_doctors
         FROM   doctors ) d
       LEFT OUTER JOIN
       ( SELECT DISTINCT
                DOCTORS_D_ID,
                COUNT( 1 ) OVER ( PARTITION BY DOCTORS_D_ID ) AS num_operations,
                COUNT( 1 ) OVER () AS total_operations
         FROM   operations ) o
       ON ( d.d_id = o.doctors_d_id )
WHERE  num_operations > total_operations / num_doctors;

It has the added bonus using analytic functions to calculate the counts rather than performing a third table scan.

A: with num_operations as
select doctors_d_id,count( * ) as operations from operations
group by   doctors_d_id and having count(*)>
(select avg(count(doctors_d_id) from operations group by doctors_d_id )
select doctors_d_id,operations,name from  num_operation a, doctors b
where a.doctors_d_id=b.d_id


text:
Q: Highchart yAxis plotLines label position I am having an issue of relocate yAxis.plotLines.label position.

I want to move label from original position to under the plotLine.
Please check this link
Highcharts.chart('container', {
    xAxis: {
        tickInterval: 24 * 3600 * 1000, // one day
        type: 'datetime'
    },

    yAxis: {
        plotLines: [{
            color: 'red',
            width: 2,
            value: 100,
            label: {
                text: 'Plot line',
                align: 'right'
            }
        }]
    },

    series: [{
        data: [29.9, 71.5, 106.4, 129.2, 144.0, 176.0, 135.6, 148.5, 216.4],
        pointStart: Date.UTC(2010, 0, 1),
        pointInterval: 24 * 3600 * 1000
    }]
});

A: check xAxis.plotLines.label.y to adjust the label positin
Fiddle demo
 yAxis: {
    plotLines: [{
        color: 'red',
        width: 2,
        value: 100,
        label: {
            text: 'Plot line',
            align: 'right',
            y: 20, /*moves label down*/
        }
    }]
},


text:
Q: Can a measure be created in Power BI that references two tables that share no relationship? I'm trying to create a matrix table in Power BI to display the monthly rent projections for a number of properties. I thought I could simply create a measure that summed the rent from one table and then displayed it by month based on start and end date conditions, but it's been a while since I created any measures and I had forgotten that there needs to be a relationship between columns, among other things.
Data Model

A site can have more than one lease associated with it and a lease can have both car-parks and floors associated with it, of which there can be multiple.
In addition to the tables in the linked image, once I had sorted out what I thought would be the easy step I was going to add another table which includes the estimated percentage rent increase and the period in which the increase will occur.
I started out by trying to create a measure along the lines of the following:
Matrix Test =
IF (
    HASONEVALUE ( Period[Month] ),
    IF (
        Period[Month] >= Leases[Custom Start Date],
        SUM ( Floor_Rent[Annual Rent] ) / 12,
        0
    ),
    0
)

This would need to be expanded upon because the end date of a lease would also need to be taken into consideration.
As well as forgetting about the relationship requirements, I've forgotten how to deal with the issue of narrowing down to a single value within a column.
The result is supposed to be something that looks like this:

The blanks indicate a lease that starts in the future or ends within the time-frame displayed.
When I try linking the Leases table and the Period table on Leases[Start month for current term] and Period[Month] all I can get to is a table that shows the rent amount in the month the lease starts.
Is what I'm trying to achieve possible? If so, how do I accomplish the desired result?
Link to .pbix file
Solution
The direct answer to the title question is probably 'no', but while trying to figure out how I could use Pratik Bhavsar's LOOKUPVALUE suggestion I had a thought and performed a clumsy google search - power bi create table for each value in column - and found this post. By meddling with some of the DAX in said post I was able to come up with the following:
Test Table =
GENERATE(
    SELECTCOLUMNS(
        VALUES(Leases[Lease ID]),"Lease ID",[Lease ID]
    ),
    SELECTCOLUMNS(
        VALUES(Period[Month]),"Month",[Month]
    )
)

The result is a table with each Lease ID mapped against each Month. I can't claim to understand exactly how the functions work, and it's not the outcome I thought I needed, but it allows me to achieve exactly what I set out to do.
I've accepted Pratik Bhavsar's answer because it effectively accomplishes the same thing as the work around I implemented. Pratik's solution might be better than what I eventually landed on, but I need to have a closer look at how the two compare.

A: The following DAX will give you a table with all buildings mapped against all rows in the period table, eliminating the requirement of a relationship.
SiteToPeriod =
CROSSJOIN(
    SELECTCOLUMNS(Sites1, "Building name/label", Sites1[Building name/label]),
    Period
)


text:
Q: JTS server unable to fetch root service document for other CLM Apps I am staging our CLM test environment with Prod data with version V6.0.3 and iFix011a .If I access the below uls, I see server rename is completed for all the apps ccm,qm,rm, rs and dcc
https:///app_name/rootservices
https:///app_name/appServerRenameStatus
But server rename status is not updated in JTS UI. As per jts.log JTS is unable to fetch root services document dor all apps and returs HHT code 500. Below is the excerpt of the error.
2018-06-05 16:50:07,135 [                     Thread-64]  INFO ping.internal.ServerRenameOverallStatusRestService  - Server rename details:Unable to contact https:///dcc/rootservices : org.apache.http.HttpException: While fetching the root services document from "https:///dcc/rootservices" a "500" HTTP status code was received
        at com.ibm.team.jfs.app.discovery.utils.RootServicesUtil.parseResponse(RootServicesUtil.java:834)
        at com.ibm.team.jfs.app.discovery.utils.RootServicesUtil.fetchRootServices(RootServicesUtil.java:785)
        at com.ibm.team.jfs.app.discovery.utils.RootServicesUtil.access$0(RootServicesUtil.java:747)
        at com.ibm.team.jfs.app.discovery.utils.RootServicesUtil$CachedResourceManager.run(RootServicesUtil.java:205)
        at org.eclipse.core.internal.jobs.Worker.run(Worker.java:54)
2018-06-05 16:50:07,147 [                     Thread-64]  INFO ping.internal.ServerRenameOverallStatusRestService  - Server rename details:Unable to contact https:///rs/rootservices : org.apache.http.HttpException: While fetching the root services document from "https:///rs/rootservices" a "500" HTTP status code was received
        at com.ibm.team.jfs.app.discovery.utils.RootServicesUtil.parseResponse(RootServicesUtil.java:834)
        at com.ibm.team.jfs.app.discovery.utils.RootServicesUtil.fetchRootServices(RootServicesUtil.java:785)
        at com.ibm.team.jfs.app.discovery.utils.RootServicesUtil.access$0(RootServicesUtil.java:747)
        at com.ibm.team.jfs.app.discovery.utils.RootServicesUtil$CachedResourceManager.run(RootServicesUtil.java:205)
        at org.eclipse.core.internal.jobs.Worker.run(Worker.java:54)
2018-06-05 16:50:07,147 [                     Thread-64]  INFO ping.internal.ServerRenameOverallStatusRestService  - Server rename details:
The following server rename status was received from the application:
        Application Name: /ccm
        Percent Complete: 0
        State: COMPLETED
        Result: ERROR
        Result Message: CRJAZ2373E The server could not retrieve the server rename status for application "/ccm". Please consult the log files for more details
2018-06-05 16:50:07,148 [                     Thread-64]  INFO ping.internal.ServerRenameOverallStatusRestService  - Server rename details:
The following server rename status was received from the application:
        Application Name: /qm
        Percent Complete: 0
        State: COMPLETED
        Result: ERROR
Any idea why JTS is unable to fetch the root services for other apps?

A: We faced the same issue while we were doing server rename.

*

*the first time we completed the steps with one final error at the end.

*the second time when we tried to redo the serverRenameStatus was showing the same error as the one that you mentioned.

Solution: place the mappingEvent file in /conf/jts and redo the serverRenameStatus and it will work like a charm.
mappingEvent file disappears from jts once the serverRenameStatus is completed.


text:
Q: How to parse through a list in Python using Regex I am trying to parse through a list of 1400+ emails and each word is a part of the list. I'm using Python 3.4. I need to filter out the following words:

*

*The output should only contain words with letters that are are 4
letters or longer (no numbers)

*The output should remove common words (stop words such as 'and', 'but', 'they', etc)

*The output should remove common words in the output
that are not meaningful for the word cloud('sakai', 'email', 're: ').

Thus a sample list looks like the following:
    words = ['re:', 'sakai:', 'which', 'code', 'base', 'to', 'use', 'in',
    'production:', 'maintenance', 'branch', 'or', 'release', 'tags']

My question is how do I eliminate the specified list items  from given 3 rules and remove them from words()?
I tried this:
import re

for word in words:
    pattern = re.match('*sample removing stop words*', word)
    try:
        if pattern:
            words = words.remove(word)
            continue
    except TypeError:
        continue

But every time I get a 'None', I get this error:
TypeError: 'NoneType' object is not iterable

Therefore the words() list doesn't change. How can I change words() list to get rid of words specified above?


text:
Q: Do I have to specify $x \in I$ for this limit? Let $a > 0$ and $I = (0,a)$. I want to prove using the definition of limit that $$\lim_{x\to c} x^2 = c^2$$ for all $c \in I$.
Let $\varepsilon > 0$ be given. Since this inequality $|x^2 - c^2| \leq 2a|x - c|$ holds for all $x,c\in I$, I can take $\delta = \varepsilon/(2a)$ as long as $x\in I$. Can I just say that $x \in I$ or  is it better to choose $$\delta = \inf \{c, a - c, \varepsilon/(2a)\}?$$
I have solve the more general problem (that is for all $c\in \mathbb{R}$) with another approach. Just curious for this one.

A: You need to select a value for $\delta$ which satisfy the definition.
I think that $\delta = \frac{\varepsilon}{2a}$ is not a good choice since, for example, for $a=\frac12$ we obtain $\delta = \varepsilon$  which does not satisfy the definition.
Indeed suppose $c=\frac12$ and $x=\frac12+k\varepsilon$ where $k\in(0,1)$, thus:
$$x^2=\frac14+k^2\varepsilon^2+k\varepsilon\implies x^2-\frac14=k^2\varepsilon^2+k\varepsilon=\varepsilon(k^2\varepsilon+k)>1 \quad \forall k\in(k_0,1)$$
The value of $k_0$ can be easily found by the condition
$$k^2\varepsilon+k>1\implies k^2\varepsilon+k-1>0\implies k>k_0=\frac{\sqrt{1+4\varepsilon}-1}{2\varepsilon} $$
plot of $k_0=\frac{\sqrt{1+4\varepsilon}-1}{2\varepsilon}$
You can proceed as follow.
We need to show that
$$\forall \varepsilon > 0 \quad \exists\delta>0 \quad0<|x-c|<\delta\implies|x^2-c^2|<\varepsilon$$
Let consider
$$|x^2-c^2|<\varepsilon\iff-\varepsilon < x^2-c^2< \varepsilon\iff c^2-\varepsilon < x^2< c^2+\varepsilon$$
Case 1: $c^2-\varepsilon\leq0$
$$c^2-\varepsilon < x^2< c^2+\varepsilon\iff0<x<\sqrt{c^2+\varepsilon}\iff-c<x-c<\sqrt{c^2+\varepsilon}-c$$
$$\iff|x-c|<\delta=\min\{|c|,\sqrt{c^2+\varepsilon}-c\}$$
Case 2: $c^2-\varepsilon>0$
$$c^2-\varepsilon < x^2< c^2+\varepsilon\iff\sqrt{c^2-\varepsilon}<x<\sqrt{c^2+\varepsilon}$$
$$\iff\sqrt{c^2-\varepsilon}-c<x-c<\sqrt{c^2+\varepsilon}-c$$
$$\iff|x-c|<\delta=\min\{c-\sqrt{c^2-\varepsilon},\sqrt{c^2+\varepsilon}-c\}=\sqrt{c^2+\varepsilon}-c$$

A: It's probably better to choose the delta you gave based on $\inf$ (or, equivalently, $\min$, since it's over a finite set), and then show that that implies $x \in I$. Since the domain of the function (seemingly) is $\mathbb{R}$, not $I$, nothing in the definition of the limit guarantees $x \in I$.
(Note that if you had a closed interval $I = [0,a]$, your approach would not work, even though your inequality still holds for all $x,c \in I$! So I think you do have to justify assuming $x \in I$.)