Do users know what "browse" and/or "browser" mean?

Question: A long time ago I saw a show on TV where they asked random people on the street if they knew what a "browser" was (they didn't). I thought there was more information about that and about the term "browse" itself, but after looking all over the place I haven't been able to find anything about it.
We are building an interface to upload files and I would like to change the term "Browse to choose files." to "Upload files." but I don't have a solid justification or argument to do so. Obviously we plan to do some testing for this, but we are not at that stage just yet in the process.
Does anyone know of some kind of documentation about this subject that you can point me to?
Comment: I guess it depends on which "users" you are talking about. For some you might even be able to say "write your own file upload code and paste it here". In short, how technical are they? You really need to identify your target audience before you can make the decision
Comment: It is a interesting topic to know about. Good one.
Comment: When I saw the title, I assumed you were going to be asking about _web_-browsers, not a file browser. As a techie, I would immediately understand "_Browse to choose files_" from the context, and perhaps a good number of "ordinary" users would too. But my (unsubstantiated) suspicion is minimally-computer-literate users might think of "the web" first and possibly get confused. For them, at least, I'd go with [musefan's suggestions](https://ux.stackexchange.com/a/133253/57088) of "Upload Files" or "Choose Files to Upload".
Comment: Good point. Our application serves a very broad spectrum of users, we have both advanced and technically driven users, but we also have clients with far less technical knowledge. So our approach is to name things based on our less technically inclined users and satisfy a broader user base.
Comment: @RicardoZea: Ah, the worst situation then... if you dumb it down too much then the "smarties" might not enjoy using it... If it helps your confirmation bias, I would go with "Upload Files", or if I wanted to be more cautious perhaps, "Click here to Upload Files" (depending on how "clickable" your button designs are).
Comment: @musefan Well, that's a pretty strong assumption, maybe savvy users would enjoy more a simple UI after all… But yes, "Upload files" over "Browse files" seems to be the consensus of what to use. Thank you!
Comment: @RicardoZea: Indeed, more of a personal view from my own preferences than anything else. Also, I was thinking as a more broader scenario. For example, I would not appreciate a 5-page hand-holding wizard, when a single-page 5-field form will do the same job. But some users might need (and even enjoy) the holding of hands.
Comment: One could argue that you should design with the assumption in mind that the answer to any question starting with "Do users know ..." is "no".
Answer: Personally I would understand the intention regardless of which wording you choose, then again I consider myself a more technical user. So let's look at it from a non-technical point of view, which is who you are trying to reach out to here.
I think the word "browse" can be misleading as it could be interpreted as the action of looking through a collection of something. It certainly does not suggest the action of uploading files. So no, I don't think you can rely on users knowing what "browse" means.
It is better to be more specific about the action that the user is expected to perform, and that is that they need to upload some files.

The button should say "Upload Files" or "Choose Files to Upload"
The browser element would benefit from the message "Select one or more files to upload" as a reminder, if possible
The browser element should have a confirm button that says "Upload Selected Files"

Any user that struggles with this was probably going to end up needing support to do it anyway.
I think the main point here is: there is no benefit to using "browse" over "upload", where as there is a benefit to using "upload" over "browse" (i.e. the intent is more clear). So you're not going to be any worse off by dropping "browse".
Comment: This is exactly how I'm thinking about it. This is a bit of an unusual case due to the type of companies our app is capable of serving so narrowing down a specific path as per as specific user base isn't as clear cut as with other products/services. Thanks for your input!
Answer: Good thought Ricardo.
I went through some content research for about 10 mins now,
I found something like this.
If you use Browse to choose files then there must be a upload button to be given ones the files are browsed and selected.
If you use 'Upload files' then probably there is a chance of letting the internet guest appearance user let know what it means directly. For eg: My dad when saw browse to choose files did not understand as I recall. He asked me 'Internet is asking me to browse'. However, when he saw a upload button with label text as upload files, it probably saved him some mental work on thinking what it is.
Apart from this, I did not find any research on this as of now.


Androidx ViewPager2 incompatible types: ViewPagerAdapter cannot be converted to Adapter

Question: I am using ViewPager2, and I get the following error on viewPager2.setAdapter:

incompatible types: ViewPagerAdapter cannot be converted to Adapter

MainActivty
viewPagerAdapter = new ViewPagerAdapter(getSupportFragmentManager(),fragmentList);
viewPager2.setAdapter(viewPagerAdapter);

ViewPagerAdapter
public class ViewPagerAdapter extends FragmentStatePagerAdapter {

    private List<PagerFragment> fragments;

    public ViewPagerAdapter(FragmentManager fm, List<PagerFragment> fragments) {
        super(fm);
        this.fragments = fragments;
    }

    /* (non-Javadoc)
     * @see android.support.v4.app.FragmentPagerAdapter#getItem(int)
     */
    @Override
    public Fragment getItem(int position) {
        return this.fragments.get(position);
    }

    /* (non-Javadoc)
     * @see android.support.v4.view.PagerAdapter#getCount()
     */
    @Override
    public int getCount() {
        return this.fragments.size();
    }
}

Answer: You're trying to use a ViewPager v1 adapter with ViewPager2.  You should convert your adapter to implement FragmentStateAdapter instead.
See this section of the migration documentation for more information.  In particular, you'll want to rename your getCount method to getItemCount, as well as renaming getItem to createFragment and making it return a new Fragment each time rather than re-using instances.
Answer: public class ViewPagerAdapter extends FragmentPagerAdapter {

private ArrayList<Fragment> fragments;
private ArrayList<String> titles;

public ViewPagerAdapter(FragmentManager fm){
    super(fm);
    this.fragments=new ArrayList<>();
    this.titles=new ArrayList<>();

}

@NonNull
@Override
public Fragment getItem(int position) {
    return fragments.get(position);
}

@Override
public int getCount() {
    return fragments.size();
}

public void addFragment(Fragment fragment, String title){

    fragments.add(fragment);
    titles.add(title);

}

@Nullable
@Override
public CharSequence getPageTitle(int position) {
    return titles.get(position);
}

}
Comment: Thanks @shimma but i am trying to use viewpager2 adapter, i think FragmentPagerAdapter is of viewPager1.


Using smart switch to control GFCI outlet

Question: I have a bunch of outdoor outlets which are all connected to a single GFCI and controlled by a standard light switch inside the house.
I recently replaced the standard light switch with a lutron caseta smart switch (which requires a neutral). I used the same neutral that connects to the GFCI to connect the smart switch. Other than that the wiring is the same as before.
Everything looked like it worked fine but ever since I did this, the GFCI seems to be tripped about once per day.
The outlets are just for some LED landscape lighting.
Did I wire this incorrectly/how can I resolve the GFCI tripping every now and then?
Edit:
The GFCI seems to trip every time I turn the smart switch OFF.
Not sure how helpful the images will be as there is a lot of other wiring for other unrelated lights/switches going through the same places.
Images
Comment: Waitaminute..."Except the neutral is going to the GFCI first and then from the GFCI to the switch." If the power goes from panel -> switch, why is the neutral going to the GFCI _then_ the switch? Do you have conduit and someone got creative with the wiring?
Comment: Can you describe the actual cable layout?  Does power go to the GFCI and that has a switch loop to the switch?  And you added a new cable to the switch to bring over the neutral?    That would be a correct way of doing it.   If it's some other arrangement please help by describing it.   If power goes first to the switch, well, then you'd have a neutral so that's not it.
Comment: Can you upload pictures (without disconnecting any wires) showing how everything connects to the switch and the GFCI?
Comment: If the wiring goes panel>switch>GFCI, then there's _no reason_ for there to have _not_ been a neutral at the switch. It may not have _connected_ to the switch, but it should have been present in the box. Please do open the switch & GFCI, pull them out of their boxes **without** disconnecting any wiring and provide pics. That will _really_ help everyone determine what's going on here.
Comment: @FreeMan you're right - it's definitely going from the panel to the GFCI first - I'm just not clear what exactly happens with the wires at the GFCI (I was initially thinking the GFCI is just being bypassed and the hot wire continues over to the switch).

I will take some photos and upload when I get the chance today
Comment: Is the neutral that you are using on the switch from "Line" or "Load" side of the GFCI?
Comment: Sounds like you created a loop or an imbalance on the neutral, possibly being detected on the self test, some GFCI's complete a daily test, so if you reset it the same time it may trip the next day or a timer/ light sensor device causing the issue , I ran into similar and it was the brand of GFCI did not like an electronic switch.
Comment: @EdBeal ah thanks! It definitely is a self test GFCI. So changing it out with a non self test GFCI would resolve the problem?
Comment: Is the setup: panel->switch->GFCI/receptacle -> other receptacles? Or is it: panel -> GFCI/receptacle -> switch -> other receptacles?
Comment: @manassehkatz-Moving2Codidact It is panel->switch->GFCI/receptacle -> other receptacles. Except the neutral is going to the GFCI first and then from the GFCI to the switch.

I added the neutral connection from the GFCI to the new smart switch since there was no neutral before on the standard switch (obviously)
Comment: @manassehkatz-Moving2Codidact it's on the line side
Comment: @freeman "creative" would be one word.    Please be wrong.
Comment: @FreeMan I'm not sure why it's wired like that but the neutral wasn't needed at the light switch before so I'm guessing that is why? There is a fairly short conduit from the GFCI to where the switch is. Is this now incorrect in the current setup? Would taking the neutral directly to the smart switch and then back to the GFCI be the solution?
Answer: GFCIs don't like to be switched, so it makes perfect sense to put the switch on the protected side of the GFCI.
However, since the smart-switch is drawing its supply hot from the protected side of the GFCI, it must also draw its supply neutral from the protected side.
If it tries to take neutral from the unprotected side of the GFCI, that means it is creating a current imbalance - the switch's own hot current is coming through the GFCI but its neutral is not.  The GFCI will trip at 5 milliamps (0.6 watts) of current imbalance.   I could easily see a smart-switch NOT drawing that most of the time, but drawing it momentarily on occasion, e.g. when broadcasting to find a WiFi connection.
Answer: Your current setup is:

panel -> switch -> GFCI/receptacle -> other receptacles

That should work just fine. However, some GFCI units do not handle power cycles very well. While that should be no different from with the previous non-smart switch, there may be something different about the way the smart switch cycles. There also shouldn't be any effect from the switch constantly using power (a very small amount) to run its own circuitry, as long as hot & neutral are on the same side of the GFCI ("Line" or "Load").
All that being said, if practical, I would change the setup to:

panel -> GFCI/receptacle -> switch -> other receptacles

That would let the GFCI stay on all the time, eliminating one possible source of the problem. It would also (for better or worse, depending on your usage) give you a protected-but-unswitched receptacle.
Of course, if the switch is not near the GFCI then this may not be practical. But based on the original switch not using neutral and the new switch using neutral from the GFCI, that should mean that everything is all in one big box and then easy enough to move the switch from Line to Load. On the other hand, if neutral is being pulled back, by itself, from the GFCI to the switch then there are likely other problems.
Comment: Your answer has just been partially invalidated by a [comment](https://diy.stackexchange.com/questions/236221/using-smart-switch-to-control-gfci-outlet?noredirect=1#comment454352_236221) from the OP. He's clarified that your "change to" suggestion is actually what he's got. I'd hold off until the promised pics show up before making any edits.
Comment: I think the switch controlling the GFCI is the desired function.
Comment: @FreeMan I've updated the post with some photos/more info
Answer: Another thing to consider is that GFCI's are notoriously finicky, and become more so with age.  If you have a spare unit around, I would swap them out, and see if the problem continues.


Top Base Fractional Number

Question: For example:
$ 2^3 = 2 \cdot 2 \cdot2 $
But what about a fractional power such as:
$$ 2^{2/3} =  ? $$
1) How would I explain this?
2) How would I find value?
3) How would computers calculate this number?
Comment: 1. The first line is not a definition, rather the result of the definition for integers. 2. By plugging in the value of the definition of an exponential function. 3. As far as I know they use power series approximation due to the fact that we know the accuracy of number of decimal places by the number of terms it calculates.
Comment: @MatthewLiu  Can you elaborate question 3?
Answer: Hint: $$2\times 2\times 2=2^{3}$$ and $$(2^{3})^{1/3}=2$$ and $$2^{2/3}=\sqrt[3]{4}=\sqrt[3]{\frac{8}{2}}=\frac{2}{\sqrt[3]{2}}$$
Comment: Thanks for your reply. But question 3 has not been answered.
Comment: A computer with a Computer Algebra System calculates this number as i have written.
Answer: For question #3: In the past, when computers didn't have the vast amounts of memory they do now, finding a root often fell to such methods as bisection, Newton's method, regula falsi, the secant method, and others.  Plus, you had to write the programs, put them on cards, and be restricted to a few decimal places.  These days, there are programs that will calculate your root to whatever accuracy you wish - I don't know what algorithm they use, but often it's one that reduces the amount of time and the amount of error in finding the root.
Comment: nice answer! thanks

Top Base Fractional Number


Cannot get correct lenght of an array pionter

Question: Maybe this is something really stupid but I cannot find the way to solve it.
typedef struct Node{
    char *val;
    struct Node *next;
}Node;

int main(){
    Node *table; // hashtable
    int n, i, j, choice, search;
    //int hash_num, val;

    char doc_name1[8] = "docA.txt";
    char doc_name2[8] = "docB.txt";
    char doc_name3[8] = "docC.txt";
    char doc_name4[8] = "docD.txt";

    // allocate table
    table = (Node*) malloc(N*sizeof(Node));     //Iniciando la table con N = 30 posiciones
    //make table "heads" NULL
    for(i = 0; i < N; i++){
        table[i].next = NULL;
    }

    printf("--h(x) = xmod%d--\n",N);
    printf("\n\n");

    while(1){
        printf("1.Insertar registros\n");
        printf("2.Delete a number\n");
        printf("3.Search a number\n");
        printf("4.Show Hash Table\n");
        printf("0.Exit Programm\n");
        printf("\n--------\n");
        printf("Choice: ");
        scanf("%d",&choice);

    switch(choice){
        case 0: return;
        case 1:
            table = insert(table, doc_name1);
            //table = insert(table, doc_name2);
            //table = insert(table, doc_name3);
            //table = insert(table, doc_name4);
            break;
        case 2:
            // delete a number
            printf("Give a number: ");
            scanf("%d",&search);
            table = del(table, N, search);
            printf("\n--------\n");
            break;
        case 3:
            // search for a number
            printf("Give a number: ");
            scanf("%d",&search);
            search_table(table, N, search);
            printf("\n--------\n");
            break;
        case 4:
            //print hashtable
            printf("-HASHTABLE-\n\n");
            print_table(table, N);
            printf("\n--------\n");
            break;
        }
    }
    return 0;
}

Node *insert(Node *table, char *val){
    Node *nn, *cur;
    int lenght = strlen(val);
    int hash_index = H(val);

    nn = (Node*)malloc(sizeof(Node));   //Memoria para el nuevo nodo
    nn->val = malloc((lenght+1)*sizeof(char));
    strncpy(nn->val, val, lenght);    //Valor del nuevo nodo va a ser lo que pasamos
    nn->next = NULL;  //Siguiente apunta a null

    if(table[hash_index].next == NULL){ //Si donde apunta el indice a insertar no hay nada
        table[hash_index].next = nn;        //Insertamos ahí el nodo
        return table;                       //Devolvemos la tabla
    }
                                        //Si no
    cur = table[hash_index].next;       //cur recibe el siguiente
    while(cur->next != NULL){           //mientras que siga habiendo siguiente
        cur=cur->next;                  //seguimos avanzando
    }
    cur->next = nn;                     //Inserta al final de la lista enlazada
    return table;                       //Devuelve la tabla
}

That's not the complete code but I think is the necessary to show my problem.
The problem is that (using the CodeBlocks debugger) I can see how the variable lenght in the insert function initializes with value 8 at initial execution point. But when the function gets called and the reference to doc_name is passed, it changes to 11.
By the time writing this lines I noticed i t only showed 8 once, now it's always 11.
I can see it's somehow related to the fact that the argument val is being passed with some more characters than declared but how do I fix it?
Comment: `char doc_name1[8] = "docA.txt";` is wrong as strings in C need to be NUL terminated. So need 9 byte array for an 8 character string. Try `char doc_name1[] = "docA.txt";` That allows the compiler to work out the size of the array needed.
Comment: @kaylum, and since `doc_nameX` are never modified, they don't need to be copies of `"docX.txt"`. A pointer would be enough: `char *doc_nameX = "docX.txt";`. Or even better: `const char *doc_nameX = "docX.txt";`
Answer: These character arrays
char doc_name1[8] = "docA.txt";
char doc_name2[8] = "docB.txt";
char doc_name3[8] = "docC.txt";
char doc_name4[8] = "docD.txt";

do not contain strings because they do not have enough space to accommodate zero terminating characters '\0' of the string literals used as initializers.
Thus using the function strlen with these array like in this declaration
int lenght = strlen(val);

invokes undefined behavior.
Instead write
char doc_name1[] = "docA.txt";
char doc_name2[] = "docB.txt";
char doc_name3[] = "docC.txt";
char doc_name4[] = "docD.txt";

Another problem with strings is that in these statements
nn->val = malloc((lenght+1)*sizeof(char));
strncpy(nn->val, val, lenght);

again the zero terminating character '\0' is not copied. You need to write
nn->val = malloc((lenght+1)*sizeof(char));
strcpy( nn->val, val );

At least the second parameter of the function insert should have the qualifier const
Node *insert(Node *table, const char *val);

because a passed string is not changed within the function.


REST API learning curve

Question: I'm a newbie to the back-end, trying to build a REST API. I'm having trouble retrieving my request data from the ajax call.
<?php
$logfile = fopen("log.txt", "w");
fwrite($logfile, "testing\n");

$method = $_SERVER['REQUEST_METHOD'];
$request = explode('/', trim($_SERVER['PATH_INFO'],'/'));
$input = json_decode(file_get_contents('php://input'),true);
$req_dump = print_r( $input, true );
fwrite($logfile, $req_dump . "\n");

fclose($logfile);
?>

My call looks like this:
$.ajax({
  dataType: "json",
  type: "GET",
  url: "http://example.com/api.php",
  data: {data:"data"},
  success: function(){ console.log('success'); }
});

My log.txt file just gets the text "testing", but nothing to indicate the passed object {data:"data"}. What steps am I skipping here?
Comment: Have you watched the AJAX request / response in the browser's developer tools? Have you included the jQuery library in the project? Are there any errors reported? Are you running this on a web-server?
Comment: try to call this php script using a tool like https://www.getpostman.com/
Comment: and remove the close php tag '?>' of the  script
Answer: The ajax what you're doing is a get request and the object data is being sent as a query string in the url: /api.php?data=data, data sent as a query string in php are stored in $_GET
Try this:
<?php

$logfile = fopen("log.txt", "w");
fwrite($logfile, "testing\n");

$method = $_SERVER['REQUEST_METHOD'];
//$request = explode('/', trim($_SERVER['PATH_INFO'],'/'));
$input = json_encode($_GET,true);
$req_dump = print_r( $input, true );

fwrite($logfile, $req_dump . "\n");

fclose($logfile);

Comment: Alfredo, that works perfectly! Thanks for your help!
Comment: @user1981130, if Alfredo's answer was helpful, please accept it.

REST API learning curve


What would cause ceiling lights in a circuit to stop working after the first one?

Question: enter image description hereSo, I have three recessed ceiling lights on a single switch.  The first ceiling light turns on, but the next two do not.  Because the lights downstream of light 1 don't work, that would suggest a problem between lights 1 and 2.  I completely uninstalled both lights and even inspected the junction boxes, but I couldn't find the problem.  I reinstalled both lights and the problem persisted.  I doubt there is anything between junction box 1 and 2, so what could the problem be?
Picture Link:  https://imgur.com/a/vM7eh5C
Comment: It might just mean the lights burned out.  Check if the light bulbs work in the first one, and then check the wire connections in the first light.  all electrical connections need to be tight.
Comment: Please [edit] to describe your process for inspecting the junction boxes. 9,999 times out of 1000 that's where your problem is, so if you didn't physically check both switched hot and neutral connections in each box, go back and do that. Looking in the box without doing anything else does not solve the problem...
Comment: I swapped bulbs, so it's not the bulbs.  I've also checked and rechecked the connections.

As for the junction boxes, I opened them up, removed the wire nuts, exposed new copper on each wire and re-did the connections before adding the wire nuts back on.
Comment: Did these lights work before and just stop, or is this a new circuit wired up?  Pictures of the wires are connected in junction/light boxes and switch will help to see if wires are connected right.
Comment: The lights worked before.  I'll go take pictures now...
Comment: Here are the pictures - https://imgur.com/a/vM7eh5C
Comment: Looking at the pictures, it looks like you have mostly solid copper and some stranded **aluminum** mixed in. If that is stranded aluminum (as opposed to stranded copper, that would be fine) then you have some major problems as aluminum and copper require special procedures/equipment to connect properly.
Comment: I agree that it's copper with some stranded aluminum.  But it's the original wiring, so I hope the builders did whatever they needed to do to make it safe.  And, the lights were working just a few days ago.  Thoughts?
Answer:
I agree that it's copper with some stranded aluminum.

STOP. RIGHT. NOW.
Copper and aluminum connected together can lead to problems. Burn your house down type of problems.
Not all situations are bad. Copper wires connected to aluminum connections in circuit breaker panels are fine. But copper wire to aluminum wire or aluminum wire to devices (receptacles, light fixtures, etc.) that are not designed for use with aluminum wire are a big NO WAY.
If it is practical, the best thing to do is to replace the aluminum wires. That may be easy or it may be very hard. If it is not practical, then you need connectors designed for that use. In a quick search, the first product I found was for solid or stranded copper but only solid aluminum.
So figure out what you've got, especially where you have aluminum (pictures are not clear which segments are which) and then we can figure out a solution.
Comment: Thank you manassehkatz.  I'll replace them immediately.


Python sending email without content

Question: SMTP send empty message, I'm reading text from a file, then I want to send it.
File looks like:
Date           Time    :          Text

2019-01-18 12:56:00,022: 'something i want to say'

Tried read(), readline(), readlines().
import smtplib

A = []
fh = open("text.txt", "r")
content = fh.read()
mail = smtplib.SMTP('smtp.gmail.com', 587)
mail.ehlo()
mail.starttls()
mail.login('my_email','my_passowrd')
mail.sendmail('my_email','my_email',content)

mail.close()

It sends email, but it's empty.
Comment: Are you sure that `text.txt` file is not empty?
Comment: It's not. It's full with "2019-01-18 12:56:00,022: 'something i want to say'"
Comment: Possible duplicate of [smtplib sends blank message if the message contain certain characters](https://stackoverflow.com/questions/11796664/smtplib-sends-blank-message-if-the-message-contain-certain-characters)
Answer: I think the answer given to the following question might be the solution.
The answer mentions that content should be started with a new line. If that's not the case the content becomes part of the message header rather than the message body.
And one more point I noticed is in the documentation of smtplib, it is given that from_address and to_address should follow the RFC822 format. Once you check whether you are correctly following that format or not.
So I don't know if this would work or not, try changing "from_address" to  "<"+"from_address"+">".

Python sending email without content


how verify that operating system support avx2 instructions

Question: I have configuration: Intel(R) Core(TM) i7-4702MQ CPU (with Haswell architecture), Windows 8, Intel C++ Compiller XE 13.0.
I want run my program with avx2 optimization and put compilation flags:

/QaxCORE-AVX2, /QxCORE-AVX2

But when I run the program I get error:

Fatal Error: This program was not built to run in your system. Please verify that both the operating system and the processor support Intel(R) AVX2, BMI, LZCNT, HLE, RTM, and FMA instructions.

I run avx2 cpu support test which is given on page: How to detect new instruction support in the 4th generation Intel Core processor family.
Result:

This CPU supports ISA extensions introduced in Haswell.

How can I check that my operating system support avx2-extensions and what could be the cause of the error? For use avx2 extensions i need set both /QaxCORE-AVX2 and /QxCORE-AVX2 flags?
upd: if i set flag
/QxAVX

that program has been successfully launched.
Comment: Probably you're running in a virtual machine that didn't expose AVX2 to the guest.   i7-4702MQ definitely supports AVX and AVX2 (and the other extensions the error message complained about.)
Comment: Perhaps XSAVE is disabled. I'm not sure how to enable it, but it's probably a boot configuration.
Comment: @Mysticial i create simple win32 project with function IsProcessorFeaturePresent(PF_XSAVE_ENABLED). This function return True.
Comment: check when ? At compile time ? At runtime ? Anyway this is more like a market related issue, for example the 2955U is a Celeron formally based on the Haswell architecture but it doesn't even offer the first generation of AVX .
Comment: @user2485710 At runtime. On http://ark.intel.com/products/75119  says that AVX2 is support. On http://ark.intel.com/products/75608/Intel-Celeron-Processor-2955U-2M-Cache-1_40-GHz says that Celeron support only sse.
Comment: Also see [How to detect New Instruction support in the 4th generation Intel® Core™ processor family](https://software.intel.com/en-us/articles/how-to-detect-new-instruction-support-in-the-4th-generation-intel-core-processor-family) on the Intel blogs.
Comment: I'd be worried about HLE and RTM: Those are disabled on Haswell by microcode.  (And even on Skylake-family, HLE is I think permanently disabled by microcode updates as of late 2020 :/).  BMI and LZCNT don't need OS support; they don't have new architectural state so there's no bit the OS has to set for them to decode instead of fault.
Answer: If you want to check for the support to a particular set of registers you basically have 2 options:

assembly with CPUid extensions
builtin functions ( if ) provided by your compiler

writing assembly that detects which sets of registers are supported is a tedious, long and potentially error-prone task, not to mention that assembly it's not portable across different OSs, different SoC and different ABIs, there is also the burden of CPUid instructions which are not always implemented with the same pattern in all CPUs, there are different ways to do the reach the same bit of information with different vendors or even different family of CPUs from the same vendor; but this has one big advantage, it's not limited by anything, if you really need to know anything about your CPU/SoC, assembly + CPUid related stuff is the way to go .
Now gcc and other compilers implement something for your basic needs when you have to investigate your cpu capabilities in the form of builtin functions, which means that this special functions will generate the equivalent code in assembly and give you the answer that you want.
Using gcc, the check for AVX2 is as easy as writing
...
if(__builtin_cpu_supports("avx2"))
{
  ...
}
...

docs : http://gcc.gnu.org/onlinedocs/gcc/X86-Built-in-Functions.html
for Visual Studio / msvc there are intrinsics such as __cpuid and __cpuidex that you can use to retrieve the same informations, here it is a link with a complete and working example .
docs : http://msdn.microsoft.com/en-us/library/hskdteyh.aspx


How do I get to the courtyard?

Question: At the start of Chapter 4 of Another Code: Recollection, you're required to find the Silver Bird Key in order to open the Silver Bird Room, where D is. Marie's letter with the Woman Doll inside the East Wing Bedroom from earlier on in the game reveals that the key is in the fountain in the courtyard.
There are various guides online explaining how to get the key once you reach the courtyard, but I don't understand how you're supposed to reach the courtyard in the first place. All the guide says is that it

can be accessed by going through the large white back doors at the Mansion's entrance.

However, when I try to do exactly that, Ashley says "I don't want to see my dad right now" and refuses to go through them. I can't go out the front doors either, as Ashley refuses to leave the mansion. I don't see any other "large white back doors" in the foyer, or anywhere else, for that matter.
So what the heck am I supposed to do here? How do I get to the courtyard?
Comment: It seems like you might need to examine the Silver Bird Room door again? https://youtu.be/wwSO948klPk?list=PLjen7U7PlzEqRAMD2ad2-_mfKHPOsKoLR&t=5464
Comment: For some reason, GameFAQs doesn't give Recollection a separate guides section, and Silver Bird Room only is mentioned in Trace Memory Chapter 1: https://gamefaqs.gamespot.com/switch/426391-another-code-recollection/faqs/44169 ... Did you typo Chapter 1 as Chapter 4?
Comment: @Malady No. That walkthrough is only applicable to the original DS game, the Switch remake in *Recollection* features different puzzles and puts things in a different order.
Answer: As @Malady stated in a comment, you need to interact with the door to the Silver Bird Room to trigger a cutscene. After that cutscene has been triggered, you can then try the "large white back doors" in the foyer, and Ashley's dialogue will change to

I don't really want to see Dad right now, but... I guess I don't have much choice.

Interact with the doors again and you'll finally step out into the courtyard in search of the Silver Bird Key.

How do I get to the courtyard?


SSIS pacakge shows it ran successfully but eventually doesnt trigger the process

Question: I have created a SSIS package and SQL job to run it. When I execute the package manually it works fine. I am logging information of the job processed which I can see however when I execute the job it shows it ran successfully in job history. I have set it to log an event on failure but don't find any events either. I am not sure what the problem is. The only difference is the while running it manually its using my windows account while running it via job is its using service account. Upon verification of data I can see that the process hasnt kicked off. Could somebody tell me what the problem could be
Comment: I know I have seen many an issue along these lines where it is a permissions issue for the service account somewhere along the line.  Try running VS locally as the service account and see what happens.  You should get more informative errors
Answer: In every task in your package you will find the properties, FailPackageOnFailure and FailParentOnFailure.
If an task fails, and does not cause the package to fail due to either of these properties, then the job will show that it completed successfully even though the package errored and did not complete successfully.


detailed how to or example needed to setup an access point using netplan

Question: As headline stated: I am looking for instructions on how to setup an access point using netplan, including setting up a bridge between eth0 and wlan0. DHCP Server would be my router, to which the system is connected via eth0. I am running Ubuntu Server 18.04.
(I used to be able to do it following examples using ifupdown and hostapd, but now I need to stay with netplan..)

What packages need to be installed for this?
Beside setting up a yaml file, what needs to be done?
where is the bridge (i.e.br0) defined?
where are credentails like ssid and password  set?
Could you share an example yaml file (i.e. with eth0 wlan0) for the above scenario?
(I need a solution without using iptables, as this can not be used in my system)

As I am far from being an expert, the more detailed the instructions, the better....
Answer: I got it to work with the help of these links: 1, 2, 3, 4
This is the sequence, which worked for me (WiFi in n-Mode, static IP):

Install hostapd: apt-get update, apt-get install hostapd
unmask & enable it: sudo systemctl unmask hostapd, sudo systemctl enable hostapd
create /etc/hostapd/hostapd.conf and cut&paste:

# the interface used by the AP
interface=wlan0
driver=nl80211
# "g" simply means 2.4GHz band
hw_mode=g
# the channel to use
channel=1
# limit the frequencies used to those allowed in the country
ieee80211d=1
# the country code
country_code=DE
# 802.11n support
ieee80211n=1
# QoS support
wmm_enabled=1
# the name of the AP
ssid=yourSSID
macaddr_acl=0
# 1=wpa, 2=wep, 3=both
auth_algs=1
ignore_broadcast_ssid=0
# WPA2 only
wpa=2
wpa_passphrase=yourpassphrase
wpa_key_mgmt=WPA-PSK
#wpa_pairwise=TKIP
rsn_pairwise=CCMP

Edit the file /etc/default/hostapd and modify the line of DAEMON_CONF like this: DAEMON_CONF="/etc/hostapd/hostapd.conf"

(Testing to verify is AP is visible i.e. on phone: sudo service hostapd start; then sudo service hostapd stop again to continue setup)

cut&paste this into `/etc/netplan/network.yaml file (no tabs, just spaces, follow indentation exactly - yaml is picky...):

network:
  version: 2
  renderer: networkd
  ethernets:
    # My Ethernet adapter
    eth0:
      # For some reason it seems I must specify at least something here.
      dhcp4: no
    # My Wi-Fi adapter
    wlan0:
      dhcp4: no
  bridges:
    br0:
      interfaces:
        - eth0
        - wlan0
      # Using a static IP for this box.
      addresses:
        - 192.168.1.xxx/24
      gateway4: 192.168.1.x
      nameservers:
        addresses: [22.214.171.124,126.96.36.199]

Apply the new configuration: sudo netplan generate,sudo netplan apply
Comment: Works great for me, even with Ubuntu 20.04.


Does anyone recognize what this kind of hinge is for?

Question: I have a set of these hinges (at least, they seem to be hinges) but I'm not sure what they're for.
They measure about 1.5" (3cm) in the longest direction.
Here are some odd features:

No obvious way to attach the parts on the left with the one on the right!
Setscrew in U-shaped piece (second photo)

I assume these would be surface-mounted, they seem too thick to mortise into anything.
Comment: Might be a latch that's faintly tamper-proof.
Answer: Hinge?
I look at that and see a clamp to assemble two panels at right-angles which is designed for easy assembly or disassembly and flat-packing.
Comment: +1. Looks like some sort of Knock-Down hardware


Superscripting any Letter/Number

Question: Is there actually any way to superscript any number? In my App I need to superscript the numbers from 0 to 24.  I know that with \u2070 for example I can display a superscripted 0, but in Unicode there aren't all the numbers I need.  I just want to set a NSString to a number with an exponent, like 10^24. Is there any way to do this?
Comment: Check out the Unicode tables here http://en.m.wikipedia.org/wiki/Wikipedia:Unicode_subscripts_and_superscripts
Answer: They are scattered throughout the Unicode blocks:

\u2070 is superscript 0
\u00B9 is superscript 1
\u00B2 is superscript 2
\u00B3 is superscript 3
\u2074 is superscript 4
\u2075 is superscript 5
\u2076 is superscript 6
\u2077 is superscript 7
\u2078 is superscript 8
\u2079 is superscript 9

To put them altogether and make it easier to choose the digit, you can either use a wchar_t[] type, or store them in a string:
NSString *superDigits = @"\u2070\u00B9\u00B2\u00B3\u2074\u2075\u2076\u2077\u2078\u2079";

As an exercise you could create a method that formats an integer as a superscript string.
Comment: Note that in most typefaces in iOS, numbers 1,2 and 3 look different to the rest. See this question for more details (and a list of typefaces that are consistent):http://stackoverflow.com/questions/7663251/why-the-display-of-unicode-characters-for-superscripted-digits-are-not-at-the-sa/7663610#7663610
Comment: @BharatDodeja: There is no contiguous series for superscript letters in Unicode, they all belong to different regions and as such they may have a different "look" than others. Check [here](http://en.wikipedia.org/wiki/Wikipedia%3aUnicode_subscripts_and_superscripts#Superscripts_and_subscripts_block).
Comment: +1 @jrturton: Yes, I've noticed this in a number of fonts too. I suppose the alternative was for TUC to define `\u2070 ~ \u2079` as superscript digits that have `\u00B2`, `\u00B3`, and `\u00B9` as duplicates... but multiple codepoints for the same glyph is probably more ugly than logically sequential characters with non-sequential codepoints.
Comment: I tried the above super script code but code of 2 and 3 (\u00B2\u00B3\) is not working. Its displaying few special symbols on label. please let me know.
Answer: Well, there are all the numbers you need. Look here
Example:
ruby-1.9.3 > "1\u2070\u00B9\u00B2\u00B3\u2074\u2075\u2076\u2077\u2078\u2079"
 => "1⁰¹²³⁴⁵⁶⁷⁸⁹"

Superscripting any Letter/Number


MongoDB Scala Driver doesn't allow use Map collection in case class

Question: I just started using MongoDB and I'm trying to write a small application to test Mongo with Scala. I created the following case class in order to cast the Documents to a Scala class:
case class User(
                 _id: ObjectId,
                 userId: String,
                 items: Map[String, Int]
               )

object User {
  def apply(userId: String , items: Map[String, Int]): User =
    new User(new ObjectId, userId, items)

  implicit val codecRegistry: CodecRegistry =
    fromRegistries(fromProviders(classOf[User]), DEFAULT_CODEC_REGISTRY)
}

I get the following error but I don't know why since the Map keys are in fact strings.
[ERROR] error: Maps must contain string types for keys
[INFO]   implicit val codecRegistry: CodecRegistry = fromRegistries (fromProviders (classOf [User]), DEFAULT_CODEC_REGISTRY)
[INFO]                                                                                ^
[ERROR] one error found

I'm also applying the codecRegistry to the MongoDatabase.
Thank you very much.
Comment: What's the driver?
Comment: The official driver https://github.com/mongodb/mongo-scala-driver/blob/master/README.md
Answer: The problem was that I was using a version of the driver that is compiled for Scala 2.11 and not 2.12. By changing the Maven dependency from
<dependency>
   <groupId>org.mongodb.scala</groupId>
   <artifactId>mongo-scala-driver_2.11</artifactId>
   <version>2.2.1</version>
</dependency>

to
<dependency>
   <groupId>org.mongodb.scala</groupId>
   <artifactId>mongo-scala-driver_2.12</artifactId>
   <version>2.2.1</version>
</dependency>

solved the problem.


MySql: Preserving order in UNION ALL result

Question: I have the following:
with
result1 as ( select column1 from table1 order by ... )
result2 as ( select column1 from table2 order by ... )
select * from result1 union all select * from result2;

The intent is to list result1 with its order preserved followed by result2 with its order preserved.  However, it appears that union all does not preserve the order of its operand tables.  How can I get the intended effect?  I have tried adding columns to the ordered result1 and result2 and then order the union result on this added column, but this seems awfully klugy for something that seems pretty typical.   Is there anything like union all ordered?
Comment: Any resultset without an ORDER BY clause is unordered. The same applies to `select * from result1 union all select * from result2;`.
Comment: add to your ORDER BY a LIMIT 18446744073709551615  , so that the optimizer don't removes the order
Comment: Select 1 seq, other columns from table1 union select 2, other columns from table 2...
Answer: Ok. Here is how you sort it out with "window functions". Provided you are using MySQL 8+
with
result1 as (
select column1, ROW_NUMBER() OVER (ORDER BY ...) AS rownum1, 0 AS rownum2,
from table1 order by ...
),
result2 as (
select column1, 0 AS rownum1, ROW_NUMBER() OVER (ORDER BY ...) AS rownum2
from table2 order by ...
),
result as (
select * from result1
union all
select * from result2
)

select * from result order by rownum2, rownum1

Comment: What is the need of the internal ORDER BY clauses?
Comment: No it does not work and you can find out why if you read the documentation: https://dev.mysql.com/doc/refman/8.0/en/union.html
Comment: Also: *The intent is to list result1 with its order preserved followed by result2 with its order preserved* how does your code meet the requirement?
Comment: @forpas I edited the query. Order by, can be used at the last select only
Comment: Order by what? to preserve the order as described in the question/
Comment: @forpas Yes you are right. I edited the original answer. Now the query should work just as intent.
Comment: @forpas You are right again. I edited a solution for that. Look at my above suggested query !
Comment: Create a fiddle here: https://dbfiddle.uk/?rdbms=mysql_8.0 with some sample data and you will see that your code does not even run.


How to use an enumeration and pattern for phone in xsd?

Question: The problem is requesting the following. That the phone should have the attribute type with 3 enumerated values of home, cell, and work. AND the phone should also be restricted to a phone format of (###) ###-####.
How do you combine the attribute for enumerated vales AND apply a restricted pattern?
XML example:
<donor level="founder">
    <name>David Brennan</name>
    <address>5133 Oak Street
             Windermere, FL  34786</address>
    <phone type="home">(407) 555-8981</phone>
    <phone type="cell">(407) 555-8189</phone>
    <email>email@example.com</email>
    <donation>50000.00</donation>
    <method>Phone</method>
    <effectiveDate>1982-09-01</effectiveDate>
</donor>

xsd code I have so far for phone:
<xs:attribute name="type" type="pType" />

<xs:simpleType name="phoneType">
    <xs:restriction base="xs:string">
        <xs:pattern value="\(\d{3}\)\s\d{3}-\d{4}" />
    </xs:restriction>
</xs:simpleType>

<xs:element name="phone">
    <xs:complexType>
        <xs:simpleContent>
            <xs:extension base ="xs:string">
                <xs:attribute ref="type" use="required"/>
            </xs:extension>
        </xs:simpleContent>
    </xs:complexType>
</xs:element>

<xs:simpleType name="pType">
    <xs:restriction base="xs:string">
        <xs:enumeration value="home" />
        <xs:enumeration value="cell" />
        <xs:enumeration value="work" />
    </xs:restriction>
</xs:simpleType>

<xs:element name="donor">
    <xs:complexType>
        <xs:sequence>
            <xs:element ref="name"/>
            <xs:element ref="address"/>
            <xs:element ref="phone" minOccurs="1" maxOccurs="unbounded"/>
            <xs:element ref="email" minOccurs="0" />
            <xs:element ref="donation" />
            <xs:element ref="method" />
            <xs:element ref="effectiveDate" />
        </xs:sequence>
        <xs:attribute ref="level" />
    </xs:complexType>
</xs:element>

Answer: Your code is almost correct. But you missed to use the phoneType definition in your element's type assignment: just change the (base)type in <xs:extension base ="xs:string"> making your phone element definition
<xs:element name="phone">
    <xs:complexType>
      <xs:simpleContent>
        <xs:extension base ="phoneType">
          <xs:attribute ref="type" use="required"/>
        </xs:extension>
      </xs:simpleContent>
    </xs:complexType>
</xs:element>

Now everything should work as desired and your RegEx definition should restrict the string values.


Given two matrices A and C (containing $x$) find the value of $x$ knowing that $|A^TC|=20$

Question: Given two matrices A and C (containing $x$) find the value of $x$ knowing that $|A^TC|=20$
The two matrices are
$A=\begin{pmatrix}2x&1\\1&4\end{pmatrix}$ and $C=\begin{pmatrix}3&2\\1&2\end{pmatrix}$
How do I find $x$ knowing that $|A^T  C|=20$
I've tried a way and got an answer, but it's not fitting in.
I'll highly appreciate it if you can show me all the steps and the final answer as well.
Comment: You say "but it's not fitting in."  What do you mean by that?  Try showing your work and your answer and we can spot a mistake if one exists.  Without showing what you did, I don't know if my answer does exactly what you already thought to do.
Comment: For clarification, are you using $|~~|$ to denote determinant or matrix(operator) norm?  Also, please check that the matrices I wrote are indeed the matrices you intended.  It seems odd to refer to $A^T$ when $A$ is symmetric.
Comment: I am using it to denote the determinant
Comment: I got 24/32 now that I resolved it. How can I check if this answers works?
Answer: Hint:  Instead of trying to first compute what the matrix $A^T C$ looks like, it is better to begin using the following theorem:

For square matrices $A$ and $B$ you have:
  $$\det(AB) = \det(A)\det(B)$$

Also, you have the following:

For square matrix $A$ you have:
  $$\det(A)=\det(A^T)$$

Calculate the determinants individually (the one on the left will depend on a variable) and multiply the results.  Given the conditions in the problem, the result will be a linear equation which can be solved using elementary techniques.

Additional hint/reminder:
The determinant of a $2\times 2$ matrix is given by:
$$\det\begin{pmatrix}a&b\\c&d\end{pmatrix} = ad-bc$$
More general formulae for determinants for matrices of this or larger sizes can be found in any textbook.
Given this result and the matrices shown above we have that
$\det(C) = $

 $\det(C)=3\cdot 2 - 2\cdot 1 = 6-2=4$

Find $\det(A)$ similarly and multiply the results together and finish solving.
Comment: I tried resolving it using this way and I got 24/32. Is that right? How can I check?
Comment: @user276520 that is not the answer I get.  Are you taking the determinants of your $2\times 2$ matrices correctly?  What is the determinant you get for $A$?  For $C$?  Are the listed matrices above the correct matrices for the problem or are there typos/mistakes?
Comment: |A|=8x-1. |C|=4. |A^TxC|=(8x-1)(4)=32x-4. 32x-4=20. x=24/32 @JMoravitz
Comment: @user276520 Ah, I didn't pay close enough attention.  Yes, that is correct then.  It is best to simplify your fractions.  $\frac{24}{32}=\frac{3}{4}$


Partitions of ℤ/18ℤ

Question: I want to partition $ℤ/18ℤ$ into ${0}$, units, irreducibles and reducibles.
I think the units are $1, 5, 7, 11, 13$ and $17$ but not sure if this is even right.
Comment: That's right; the number of units is $\phi(18)=6$
Comment: Do you know how to then partition it in to {0}, irreducibles and reducibles?
Comment: You need to determine which elements are reducible and which are irreducible. Do you know how to do this?
Comment: I've got this definition but don't know how to use it. X is reducible if there exist a, b ∈ R \ R× such that x = ab
Comment: See also https://math.stackexchange.com/questions/3705573/irreducible-elements-mod-n
Answer: You got the units right; now, all the numbers 4,8,16 are reducible since they are powers of 2, which is not a unit, furthermore $2 = 2 \cdot 10$ where neither 2 or 10 are units, hence 2 is reducible too, while $9=3\cdot 3$ and $6=2 \cdot 3$. It remains to check the nature of 3,10,14,15. $14 = 2 \cdot 16$, now, since 3 divides 18, we have that if $3 = a \cdot b$ we can suppose $a =3$, then check by multiplying 3 with all the non-units you can check that this is not possible, therefore 3 is irreducible. In a similar way 15 is seen to be irreducible. At last, $10 = 2 \cdot 14$.

Partitions of ℤ/18ℤ


Solution of quadratic equation with some constraints

Question: Setting the following constraints on $(A, B,C, D)$ (reals):
$ A +  \frac{B}{2} + \frac{C}{4} +  \frac{D}{8}=0$
$ A +  \frac{B}{4} + \frac{C}{16} +  \frac{D}{64}=0$
Is it always possible to find $(A, B,C, D)$ such that:
$$ (3 AB +\frac{12}{8} BC  + \frac{48}{64} CD) X_1 + (63 A D + \frac{60}{8} BD) X_2 + 15 A C  X_3 =0$$
Where $X_1, X_2, X_3$ are fixed real numbers ?
I suppose there is except if the associated quadratic form is definite positive, but how to characterise a definite positive form ? Any reference ?
Answer: From the constraints, you can get that:
$$\begin{cases}
A = \displaystyle\frac{C}{8} + \frac{3D}{32}\\
B = \displaystyle-\frac{3C}{4} - \frac{7D}{16}
\end{cases}.$$
Pluggin this in the 3rd equation, you get:
$$C^2 (960X_3 - 720X_1) + D^2(1344X_2 - 63X_1) + CD(720X_3 + 1152 X_2 - 144 X_1) = 0.$$
Starting from this point, you can write your equation as a quadratic form in matricial fashion:
$$v^\top M v = 0,$$
where
$$v = \begin{bmatrix}C\\D\end{bmatrix} ~\text{and} ~ M = \begin{bmatrix}960X_3 - 720X_1 & \displaystyle\frac{720X_3 + 1152 X_2 - 144 X_1}{2}\\\displaystyle\frac{720X_3 + 1152 X_2 - 144 X_1}{2} & 1344X_2 - 63X_1\end{bmatrix}.$$
Now, you need to look to the eigenvalues of $M$ in order to say that $v^\top M v$ is a definite positive quadratic form. For reference on this, please take a look here.
Anyway, this approach can be a little bit messy, since the matrix $M$ depends on $3$ real parameters $X_1$, $X_2$ and $X_3$.
Instead, I would start by looking if $M$ is not full rank. In that case, then there exists a $v \neq [0, 0]^\top$, such that
$$v^\top M v = 0.$$
Comment: Thanks for your solution. Is it correct to say that the initial given quadratic form given: $$ (3 AB +\frac{12}{8} BC  + \frac{48}{64} CD) X_1 + (63 A D + \frac{60}{8} BD) X_2 + 15 A C  X_3 $$ is not definite positive thanks to the fact that its leading principal minors are not all positive ? (first one being equal to zero)


What's this game of a woman throwing a person up into the air?

Question: I found this game on TikTok and I'd love to know what it's called. Sadly the person who uploaded the video doesn't respond. Can you help me please?
Answer: Looks to be called Lady Toss.  It reminds me of "Kitten Cannon" from back in the day, where the goal is to shoot/throw something as far as possible.
Here is also a video:
Comment: Thanks for including the links, Googling that might give some weird results...

What’s this game of a woman throwing a person up into the air?


Does being mounted on a horse make fast traveling faster?

Question: Is there any difference between:

Fast travel with no horse.
Fast travel with a horse you are not currently on.
Fast travel with a horse you are mounted on.

By difference, I mean in-game time that is consumed by the fast travel.
Comment: [In TES IV: Oblivion, being mounted on a horse will improve the speed of fast traveling](http://www.uesp.net/wiki/Oblivion:Horses).
Comment: This should be easy to test. Pick up 2 cities. Press tab and check the time, then fast travel to the second town. Check the time again. Mount a horse and then fast travel back to the first town. Check the time again and compare.
Comment: Ha. I'd been wondering about this the entire time, and still haven't bothered to check. And now I know.
Answer: No, there is absolutely no difference, whether you're on foot, on a stolen horse, on a horse you own, or near a horse you own.
Tested by fast traveling between Riften stables and Markarth stables. the trip always took 26 hours and 5 minutes.
Answer: Yes, but only in one very specific instance: you're over-encumbered.  Otherwise, all forms of fast travel occur at the same speed.
http://www.uesp.net/wiki/Skyrim:Horses
http://www.uesp.net/wiki/Skyrim:Carriage#Fast_Travel
Comment: That doesn't make it faster, that just makes it possible.
Comment: Any form of fast travel is faster than no fast travel.
Comment: Wow, and that is a great reason for horses!
Comment: but...how do you get up onto the horse when you're over-encumbered?
Comment: Good one! Upvoted.


Recruitment involving Veil of Shadows

Question: As a sort of follow up question to a previous question regarding the Veil, how would recruitment work?
For example:
A) An inquisition leader recruiting a village WC holding the Veil
B) Any town recruiter trying to recruit an evil role holding the Veil (Does it differ if trying to recruit a wolf or vamp that would normally kill the recruiter?)
Answer: The game resolves these interactions by checking directly against the player's true role, not at the player's observed alignment/killer status/witchcraft status, as intel-gathering roles do.
This means that a recruitment attempt by Inquisition Leader on a Seer with a Veil of Shadows would still bounce, and an attempt against a Vampire with a Veil would still result in death for the Leader.

Recruitment involving Veil of Shadows


C++ Pointer as a member of template class

Question: I'm very new to Template Class and Template Function. So this time I tried to create my own Nullable class, that allows any object to have value, or null value.
template<typename _Type>
class Nullable
{
private:
    _Type *_Pointer
public:
    Nullable::Nullable(const _Type &x)
    {
        this->_Pointer = new _Type(x);
    };

However, when I compile it, it returns me 2 errors:

C2059: syntax error: 'this'
C2238: unexpected token(s) preceding ';'

at the line of the constructor above.
So please explain to me how to write a constructor correctly for Template class. And is it recommended to use Pointer as a member of Template Class?
Thanks in advance.
Comment: When you syntactically inline functions, the namespace of the class you are in is implicitly added, so you were trying to define Nullable::Nullable::Nullable.
Comment: Another thing to think about is who is responsible for this memory you are allocating in your constructor, since your class isn't cleaning it up.   I'd recommend instead of using a raw pointer, to use std::unique_ptr<_Type> instead, so that the memory is automatically cleaned up when your Nullable object is destroyed.
Answer: Problem 1
You are missing a ; in the line:
_Type *_Pointer;
              ^^ missing

Problem 2
When a constructor is defined inline, you can't use the scope operator.
Change
Nullable::Nullable(const _Type &x) { ... }

to
Nullable(const _Type &x) { ... }

A nitpick
You don't need the ; at the end of the constructor definition.
Nullable(const _Type &x)
{
    this->_Pointer = new _Type(x);
};
 ^^ Remove it.

It is not an error to have it there but it is not needed.
Comment: Wow, thanks, it works perfectly now. Sorry for missing the ';' :D


To parameterize a SQL statement with greater than, less than or equal to

Question: I have a SQL report. I want to pass a new parameter to this and this parameter should decide below 3 outputs.
select * from po_distributions_all:
encumbered_amount is one of the column.
Parameter Value = P, return all rows with encumbered_amount values which are > zero
Parameter Value = N, return all with encumbered_amount values which are < zero.
Parameter Value = E, return all encumbered_amount values not equal to zero
Parameter as Blank, return all the  rows.
I know I can achieve this by a union query.
Is there a way I can achieve without a union?
The query is already a lengthy one. For the simplicity of this question I mentioned it as a single line query above.
Answer: You could do this in the where clause:
WHERE
  (( :parameter = 'P' AND encumbered_amount > 0 ) OR
   ( :parameter = 'N' AND encumbered_amount < 0 ) OR
   ( :parameter = 'E' AND encumbered_amount != 0 ) OR
   ( :parameter IS NULL )
  )

Answer: What about dynamic SQL?
   sqlstr VARCAR2(1000);
   cur SYS_REFCURSOR;
BEGIN
   sqlstr := 'select * from po_distributions_all';
   IF Parameter = 'P' THEN
      sqlstr := sqlstr || ' WHERE encumbered_amount > 0';
   ELSEIF Parameter = 'N' THEN
      sqlstr := sqlstr || ' WHERE encumbered_amount < 0';
   ELSEIF Parameter = 'E' THEN
      sqlstr := sqlstr || ' WHERE encumbered_amount <> 0';
   ELSEIF Parameter IS NULL THEN
      NULL;
   ELSE
      RAISE VALUE_ERROR;
   END IF;

   OPEN cur FOR sqlstr;
   ...
END;

Answer: How about CASE expression? Could've been simpler if there were no E option :)
This is a SQL*Plus example; depending on tool you use, its '&&parameter' substitution variable could be :parameter or something else.
SQL> WITH
  2     po_distributions_all (encumbered_amount)
  3     AS
  4        (SELECT -200 FROM DUAL
  5         UNION ALL
  6         SELECT 100 FROM DUAL
  7         UNION ALL
  8         SELECT 0 FROM DUAL)
  9  SELECT *
 10    FROM po_distributions_all
 11   WHERE (   CASE
 12                WHEN    '&&parameter' <> 'E'
 13                     OR '&&parameter' IS NULL
 14                THEN
 15                   SIGN (encumbered_amount)
 16             END =
 17             CASE
 18                WHEN '&&parameter' = 'P' THEN 1
 19                WHEN '&&parameter' = 'N' THEN -1
 20                WHEN '&&parameter' IS NULL THEN SIGN (encumbered_amount)
 21             END
 22          OR CASE WHEN '&&parameter' = 'E' THEN encumbered_amount END <> 0);
Enter value for parameter: P

ENCUMBERED_AMOUNT
-----------------
              100

Negative values:
SQL> UNDEFINE PARAMETER
SQL> /
Enter value for parameter: N

ENCUMBERED_AMOUNT
-----------------
             -200

All values except zero:
SQL> UNDEFINE PARAMETER
SQL> /
Enter value for parameter: E

ENCUMBERED_AMOUNT
-----------------
             -200
              100

All values (parameter's value is NULL):
SQL> UNDEFINE PARAMETER
SQL> /
Enter value for parameter:

ENCUMBERED_AMOUNT
-----------------
             -200
              100
                0

SQL>


How to extend the kde part using distplot?

Question: plt.figure(figsize=(6, 4))
ax = sns.distplot(np.log10(df['income']), kde=True, hist=False, rug=False, kde_kws = {"bw": 0.35})
plt.xlabel('Gross national income per capita, Atlas method: $: 2016')
plt.ylabel('')
plt.title('World Bank Gross Nationnal Income Per Capita')
plt.xlim(0.7, 6.3)
plt.ylim(-0.05, 0.73)

I use this code and got this plot:

but I want the plot to look like this:
Answer: sns.distplot() has been deprecated in the current seaborn version (0.11.2). To draw a kde curve, sns.kdeplot() can be called directly, as it has parameters which help for this use-case.
Default, the kde is extended to 3 times the smoothing bandwidth, which usually works well. You can increase it with sns.kdeplot(..., cut=4). If you want to cut off at a certain spot, you can combine with clip=, e.g.: sns.kdeplot(..., cut=4, clip=(1,6)).
kdeplot also has a log_scale=True parameter, which will take the log base 10 of the data to generate the curve, and show the x-axis in log scale. With logscale=True, cut and clip will also use log units.
Here is some code illustrating these options:
from matplotlib import pyplot as plt
import seaborn as sns
import numpy as np

sns.set()
data = 10 ** np.random.normal(3.5, 0.7, 20)
fig, (ax1, ax2, ax3) = plt.subplots(ncols=3, figsize=(14, 3), sharey=True)
sns.kdeplot(data, log_scale=True, ax=ax1)
ax1.set_title('Default')
sns.kdeplot(data, log_scale=True, cut=4, ax=ax2)
ax2.set_title('cut=4')
sns.kdeplot(data, log_scale=True, cut=4, clip=(1, 6), ax=ax3)
ax3.set_title('cut=4, clip=(1, 6)')
plt.tight_layout()
plt.show()

Comment: `kdeplot` has always been around: `distplot` is just calling it internally. It did gain a lot of features in 0.11.0, though.
Answer: Just add 'cut':3 to kde_kws
for example, kde_kws = {"bw": 0.35,'cut': 3}
Comment: Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer).


Not able to deactivate Alt+Shift for switching between sources. Need it for smart column selection in the text editor

Question: I have successfully updated Ubuntu 18.04 to 20.04. While updating I was asked to set a keyboard shortcut to switch between Latin (not sure something like this) and US keyboard layout and I was unfortunately stupid enough to set it to Alt+Shift.
Now I got problems because I would like to use this shortcut to start a smart column selection in the text editor (actually c++ programming). But anytime I press Shift+Alt the source language is switched instead.
The Settings->Keyboards Shortcuts->Typing->"Switch to next input source" are set to Super+Space (no Alt+Shift at al) Also tried to disable this issue. No effect.
This shortcut / setting seems to be hidden quite deep.
Many thanks for any good idea how to resolve it
Cheers
Comment: What is your desktop environment? GNOME, KDE, whatever? What is the output of `cat /etc/default/keyboard | grep XKBOPTIONS` .
Comment: The desktop environment is GNOME
The output of cat /etc/default/keyboard | grep XKBOPTIONS is
XKBOPTIONS="lv3:ralt_switch,terminate:ctrl_alt_bksp
I have already deleted grp:alt_shift_toggle string from there. No effect
Answer: The options for toggling keyboard layout are those starting with grp: in man xkeyboard-config.
You have chosen grp:alt_shift_toggle when configuring your system. To revert it to the defaults,
simply delete that string from /etc/default/keyboard via text-editor. It may also be possible
via dpkg-reconfigure keyboard-configuration. which is an interactive tool, but I'm not sure if
it will ask about that option. Worth giving it a try.
Comment: Thank you. I have already done it. Here is the content of my /etc/default/keyboard
Comment: Sorry. I was too fast :)
XKBLAYOUT="us"
XKBVARIANT=""
BACKSPACE="guess"
XKBMODEL="pc105"
XKBOPTIONS="lv3:ralt_switch,terminate:ctrl_alt_bksp"
Comment: It does not help. The same behavior as before


Top row of keyboard (volume etc.) have started doing different things

Question: I'm running Ubuntu 20.04 on a Dell XPS15 9500. A few days ago, the buttons on the top row of my keyboard stopped working properly. They seem to be assigned to different things. For example the mute button launches a help page.
I haven't changed my keyboard settings, and if I look at the keyboard setting, launch help browser is disabled for example. But volume up, volume down, brightness up, brightness down etc. are all doing different things.
Comment: You probably pressed Fn Lock button. Press it again.
Answer: The top row of this laptop doubles as function keys and media keys. By default, the media keys are in effect, and one has to hold down Fn to access the function keys. You can hit Fn+Esc to change the behaviour - hitting "Mute" will then act as F1 (which is what you currently have) and Fn+F1 will act as the mute key.
If the change is not remembered between reboots, then you can still change how these keys behave after startup in the computer's Bios settings.
Comment: It seems like the issue is that media keys are doing *different* media tasks than they did originally, not that they are acting as media keys rather than function keys.


How to query to couchdb by key and string search

Question: I'm new to CouchDB and I have documents like this:
{
    "credit_type" : "ADJ",
    "particular" : "Adjusted hours on 2018-01-01"
}

Then I have a view with this Map function
function(doc) {
   if(doc.credit_type == "ADJ") { emit(doc.particular, doc); }
}

My view url is like this:
http://mywebsite.com:5984/_utils/database.html?client_docs/_design/adj/_view/adj

What I want to do is be able to query documents that will match my search key. The lookup field is the particular field.
The search key is a date like 2018-01-01 When I put they search url like
http://black-widow.remotestaff.com:5984/client_docs/_design/adj/_view/adj?key=20180-01-01

I should be able to fetch records which contains 2018-01-01 string in the particular field
I don't have any reduce function yet
Comment: I do not think your view is any help to you as it is not indexed on the information you want to find. You have two main options: go through all your "ADJ" docs and check the text of the "particular" field, or extract the date from the particular field and create a view to index it.
Comment: If you want to stick to text search, you will need Apache Lucene
Answer: In order to search by some key, you must emit that key.
For you to be able to do this, I would suggest potentially moving the date out of the particular field, into its own field, this way you wont have to do any string parsing on the particular field to grab your date.
If you do not or can not do this, the you will have to parse the particular field for the date. This can be achieved by this question and answer.*
Once you have gotten the date, you will need to emit it, so let me give you an example.
function(doc){
    String date = doc.particular.parse.date.here();

    emit([date, doc.credit_type], doc.particular);
}

Here, we parse the date from the doc.particular field, and emit it along with the credit type. Now, you can keep your if statement as it is, but doing it this way means you can search for ANY credit_typevs just the ADJ.
Now your keys should be 2018-01-01 and ADJ.
*You will need to make sure that CouchDB version of JS supports these functions.


How do I install roofing material on a roof with a ridge vent?

Question: I am helping a friend repair his roof; his roof has a roof vent at the peak of the roof.  I've done a few roofs, but never with a roof vent.  So any help in how you roof with a roof vent?  I assume there's no roof cap underneath, since it vents the attic...  Any tips would be very helpful.
Comment: Check out [this blog post](http://diy.blogoverflow.com/2011/12/resuscitating-the-roof-providing-adequate-roof-ventilation/)
Answer: You will need to remove the ridge vent so you can shingle up to the cut opening, and under where the ridge vent attaches.  If you can salvage it great, but otherwise, install a new ridge vent. Do not try to mickey mouse your last row of shingles under it to avoid taking it off. You WILL be sorry the first time it rains.
Comment: Yes I figured, we're going to do it right.  Thanks.


Examples of polynomial injections $f:\mathbb{N}\times \mathbb{N}\to \mathbb{N}$

Question: I've seen that there are polynomial bijections $f:\mathbb{N}\times \mathbb{N}\to \mathbb{N},$ for example $f(m,n)=\frac{1}{2}(n+m)(n+m-1)+m.$ I'm looking for more examples of injective polynomials from $\mathbb{N}\times \mathbb{N}\to \mathbb{N}.$ Are these common? Are there simple examples that are easy to prove injective?
Also, I should clarify that I am looking for an example that is fundamentally different than the example I gave, not just modifications of it. Preferably there would be a simple explanation of why this example was injective.
Comment: If your given $f$ is a bijection (haven't checked but I trust), just add a strictly positive natural constant $c \in \mathbb N^+$ to $f$ and you are done
Comment: Related $\;-\;$ [Is There An Injective Cubic Polynomial $\mathbb Z^2 \rightarrow \mathbb Z\,$?](https://math.stackexchange.com/questions/1073961/is-there-an-injective-cubic-polynomial-mathbb-z2-rightarrow-mathbb-z)
Comment: They probably put it in because you are looking for a specific type of function (injective nonsurjective), which is a set theoretic question. I don't know if the tag is needed or not though. @subrosar
Comment: Surjective is fine actually. It just doesn't have to be surjective. I changed the wording to make it less ambiguous.
Comment: I see, that edit is more clear
Comment: Can you define "fundamentally different" precisely?
Comment: @GregMartin No, I can't. That's why I added the soft-question tag. I guess I'm trying to find a general technique for proving injectivity of various polynomials.
Answer: It's easy to construct injective polynomials from $\Bbb N$ to $\Bbb N$: any increasing polynomial will do, for example, and thus any (nonzero) polynomial with nonnegative coefficients will do.
This observation might seem irrelevant, but note that if $g_1,g_2,h\colon \Bbb N\to \Bbb N$ are injective polynomials, then
$$
h\Big( f\big( g_1(m), g_2(n) \big) \Big)
$$
(where $f$ is the polynomial in the OP) is an injective polynomial from $\Bbb N^2$ to $\Bbb N$. One can generate a huge number of examples this way.
Comment: (+1) Extremely clever! And much easier than my idea, haha.
Comment: This is a good answer, but it's not quite what I was looking for since these are all essentially the same example. I will edit my question to clarify what I am looking for.
Answer: Apparently there is such an injection:
$$
(3x^2 + x + 1) + (3x^2 + x + 1 + 3y^2 + y + 1)^2
$$
I found this in a comment at this MO question, and they also link this article, which provides a wealth of information on a related problem (finding polynomial injections $\mathbb{Z}^4 \hookrightarrow \mathbb{Z}$), and thus, by plugging in $f(x,x,y,y)$, on this problem.
As an aside, it's well known that every integer polynomial $\mathbb{N}^2 \to \mathbb{N}$ can be written as a linear combination of the form
$$
p(x,y) = \sum a_{ij} \binom{x}{i} \binom{y}{j}.
$$
I don't have the time to come up with anything right now, but it seems reasonable that you could play around with this representation in order to force injectivity.

I hope this helps ^_^


Scaling generated content in CSS

Question: How do you scale an image added in :before or :after in CSS?
For example, I have a page which contains a book cover:

I want to use CSS to make it look more like a book, rather than just a cover.  I can use :before to add a second image to do this, but as all books vary in size, I need to be able to scale this image to fit the book cover.
I have tried
.book:before{
    content:url("/images/book.png");
    position:absolute;
    height:100%;
    width:100%;

}

but this doesn't work in scaling the image.
Answer: you can scale it:
transform: scale(0.7);

but it won't work with px or %.
Comment: -webkit-transform: scale(0.7)
Worked for me.
Answer: The generated image is always displayed 1:1. You cannot scale it. When you fix the size of the generated element, that works well. You could check it with the following CSS attributes:
#logo-image:before
{
    display: block;
    content: url(img/logo.png);
    width: 300px;
    height: 100px;
    border: solid 1px red;
    overflow: scroll;   /* alternative: hidden */
}

You can see the red border at the specified size, and the image content is clipped. But if you leave out the overflow:scroll, you will see the image exceeding its element.
(Tested on Firefox 11)
Answer: Try setting a min-height and a max-height for both of them to the same value, It should then scale the images to the correct size while keeping the correct aspect ratio. (And do that with the width, depending on which one you want to scale)

Scaling generated content in CSS


GLSL Uniform Layout Spec says member array stride alignment is rounded up to vec4?

Question: in GLSL spec section 126.96.36.199 about Standard Uniform Block Layout, rule (4) says:

If the member is an array of scalars or vectors, the base alignment and array stride are set to match the base alignment of a single array element, according to rules (1), (2), and (3), and rounded up to the base alignment of a vec4.

I am not sure about the rounding of array stride to the base alignment of a vec4?
What does it mean the array element stride would be for a Uniform member looking like that:
struct MyStruct
{
   float myArray[7];
}

uniform MyStruct myStruct;

Answer: It does mean exactly that. Whenever you have an array, it's treated as an array of vec4s with regards to the memory layout. So in your float array you actually have 28 floats with each of the 7 values followed by 3 values of (basically unnecessary) padding to round each array element's alignment up to 16 byte (the size of a vec4). And yes, that's why std140 layout plain sucks! ;-)
However, do keep in mind that this only applies to uniform blocks, i.e. uniform data sourced from buffers. Your example actually isn't that. You merely declared a non-block uniform that happens to be a structure/array. This doesn't adhere to the same layout rules as an actual uniform block (and you don't really know/care how it's laid out), as there is no need to synchronize the layout of an arbitrary memory chunk between the GL and youself. Good old glUniform explicitly knows what data it gets.


why i get last data in column sqlite android

Question: i want to get all title and theme_filepath on id of table book = book_id of table theme but i get a last title and theme file_path can you check a logic in my code please.
this is my code
public HashMap<String, ArrayList<String>> getBookTheme(){

    HashMap<String, ArrayList<String>> hm = new HashMap<String, ArrayList<String>>();
    ArrayList<String> list_book = new ArrayList<String>();
    ArrayList<String> list_theme = new ArrayList<String>();

    Cursor cursor = db.rawQuery("SELECT title, filepath FROM " +
                BooksDBHelper.TABLE_BOOK + " INNER JOIN " + BooksDBHelper.TABLE_THEME +
                " ON " + BooksDBHelper.TABLE_BOOK + "." + BooksDBHelper.KEY_ID + " = " +
                BooksDBHelper.TABLE_THEME + "." + BooksDBHelper.KEY_BOK_ID +
                " WHERE " + BooksDBHelper.TABLE_BOOK + "." + BooksDBHelper.KEY_ID + " != ? ", new String[]{Integer.toString(0)});
    cursor.moveToLast();
    if(cursor.getCount() != 0){
        do{

            list_book.add(cursor.getString(cursor.getColumnIndex(BooksDBHelper.KEY_TITLE)));
            list_theme.add(cursor.getString(cursor.getColumnIndex(BooksDBHelper.KEY_fILEPATH)));

        }while(cursor.moveToNext());

        hm.put("title", list_book);
        hm.put("theme", list_theme);
    }

    return hm;

}

thank you
Answer: Because of cursor.moveToLast().
Consider replacing
cursor.moveToLast();
if(cursor.getCount() != 0){

with
if (cursor.moveToFirst()) {


Untrusted Application Launcher

Question: So I'm trying to create a desktop icon for an application, and I dragged it from the top-left menu (I think it's called Dash or something). I clicked on it and it says it is untrusted and refuse to execute it.
I found out that I have go to Permission and check the checkbox saying "Allow executing file as program". However, when I open up the Permission dialog it says "I am not the owner, therefore I cannot change those settings." Everything is disabled and I can't check it.

Why is this happening and how do I "make myself the owner"?
Answer:
Open a terminal with Ctrl + Alt +T then run this command:
cd ~/Desktop
sudo chmod +x sublime_text.desktop

Change Desktop to whatever your desktop is called in your language.
chmod is a command line command to change permissions, +x make it executable
or instead you can run:
cd ~/Desktop
sudo chown yourusername sublime_text.desktop

chown is command line command to change file owner
Comment: Thanks this works. The shortcut becomes executable when set it via command line, but when I try to do it to change file owner it doesn't work
Comment: you have changed "yourusername" with your username on the system.

 try: sudo chown yourusername:yourgroupname sublime_text.desktop

to change the group too (group name is same as username, most desktop linux)
Comment: Yes I did change it. I figured it out, I have to re-login to see the effect. It worked, thank you so much!
Answer:
Open a terminal with ctrl+alt+T and type in the terminal: gksu nautilus

Enter your password when prompted and your file browser should emerge.
This will make you root until you close the file browsing window, which is necessary to edit the file (as you can see that only "root" has permission.

In here navigate to the file you want to edit. Now you can set the file to execute as program.

Be advised to use gksu with extreme caution. Everything you delete will be deleted permanently. Making changes to the wrong files is really easy this way and could leave you with an unusable system!
This is AFAIK about getting ownership of a file that belongs to Root
Comment: It should work, That's why I think @Derek朕會功夫 may missed the folder as default for root is `/root/Desktop`.
Comment: @Nkciy84 I believe that's the problem, sorry for the slow response, and thanks for solving my problem.
Comment: It does open up the file browser but when I navigate to Desktop there's nothing there.
Comment: Yeah, Because you run it as user **root**. So the one you see empty is `/root/Desktop/`. Your user should be in `/home/yourusername/Desktop/`.
Comment: Is my answer not usefull at all? I'd like to know so don't hesitate to downvote if it didn't help.
Answer: Figured out an answer:

Open Terminal
Type sudo -H nautilus
Ignore the messages, go to the opened Nautilus
Open the Desktop folder
Find the icon for your "untrusted program"
Right click the icon
Select Properties
Click the Permissions tab
Check the box by Allow executing file as program
Reboot

Untrusted Application Launcher


Using too much Ram in Java

Question: I'm writing a program in java which has to make use of a large hash-table, the bigger the hash-table can be, the better (It's a chess program :P). Basically as part of my hash table I have an array of "long[]", an array of "short[]", and two arrays of "byte[]". All of them should be the same size. When I set my table size to ten-million however, it crashes and says "java heap out of memory". This makes no sense to me. Here's how I see it:
1 Long + 1 Short + 2 Bytes = 12 bytes
x 10,000,000 = 120,000,000 bytes
/ 1024 = 117187.5 kB
/ 1024 = 114.4 Mb

Now, 114 Mb of RAM doesn't seem like too much to me. In total my CPU has 4Gb of RAM on my mac, and I have an app called FreeMemory which shows how much RAM I have free and it's around 2Gb while running this program. Also, I set the java preferences like -Xmx1024m, so java should be able to use up to a gig of memory. So why won't it let me allocate just 114Mb?
Comment: You could use a memory profiler to see what exactly is going on.
Comment: Could you come up with a minimal self-contained example that you think uses too much space, and post it together with the exact `java` command line you're using?
Comment: Could you try a lesser size? To exclude that it might be some awesome recursion.
Comment: Oh, by the way, if I try it with a size of nine-million, it works fine.
Comment: Post code that can reproduce your problem, profile your memory on your own.
Comment: Here's an example: Hash_TABLE_SIZE = 10000000; long[] pos = new long[Hash_TABLE_SIZE]; short[] vals = new short[Hash_TABLE_SIZE]; byte[] depths = new byte[Hash_TABLE_SIZE]; byte[] flags = new byte[Hash_TABLE_SIZE];
Comment: (I deleted my incorrect reply, as I was mixing up normal primitives and arrays of primitives)
Comment: Which JVM are you using? What version of Java?
Comment: I'm using the bluej virtual machine. I know bluej sucks, but I have to use it for my AP Computer Science class.
Comment: You should edit your question instead of posting code in the comment.
Comment: BlueJ is an IDE, not a JVM. What JVM are you running? How did you pass `-Xmx1024m` to the JVM? Are you sure the JVM actually picked up that flag?
Comment: @MattBall It is actually a JVM as well---and a language, which is not 100% Java (lacks features).
Comment: I tried this at the command line: java -Xms512m -Xmx1024m and I still can't initialize my array. When I try it with size nine-million then it works and says its only using about 105MB
Answer: You predicted that it should use 114 MB and if I run this (on a windows box with 4 GB)
public static void main(String... args) {
    long used1 = memoryUsed();
    int Hash_TABLE_SIZE = 10000000;
    long[] pos = new long[Hash_TABLE_SIZE];
    short[] vals = new short[Hash_TABLE_SIZE];
    byte[] depths = new byte[Hash_TABLE_SIZE];
    byte[] flags = new byte[Hash_TABLE_SIZE];
    long used2 = memoryUsed() - used1;
    System.out.printf("%,d MB used%n", used2 / 1024 / 1024);
}

private static long memoryUsed() {
    return Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory();
}

prints
114 MB used

I suspect you are doing something else which is the cause of your problem.
I am using Oracle HotSpot Java 7 update 10
Comment: ...like using BlueJ instead of a real JVM.
Comment: @MattBall I didn't think I needed to provide the JVM used, but I suspect you are right.
Comment: Last half hour I've been busy researching BlueJ and its feature set seems to point towards a JVM built on top of JVM. BlueJ is written in Java, but provides many interactive features that resemble dynamic languages, and which can't be replicated in professional IDE's that use production VMs.
Answer: Has not taken into account that each object is a reference and also use memory, and more "hidden things"... we must also take into account also the alignment... byte is not always a byte ;-)

Java Objects Memory Structure
How much memory is used by Java

To see how much memory is really in use, you can use a profiler:

visualvm

If you are using standard HashMap (or similar from JDK), each "long" (boxing/unboxing) really are more than 8bytes), you can use this as a base... (use less memory)

NativeIntHashMap
Answer: From what I have read about BlueJ, and serious technical information is almost impossible to find, BlueJ VM is quite likely not to support primitive types at all; your arrays are actually of boxed primitives. BlueJ uses a subset of all Java features, with emphasis on object orientation.
If that is the case, plus taking into consideration that performance and efficiency are quite low on BlueJ VM's list of priorities, you may actually be using quite a bit more memory than you think: a whole order of magnitude is quite imaginable.
Answer: I believe one way it would be to clean the heap memory after each execution, one link is here:
Java heap space out of memory

Using too much Ram in Java


How to use the Tiny Music Box?

Question: I have a Tiny Music Box, which I have been trying out with a few different enemies. I noticed it doesn't seem to affect normal enemies, nor the first boss, Cleric Beast.
It looks like it affected the 2nd boss, Father Gascoigne, though. He covered his ears for a brief second, but I wasn't close enough to attack him afterwards.
I wonder if someone can shed some light on how to effectively use this item?
Answer: You should use it in the third and final phase of the Father Gascoigne encounter. If you're able to fully complete the animation -- I believe it takes a second or two -- Father Gascoigne will be stunned for a few seconds. You should have enough time to get in a few attacks, or lob an Oil Urn followed by a Molotov Cocktail for heavy damage.
If there are any other uses for the music box, I haven't encountered them yet.
Comment: According to the fextralife wiki, you can also use it on another boss fight, and it makes it sidestep (seems pretty useless but it is another use for it). You can see more about it on this page http://bloodborne.wiki.fextralife.com/Tiny+Music+Box (be careful as the wiki may contain potential spoilers for the game, including this particular boss).

How to use the Tiny Music Box?


Do I need a stud on each side to install a swinging shower door?

Question: I recently started looking into installing a glass shower door for my stall shower. The shower is a one-piece fiberglass pre-fab shower. I assume I need a stud on at least one side of the door to screw the frame into. (through the shower, into the wall, into a stud.) My problem is that I checked both walls and found out that the studs aren't lined up on both sides.
Luckily, the side I would put the hinge on lines up with the edge of the shower. It makes sense to me that the majority of the force/moment is going to be on the hinge side of the frame. However, I'm worried about what might happen if the shower door is slammed shut, applying a large impulse to the side of the frame not anchored into a stud.
So am I screwed because my builder didn't have enough foresight to line up the studs on both sides of the shower, or is one side good enough?
EDIT: What type of anchors should I use, if I decide to put in the shower door with only a stud on the hinge side? Should I drill out  the fiberglass and stick an anchor just in the drywall behind it? Do anchors exist that will span the 1.5" gap between the fiberglass shower and the drywall?
Answer: You may be OK if you use proper anchors. I assume this is drywall. The shower door shouldn't be that heavy but you certainly don't want a bunch of glass raining down on someone. It would probably be a good idea to put a stud if you still don't feel the anchors will work for you.
Comment: Some single stall shower doors that are say less than 30 inches wide actually have a hinge point that is not at the extreme edge of the door. Instead a hinge point is maybe a third of the way from the edge at the bottom and the top. Support of the top hinge point involves installing a head railing across the top of the opening. This type of hinge greatly reduces the amount of stress on the wall structure or fiber glass side of the shower where a conventional hinge would be located.
Comment: What type of anchors would work though? I'd have to drill through the fiberglass first, and then there's a 1.5" gap between that and the drywall. Also, if it's a big enough project to require tearing open the wall to put a stud in, I think I'd rather tear out the fiberglass shower and tile it.
Comment: Trying to put an anchor through drywall from the fiberglass with a 1.5" space in between will surely pop the drywall when you apply any pressure to the connection. In addition I suspect that when the anchor went into a stud behind the drywall the drywall will be OK but the fiberglass structure will get undo stress on it when tightening down the anchor enough to hold the door frame securely.
Answer: I recently installed a door kit that was meant for use with a fiberglass shower. The kit came with anchors for the track and recommended that I use silicone caulk to further secure/seal the track to the shower wall. The anchors weren't deep enough to reach the wall behind the shower, so it's definitely not tied into anything other than fiberglass. It's been several months years so far with no signs of damage or wear to the fiberglass.
So if you're using a kit specifically designed to be compatible with fiberglass showers, you most likely don't need to anchor into a stud.


Hive Metastore initialisation

Question: I am trying to set up metastore for Hive but getting error saying:

"Hive metastore is not initialized"

I tried it with derby and mysql but I am getting the same error for both the database.
Comment: maybe check out the answers in http://stackoverflow.com/questions/35655306/hive-installation-issues-hive-metastore-database-is-not-initialized
Comment: Hi I already tried all the solutions provided in stackover flow and other sites but none of them works for me. Do you have an other solution ?
Comment: hi do you have another trick to solve this problem or could you please provide me any better link to re install the hive on my machine ?
Answer: For a mysql databasem you first have to create a userhive and a metastore database. You then have to initialize the metastore thought the below command:
<code>$HIVE_HOME/bin/schematool  -dbType mysql  -initSchema
</code>
This will initialize the schema.
more detail on that tutorial

Hive Metastore initialisation


Transparency background wrong on Dual-screen

Question: Using compiz with transparency behind windows and borders on a dual-screen system; all works fine, but the background that shows through with any transparency done by compiz is wrong.
It appears to be using the whole-width image from the display to generate the transparent image, but applying it to each display separately; so it's squished horizontally by 50%, and doesn't match the foreground.
Cripes this is hard to put into words... if anyone can tell me how to grab a screengrab I can paste it somewhere!
I'm an ubuntu veteran -- but new to ubuntu desktops!
(Display controller is ATI Technologies Inc Radeon X1650 Pro)
Answer: Have found a russian website that google managed to kind-of translate, which seemed relevant.
Had instructions for updating radeon drivers from a third-party ppa - which I've tried and it seems to work so far... posting here in case anyone can cast any light - or knows who to report it to for fixing in next ubuntu release.

sudo add-apt-repository ppa:xorg-edgers/radeon
sudo apt-get update
sudo apt-get dist-upgrade


Python - re.sub return pattern rather than replacing

Question: I am trying to revise a list of dictionary keys in Python 3 so that they are identifiable by the first set of numbers in the dictionary but it appears to be returning the regex pattern rather than the set of numbers.
>>>> import re
>>>>re.sub(r'GraphImages_[0-9]{2}_edge_media_to_caption_edges_0_node_text', '(?<=GraphImages_)\n{3}', 'GraphImages_99_edge_media_to_caption_edges_0_node_text')
'(?<=GraphImages_)\n{3}'
>>>>re.sub(r'GraphImages_[0-9]{2}_edge_media_to_caption_edges_0_node_text', '(?<=GraphImages_)\n{3}', 'GraphImages_123_edge_media_to_caption_edges_0_node_text')
'(?<=GraphImages_)\n{3}'

When the intended output from the above output would be 99 and 123 respectively.
Any guidance would be much appreciated. I am not very adept at the re package
Answer: Found a cumbersome workaround in the following
try_1 = re.sub('[^0-9]', "", 'GraphImages_99_edge_media_to_caption_edges_0_node_text')
try_2 = re.sub( '0$', "" , try_1)

Answer: If you just want to extract the numbers, you need to find them, not to replace:
re.findall("GraphImages_([0-9]{2,})", yourstring)[0]
#'99'

In fact, in your case a split may be a better choice:
yourstring.split("_")[1]
#'99'

Answer: You may use
^\D+(\d+).+

See a demo on regex101.com.
Comment: Thanks for your suggestion! I get the following curious traceback.
```error: bad escape \D at position 1``` which led to putting extra ```/``` to no avail
Comment: This is to say that I don't think it's a problem with your or my regex but my lack of understanding about ```re.sub```


What do the numbers next to the recipes in the crafting window mean?

Question: In my crafting window there are numbers next to all the items I can make, but I don't know what they mean.  I initially thought it was how many I could make with stuff I had on hand, but in my screenshot I can clearly make 3 when it says 0.  Is it bugged or does it mean something else entirely?
Answer: Those figures are supposed to show how many of the item you can make, I believe the fault you have pointed out is because of the systems inability to differentiate between your characters inventory, and yoru cargo hold inventory :S
Additionally the intensity of the colour indicates how much of a boost the item will give the crafting skill when made:

grey ( + 0 pt )
green ( + 1 pt per 2 items made )
yellow ( + 1 pt per item made )
orange ( +2 pt pre item made ) ~VMT to sarge-smith, and mufasa for this information~

It might be worth popping into the devtracker forum and letting them know about this.
Comment: The color indicates the level compared to your max. So gray won't help you level the skill at all. Green a little, yellow more, orange the most.
Comment: specifically, green increases your skill level 1 pt/2 made. yellow 1pt/1 made. and orange 2pt/1made.
Answer: They're supposed to represent how many you can craft.
But, as you've noted, the crafting UI is just a little bit broken.


Why do I get 'Next is not a function' when I try to export a Middleware function to module.exports object?

Question: I have a middleware function written inside my logger.js module which I then import into app.js and use

// ------ File : logger.js ------ //

function log(req, res, next) {
  console.log('Logging details ... ');
  next();
}

module.exports = log;

// ------ File : app.js -------- //

const logger = require('./logger');

app.use(logger);

The above code works without any issue and my log functionality works. However, if I export this log function in the following way (add it to the module.exports object), I get an error

// ------ File : logger.js -------//

function log(req, res, next) {
  console.log('Logging details ... ');
  next();
}
module.exports.log = log;

// ------ File : app.js -------- //

const logger = require('./logger');

app.use(logger.log());

Logging details ...
D:\express-demo-worked\logger.js:4
    next();
    ^

TypeError: next is not a function
    at Object.log (D:\express-demo-worked\logger.js:4:5)
    at Object.<anonymous> (D:\express-demo-worked\app.js:18:16)
    at Module._compile (internal/modules/cjs/loader.js:738:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:749:10)
    at Module.load (internal/modules/cjs/loader.js:630:32)
    at tryModuleLoad (internal/modules/cjs/loader.js:570:12)
    at Function.Module._load (internal/modules/cjs/loader.js:562:3)
    at Function.Module.runMain (internal/modules/cjs/loader.js:801:12)
    at internal/main/run_main_module.js:21:11
[nodemon] app crashed - waiting for file changes before starting...

Can someone explain to me why this behaves differently and how to correct the second code snippet I added here?
Comment: I'm no expert with express, or the ES6 module system - but it appears to me that you've made a simple mistake of making the function call in `app.use(logger.log());` rather than simply passing the function reference: `app.use(logger.log);`
Comment: Possible duplicate of [*setTimeout calls function immediately instead of after delay*](https://stackoverflow.com/questions/27643714/settimeout-calls-function-immediately-instead-of-after-delay)?
Answer: app.use(logger.log());

This will call logger.log immediately, passing in no arguments. Whatever logger.log returns will then be passed into app.use. Since you passed in no arguments, next is undefined, resulting in that exception.
Instead, do:
app.use(logger.log);

This will pass logger.log into app.use. At some point later, logger.log will be called, passing in the correct arguments.
Answer: Here:
app.use(logger.log());

you're calling log, without any arguments, and passing its return value into app.use. Since log expects and uses its parameters, that will fail on next() because the value of the next parameter is undefined, as you didn't pass an argument for it.
You may have meant just to pass the function in:
app.use(logger.log);
// No () ---------^


show complex function is injective in the unit disk

Question: Let $f(z)=e^{2iπ|z|}z$, how to prove this function is one to one on unit disk.
Generally ,What is useful technique or theorem to solve problems like this?
Comment: Welcome to MSE.  Please use [MathJax](https://math.meta.stackexchange.com/questions/5020/mathjax-basic-tutorial-and-quick-reference) to typeset math.
Answer: Suppose $\exp(2\pi i |z|)z = \exp(2 \pi i |w|)w$. Taking absolute values we see $|z| = |w|$. Now dividing both sides by $\exp(2\pi i |z|)$ we see $z = w$.
Comment: How about  f(z)=e^(2itπ|z|))z, where t is an number between 0,1?
Comment: @m.mir same argument, same proof. the exponential part has absolute value one so you get |z| = |w|, and then the rest cancels so you get z = w.