pass variable through url in wordpress

Question: I have wordpress custom template page test.php in which I want to pass variable throuh url like,
http://localhost/wordpress/test?date=2017&postid=11&title=some-title

in this format,
http://localhost/wordpress/test/2017/11/some-title

and grab the parameter from the url.
I have followed this link, but couldn't produce the result as I have desired.
Is there another way to achieve the desired result as I have mentioned??? I am pretty newbie to wordpress theme development.
Comment: Would be interested in "why". Given I have some experience with WP, and have simply never had to do it. Of course you may have a reason, or you might be missing an easier way to achieve your end result.
Comment: You could use your web server (apache or nginx) rewrite rules to rewrite the path to the query parameters. That way the user will see the second format but in php you will have the first format with query parameters and use the normal `get_query_var` from wordpress
Answer: Well, as suggested by @vl4d1m1r4 , I have used the web server(in my case apache) rewrite rule to rewrite the path. Some-what I have achieved the desired result.
In function.php
I have written the following code to update the rewrite rule in wordpress(.htaccess)
add_filter( 'query_vars', 'add_custom_query_vars' );
function add_custom_query_vars( $vars )
{
    array_push($vars, "test_year", "test_postid", "test_title");
    return $vars;
}
function custom_rewrite_rule()
{
    add_rewrite_rule('^test/([^/]*)/([^/]*)/([^/]*)?','index.php?pagename=test&test_year=$matches[1]&test_postid=$matches[2]&test_title=$matches[3]','top');
}
add_action('init', 'custom_rewrite_rule');

After adding the above code, I have re-saved the permalink settings(setting>>permalink)
To Get the parameter in custom-template-page i.e test.php. I have used the following query.
echo get_query_var('test_title');
echo get_query_var('test_postid');
echo get_query_var('test_year');

pass variable through url in wordpress


How to insulate the inside of a door

Question: I am building a sliding door with a frame made of 2x2s covered with plywood panels on each side. I would like to make it reasonably soundproof and was planning on filling the void with some insulation material.
What would be a good material to use in between the panels of plywood?
Here's a peek at what the door will look like: https://s3-production.bobvila.com/articles/wp-content/uploads/2016/03/DIYSlidingDoor_Step07.jpg
Answer: I would consider some of that "solid" expanded foam insulation with or without aluminum facing...
Should be available in a 2" thickness, cut to fit and possibly glued should work well.

How to insulate the inside of a door


Ubuntu 13.04. fail to start after installing nvidia drivers (Vostro laptop)

Question: Everything worked fine in 13.04 Ubuntu but then i installed nvidia-drivers-103 Now it does not load into login screen at all. I see blank purple screen during start-up and then just blank black screen appears and nothing happens after.
I booted into recovery mode and removed nvidia drivers, that did not helped. I noticed i had broken Unity environment in recovery mode (no launcher or toolbars, just wallpaper) so i followed :
Unity doesn't load, no Launcher, no Dash appears
where i reseted my unity/compiz back but this did not helped me to boot so finally i installem gdm and now i have compiz and unity fully removed and nvidia drivers too. I still cannot boot, only recovery mode works fine.
What i should try next to have Unity and Compiz happily working ? Which logs should i check and what could be wrong ?
I would expected that unity/compiz is problem but as i still cannot start my OS i guess the reason is much more deeper than i expected. How to restore original version of graphics drivers ? Obviously just removing NVidia drivers did not restored original configuration.
HW : laptop Vostro 3750, Nvidia GT 525M, Intel Mobile HM67 Chipset
Comment: Same here, I've got an nvidia geforce G210M and installed one of those newer nvidia drivers. Can't remember which exactly.
Answer: I have a dell Latitude E6500, and got the same problems
the only solution I found was the following :

Switch to console mode: Alt+Ctrl+F1
Kill x server: sudo service lightdm stop
Remove nvidia drivers: sudo apt-get remove --purge nvidia*
Generate new xorg.conf file: sudo X -configure -- this will create
xorg.conf. A new file in your current dir
Rename and move: sudo mv xorg.conf.new /etc/X11/xorg.conf
Return to GUI: sudo start lightdm

Of course  I would prefer a better solution
Comment: did not worked for me :/
Comment: that worked for me at least to remove all nvidia packages on Samsung RV511
Comment: nvidia installation worked for me after doing this, then installing nvidia again,  I opted to try installing again, because my x server failed to configure , it said that my screen number doesn't match detected devices (something like that), I also apt-get reinstall xorg before seeing your answer, so it might have to do with either error or success of nvidia reinstallation. also this time i chose not add it to sources when it asks.  driver is 319
Answer: I had the same problem on Samsung RC530. Graphics was functional until Nvidia drivers installed which messed up the drivers (I could log in in low resolution, monitor was not recognized at all). I have to say that answer provided by Alain worked. After removing Nvidia drivers in console mode and adding new configuration file everything was back to the old graphics setup.
Answer: Solution is to install vanilla Ubuntu 13.04 and do not touch any nvidia / compiz / tweak tools otherwise you will gonna have bad time. Default configuration runs just fine. Before you will try some major changes run clonezilla and save yourselft precious time and do full backup.
If you want to have nvidia drivers (e.g.  because of 3d games) i wish you good luck.
Answer: I'm on a Dell Latitude E6410 and also get the blank purple screen on bootup.
If I hit the power button, it will then show me a bit of the shutdown but then it stalls. I have been holding onto the power button the power off the laptop. If I boot up a few times, eventually I'll be able to reach the login and usually this means things will continue working (until the next boot).
There's a bunch of what look like kernel Oopses in /var/log/kern.log that seem to coincide with the startup problems. Skimming through it, I see enough "nvidia" and "nv" to think the problem is due to Nvidia drivers or kernel modules.
Answer: The built-in drivers on Ubuntu do not require /etc/X11/xorg.conf, but the Nvidia drivers do require it so you will need to create it.
Thankfully, Nvidia provides nvidia-xconfig to do just that.
Create /etc/X11/xorg.conf and reboot to a working system with:
sudo nvidia-xconfig
sudo reboot

The menus and other aspects of Unity including full resolution support for your displays should be restored.


How do I create a feudal vassal as a tribal ruler?

Question: I am an independent unreformed Pagan tribal ruler and when I give an unlanded tribal courtier a city or a temple, their government changes to the correct type, but when I give them a castle they stay tribal (and have the wrong holding type penalty). I think it might only apply to county capital castles.
How do I create a feudal vassal as a tribal ruler? Every time I give an unlanded tribal courtier a feudal title, they stay tribal.
Comment: How do I create a feudal vassal as a tribal ruler? Every time I give an unlanded tribal courtier a feudal title, they stay tribal.
Answer: I'm pretty sure there are no automatic conversions between tribal and feudal character types or holding types. There are strict conditions for converting either one, and there does not seem to be a path for a tribal character to convert to feudalism if they don't hold any tribal lands: the wiki says you must have a stone hillfort to adopt feudalism.
What you can try is creating a new vassal, the way you would for any newly built or acquired holding that you don't want in your personal demesne.
Comment: After asking the question initially, I confirmed it only affects county capitals, so that button does not apply, as it can only be used on baronies (but it is definitely useful given how aggressive I apply and I forgot about it until now). I would think it's a design decision to prevent you from easily changing to feudalism, but your heir could just be given a castle barony.


Segmentation Fault occurs after using global variable in several function

Question: I'm currently programming my Bachelor Project what consists an RFB-Client and a Shared Memory. The initialisation of the RFB-Client is done, the Shared Memory is created. My teacher told me to decouple the code and I wrote several functions and used a global variable for the shared memory.
But now a segmentation fault occurs while trying to read the content of the global variable. I debugged the code and found out: The content of the global variabel "my_shm" is always "0x00" :-/
Could you please help me?
These are the portions of code where the problem occurs:
(I know, this is a long code, but sending just parts of it would be useless...)
char *my_shm; --> //global variable

int SHM_init (int shmid, char* shm, key_t key, long int size) {

    /* Create a new (System V) shared memory segment of the specified size */
    shmid = shmget(key, SHM_SIZE, IPC_CREAT|0777);
    /* Check if SHM creation was successful */
    if (shmid < 0) {
        /* DBG: Debug message to show which point of the program has been passed */
        DBG_PRINT("C\n");

        /* Check if creation failed because of already existing SHM */
        if (EEXIST == errno) {
            /* DBG: Debug message to show which point of the program has been passed */
            DBG_PRINT("CC\n");
            /* Delete already existing SHM with shmctl */
            shmctl(shmid, IPC_RMID, NULL);
        } else {
            /* DBG: Debug message to show which point of the program has been passed */
            DBG_PRINT("CCC\n");
        }

        /* Creation and initialization of SHM failed */
        return -1;
    }
    /* Attach the SHM data pointer to the previously created SHM segment */
    shm = shmat(shmid, NULL, 0);

    if(shm == (char *) -1) {
        /* Attaching failed */
        return -1;
    }
    DBG_PRINT("Shared Memory Initialization successful\n");
    /* Creation and initialization of shared memory was successful */
    return 0;
}

void RFB_update(rfbClient* client) {

    DBG_PRINT("RFB_update called\n");
    int i,j;

    rfbPixelFormat* pformat=&client->format;

    DBG_PRINT("A\n");

    /*bytesPerPix: variable which stores Bytes per Pixel*/
    int bytesPerPix = pformat->bitsPerPixel/8;

    DBG_PRINT("B\n");

    /*row= width of frame*bytes per Pixel*/
    int row=client->width*bytesPerPix;

        DBG_PRINT("C\n");

    char byte_to_write;

    //as long as j is smaller than 128*(width*bytesPerPix)
    for(j=0;j<client->height*row;j+=row) {
        //as long as i is smaller than 128 * bytesPerPix
        for(i=0;i<client->width*bytesPerPix;i+=bytesPerPix) {
            /*frameBuff: Pointer on FrameBuffer*/
         unsigned char* frameBuff = client->frameBuffer+j+i;
            unsigned int v;

           if(bytesPerPix==4)
                v=(unsigned int*)frameBuff;

            byte_to_write = ((v>>pformat->redShift)*256/(pformat->redMax+1));
            SHM_write_byte(my_shm,byte_to_write);

            byte_to_write = ((v>>pformat->greenShift)*256/(pformat->greenMax+1));
            SHM_write_byte(my_shm,byte_to_write);

            byte_to_write = ((v>>pformat->blueShift)*256/(pformat->blueMax+1));
            SHM_write_byte(my_shm,byte_to_write);

        }
    }

    DBG_PRINT("RFB_update successful, Shared Memory is filled\n");
}

int SHM_write_byte (char** shm, char byte) {

    /*Check if pointer to SHM is valid */
    if (shm == (char **) -1) {
        /* Pointer is invalid */
        return -1;
    }
    shm = byte;
    shm++;

    return 0;
}

int main (int argc, char *argv[]) {

    if (SHM_init(shmid, my_shm, SHM_KEY, SHM_SIZE) != 0) {
        DBG_PRINT("Shared Memory initialized\n");
        /* Couldn't initialize SHM,initializing failed */
        return -1;
    }
    /* Initialize RFB Client         */
    if (RFB_client_init(rfb_client, (FinishedFrameBufferUpdateProc)RFB_update) != 0) {
        DBG_PRINT("Couldn't initialize client\n");
        /* Couldn't initialize Client,initializing failed */
        return -1;

}

--> everywhere the variable "my_shm" is used: the content is: 0x00...
Answer: This seems to be a very common problem here on stackoverflow.com today, and the problem is that you pass arguments to function by value and not by reference.
What that means is that when you pass an argument to a function, its value is copied, and the function only work on the copy locally inside the function. As you should know, modifying a copy will of course not modify the original.
C does not have pass by reference, but it can be emulated by using pointers. In your case, since you have a pointer you need to pass a pointer to the pointer using the address-of operator, like
SHM_init(shmid, &my_shm, SHM_KEY, SHM_SIZE)
//              ^
//              |
// Note ampersand (address-of operator) here

You of course need to modify the function to actually accept a pointer to the pointer:
int SHM_init (int shmid, char** shm, key_t key, long int size)

And of course use the dereference operator * when using the variable:
*shm = shmat(shmid, NULL, 0);


Base64 multiple lines decoder

Question: I am looking for a perl script able to decode multiple lines of Base64 encoded strings.
I found a few tools to do the job line by line. Which is really time consuming considering the amount of lines that I have.
I can have all the strings in one base file called "infile.txt", would that be possible to run a perl script to convert all the lines in "infile.txt" to "outfile.txt" and keeping one line per string?
Thanks for guiding me.
Answer: If each line was the result of an encode:
while (<>)
   chomp;
   print decode_base64($_), "\n";
}

If the entire file was the result of an encode:
local $/;
while (<>) {
   print decode_base64($_);
}

Base64 multiple lines decoder


Will installing Ubuntu harm my computer?

Question: I installed Ubuntu using wubi on hp dv6-6135dx.
When I boot into Ubuntu, I get a black screen.
The wireless light turns blue after a while, meaning Ubuntu has loaded the driver, but the screen stays turned off.
When I first booted into Wubi I got a black screen with white screen with text that said

generating locales... done. Warning: Not compatible with locale
  us.uTF8....

It stayed stuck at this screen, so I hard shut down the computer after about a half hour.
Now wubi won't boot. I'm considering dual-booting, but will Ubuntu actually start? Can Ubuntu mess up my Windows 7 installation?
Comment: Unless you play with partitions, Ubuntu is harmless to all other operating systems.
Answer: If Ubuntu works on a LiveCD, it will likely work when you dual boot. Ubuntu cannot mess your Windows installation up unless you do it incorrectly.
To install it correctly, resize the Windows partition from within Windows 7. Do this by using the device manager (right click My Computer, click device manager, and then use the disk management section).
When you boot the LiveCD and go to the installation screen, it will offer to install alongside Windows 7. Use that option and you should have no further issues, and it will offer to boot Windows on startup.

If you have a Windows 7 DVD, and later want to restore the boot loader for Window 7, you can also do that, but you wouldn't be able to load Ubuntu in that case.

Ubuntu cannot harm your computer btw.
Comment: @William: Yes, but you wouldn't be able to boot Ubuntu, unless you can find a GRUB2 for Windows :).
Comment: Is there any way to install Ubuntu without modifying the windows bootloader?
Comment: Yes, if you have 2 physical different hard drives you can install a boot loader on each and change the boot device on your computer's BIOS every time you want to boot one or the other, on the same disk with 2 systems only 1 boot loader can exist.
Comment: Use VirtualBox or Vmware to create a virtual PC and install Ubuntu on virtual PC. It will be completely safe and more comfortable for you.
Comment: A hard disk costs less then 20 dollars/euros/(what ever), if you are afraid of messing up your windows partitions you can always get a 2nd disk, plug it in, install Ubuntu in it and set it as boot device in your BIOS, when you are comfortable playing around with dual boots, grubs, resizings, etc you can always keep the 2nd disk as a backup solution.
Comment: @BrunoPereira: the HP dv6 is a single hard drive laptop :). I've got a dv7 - so I can play around with the dual HDD solution, but he can't :).
Comment: @RolandTaylor Sure he can, for 25 euros/dollars/(whatever) he can buy a USB external one, play around with Ubuntu, when he sees that its much better then Windows he will remove Windows from his main and use the USB external as a backup solution! *Eats cookies*
Comment: @RolandTaylor My gf has a dv7 also, I am sure it allows external device booting ;)
Comment: @BrunoPereira: rofl :D
Comment: @RolandTaylor I'm not saying your answer is wrong, actually its very good, but if the user wants to install Ubuntu and be able to double boot there are also other options (even a USB pen will do!)
Answer: The dual boot option will work for you, but there are a few considerations.
First, is that you have to resize your hard drive partitions, which, if you've got a newish machine, shouldn't be too challenging.  The windows disk manager can be used, but I recommend using an application to handle it, like Partition Magic ($) or GParted (Free).
Next, GRUB is installed by default, but should you choose to roll back, you may need to fix the Master Boot Record in Windows Safe Mode.  That can be a pain, but ultimately it's fixed quickly.
Finally, you may still end up with driver issues.  Wubi isn't new, but it has it's challenges with newer hardware, as you know.  This is less of an issue with the traditional installation since there isn't another layer that the OS has to use to access the hardware.  The more generic drivers will get you through.
Ultimately, to answer your question, it won't hurt your computer, but I'd make sure I have a recent backup and Win7 restore partition or install dvd handy should anything happen.
Comment: Do you mean wubi?
Comment: Yea, but re-reading your post, that's what caused the issue.  My apologies.  I'll update my response.


Check if filename contains Umlauts in php

Question: Is there any way, to check in php if a filename has Umlauts?
Answer: There's a quick way to do this:
$s = 'äëüïö';

if (preg_match('/&[a-zA-Z]uml;/', htmlentities($s, ENT_COMPAT, 'UTF-8'))) {
    echo 'Filename contains umlaut';
}

Answer: <?php
$your_text = "hiÍ :)";
$umlauts = "Ŕ,Á,Â,Ă,Ä,Ĺ,Ç,Č,É,Ę,Ë,Ě,Í,Î,Ď,Ň,Ó,Ô,Ő,Ö,Ř,Ů,Ú,Ű,Ü,Ý,ŕ,á,â,ă,ä,ĺ,ç,č,é,ę,ë,ě,í,î,ď,đ,ň,ó,ô,ő,ö,ř,ů,ú,ű,ü,ý,˙,Ń,ń";
$umlauts = explode(",", $umlauts);
foreach($umlauts as $umlaut){
    if (false !== (strpos($your_text, $umlaut))){
          echo "found ".$umlaut."
";
    }
}
?>

working demo


I put 2-stroke fuel in my 4-stroke mower and now it won't start

Question: My first time doing the lawn. Trying to help. Now I can't get it to start.
Comment: More likely the mixed fuel is old and has lost its volatility. Remove the fuel from the mower and add fresh gas.
Comment: I'm voting to close this question because small engine repair should have been migrated to [mechanics.se].
Comment: That's the less dangerous way.  **Don't** do it the other way 'round, or you'll be buying yourself a new chainsaw/weedwacker.
Comment: Was the gasoline new or had it sat all winter?
Answer: Remove the air filter and spray a small blast of starting fluid into the carburetor. It should run for a second or two. If it does then the problem is the gas is most likely old/bad. If it doesn't run for even a split second then you're not getting any spark which means you have an ignition problem which is most likely a fouled spark plug.
Answer: I've burned off old gas and even 2-cycle in a 4-cycle motor. Some tips I've found to help with this

Buy some pre-mix stabilized 4-cycle gas (sold in home improvement stores next to the 2-cycle pre-mix). It typically has better detergents than pump gas and can help you get a bad motor started again
Clean your spark plug. Take it off the mower and clean it with a wire brush. This sometimes helps to get a better spark going
If you have a push primer, try doing a LOT of priming to get the newer gas into the chamber. Otherwise, just keep trying to crank it.
Answer: Not likely the problem ; it has a little oil in the same gasoline ; you may see a little blue smoke when it is running. When I have been short on gas , I have added at least 50 % 2 cycle gas to my 4 cycle mower to finish the lawn.
Comment: Fouled spark plug? The oil burns with a lot more carbon. Did it run at all though? If it never started, then it's probably something else.
Comment: What could be the reason why it will not start?
Comment: This might help if you'relooking for more general starting issues: https://diy.stackexchange.com/questions/109999/difficult-to-start-a-four-stroke-mower-when-cold-how-to-diagnose-the-problem?rq=1
Answer: It might not have started anyway this season. Petrol left in the carb. degrades and crystallises, so even with the right fuel, it won't start.
If, however, all the fuel from last year was drained out/ run till dry, it'll be the oil in the two-stroke petrol oiling up the spark plug. Which will have to be removed, cleaned and dried. Two stroke mix carefully drained, new petrol put in, and if possible, drain not just the tank but the carb also. With extremem care!


display_errors ON has no effect (Apache 2.4.7 & PHP 5.5.8-2)

Question: i've a problem with my http server (actually Apache 2.4.7 and PHP 5.5.8-2) running on debian.
Without enabled display_errors the server returns, as expected a 500-http error, but when enabling display_errors using php.ini or apache vhost directives the server only returns a blank (or whatever output occured until the error) to the client. I'm not able in any way to show the actual occured php error.
Here i've the configuration parts from phpinfo()
error_reporting         0
display_errors          On
display_startup_errors  On
html_errors             On
log_errors              On

And here is the actual php file i try to test
<?php
echo "A message before php-error occurs";
foobar1();
echo "A message after error occured";
?>

The second message is not displayed, just as there is no php error output, neither in the http request nor in the error log of the server. HTTP Status Code is 200.
HTTP/1.1 200 OK
Date: Sun, 16 Mar 2014 16:18:36 GMT
Server: Apache/2.4.7 (Debian)
Strict-Transport-Security: max-age=604800
X-Powered-By: PHP/5.5.8-2
Content-Length: 33
Keep-Alive: timeout=5, max=100
Connection: Keep-Alive
Content-Type: text/html

A message before php-error occurs

If anyone has an idea what the problem is it would be great if i get a reply. In the moment i've to copy the production platform every time when an error occurs on a local machine to get the php error output.
Comment: Do you see the actual "E_ALL" string in `phpinfo()`'s output? How exactly do you set the value?
Comment: How about error logs? Why do you suppress `E_NOTICE`?
Comment: I've updated my test scenario and my post, `E_NOTICE` is not the problem. Also the given code example should end in a real error no notice.

Error logs are always empty, don't know why, on my local instance it works..
Comment: Are you sure you're running this particular script? If you replace it all with `<?php echo 'foo';` will you observe the corresponding changes?
Comment: Yes i am sure that i edited the right script. Here i've a example: http://test.foxylion.de/ all files are shown (inclusive configuration and log file).
Answer: Looking at your phpinfo.php error_reporting has a value of 0, which implies that it's not being set from your virtualhost config.
According to the PHP documentation

Using PHP Constants outside of PHP, like in httpd.conf, will have no useful meaning so in such cases the integer values are required.
  And since error levels will be added over time, the maximum value (for
  E_ALL) will likely change. So in place of E_ALL consider using a
  larger value to cover all bit fields from now and well into the
  future, a numeric value like 2147483647 (includes all errors, not just
  E_ALL).

Insert the numeric constant for E_ALL ( 32767 ) in your virtualhost.conf.
A full list of error code constants can be found here: http://www.php.net/manual/en/errorfunc.constants.php
You can also try inserting
error_reporting(E_ALL);

at the top of your PHP script to see if you get the error reports shown that way.
Comment: Thanks a lot, it was the problem. If set the error_reporting value with `php_admin_value` and `E_ALL`. So it was fixed to `0` and therefore any override I tried in php files failed.


Submit form to 2 different action page

Question: I would like to have a form that can submit to two different action pages based on a select box.
Meaning if I select in the select box Products, the action would be products.html, and if I select Users, the action would be users.html
I have found many examples that have two submit buttons, but I need only one submit button.
Any ideas on how to do it?
Answer: you can use jQuery for that ...
if selected value equals something
set form attribute action to the other thing not initial action
this is pseudo code of course ..
here is a working solution :

<select name="dummy" id="selectList">
<option value="0">foo</option>
<option value="1">bar</option>
</select>

<form id="yourform" action="primaryaction">
bla bla
</form>

Comment: Thank you, just add the submit button :D
Answer: Try something like this (assuming a form named "myForm"):
document.myForm.onsubmit = function() {
    if (this.mySelector.value == 'products') {
        this.action = 'products.html';
    }
    // the "else" isn't necessary: leave it at "users.html" as a default.
};

Answer: read about new attributes
Attributes for form submission that may be specified on submit buttons. The attributes are: formaction, formenctype, formmethod, formnovalidate, and formtarget
Works in IE >= 11
my example for will be demonstrated point :
<form action="1.php">
  <input type="text" >
  <button value="go"> GOOOOOOOOOOOO</button>
 <button value="go" formaction="2.php"> DONNNNNNNNNNNNNNNNOOOO</button>
</form>

Answer: if(condition==products)
document.forms[0].action = 'products.html;
else
document.forms[0].action = 'users.html;

Submit form to 2 different action page


Multiple header in Drupal website

Question: I want to make 2 headers one for home page and one for rest of website (they would be almost same just have little change). I'm using Drupal 7. Please guide me any simple way because I know bit difficult way through using its url.
Thanks in advance :)
Answer: Put each of headers in a separate block then position these 2 blocks in the header of your theme (menu structure then blocks).
For the one on the front page, go inside the settings of the block then check "Only the listed page" and add : <front>
For the one everywhere but on the front page, go inside the settings of the block then check "All pages except those listed" and add <front>.
Comment: Thank you so much for your response. And I understand your answer. But the problem is I have already a block  "Main Menu" and I just want to duplicate it to make some little changes. But I didn't find how to make changes in this block "Main Menu" or duplicate this block.
Comment: If you just want to adapt the css (hiding parts of the menu or relooking it), just add css selectors based on the class front, this class is added to the body html element. Or not-front if you want to alter css on all pages but front one.
Comment: Else if you really need to alter the html structure, you will have to alter the view of this block with the hook : hook_block_view_main_menu_alter(...) : https://api.drupal.org/api/drupal/modules%21block%21block.api.php/function/hook_block_view_MODULE_DELTA_alter/7

Multiple header in Drupal website


Exercise of implication

Question: I have extracted this problem from the book How to Solve It by Daniel Velleman. Could someone explain me the solution? The problem is to determine the validity or invalidity of the argument. I would especially like to know how the conclusion is false by applying reasoning, not so much with the truth table (which I honestly don't understand much) that Velleman provides and whose image I attach.
" The warning light will come on if and only if the pressure is too high and the relief valve is clogged. The relief valve is not clogged. Therefore, the warning light will come on if and only if the pressure is too high."
Here is the solution:
solution by Velleman
Answer: The statement "The warning light will come on if and only if the pressure is too high and the relief valve is clogged" requires both the pressure to be too high and the relief valve to be clogged. If one of the two is false (such as in our case, the "The relief valve is not clogged"), then the warning light cannot come on.

In the truth table, he is saying exactly this although, there is no explanation which is why I will attempt to explain it here.
We use the same notation: Let $W$ stand for "The warning light will come on," $P$ for "The pressure is too high," and $C$ for "The relief valve to be clogged."
We are given "The warning light will come on if and only if the pressure is too high and the relief valve is clogged," which translates to $W \iff (P \land C)$. We are also given "The relief valve is not clogged," which means $C$ is false. Then from the above statement, we know that $W$ is false. We are not given any information about $P$. In the line he presents, he considers the case when $P$ is true (because he wants to present a counterexample for which only one case is sufficient). From this information, it is obvious that $W \iff P$ is not true because $W$ is false in this case but $P$ is true.

Exercise of implication


document.getElementsByName returning undefined and it cannot find the value

Question: I have the following code
<!DOCTYPE html>

<input type="hidden" name="test" value="Hi"/>

I need it to log "Hi", though it is failing, It says that index [0] is undefined even though when only console logging the object I can see it perfectly along with the value.
I tried using it without an index and it failed obviously because it is a NodeList, I can't see exactly what is wrong and I tried to fix it a lot. I'm sure that index 0 is there and that there is value though I cannot access it..
Comment: Your code seems working fine, Just move your `` above the `
Comment: This is a better jsFiddle example: http://jsfiddle.net/tSN5U/1/   If the script is before the html, it doesn't work.  If the script is after the html, it works.
Answer: It's because your javascript is executing before the DOM completes loading.
If you put your script after the <input>, your console will show up an [HTMLInputElement]. Then show up the value
<!DOCTYPE html>

<input type="hidden" name="test" value="Hi"/>

Comment: Is there a way to still place my JS above the input element but wait for it to load and then get the value?
Comment: You need to wait before the DOM is fully loaded. You can try with jQuery `$(document).ready` function or setting up a timer with `setTimeout` before running your javascript.

Also, for optimal performance and speed loading, it's recommended that you load your scripts just before `` closing tag
Answer: The console is returning undefined because you're trying to access a DOM element (the input) before it has even been parsed by the browser.
Place your

Comment: Is there a way to still place my JS above the input element but wait for it to load and then get the value?
Comment: @ChosenWann: You can use [`window.onload`](https://developer.mozilla.org/es/docs/DOM/window.onload)
Answer: Try this :
<!DOCTYPE html>

<input type="hidden" name="test" value="Hi"/>

Answer: It is because you are getting the Dom elements before it's loading finished
use the script as below
 <input type="hidden" name="test" value="Hi"/>

or
  you can use external Javascript file and place your coding in javascript file as below
  $(document).ready(function(){
   var object = document.getElementsByName("test");
           console.log(object[0]);
  }

Comment: `getElementsByTagName` would match `input`, not the name attribute
Comment: @DarrenKopp sorry friend. slight confusion. now i understand my mistake


Is Skype 4.2 still supported on Linux?

Question: I am currently using Skype 4.2 but I cannot sign in to the Skype network. (Internet connection is OK and so is the password). And since I'm using Ubuntu without PulseAudio (it doesn't support my soundcard), I cannot upgrade to Skype 4.3:

This version dropped support for direct Alsa support; please install PulseAudio 4.0 or greater for the best calling experience.

Is Skype 4.2 still supported on Linux? If not, how can I keep using Skype without PulseAudio?
Comment: Skype 4.2 is supported on Linux (as you can see, it works), but it is not supported on the Skype network, which is why it won't sign in. You might want to varify that at http://community.skype.com/.
Comment: This can' t be the case that your sound card is not supported by pulseaudio. Pulseaudio is not a hardware driver. If alsa supports your card, pulseaudio can be configured to use it through alsa.
Comment: @Pilot6 PulseAudio will run into hissy fits with certain USB DACs (e.g. FiiO X3ii). In my case it incapacitates my computer as soon as I connect the damn device, and I have to perform a hard reboot. While I understand the theoretical arguments that PulseAudio "cannot 'cause it's not hardware driver", it turns out that it actually can. I'm [not](http://wiki.marklesh.com/How-to/Asoundconf) the only one. After I remove PulseAudio, I can use the device with plain Alsa without any issues.
Comment: Thanks. I don't think this question should be closed, though, as other users are likely to end up in the same boat and have this precise question... (I posted an answer linking to an official source.)
Comment: Your link is an old one. In '10 pulseaudio was not good at all no matter which hardware was used.
Comment: @Pilot6 This is beyond the point. My experience is with 14.04. Trusty will effectively crash with FiiO X3ii when PulseAudio is running. I can provide other links, but this is off-topic here.
Answer: As per Having trouble signing in? Retirement of older versions of Skype (01-08-2014):

From today, users with Skype for Linux version 4.2 and older will not be able to sign in to Skype. The error messages user will see during sign in may include "Can't Connect to Skype" or "Can't login on Skype". To continue using Skype, please update to the latest version.

So it seems that now it is impossible to use Skype without PulseAudio. The attitude from Microsoft seems to be "tough luck".

Is Skype 4.2 still supported on Linux?


Delay in generation of dynamic controls in VB.NET

Question: I'm trying to generate a grid of 1x1 pixels Images in .NET using VB.NET, using this code:

    For i = 1 To 500
        Dim img As New ImageButton
        img.ID = "ibtn" + i.ToString
        img.ImageUrl = "images/design/click.gif"
        form1.FindControl("upperpanel").Controls.Add(img)
    Next

Problem is that it takes a very long time to generate the HTML when I'm running this on page_load event. Can anyone help me out to speed up the rendering of the controls.  Also, I want to add Click event on each image button. How can I do that ??
 Thanks
Comment: Why do you need to  create 500 consecutive 1x1 pixel images?
Comment: some kinda project work with overlapping panels/divisions..
Answer: Ok, first thing to do is get the panel control once. Second, create your click method, and then add your handler.  This needs to be done prior to the page load event.  Use the page_Init event for creating your buttons when you need to add a handler.
<code>    Private Sub WebForm1_Init(sender As Object, e As EventArgs) Handles Me.Init
    Dim tempPanel As Panel = form1.FindControl("upperpanel")

    If tempPanel Is Nothing Then
        Return
    End If

    For i = 1 To 500
        Dim img As New ImageButton
        img.ID = "ibtn" + i.ToString
        img.ImageUrl = "images/design/click.gif"
        AddHandler img.Click, AddressOf ImageButton_Click
        tempPanel.Controls.Add(img)
    Next
End Sub

Protected Sub ImageButton_Click(sender As Object, e As ImageClickEventArgs)
    Dim tempImageButton As ImageButton = CType(sender, ImageButton)

    Select Case tempImageButton.ID
        Case "ibtn1"
                    'blah
        Case Else
    End Select

End Sub
</code>
As far as performance goes, getting the panel control up front will improve performance.  Probably not much.  Creating 500 buttons is going to take some time.
Comment: @Robert Beaubien: Thanks a lot for the help..I sincerely request you to kindly provide an explanation for what is the reason you did this in the init instead of page_load (which I was doing). THanks..

And also, if you could help with this:
if I have resized my panel as 400x400, this would yield me 160,000 pixels or generated images...but they spread across the page instead of restraining themselves within the panel. How can I do this ??
Also, when I click on say 150000th pixel I get an HTML exception stating REQUEST TOO LONG...what could be the reason of this ??
Comment: Generating 160000 separate imagebuttons is  probably going to overflow  a lot.  I think you need to re-think your implementation.  I'm not sure what you are trying to do, but there is probably a better way.  As far as why you need to use the init event, you have to attach the handler earlier in the process.  If you don't, it won't work. Here is more information on the page life cycle: http://msdn.microsoft.com/en-us/library/ms178472(v=VS.100).aspx
Comment: @RobertBeaubien I have to use a grid of transparent single pixel images for the purpose. :(
anyways Thanks a lot for your help.


Color transform algorithm (that also works on saturation and value/lightness)?

Question: To change particular colors in an image, generally you multiply the RGB by a transformation matrix. Image manipulation programs such as gimp & photoshop have a selective color change function that allows a user to convert pixels within a certain "distance" to the original color in some color space to a new color. Eg, changing #00f blue into #ffd pale yellow.
I'm trying to implement such a function in a <canvas>. What color space and distance definition do these algorithms typically use, and then how do they compute the transformation matrix?
Comment: Yes, it's way more clear.
Comment: OK, made the edit.
Comment: Is it understandable now?
Answer: Very often, the Lab color space is used, since it is close to how humans perceive color. As to which distance to apply: This wikipedia article mentions a Delta E distance of 1.0 for a just noticeable difference. There are a lot of different formulas resulting in different thresholds.
Answer: I find the hue/saturation or luminance/chrominance spaces to be fairly easy to work in. They follow our intuitive sense of how color works, even if they're not as scientifically accurate as Lab is. The conversion from RGB to YCbCr is a simple matrix multiply. Working in YCbCr would allow you to do things like keep luminance constant while changing hue and/or saturation. You can think of saturation as the distance of the color from the luminance axis (so just the magnitude of CbCr = sqrt(Cb x Cb + Cr x Cr)). The hue is the angle the color point makes with the x-axis when projected onto the CbCr plane. (So you can use atan2(Cr, Cb).) Once you've modified your values, converting back to RGB is another matrix multiply.


My matlab while loop isn't recognising my function button press

Question: I have a script that runs when a button is pressed causing a while loop to initiate. When my stop button is pressed it is supposed to cause the loop condition to be untrue thus stopping the loop. My stop button doesn't seem to stop the loop during testing. it would seem the value I assigned in the pushDisconnect button isn't updating to the while loop and i'm not sure why this is occurring.
% --- Executes on button press in pushConnect.
function pushConnect_Callback(hObject, eventdata, handles)
% hObject    handle to pushConnect (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

set(handles.pushDisconnect,'Enable','on')
set(handles.pushConnect,'Enable','off')

handles.myDevice.StartAcquisition;
sampleRate_BP = double(handles.myDevice.BioPotentialSignals.SamplesPerSecond);
axis_handles = zeros(1,handles.numEnabledBPChannels);
BioPotentialSignals = cell(1,handles.numEnabledBPChannels);
handles.CheckFinger = cell(1,5);
handles.stopNow = 0;

for ch = 1:handles.numEnabledBPChannels
    axis_handles(ch) = subplot(length(axis_handles),1,ch,'Parent',handles.uipanelGraph);
    if ch==1
        title(char(handles.deviceName))
    end
    ylabel([char(handles.myDevice.BioPotentialSignals.Item(ch-1).Name) ' (V)']);
    hold on
end

xlabel('Time (s)')
linkaxes(axis_handles,'x')

plotWindow = 5;
plotGain_BP = 1;

while handles.stopNow == 0
    for ch = 1:handles.numEnabledBPChannels
        BioPotentialSignals{ch} = [BioPotentialSignals{ch};handles.myDevice.BioPotentialSignals.Item(ch-1).GetScaledValueArray.double'];
        if length(BioPotentialSignals{ch}) <= plotWindow*sampleRate_BP
            cla(axis_handles(ch))
            t = (0:(length(BioPotentialSignals{ch})-1))*(1/sampleRate_BP);
            plot(axis_handles(ch),t,plotGain_BP*BioPotentialSignals{ch});
            xlim([0 plotWindow])
        else
            if ch==1
                t = ((length(BioPotentialSignals{ch})-(plotWindow*sampleRate_BP-1)):length(BioPotentialSignals{ch}))*(1/sampleRate_BP);
            end
            cla(axis_handles(ch))
            plot(axis_handles(ch),t,plotGain_BP*BioPotentialSignals{ch}(end-plotWindow*sampleRate_BP+1:end));
            xlim([t(end)-plotWindow t(end)])
        end
    end
    % Update handles structure
    guidata(hObject, handles);
    pause(0.1)
    disp(handles.stopNow)
end

% Stop signal
handles.myDevice.StopAcquisition;
% Disconnect from all sensors
handles.myDevice.Disconnect;

msgbox('Device requires cycling, in order to restablish connection. Closing program.')

% Close window
close all;

% --- Executes on button press in pushDisconnect.
function pushDisconnect_Callback(hObject, eventdata, handles)
% hObject    handle to pushDisconnect (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

set(handles.pushDisconnect,'Enable','off')

handles.stopNow = 1;

% Update handles structure
guidata(hObject, handles);

Final Working Code, if anyone is interested:
% --- Executes on button press in pushConnect.
function pushConnect_Callback(hObject, eventdata, handles)
% hObject    handle to pushConnect (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

set(handles.pushDisconnect,'Enable','on')
set(handles.pushConnect,'Enable','off')

handles.myDevice.StartAcquisition;
sampleRate_BP = double(handles.myDevice.BioPotentialSignals.SamplesPerSecond);
axis_handles = zeros(1,handles.numEnabledBPChannels);
BioPotentialSignals = cell(1,handles.numEnabledBPChannels);
handles.CheckFinger = cell(1,5);
handles.stopNow = 0;

for ch = 1:handles.numEnabledBPChannels
    axis_handles(ch) = subplot(length(axis_handles),1,ch,'Parent',handles.uipanelGraph);
    if ch==1
        title(char(handles.deviceName))
    end
    ylabel([char(handles.myDevice.BioPotentialSignals.Item(ch-1).Name) ' (V)']);
    hold on
end

xlabel('Time (s)')
linkaxes(axis_handles,'x')

plotWindow = 5;
plotGain_BP = 1;

% Update handles structure
guidata(hObject, handles);

while handles.stopNow == 0
    for ch = 1:handles.numEnabledBPChannels
        BioPotentialSignals{ch} = [BioPotentialSignals{ch};handles.myDevice.BioPotentialSignals.Item(ch-1).GetScaledValueArray.double'];
        if length(BioPotentialSignals{ch}) <= plotWindow*sampleRate_BP
            cla(axis_handles(ch))
            t = (0:(length(BioPotentialSignals{ch})-1))*(1/sampleRate_BP);
            plot(axis_handles(ch),t,plotGain_BP*BioPotentialSignals{ch});
            xlim([0 plotWindow])
        else
            if ch==1
                t = ((length(BioPotentialSignals{ch})-(plotWindow*sampleRate_BP-1)):length(BioPotentialSignals{ch}))*(1/sampleRate_BP);
            end
            cla(axis_handles(ch))
            plot(axis_handles(ch),t,plotGain_BP*BioPotentialSignals{ch}(end-plotWindow*sampleRate_BP+1:end));
            xlim([t(end)-plotWindow t(end)])
        end
    end
    handles = guidata(hObject);
    drawnow
    pause(0.1)
end

% Stop signal
handles.myDevice.StopAcquisition;
% Disconnect from all sensors
handles.myDevice.Disconnect;

msgbox('Device requires cycling, in order to restablish connection. Closing program.')

% Close window
close all;

% --- Executes on button press in pushDisconnect.
function pushDisconnect_Callback(hObject, eventdata, handles)
% hObject    handle to pushDisconnect (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

set(handles.pushDisconnect,'Enable','off')

handles.stopNow = 1;

% Update handles structure
guidata(hObject, handles);

Answer: Kill the guidata(hObject, handles) line, and replace it by handles=guidata(hObject) since you're overwriting the GUI state with whatever was current at the time the loop started, and you want to be polling the GUI state instead. Put the guidata(hObject, handles)-line before the loop, to ensure that handles.stopNow is indeed reset to 0.
If that doesn't help, an additional problem may be that Matlab waits with processing commands from one button callback until the other callback is done running.
Two things you can try: Add a drawnow command before the pause. This will force the GUI to update, and processes all the interactions. Also, make sure that the pushbutton callback for pushConnect is interruptible.
Comment: @IamTrent: just noticed the guidata line. You're overwriting the GUI state, ensuring that handles.stopNow never becomes one! Answer has been edited.
Comment: @IamTrent: just noticed another issue :)
Comment: (1) set the field `stopNow` in your `openingFcn`. It's bad practice to create fields inside a callback. (2) Before your while-loop, add `guidata(hObject,handles)` to ensure `stopNow` is set to 0.
Comment: Tried both, still the same problem.
Comment: Still the same problem.
Comment: I get this error when I try the latest method: 'Reference to non-existent field 'stopNow'.'
Comment: Got it working now, I needed the 'guidata(hObject, handles);' before the while loop as well as your polling handles. Thank you so much for your help, do you happen to know where I can read up more on 'handles=guidata(hObject)' still trying to work out when it's appropriate to use these parts of guidata. Thank you again!
Comment: @IamTrent: `handles` is where the GUI state is stored. `handles=guidata(hObject,handles)` reads the state, `guidata(hObject,handles)` writes the state. Unlike handle objects, `handles` is not pass-by-reference, so you need to update manually.
Comment: @IamTrent: No problem, Matlab GUIs can be a bit obscure at times :)


3D Plotting in python, help for the z-axis

Question: My objective is to make a chart like this (not with the same data but of the same type):
3D time series of opinion dynamics
Suppose I have a pandas DataFrame with 100 columns that contain values between [0,1], they are the same as 'Opinions' in the figure. The dataset df also has 500 rows, that represent the 'time' of the figure. For instance:
df:

Ind y0   y1  y2  y3  y4  y5  y6  ... 100
0   0.7 0.9 0.2 0.0 0.0 0.9 0.9 0.9 0.9
1   0.8 0.9 0.2 0.0 0.0 0.9 0.9 1.0 0.9
2   0.8 0.9 0.1 0.0 0.0 0.9 1.0 1.0 0.9
... 0.9 0.9 0.1 0.0 0.0 0.9 1.0 1.0 0.9
500 0.9 0.9 0.1 0 0 0.9 1.0 1.0 1.0 1.0

If we consider the index as the x and the columns as y I have managed to plot them in 2D with the following code:

fig = plt.figure(figsize=(10,10))
ax = plt.axes(projection ='3d')
for column in df:
    ax.plot(df.index, df[column], marker='', color="dodgerblue", linewidth=1, alpha=0.9, label=column)

My result is the following:
2D plot
What I am struggling with is the z-axis.  In my opinion, what I need is another dataset (let's call it df_1)  where columns are filled with the count of  dfacross the entire row. For instance, considering only 6 columns and 2 rows of the previous example, df_1 would be:
df_1:

Ind  z0  z1  z2  z3  z4  z5  z6
0     1  3   1   2    2  3  3
1     1  3   1   2    2  3  3
2     1  2   1   2    2  2  1

The first cell of the first row in df_1 is = 1 because in df[:,0]  there was one-time 0.7. The second is 3 because df[:,0] has 3 times 0.9 and so on...
How could I build a dataset as df_1 in the example? or do you have any better ide on how to implement the z-axis in my chart?
Thanks in advance for the help
Answer: Solved with
def map_value_counts(row):
    vmap = row.value_counts().to_dict()
    return row.replace(vmap)

df_1 = df.apply(map_value_counts, axis=1)`


mongodb: how to list all users across all authentication databases

Question: I'm pretty new to Mongo, so this may be a silly question, but I have not found a way to list all users (and their privileges) across all (authentication) databases. Similarly, I have not found a way to list all (authentication) databases. The "show users", "show databases" and their "db.adminCommand(...) versions all seem to run against the current database (the one specified with the "use" command), but what I need is a list of all(!) users and/or all(!) databases, regardless of those users' authentication databases.
Why do I (think) I need this? Well, I periodically must set up Mongo accounts for large groups of users, with each user having his/her/their own database. A few months later, I have to drop those users and their databases. I have a Python program that creates/drops these users and their databases. It all seems to work just fine. When creating a user, I give them their own authenticationDatabase (rather than adding them to "admin") with ReadWrite privileges on that database. As said, all of that seems to work just fine.
However... I need a way to see if, after the program runs (create or drop), users have indeed be created or databases have indeed be dropped by the Python program. Similarly, I need, from time to time, to see who all the users are and what databases I might still have around. Hence, a command for listing all users across all (authentication) databases and for listing all databases across all authentication databases would be welcome.
Hope someone can help (sorry for the long read).
R.
Answer:
I have not found a way to list all users (and their privileges) across
all (authentication) databases.
I have not found a way to list all
(authentication) databases.
... what I need is a list of all(!) users
and/or all(!) databases, regardless of those users' authentication
databases.

Here is a way to get the info you are looking for. Assuming you have the privilege to read other user's information (viewUser action), from the mongo shell you can query as follows:
> db.getUsers( { usersInfo: { forAllDBs: true } } )

This returns an array of all users and authentication databases and other related information. You are interested in "user" and "db fields, mostly. For example:
[
        {
                "_id" : "admin.user1",
                "userId" : UUID("4f7369f6-bffa-45d9-bbdc-5bf50c196ea3"),
                "user" : "user1",
                "db" : "admin",
                "roles" : [ { "role" : "read", "db" : "test" } ],
                "mechanisms" : [ "SCRAM-SHA-1", ... ]
        },
        {
                "_id" : "test.user2",
                "userId" : UUID("1e36faaf-0667-4ec5-bbe9-3f703712cd9a"),
                "user" : "user2",
                "db" : "test",
                "roles" : [ { "role" : "readWrite", "db" : "test" } ],
                ...
        },
        {
                "_id" : "admin.super1",
                "userId" : UUID("bcb2f424-7367-4686-82d8-115748fab951"),
                "user" : "super1",
                "db" : "admin",
                "roles" : [ { "role" : "root", "db" : "admin" } ],
                ...
        }
]

Since you need specific info, the query is customized as follows:
(1) To list all authentication databases, you can query like this:
var dbs = new Set()
db.getUsers( { usersInfo: { forAllDBs: true } } ).forEach(doc => dbs.add(doc.db))
print([...dbs])

The output is a list of unique authentication database names:
admin
test

(2) To list all authentication databases and users:
var dbUsers = [ ]
db.getUsers( { usersInfo: { forAllDBs: true } }  ).forEach(doc => dbUsers.push(doc.db + ", " + doc.user))
dbUsers.sort()
dbUsers.forEach(printjson)

This get the ouput sorted by the authentication database and the user:
"admin, user1"
"admin, super1"
"test, user2"

(3) There are other ways to query too. For example, you can add a filter to get users with authentication database "admin":
db.getUsers( { usersInfo: { forAllDBs: true }, filter: { db: "admin" } }  ).forEach(doc => print(doc.user))

This prints users only for "admin":
super1
user1

NOTES:
For more details see the User Management command usersInfo. The mongo shell provides the db.getUser() helper for this command, and this is used in the above examples.
The server version I tried with is the MongoDB version 4.2.
Comment: Super helpfu;l! Thanks a bundle! (RR)
Answer: There is no built-in command that does that as far as I know but it is straightforward to implement this functionality:

Obtain the list of databases.
For each database, obtain the list of users.


How to properly update nested data in redux

Question: This is my current object which i need to update:
 [
    { id: q1,
      answers:[
                { id: a1,
                  answered: false
                },
                ...
              ]
    },
    ...
 ]

I can't figure out how to update this object and set for example answered = true.
Is there any better way saving this kind of object? I tried to use the update addon from React but can't get it to work properly.
Answer: You can update the answers list this way, in your reducer:
function update(state, action) {
    // assuming you are passing an id of the item to be updated via action.itemId
    let obj = state.whatever_list.filter(item => item.id === action.itemId)[0]

    //assuming you are passing an id of the answer to be updated via action.answerId
    //also, assuming action.payload contains {answered: true}
    let answers = obj.answers.map(answer => answer.id === action.answerId ?
                                            Object.assign({}, answer, action.payload) : answer)
    obj = Object.assign({}, obj, {answers: answers})
    return {
        whatever_list: state.whatever_list.map(item => item.id == action.itemId? Object.assign({}, item, obj) : item)
    }
}

Here is what your action might look like:
function updateAnswer(itemId, answerId, payload) {
    return {
        type: UPDATE_ANSWER,
        itemId: itemId,
        answerId: answerId,
        payload: payload
    }
}

In your react component class, assuming there is an event handler for monitoring whether if a question is answered:
export default class Whatever extends React.Component {

    ...

    // assuming your props contains itemId and answerId
    handleAnswered = (e) => {
        this.props.dispatch(updateAnswer(this.props.itemId, this.props.answerId, {answered: true}))
    }

    ...
}

So basically what happens is this:

Your event handler calls the action and pass the updated data to it
When your action is called, it returns the updated data along with a type parameter
When your reducer sees the type parameter, the corresponding handler will be triggered (the first piece of the code above)
The reducer will pull out the existing data from the list, replace the old data with the new one, and then return a list containing the new data
Answer: You can create a sub-reducer for the answers key. Look at this example:
https://github.com/rackt/redux/blob/master/examples/async/reducers/index.js
Comment: This is already a sub reducer. I don't want to split them one more time.
Answer: You could use dot-prop-immutable and an update would be as simple as:
return dotProp.set(state, 'quiz.0.answers.0.answered', true);


Does the newest Nvidia driver support 3D Vision in Diablo 3?

Question: I used version 300+
http://us.battle.net/d3/en/forum/topic/3123040038?page=2 says that version 280+ already support diablo 3.
Yet when I tried diablo 3 in 3D I do not see anything different. It still look 3D but as any 3D run on full screen.
It's  not impressive. What am I missing? Do I need to set up a 3D profile for diablo 3? If so how?
Some said that diablo 3 is simply not 3D ready yet.
In general any video card have data on the depth. So I wonder why the game has to be 3D ready? As long as they display 3D rendered images any video card should be able to incorporate that.
Comment: There's a difference between a first person shooter, where depth is part of the calculations, and a third person isometric view, where most things are a constant distance away.
Comment: Have you also enabled Stereoscopic 3D in the Nvidia Control Panel?
Comment: Yes of course I have enabled stereoscopic 3d. I just need to test my 3D glasses with something.
Answer: Yes, you can play Diablo 3 in Stereoscopic 3D. Here is a great guide in setting it up: http://us.battle.net/d3/en/forum/topic/5960916051
Answer: 418 was the last driver to support 3D vision for all games.

Official Link
Mirror


configurable jframe elements

Question: I have build a digital clock using Swing JFrame, for now the clock is live but it will always show a set of timezone. Is that possible for me to configure the timezone?
I want to set the timezone, name of the label, show/hide the clock.
Is these are possible in executable jar?
Comment: Yes, you can configure a Swing clock, but you have to create the GUI and write the code to make customization possible.
Answer: Being a configurable application we have two options

Database
File

If it's a small application then choosing a database is completely waste of time and memory. We can achieve the same via writing/reading the file.
Again, if we are packing the configuration.properties or reference file along with our runnable jar. It will fail because all the files within jar are read only, we cannot write into it.
So the only possibility is to

create a temp file either in the same location of the jar or in system
temp folder

configurable jframe elements


Strange Invisible Character in String causing NSURL to fail

Question: I am having a String to Number problem that is taking me days to resolve.  So it all started out in my app that involves taking a phone number from the addressbook and making a call.  Everything was working fine until I noticed some phone numbers were causing my program to crash.
After some time, I finally figured that they were crashing for the phone numbers that had a space in it, which finally made sense because even though it is a phone number I am using NSURL to call "tel://(555) 555 5555" and having a space between it will make the URL invalid which was causing my program to crash.
Now I was happy I figured out the second problem and decided to do a simple character replacement to replace all whitespace with "-".  This worked for the test string I tested it on and everything looked good.  I decided to hook this back up to my code and then my program is still crashing.
I then did some debugging and noticed even though my test case worked, the phone numbers I am pulling from the iOS address book were not having the whitespace replaced.  It seems that whatever character is being used to space out the phone digits is not a whitespace or at least it is not a whitespace that I can simply type like this -> " "
Any idea how to resolve this? Either (1) to know what exactly this invisible character is and replace it or (2) is there a way to just extract a phone number as all numbers instead of the extra chars "+(.)- " or any option here?
Answer: You have to use .stringByAddingPercentEscapesUsingEncoding to convert special characters.
<code>let myLink = "http://google.com"

let myUrl = NSURL(string: myLink.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding)!)!
</code>
Comment: OMG Thank you!!! Just tried it and it worked.  I can't believe how the smallest things sometimes are the things that can cause the biggest headaches.  This literally took me days and slowed me down so much.  I knew it had to be something so silly.  What threw me off is that my messaging part was working fine, until I realized messaging wasnt' using NSURL, so the results wouldn't affect each other.
Comment: I will accept the answer once my 8 mins timer is up.


How can you properly model Nested/Sub Classes in UML?

Question: I've been playing around with UML
My primary background is that of a sysadmin, not as a programmer.
In order to get a better understanding of class models I've been trying to do map out the xmdomain.cfg file the xen hypervisor in UML (you can find the man page at http://linux.die.net/man/5/xmdomain.cfg)
So after working it out i get a basic start like this (note, this is attributes only, not actions)
xenDomU:[
    - kernelImage
    - initialRamdisk
    - allocatedMemory
    - rootDevice
    - nicAmount
    - domuName
]

The following situation has been a real pain in the ass
"disk" and "vif" can both occur multiple times in a domu config file. ("disk" can occur 1 to infinite times and "vif" 0 to infinite times) essentially they are classes themselves
disk:[
    - backendDevice
    - frontendDevice
    - deviceAccessMode
]

virtualNetworkInterface:[
    - networkBridgeDevice
    - interfaceIP
    - macAddress
    - interfaceName
]

In addition, "domain shutdown options" are really 3 values but it's actually best summorized as a single attribute, but then you get the same situation as above.
shutdownOptions{
    - onShutdown
    - onReboot
    - onCrash
}

So after that, you end up with something that really doesn't seem like valid UML to me.
xenDomU:[
    kernelImage
    initialRamdisk
    allocatedMemory
    rootDevice
    nicAmount
    disk:[
        backendDevice
        frontendDevice
        deviceAccessMode
    ]
    domuName
    virtualNetworkInterface:[
        networkBridgeDevice
        interfaceIP
        macAddress
        interfaceName
    ]
    shutdownOptions{
        onShutdown
        onReboot
        onCrash
    }
]

I'm sure there are "better" ways to do this, but this is what seems like the most natural to me.
Could someone please enlighten me and show the right way to do this.
Answer: I didn't understand why couldn't you have Disk and VIF as regular classes and create associations.
As far as I know, UML doesn't support nested classes. However in some cases you can associate package with classes you wanted to be nested with the class you want to nest into.
Answer: For the shutdownOptions, you want to make it an enumeration, instead of a class. You need to declare an attribute of that type in the class for objects that will have one of those options.
Even though classes do allow nested classifiers (UML 2.3, 9.3.1), I agree with Gabriel that Disk and VIF should be standalone classes in the same package, with your main class declaring aggregations of Disks and VIFs. Nested classes are interesting when you want to hide that nested classifier from the outside world, which is rarely the case.

Or in the TextUML notation (which generated the diagram above):
package xen;

class XenDomU
    attribute domuName : String;
    attribute kernelImage : any;
    attribute initialRamdisk : any;
    attribute allocatedMemory : any;
    attribute rootDevice : any;
    attribute nicAmount : any;
    attribute shutdownMode : ShutdownOptions;
    composition disks : Disk[*];
    composition interfaces : VirtualNetworkInterface[*];
end;

class Disk
    attribute backendDevice : any;
    attribute frontendDevice : any;
    attribute deviceAccessMode : any;
end;

class VirtualNetworkInterface
    attribute networkBridgeDevice : any;
    attribute interfaceIP : any;
    attribute macAddress : any;
    attribute interfaceName : any;
end;

enumeration ShutdownOptions
         onShutdown,
         onReboot,
         onCrash
end;

end.


QML Coding Style Checker

Question: I'm looking for a coding style checker for QML code. Something like Checkstyle or Artistic Style. What do people use to define coding style checks for their DSL of choice?
Clarification: I'm looking for something that can be used in build automation not a GUI tool.
Comment: There is a discussion on a Qt list: https://interest.qt-project.narkive.com/RjEOW4BF/beautifier-for-qml
Answer: As far as I know QtCreator works well enough with QML. You can specify a coding style you'd like the editor to adhere to. Then use Tools > Reformat File to format the style.
Comment: That's nice. However I want to automate this (auto-check style on commit, etc). So a GUI tool doesn't kick it, unfortunately.
Comment: Hmmm in that case maybe look for QtCreator plugins? There's an [Artistic Style plugin](http://histomatics.de/proasp.php) for it. You could also refer to this [list](http://qt-project.org/wiki/Qt_Creator_Plug-in_Gallery).
Answer: Since Qt 5.15, a new tool qmlformat is shipped which automatically formats any QML file according to the QML Coding Conventions.
Source: Qt 5.15 release notes
Comment: It formats terrible, not according to this  QML Coding Conventions and not adjustable.
Answer: There seems to be a new code formatter called qmlfmt.
See on github: https://github.com/jesperhh/qmlfmt
Sadly, it doesn't seem to offer a lot of options for now.

QML Coding Style Checker


pam_tally2 on Ubuntu Desktop 22.04LTS

Question: Am I missing something or has the pam_tally2 module and binary been moved to a different package in 22.04?
The libpam-modules and libpam-modules-bin packages are installed but there is no pam_tally2 binary or pam_tally2.so on the machine.
Any ideas?
Answer: The pam_tally2 (and pam_tally) modules are no longer built and pam_faillock is the replacement.
From the changelog for pam (the source package for libpam-modules)
Date: Mon, 28 Dec 2020 06:05:13 +0000
...
   * Drop pam_tally and pam_tally2 modules, which have been deprecated
     upstream in favor of pam_faillock.  Closes: #569746, LP: #772121.

These are the bug reports referenced in that comment

https://bugs.debian.org/cgi-bin/bugreport.cgi?bug=569746
https://bugs.launchpad.net/ubuntu/+source/pam/+bug/772121

The pam_faillock man page

http://manpages.ubuntu.com/manpages/jammy/en/man8/pam_faillock.8.html
Comment: Thanks Andrew. Makes sense and i have moved it over to faillock now.
Comment: how to remove the modules? They are preventing OS upgrade. I understand they have been removed from PAM and it tells me that I need to remove the use of these 2 modules but I haven't been able to find out how to actually do that.
Answer: If Ubuntu won't allow you to upgrade from 20.04 to 22.04 you will need to run grep or find within the /etc/pam.d folder and locate instances in the config files of pam_tally and pam_tally2.
For instance: sudo find /etc/ -type f -exec grep -l -i "pam_tally" {} \;
Simply commenting out the entries was not enough for us - we had to completely remove the lines AND any .bak files we created with pam_tally in them. Good luck!
Answer: I can see the man page is available for pam_tally2 under ubuntu 22.04 jammy.
https://manpages.ubuntu.com/manpages/jammy/man8/pam_tally2.8.html

pam_tally2 on Ubuntu Desktop 22.04LTS


Why are most public restroom faucets so short?

Question: My question was inspired by this one. The majority of public restrooms have huge sinks and short faucets. When I wash my hands, most of the time I touch the back wall of the sink and that makes me wonder, what is all that empty space in the sink used for if the faucet only reaches in to about the fifth of the sink's diameter. Why can't sinks be smaller or faucets go out to the middle of the sink?
Comment: Sinks are cheap, faucets are oddly expensive?
Comment: lot of bathroom posts of late..
Comment: They are making some that are higher, or do what I did put a kitchen sink in bathroom. Had a extra hole drilled in vanity top and put a sprayer for rinsing hair. Everyone has loved it. It comes out further so hands don't hit back of sink and the kid's like it.
Answer: In addition to the material cost that Chad mentioned, they are more durable.  Public restrooms are likely to experience much wear-and-tear from abusive patrons, especially in certain settings.  They must be built to last.
If you have a longer faucet, you can exert greater force on the base of the faucet with less effort on the end.  Simply put, longer faucets are easier to break.
Comment: @Eugene To facilitate multiple people scrubbing simultaneously (not all of the sink time is spent under the faucet)...
Comment: Breaking off a faucet to get into a fight... maybe. But why are the sinks so wide?
Answer: My speculation would be that it also helps to save water (same as the tricks used to make people push controls for the water to flow every 5 seconds) If you have the faucet in a more convenient distance to yourself, you'll probably just keep the water running even when not directly using it, if it's less convenient to reach - you may be encouraged to run the water less times.
Interesting to consider as well (my observations):

if you live in a Scandinavian country (e.g. Holland) you'll notice that in many cases the whole sink/faucet station is so high that a normal/non Scandinavian person, especially a girl, can not really use it properly. Do we really need this kind of height adjustments based on the statistical height of the population?
in South East Asia in smaller bathrooms sometimes you notice that the sink and a shelf above it are almost the same size, protruding from the wall with same distance which makes it impossible to for example wash your face (the shelf will prevent you from keeping your head over the sink) - bad design or built with some purpose?

Just some more bathroom stuff :)
Comment: Holland is not a Scandinavian country, but thanks for playing! ;)
Comment: And also if the faucet is short, then the sensors will not be able to accurately pick up if someone is ready to wash their hands.
Comment: @rahul you're right, I should have phrased the dutch as simply Scandinavian-like very tall people ;)
Comment: Holland is not a country at all, actually, Scandinavian or otherwise.
Comment: As a fairly tall person (1.85 cm, just slightly above average in Norway) I can tell you that using a sink or kitchen desk, etc. much lower than what is the standard height in Norway (sometimes found in kindergardens or childrens schools and everywhere outside scandinavia) so that i have to reach down to about knee height with my hands; it's quite painful to the back. Fewer would probably wash their hands if the sink were uncomfortably high or low, so adjusting for the average height is probably sensible.
Comment: Holland is frequently used as the name of a country. God I hate pedants.
 citation:
G. Geerts & H. Heestermans, 1981, Groot Woordenboek der Nederlandse Taal. Deel I, Van Dale Lexicografie, Utrecht, p 1105


When to use a diamond operator with a method call in Java in form of .methodName()?

Question: Sometimes I see examples of using a diamond operator in the method invocation.
An example of syntax is:
.<ClassName>methodName()

I'm not sure that I understand entirely in which condition there is a case for such use.
Didn't find an explanation of that in the references.
May you explain that case or suggest a source of information where I can find an explanation?
I am providing working an example down below. This example uses RxJava2.
There Flowable.<Integer>create(emitter -> emit(emitter), BackpressureStrategy.BUFFER) doesn't compile without <Integer> because the method emit accepts FlowableEmitter<Integer> emitter.

import io.reactivex.BackpressureStrategy;
import io.reactivex.Flowable;
import io.reactivex.FlowableEmitter;
import io.reactivex.schedulers.Schedulers;

public class Sample {

    public static void main(String[] args) {
        Flowable.<Integer>create(emitter -> emit(emitter), BackpressureStrategy.BUFFER)
                .observeOn(Schedulers.computation(), true,2)
                .map(data -> data * 1)
                .subscribe(Sample::process,
                        err -> System.out.println("ERROR: " + err),
                        () -> System.out.println("DONE"));

    }

    public static void process(int value) {
        System.out.println(value);
        sleep(1000);
    }

    private static void emit(FlowableEmitter<Integer> emitter) {
        int count = 0;

        while(count < 10) {
            count++;

            System.out.println("Emitting ..." + count);
            emitter.onNext(count);
            sleep(500);
        }
    }

    private static boolean sleep(int ms) {
        try {
            Thread.sleep(ms);
            return true;
        } catch (InterruptedException e) {
            return false;
        }
    }

}

When I try to simulate a similar case with plain Java it doesn't work. What I understand wrong?

public class Sample2 {

    public static void main(String[] args) {
        GenericClass.<Integer>genericMethod(param -> processParam(param));

    }

    private static void processParam(GenericClass<Integer> b) {
        }
    }

}

class GenericClass <T> {
    public static <T> GenericClass<T> genericMethod(GenericInterface<T> genericinterface) {
        return new GenericClass<T>();
    }
}

interface GenericInterface <T> {
    T doJob();
}

Comment: It's not `.methodName()` it's `.methodName()`
Comment: The `Foo.baz()` syntax is for when the **method** is generic (not the class itself). So when the method itself introduces a generic type, then this is the way to explicitly state the type, in case auto-inference fails. Auto-inference usually fails in complex setups, when the compiler is "*too dumb*" to follow whats going on, type-wise.
Comment: It's like using `new ArrayList`. Usually it can be omitted, but sometimes the compiler can't infer the generic type. This occurs mostly when there are some chained method calls, and the final generic type isn't given until the last step (or perhaps in an intermediary step). By providing the explicit generic-type for the method, you're helping the compiler (or perhaps yelling at it) by telling what the type should be.
Comment: The diamond operator is when you *don't* specify the type (`<>`).  Does anyone know the correct name for the OPs question?  I've tried looking it up and it's hard to find.
Comment: @markspace The JLS just lists it as a form of invocation expression but I don't think it is given a particular name/term. IIRC, it just calls it things like "invocation with explicit type arguments" or something like that.
Comment: Have somebody managed to simulate this case with plain Java?
Comment: @markspace, this is from Java language specification:  A parameterized type is a class or interface type of the form C, where C
is the name of a generic class or interface, and  is a list of type arguments
that denote a particular parameterization of the generic class or interface.
Comment: Thanks folks and @Sweeper.  I found that a web search for "java generic method invocation parameter" worked pretty well ("method invocation" seems to help a lot).  The tutorial calls this "explicitly" specifying the type (as opposed to inferring the type). https://docs.oracle.com/javase/tutorial/java/generics/methods.html
Answer: ClassName.<Type>methodName(...) is one of the forms of method invocations in Java. There are many other forms as listed in the JLS:
MethodInvocation:
  MethodName ( [ArgumentList] )
  TypeName . [TypeArguments] Identifier ( [ArgumentList] ) <--- this is the form in question
  ExpressionName . [TypeArguments] Identifier ( [ArgumentList] )
  Primary . [TypeArguments] Identifier ( [ArgumentList] )
  super . [TypeArguments] Identifier ( [ArgumentList] )
  TypeName . super . [TypeArguments] Identifier ( [ArgumentList] )

TypeArguments:
  < TypeArgumentList >
TypeArgumentList:
  TypeArgument {, TypeArgument}

Inside the <...>, you are supposed to write the type arguments for each of the type parameters of the generic method explicitly.
Note that ClassName<Type>.methodName is not one of the forms.
The main thing you missed in your attempt to simulate this behaviour in plain Java is that GenericInterface.doJob should take a parameter, because the lambda you pass in has a parameter:
param -> processParam(param)
^^^^^

This parameter should be of type GenericClass<T>, because that is what processParam takes.
interface GenericInterface <T> {
    void doJob(GenericClass<T> param);
}

This is analogous to the subscribe method in FlowableOnSubscribe<T>, which is what Flowable.create takes as argument.
Note that subscribe takes a different type from what Flowable.create returns, but we are taking the same type as what GenericClass.genericMethod returns. This still simulates the same behaviour of "writing the type parameter explicitly compiles but omitting it produces an error", so I will not bother to create a new type.
Now you get the same behaviour as the Flowable.create method in RxJava:
GenericClass.genericMethod(param -> processParam(param)); // error
GenericClass.<Integer>genericMethod(param -> processParam(param)); // OK

This is because Java's type inference algorithm is not powerful enough to infer the type correctly in the first case.
There is still a difference between this and RxJava though - Flowable.create takes a FlowableOnSubscribe<T>, which has a ``
Answer: You can expand your example to:
class Sample2 {

    public static void main(String[] args) {
        GenericClass.genericMethod(new GenericInterface<Integer>() {

            @Override
            public Integer doJob(? param) {
                return param;
            }
        }));

    }

    private static void processParam(GenericClass<Integer> b) {
    }
}

}

class GenericClass <T> {
    public static <T> GenericClass<T> genericMethod(GenericInterface<T> genericinterface) {
        return new GenericClass<T>();
    }
}

interface GenericInterface <T> {
    T doJob();
}

As you can see your lambda expression expects some input parameter "? param" which does not match the signature of GenericInterface#doJob. If you change your code to this:
lass Sample2 {

    public static void main(String[] args) {
        GenericClass.genericMethod(param -> processParam(param)); // <- this compiles now without any "<..>"

    }

    private static void processParam(GenericClass<Integer> b) {
    }
}

}

class GenericClass <T> {
    public static <T> GenericClass<T> genericMethod(GenericInterface<T> genericinterface) {
        return new GenericClass<T>();
    }
}

interface GenericInterface <T> {
    T doJob(T param);
}

When you struggle with lamdas and Functional Interfaces try expanding them to their anonymous inner class counterparts. This can help your IDE to give your better feet back and makes mistakes like this more obvious.


Loop through multiple CSV files and run a script

Question: I have a script which pulls in data from a csv file, does some manipulations to it and creates an output excel file. But, its a tedious process as I need to do it for multiple files.
Question: Is there a way for me to run this script across multiple csv files together and create a separate excel file output for each input file?
I'm not sure what to try out here. I've read that I need to use a module called glob but I'm not sure how to go about it.
This script works for a single file:
# Import libraries
import pandas as pd
import xlsxwriter

# Set system paths
INPUT_PATH = 'SystemPath//Downloads//'
INPUT_FILE = 'rawData.csv'

OUTPUT_PATH = 'SystemPath//Downloads//Output//'
OUTPUT_FILE = 'rawDataOutput.xlsx'

# Get data
df = pd.read_csv(INPUT_PATH + INPUT_FILE)

# Clean data
cleanedData = df[['State','Campaigns','Type','Start date','Impressions','Clicks','Spend(INR)',
                  'Orders','Sales(INR)','NTB orders','NTB sales']]
cleanedData = cleanedData[cleanedData['Impressions'] != 0].sort_values('Impressions',
                                                                       ascending= False).reset_index()
cleanedData.loc['Total'] = cleanedData.select_dtypes(pd.np.number).sum()
cleanedData['CTR(%)'] = (cleanedData['Clicks'] /
                         cleanedData['Impressions']).astype(float).map("{:.2%}".format)
cleanedData['CPC(INR)'] = (cleanedData['Spend(INR)'] / cleanedData['Clicks'])
cleanedData['ACOS(%)'] = (cleanedData['Spend(INR)'] /
                          cleanedData['Sales(INR)']).astype(float).map("{:.2%}".format)
cleanedData['% of orders NTB'] = (cleanedData['NTB orders'] /
                                  cleanedData['Orders']).astype(float).map("{:.2%}".format)
cleanedData['% of sales NTB'] = (cleanedData['NTB sales'] /
                                 cleanedData['Sales(INR)']).astype(float).map("{:.2%}".format)
cleanedData = cleanedData[['State','Campaigns','Type','Start date','Impressions','Clicks','CTR(%)',
                           'Spend(INR)','CPC(INR)','Orders','Sales(INR)','ACOS(%)',
                           'NTB orders','% of orders NTB','NTB sales','% of sales NTB']]

# Create summary
summaryData = cleanedData.groupby(['Type'])[['Spend(INR)','Sales(INR)']].agg('sum')
summaryData.loc['Overall Snapshot'] = summaryData.select_dtypes(pd.np.number).sum()
summaryData['ROI'] = summaryData['Sales(INR)'] / summaryData['Spend(INR)']

# Push to excel
writer = pd.ExcelWriter(OUTPUT_PATH + OUTPUT_FILE, engine='xlsxwriter')
summaryData.to_excel(writer, sheet_name='Summary')
cleanedData.to_excel(writer, sheet_name='Overall Report')
writer.save()

I've never tried anything like this before and I would appreciate your help trying to figure this out
Comment: Possible duplicate of [Looping through Multiple CSV files and producing Multiple Outputs](https://stackoverflow.com/questions/53174144/looping-through-multiple-csv-files-and-producing-multiple-outputs)
Answer: You can use Python's glob.glob() to get all of the CSV files from a given folder. For each filename that is returned, you could derive a suitable output filename. The file processing could be moved into a function as follows:
# Import libraries
import pandas as pd
import xlsxwriter
import glob
import os

def process_csv(input_filename, output_filename):
    # Get data
    df = pd.read_csv(input_filename)

    # Clean data
    cleanedData = df[['State','Campaigns','Type','Start date','Impressions','Clicks','Spend(INR)',
                    'Orders','Sales(INR)','NTB orders','NTB sales']]
    cleanedData = cleanedData[cleanedData['Impressions'] != 0].sort_values('Impressions',
                                                                        ascending= False).reset_index()
    cleanedData.loc['Total'] = cleanedData.select_dtypes(pd.np.number).sum()
    cleanedData['CTR(%)'] = (cleanedData['Clicks'] /
                            cleanedData['Impressions']).astype(float).map("{:.2%}".format)
    cleanedData['CPC(INR)'] = (cleanedData['Spend(INR)'] / cleanedData['Clicks'])
    cleanedData['ACOS(%)'] = (cleanedData['Spend(INR)'] /
                            cleanedData['Sales(INR)']).astype(float).map("{:.2%}".format)
    cleanedData['% of orders NTB'] = (cleanedData['NTB orders'] /
                                    cleanedData['Orders']).astype(float).map("{:.2%}".format)
    cleanedData['% of sales NTB'] = (cleanedData['NTB sales'] /
                                    cleanedData['Sales(INR)']).astype(float).map("{:.2%}".format)
    cleanedData = cleanedData[['State','Campaigns','Type','Start date','Impressions','Clicks','CTR(%)',
                            'Spend(INR)','CPC(INR)','Orders','Sales(INR)','ACOS(%)',
                            'NTB orders','% of orders NTB','NTB sales','% of sales NTB']]

    # Create summary
    summaryData = cleanedData.groupby(['Type'])[['Spend(INR)','Sales(INR)']].agg('sum')
    summaryData.loc['Overall Snapshot'] = summaryData.select_dtypes(pd.np.number).sum()
    summaryData['ROI'] = summaryData['Sales(INR)'] / summaryData['Spend(INR)']

    # Push to excel
    writer = pd.ExcelWriter(output_filename, engine='xlsxwriter')
    summaryData.to_excel(writer, sheet_name='Summary')
    cleanedData.to_excel(writer, sheet_name='Overall Report')
    writer.save()

# Set system paths
INPUT_PATH = 'SystemPath//Downloads//'
OUTPUT_PATH = 'SystemPath//Downloads//Output//'

for csv_filename in glob.glob(os.path.join(INPUT_PATH, "*.csv")):
    name, ext = os.path.splitext(os.path.basename(csv_filename))
    # Create an output filename based on the input filename
    output_filename = os.path.join(OUTPUT_PATH, f"{name}Output.xlsx")
    process_csv(csv_filename, output_filename)

os.path.join() can be used as a safer way to join file paths together.
Answer: Something like:
import os
import glob
import pandas as pd

os.chdir(r'path\to\folder') #changes folder path to working dir
filelist=glob.glob('*.csv') #creates a list of all csv files
for file in filelist:       #loops through the files
    df=pd.read_csv(file,...)
    #Do something and create a final_df
    final_df.to_excel(file[:-4],+'_output.xlsx',index=False) #excel with same name+ouput

Answer: you can run this scrip inside a for loop:
for file in os.listdir(INPUT_PATH):
    if file.endswith('.csv') or file.endswith('.CSV'):
        INPUT_FILE = INPUT_PATH + '/' + file
        OUTPUT_FILE = INPUT_PATH  + '/Outputs/' + file.[:-4] + 'xlsx'

Comment: Thank you for this, this was the easiest way to do it!
Answer: try this:
import glob

files = glob.glob(INPUT_PATH + "*.csv")

for file in files:
    # Get data
    df = pd.read_csv(file)

    # Clean data
    #your cleaning code

   # Push to excel
   writer = pd.ExcelWriter(OUTPUT_PATH + file.split("/")[-1].replace(".csv","_OUTPUT.xlxs", engine='xlsxwriter')


Error when creating Sales Order via Script for Fedex Ground

Question: While I try to create sales order via Suitelet and give shipmethod or Ship Via field to Fedex Ground for Customers who are not in terms, it throws an error
<code> Could not calculate cost for the selected Realtime rate. The rate for this service is not available for the specified source and destination addresses.
    {
       type: "error.SuiteScriptError",
       name: "USER_ERROR",
       message: "Could not calculate cost for the selected Realtime rate. The rate for this service is not available for the specified source and destination addresses.",
       stack: [
          "anonymous(N/recordService)",
          "functionname(/SuiteApps/script name:line number)"
       ],
       cause: {
          type: "internal error",
          code: "USER_ERROR",
          details: "Could not calculate cost for the selected Realtime rate. The rate for this service is not available for the specified source and destination addresses.",
          userEvent: null,
          stackTrace: [
             "anonymous(N/recordService)",
             "functionname(/SuiteApps/script name:line number)"
          ],
          notifyOff: false
       },
       id: "",
       notifyOff: false
    }
</code>
Answer: What do you mean by "customers who are not if terms"? Usually I experience this error if customer address is not populated properly.
Comment: We use terms 30, terms 60 etc.. It just mean that customers whoa re in terms with us can pay later.
The address is entered correctly. When I change the customers to terms, the script works fine. But when I change customer back to no/nill terms , script throws an error
Comment: Instead of setting the terms to empty, why not set it to "Due on Receipt"?
Answer: The shipping carrier you have opted for delivery is not able to calculate the real-time shipping cost for the customer's address, or it is also possible that the shipping carrier does not provide their services at customer's address. You can check by changing the customer's address. Also, you can check by choosing different shipping methods.


Minecraft testfor not me

Question: I tried to make the testfor command in Minecraft to test for a player that is not me in a radius of 10 blocks, but when I did /testfor @p[r=10,!name=KeithAwesome2] it didn't work.
Please help me!
Answer: Use /testfor @p[r=10,name=!KeithAwesome2], You just had the syntax a little bit wrong.

Minecraft testfor not me


PowerShell variable within variable

Question: I am trying to add a variable $numberOfNics which adds nics based on the number.  Right now this is my code, and I am a little confused as to how to put it into a loop.  I know an array is probably the way to go but not quite sure how to make an array in this sense that just calls variables instead of sets them.
old code:
$numberOfNics=1

$networkname1 = "ondemandport1"
$networkname2 = "ondemandport2"
$networkname3 = "ondemandport3"
$networkname4 = "ondemandport4"
$networkname5 = "ondemandport5"
$networkname6 = "ondemandport6"
$networkname7 = "ondemandport7"
$networkname8 = "ondemandport8"
$networkname9 = "ondemandport9"

$networkInterface1 = New-AzureRmNetworkInterface -Name $networkname1

$networkInterface2 = New-AzureRmNetworkInterface -Name $networkname2

$networkInterface3 = New-AzureRmNetworkInterface -Name $networkname3

$networkInterface4 = New-AzureRmNetworkInterface -Name $networkname4

$networkInterface5 = New-AzureRmNetworkInterface -Name $networkname5

To tidy this up, I would like to make a loop something like this
for ($i = 0; $i -lt $numberOfNics; $i++)
{
    $networkInterface$i = New-AzureRmNetworkInterface -Name $networkname$i
}

EDIT:
Thanks Martin, but now I am having trouble calling the variable.
$networkInterfaces = 1 .. $numberOfNics | ForEach-Object {
if ($a -eq 0){
    New-AzureRmNetworkInterface -ResourceGroupName $resourceGroupName -Name "ondemandport$_" -Location $locationName -SubnetId $virtualNetwork.Subnets[$a].Id -PublicIpAddressId $publicIp.Id -force
    }
ElseIf ($a=1){
    New-AzureRmNetworkInterface -ResourceGroupName $resourceGroupName -Name "ondemandport$_" -Location $locationName -SubnetId $virtualNetwork.Subnets[$a].Id -force
    }
Else{
    New-AzureRmNetworkInterface -ResourceGroupName $resourceGroupName -Name "ondemandport$_" -Location $locationName -SubnetId $virtualNetwork.Subnets[2].Id -force
    }

}

#also looking to make this into a array loop
$vmConfig = Add-AzureRmVMNetworkInterface -VM $vmConfig -Id $networkInterfaces[1].Id -Primary
$vmConfig = Add-AzureRmVMNetworkInterface -VM $vmConfig -Id $networkInterfaces[2].Id
$vmConfig = Add-AzureRmVMNetworkInterface -VM $vmConfig -Id $networkInterfaces[3].Id
$vmConfig = Add-AzureRmVMNetworkInterface -VM $vmConfig -Id $networkInterfaces[4].Id
$vmConfig = Add-AzureRmVMNetworkInterface -VM $vmConfig -Id $networkInterfaces[5].Id
$vmConfig = Add-AzureRmVMNetworkInterface -VM $vmConfig -Id $networkInterfaces[6].Id
$vmConfig = Add-AzureRmVMNetworkInterface -VM $vmConfig -Id $networkInterfaces[7].Id
$vmConfig = Add-AzureRmVMNetworkInterface -VM $vmConfig -Id $networkInterfaces[8].Id
$vmConfig = Add-AzureRmVMNetworkInterface -VM $vmConfig -Id $networkInterfaces[9].Id

Error message: Add-AzureRmVMNetworkInterface : Cannot validate argument on parameter 'Id'. The argument is null or empty. Provide an argument
that is not null or empty, and then try the command again.
Answer: You can also do it with one line:
$networkInterfaces = 1 .. $numberOfNics | ForEach-Object { New-AzureRmNetworkInterface -Name "ondemandport$_" }

Now you can access the interfaces by index, for example:
$networkInterfaces[2]

By the way, consider using ARM templates instead.

Edit:
$networkInterfaces = 1 .. $numberOfNics | ForEach-Object {

    $isPrimary = $_ -eq 0 # set the first one as primary

    $nic = Get-AzureRmNetworkInterface -Name "ondemandport$_" -ResourceGroupName $resourceGroupName
    Add-AzureRmVMNetworkInterface -VM $vmConfig -Id $nic.Id -Primary:$isPrimary
}

Comment: Thanks Martin, the one liner worked well, and I've added it to my code, however, now I am having errors when calling the variable.  I've edited my original post to show the error I am getting.
Comment: @doggydogworld The first interface would have index 0, maybe you get out of range here? However, you could try to use the `Get-AzureRemNetworkInterface` cmdlet to retrieve the nic, see my edited answer.
Answer: You should be able to do something like this:
$numberOfNics= 10
$networkname = "ondemandport"

$networkInterface = @()

for ($i = 0; $i -le $numberOfNics; $i++)
{
    $networkInterface += ,@( New-AzureRmNetworkInterface -Name ($networkname + $i ))
}

Not sure if it will work with the New-AzureRmNetworkInterface but works with other New- commands
Answer: You could use PowerShell Get-Variable cmdlet. One thing which I would like to point out is the for loop which you are using will not be limited till $numberOfNics, but as a matter of fact, it's length will depend upon $networkname variable. For example, you are having networkname variables from $networkname1 to $networkname9, so your loop will look something like this -
$NetworkInfo = @()
for($i = 1; $i -le 9; $i++) {$NetworkInfo += Get-Variable("networkname" + $i)}

Now $NetworkInfo has
Name                           Value
----                           -----
networkname1                   ondemandport1
networkname2                   ondemandport2
networkname3                   ondemandport3
networkname4                   ondemandport4
networkname5                   ondemandport5
networkname6                   ondemandport6
networkname7                   ondemandport7
networkname8                   ondemandport8
networkname9                   ondemandport9

You can put another for loop something like this -
$NetworkInterface = @()
for ($i = 0; $i -lt $NetworkInfo.Length; $i++)
{
    $NetworkInterface +=  New-AzureRmNetworkInterface -Name $NetworkInfo.Value[$i]
}

Individual elements can then be accessed by $NetworkInterface[0], $NetworkInterface[1]... and so on.

PowerShell variable within variable


I can't find the error in a program with a while loop

Question: I'm learning how to program in C. Can someone help me out to find a problem in my code? I'm trying to write a program that change seconds to minutes and seconds (like 100 seconds equals 1 minute and 40 seconds).
That's the program:
#include <stdio.h>
#define SEC_TO_MIN 60

int main(void)
{
    int sec, min, left;

    printf("Seconds to minutes and seconds!\n");
    printf("Give me an amount of seconds (<=0 is the end):\n");
    scanf("%d, &sec");

    while (sec > 0)
    {
        min = sec / SEC_TO_MIN;
        left = sec % SEC_TO_MIN;
        printf("%d seconds is %d minutes, %d secunds.\n", sec, min, left);
        printf("Next number of seconds (<=0 is the end):\n");
        scanf("%d", &sec);
    }
    printf("The End!\n");
    return 0;
}

Comment: `scanf("%d, &sec");` --> `scanf("%d", &sec);`
Comment: Do you have warnings enabled? Your compiler should've warned you about `scanf("%d, &sec");`.
Comment: With an error such as a missing `"` or `#endif` or `}` the compiler can't easily tell exactly where it was supposed to be, so you can get an unusual or irrelevant error report.
Comment: @DavidRanieri: Sorry for not understanding what you intended in your initial comment. In principle, I agree with you about checking the input for errors, but for such a small program, I think "accept input while it's valid, then stop" is valid. Sorry again for starting a slew of comments that won't halp the OP at all.
Comment: @MOehm C'mon, is there a better way to pass the quarantine? :)
Comment: @HolyBlackCat Oh my god. I'm really sorry. It was so easy.
Thank you a lot!
Comment: @HolyBlackCat
I do have warrning enabled but it did not showed me any problems with my scanf :/
Comment: You are welcome, notice that repeating code (like in this case where you are calling `scanf` twice) is considered bad  style and more prone to errors (as you can see in your snippet). Take a look to the `do {...} while(...);` iterator.
Comment: @DavidRanieri: I don't see how `do` ... `while` is useful here. The repetition could be removed by putting everything related to input and validation into the loop control: `while (scanf("%d", &sec) == 1 && sec > 0) ...`, which would stop on non-positive numbers, on anything that's not a number and on end of input via `^Z`/`^C`.
Comment: @MOehm  In your approach (`while (scanf("%d", &sec)`)  there is no way to check the result of `scanf`, consider `do { int error = scanf(....) != 1; if (error) ... } while (error == 1);`
Comment: @DavidRanieri: You are misquoting my approach, which does check for `scanf`'s return value and for the value of `sec`, which is what OP requires. _De gustibus_ and all that, but I find your approach with an additional variable and an additional if and therefore an extra level of indentation inferior.
Comment: @MOehm I'm not misquoting, you can check it, but you can not inform (i.e. `puts("Write a valid number");`) using your approach, there are tons of way to solve this, my point was: do not repeat code
Comment: You may want to select a more helpful compiler.  Even without enabling any extra warnings, gcc warns about this code: `warning: format '%d' expects a matching 'int *' argument [-Wformat=]`
Comment: Oh, you are suggesting error handling of the input? Sure, that would be good, but the original post didn't have that, either and it would probably be a bit too much for such a small program That's the big issue with C training: You want to teach algorithms but you end up arguing about `scanf`. `:(`
Comment: @MOehm ... you are right and I didn't pay attention to this: OP is not checking for errors (OP: you should, even in short snippets), personally I prefer a `do .. while` than a `while(1)` or a `for(;;)` in those cases, even if its more verbose, it makes clear that it must runs at least once.
Answer: Because code was not compiled with a good compiler with warnings all enabled. Example: "warning: format '%d' expects argument of type 'int*'
so if you replace
scanf("%d, &sec");

to be
scanf("%d", &sec);

it will works successfully
Answer: It is not the problem of while but the solution is simple
check out the scanf statement before the while
i.e
scanf("%d",&sec);

reason why that problem came is to read a value through scanf function u use the format specifier %d for signed integer that u r going to allocate a value and that value is stored in the variable sec so while coding  always be care full about the inverted commas. it cannot be used where address is specified.