What is /Library/StagedExtensions for and how to remove extensions

Question: I'm trying to uninstall Parallels completely from macOS High Sierra.
I removed everything from the disk except some Parallels extensions that are stored under /Library/StagedExtensions/Parallel Desktop.app
I think the location has to do with user approved extensions, but I'd like to find a way to remove/uninstall those too. If I try to delete the extensions it says operation not permitted despite the root rights.
Any idea?
Comment: have you tried to check if the kernel extension is loaded or in kernel using command kextstat? run this kextstat command and check if you have any of the parallel extension.
Answer: There is new way to clear the StageExtensions folder as following
sudo kextcache --clear-staging

This command will clear the /Library/StageExtensions folder. We dont need to go to recovery mode and delete manually this folder in case there are some permission errors while installing software.
Comment: For me it did not remove the directory permanently. After the next reboot everything was back.
Answer: In my case, deleted kext disappears from StagedExtensions when you invalidate kext cache.
sudo rm -rf /Library/Extensions/Parallel\ Desktop.app # check if the name is correct so you don't delete some other kext
sudo kextcache -invalidate /
# now you should not see your deleted kext here
ls /Library/StagedExtensions/

UPDATE 2019:
See man page for full details: man kextcache.
Excerpt related to -invalidate, -i for short:
 -i os_volume, -invalidate os_volume
              Rebuild out-of-date caches and update any helper partitions
              associated with os_volume.

              This option mimics sudo touch /System/Library/Extensions on
              os_volume.  If kextcache cannot find or make sense of
              os_volume/usr/standalone/bootcaches.plist, the volume is treated
              as if no caches need updating: success is returned.

There are also new options:
     -clear-staging
          Clears the kernel extension staging area by removing all staged content.

     -prune-staging
          Prunes the kernel extension staging area by removing all kernel extensions
          no longer present in their original location.

Looks like  -prune-staging removes only the deleted extensions, shaving little bit of time from the next kext cache rebuild.
See https://www.unix.com/man-page/mojave/8/KEXTCACHE/ for Mojave man page, which contains these new options.
Comment: This only answers half the question, it doesn't explain what this folder is for
Comment: Well... Only Apple knows why is it called like that, but it's, by the looks of it, used for kexts which are "staged", e.g. are cached, verified and ready for next boot. Kexts are copied there after successful boot - e.g. they are verified and approved/staged for next boot. At least that's what I take from it.
Answer: sudo kextcache --clear-staging
Was in folder HD/Library/
Cheers
Edit: Formatting
Edit2: I believe that Parallels writes some files directly into the bootloader/kernel. After running the command from the CMD+R hold restart Disk Utility Terminal the extension was removed from /Library .
I hope this makes sense.
Comment: Please give an explanation on how and why your solution works for the question.
Answer: I had a similar issue in trying to uninstall the TelestreamAudio.kext for ScreenFlow. What might be happening is that the kext in StagedExtensions is currently in use or protected while you're in regular mode. Once you get into Recovery mode, you can delete it without disabling System Integrity Protection. The following steps worked for me, though please use caution.

Click the  menu. Select Restart
Hold down command-R to boot into the Recovery System
Choose Disk Utility from the Recovery Menu
Within Disk Utility click on your main hard drive (e.g. Macintosh HD) and then click on Mount
Exit out of Disk Utility
Click Utilities in the menu bar and select Terminal
Use the following commands:

.
cd /Volumes/Macintosh\ HD/Library/StagedExtensions/Library/Extensions/
rm -rf NAME_OF_EXTENSION.kext

Close the Terminal app
Click the  menu and select Restart

From there on, I was able to reinstall ScreenFlow's audio kext and it worked. It may also help you completely remove the Parallels kext.
Answer: If you've already deleted the extensions from /Library/Extensions, open the Terminal app from Launchpad, copy/paste the command below and press Enter to run it:
sudo kextcache -prune-staging
As mentioned in another comment, this will only remove the kernel extensions that are no longer present in their original location, i.e., /Library/Extensions.
The extensions you deleted from /Library/Extensions will then disappear from /Library/StagedExtensions/. It won't affect your other kernel staged extensions.
/Library/StagedExtensions/ is an intermediate area where your extensions live after you start your session (like a cache). The staging area won't be immediately affected if changes are made to /Library/Extensions, which I believe is meant to improve stability and security.
Answer: This is because of the System Integrity Protection (SIP).
You can disable it (not recommended) and remove the kext manually.
(from https://www.imore.com/el-capitan-system-integrity-protection-helps-keep-malware-away)

Click the  menu. Select Restart...
Hold down command-R to boot into the Recovery System.
Click the Utilities menu and select Terminal.
Type csrutil disable and press return.
Close the Terminal app. Click the  menu and select Restart....

If you decide later you want to re-engage SIP (and I earnestly hope that you do), repeat these steps, use csrutil enable instead.
Comment: No, above is not the solution to a problem. Customer wont disable SIP and remove it. I guess this is serious bug from apple
Comment: I have already reported this to apple but i haven't got any response from them. If they reply, ill let you know guys


SDL está sempre gerando tela transparente. c++

Question: criei e compilei um programa em SDL, não sei o motivo, mas ele sempre retorna uma tela transparente, quando o esperado é uma tela branca.

Estou utilizando o seguinte código:
<code>#include <SDL.h>

int main(int argc, char *argv[])
{
    SDL_Window *window;
    SDL_Surface *screenSurface;

    SDL_Init(SDL_INIT_VIDEO);

    window = SDL_CreateWindow("Tutorial", 100, 50, 320, 480, SDL_WINDOW_SHOWN);
    screenSurface = SDL_GetWindowSurface(window);

    SDL_Delay(5000);

    SDL_FreeSurface(screenSurface);
    SDL_DestroyWindow(window);
    SDL_Quit();

    return 0;

}
</code>
E estou compilando com este comando no cmd:
<code>g++ "C:\Users\DANI\Documents\Learn\SDL\Test.cpp" -o Test.exe -I "C:\MinGW\include\SDL2" -mwindows -lmingw32 -lSDL2main -lSDL2
</code>
Answer: Para desenhar na janela temos de usar o SDL_Renderer. A função SDL_RenderClear preenche o background.
<code>#include <SDL.h>

int main(int argc, char* argv[])
{
    SDL_Window* window;
    SDL_Surface* screenSurface;

    SDL_Init(SDL_INIT_VIDEO);

    window = SDL_CreateWindow("Tutorial", 100, 50, 320, 480, SDL_WINDOW_SHOWN);
    screenSurface = SDL_GetWindowSurface(window);

    SDL_Renderer* renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED);
    SDL_SetRenderDrawColor(renderer, 255, 255, 255, 255);
    SDL_RenderClear(renderer);
    SDL_RenderPresent(renderer);

    SDL_Delay(5000);

    SDL_FreeSurface(screenSurface);
    SDL_DestroyWindow(window);
    SDL_Quit();

    return 0;
}
</code>


PHP to run jquery script every 'x' minutes

Question: I've been looking through multiple questions but I didn't understand much (it figures since all I know in PHP are contact forms and basic stuff) from what seemed to be similar questions.
I only need a php script to run on the server side and run a jquery script every 'x' minutes...in jquery I could simply set an interval and that would be it but it will not run if the page isn't accessed and I want it to run continuously.
If you would please have the patience to give an example and maybe explain the principle a little...Thanks
Comment: Look into running a cron job on your server.
Comment: I would like to know what you are trying to achieve before answering this question.
Comment: we need some extra info: you have a webpage that has a jquery script inside it that you want to run as if the page were accessed by a browser? or do you have some server side jquery script?
Comment: @maartenVenema I am just creating a jquery script that tests if the website is online by checking if a called image loads. I want to perform that test every hour or so. That's what I want to use it for.
Comment: hi please try the setInterval() method in Jquery, You can use this method to run after a certain interval
Comment: @alexalex jquery se afla in interiorul unei pagini separate. Mersi
Comment: @Alin Ok so why not do it all serverside and use the interval methods of Javascript?
Comment: @robin Sorry to say but setInterval() will not work until the page is accessed!
Comment: you can test the online-status of a website without jQuery. You can set up a cronjob with runs a php-script every hour. Have a look [here](http://css-tricks.com/snippets/php/check-if-website-is-available/)
Comment: why dont you write a code to refresh the php page after every hour
Comment: @empiric, that looks promising, I'll go by and read it and see where it takes me :)
Comment: @empiric Well thanks, I tested one of the scripts and it's working nice ^^ I see it's a felony here to not know something and ask for guidance...have a great day !
Comment: use cron for this ;)
Comment: after getting info about how things work in comments you can update your question to reflect what you need so you won't attract negative score.
Answer: In according to your comment, that you want to check wether a website is online or not here a little example:
ini_set("default_socket_timeout","05");//see 1)
set_time_limit(5); //see 1)

$f=fopen("http://www.example.com","r"); //see 2)

$r=fread($f,1000); //see 3)
fclose($f); // see 4)

if(strlen($r)>1) { //see 5)
    echo "Online";
}
else {
    echo "Offline";
}

Notes
1) set stream-timeout to 5 seconds. If a site is offline the response should be send directly so there is no need to check over a long time
2) opens the url (only-read)
3) reads the first 1000 charaktars of the opend url (binary)
4) close the connection
5) check if data could be readed. If there is data existing the website could be opened
To install a cronjob which executes the php-script you can use:
1 * * * * /usr/bin/wget -q -O /var/log/website_check.log http://www.webiste.com/pathTo/check.php

This will execute your php-script every our via wget and write the output into a log-file.
Please check the path for the cron, they can be different on your server. The url to the php-script can be changed to a absolute path, too. (e.g. var/www/webroot/check.php)
Comment: Hey, thanks, will certainly test it. Also thanks for not being a cocky know-it-all with those who simply have almost no knowledge of back-end programming. Giving you a +1 and if this works I will also accept the answer. :)
Answer: What needs to be achieved is to verify if a website/webpage is up.
There is no point to run a cron job that will run a wget that will run a php script! If you can run a cron job I'll assume you are on a unix server and can use a bash script (win-bash will probably run on windows too but I'm not familiar with that)
There is a nice thread on serverfault.com that is looking for almost the same thing: script to automatically test if a web site is available.
and one script that you can easily customize to do what you want is this one:
#! /usr/bin/sh

function check {
 if [ $? -ne 0 ] ; then
     echo "Error occurred getting URL $1:"
     if [ $? -eq 6 ]; then
         echo "Unable to resolve host"
     fi
     if [$? -eq 7 ]; then
         echo "Unable to connect to host"
     fi
     exit 1
 fi

}
curl -s -o "/dev/null" $1
check;

script and extra info from http://answers.google.com/answers/threadview/id/276934.html user: wengland-ga

In a nutshell, call the script with the HTTP URL to check.  curl will
  silently try to get the file and send it to /dev/null.  If it fails,
  it'll set the exit code, which is checked in the 'check' function.
You may have to play with the curl parameters to make it work just how
  you want it.  You can also redirect the curl output to a temp file,
  and use grep and filesize checks to make sure the content is correct.
  Read the man page for details.
Search Strategy:
man curl
  ://www.google.com/search?hl=en&lr=&ie=ISO-8859-1&q=man+curl&btnG=Google+Search
bash check exit code
  ://www.google.com/search?q=bash+check+exit+code&sa=Google+Search
bash +if syntax
  ://www.google.com/search?q=bash+%2Bif+syntax&hl=en&lr=&ie=UTF-8&start=10&sa=N

It's a little bit of reading but this is the way I do it (I feel it's as no overkill as it gets)
On some servers curl might not be installed so you'll have to install it
Comment: Well thanks, I'll get into it right away, there's a lot of reading for me to do if I want to understand all of this properly. +1


What is the fundamental group of $RP^{2}$ # $\cdots$ # $RP^{2}$

Question: I want to know about fundamental group of $RP^{2}$ # $\cdots$ # $RP^{2}$ by Seifert-Van Kampen theorem.
In my guessing, that is $\langle a_1, a_2 ,... a_n | a_1^{2}a_2^{2}\cdots a_n^{2}=1\rangle$.
Is this correct?
Comment: Hint: $\Bbb{R}P^2\#\Bbb{R}P^2\#\Bbb{R}P^2$ is homeomorphic to $T^2\#\Bbb{R}P^2$.
Comment: Use the nice CW structure of $n\#\mathbb{RP}^2$, or compute its (co)homology and use the classification of closed surfaces.
Answer: Assuming that it is a connected sum of n copies of the projective plane, yes,
that is a correct presentation for the fundamental group.  One thing to keep in mind is that just because you know a presentation of a group, you don't necessarily 'know the group'.  As an interesting exercise, can you tell if these groups are different for different values of n?
BTW, you don't need to know about CW complexes or cohomology or the classification of surfaces to do this problem.


A better formula for derivative of determinant

Question: I need to evaluate the derivative of the function $X \mapsto \operatorname{det}X$, where $X$ is an $n\times n$ real matrix. I already proved that if $f: \mathbb{R}^{n}\times \cdots \times \mathbb{R}^{n} \to \mathbb{R}^{m}$ is a $p$-linear map, then:
$$f'(x_{1},...,x_{p})(h_{1},...,h_{p}) = \sum_{i=1}^{n}f(x_{1},...,x_{i-1},h_{i},x_{i+1},...,x_{p}).$$
Since $\operatorname{det}X$ is an $n$-linear map of its rows $\varphi_{1},...,\varphi_{n}$, $\varphi_{i}\in \mathbb{R}^{n}$, it follows immediately from the last expression that, if $f(X) = \operatorname{det}X$ and $H$ is some $n\times n$ real matrix with rows $h_{1},...,h_{n}$:
$$f'(X)H = \sum_{i=1}^{n}\operatorname{det}(X|_{h_{i}})$$
where I denoted by $X|_{h_{i}}$ the $X$ matrix with the $i$-th row replaced by $h_{i}$.
So, my question is: is there another way to express $f'(X)H$? I think there must be some nicer way to express it, so to get some sort of formula.
Answer: Using the formula you got, for $X = I_n$ the identity, you get :
$$\text df(I_n)H = \operatorname{Tr}( H)$$
Then, for $X$ an invertible matrix, you have :
\begin{align}
f(X+H) &= \det(X+H) \\
&= \det(X)\det(I_n+X^{-1}H) \\
&= \det(X) \Big( 1+\operatorname{Tr}(X^{-1}H) + o(\|H\|)\Big)
\end{align}
and therefore :
$$\text d f(X)H = \det(X)\operatorname{Tr}(X^{-1}H) = \operatorname{Tr}(\operatorname{Cof}(X)H)$$
where $\operatorname{Cof}(X)$ is the cofactor matrix of $X$. Since it is polynomial in the coefficient of $X$, the last formula extends by continuity to any matrix $X$.


java: the import data cannot be resolved - import data.Frame

Question: I'm using some code from my university's lecturer for a new project and everything seems to be working except for that one little piece, where I want to import "data.Frame" and I just don't know what's missing so my code would function. If anyone knows the solution or could give me an alternative so I could import the needed "Frame" - would be awesome!
I'm using eclipse!
The code is:
import java.io.FileWriter;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;

import data.Frame; // HERE IS THE PROBLEM!

/**
 * Compares the annotations of two or more annotators and groups them together,
 * before they are written to a csv file.
 */
 public class ComparisonWriter
{
private String content;

private final int A1 = 1;
private final int A2 = 2;
private final int A3 = 3;
//  private final int A4 = 4;

private int numberOfAnnotators = 3;

String outputFileName = "data/200Saetze/Gruppe 1/comparison_buchpreis2_alle.csv";

String inputA1 = "data/200Saetze/Gruppe 1/Daniela/buchpreis2.xml";
String inputA2 = "data/200Saetze/Gruppe 1/Inga/buchpreis2.xml";
String inputA3 = "data/200Saetze/Gruppe 1/Stefan/buchpreis2.xml";

public ComparisonWriter()
{
    content = "SatzID;Annotator;Frame;SE;exact;partial;Source;Annotator;SourceString;" +
            "exact;exact ohne leer;exact ohne leer (SE);partial;koreferent;SourceFlag;exact;Target;Annotator;" +
            "TargetString;exact;exact ohne leer;exact ohne leer (SE);partial;koreferent;TargetFlag;;FrameFlag";

    AnnotationReader annotationReaderA1 = new AnnotationReader(inputA1);
    Map<String, List<Frame>> seAnnotator1 = annotationReaderA1.getAllSubjectiveExpressions();
    AnnotationReader annotationReaderA2 = new AnnotationReader(inputA2);
    Map<String, List<Frame>> seAnnotator2 = annotationReaderA2.getAllSubjectiveExpressions();
    AnnotationReader annotationReaderA3 = new AnnotationReader(inputA3);
    Map<String, List<Frame>> seAnnotator3 = annotationReaderA3.getAllSubjectiveExpressions();

    Set<String> sentences = seAnnotator1.keySet();
    for (String sentence : sentences)
    {
        //add leading zeros
        content += "\n\n" + sentence + ";" + annotationReaderA1.sentenceStrings.get(sentence);

        //add the annotations in a sorted order
        Map<Integer, List<Frame>> allFramesInSentence = new HashMap<Integer, List<Frame>>();
        allFramesInSentence.put(A1, seAnnotator1.get(sentence));
        allFramesInSentence.put(A2, seAnnotator2.get(sentence));
        allFramesInSentence.put(A3, seAnnotator3.get(sentence));
 //         allFramesInSentence.put(A4, seAnnotator4.get(sentence));
 //
        //get the one with the most annotations
        int largest = getIndexOfLargestList(allFramesInSentence);

        if(largest == 0)
            continue;

        for (int i = 0; i < allFramesInSentence.get(largest).size(); i++)
        {
            Frame frame = allFramesInSentence.get(largest).get(i);
            content += "\n\n;A" + largest + ";" + frame;
            frame.setConsidered(true);
            findOverlappingAnnotations(allFramesInSentence, largest, frame);
        }

        //Check, if there are not considered annotations in one of the frame lists for that sentence.
        for (int a = 1; a <= 4; a++)
        {
            List<Frame> frameList = allFramesInSentence.get(a);
            if(a != largest && frameList != null)
            {
                for (Frame frame : frameList)
                {
                    if(frame.isConsidered() == false)
                    {
                        content += "\n\n;A" + a + ";" + frame;
                        frame.setConsidered(true);
                        findOverlappingAnnotations(allFramesInSentence, a, frame);
                    }
                }
            }
        }
    }

    writeContentToFile(content, outputFileName, false);
}

/**
 * Find overlapping annotations.
 * @param frames - list of frames, potentially overlapping with the given one.
 * @param largest
 * @param frame - frame in question.
 */
private void findOverlappingAnnotations(Map<Integer, List<Frame>> frames,
        int largest, Frame frame)
{
    for (int a = 1; a <= 4; a++)
    {
        //If j is not the current largest frame list and there are annotated frames
        //in from this annotator (a)
        if(a != largest && frames.get(a) != null)
        {
            for (Frame compareFrame : frames.get(a))
            {
                addOverlappingAnnotations2Conent(frame, a, compareFrame);
            }
        }
    }
}

/**
 * Add overlapping Annotations (measured by matching ids) to the content attribute.
 * @param frame
 * @param a - Annotator index
 * @param compareFrame
 */
private void addOverlappingAnnotations2Conent(Frame frame, int a,
        Frame compareFrame)
{
    List<String> terminalIDs = compareFrame.getTerminalIDs();
    for (String id : terminalIDs)
    {
        if(compareFrame.isConsidered())
            break;
        if(frame.getTerminalIDs().contains(id))
        {
            //Write it to the content
            content += "\n;A" + a + ";" + compareFrame;
            compareFrame.setConsidered(true);
            break;
        }
    }
}

/**
 * Get the index of the largest frame list in the map.
 * @param frames -  a map with all the frames for each annotator (key: annotator)
 * @return The index of the largest frame list.
 */
private int getIndexOfLargestList(Map<Integer, List<Frame>> frames)
{
    int size = 0;
    int largest = 0;

    for(int a = 0; a <= numberOfAnnotators; a++)
    {
        if(frames.get(a) != null)
        {
            if(frames.get(a).size() > size)
                largest = a;
        }
    }

    return largest;
}

Answer: You need to get a copy of the source code or class file for the Frame class and add it to your project.  The source code should be in a file called Frame.java.
Comment: Can you shed some light on why the source code is required and not just the class file? im holding my negative vote till then.
Comment: The class file would work too.  I edited my answer to reflect that.
Answer: You basically need Frame class in your classpath. If you have this class in some jar, then add that jar to your classpath.


Use TinyMCE in an overlay (jQuery Tools-Overlay)

Question: I want to use TinyMCE editor in a overlay dialog.. Is that possible?
I have latest version TinyMCE and Jquery Tools Overlay.
JQuery Tools Overlay: http://flowplayer.org/tools/demos/overlay/index.html
Comment: Have you tried? Where did you fail?
Comment: Yes, I've used normal way to get it work..

Example:  <-- this is inside the overlay.. and then I use tinyMCE.init function get it work work.. nothing happen.. no js error..
Answer: I ran into a few issues with this, apparently tinymce doesn't play nicely with hidden elements, and gets confused when you write over elements it's attached to.  Anyway, got it to work by using overlay's hooks, making a synchronous js call (this is the crucial part), and detaching tinymce before closing it.  Code:
<code>$(".overlayed").overlay({
  onBeforeLoad: function() {
    var wrap = this.getOverlay().find(".contentWrap");
    var url = this.getTrigger().attr("href");
    $.ajax({
      url: url,
      async: false,
      dataType: "html",
      type: "GET",
      success: function(data){
        wrap.html(data);
      }
    })
  },
  onLoad: function(){
    if($('#overlay .mceEditor').length > 0){
      tinyMCE.execCommand('mceAddControl', false, $('.mceEditor').attr('id'));
    }
  },
  onBeforeClose: function(){
    if($('#overlay .mceEditor').length > 0){
      tinyMCE.execCommand('mceFocus', false, $('.mceEditor').attr('id'));
      tinyMCE.execCommand('mceRemoveControl', false, $('.mceEditor').attr('id'));
    }
    this.getOverlay().find(".contentWrap").html("");
  }
});
</code>
Code could be more elegant but works 100% of the time ;)
Hope this helps someone!


Can constructorless classes have their methods called without instantiation?

Question: Can I avoid initializing this?
I have a simple factory with no constructor. I use it like this:
var slf = new GenericSelectListFactory();
vm.Works = slf.getWorkgsl(0);
vm.Cars = slf.getCargsl(0);

I can also use it like this:
vm.Cars = new GenericSelectListFactory().getCargsl(0);

Is there any way to use it without the new keyword?
vm.Cars = GenericSelectListFactory.getCargsl(0);

Comment: If you don't want/need an instance, why not make the method `static`?
Comment: It would also make sense to make the class `static`, if you only plan on it having static members.
Comment: Also note that there's a difference between "constructorless" classes and "stateless" classes. Only static classes truly have no constructor, non-static ones have an implicit constructor generated by the compiler.
Comment: @zneak - You can have a static constructor. ;)
Comment: From the MSDN article [Using Constructors](http://msdn.microsoft.com/en-us/library/ms173115.aspx) `Unless the class is static, classes without constructors are given a public default constructor by the C# compiler in order to enable class instantiation. For more information, see Static Classes and Static Class Members (C# Programming Guide).`
Answer: Make the method of your class static.
class GenericSelectListFactory
{
   public static List<Cars> getCargsl()
   {
      // your logic here
   }

}

Comment: This allows the call to be made: `var cars = GenericSelectListFactory.getCargsl();`. Thanks :)
Answer: without "new" you should mark method as static
Answer: A class without a constructor is assigned a default constructor by the compiler, mainly to eliminate the need for empty constructors:

Unless the class is static, classes without constructors are given a public default constructor by the C# compiler in order to enable class instantiation.

If you want to access the methods without initializing the class, make the method(s) static. In doing this though, you should ensure that the methods are thread safe.
Answer: you can make the functions static.


Executar scripts de diferentes diretorios

Question: Tenho uma série de rotinas para executar diariamente no Python.
Gostaria de um código para executar todas em um scipts apenas.
Ex:

#rotina 1
r1 = C:\Users\rotina1\rotina1.py
r1.execute

#rotina 2
r2 = C:\Users\rotina2\rotina2.py
r2.execute

Existe algo do tipo? Me ajudaria muito.
Comment: faz um script do powershell
Answer: Para rodar scripts Python utilizando outro script Python você pode utilizar a biblioteca os.
#importando biblioteca
import os

Com a função os.system() é possível utilizar comandos do sistema operacional:
os.system('<<comando>>')

logo para a execução dessas rotinas pode ser executada com o código abaixo:
*WINDOWS
import os
r1 = 'C://Users//rotina1//rotina1.py'
r2 = 'C://Users//rotina2//rotina2.py'

rotinas = [r1, r2]

for r in rotinas:
    os.system(f'python {r}')

Para sistemas UNIX o comando provavelmente será necessário específicar a versão do python instalada no seu computados, ficando da seguinte maneira:
Exemplo Python3.X:
import os

r1 = 'C://Users//rotina1//rotina1.py'
r2 = 'C://Users//rotina2//rotina2.py'

rotinas = [r1, r2]

for r in rotinas:
    os.system(f'python3 {r}')

Espero ter ajudado :)


Mongodb autoConnectRetry option in connection string is not working with C# driver

Question: I have a quick questions here. I am using mongodb with C# and Java. Connectionstring that i use is:
mongodb.domain.com/?autoConnectRetry=true

The same connection string is working with Java but not with C#. I saw many posts around this that, if we remove autoConnectRetry option it works fine.
Looked at the logs and saw that its erroring out with below exception
System.ArgumentException: Invalid option 'autoConnectRetry'.
Parameter name: url
   at MongoDB.Driver.MongoUrlBuilder.Parse(String url)
   at MongoDB.Driver.MongoUrl..ctor(String url)
   at MongoDB.Driver.MongoUrl.Create(String url)
   at MongoDB.Driver.MongoServer.Create(String connectionString)

Is there any alternative that can make this work?
I am using .NET Framework 3.5 and Mongodb C# driver v 1.0
Answer: There is just no such option ("autoConnectRetry") in C# MongoDb driver, while there is in Java, so you will have to implement retry logic yourself. If you just want to use the same connection string for both and don't care about retry logic - I think that in current version of the driver it no longer throws InvalidOperationException on unknown options.


What is the meaning of this notation of matrix?

Question: I find it in a proof, and I don't understand at all.
"... an orthogonal matrix $D$ satisfying:
$D=[d_1,d_2, \dots,d_n]$ , $d_1=\frac{1}{\sqrt{n}}\mathbb{1}_n $"
Any help is appreciated!
Answer: $D$ has $n$ columns. The $j$-th column of $D$ is $d_j$. The symbol $\mathbb 1_n$ means a vector containing $n$ ones. So, $d_1$, the first column of $D$, is equal to $\frac1{\sqrt{n}}(1,\ldots,1)^T$.
Comment: This is what i thought, but in this case the matrix is not orthogonal
Comment: You cannot tell whether it is orthogonal just knowing the first column.  It could well be orthogonal with those specifications.
Comment: Oh, thanks for the clarification!


Solving $\arccos (x) +\arccos (2x)=\frac{3\pi}{4}$

Question: $\arccos (x) +\arccos (2x)=\frac{3\pi}{4}$
$\implies \arccos (x)=\frac{3\pi}{4}-\arccos (2x)$
$\implies \cos(\arccos (x))=\cos(\frac{3\pi}{4}-\arccos (2x))$
$\implies x=\cos(\frac{3\pi}{4})\cos(\arccos (2x))+\sin(\frac{3\pi}{4})\sin(\arccos(2x))$
$\implies x=\cos(\frac{3\pi}{4})\cos(\arccos (2x))+\sin(\frac{3\pi}{4})\sin(\arcsin(\sqrt{1-4x^2}))$
$\implies x=-\frac{2x}{\sqrt{2}}+\frac{\sqrt{1-4x^2}}{\sqrt{2}}$
$\implies \sqrt{2}x=-2x+\sqrt{1-4x^2}$
$\implies x(\sqrt{2}+2)=\sqrt{1-4x^2}$
$\implies x^2(2+4\sqrt{2}+4)=1-4x^2$
$\implies x^2(4\sqrt{2}+10)=1$
$\implies x^2=\frac{1}{4\sqrt{2}+10}$
$x=\pm\sqrt{\frac{1}{4\sqrt{2}+10}}$
But $x=-\sqrt{\frac{1}{4\sqrt{2}+10}}$ does not satisfy the given equation.
$\therefore x= \sqrt{\frac{1}{4\sqrt{2}+10}}$
I am looking for other methods to solve this equation. I applied the formula to combine two $\arccos(x)$ functions into one $\arccos(x)$ function and on simplifying I obtained a complicated equation.
Answer: $$\arccos(y)>\dfrac\pi2$$ for $y<0$
Here what if $x<0\iff2x<0$
Answer: use that $$\arccos(x)+\arccos(y)=\arccos(xy-\sqrt{1-x^2}\sqrt{1-y^2})$$ for $$x+y\geq 0$$ and
$$2\pi -\arccos(xy-\sqrt{1-x^2}\sqrt{1-y^2})$$ for $$x+y<0$$
Comment: This is the same that they did, but hiding the use of cosine sum and $\sin\circ \arccos$ into a memorized formula.
Comment: i think it is not the same, or it is to late for me!


Understanding Pointer Behavior and Copy Elision in Object Returns Pre- and Post-C++17

Question: I'm trying to understand how pointers within objects behave when these objects are returned from functions, particularly in relation to copy elision and temporary object creation in C++ standards before and after C++17. Below is my code example:
struct A {
    void* p;
    A() : p(this) {}
    A(const A&); // Disable trivial copyability
};

A f() {
    A x;
    return x;
}

int main() {
    A a;  // OK: a.p points to a
    A b = f(); // Concern: b.p could be dangling and point to the x inside f
    A c = A(); // (until C++17) Concern: c.p could be dangling and point to a temporary
               // (since C++17) OK: c.p points to c; no temporary is involved
}

Specifically, my concerns are:
In A b = f();, is it correct that b.p could be a dangling pointer pointing to x inside f(), depending on whether the compiler applies RVO before C++17?
For A c = A();, I understand that in C++17, c.p points directly to c with no temporary involved. But prior to C++17, could c.p be a dangling pointer if a temporary object is created and then destroyed?
I would appreciate any clarification or insights into how these scenarios are handled in different C++ standards.
P.S. I specifically meant C++11 and C++14 as this code won't compile in C++03
Comment: I'd say as a rule of thumb: if it works with copy constructor and move constructor deleted for a class, it's safe. So `f` isn't safe, because it's NRVO. `A g() { return {}; }` on the other hand would be safe.
Comment: What you are describing in the code (the `f()` function) is NRVO, which is allowed but not required.  URVO is required as of C++17.
Comment: NRVO requires availability of move&|copy constructor as fallback strategy. URVO doesn't require that. So if it compiles with deleted copy+move constructor, it's not NRVO. The official term for copy elision is direct initialization, which informally means `this` equals the `addressof` final resultant object.
Answer: When a copy is elided, it means that the the source and destination objects are the same object.  There is no copy; that's the whole point.

In A b = f();, is it correct that b.p could be a dangling pointer pointing to x inside f(), depending on whether the compiler applies RVO before C++17?

No.  Because A's copy constructor isn't implemented, the only way for it to possibly be returned from f is via NRVO, in which case b and x are the same object.  Behind the scenes main passes a pointer to f into which f initializes its return object.  When (N)RVO is applied, main and f simply both use that storage directly as b and x, respectively, instead of f copying x into the return value and then main copying from the return value to b.

For A c = A();, I understand that in C++17, c.p points directly to c with no temporary involved. But prior to C++17, could c.p be a dangling pointer if a temporary object is created and then destroyed?

No.  Because A's copy constructor isn't implemented there's no way for a temporary to be copied to c.  That means that the only way the program could possibly compile is if the copy is elided and c is directly initialized.

Note that I don't think it's a good idea to rely on this behavior.  It would be very easy for someone to get a random link error (because NRVO didn't get applied in some situation) and change the copy constructor to A(const A&) {} to "fix" the problem, which could easily lead to dangling pointers.
Comment: @Sami Yes, that's correct.  See my answer on [this question](https://stackoverflow.com/questions/48955310/how-does-c-abi-deal-with-rvo-and-nrvo/48955636#48955636) for a bit more context.  The caller is always responsible for allocating space for the return object (in all calling convention's I'm familiar with, at least).
Comment: Thank you so much! Great explanations! The part you said behind the scenes main passes a pointer to f ... do you mean this ?"the compiler "passes a pointer" to the space allocated for b in the main function into the f function. When f constructs the object x, it actually constructs it directly in the space pointed to by this pointer — that is, where b will be in main. This way, x and b are essentially the same object, and no copy or move operation is needed to return x from f." and does the compiler always passes a pointer only if there is RVO or NRVO?
Answer:
is it correct that b.p could be a dangling pointer pointing to x inside
f(), depending on whether the compiler applies RVO before C++17?

There is no RVO (which is mandatory) here, but possibly NRVO (named return value optimization), which is not mandatory, so yes, it could very well be dangling if you enabled the copy constructor. Without it, it'll fail to link in case NRVO isn't selected.
Note: This is true in C++17 too! NRVO does not mandate that there will be copy/move elision of x -> b and if you = delete; the copy constructor, it will not compile even in C++17.

For A c = A();, I understand that in C++17, c.p points directly to c with no temporary involved. But prior to C++17, could c.p be a dangling pointer if a temporary object is created and then destroyed?

For C++17, that's correct. For C++14, the selected constructor must be accessible even if the call is elided, so in your case, it would fail to link if elision isn't selected by the compiler. If you = delete; the copy constructor, it'll fail to compile, even if it could elide the copy.
Comment: @Sami The `inline` keyword does not change the semantics of a function call at all.  It's not even really a suggestion to the compiler to inline calls to a function.  All the `inline` keyword does these days is allow you to define a function in multiple translation units without violating the ODR (as long as they're all identical).  Even if a function call _is_ inlined, it doesn't change the semantics of the call at all.
Comment: @MilesBudnek, you're really awesome! every time I ask questions here, you explain a concept really well and talk about nuances I have never heard of ! I've learned something new about 'inline'. thank you!
Comment: Thank you so much for the explanation! very helpful! i have a question:

if we have a copy and move constructor deleted and in the 'main' function we have
' A b = f(); ' and even if we defined f as inline 'inline A f(){}' , would we still get error in c++11 and c++14 because copy and move are not callable or because on inline it wouldn't cause any issue?! like instead of 'A b= f();' compiler turned it to 'A b;'? is it possible?
Comment: I think the inline keyword is considered a suggestion to the compiler, not an obligation, and it can choose to inline f() or not. If inlined, in C++17, it doesn't affect the outcome because of guaranteed copy elision, which allows the prvalue N() to be constructed directly in place as auto n in main. However, in C++11 and C++14, even with inlining and copy elision, a copy or move constructor must still be callable. if A's copy and move constructors are deleted, this results in a compile-time error in these earlier versions of the standard regardless of being inlined or not. am i right?


Computing Hessian in Python using finite differences

Question: I am computing the Hessian of a scalar field, and tried using numdifftools. This seems to work, but was quite slow so I wrote my own approach using finite differences.
Here is my code for the Hessian:
def hessianComp ( func, x0, epsilon=1.e-5):
    f1 = scipy.optimize.approx_fprime( x0, func, epsilon=epsilon)

    # Allocate space for the hessian
    n = x0.shape[0]
    hessian = np.zeros ( ( n, n ) )
    # The next loop fill in the matrix
    xx = x0
    for j in range( n ):
        xx0 = xx[j] # Store old value
        xx[j] = xx0 + epsilon # Perturb with finite difference
        # Recalculate the partial derivatives for this new point
        f2 = scipy.optimize.approx_fprime( xx, func, epsilon=epsilon)
        hessian[:, j] = (f2 - f1)/epsilon # scale...
        xx[j] = xx0 # Restore initial value of x0
    return hessian

I tried both on a test function using the following code:
def testfunction(x):
    return(x[0]**2 + x[1]**2)

out1 = hessianComp(testfunction, np.array([2.,2.]))
out2 = numdifftools.Hessian(testfunction)([2., 2.])

which returns
out1 = array([[2.00000017, 0.        ],
             [0.        , 2.00000017]])

out2 = array([[2.00000000e+00, 1.04776726e-14],
             [1.04776726e-14, 2.00000000e+00]])

So for my test function, it seems to give the correct result. If, however, I try doing it on the actual function for which I was computing the Hessian I am not getting the same results. The function for which I am computing the Hessian is a scalar field:
def lambda2Field(x):
    out = solve_ivp(doubleGyreVar, t_span=(0, T), y0=[x[0], x[1], 1, 0, 0, 1],t_eval=[0, T], rtol = 1e-10, atol=1e-10)
    output = out.y
    J = output[2:,-1].reshape(2,2,order="F")
    CG = np.matmul(J.T , J)
    lambdas, xis = np.linalg.eig(CG)
    lambda_2 = np.max(np.abs(lambdas))
    return lambda_2

out1 = hessianComp(lambda2Field, np.array([2.,2.]))
out2 = numdifftools.Hessian(lambda2Field)([2., 2.])

and gives the following:
out1 = array([[-1.53769104e+18, -2.20719407e+21],
             [-2.20719407e+21,  1.39720111e+27]])

out2 = array([[-1.53767292e+18,  2.27457455e-07],
             [ 2.27457455e-07, -9.43198781e+16]])

Interestingly, only the first element (1,1) of my Hessian matrix is the same. The other elements are off by quite a bit. Could somebody help me understand where this could be coming from?
Thanks!
Comment: Remark probably unrelated to error: You could compute the singular values also directly from `J` with the `svd` method. // A little more relevant: How sure are you that the maximum singular value is twice differentiable at this point?
Comment: Why don't you compute the Hessian symbolically?
Comment: @BarkingCat Since you are using finite differences to approximate the second derivatives, using the first order derivatives from python, why not approximate the second derivatives directly from function values? For instance,
$$ f''_{xx}(x,y) \approx \dfrac{f(x+h,y)-2f(x,y)+f(x-h,y)}{h^2}$$
$$ f''_{yy}(x,y) \approx \dfrac{f(x,y+h)-2f(x,y)+f(x,y-h)}{h^2}$$
Comment: In my experience, these numerical methods tend to be horribly unstable. The automatic differentiation approach tends to be vastly superior.
Answer: May I recommend using a slightly different approach? It is still a numerical approach, although not based on finite differences.
You can use automatic differentiation to calculate Hessians. Check out the autograd package in Python. The Hessian can be computed as the Jacobian of the gradient using the following snippet:
from autograd import elementwise_grad as egrad
from autograd import jacobian
import autograd.numpy as np

def func(x):
    return np.sin(x[0]) * np.sin(x[1])

x_value = np.array([0.0, 0.0])  # note inputs have to be floats
H_f = jacobian(egrad(func))  # returns a function
print(H_f(x_value))

This will give the output
$$
\begin{bmatrix}
0 & 1 \\
1 & 0 \\
\end{bmatrix}
$$
Answer: Use a two-point formula instead to compute the derivative, it's much more accurate. See numerical differentiation Wikipedia page.


Multiple relationships in Views Contextual Filters

Question: I use Views in every project, and its not that often that I run into a use case like this any more.
In the set up below, I have a Content type with two field collection fields (day guest and evening guest). I want to display the results of both field collection fields on the node, in the same view.
Both field collections share an "E-mail" field, and when a user enters their e-mail field, I want them to see their results, whether they have been added as a day guest, or an evening guest.
Here's the setup...

When I remove one of the two Contextual filters, the results show for the remaining field, and vice versa. But when both Contextual filters are added, I get no results.
Is there a way to do an AND or OR for Contextual filters?
Or in the Contextual filter options, a way to add multiple relationships like below?

While I know this is not possible in the default behaviour, it is a good example of what i'm trying to achieve, perhaps someone knows a decent workaround to the issue?
Comment: You was able to found solution for this?
Answer: Use this module:  https://www.drupal.org/project/views_contextual_filters_or
it gives you posibility to achive your needs
Comment: Welcome to Drupal Answers! Whilst this may theoretically answer the question, [it would be preferable](http://meta.stackoverflow.com/q/8259) to include the essential parts of the answer here, and provide the link for reference.


Create empty Corpus in textacy

Question: I want to create an empty corpus in textacy and later on fill it up with data via
corpus.add(doc)

But everytime I try to create an empty corpus I am not able to save it and instead I get this error:
IndexError: list index out of range

I tried both not giving any data when creating the corpus or giving None as data:
corpus = textacy.Corpus(lang=locale)
corpus = textacy.Corpus(lang=locale, data=None)
corpus.save(path) # this line results in the index error

It would be nice if anybody could help me :)
Answer: I have just tried this out myself. What is locale exactly? I have performed the following:

created spacy language object for german language with

nlp = spacy.load("de_core_news_lg")

and then passed it to

corpus = textacy.Corpus(nlp)
After that I was able to iterate through my documents and add them item per item.
However, I would not recommend doing this. I have performed two scenarios to process 15k short comments:

I first preprocessed my documents as a list and put it directly into textacy.Corpus(nlp, data=preprocessed_list). That took me around 22 s.
Performing the same logic, but by creating an empty corpus and adding each one item to it lasted 1 min 26 s.

Create empty Corpus in textacy


how to repeat group section in one page with using crystal reports?

Question: I am working on school management system and i want to print fee receipt of student with crystal report tool in vb.net with visual studio 2008. my requirement is to print fee receipt two time in one page after the receipt blank page are there. i want above receipt repeat in that blank section.
please help me
Answer: One way to handle this is a subreport. Place the subreport where you want the duplicate to appear, add subreport links to select which content you want displayed, and add the data sources, grouping levels, and so on.
The other solution is to provide a data source that returns two rows, like a SQL select statement or a dummy table. Join that to your data source and insert a grouping level for the field in the dummy table. I outlined it in more general terms in this answer: https://stackoverflow.com/a/7520428/893113
In other words, Crystal doesn't provide a way to do this automatically.
Comment: Please mark it accepted, if you don't mind, and upvote it if you like.


Why are cars allowed to unlap themselves during safety car period?

Question: As FIA indicates in Article 39.12 (sporting regulations 2017), lapped cars may unlap themselves once cars were lined up behind the safety car.

39.12 If the clerk of the course considers it safe to do so, and the message
  "LAPPED CARS MAY NOW OVERTAKE" has been sent to all teams via the
  official messaging system, any cars that have been lapped by the
  leader will be required to pass the cars on the lead lap and the
  safety car.

What is the purpose of this rule?
I don't see any benefit to drivers' safety. It also causes unfair competition in some cases. For example, Valtteri Bottas gained a big advantage by this rule in 2017 Azerbaijan Grand Prix.
Answer: There is another purpose to this rule besides lapped cars being mixed up between the leaders.
Consider this example:
We are in the 2nd half of the race. Two drivers (let's say, Hulkenberg and Perez) fight for P10, which is effectively a fight for a Championship point. They are far from the leader (almost a lap down). Perez is currently P11 and a few seconds behind Hulkenberg, who is P10. Perez is lapping a second a lap faster than Hulkenberg and so he's almost sure to catch Hulkenberg and overtake him before the end of the race.
The race leader catches up to Perez, who gets shown blue flags and lets the leader pass him. He is now lapped. At this moment, some accident happens and the safety car is deployed. It picks up the leader and other drivers line up behind him, including Perez, who's been lapped just before the safety car was deployed and so he's right behind the race leader. But Hulkenberg hasn't yet been lapped and so he is now allowed to do an entire lap and join the end of the queue behind the safety car. Now Hulkenberg effectively has entire lap's advantage over Perez (even though it was just a few seconds before the safety car period) and Perez will not be able to close that gap.
However, if the lapped cars are able to unlap themselves, Perez will also do an extra lap and join the queue just behind Hulkenberg, which means he will be able to fight Hulkenberg for 10th position.
Answer: F1 previously had this rule but it was removed because it was difficult to manage and potientially dangerous. Now there are new safeguards involved like drivers will only be allowed to overtake once they have all passed the pit entry twice (which will allow all drivers to pit if they want), lead drivers has to stay on the racing line once the order is given to allow cars to overtake, and will be allowed to weave again, to get heat into their tyres, when informed it is safe to do so. By Charlie Whiting FIA technical delegate
View of Andrew Shovlin, Senior Race Engineer at mercedes at 2012 is that before this rule was introduced (2010 and 2011 lapped cars were not allowed to overtake prior to a safety car restart), race leader get mixed up with back markers at the end of race. Depriving the spectators of an exciting finish as it allowed some cars to build good lead while their competitors were stuck in traffic. Making it confusing for those watching as the order of cars on track was not the actual race order.

This will have two important effects, firstly the cars directly behind the safety will line up in actual race order so when the race restarts they are in a position to overtake each other. Secondly, the majority of the field will be on the same racing lap, bunched together and with some of the cars on new tyres. Together with the DRS, this should create exciting racing in the midfield where cars on older tyres will be ahead of cars that have stopped for fresh rubber who are trying to battle their way up the order for points."

Other source: Formula 1 reddit
This view makes it easier to understand the purpose of this rule in some way, will add more sources later.


Grails 3.1 - Can't find codec for domain class

Question: I am not able to convert domain class into Basic DB object.
Below is my code:
def update_val
class_object.class.withNewSession { MongoCodecSession m ->
             update_val = m.pendingUpdates.find {
                it.key.name == d.class.getName()
            }.value[0]nativeEntry.regions[0]."${instance.getDbKey()}"[0]
            }

On below findOneAndUpdate function, I am getting error: "Can't find a codec for class class.domain". updateVal is returning as Domain Class object.
ClassName.class.findOneAndUpdate(new BasicDBObject(findVal), new BasicDBObject(updateval))

I am converting it from Grails 3.0 to Grails 3.1, here nativeEntry is returning as a domain class while in previous version, nativeEntry is returning as BasicDBObject.
Any solution?
I am using Grails 3.1 with gorm 5.0 and mongodb 3.4
Answer: I have resolved it. Add below solution to Application.yml
grails:
mongodb:
   engine: mapping

It will convert MongoCodecSession to the previous MongoSession.
As in codecs, objects are no longer converted first to MongoDB Document objects and then to Groovy objects, instead the driver reads Groovy objects directly from the JSON stream at the driver level, which is far more efficient than the previous MongoSession.


Is there a way to prevent only a specific child from triggering a SIGCHLD?

Question: I'm writing a debugging utility, and I want to fork a child while preventing that child's termination from triggering a SIGCHLD to its parent. I still want other children to normally cause a SIGCHLD upon termination.
I want to do this because I don't want the fork to trigger an existing $SIG{CHLD} handler, but I still want other children to trigger it. That is, I want to isolate my new child and I don't want it to interfere with management of existing children.
I'm wary of locally installing a custom $SIG{CHLD} handler since I don't think I can properly detect when I should call the original handler. For instance, if I install a local $SIG{CHLD} handler, then I'm guaranteed to receive a SIGCHLD signal once I spawn a child and have the parent waitpid for it to terminate. However, that SIGCHLD won't indicate whether or not other children have terminated as well, so I can't be sure whether to call the original handler.
I researched that a process cannot change its parent pid. I'm not sure if changing the child's process group id or session id would be useful.
Is it even possible to prevent a specific child from triggering the SIGCHLD on the parent? Am I forced to rely on the existing $SIG{CHLD} handler to Do The Right Thing when it receives the SIGCHLD signal for a child that it did not expect?
Although there may be a better way to implement that debugging utility (let me know if there is), I'm still wondering whether POSIX offers such fine-grained control over children, and am looking for a Perl solution to my dilemma.
Answer: You can't portably prevent the SIGCHLD entirely, but if the signal handler is written properly you can prevent the waitpid from returning your debugging tool's pid by orphaning it.
use Signal::Mask;
sub start_background_child {
  local $Signal::Mask{CHLD} = 1;
  my $first = fork;
  croak "fork failed: $!" if not defined $first;
  if ($first) {
    waitpid $first, 0;
    return;
  }

  my $second = fork;
  croak "fork failed: $!" if not defined $second;
  exit if $second;

  your_stuff_here();
}

Comment: This approach may or may not prevent that initial SIGCHLD (portability issue), but if it doesn't waitpid will never return the debugging process.
Comment: As perfect as it can get! On my macbook (OS X 10.8.2), this works as desired. Also, I love your `Signal::Mask` and `Signal::Pending` modules; they made it very easy to explore the behavior on my system. :)
Answer: I think you could daemonize the special child -- fork twice -- to sever the parent-child relationship. You'd still receive a SIGCHLD when the process was created -- I don't know if that's acceptable for you.
sub start_special_child {
    return if fork;     # run rest of this routine in child process
    fork && exit;       # run rest of this routine in grandchild process
                        # the  exit  here triggers SIGCHLD in the parent
    ...                 # now run your special process
    exit;               # exit here does not trigger SIGCHLD
}

The other approach is to keep track of the process id's of your child processes, and use waitpid to figure out which process(es) triggered the SIGCHLD handler.
$SIG{CHLD} = \&sigchld_handler;
$pid1 = start_child_process();
$pid2 = start_child_process();
$pid3 = start_child_process();
$pidS = start_special_child_process();

sub sigchld_handler {
    $pid = waitpid -1, WNOHANG;     # use POSIX ':sys_wait_h'
    return if $pid == $pidS;
}

Comment: I'd like to avoid that initial `SIGCHLD`, so the first approach is unfortunately not acceptable for me (since it would still trigger the existing `$SIG{CHLD}` handler). The second approach would be ideal if I had control of the original `$SIG{CHLD}` handler as well as the other children. However, I'm looking for a generic solution that works regardless of the original `$SIG{CHLD}` and without knowledge of any other children. I'd also like to avoid reaping the other children (but I don't mind if the special child is reaped).
Comment: I don't usually like Perl's threads, but maybe a thread is more appropriate here than a fork.


IE creating a phantom div in a listing loop

Question: I've been working on this for a few days now and cannot find a solution.
http://mri.sniperdyne.com/inventory.asp?CatId=C547E3B5-44F4-4BB5-BF2D-CE51BB8E8DA6
In FF the loop works fine. In IE8 it creates a phantom div at the top. Has anyone seen this before?
The background programming language is ASP with VB.
I'm not sure if this is something that is caused by cross browser compatibility.
Answer: When I have problems like this, it's usually an indication that I forgot to close a div somewhere. Or I closed one too many. If it's not obvious when you eyeball the code, try running the page through the W3C Validator Service to find and fix any markup problems.
Comment: Thanks! I had a dynamic breadcrumb that was generating anchors that weren't closing, which somehow created the phantom div. I give you and up one but my reputation isn't at 15 yet. Thanks again.
Comment: No problem, glad to help. Even if you can't vote, you can accept the answer. Helps to keep SO cleaner.


How to tab focus on a button like image Component in vue.js

Question: I have the following template in my vue.js application:

     <button class="button_text" @click="reset">Reset</button>
     <button class="button_text">Search</button>
     <image-component class="button_image_icon"/>

I am trying to set the tab focus on the <image-component> which is not a <button> but a Component with a label and input inside a  . It sets focus on the buttons easily but not sure how to do it on an button like image icon.
Tried: @click="setFocus", didn't work.
Answer: You should be able to achieve it by adding the tabindex attribute to all the elements

     <button class="button_text" @click="reset" tabindex="1">Reset</button>
     <button class="button_text" tabindex="2">Search</button>
     <image class="button_image_icon" tabindex="3" />

Example with focus manually set with javascript: https://jsfiddle.net/qeugo6hm/5/
Comment: Hasn't worked. Adding this even lose the previous focus on the buttons.
Comment: Perhaps what I missed could be the issue. The `image` is a `Component` itself. Now updated the problem description.


Output $(rpm -Va) to array with spaces intact

Question: I'm attempting to put the output from rpm -Va into an array so that I can then run multiple checks against the results. I would very much like to be able to have each output line from the rpm command be its own line in the array. So far I haven't had too much luck, so I thought it best to reach out and see what other people think. I've tried some of the below options, but to no avail.
This adds to the array but doesn't keep spaces:
rpmarr=($(rpm -Va | sed 's_^_"_g' | sed 's_$_"_g'))

This adds to the array but as one huge line:
while IFS= read -r line; do rpmarr+=("$line"); done < "$(rpm -Va)"

This also adds to the array but as one huge line:
IFS=$'\n'; set -f; rpmarr=$(rpm -Va); set +f; unset IFS; echo ${#rpmarr[@]}

Answer: With Bash 4.0:
readarray -t rpmarr < <(exec rpm -Va)

Else
rpmarr=() i=0
while IFS= read -r line; do
    rpmarr[i++]=$line  ## Can be rpmarr+=("$line") in which case you won't need i. Only available in Bash 3.1+
done < <(exec rpm -Va)

<(exec rpm -Va) is a form of process substitution and exec saves forking another subshell.
Comment: Looks like my account is too new to be able to upvote, but I would if I could since this worked for me! I was able to print the array with the spaces in tact with a test while loop.
Comment: I'm trying to add both to a script file as provided but neither seem to function properly. I'm getting errors like below. Searching around now to see if I can find something.

test: line 3: syntax error near unexpected token '<'
test: line 3: `         readarray -t rpmarr < <(exec rpm -Va)'
Comment: How do you run your script? Perhaps it's not exactly `bash` that runs it?
Comment: I usually use sh -vx ./script 2> out when testing execution and remove the verbose/debugging/output when running for real, unless needed. This time was with the -vx options. I checked /bin/bash --version and it states "GNU bash, version 4.1.2(1)-release".
Comment: Try to run it as `bash -vx ./script` instead. Bash emulates nearly like POSIX sh when called with just `sh`.
Comment: That did it! Is it best practice to use bash over sh? I wasn't aware that sh acted differently. I assumed one was an alias for the other, but never looked into it like I should have.


PHP filter multimensional array by column only where other indexes match

Question: I have multidimensional array similar to this:
$multidimentionalArray = array (
    array(
    'product' => 'apples',
    'manufacturer' => 'testmanufacturer',
    'price' => '3'
    ), array(
    'product' => 'apples',
    'manufacturer' => 'testmanufacturer',
    'price' => '2'
    ) , array(
    'product' => 'bananas',
    'manufacturer' => 'testmanufacturer',
    'price' => '2'
    )
);

I'm trying to create a function that filter this array so that it would only filter the lowest product price where the product and manufacturer are the same.
So the end result would be:
Array
(
    [0] => Array
        (
            [product] => apples
            [manufacturer] => testmanufacturer
            [price] => 2
        )

    [1] => Array
        (
            [product] => bananas
            [manufacturer] => testmanufacturer
            [price] => 2
        )

)

I've tried the following with no luck:
$price = array_column($multidimentionalArray, 'price');

array_multisort($price, SORT_ASC, $multidimentionalArray);

Thanks
Answer: You can first find the min and then iterate the array and find the min prices like this:
<?php
$multidimentionalArray = array (
    array(
    'product' => 'apples',
    'manufacturer' => 'testmanufacturer',
    'price' => '3'
    ), array(
    'product' => 'apples',
    'manufacturer' => 'testmanufacturer',
    'price' => '2'
    ) , array(
    'product' => 'bananas',
    'manufacturer' => 'testmanufacturer',
    'price' => '2'
    )
);

$finalArray = [];
$minPrice = min(array_column($multidimentionalArray, 'price'));
foreach ($multidimentionalArray as $value) {
    if ($value['price'] == $minPrice) {
        $finalArray[] = $value;
    }
}

print_r($finalArray);

output
Array
(
    [0] => Array
        (
            [product] => apples
            [manufacturer] => testmanufacturer
            [price] => 2
        )

    [1] => Array
        (
            [product] => bananas
            [manufacturer] => testmanufacturer
            [price] => 2
        )

)

Comment: This won't work if, for example, you had  3rd array with oranges with a price of 3
Comment: so what is the problem? first i get the min price and then just iterate it


Solution Poisson Equation by Homotopy Perturbation Method

Question: I need to solve the following Boundary Value problem
$$\frac{\partial^2w }{\partial x^2}+\frac{\partial^2w }{\partial y^2}=c$$
Boundary conditions are
$$w(x,h)=0$$
$$w\left(\frac{\pm h}{\sqrt3},y\right)=0$$
I am trying to solve it by Homotopy Perturbation Method, but unable to succeed to get desired answer which should be
$$w=\frac{c(y-h)(3x^2-y^2)}{4h}$$
Comment: is $c$ constant? and what's the domain of the problem?
Comment: Yes $c$ is contant,and I think it's in real domain.
Comment: It can't be $\Bbb R^2$ since your boundaries are $x=\pm h/\sqrt{3}$ and $y=h$. Either it's $(-h/\sqrt{3},h/\sqrt{3}) \times (h,\infty)$ or $(-h/\sqrt{3},h/\sqrt{3}) \times (-\infty,h)$. I'm asking you which is it?
Comment: its $(-h/sqrt(3), h/sqrt(3)) × (h,∞)$
Answer: You might want to verify your given solution. I don't think it satisfies the equation.
First, let
$$ w(x,y) = \frac{c}{6}(3x^2-h^2) + v(x,y) $$
then $v(x,y)$ is harmonic with boundary conditions
\begin{cases}
v\left(\pm \frac{h}{\sqrt3},y\right) = 0 \\
v(x,h) = -\frac{c}{6}(3x^2-h^2)
\end{cases}
The solution to this problem isn't unique. If we assume $v(x,y\to\infty)$ is bounded, then separation of variables gives
$$ v(x,y) = \sum_{n=1}^\infty c_n \exp\left(-\frac{n\pi\sqrt 3}{2h}(y-h)\right) \sin\left(\frac{n\pi}{2h}\big(\sqrt3 x+h\big)\right) $$
where
$$c_n = \frac{\sqrt 3}{h}\int_{-h/\sqrt3}^{h/\sqrt3} v(x,h) \sin\left(\frac{n\pi}{2h}\big(\sqrt3 x+h\big)\right) \ dx$$


Unsure how to declare and then access an int array in heap memory

Question: I have a giant array that's being used to temporarily store pixel data (before it's written to a file). I've been having "random" crashes and someone much more proficient with C++ than myself suggested that I should put my pixel array in the heap than stack. These were all new words to me but I've read up and it makes sense but I'm struggling to set this up.
Declaring the heap array:
int *heap = new int[MAX_WIDTH * MAX_HEIGHT * 3];

This is then used by my Canvas class, which I want to hold a pointer to a specific heap:
class Canvas {
    public:
    Canvas(int w, int h, bool fill_transparent, int* heap);
    Canvas();

    int width;
    int height;

    int* heap;
}

Canvas::Canvas(int w, int h, bool fill_transparent, int* heap) {
    if (w>MAX_WIDTH) w = MAX_WIDTH;
    if (h>MAX_HEIGHT) h = MAX_HEIGHT;

    width = w;
    height = h;
    heap = heap;

    if (fill_transparent) {
        for(int x=0; x<width; ++x) {
            for(int y=0; y<height; ++y) {
                set(x, y, transparent);
                //heap->pixels[x][y] = transparent;
            }
        }
    }
}

Creating a new canvas and passing the heap along:
Canvas new_texture(int w, int h, int* heap) {

  Canvas canvas(w, h, true, heap);

  // Do some things with it, using set(x,y);

  return canvas;

}

And then attempting to set pixel data (Pixel is a struct with {int r, int g, int b}:
void Canvas::set(int x, int y, Pixel colour) {
    if (x>=width || y>=height || x<0 || y <0) return;

    // Set the heap :C
    *heap[(x * (MAX_HEIGHT*3)) + y] = colour.r;
    *heap[(x * (MAX_HEIGHT*3)) + y + 1] = colour.g;
    *heap[(x * (MAX_HEIGHT*3)) + y + 2] = colour.b;
}

This is wrong! I just can't figure out how I should be declaring the array, storing the pointer in a class, and then accessing it. int *heap[] makes more sense to me but also doesn't work.
I'm learning on the job, and am really struggling to find an overview of how I should be doing this.
I've tried most variations that I can think of, I'm struggling to get something that works in all three places!
Comment: Use `std::vector` instead.  No muss, no fuss.
Comment: side note: [Why are the terms "automatic" and "dynamic" preferred over the terms "stack" and "heap" in C++ memory management?](https://stackoverflow.com/q/9181782/4581301)
Comment: Side note: Someone out there owns the allocation pointed at by `heap`, and it isn't `Canvas`. You have to make absolutely certain that the object `heap` points at outlives `Canvas` and is correctly managed throughout its life. Essentially, you could have a bug anywhere in the code and we can't help with any mistakes not in the bits of `Canvas` you have shown.
Comment: As @NathanOliver said use std::vector, current C++ does not recommend the use of new/delete. (See [R.11 C++ core guidelines](https://isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines#Rr-newdelete))
Comment: Side note: `if (w>MAX_WIDTH) w = MAX_WIDTH;` -> `w = std::max(w, MAX_WIDTH);`
Comment: If this is for anything else then a learning / hobby project, you should seriously consider using one of the many image manipulation libraries available. Rolling you own code to handle RGB images is not an efficient use of you time.
Answer: Main issue
*heap[(x * (MAX_HEIGHT*3)) + y] = colour.r;

First of all, syntactically this should be:
heap[(x * (MAX_HEIGHT*3)) + y] = colour.r

Putting a * there is just wrong in this case.
Next if width < MAX_WIDTH or height < MAX_HEIGHT, then you'd obviously be completely off!
This should be heap[x*(height + 3) + y], not MAX_HEIGHT.
And then you're still missing the 3 factor from your y term here, so actually this should be
heap[3*(x*height + y)]
General Notes
So this will be part "code review", not just addressing the issue.
int *heap = new int[MAX_WIDTH * MAX_HEIGHT * 3];

Two things here: In C++ it's way easier to just use std::vector when allocating a dynamically sized array; That way you get the memory management part 'automatically'.
std::vector<int> heap(MAX_WIDTH * MAX_HEIGHT * 3);

Moving on, it'd be a bit weird to allocate the memory outside of the Canvas: You'd normally expect the canvas to "own" the memory, so you'd actually just write:
// assuming you have your `heap` member as `std::vector<int>` instead of `int *`.
// we know longer take the 'heap' as a parameter, instead we just construct it directly inside of our object
Canvas::Canvas(int w, int h, bool fill_transparent)
// this : thing is a relatively unique thing to C++, this means
// "initialise this field with this expression"; In C++ class
// member initialisation happens *before* we actually enter the constructor body.
// This is called an initialiser list, you should look that term up for more details
: heap(w * h * 3)
{
  // rest of your constructor code here
}

This way you don't need to worry about all this setup outside your canvas, and as a bonus you're now only allocating as much memory as you need, not as much memory as you might maximally need. There are situations where you might want to manage the memory outside the canvas struct, or always allocate the maximum amount of memory you may ever need, but unless you know you need this it's not a good idea to add these complications.
Finally, if your Pixel is just a simple RGB struct you could just put that into the array directly, no need to have it "unrolled" into integers unless you need to force a particular in-memory representation (while fortunately most C++ implementations have a pretty predictable way they layout structs, technically it's unspecified in the C++ standard so if you don't know what implementations you're targeting you unfortunately might have to skip this step, but this will be fine for most cases):
std::vector<Pixel> heap; // inside the class

// in the initialiser list:
: heap(w*h) // note no more *3 here

// and in the method, note we don't have the weird 3* term in here anymore

heap[x*height + y] = colour;

Also, while this is more a matter of opinion, heap is a bit of a weird name for this. You could just call it pixels; then you'd write
pixels[x * height + y] = colour;

which at least to me seems clearer.
Comment: Thank you! It looks like vectors are the way to go. Heap only ended up outside of canvas because I was.. well.. incredibly confused. My initial array was part of it. I'll move the vector back inside.
Answer: You would access the dynamically allocated memory using
heap[y * width * 3 + x * 3 + color] but it's both inconvenient and error prone.
Your class is also lacking the special member functions to follow the rule of five which makes future bugs very likely.
I recommend using a std::vector which will manage the dynamically allocated memory for you and you also store Pixels directly in the std::vector instead of just multiplying the number of ints needed by 3. The struct and the transparent constant could look like this:
struct Pixel {
    int r = 0;
    int g = 0;
    int b = 0;
};

// replace with the constant values you want for transparent:
inline constexpr Pixel transparent{255, 255, 255};

int for the individual channels in Pixel may be overdoing it a bit. Consider using a smaller type, like uint8_t for example.
In your Canvas class, you could create operator() overloads for accessing the Pixels, that you then store in a std::vector<Pixel>:
class Canvas {
public:
    explicit Canvas(size_t h, size_t w, bool fill_transparent);

    Pixel& operator()(size_t h, size_t w);
    const Pixel& operator()(size_t h, size_t w) const;

    size_t Height() const { return height; }
    size_t Width() const { return width; }

private:
    size_t height;
    size_t width;

    std::vector<Pixel> pixels;
};

And the implementation of the operator() overloads becomes a bit simpler than with your dynamically allocated ints. The constructor also tells the std::vector<Pixel> how many pixels there should be and if they should be transparent or have the default constructed Pixel:
Canvas::Canvas(size_t h, size_t w, bool fill_transparent)
    : height(std::min(h, MAX_HEIGHT)),
      width(std::min(w, MAX_WIDTH)),
      pixels(height * width, fill_transparent ? transparent : Pixel{}) {}

Pixel& Canvas::operator()(size_t h, size_t w) {
    return pixels[h * width + w];
}

const Pixel& Canvas::operator()(size_t h, size_t w) const {
    return pixels[h * width + w];
}

Demo
Comment: >It was just OPs trial-and-error that got him into the situation where the heap is allocated separately - if I'm correct

You are indeed! :) Thank you so much!
Comment: I hesitate on calling out the lack of support for the rule of three/five/zero because I'm not certain `Canvas` is supposed to own the object at `heap`. Structurally, `Canvas` owning it will probably make the program simpler, but I'd have to see the rest of the program.
Comment: @user4581301 I understand the hesitation but I read the intro in the question a few times and I'm pretty sure that there's no complicated owership scheme going on. It was just OPs trial-and-error that got him into the situation where the `heap` is allocated separately - if I'm correct that is :-)
Comment: Didn't realise std::vector already used the heap (at least, for its contents). This is great, I was fearing a lot of work for the rest of my codebase but I'm making heavy use of vectors already. Thank you again!


Rails polymorphic association error

Question: I'm having problems with a polymorphic association.
A quick explanation about my project.  You can see it here: majorfinder.com  On my app there will be majors, schools, and careers.  I want to be able to add reviews for each.  Since I'm just starting out I'm just beginning with adding reviews for majors but creating the association so that when I get to the careers and schools the reviews association will go quickly.
Here are my associations:
models/review.rb
belongs_to :user
belongs_to :reviewable, polymorophic: true

models/user.rb
has_many :reviews

models/major.rb
has_many :reviews, as: :reviewable

My db schema for reviews looks like this:
create_table "reviews", :force => true do |t|
    t.text     "review"
    t.datetime "created_at",      :null => false
    t.datetime "updated_at",      :null => false
    t.integer  "user_id"
    t.integer  "reviewable_id"
    t.string   "reviewable_type"
  end

In my majors controller I've followed this railscast in order to create a url that looks like this www.majorfinder.com/majors/major-name.  So part of my majors controller looks like this:
def show
    @major = Major.find_by_slug(params[:id]).includes(:reviews => :user)
end

In my majors show page I have:
<% @reviews.each do |review| %>

<%= link_to review.review,
        :controller => "reviews", :action => "show", :id => review.id %>

      Posted on <%= review.created_at %> by
        <%= review.user.profile_name %>

  <% end %>

And lastly, here are my routes:
resources :majors, has_many: :reviews

I'm getting the following error:
NoMethodError in MajorsController#show

undefined method `includes' for #<Major:0x007f9466e001a8>

Here it is from the console:
Started GET "/majors/statistics" for 127.0.0.1 at 2013-03-05 07:45:01 -0700
Processing by MajorsController#show as HTML
  Parameters: {"has_many"=>:reviews, "id"=>"statistics"}
  Major Load (24.2ms)  SELECT "majors".* FROM "majors" WHERE "majors"."slug" = 'statistics' LIMIT 1
  CACHE (0.0ms)  SELECT "majors".* FROM "majors" WHERE "majors"."slug" = 'statistics' LIMIT 1
Completed 500 Internal Server Error in 28ms

NoMethodError (undefined method `includes' for #<Major:0x007f8ad51fdd00>):
  app/controllers/majors_controller.rb:16:in `show'

Line 16 in the majors_controller.rb file is this one:
@major = Major.find_by_slug(params[:id]).includes(:reviews => :user)

Can you see what I'm missing or what I should change?  It seems like the solution is simple but I am not sure what it is. Thanks in advance for your help!
Comment: Your problem is pretty clear: the `includes` method isn't defined for Major instances. I'm not quite sure what the fix to your problem is. Did you get that from an example? What are you trying to do with that method invocation?
Answer: I believe what you are trying to do is eager load :reviews when you find the Major. You are close but your order is backwards. It needs to be
@major = Major.includes(:reviews => :user).find_by_slug(params[:id])

For more information on eager loading checkout this RailsGuides article.
Comment: Yes, exactly!  Thank you!  Thanks for the rails guide too.  I have been looking for that but didn't know the term eager loading.  I really appreciate it!

Rails polymorphic association error


Como misturar duas cores utilizando JavaScript?

Question: Existem dois campos onde o usuário informa uma cor em hexadecimal. Ao clicar em misturar cores, deverá ser feito um cálculo em JavaScript e este terá que apresentar um quadro pintado com a cor misturada e o resultado em hexadecimal.
Estrutura no jsfiddle
JavaScript
$('button').click(function(){
    var cor1 = $('#cor1').val(); //exemplo: #FF0000
    var cor2 = $('#cor2').val(); //exemplo: #00FF00
    // realiza a mistura
    var mistura_em_hexadecimal;
    $('#cor_misturada').css('background-color', mistura_em_hexadecimal);
    $('h2 span').text(mistura_em_hexadecimal);
});

Como realizar este cálculo para misturar duas cores hexadecimais?
Obs: o resultado deve ser preciso e não pode utilizar nenhum plugin.
Answer: Creio que o que procura é uma média entre cada côr.
Dê uma olhada aqui: http://jsfiddle.net/XdQ88/1/
function tratarInput(arr, degraus) {
    arr = arr.toLowerCase();
    if (arr.length == 3) {
        var partes = arr.split('');
        for (var i = 0; i < arr.length; i++) {
            if (!~degraus.indexOf(arr[i])) {
                alert('formato errado!')
                return false;
            }
        }
        arr = [partes[0], partes[0], partes[1], partes[1], partes[2], partes[2]].join('');
    } else if (arr.length == 6) {} else {
        alert('formato errado!')
        return false;
    }
    return arr;
}

$('button').click(function () {
    var degraus = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'];
    var cor1 = $('#cor1').val().replace('#', '');
    var cor2 = $('#cor2').val().replace('#', '');

    cor1 = tratarInput(cor1, degraus);
    cor2 = tratarInput(cor2, degraus);

    // realiza a mistura
    var mistura = [];
     for (var i = 0; i < 6; i+=2) {
        mistura[i] = Math.round((parseInt(cor1[i] + cor1[i + 1], 16) + parseInt(cor2[i] + cor2[i + 1], 16)) / 2);
        mistura[i] = (0x1000000 | mistura[i]).toString(16).substring(5);
    }

    mistura = '#' + mistura.join('');
    $('#cor_misturada').css('background-color', mistura);
    $('h2 span').text(mistura);

});

Este código pode precisar de alguns ajustes mas explicando um pouco os passos ele faz:

define as variáveis. Aqui criei uma array para todas os degraus de cores, isso vai ser útil mais tarde. Retiro também o caracter # para facilitar, mas volto a inserí-lo mais tarde. Uma vantagem aqui é que se não usar ele corrige na mesma.
criei uma função para tratar o input. Aqui a função converte todas as cores em 6 caracters (no caso do input ter sido de 3), verifica se existem carateres não válidos e se os inputs têm 3 ou 6 caracteres como esperado
depois no for faz a própria mistura. Calcula a posição daquela cor na array de degraus e faz uma média. Quando faz a média faz também um arredondamento e usa o valor absoluto (para corrigir valores negativos). Este valor é uma referência e é então usado para ir buscar o valor real na array degraus.
por fim, antes do seu código continuar, volto a colocar o caracter # para o valor ficar correto
Comment: @PauloMaciel Só estou tentando compartilhar um conhecimento técnico que eu já precisei. Existem varias maneiras de se converter cores, e justo a RGB não te atende. Não tem uma mais certa que outra, vai do uso. Em RGB, sempre cor complementar se anula, e vira cinza. Esse 7f ou 80 é mero problema de arredondamento. Se fizer 404000 com 000040, vai dar 202020, em RGB, nao tem outro jeito. Só que este modelo, apesar de correto, não é o que te serve. Só isso, não se trata de certo e errado.
Comment: @Bacco eu ainda acho que o problema é mais uma limitação na conversão (método como é feito), mas de qualquer forma a solução atual me atende bem
Comment: @PauloMaciel: por onde se está a guiar para os resultados que pretende?
Comment: @Sergio estou fazendo teste através de um software e ele é preciso, na transição entre amarelo e azul não pode ficar cinza absoluto, isso só ocorre entre preto e branco. Mas não vou reutilizar a mistura para novos cálculos, então não afetará o resultado final, isso no meu caso.
Comment: @Bacco estou afirmando baseado em testes que eu fiz, como eu disse, o resultado é aproximado, não é exato, o que acaba fazendo com que a cor fique cinza absoluto. Ao nossos olhos o resultado é o mesmo, mas no código hexadecimal ter 'resíduos' da cor (azul+vermelho por exemplo). O resultado deve ser `#80807F` e afirmo com convicção, `7F` é resíduo das cores que foram misturadas. A prova disso é você deixar o 7F no final mudar o código anterior, exemplo: `#00007F` ("azul escuro") `#FFFF7F` ("amarelo claro"). Faça os testes e veja.
Comment: @PauloMaciel, só pra complementar, 80 é a mesma coisa que 128, e 7F é a mesma coisa que 127. rgb(128,128,127) e rgb(128,128,128) é praticamente o mesmo cinza, com diferença de 1 bit no azul, por arredondamento. (Equivalem a #80807F e #808080 respectivamente). Uma curiosidade minha: neste soft que você fez o teste, como fica o resultado se inverter a posição das duas cores? E quanto dá se misturar #FEFE00 com #0000FE?
Comment: @Bacco a mistura de #FEFE00 com #0000FE é igual a #7F7F7F
Comment: @Bacco este sim deu cinza (127, 127, 127). Pelo visto eu estava equivocado quando eu disse que apenas com branco e preto é possível fazer cinza. Mas em relação ao valor hexadecimal da mistura de #FFFF00 com #0000FF resultar em #808080, pode ser "praticamente o mesmo cinza", mas essa diferença mínima pode afetar determinado software que reutiliza mistura de cores.


java generic function parameter type mismatch for "Object" class

Question: I've got following code snippet:
class pp<K, V> {
    public pp(K k, V v) {
        this.k = k;
        this.v = v;
    }

    private K k;
    private V v;
}
class my{
    public static void f(pp<? extends Object, ? extends Object> p){
        System.out.println(p);
    }
}
public class genericFunction {
    public static void main(String[] args) {
        my.f("abc", new Integer(2));//compilation failure
    }
}

It fails to compile inside the main. Saying looking for
pp<? extends java.lang.Object,? extends java.lang.Object>

but found
java.lang.String,java.lang.Integer

How to fix it?
Answer: You don't have a pp, you have two arguments.
Put them in your object type: my.f(new pp<>("abc", new Integer(2))).
Answer: Because you are passing literal arguments (String and Integer) instead of passing an object of pp.
Try my.f(new pp<>("abc", new Integer(2)))
Side note: use Pascal casing for type names


Categorical proof of the existence of the real numbers

Question: In his answer to my question on the real numbers SE/839848, Qiaochu Yuan mentioned that the real numbers are the terminal archimedian ordered field. I wondered, what can be said about the category of archimedian ordered fields. In particular, which limits and colimits do exist? Can the existence of a terminal object be proven categorically?
Comment: What is a "categorical proof"? There are a number of general principles that tell you that some category is complete if another is, but at some point one actually has to sit down and prove that a particular category is complete. I think this is one of those cases.
Answer: This category is less interesting than it might sound: because $\mathbf{Q}$ embeds uniquely in its completion $\mathbf{R}$ and is dense in any Archimedean ordered field, there is a unique order-preserving homomorphism from any Archimedean ordered field to $\mathbf{R}$: this category is just the category of subfields of $\mathbf{R}$. And, thus, it is complete and cocomplete, because arbitrary intersections of subfields are again subfields.
Comment: Of course you have said this, but just to be clear: This category is (equivalent to) a partial order. This follows simply because $\mathbb{Q}$ is dense in any Archimedean ordered field, so that any two parallel homomorphisms agree. We don't need $\mathbb{R}$ for this reasoning.


Ping a computer over VPN when ip is in conflict

Question: I usually connect to a remote server over Remote Desktop Connection, however this time it doesn't work (for this particular new server) and I don't really know what to blame.
I connect to the network using VPN an that works fine, however when I want to use Remote Connection to connect to the server it won't work ... I think the problem might be that the remote server has the same ip in its domain that a server has in our domain.
I'm not sure how to check what is really the problem. If I try to ping after connecting the VPN, I think I'm still getting the response from our server, not from the remote one.
Is there a way to specify domain name when trying to ping?
Either way I'm not sure why I can not connect to the server. The bottom line is that the VPN connects just fine and remote connection won't work. What is usually at fault?
P.S.: I don't have the control over any of the two Domains or IPs.
EDIT: This just became weirder ... I just tried RDPing to the remote server in question and got the following error message:
The connection was denied because the user account is not authorised for remote login.
Then I tried entering the wrong password on purpose and it tells me the password is wrong. Now this leads me to believe that the Remote Desktop Connection works correctly and the IT company on the other side just screwed up my user rights ... Is that possible? Would that explain what is going on?
Answer: Hmmm - If your local network and the remote network have the exact same IP range and subnet mask, then pinging/connecting by IP to a particular system will likely depend on your adapter order (the order in which your OS looks at your network connections).  For example, say you have your LAN connection and a VPN connection as your network adapter choices.  If your VPN connection adapter is first in the order, when you try to connect to a remote machine by IP, it will connect using the VPN connection and hit the local system.  If your LAN adapter is first, however, it will try locally first and connect to the local system.
To get around this situation, use the FQDN of the remote server - servername.domain.com - to ping and connect.  When you connect to the VPN you will likely obtain IP address, subnet mask, gateway, and (hopefully) DNS server values and a connection-specific DNS suffix for the other domain.  By specifying the FQDN of the server, you are telling it to use the VPN adapter based on the domain instead of relying on the adapter order to determine which network you connect to.
Comment: I'm very suprised that this worked.
Comment: Why? If you think about it, yes the local LAN and the remote LAN have the same IP range, but you are connecting to them via 2 separate network adapters - your physical NIC and the VPN virtual NIC.  Therefore, NIC adapter order would determine which network (local or VPN) you look at first.  To test this theory (and it IS just a theory since I have never done it), you could use 2 physical NICs in a PC and dual-home to 2 separate networks with the same IP ranges - your adapter order will determine which network you try to get to first.
Comment: thank you, this way I did get a response with a larger ping value - leading me to believe that now I am pinging the remote server. However remote connection won't connect this way either with servername.domain.com or with the ip that the ping prints.
Comment: can you connect to anything in the other domain over VPN?  maybe RDP is not permitted over the VPN for whatever reason.  Another test - disconnect from the VPN and RDP to the local server with the same IP.  If you connect and get a login window, then it is trying to get to the remote server while on VPN and failing.  You can also try connecting via UNC (\\servername\share) and poke around to determine which server you are connecting to.
Answer: If the local and remote networks are sharing an IP range, it seems extremely counterintuitive to me that you could get this to work at all.  Why would a packet destined for your local subnet ever travel to your gateway?  It shouldn't, by definition.
However, I'm looking forward to learning exciting new tricks if someone knows how to make this work.  Otherwise I'd think you're going to be stuck trying to go through LogMeIn or some similar remote control app rather than VPN.


Stream API, is there way to iterate descending using instream.range?

Question: For example,
Instream.range(0,10) - is iterating from 0 index to 10.
Instream.range(10,0) - but from 10 to 0 is not working, how to do it using Stream API?
Comment: Does this answer your question? [Java 8 stream reverse order](https://stackoverflow.com/questions/24010109/java-8-stream-reverse-order)
Comment: @Apokralipsa If possible, I would recommend to avoid sorting in this circumstance since sorting is a stateful operation.
Answer: You can use IntStream.iterate(initialValue, hasNext, next):
IntStream.iterate(10, i -> i >= 0, i -> i - 1)

If you are stuck with java 8:
IntStream.iterate(10, i -> i - 1).limit(11)

Comment: I recommend `i-1` instead of `--i`
Answer: You cannot generate descending stream using range(). Java doc clearly specifies that the steps are an increment of 1. If there was an option to provide a step then we could have. However, there are different ways in which you can achieve the same.
IntStream.iterate(10, i -> i >= 1, i -> --i)

IntStream.rangeClosed(1, 10).boxed().sorted(Comparator.reverseOrder())

IntStream.range(-10, 0).map(i -> -i)

Out of this three using and iterate method would be the best approach.
Comment: "sorted" that's bad, because it holds all values in memory before you can use it
Comment: Yup I know it's bad, I was just listing out the possible ways. I have also added a note at the end.
Answer: If you want the same set of numbers to be repeated if start/end are transposed then this will replace the ranges if start > end:
IntStream range(int start, int end) {
    return start < end ? IntStream.range(start,end)
                       : IntStream.range(-start+1, -end+1).map(i -> -i);
}
range(2,5).forEach(System.out::println);
2
3
4

range(5,2).forEach(System.out::println)
4
3
2

If you want the meaning of (startInclusive, endExclusive) to be preserved modify as:
IntStream range2(int start, int end) {
    return start < end ? IntStream.range(start,end)
                       : IntStream.range(-start, -end).map(i -> -i);
}

range2(5,2).forEach(System.out::println)
5
4
3

Answer: Another trade-off solution is modify the range value like :
    int exclusiveEnd = 10;
    IntStream.range(0, exclusiveEnd).forEach((i) -> {
        System.out.println(exclusiveEnd - 1 - i);
    });

Answer: Use map after range to calculate new value:
IntStream.range(0, 10).map(i -> 10 - i); // 10, 9, .. 1
IntStream.rangeClosed(0, 10).map(i -> 10 - i); // 10, 9, .. 0


Bringing matrices to the other side of the equation

Question: Let's say that A, B, and C are all 2x2 matrices such that AC = B; if I want to multiply both sides by the inverse of A to "bring" A to the other side of the equation, would it be C = B$A^{-1}$ or C = $A^{-1}$B? Is there a general rule for multiplying both sides of the equation with an element and where the element should be placed?
Comment: Left-multiply by $A^{-1}$, since $A^{-1}A=I$
Comment: Matrix multiplication is not commutative. This means that, generally, $A^{-1}B \ne BA^{-1}$. To undo multiplication by a matrix, you must multiply the product by the inverse of said matrix (if it exists) in the same direction as the original matrix.
Answer: The rule is that if you multiply by $A^{-1}$ on the left/right of a term, you must also multiply on the left/right on the other side of the equation. In your case, if $AC= B$ then, $A^{-1} (A C) = A^{-1} B$. Hence by associativity, $(A^{-1} A)C = IC= C = A^{-1} B$, where $I$ is the identity matrix. This is assuming, of course, that multiplication by $A$ is defined.


Restriction of a stable bundle on a curve

Question: Let $X \subset \mathbb P^N$ be a smooth projective surface. Let $H$ be an ample divisor on $X$. Let $M_{X,H}(r;c_1,c_2)$ be the moduli space of rank r, slope stable (w.r.to $H$) vector bundles with fixed Chern classes $c_1,c_2$. Let $C$ be a smooth curve lying on $X$ such that for every $E \in M_{X,H}(r;c_1,c_2)$, $E|_{C}$ is semistable on $C$. Then we have a natural map from $M_{X,H}(r;c_1,c_2)$ to $M_C(r, d)$ (moduli of semistable bundles of rank $r$ and degree $d$ on the curve $C$) given by $E \mapsto E|_C$. My questions are :
$(i)$ Is this map a morphism between these two moduli schemes?
$(ii)$ If so, then is it an injective morphism? (I guess in rank $1$ case it is injective, please correct me if this is wrong)
Any help is appreciated.
Answer: Yes for (1), because the restriction gives a morphism of moduli functors, hence also of their coarse moduli spaces.
No for (2), even in the rank 1 case; consider for instance $X = Y \times \mathbb{P}^1$ and $C = \{y_0\} \times \mathbb{P}^1$, where $Y$ is a smooth curve of positive genus and $y_0 \in Y$ is a point.
Comment: (2) is true if you take $C$ in $|nH|$ with $n \gg 0$, where $H$ is an ample class on $X$.
Comment: Thank you very much for your response. Can we say that $(2)$ is true if we carefully choose curves on the surface say $\mathbb P^2$ or hypersurfaces in $\mathbb P^3$? ( Or is it the case that it is almost never true?)
Comment: On $\mathbb P^2$, if we take $H$ to be the divisor corresponding to $\mathcal O(1)$, then can we give an effective bound on $n$?
Comment: Probably yes, but I am not an expert in this. Maybe a good idea is to look through the papers of Soheyla Feyzbakhsh.


2 vectors in $\mathbb{K}^2$ are linear independent if and only if $ad−bc≠0 $

Question: I have the following assignment what I've also posted here but the proof I provided there was wrong. I am no sure whether opening a new thread for that is allowed - I will definitely link to this one in the other post.
Note: I am not allowed to use determinants in my solution.
Now the assignment:
Let $V$ be a vector space over a field $\mathbb{K}$ and $v_i \in \mathbb{K}$ for $i \in \mathbb{N}$. Prove or falsify the following statements about linear independency:
Let $v_1 = \begin{pmatrix} a \\ b \end{pmatrix}, ~ v_2 = \begin{pmatrix} c \\ d \end{pmatrix} \in \mathbb{K}^2$. $(v_1, v_2)$ are linear independent if and only if ad−bc≠0
My approach
Let $w$ and $v$ be linear independent. Thus one could write:
$\lambda_1(a+b) + \lambda_2(c+d) = 0$
Now lets say $ad-bc = 0 \Leftrightarrow ad = bc$
Furthermore one could write:
$$a+b = \frac{d}{d}a + \frac{c}{c}b = \frac{bc}{d} + \frac{bc}{c} = bc\left(\frac{1}{d}+\frac{1}{c}\right) = ad\left(\frac{1}{d}+\frac{1}{c}\right)$$
$$c+d = \frac{b}{b}c + \frac{a}{a}d = \frac{ad}{b} + \frac{ad}{a} = ad\left(\frac{1}{b}+\frac{1}{a}\right)$$
Thus we get:
$$\lambda_1(a+b) + \lambda_2(c+d) = \lambda_1  ad\left(\frac{1}{d}+\frac{1}{c}\right) + \lambda_2 ad\left(\frac{1}{b}+\frac{1}{a}\right) = ad\left[\lambda_1  \left(\frac{1}{d}+\frac{1}{c}\right)   + \lambda_2 \left(\frac{1}{b}+\frac{1}{a}\right)\right]$$
There we get that the trivial solution is not $\lambda_1 = \lambda_2 = 0$ but $ac = 0$ and the vectors are not linear independent anymore - contradiction.
Can one do that?
Thank you very much!
FunkyPeanut
Comment: $v_1=(a,b)$ and $v_2=(c,d)$?
Comment: Yes - omg sorry.
Comment: $v_1,v_2$ are l.i. iff  det(matrix with columns $v_1,v_2$)=0
Comment: I am not allowed to use determinants in this assignment - I should add that in my post.
Comment: If $d=0$ your are not allowed to use $d/d$.
Answer: If $(a,b)=(0,0)$ or $(c,d)=(0,0)$ we're done.  So we assume $a\neq0$ and $c\neq0$. We will prove: $\begin{pmatrix}a\\ b\end{pmatrix}\parallel\begin{pmatrix}c\\ d\end{pmatrix}\iff ad=bc$. Iff both vectors are parallel there exists $k\in K$ such that $ka-c=0$ and $kb-d=0$; this $k$ can't be $0$, otherwise $c=d=0$. By multiplying the first equation by $d$, the second by $-c$ and adding both equation we arrive in $k(ad-bc)=0$.
If conversely $ad-bc=0$, suppose that $a=0$. Then $b\neq0$, thus $c=0$ and $d\neq0$ so $k=d/b$, similar if $b=0$. Now if $a\neq0$ and $b\neq0$, choose $k=c/a$.