Embedded Google Maps or static stylized map

Question: Embedding Google Maps on your website doesn't always have the right effect on the design. With some effort you can stylize Google Maps, but I have bad experiences with that.
To me, the only real reason to embed the Google map is the interactivity and the fact visitors can easily plan a route.
When I'm advising clients what to use I name the aesthetic value of the static stylized map and the interactive possibilities of the Google map. Most of the time they don't question my advice and go for the Google Map, but recently a client asked me about the usage of the Google map. How often do visitor actually use the interactive possibilities of the Google Map? I couldn't answer.
My personal experience is that I never use any Google maps on websites. Often they are 300x500 pixels and just too small to use easily. The Google Maps website is often more clear with the big, window filling, map.
Does anyone have any statistics or experience with this issue? (I couldn't find any)
Comment: Purely subjective here - but I often use the embedded map on sites to zoom out to give me some context as to their actual location. (I'm not looking for full navigation, just a way to zoom out until I recognise the general area). Specific street address may be useful for people who know the area of the place, but just a zoomed in map showing 'George St' and 'Martin Luther King Bvd' is no use to someone not familiar with the location.
Comment: Have you considered using some other map services? E.g. the BBC [chose to use](http://careerssearch.bbc.co.uk/jobs/job/Work-Experience-Opportunities-in-London-%20within-Television/9587) [Openstreetmap](http://www.openstreetmap.org/), there are also the [Bing Maps](http://www.bing.com/maps/) or [Here Maps](http://here.com) which are also a good alternative. Just wanted to point out to whoever finds this that it's not only about the Google Maps really
Answer: Coming from a cartography background, I agree with you in a sense. Some of those maps are useless, however some are quite useful. Let's take a look at a couple examples.
The first is something like you describe like on the Yelp website when you search. The link provided takes you to a search I did searching for Taco places in NYC and as you can see, this map isn't very helpful IF you want to browse using the map. In this particular case however, that isn't the main point of why Yelp wanted you to go to their website. They wanted you to go to browse listings, read and create reviews, add photos, etc. Having the map there is like a cherry on top.
The next example is something like AirBnB when searching for a place to stay. The map takes up half of the screen, but the intention is that the user will browse the list on the left first, then continue on the right with the map to make sure the location is close to attractions, friends, or whatever else they want to see.
The final example is something like Padmapper while looking for apartments and homes. In this case, the filters are somewhat of a secondary measure, because without the map, you would be browsing a giant list of apartments. This isn't super helpful because in real estate, it's all about "Location, Location, Location!".

So to answer your original question...

What's your opinion?

My answer would be it depends on what you want to the user to do with the map. One thing to always keep in mind though is the smaller the map, the harder it will be to interact with it. So if you want to put a map up that you want your users to use, make sure it is big enough so people don't get so frustrated they leave your site.
Also, consider other alternatives other than Google Maps. Leaflet has a great set of tools to create awesome looking maps and there are plenty of tile sources out there, like the ones from Stamen Design to help give you the perfect look for your map.
Answer: Typically maps shown on a website are small as they aren't the focus of the page, and so trying to navigate or interact with a small map is a nightmare.  So usability wise, the interactivity is poor.
To me the best option is to use a good looking stylistic map, but make it clickable and link it to an interactive online map where a user can use the full screen.  Something like the map below.
Comment: I like the idea of linking to Google Maps (or other interactive map) with full route description, maybe even with 'your location' selected.
Answer: I just randomly found this but thought that I could help out in some way.
You ought to check out a company like Mapbox! A great, styler for Google Maps design. This customizer is great for these GM integrations.
Also, in my personal experience, I have used maps in websites before. In commerce design, it's essential for displaying the numerous retailers your client is located. However the use of static VS interactive depends solely on context – what is the user trying to do with the map? Getting a glance at a location? Or planning a trip? Etc.
Answer: It depends greatly on the nature of your app. If you only need to highlight the location of your business consider a static or extremely simple map embedded for reference.
If you need directions - as somebody above mentioned - you can link to a directions provider like Google (with the destination prepopulated) to guide users to the business.
Yelp or AirBnB use a Partial Map to relate results in a list to their geographic location on the map. The map also serves as a 'spatial filter' to adjust the results accordingly.
Concluding I don't think you are after statistics for what works better but ought to think about the purpose of using a map which will inform the best approach.


Unable to send text to Email field on Microsoft login page using Selenium

Question: I'm trying to figure out a way to automatically log in / enter text into a given text field on a particular web page. I've already don't this before, but this particular page isn't responding to anything I've thrown at it yet.
The default page load already has the auto-focus on the necessary text box. I'm currently using Python to write the Selenium code. My current script includes prior processes that lead to the page in question, where my current problem lies. Additionally, I've been running this code in a Google-Chrome browser, but with the user-agent selected to Edge - Mobile (but that probably won't matter here).
The website in question is the Microsoft login at this link.
The CSS/HTML of the text box in question:
<input type="email" name="loginfmt" id="i0116" maxlength="113" lang="en" class="form-control ltr_override" aria-describedby="usernameError loginHeader loginDescription" aria-required="true" data-bind="textInput: usernameTextbox.value,
                    hasFocusEx: usernameTextbox.focused,
                    placeholder: $placeholderText,
                    ariaLabel: tenantBranding.UserIdLabel || str['CT_PWD_STR_Username_AriaLabel'],
                    css: { 'has-error': usernameTextbox.error },
                    attr: inputAttributes" placeholder="Email, phone, or Skype" aria-label="Enter your email, phone, or Skype.">

The code I'm currently testing (which is basically three varied iterations of the same idea), after the given page loads:
element = driver.find_element_by_id("i0116")
element.click()
element.clear()
element.send_keys("firstname.lastname@example.com")
element.send_keys(Keys.RETURN)

time.sleep(1)

element = driver.find_element_by_name("loginfmt")
element.click()
element.clear()
element.send_keys("firstname.lastname@example.com")
element.send_keys(Keys.RETURN)

time.sleep(1)

element = driver.find_element_by_css_selector("input.email")
element.click()
element.clear()
element.send_keys("email@example.com")
element.send_keys(Keys.RETURN)

Unfortunately, trying to select the textbox via the input id, class, or name don't seem to be working. It should be worth noting that the page CSS I'm referencing for the text box includes an element "input" prior - I'm not sure if this will affect my current code. I'm fairly certain that either the send_keys aren't working, or perhaps the selection of the element, itself.
What makes the situation even more frustrating is that the page's default focus is on the textbox - so I don't even truly need to select the element, I just need to be able to enter text and submit/enter.
I've also tried targeting it as an iframe, but that hasn't seemed to help either.
Any ideas? Any and all help would be deeply appreciated. I am simply trying to find a way to enter text into the login box.
Answer: To enter an EmailID into the field with placeholder text as Email, phone, or Skype you can use the following code block :
from selenium import webdriver
from selenium.webdriver.chrome.options import Options

options = Options()
options.add_argument("start-maximized")
options.add_argument("disable-infobars")
options.add_argument("--disable-extensions")
driver = webdriver.Chrome(chrome_options=options, executable_path=r'C:\Utility\BrowserDrivers\chromedriver.exe')
driver.get('https://login.live.com/login.srf')
print("Page Title is : %s" %driver.title)
element = driver.find_element_by_xpath("//input[@class='form-control ltr_override' and @name='loginfmt']")
element.click()
element.clear()
element.send_keys("firstname.lastname@example.com")

Console Output :
Page Title is : Sign in to your Microsoft account

Snapshot :
Comment: Everything seems to be working. Thank you very much. Side question: say I was trying to do basically the same thing with the next page, which has password text box- how do I select the text box? I tried using your driver.find_element_by_xpath method but switched out the @class and @name's; however, nothing enters into the text field. Any thoughts?
Comment: Actually, it seems that I've got it! I realized that other parts of the code I was using that I hadn't posted were conflicting. Thanks again.


Iron in Hot Water Heater

Question: My water has a lot of iron in it so I have a water softener to take care of that. The problem is I forgot to check it and it ran out of salt.
The majority of my house is fine (I have to better clean my toilet tanks still), but my hot water heater appears to be giving out brown water now. I am in the middle of draining it now so that I can flush it, but I am wondering if there is anything else I should do to care of this? Is solving this problem something for a professional or do I just need to keep flushing it out until the problem is solved?
Answer: Flushing the water heater did the trick.

Iron in Hot Water Heater


Date not saved correctly to MySQL

Question: MySQL doesn't save the date properly.I am trying to add createdAt column in database.
I've tried using MySQL NOW() function already, but it doesn't seem to work.
// Go pseudo-code with sql query
stmt, _:= d.db.Prepare("INSERT INTO posts(title, body, EmailHref, SlackHref, DiscordHref, InstHref, Time) VALUES(?, ?, ?, ?, ?, ?, NOW());")
res, err := stmt.Exec(newPost.Title, newPost.Body, newPost.EmailHref, newPost.SlackHref, newPost.DiscordHref, newPost.InstHref)

The type for createdAt column in MYSQL is DATE.
This is what I get when i fetch newly created post:
"time": "2019-04-24T00:00:00Z"

I expect to get actual time with up to minutes.
Comment: ok thanks everyone, your answers solved my problem.
Answer: In case you want to store the time too, you have to use DATETIME instead of DATE.
You can use the following query to change the column type of column createdAt:
ALTER TABLE posts MODIFY createdAt DATETIME

The DATE data type can't store a time part so you have to use DATETIME:
SELECT CAST(NOW() AS DATE);     -- 2019-04-24
SELECT CAST(NOW() AS DATETIME); -- 2019-04-24 09:47:57

Answer: I think you simple need to change the type from DATE to DATETIME in mySQL
alter table <tableName> modify <columnName> DATETIME;

Comment: @E.Belekov DATE is for storing dates, DATETIME for storing datetimes (dates with times), TIMESTAMPS also stores dates with times, are also faster, but datetime is easier to work with (timezones, sql native functions, ...)
Comment: DATE will simply show you only the date without any time. If you want to add the time you need to change your type to DATETIME or TIMESTAMP
Comment: Couldn't say it any better @PavelTřupek
Comment: Whose answer should I accept? You and Sebastian Brosch both answered at the same moment.
Comment: You can order on oldest an choose the oldest answer, the choice is yours :-)
Comment: Sorry for the fact that it's been 2 days, thanks anyway!

Date not saved correctly to MySQL


dual boot windows 10 and ubuntu 14.04 problem error no such device

Question: [gparted photo]
I had windows 10 alongside Ubuntu 14.04 on the same hard drive.
When I switch on and the list of options to boot appears I can boot into Ubuntu ok and access all windows files, but can not boot into windows 10.
When I choose windows 10 to boot I get the message:
error: no such device: 27795F9B69145D5C.
press any key to continue...

Then the screen goes blank
I am new to Ubuntu.

vuletic@vuletic-Aspire-5735:~$ sudo blkid
[sudo] password for vuletic:
/dev/sda1: LABEL="PQSERVICE" UUID="EAEE-EB49" TYPE="vfat"
/dev/sda2: UUID="a03c32da-1e8d-4c37-8aa7-b8e8e501f63b" TYPE="ext4"
/dev/sda3: LABEL="C:/" UUID="27795F9B69145D5C" TYPE="ntfs"
/dev/sda4: UUID="323C3EB83C3E7747" TYPE="ntfs"
vuletic@vuletic-Aspire-5735:~$

vuletic@vuletic-Aspire-5735:~$ cat /etc/fstab
# /etc/fstab: static file system information.
#
# Use 'blkid' to print the universally unique identifier for a
# device; this may be used with UUID= as a more robust way to name devices
# that works even if disks are added and removed. See fstab(5).
#
#
proc            /proc           proc    nodev,noexec,nosuid 0       0
# / was on /dev/sda2 during installation
UUID=a03c32da-1e8d-4c37-8aa7-b8e8e501f63b /               ext4    errors=remount-ro 0       1
vuletic@vuletic-Aspire-5735:~$

vuletic@vuletic-Aspire-5735:~$ sudo fdisk -l

Disk /dev/sda: 500.1 GB, 500107862016 bytes
255 heads, 63 sectors/track, 60801 cylinders, total 976773168 sectors
Units = sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes
Disk identifier: 0xc637a1a9

   Device Boot      Start         End      Blocks   Id  System
/dev/sda1            2048    20482047    10240000   27  Hidden NTFS WinRE
/dev/sda2        20482048    79077375    29297664   83  Linux
/dev/sda3   *    79079424   975055575   447988076    7  HPFS/NTFS/exFAT
/dev/sda4       975056896   976054271      498688   27  Hidden NTFS WinRE
vuletic@vuletic-Aspire-5735:~$

vuletic@vuletic-Aspire-5735:~$ sudo add-apt-repository ppa:yannubuntu/boot-repair
[sudo] password for vuletic:
 Simple tool to repair frequent boot problems.

Website: https://sourceforge.net/p/boot-repair/home
 More info: https://launchpad.net/~yannubuntu/+archive/ubuntu/boot-repair
Press [ENTER] to continue or ctrl-c to cancel adding it

gpg: keyring `/tmp/tmphj6oekac/secring.gpg' created
gpg: keyring `/tmp/tmphj6oekac/pubring.gpg' created
gpg: requesting key 60D8DA0B from hkp server keyserver.ubuntu.com
gpg: /tmp/tmphj6oekac/trustdb.gpg: trustdb created
gpg: key 60D8DA0B: public key "Launchpad PPA for YannUbuntu" imported
gpg: Total number processed: 1
gpg:               imported: 1  (RSA: 1)
OK
vuletic@vuletic-Aspire-5735:~$
14.04

vuletic@vuletic-Aspire-5735:~$ sudo update-grub
Generating grub configuration file ...
Found linux image: /boot/vmlinuz-3.13.0-106-generic
Found initrd image: /boot/initrd.img-3.13.0-106-generic
Found linux image: /boot/vmlinuz-3.13.0-49-generic
Found initrd image: /boot/initrd.img-3.13.0-49-generic
Found linux image: /boot/vmlinuz-3.13.0-48-generic
Found initrd image: /boot/initrd.img-3.13.0-48-generic
Found linux image: /boot/vmlinuz-3.5.0-49-generic
Found initrd image: /boot/initrd.img-3.5.0-49-generic
Found Windows Recovery Environment (loader) on /dev/sda1
Found Windows 10 (loader) on /dev/sda3
Found linux image: /boot/vmlinuz-3.13.0-106-generic
Found initrd image: /boot/initrd.img-3.13.0-106-generic
Found linux image: /boot/vmlinuz-3.13.0-49-generic
Found initrd image: /boot/initrd.img-3.13.0-49-generic
Found linux image: /boot/vmlinuz-3.13.0-48-generic
Found initrd image: /boot/initrd.img-3.13.0-48-generic
Found linux image: /boot/vmlinuz-3.5.0-49-generic
Found initrd image: /boot/initrd.img-3.5.0-49-generic
Found memtest86+ image: /boot/memtest86+.elf
Found memtest86+ image: /boot/memtest86+.bin
Found Windows Recovery Environment (loader) on /dev/sda1
Found Windows 10 (loader) on /dev/sda3
done
vuletic@vuletic-Aspire-5735:~$
Comment: Edit your question to include the output, from the `terminal` app, of `sudo blkid` and `cat /etc/fstab`.
Comment: i hope this is info you asked
Comment: The line **/dev/sda3: LABEL="C:/" UUID="27795F9B69145D5C" TYPE="ntfs"** tells me that indeed that the device IS there. What I don't see is any swap file or swap partition. Post the output of `sudo fdisk -l` and a current-window-only screenshot of `gparted`. Do you have a Windows 10 install/repair disc?
Comment: i dont have windows 10 install/repair disc as i installed it from internet
Comment: Did this **ever** boot into Windows 10 after Ubuntu was installed? Are you still working on a gparted screenshot?
Comment: yes it worked with windows 8, and then with windows 10 for years, sorry dont know how to get gparted screenshot
Comment: Start `gparted` and make sure it's looking at /dev/sda. Start `screenshot` and select current-window-only and hit Take Screenshot button. Save image. Edit answer and click the little graphic icon in the toolbar to include the image. Different question... did you do a `sudo update-grub`? Can you boot Windows now?
Comment: done sudo update-grub, will try windoes now
Comment: I think that you need a `Windows install/repair disc` to fix this problem. Later, you also need to add a `swap file` or `swap partition`.
Comment: stil not working, dont know how to get windows 10 install/repair disk, on boot menu there is recovery option on sd1, while windows 10 is on sd3, then when try to run it get message; fail to get disk 2 drive letter
Comment: You can download it from Microsoft. Google it for the location.
Comment: You also need a Ubuntu Live DVD (not USB).
Comment: The Windows 10 disc image is at https://www.microsoft.com/en-us/software-download/windows10ISO
Comment: i got windows 10 disk now and ubuntu 14.04, dont know what to do now. when try to boot from windows disk and get to install windows 10, get to point where says you started booting from disk, eject disk out, boot into windows and try disk again. dont know how to run windows disk from ubuntu. any more help please?
Comment: It looks like you installed `Boot Repair`, but did you ever run it? Go to the Unity dash and type `boot` and run it. To boot the Windows disc, you enter your BIOS boot menu... F12 or something similar... and select the DVD to boot. Then when the Windows install/repair menu comes up... follow repair.
Comment: tried repair, it did not work, stil same
Answer: it seems the OS is looking for a UUID that doesn't exist. Use Boot Repair tool to repair the issue,install it via terminal
sudo add-apt-repository ppa:yannubuntu/boot-repair
sudo apt-get update
sudo apt-get install -y boot-repair && boot-repair

Then if the simple click won't fix things,then you will post the Booting Summary for further help.
Comment: tried reboot and still nothing, same message error: no such device
Comment: thank you sentinel, i tried your instructions and its still same
Comment: can you post the booting summary from the same tools so as i could see the errors
Comment: you should try `sudo update-grub` fit,it won't work,then you are going to have to modify `boot/grub/grub.cfg` manual,excuse that command first,if it won't work then we shall proceed with the next setup
Comment: @ArduinoSentinel you don't modify grub.cfg by hand.
Comment: no,will have to change the UUIDs correspondly on `/etc/fstab`
Comment: @ArduinoSentinel as you can see from my earlier exchange, I've got the UUID info... and it's fine... and fstab has nothing to do with grub. The only thing that's missing from the fstab is swap.
Comment: oh!yes you are right,i didn't look at it well
Comment: sorry guys, what shall i do/try next?
Comment: did you try grub update?
Comment: tried, ill enter details
Comment: after `sudo update-grub` then reboot the system and see if error persist
Comment: @VULETICA did you ever find a solution for this? Currently I have to choose my OS by booting the respectove HDD via the BIOS boot menu.


Add outlet to circuit with dishwasher and disposal

Question: I currently have one 20A circuit feeding my dishwasher and garbage disposal. The garbage disposal is also switched. There's a 12AWG wire hard wired into the back of the dishwasher, and the source also goes to a switch by the sink. Then there's a 12/2 wire that goes from the switch to an outlet under the sink for the disposal.
I have a automatic faucet that requires power. I've been using batteries for a while, and I just recently got an AC adapter so that I don't have to change batteries so often. Now I just need to find a way to wire it.
My plan was to take the wire that's going into the dishwasher and feed it into the area under the sink (the dishwasher is immediately adjacent to the sink), then add a small junction box and receptacle and send the wire back to the dishwasher. All I plan to plug into this receptacle is that AC adapter which provides 1Amp at 12 volts DC, so a miniscule amount.
My questions are:

Can I do this?
Is it safe?
Is it up to code?
If not, is there a better option?

Edit to add more info requested in comments:

I'm in Utah.
The dishwasher's tag lists: Total Amps: 9.6.
The disposal is 1/3 HP. The label says 5.6 Amps.
Comment: What state are you in (so we can look up the code version) it sounds like the faucet is only a few watts.
Comment: How many watts/amps is the dishwasher, and how many HP is the disposal for that matter?
Comment: While you may only plan to plug the small DC adapter into this particular outlet, you must design it for anyone to plug anything into it at some point in the future, thus the questions above.
Comment: @EdBeal: I'm in Utah
Comment: @ThreePhaseEel: I updated the post with the amps.
Comment: Can you get a DC adapter that puts out the correct voltage and has a hole for a mounting screw on it...?
Comment: The code allows DW connection by plug and receptacle only in cabinet next to DW. After routing the cable that feeds the DW to the sink cabinet put a duplex there and get a cord for the DW.  Both halves of duplex will be used avoiding having an open receptacle for "equipment not fastened in place".
Answer: I'd use a screw-mount 12VDC adapter for this
Given your situation, and the fact that NEC 210.23(A)(2) limits the total amps of fastened-in-place equipment to 50% of the circuit ampacity if light fixtures or non-fastened-in-place equipment is also present on the circuit:

(2) Utilization Equipment Fastened in Place. The total rating
of utilization equipment fastened in place, other than luminaires, shall not exceed 50 percent of the branch-circuit ampere
rating where lighting units, cord-and-plug-connected utilization
equipment not fastened in place, or both, are also supplied.

, I'd replace the 12/2 from the switch down to the existing disposal receptacle with a 12/3 and wire the disposal receptacle as half-switched with the switched receptacle on top.  This lets you then use a screw-mounted 12VDC "wall-wart" of the type used in security alarm work to power the faucet; the mounting screw for said wall-wart replaces the screw holding the faceplate to the receptacle yoke, by the way.


Making popup windows in pygame with pgu

Question: I'm trying to add some gui elements (dialog boxes with buttons) to a game I'm writing with pygame. I looked around for a decent gui toolkit and ended up with pgu. Anyway, I'm trying to get it to pop up a dialog box, which it does (sort of), but it isn't closing.
Here's a simplified version of my code that just shows the behavior I care about:

import pygame, sys
from pgu import gui

screen = None
WIDTH = 640
HEIGHT = 480

def init_pygame():
    global screen
    pygame.display.init()
    screen = pygame.display.set_mode((WIDTH, HEIGHT), pygame.DOUBLEBUF)
    pygame.display.set_caption('Testing PGU')

class SimpleDialog(gui.Dialog):
    def __init__(self):
        title = gui.Label("Spam")
        main = gui.Container(width=20, height=20)
        # I patched PGU to use new style classes.
        super(SimpleDialog, self).__init__(title, main, width=40, height=40)

    def close(self, *args, **kwargs):
        print "closing"
        return super(SimpleDialog, self).close(*args, **kwargs)

def run():
    init_pygame()
    app = gui.App()

    dialog = SimpleDialog()
    app.init(dialog)

    app.paint(screen)
    pygame.display.flip()
    while True:
        app.paint(screen)
        pygame.display.flip()
        for event in pygame.event.get():
            if event.type == pygame.MOUSEBUTTONDOWN:
                if event.button == 3: # right mouse button
                    print "opening"
                    dialog.open()
                else:
                    app.event(event)
            elif event.type == pygame.QUIT:
                sys.exit()
            else:
                app.event(event)

if __name__=='__main__':
    run()

The behavior I'm seeing: A window opens with a full screen version of the dialog box. Nothing I do will close it, though right clicking will print "opening" on my console and left clicking the little red circle will get it to print "closing". It looks like the dialog box is using the whole background surface instead of a smaller one just for itself.
The behavior I'd like to see: A big black screen appears (I'll draw on it later) and when I right click on it, a little window opens up. When I left click the close button, the window goes away.
I suspect it has something to do with the fact that I'm not using a Desktop, but I don't want the whole game to live inside a gui.
Now, just to be explicit, the question: How do I modify my code to get from the behavior I'm seeing to the behavior I'd like to see? I'm open to using a different gui library if someone knows of something more recently maintained than pgu.
Answer: In case anyone else ever wants to do this, I found something that works: Create an empty container and call app.init() on it.
empty = gui.Container(width=WIDTH, height=HEIGHT)
gui.init(empty)

Answer: I had tried something similar to nmicahaels's answer to achieve a stand-alone dialog in my pygame app, but I kept getting a typeerror:

pygame_pgu-0.21-py3.6.egg\pgu\gui\surface.py", line 10, in subsurface
      r = pygame.Rect(r) TypeError: Argument must be rect style object

(r was being passed a None)
Removing the dialog height parameter fixed the issue for me. Here's the adapted code
import pygame, sys
from pgu import gui

# original author: user nmicahaels https://stackoverflow.com/questions/3302973/making-popup-windows-in-pygame-with-pgu

WIDTH = 640
HEIGHT = 480

def init_pygame():
    pygame.display.init()
    screen = pygame.display.set_mode((WIDTH, HEIGHT), pygame.DOUBLEBUF)
    pygame.display.set_caption('Testing PGU')
    return screen

class SimpleDialog(gui.Dialog):
    def __init__(self):
        title = gui.Label("Spam")
        main = gui.Container(width=20, height=20)
        # passing the 'height' parameter resulting in a typerror when paint was called
        super(SimpleDialog, self).__init__(title, main, width=40)  # , height=40)

    def close(self, *args, **kwargs):
        return super(SimpleDialog, self).close(*args, **kwargs)

def run():
    black = (0, 0, 0)
    screen = init_pygame()  # type: pygame.Surface
    refresh = pygame.display.update
    app = gui.App()

    dialog = SimpleDialog()
    # app.init(dialog)

    empty = gui.Container(width=WIDTH, height=HEIGHT)
    app.init(empty)

    app.paint(screen)
    pygame.display.flip()
    while True:
        screen.fill(black)
        app.paint(screen)
        pygame.display.flip()
        for event in pygame.event.get():
            if event.type == pygame.MOUSEBUTTONDOWN:
                if event.button == 3:  # right mouse button
                    dialog.open()
                else:
                    app.event(event)
            elif event.type == pygame.QUIT:
                sys.exit()
            else:
                app.event(event)
    refresh()

if __name__ == '__main__':
    run()

Making popup windows in pygame with pgu


vimrc reference python3 path through system command

Question: For the YouCompleteMe plugin, I would like to set the parameter g:ycm_path_to_python_interpreter in my vimrc to the path of the system python3 installation.
I am using let g:ycm_path_to_python_interpreter = system('which python3') however that is invalid, as the system(..) returns the string of the python3 path in a separate buffer it seems like. What I mean is that I see
/home/ubuntu/anaconda3/bin/python3

Press ENTER or type command to continue

when I :echo g:ycm_path_to_python_interpreter. I would expect just the path as string (i.e. /home/ubuntu/anaconda3/bin/python3). How can I do that?
Answer: The issue you're having is that system() will include the newline at the end of the command.
You can see that with the command:
:let g:ycm_path_to_python_interpreter

Which will show you:
g:ycm_path_to_python_interpreter     /home/ubuntu/anaconda3/bin/python3^@

(The ^@ at the end represents the newline character.)
To fix that, just use a call to trim() around the system() call.
let g:ycm_path_to_python_interpreter = trim(system('which python3'))


How can I launch apps on the screen that the mouse cursor is on?

Question: I have two screens connected to my computer. I want applications to start on the screen my mouse cursor is on. How can I set this?
Answer: I had wanted to do this myself.  Here is what I found:

Go to the CompizConfig Settings Manager (type compiz into the Dash).
Click on the Place Windows item in the Window Management section.
Select Use output device with pointer from the Multi Output Mode dropdown menu
Make sure you also click the checkbox that enables the Place Windows "plug-in"

You may run into trouble with the behavior remaining unchanged unchanged in certain cases.  This happened to me, but then I realized the reason:  Smart output mode will place a full-screen application on a monitor with a higher resolution by default, even if the "Use output device with pointer" option is selected.  To fix this problem, I changed the Placement Mode to Pointer.  I also found that the other available options, like Centered, also achieve the result of the window being placed on the screen currently containing the mouse cursor.  I recommend trying out each of the options to see which one you personally prefer (personally, I found that I like Centered the best).  It seems that Smart mode is trying to be "too smart" for what I want, I believe that it assumes that one wants bigger windows to be placed on the higher resolution screen regardless of what other options are selected, which is not necessarily what one may want in many cases.
I hope this helps!
Answer: By default the screen with mouse cursor is chosen. If not it can be chosen from display settings in Ubuntu settings.
Just do following steps:

Press Windows or Super button
Type display settings in box
After opening the display select the screen which you want to show cursor by default
That's all


Passive-Aggressive smoke detectors

Question: At about 3am this morning, one of my smoke detectors started to give off a chirp -- the 'maybe my battery is dead, maybe I'm dirty' chirp.
We managed to more or less sleep through it. By the time we got up in the morning, no more chirps. I'm sure it's waiting for us to be fast asleep again.
I've been through this before. These are all, by the way, wired detectors. it's their backup batteries that they complain of.
A few weeks ago, in the hopes of heading all of this off, I double-checked that all the batteries were recent, and I replaced all the remaining 10-year-old detectors with new ones.
UPDATE
3:30AM this morning. Beep *Beep*
Take a walk around. It is not evident which one is making the noise. Reach a conclusion. Pull one down. Back to bed.
A few moments later: Beep *Beep*
Out of bed again, but it refuses to beep while I'm standing there.
There are not alarm beeps, these are battery beeps.
Turn up the thermostats to daytime. Beeping stops.
Any suggestions?
Comment: What brand and model?  BRK is famous for this problem.
Answer: I had this problem for awhile with my recently installed hardwired detectors.  At first I started replacing the batteries figuring maybe the ones included in the box were old (who knows how long they were sitting on the shelf at the store?).  Then it kept happening even on some of the detectors that I had already replaced the battery with a fresh one so I stopped replacing the batteries but I would disconnect the hardwire, reset the alarm and re-attach it. That usually would stop it for awhile but a couple days later it kept happening, so I was repeating the procedure and I saw a little spider run across the inside of the alarm.  My theory is I have these little spiders were running around inside the alarm.  So now I just take them off the ceiling and blow real hard inside to try and get anything out that might be inside.
Answer: Watch the LED on the detector; the blink pattern can tell you what the problem is (at least on some detectors).
Answer: "Turn up the thermostats to daytime. Beeping stops"  -> Are you getting condensation inside of the alarm?
Comment: At 62 degrees? Though the beeping could be the detectors in the garage, which could well get colder.
Comment: @bmargulies, what else changes when you turn up the thermostat?.   It may not be 62 degreee inside the alarm if it is old a cold service (e.g. loft hatch door)
Comment: Most of the detectors are on the second floor ceilings, just below the attic. Some are near a hatch to the attic. Two are in the garage, which is only heated as a byproduct of the oil furnace.
Comment: Voltage drop in the battery due to the cold?
Answer: I had this SAME problem. It was driving everyone in the house crazy, not to mention a complete waste of batteries. I recently replaced them all with detectors that have 10 year sealed lithium batteries. Well worth it. Here is a link to the one's I bought:
http://www.amazon.com/Kidde-0910-10-Year-Lithium-Battery-Operated/dp/B0009RWK52
Matt
Answer: Test the detector. Both using the test button as well as an actual smoke test.

Passive-Aggressive smoke detectors


Does HVAC lineset need to be grounded?

Question: My HVAC contractor says the installation of the line set between the air handler and the condenser outside is complete but he has not grounded the lines.
Do HVAC copper pipes need to be grounded?
Comment: A 12 gauge ground wire is not going to be much help in a direct lightning strike. The primary purpose of grounding wires is to provide a safe path for electricity in the case of an appliance malfunction, not to handle 100,000 amps from lightning. I agree with @Ecnerwal below: if you're concerned about lightning you should install equipment appropriate to that purpose.
Comment: I see you removed the portion of your question dealing with lightning. What is it that you're worried about? Any electrical components such as the compressor motor will already be grounded.
Answer: Metal lines connected by metal fittings to metal enclosures which actually have power connected to them, and therefore also have grounds connected to them - so, they already are grounded.
Comment: And it has an electric motor in it to run the compressor, and that electric motor is connected to the electrical system of the house, and is grounded. So the lines are grounded. If you have lightning paranoia issues, install a lightning rod system, don't harass your HVAC installer.
Comment: my condenser is on the roof of the house
Comment: so if a lightening hits a refrigerant line, it will get grounded through the power supply cable, right ?

Does HVAC lineset need to be grounded?


Is there an IDE that works with CUDA on mac osx lion?

Question: I'm trying to learn Cuda and its very interesting but I'm having problems creating code without a bit of help from an IDE.  I know Java/Python but I'm unfamiliar with C/C++ so I have been using eclipse and Xcode to help me with commands and finding things(via code code completion).  I can't seem to get these options for CUDA?
I have seen examples and can build them find(nvcc is working) but without the IDE to help catch some of my mistakes I'm a bit lost editing the code in just a text editor.  I found a toolkit plugin for eclipse but although it seems to install I think its for a older build of eclipse because most of the options in the instructions do not match my version(Indigo). Nvidia has a plugin for Visual studio only on their site(I'd rather not install windows on my mac to use Cuda).
I'm sorry if this sounds bad but I'm curious to how people are developing cuda on Mac's.  I don't care what IDE I use as long as it helps me see the options and warn me if I have syntax issues,etc..(I'm not the best programmer but switching IDE's for me has just been a matter of finding out where things are so I'm really fine with any solution as long as it helps me as I'm learning).
Comment: There is a GTC 2012 session on 05/16/2012 titled Nsight IDE for Linux and Mac with the desription: Nsight IDE for Linux and Mac is an all-in-one development environment that lets you develop, debug and optimize CUDA code in an integrated UI environment. If you were waiting for an IDE on Linux and Mac then this session is for you. This session provides a detail usage walk-through of a fully CUDA aware source editor, build integration of the CUDA toolchain, graphical debugger for both CPU and GPU, and graphical profiler to enable performance optimization.
Comment: @GregSmith sounds interesting and I did read that nvidia would have big news for mac/linux developers at that conference.  Do you know if this product is already released? I can't seem to find it.
Answer: Nsight Eclipse Edition is available as a part of the CUDA Toolkit 5.0 (no additional download required).
Answer: Qt Creator!
You can read Qt Creator + CUDA + Linux for inspiration on how to setup the build environment on Mac OS X.
Comment: I use it all the time for non-graphics development. :)
Comment: I also recommend it. I've been using QT Creator for a year for R&D with CUDA apps that run in console.
Comment: I'm a n00b, sorry.  I always thought QT creator was for graphics related work, will it still be okay for using CUDA for general purpose programming?
Comment: @pQB Nice posts, by the way, too bad you stopped blogging. If you also recommend it, consider upvoting the answer :)
Comment: @karlphillip Thanks you. It seems in need a new reset ;).
Answer: You could think about using JCuda:
http://www.jcuda.de/
Comment: I'll check it out.  I saw that before but I thought it was just libraries to let Java talk to Cuda. I figured since Cuda is like C, its a good opportunity to learn C/C++.
Comment: Wait..sorry, I'm slow(its late), I think your suggesting I use Java to code Cuda?  Thats a option for sure, but I'd rather do it all in C right now since I can learn and plus all the examples in the books/tutorials seem to be in C.
Comment: JCuda is CUDA bindings in Java.  Looks like a 1:1 port to me.
Comment: Thanks Duffmo.  I'll study it a bit and keep this option open, but ideally I would like something that is in c/c++ as it'll allow me to follow the tutorials and example code alot more easily.  Good to know this option exists though.
Answer: There is XCode plug-in for CUDA development. I found it there. There is the main discussion on nvidia.com
Answer: Visual Studio Code + this extension:
https://github.com/gangliao/VS-Code-Cuda.
For me, Visual Studio Code is my favorite IDE for every language I found out there


How to use htaccess in nginx , datalife engine (cms) and

Question: I installed Datalife Engine (cms) on my nginx server , all thing was working great actually until
visiting html catagories from this cms that showed me 404 not found. I thought its for htaccess file and i didnt know that we cant use htaccess in directory like apache. so i checked the htaccess file and these are the converted (apache to nginx https://winginx.com /en/htaccesscodes):
<code>    # nginx configuration by winginx.com

index index.php;

location /page {
  rewrite ^/page/([0-9]+)(/?)$ /index.php?cstart=$1 break;
  rewrite ^/page,([0-9]+),([0-9]+),([0-9]+)-(.*).html$ /index.php?newsid=$3&news_page=$1&cstart=$2&seourl=$4 break;
  rewrite ^/page,([0-9]+),([0-9]+)-(.*).html$ /index.php?newsid=$2&news_page=$1&seourl=$3 break;
  rewrite ^/page,([0-9]+),([^/]+).html$ /index.php?do=static&page=$2&news_page=$1&seourl=$2 break;
}

location / {
  rewrite "^/([0-9]{4})/([0-9]{2})/([0-9]{2})/page,([0-9]+),([0-9]+),(.*).html$" /index.php?subaction=showfull&year=$1&month=$2&day=$3&news_page=$4&cstart=$5&news_name=$6&seourl=$6 break;
  rewrite "^/([0-9]{4})/([0-9]{2})/([0-9]{2})/page,([0-9]+),(.*).html$" /index.php?subaction=showfull&year=$1&month=$2&day=$3&news_page=$4&news_name=$5&seourl=$5 break;
  rewrite "^/([0-9]{4})/([0-9]{2})/([0-9]{2})/print:page,([0-9]+),(.*).html$" /index.php?mod=print&subaction=showfull&year=$1&month=$2&day=$3&news_page=$4&news_name=$5&seourl=$5 break;
  rewrite "^/([0-9]{4})/([0-9]{2})/([0-9]{2})/(.*).html$" /index.php?subaction=showfull&year=$1&month=$2&day=$3&news_name=$4&seourl=$4 break;
  rewrite ^/([^.]+)/page,([0-9]+),([0-9]+),([0-9]+)-(.*).html$ /index.php?newsid=$4&news_page=$2&cstart=$3&seourl=$5&seocat=$1 break;
  rewrite ^/([^.]+)/page,([0-9]+),([0-9]+)-(.*).html$ /index.php?newsid=$3&news_page=$2&seourl=$4&seocat=$1 break;
  rewrite ^/([^.]+)/print:page,([0-9]+),([0-9]+)-(.*).html$ /index.php?mod=print&news_page=$2&newsid=$3&seourl=$4&seocat=$1 break;
  rewrite ^/([^.]+)/([0-9]+)-(.*).html$ /index.php?newsid=$2&seourl=$3&seocat=$1 break;
  rewrite ^/([0-9]+)-(.*).html$ /index.php?newsid=$1&seourl=$2 break;
  rewrite "^/([0-9]{4})/([0-9]{2})/([0-9]{2})/*$" /index.php?year=$1&month=$2&day=$3 break;
  rewrite "^/([0-9]{4})/([0-9]{2})/([0-9]{2})/page/([0-9]+)/*$" /index.php?year=$1&month=$2&day=$3&cstart=$4 break;
  rewrite "^/([0-9]{4})/([0-9]{2})/*$" /index.php?year=$1&month=$2 break;
  rewrite "^/([0-9]{4})/([0-9]{2})/page/([0-9]+)/*$" /index.php?year=$1&month=$2&cstart=$3 break;
  rewrite "^/([0-9]{4})/*$" /index.php?year=$1 break;
  rewrite "^/([0-9]{4})/page/([0-9]+)/*$" /index.php?year=$1&cstart=$2 break;
  if (!-e $request_filename){
    rewrite ^/([^.]+)/page/([0-9]+)/*$ /index.php?do=cat&category=$1&cstart=$2 break;
  }
  rewrite ^/([^.]+)/?$ /index.php?do=cat&category=$1 break;
  if (!-e $request_filename){
    rewrite ^/([^.]+)/rss.xml$ /index.php?mod=rss&do=cat&category=$1 break;
  }
  if (!-e $request_filename){
    rewrite ^/([^/]+).html$ /index.php?do=static&page=$1&seourl=$1 break;
  }
}

location /print {
  rewrite ^/print:page,([0-9]+),([0-9]+)-(.*).html$ /index.php?mod=print&news_page=$1&newsid=$2&seourl=$3 break;
  rewrite ^/print:([^/]+).html$ /index.php?mod=print&do=static&page=$1&seourl=$1 break;
}

location /tags {
  rewrite ^/tags/([^/]*)/*$ /index.php?do=tags&tag=$1 break;
  rewrite ^/tags/([^/]*)/page/([0-9]+)/*$ /index.php?do=tags&tag=$1&cstart=$2 break;
}

location /xfsearch {
  rewrite ^/xfsearch/(.*)/page/([0-9]+)/*$ /index.php?do=xfsearch&xf=$1&cstart=$2 break;
  rewrite ^/xfsearch/(.*)/?$ /index.php?do=xfsearch&xf=$1 break;
}

location /user {
  rewrite ^/user/([^/]*)/rss.xml$ /index.php?mod=rss&subaction=allnews&user=$1 break;
  rewrite ^/user/([^/]*)/*$ /index.php?subaction=userinfo&user=$1 break;
  rewrite ^/user/([^/]*)/page/([0-9]+)/*$ /index.php?subaction=userinfo&user=$1&cstart=$2 break;
  rewrite ^/user/([^/]*)/news/*$ /index.php?subaction=allnews&user=$1 break;
  rewrite ^/user/([^/]*)/news/page/([0-9]+)/*$ /index.php?subaction=allnews&user=$1&cstart=$2 break;
  rewrite ^/user/([^/]*)/news/rss.xml/*$ /index.php?mod=rss&subaction=allnews&user=$1 break;
}

location /lastnews {
  rewrite ^/lastnews/*$ /index.php?do=lastnews break;
  rewrite ^/lastnews/page/([0-9]+)/*$ /index.php?do=lastnews&cstart=$1 break;
}

location /catalog {
  rewrite ^/catalog/([^/]*)/rss.xml$ /index.php?mod=rss&catalog=$1 break;
  rewrite ^/catalog/([^/]*)/*$ /index.php?catalog=$1 break;
  rewrite ^/catalog/([^/]*)/page/([0-9]+)/*$ /index.php?catalog=$1&cstart=$2 break;
}

location /newposts {
  rewrite ^/newposts/*$ /index.php?subaction=newposts break;
  rewrite ^/newposts/page/([0-9]+)/*$ /index.php?subaction=newposts&cstart=$1 break;
}

location /favorites {
  rewrite ^/favorites/*$ /index.php?do=favorites break;
  rewrite ^/favorites/page/([0-9]+)/*$ /index.php?do=favorites&cstart=$1 break;
}

location = /rules.html {
  rewrite ^(.*)$ /index.php?do=rules break;
}

location = /statistics.html {
  rewrite ^(.*)$ /index.php?do=stats break;
}

location = /addnews.html {
  rewrite ^(.*)$ /index.php?do=addnews break;
}

location = /rss.xml {
  rewrite ^(.*)$ /index.php?mod=rss break;
}

location = /sitemap.xml {
  rewrite ^(.*)$ /uploads/sitemap.xml break;
}
</code>
and this is my default config (default) :
<code>##
# You should look at the following URL's in order to grasp a solid understanding
# of Nginx configuration files in order to fully unleash the power of Nginx.
# https://www.nginx.com/resources/wiki/start/
# https://www.nginx.com/resources/wiki/start/topics/tutorials/config_pitfalls/
# https://wiki.debian.org/Nginx/DirectoryStructure
#
# In most cases, administrators will remove this file from sites-enabled/ and
# leave it as reference inside of sites-available where it will continue to be
# updated by the nginx packaging team.
#
# This file will automatically load configuration files provided by other
# applications, such as Drupal or Wordpress. These applications will be made
# available underneath a path with that package name, such as /drupal8.
#
# Please see /usr/share/doc/nginx-doc/examples/ for more detailed examples.
##

# Default server configuration
#
server {
location /phpmyadmin {
    root /usr/share/;
    index index.php;
    try_files $uri $uri/ =404;

location ~ ^/phpmyadmin/(doc|sql|setup)/ {
    deny all;
    }

location ~ /phpmyadmin/(.+\.php)$ {
    fastcgi_pass unix:/run/php/php7.4-fpm.sock;
    fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
    include fastcgi_params;
    include snippets/fastcgi-php.conf;
    }
}

    listen 80 default_server;
    listen [::]:80 default_server;

    # SSL configuration
    #
    # listen 443 ssl default_server;
    # listen [::]:443 ssl default_server;
    #
    # Note: You should disable gzip for SSL traffic.
    # See: https://bugs.debian.org/773332
    #
    # Read up on ssl_ciphers to ensure a secure configuration.
    # See: https://bugs.debian.org/765782
    #
    # Self signed certs generated by the ssl-cert package
    # Don't use them in a production server!
    #
    # include snippets/snakeoil.conf;

    root /var/www/html;

    # Add index.php to the list if you are using PHP
    index index.php index.html index.htm index.nginx-debian.html;

    server_name 192.168.1.107;

    location / {
        # First attempt to serve request as file, then
        # as directory, then fall back to displaying a 404.
        try_files $uri $uri/ /index.php?q=$uri&$args;
    }

    # pass PHP scripts to FastCGI server
    #
    location ~ \.php$ {
        include snippets/fastcgi-php.conf;
    #
    #   # With php-fpm (or other unix sockets):
         fastcgi_pass unix:/var/run/php/php7.4-fpm.sock;
    #   # With php-cgi (or other tcp sockets):
    #   fastcgi_pass 127.0.0.1:9000;
    }

    # deny access to .htaccess files, if Apache's document root
    # concurs with nginx's one
    #
    #location ~ /\.ht {
    #   deny all;
    #}

}
# Virtual Host configuration for example.com
#
# You can move that to a different file under sites-available/ and symlink that
# to sites-enabled/ to enable it.
#
#server {
#   listen 80;
#   listen [::]:80;
#
#   server_name example.com;
#
#   root /var/www/example.com;
#   index index.html;
#
#   location / {
#       try_files $uri $uri/ =404;
#   }
#}
</code>
how should i fix 404 not found and its possible to fix it with htaccess !?
so if its possible , how can i use this configuration without any error?!
photo :404 not found html pages
Answer: Try this
<code># nginx configuration

index index.php;

location /page {
  rewrite ^/page/([0-9]+)(/?)$ /index.php?cstart=$1 break;
  rewrite ^/page,([0-9]+),([0-9]+),([0-9]+)-(.*).html$ /index.php?newsid=$3&news_page=$1&cstart=$2&seourl=$4 break;
  rewrite ^/page,([0-9]+),([0-9]+)-(.*).html$ /index.php?newsid=$2&news_page=$1&seourl=$3 break;
  rewrite ^/page,([0-9]+),([^/]+).html$ /index.php?do=static&page=$2&news_page=$1&seourl=$2 break;
}

location / {
  rewrite "^/([0-9]{4})/([0-9]{2})/([0-9]{2})/page,([0-9]+),([0-9]+),(.*).html$" /index.php?subaction=showfull&year=$1&month=$2&day=$3&news_page=$4&cstart=$5&news_name=$6&seourl=$6 break;
  rewrite "^/([0-9]{4})/([0-9]{2})/([0-9]{2})/page,([0-9]+),(.*).html$" /index.php?subaction=showfull&year=$1&month=$2&day=$3&news_page=$4&news_name=$5&seourl=$5 break;
  rewrite "^/([0-9]{4})/([0-9]{2})/([0-9]{2})/print:page,([0-9]+),(.*).html$" /index.php?mod=print&subaction=showfull&year=$1&month=$2&day=$3&news_page=$4&news_name=$5&seourl=$5 break;
  rewrite "^/([0-9]{4})/([0-9]{2})/([0-9]{2})/(.*).html$" /index.php?subaction=showfull&year=$1&month=$2&day=$3&news_name=$4&seourl=$4 break;
  rewrite ^/([^.]+)/page,([0-9]+),([0-9]+),([0-9]+)-(.*).html$ /index.php?newsid=$4&news_page=$2&cstart=$3&seourl=$5&seocat=$1 break;
  rewrite ^/([^.]+)/page,([0-9]+),([0-9]+)-(.*).html$ /index.php?newsid=$3&news_page=$2&seourl=$4&seocat=$1 break;
  rewrite ^/([^.]+)/print:page,([0-9]+),([0-9]+)-(.*).html$ /index.php?mod=print&news_page=$2&newsid=$3&seourl=$4&seocat=$1 break;
  rewrite ^/([^.]+)/([0-9]+)-(.*).html$ /index.php?newsid=$2&seourl=$3&seocat=$1 break;
  rewrite ^/([0-9]+)-(.*).html$ /index.php?newsid=$1&seourl=$2 break;
  rewrite "^/([0-9]{4})/([0-9]{2})/([0-9]{2})/*$" /index.php?year=$1&month=$2&day=$3 break;
  rewrite "^/([0-9]{4})/([0-9]{2})/([0-9]{2})/page/([0-9]+)/*$" /index.php?year=$1&month=$2&day=$3&cstart=$4 break;
  rewrite "^/([0-9]{4})/([0-9]{2})/*$" /index.php?year=$1&month=$2 break;
  rewrite "^/([0-9]{4})/([0-9]{2})/page/([0-9]+)/*$" /index.php?year=$1&month=$2&cstart=$3 break;
  rewrite "^/([0-9]{4})/*$" /index.php?year=$1 break;
  rewrite "^/([0-9]{4})/page/([0-9]+)/*$" /index.php?year=$1&cstart=$2 break;
  if (!-e $request_filename){
    rewrite ^/([^.]+)/page/([0-9]+)/*$ /index.php?do=cat&category=$1&cstart=$2 break;
  }
  rewrite ^/([^.]+)/?$ /index.php?do=cat&category=$1 break;
  if (!-e $request_filename){
    rewrite ^/([^.]+)/rss.xml$ /index.php?mod=rss&do=cat&category=$1 break;
  }
  if (!-e $request_filename){
    rewrite ^/([^/]+).html$ /index.php?do=static&page=$1&seourl=$1 break;
  }
}

location /print {
  rewrite ^/print:page,([0-9]+),([0-9]+)-(.*).html$ /index.php?mod=print&news_page=$1&newsid=$2&seourl=$3 break;
  rewrite ^/print:([^/]+).html$ /index.php?mod=print&do=static&page=$1&seourl=$1 break;
}

location /tags {
  rewrite ^/tags/([^/]*)/*$ /index.php?do=tags&tag=$1 break;
  rewrite ^/tags/([^/]*)/page/([0-9]+)/*$ /index.php?do=tags&tag=$1&cstart=$2 break;
}

location /xfsearch {
  rewrite ^/xfsearch/(.*)/page/([0-9]+)/*$ /index.php?do=xfsearch&xf=$1&cstart=$2 break;
  rewrite ^/xfsearch/(.*)/?$ /index.php?do=xfsearch&xf=$1 break;
}

location /user {
  rewrite ^/user/([^/]*)/rss.xml$ /index.php?mod=rss&subaction=allnews&user=$1 break;
  rewrite ^/user/([^/]*)/*$ /index.php?subaction=userinfo&user=$1 break;
  rewrite ^/user/([^/]*)/page/([0-9]+)/*$ /index.php?subaction=userinfo&user=$1&cstart=$2 break;
  rewrite ^/user/([^/]*)/news/*$ /index.php?subaction=allnews&user=$1 break;
  rewrite ^/user/([^/]*)/news/page/([0-9]+)/*$ /index.php?subaction=allnews&user=$1&cstart=$2 break;
  rewrite ^/user/([^/]*)/news/rss.xml/*$ /index.php?mod=rss&subaction=allnews&user=$1 break;
}

location /lastnews {
  rewrite ^/lastnews/*$ /index.php?do=lastnews break;
  rewrite ^/lastnews/page/([0-9]+)/*$ /index.php?do=lastnews&cstart=$1 break;
}

location /catalog {
  rewrite ^/catalog/([^/]*)/rss.xml$ /index.php?mod=rss&catalog=$1 break;
  rewrite ^/catalog/([^/]*)/*$ /index.php?catalog=$1 break;
  rewrite ^/catalog/([^/]*)/page/([0-9]+)/*$ /index.php?catalog=$1&cstart=$2 break;
}

location /newposts {
  rewrite ^/newposts/*$ /index.php?subaction=newposts break;
  rewrite ^/newposts/page/([0-9]+)/*$ /index.php?subaction=newposts&cstart=$1 break;
}

location = /feedback.html {
  rewrite ^(.*)$ /index.php?do=feedback break;
}

location = /register.html {
  rewrite ^(.*)$ /index.php?do=register break;
}

location /favorites {
  rewrite ^/favorites/*$ /index.php?do=favorites break;
  rewrite ^/favorites/page/([0-9]+)/*$ /index.php?do=favorites&cstart=$1 break;
}

location = /rules.html {
  rewrite ^(.*)$ /index.php?do=rules break;
}

location = /statistics.html {
  rewrite ^(.*)$ /index.php?do=stats break;
}

location = /addnews.html {
  rewrite ^(.*)$ /index.php?do=addnews break;
}

location = /rss.xml {
  rewrite ^(.*)$ /index.php?mod=rss break;
}

location = /sitemap.xml {
  rewrite ^(.*)$ /uploads/sitemap.xml break;
}
</code>
Comment: How to use and add it in configuration?


Hyper-V PLINQ Virtual Machine Parallel issue

Question: I have a PLINQ query as such...
batch
.AsParallel()
.WithExecutionMode(ParallelExecutionMode.ForceParallelism)
.WithCancellation(cancellationToken);
.Select(i => new { instruction = i, accountKey = new AccountKey(i.x, i.y, i.z) })
.GroupBy(x => x.accountKey)
.ForAll(grouping =>
{
    foreach (var instructionBatch in grouping.OrderBy(i => i.instruction.FileRow).Select(i => i.instruction))
    {
        // High CPU method.
    }
});

In a batch, there can be 10,000 records. These make calls to the High CPU method which in turn is making calls out to web-services and saving info to databases.
On my physical 64bit pc i7-4770 CPU @ 3.40 GHz 16.0GB ram. The service where this code is run from fires up around 32 threads and sits around 150,000 - 200,000 KB memory usage.
On a Hyper-V test environment which is a 64 bit virtual machine E5-2630 v3 @2.40GHz it generates over 200 threads and memory hits nearly the 2gb limit.
Is there any reason why it is firing up so many threads and why memory is not being released on the virtual machine?
Do I need to use WithDegreeOfParallelism. If this process might be called simultaneously with 4 different batches (1 x 1 record, 1 x 100 records, 1 x 1000 and 1 x 10,000 for example) does this mean that when if I specify a WithDegreeOfParallelism the 4 batches will each fire with that number of threads, even the batch of 1 record?
Thanks for any assistance.
Answer: The TPL Parallel and PLINQ facilities are not good at handling IO. They tend to chose bad thread counts. The thread count employed by these methods is heuristically driven. I believe it is the thread-pool that contains this heuristic.
When IO is in play I highly recommend using WithDegreeOfParallelism. You can use Environment.ProcessorCount. If there is IO involved you probably want to slightly over-subscribe and add a constant amount of threads.
In PLINQ WithDegreeOfParallelism is an absolute amount. No more, no less. So yes, 4 concurrent queries result in 4 times the number of threads. I believe this problem does not happen with the built-in automatic thread count heuristic.
Consider using a fixed concurrency TaskScheduler for all concurrent queries.
Here's an experiment: Run that loop with a Thread.Sleep(1000000). You'll find tons of threads. Probably, one every 500ms. This is the thread-pools way of injecting threads when it thinks more are needed to avoid deadlocks and increase utilization. Totally inappropriate for IO.
Comment: Thanks for this @usr. If i use TPL parallel with MaxDegreeOfParallelism. it seems to limit the threads. However the other issue that i still see is whereby the memory constanly creeps up on the Hyper-V machine until it nears the 2GB limit. On the physical machine. You can see the memory being used and released around the 180,000 KB mark. Are you aware if this is an environment issue or is it something that i need to code for in the application?
Comment: I doubt it's an environment issue. Maybe different thread count or other IO latency profile. There was/is a bug with PLINQ in that it does not always release object references in a timely manner. That can keep garbage alive. Consider pushing wrapper objects through PLINQ that you manually clear. For example if you push a List call Clear on that list when you are done. The now almost empty list might stay around but not the original big list.
Answer: In the end whist running performance monitor I noticed that in the virtualized environment, the perf counter # of Exceps Thrown / Sec was showing a very high number. I followed http://blogs.msdn.com/b/spike/archive/2011/06/23/how-to-figure-out-what-exception-is-causing-a-high-number-in-of -exceps-thrown-sec-using-procdump-and-windbg.aspx and identified that an unhandled exception was being thrown whilst trying to connect to a mysql db. This was due to a firewall rule not being in place.
With regards to the parallelism. A second fire and forget task further down the High CPU method was being started to generate letters. This however did not
any exception/logging handling around it. This was where the error was being thrown. To overcome this I wrapped the await Task.Run in a try catch.


Prove, if $p$ is an odd prime: $1^{p-1} + 2^{p-1} + ... + (p-1)^{p-1}$ is congruent to -1 modulo p

Question: Prove, if $p$ is an odd prime:
$1^{p-1} + 2^{p-1} + ... + (p-1)^{p-1}$ is congruent to -1 modulo p.
I was going to try and show this by induction but I am having trouble with the base case that $1^{p-1}\equiv-1$ mod p. This makes me think that induction isn't the right way to go. Any help would be much appreciated. Thank you!
Comment: Fermat's Little theorem ? ...
Answer: Use Fermat's little theorem to prove that each term is congruent with $1$ modulo $p$. Then the whole sum is going to be congruent with $p-1=-1$ modulo $p$
Comment: @Math4Life It says $a^p\equiv a\pmod{p}$ dividing through $a$ you get $a^{p-1}\equiv 1\pmod{p}$
Comment: Doesn't the theorem say that $a^{p-1}\equiv a$ mod p though?...
Comment: Thank you. Since I will have 1+1+...+1 p-1 times it will give -1. I see it now I think. Thanks!


Undelete files in docker

Question: I have docker container and execute command
# rm -rf /etc/
rm: cannot remove '/etc/hosts': Device or resource busy
rm: cannot remove '/etc/resolv.conf': Device or resource busy
rm: cannot remove '/etc/hostname': Device or resource busy

How to recover deleted files and directories?
UPD: according to comment about https://unix.stackexchange.com/questions/91297/how-to-undelete-just-deleted-directory-with-rm-r-command
It doest not work for me beacause I have removed /etc/ directory and unable to install any additional software inside docker container.
Comment: http://unix.stackexchange.com/questions/91297/how-to-undelete-just-deleted-directory-with-rm-r-command
Comment: @Rao I have HDD not SSD
Comment: @Rao do you know how to migrate question on `unix.` ?
Comment: it appears only moderators can move a topic http://meta.unix.stackexchange.com/questions/882/how-to-migrate-questions-from-stackoverflow
Comment: @Rao do you know why people downvote?
Comment: http://stackoverflow.com/help/privileges/vote-down
Answer: Your not going to be able to recover them reliably without a backup which would most likely come in the form of a docker commit of the container or a snapshot of the underlying docker filesystem.
You can get the original /etc back from the image you started the container from though, which is at least better than where you are now.
docker run {your_image} tar -cf - /etc | docker exec {your_container_missing_etc} tar -xvf -

{your_image} being the image your container is running.
{your_container_missing_etc} being the id or name of the container missing /etc
Comment: Recreate container with loosing database was acceptable for me, so I did it, but thx for thoughts about recovering, I'll accept answer after week or two. Any way after this issue I had another one with write access from docker container solving which led to data corruption of data volume.

Undelete files in docker


Create list with for loop for incrementing IP address

Question: net = '192.168.1.'
host = []

for x in range(1,255):
    host.append(net+str(x))

I'm trying to generate a list of IPs in python with a for loop. Is there a more simplified way to write this? For instance a way to create the host list in line with the for loop, without having to pre-generate the host list?
Comment: If you're using python 3, the `ipaddress` module has ways to do this very succinctly.
Comment: I'm currently using python 2.
Answer: You may want to use a generator expression for this, if you intend to consume that exactly once.
addrs = (net + str(x) for x in range(1, 255))

Otherwise you might want something like this
def make_24_hosts(prefix):
    return (prefix + str(x) for x in range(1, 255))

Then you can do something like
>>> make_24_hosts('192.168.2.')
<generator object <genexpr> at 0x7f7b364930a0>
>>> g = make_24_hosts('192.168.2.')
>>> next(g)
'192.168.2.1'
>>> next(g)
'192.168.2.2'

Or iterate that generator using a for loop.
Answer: You can easily create a list in one line using a list comprehension :
net = "192.168.1."
hosts =  [ net + str(i) for i in range (1, 255)


Replacing two 3-way dimmer switches with two non-dimmer 3-way switches

Question: I had two Lutron 3-way dimmer switches for my bedroom lights. They looked something like this: https://www.amazon.com/Lutron-MAW603RH-WH-Electronics-Maestro-Dimmer/dp/B000BQMVXC
I replaced the bulbs w/Philips Hue smart lightbulbs, so I needed non-dimmer switches. I bought two simple 3-way rocker switches, and tried to wire them the same way. Unfortunately, on my first try, something was wrong. When the 1st switch was up, 2nd switch could turn the lights on and off. But when the 1st switch was down, lights were off and 2nd switch couldn't turn the lights back on.
So I tried moving wires around on the 2nd switch, and they behave as expected -- I can turn on/off the lights from both switches.
Does the mere fact that switches behave as expected show that I wired these two switches correctly? I ask because I'm a new homeowner, and am just paranoid that I may have mis-wired something that will burn down the house one day. Thank you!
(Ground wires are easy to identify, so you can assume I wired them correctly)
(There were no neutral wires on both my old and new switches)
Answer: You now have them correct, the one good thing with 3 wires connecting the 3 way switches you don't have to worry about burning things down they just don't work as you found out if they are wrong. Good job of figuring it out, you would not believe how many times I have been called to do what you just figured out.
Answer: Yes, it's fairly easy  to confuse the common terminal with the traveler terminals, becuase they are in a different position on every model of switch.
The rule of thumb is that the 2 travelers always go into the same cable, whereas the common will not, at least not at one end.
So for instance if one end all 3 wires (red white black) go into the same cable, and at the other end red and black go to the same cable and the other black comes from a different cable, red and black are your travelers.
I am a huge fan of marking travelers with yellow (or whatever) tape. There is no need to distinguish them from each other, but two wires tagged same-color in the same cable are a dead giveaway that they are travelers.
Comment: Sometimes it's not even the terminal that's a different color. Like, WTF guys?!?!
Answer: It sounds like you mixed up a common terminal with a traveler terminal
The misbehavior of your original, incorrect installation makes me think that you landed your common on a traveler terminal at one end (the end that was stopping the other switch from working), while one of the traveler wires was landed on the common terminal (on a 3 way switch, this is always the differently colored non-ground screw, don't pay attention to where on the switch it is).
As a result, that miswired switch stopped power from getting to the lights entirely when flipped to one position, as the common wire on that end was disconnected, while the two travellers were connected to each other and nothing else.  When you flipped the miswired switch to the other position, it then connected the common to the miswired traveler, allowing the other switch to control the light normally.  Now that it's fixed, there's no need to worry about the house burning down as a result of this particular oops.


How would you prove the series $\{\frac{1}{n^2+1}\}$ from 0 to infinity converges?

Question: I understand you would usually compare it with $\{\frac{1}{n^2}\}$ if $n=1$, which converges, but this series starts at $n = 0$ which is undefined for $\{\frac{1}{n^2}\}$ which is the start point of this series.
Comment: It doesn't matter what happens at $n=0$. We only care about large $n$, and for large $n$ we have $0<\frac{1}{n^2 + 1} < \frac{1}{n^2}$ so the series converges by comparison.
Answer: $$\sum_{n=0}^\infty \frac 1{n^2+1}=1+\sum_{n=1}^\infty \frac 1{n^2+1}$$
Adding one (or any finite number) cannot change whether the sum converges, so the comparison you mention with $\sum \frac 1{n^2}$ is sufficient to establish convergence.


How to fix door angle?

Question: What can I do to fix a door that is off-center? the top left is touching the frame. There's a wider gap on the top right than bottom right. We drilled it into frame so it got a little closer but it's still off. We couldn't figure out why it's off.
Comment: The first step is to use a level to see what is out of whack.
Comment: Is the door plumb?  Is the jamb plumb?
Answer: The doors (and windows) has to be plumb, level, and square. The door has to be parallel to the ground, vertical, and also not skewed (corners at 90 degrees / right angles).
Rough opening is called rough because it doesn't have to be perfectly plumb, level, and square.
To bring doors to be level and square you use shims and level. Also check for square by measuring corner-to-corner distances (e.g. top-left corner to bottom-right corner distance has to equal to top-right corner to bottom-left corner distances).

How to fix door angle?


array.includes(element) is giving false only in Angular 8(typescript)

Question: I am having an array as :
const ELEMENT_DATA: any[] =[
      {first:'1001', second:'john', third:'India'},
      {first:'1002', second:'Mack', third:'US'}]

Now, I want to check if my array is having an element named "first" or not. simply I want to get the names of elements only or just want to check if my array contains the required element or not in angular 8.
I have tried everything like array.includes(arr), array.find(arr=>....), array.some(...) etc. But for everything it's giving false value only. even if the element is present then also it's giving false only.
Comment: Do you want to check whether the array has an element with a key `first` or are you looking for a specific _value_ of `first`?
Comment: yes i am looking for  whether the array has an element with a key first
Answer:
Now, I want to check if my array is having an element named "first" or not

To check whether any of your array items has a key named first you should use some

const ELEMENT_DATA = [
      {first:'1001', second:'john', third:'India'},
      {first:'1002', second:'Mack', third:'US'}];

var result = ELEMENT_DATA.some(e => Object.keys(e).includes('first'));
console.log(result);
Comment: @CristianTraìna because if the value of `first` is falsey, then it will return false.
Comment: Why isn't `some(e => e.first)` enough?
Comment: hey thanks Jamiec and Cristian both the answers worked for me.
Answer: If i understood correctly, you want to check some element of array includes property "first". I could do it like this
const ELEMENT_DATA = [
      {first:'1001', second:'john', third:'India'},
      {first:'1002', second:'Mack', third:'US'}
];

var result = ELEMENT_DATA.some(e => e.hasOwnProperty('first'));

console.log(result);


php jquery ajax form submitted twice

Question: i had a form which uses jquery validation engine and ajax. and i'm using zend as the framework. but i had this weird case. from my test, i know that there are 3 cases which two of them are correct.
1. when i press enter after i fill out all of the input form, the form submitted normally (once)
2. when i'm in the last input box then i press tab to jump to the submit button and either press enter or click it, the form also submitted normally (once)
3. but after i fill out all of the form, then fill the captcha input box (the cursor is still in the captcha input box) and click the submit button straight out without move the cursor position to other element, then the form submitted twice
i don't understand why this happens. please help me to figure this out.
here is my html code from the :
<form id="kk_da" />
-- my form --
//here is the captcha

            security code*

                <img src="<?php print $this->app->base_url ?>lib/captcha.php" id="captcha">

                <a href="#" onclick="document.getElementById('captcha').src='<?php print $this->app->base_url ?>lib/captcha.php?'+Math.random();
                return false" id="change-image">Not readable? Change text.

            <div class="mkk_field mkk_field_important <?php print $_cap ? 'mkk_field_alert' : ''; ?>
                <?php if($this->error_captcha)print 'alert_captcha'; ?>">
                <?php //print $this->form->getElement('captcha'); ?>
    //the part above is described as follow
    //and it happens that the ajax[ajaxCaptchaCall] is the problem
    <input type="text" size="40" name="captcha" id="captcha"
class="validate[required,ajax[ajaxCaptchaCall]]" data-prompt-position="bottomRight"/>

            <input class="btn btn_blue" name="submit" type="submit" value="Buy" />
            <input type="hidden" name="process_marker" value="process_order" />
            <a href="<?php print $this->app->base_url ?>katalog/form" class="btn">back

</form>

and here is the javascript
> jQuery(document).ready(function()
{
    jQuery("#kk_da").validationEngine('attach',
    {
        onValidationComplete: function(form, status)
        {
            if (status == true)
            {
                var formData = jQuery('#kk_da').serialize();
                jQuery.ajax(
                {
                    url : '<?php print $this->app->base_url ?>katalog/checkout_process',
                    type : 'POST',
                    data :  formData,
                    beforeSend : function()
                    {
                        loading_pop();
                    }
                }).done(function(data)
                {
                    loading_done();

                    if (data== 'success')
                    {
                        window.location = '<?php print $this->app->base_url ?>katalog/success';
                    }
                }).fail(function()
                {
                    loading_done();
                }) ;
            }
        }
    });
});

UPDATE
it seems that i got the problem. it appears that the "ajax[ajaxCaptchaCall]" part is where the problem commence. when i erase that part, my form submitted normally. but then it makes my captcha doesn't work because it bypass it. how can i fix this part so the captcha works and the form submitted only once?
Answer: could it be that the attach is executed twice?
jQuery("#kk_da").validationEngine('attach', ....)
OD
try to set form.status = false after serializing it

php jquery ajax form submitted twice


Is is possible to use ag-grid-community with LitElements?

Question: Is is possible to use ag-grid-community with LitElements?
This is what I have tried, I am unable to initialize the ag-grid instance with the below code,
Console Error - ag-grid-community.auto.esm.js:45056 Uncaught TypeError: Failed to execute 'observe' on 'MutationObserver': parameter 1 is not of type 'Node'.
import { Grid } from 'ag-grid-community';

export class myComponent extends LitElement {
  static scopedElements = {
    'ag-grid': Grid
  };

  constructor() {
    super();
    this.columnDefs = [
      {headerName: "Make", field: "make"},
      {headerName: "Model", field: "model"},
      {headerName: "Price", field: "price"}
    ];

    this.rowData = [
      {make: "Toyota", model: "Celica", price: 35000},
      {make: "Ford", model: "Mondeo", price: 32000},
      {make: "Porsche", model: "Boxter", price: 72000}
    ];

    this.gridOptions = {
      columnDefs: this.columnDefs,
      rowData: this.rowData,
    };

    const eGridDiv = document.querySelector('#myGrid');
    new Grid(eGridDiv, this.gridOptions);
  }
  render() {
    return html`

          <ag-grid
            .gridOptions=${this.gridOptions}
          ></ag-grid>

    `;
  }
}

Answer: The constructor is too soon to get a reference to a rendered div. firstUpdated() would be a good place to do that. You also need to give the div an id ("myGrid") and you need to query for it in this.renderRoot rather than document.
ag-grid also needs styles loaded for it to work so I've added link tags in the returned template below. This could be improved by grabbing the styles directly and wrapping it with css tag function to provide to the component as static styles instead.

<my-element></my-element>
Answer: You must delete comments text from you code
 **specify the data** this.rowData = [

**let the grid know which columns and what data to use** this.gridOptions

also I think you fogot delete comma here:
.gridOptions=${this.gridOptions}

Comment: As it's currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer).


Deny items to be removed from inventory slots.

Question: Is there a way to disallow players to remove a certain item from a certain inventory slot. What I have tried is to add a curse of binding to the item as following:
<code>/replaceitem entity @p slot.hotbar.8 wool 1 0 {ench:[{id:10,lvl:1}]}
</code>
But as you may know, this only works for armor slots, not other inventory slots.
Comment: Can't you just spam that replaceitem command on a repeating command block?
Comment: @ppperry Then a player can remove it and use it for other purposes. Thank you for the suggestion though.
Answer: Killing items on the ground
setup a scoreboard :
<code>/scoreboard objective add Item dummy Item
</code>
Inside repeating active commandblocks (one that executes a command every thick) use these 3 commands:
<code>/replaceitem entity @p slot.hotbar.8 wool 1 0

/scoreboard players set @e[type=Item] Item 1 {Item:{id:wool,Count:1,Damage:8}}

/kill @e[type=Item,score_Item_min=1]
</code>
The first command adds the item to a specific spot on the hotbar just like you're command but without the curse.
The second assigns any wool blocks with damage value 8 to the scoreboard and the third command kills all items assigned to the scoreboard.
deleting items from unwanted inventory slots
If you want to delete the item from another slot in the hotbar use this inside first command inside a active repeating commandblock.
<code>/testfor @a {Inventory:[{Slot:0b,id:"minecraft:wool",Damage:8}]}
</code>
then add a comparator to that commandblock running into a normal command block executing:
<code>/replaceitem entity @p slot.hotbar.1 air
</code>
This you will have to setup for each slot in the inventory. Note that the slot number in the testfor is 1 less than the slot in the replaceitem (and note the b after it)


Deprecated Android drawing cache APIs

Question: I was going through the Android documentation, regarding deprecated drawing cache API's.We have extensive use of drawing cache APIs in our codebase. We are using it for snapshot of bitmaps and Views.
https://developer.android.com/reference/android/view/View#setDrawingCacheEnabled(boolean).
My doubts are mainly focused on points mentioned in the doc.
Doc says :  "For software-rendered snapshots of a small part of the View hierarchy or individual Views it is recommended to use Canvas approach"

What does "software-rendered snapshots" mean here ?

As by default Hardware acceleration is used from Android 4.0 on-wards. So all the views when attached to window would be having isHardwareacclerated() as true. Does "software-rendered snapshots" mean, all the views to which we have disabled Hardware acceleration ?

Doc also says : However these software-rendered usages are discouraged and have compatibility issues with hardware-only rendering features such as Config.HARDWARE bitmaps, real-time shadows, and outline clipping. For screenshots of the UI for feedback reports or unit testing the PixelCopy API is recommended.

Does this mean, we have to use PixelCopy APIs instead of canvas approach?

As per my understanding, PixelCopy APIs should be used incase of SurfaceView. Is this wrong ? Is it correct approach to use PixelCopy APIs for all the views ?

Note : Correct me If my understanding is wrong
Comment: you want to get code for screenshot without using `buildDrawingCache()`?
Comment: No, I have the code. I am just trying to understand the statements mentioned in doc,regarding deprecated APIs. Atleast for me they are difficult to understand. Any changes in my codebase, without proper understanding will screw up my feaures.
Answer: After exploring Android docs and working with samples related to above queries, I have found answers to my queries.

What does "software-rendered snapshots" mean here ?

Ans : Hardware acceleration is enabled by default if your Target API level is >=14. Here Views canvas use GPU for drawing. If we create canvas object in our code, It would be having isHardwareAccelerated() as false, which says draw would be performed by CPU. So "software-rendered snapshots" mean, objects which are rendered through CPU.
https://developer.android.com/guide/topics/graphics/hardware-accel

As by default Hardware acceleration is used from Android 4.0 on-wards. So all the views when attached to window would be having isHardwareacclerated() as true. Does "software-rendered snapshots" mean, all the views to which we have disabled Hardware acceleration ?

Ans: All the drawings happend through canvas object created in code.
3.Does this mean, we have to use PixelCopy APIs instead of canvas approach?
4. As per my understanding, PixelCopy APIs should be used incase of SurfaceView. Is this wrong ? Is it correct approach to use PixelCopy APIs for all the views ?
Ans : PixelCopy APIs have to be used on SurfaceView and Window objects. We cannot use PixelCopy APIs for all the views
https://developer.android.com/reference/android/view/PixelCopy

Deprecated Android drawing cache APIs


Setting src for image inside an li selected using .eq?

Question: I am trying to set the src of of the first image in the first li to the combination of two variables each containing a string.
I tried using:
    $( "li" ).eq(0, function(){
    $("img").eq(0).attr("src", eval(id+thumbnail));
   });

I also tried this:
$( ".mainlist li:nth-child(0)", function(){
$("img:eq( 0 )").attr("src", eval(id+thumbnail));
});

but it does not work.
Edit:
After a few hours of trying I got this to work:
$( "ul.mainlist li:nth-child(1)", function(){
$("img:eq( 0 )").attr("src", id+thumbnail);
});
});

however it only works on the first image of the page and not the first image inside the first li in the mainlist ul.
Comment: That's not what `eval()` is for. It's probably returning either 0 or true. How's `$("img").eq(0).attr("src", \`${id}${thumbnail}\` );` work for ya? PS: [Template literals are neat](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals)
Comment: yes! i just got **$("img:eq( 0 )").attr("src", id+thumbnail);** to work but it only works for the first image on the page
Comment: That's because of the eq(0), it throws away all but the first result/item.
Comment: so would there be any way to select the first image in the first li of the page and then set its src?
Answer: Your selector is not qualifying the img, so it does - as you found - select the first image on the page. To find the first image inside the li, use .find to find the img elements below the li element and .first to select the first image:
$('ul.mainlist li:nth-child(0)').find('img').first().attr("src", id+thumbnail);

Comment: still affecting the first image on the page :(
Comment: @Jerick120 sorry, hadn't noticed how you were calling the function, so `$(this)` wasn't pointing to the actual `li` element. Are you trying to do this on an event? If not, my edited code should work.


Getting list of server instances installed reliably

Question: I am using following code to get a list of server instances installed.
Dim sqldatasourceenumerator1 As SqlDataSourceEnumerator = SqlDataSourceEnumerator.Instance
    datatable1 = sqldatasourceenumerator1.GetDataSources()

Sometimes this code works fine but most of the times it gets lost and system becomes unresponsive.
Could anyone advise me some alternative code that is reliable in all conditions?
Thanks
Answer: You could check the registry, for example you can try reading this registry key:
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Microsoft SQL Server\Instance Names\SQL

32 bit instances on a 64 bit OS should be listed under:
HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\Microsoft SQL Server\Instance Names\SQL

Here is a c# code snippet to get this info for 64 bit instances on 64 bit Windows:
RegistryKey baseKey = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry64);
RegistryKey key = baseKey.OpenSubKey(@"SOFTWARE\Microsoft\Microsoft SQL Server\Instance Names\SQL");

foreach (string s in key.GetValueNames())
{
   ...
}

key.Close();
baseKey.Close();


How to add USB boot option to grub.cfg in Ubuntu 20.04?

Question: I have confirmed that the USB has a proper bootable Ubuntu ISO on it with the file command.
USB is plugged in the laptop.
The grub menu does get shown on its own at the startup.
Problem is that there is no option to boot from USB.
Now I want to edit grub.cfg such that it contains USB boot options.
What do I do from here?
Also, /boot/grub/grub.cfg:
#
# DO NOT EDIT THIS FILE
#
# It is automatically generated by grub-mkconfig using templates
# from /etc/grub.d and settings from /etc/default/grub
#

### BEGIN /etc/grub.d/00_header ###
if [ -s $prefix/grubenv ]; then
  set have_grubenv=true
  load_env
fi
if [ "${initrdfail}" = 2 ]; then
   set initrdfail=
elif [ "${initrdfail}" = 1 ]; then
   set next_entry="${prev_entry}"
   set prev_entry=
   save_env prev_entry
   if [ "${next_entry}" ]; then
      set initrdfail=2
   fi
fi
if [ "${next_entry}" ] ; then
   set default="${next_entry}"
   set next_entry=
   save_env next_entry
   set boot_once=true
else
   set default="0"
fi

if [ x"${feature_menuentry_id}" = xy ]; then
  menuentry_id_option="--id"
else
  menuentry_id_option=""
fi

export menuentry_id_option

if [ "${prev_saved_entry}" ]; then
  set saved_entry="${prev_saved_entry}"
  save_env saved_entry
  set prev_saved_entry=
  save_env prev_saved_entry
  set boot_once=true
fi

function savedefault {
  if [ -z "${boot_once}" ]; then
    saved_entry="${chosen}"
    save_env saved_entry
  fi
}
function initrdfail {
    if [ -n "${have_grubenv}" ]; then if [ -n "${partuuid}" ]; then
      if [ -z "${initrdfail}" ]; then
        set initrdfail=1
        if [ -n "${boot_once}" ]; then
          set prev_entry="${default}"
          save_env prev_entry
        fi
      fi
      save_env initrdfail
    fi; fi
}
function recordfail {
  set recordfail=1
  if [ -n "${have_grubenv}" ]; then if [ -z "${boot_once}" ]; then save_env recordfail; fi; fi
}
function load_video {
  if [ x$feature_all_video_module = xy ]; then
    insmod all_video
  else
    insmod efi_gop
    insmod efi_uga
    insmod ieee1275_fb
    insmod vbe
    insmod vga
    insmod video_bochs
    insmod video_cirrus
  fi
}

if [ x$feature_default_font_path = xy ] ; then
   font=unicode
else
insmod part_gpt
insmod ext2
set root='hd0,gpt2'
if [ x$feature_platform_search_hint = xy ]; then
  search --no-floppy --fs-uuid --set=root --hint-bios=hd0,gpt2 --hint-efi=hd0,gpt2 --hint-baremetal=ahci0,gpt2  e860e8f0-912f-4874-8f0f-97e343371f12
else
  search --no-floppy --fs-uuid --set=root e860e8f0-912f-4874-8f0f-97e343371f12
fi
    font="/usr/share/grub/unicode.pf2"
fi

if loadfont $font ; then
  set gfxmode=auto
  load_video
  insmod gfxterm
  set locale_dir=$prefix/locale
  set lang=en_IN
  insmod gettext
fi
terminal_output gfxterm
if [ "${recordfail}" = 1 ] ; then
  set timeout=30
else
  if [ x$feature_timeout_style = xy ] ; then
    set timeout_style=menu
    set timeout=5
  # Fallback normal timeout code in case the timeout_style feature is
  # unavailable.
  else
    set timeout=5
  fi
fi
### END /etc/grub.d/00_header ###

### BEGIN /etc/grub.d/05_debian_theme ###
set menu_color_normal=white/black
set menu_color_highlight=black/light-gray
### END /etc/grub.d/05_debian_theme ###

### BEGIN /etc/grub.d/10_linux ###
function gfxmode {
    set gfxpayload="${1}"
    if [ "${1}" = "keep" ]; then
        set vt_handoff=vt.handoff=7
    else
        set vt_handoff=
    fi
}
if [ "${recordfail}" != 1 ]; then
  if [ -e ${prefix}/gfxblacklist.txt ]; then
    if hwmatch ${prefix}/gfxblacklist.txt 3; then
      if [ ${match} = 0 ]; then
        set linux_gfx_mode=keep
      else
        set linux_gfx_mode=text
      fi
    else
      set linux_gfx_mode=text
    fi
  else
    set linux_gfx_mode=keep
  fi
else
  set linux_gfx_mode=text
fi
export linux_gfx_mode
menuentry 'Ubuntu' --class ubuntu --class gnu-linux --class gnu --class os $menuentry_id_option 'gnulinux-simple-e860e8f0-912f-4874-8f0f-97e343371f12' {
    recordfail
    load_video
    gfxmode $linux_gfx_mode
    insmod gzio
    if [ x$grub_platform = xxen ]; then insmod xzio; insmod lzopio; fi
    insmod part_gpt
    insmod ext2
    set root='hd0,gpt2'
    if [ x$feature_platform_search_hint = xy ]; then
      search --no-floppy --fs-uuid --set=root --hint-bios=hd0,gpt2 --hint-efi=hd0,gpt2 --hint-baremetal=ahci0,gpt2  e860e8f0-912f-4874-8f0f-97e343371f12
    else
      search --no-floppy --fs-uuid --set=root e860e8f0-912f-4874-8f0f-97e343371f12
    fi
    linux   /boot/vmlinuz-5.13.0-27-generic root=UUID=e860e8f0-912f-4874-8f0f-97e343371f12 ro  quiet splash $vt_handoff
    initrd  /boot/initrd.img-5.13.0-27-generic
}
submenu 'Advanced options for Ubuntu' $menuentry_id_option 'gnulinux-advanced-e860e8f0-912f-4874-8f0f-97e343371f12' {
    menuentry 'Ubuntu, with Linux 5.13.0-27-generic' --class ubuntu --class gnu-linux --class gnu --class os $menuentry_id_option 'gnulinux-5.13.0-27-generic-advanced-e860e8f0-912f-4874-8f0f-97e343371f12' {
        recordfail
        load_video
        gfxmode $linux_gfx_mode
        insmod gzio
        if [ x$grub_platform = xxen ]; then insmod xzio; insmod lzopio; fi
        insmod part_gpt
        insmod ext2
        set root='hd0,gpt2'
        if [ x$feature_platform_search_hint = xy ]; then
          search --no-floppy --fs-uuid --set=root --hint-bios=hd0,gpt2 --hint-efi=hd0,gpt2 --hint-baremetal=ahci0,gpt2  e860e8f0-912f-4874-8f0f-97e343371f12
        else
          search --no-floppy --fs-uuid --set=root e860e8f0-912f-4874-8f0f-97e343371f12
        fi
        echo    'Loading Linux 5.13.0-27-generic ...'
        linux   /boot/vmlinuz-5.13.0-27-generic root=UUID=e860e8f0-912f-4874-8f0f-97e343371f12 ro  quiet splash $vt_handoff
        echo    'Loading initial ramdisk ...'
        initrd  /boot/initrd.img-5.13.0-27-generic
    }
    menuentry 'Ubuntu, with Linux 5.13.0-27-generic (recovery mode)' --class ubuntu --class gnu-linux --class gnu --class os $menuentry_id_option 'gnulinux-5.13.0-27-generic-recovery-e860e8f0-912f-4874-8f0f-97e343371f12' {
        recordfail
        load_video
        insmod gzio
        if [ x$grub_platform = xxen ]; then insmod xzio; insmod lzopio; fi
        insmod part_gpt
        insmod ext2
        set root='hd0,gpt2'
        if [ x$feature_platform_search_hint = xy ]; then
          search --no-floppy --fs-uuid --set=root --hint-bios=hd0,gpt2 --hint-efi=hd0,gpt2 --hint-baremetal=ahci0,gpt2  e860e8f0-912f-4874-8f0f-97e343371f12
        else
          search --no-floppy --fs-uuid --set=root e860e8f0-912f-4874-8f0f-97e343371f12
        fi
        echo    'Loading Linux 5.13.0-27-generic ...'
        linux   /boot/vmlinuz-5.13.0-27-generic root=UUID=e860e8f0-912f-4874-8f0f-97e343371f12 ro recovery nomodeset dis_ucode_ldr
        echo    'Loading initial ramdisk ...'
        initrd  /boot/initrd.img-5.13.0-27-generic
    }
    menuentry 'Ubuntu, with Linux 5.11.0-37-generic' --class ubuntu --class gnu-linux --class gnu --class os $menuentry_id_option 'gnulinux-5.11.0-37-generic-advanced-e860e8f0-912f-4874-8f0f-97e343371f12' {
        recordfail
        load_video
        gfxmode $linux_gfx_mode
        insmod gzio
        if [ x$grub_platform = xxen ]; then insmod xzio; insmod lzopio; fi
        insmod part_gpt
        insmod ext2
        set root='hd0,gpt2'
        if [ x$feature_platform_search_hint = xy ]; then
          search --no-floppy --fs-uuid --set=root --hint-bios=hd0,gpt2 --hint-efi=hd0,gpt2 --hint-baremetal=ahci0,gpt2  e860e8f0-912f-4874-8f0f-97e343371f12
        else
          search --no-floppy --fs-uuid --set=root e860e8f0-912f-4874-8f0f-97e343371f12
        fi
        echo    'Loading Linux 5.11.0-37-generic ...'
        linux   /boot/vmlinuz-5.11.0-37-generic root=UUID=e860e8f0-912f-4874-8f0f-97e343371f12 ro  quiet splash $vt_handoff
        echo    'Loading initial ramdisk ...'
        initrd  /boot/initrd.img-5.11.0-37-generic
    }
    menuentry 'Ubuntu, with Linux 5.11.0-37-generic (recovery mode)' --class ubuntu --class gnu-linux --class gnu --class os $menuentry_id_option 'gnulinux-5.11.0-37-generic-recovery-e860e8f0-912f-4874-8f0f-97e343371f12' {
        recordfail
        load_video
        insmod gzio
        if [ x$grub_platform = xxen ]; then insmod xzio; insmod lzopio; fi
        insmod part_gpt
        insmod ext2
        set root='hd0,gpt2'
        if [ x$feature_platform_search_hint = xy ]; then
          search --no-floppy --fs-uuid --set=root --hint-bios=hd0,gpt2 --hint-efi=hd0,gpt2 --hint-baremetal=ahci0,gpt2  e860e8f0-912f-4874-8f0f-97e343371f12
        else
          search --no-floppy --fs-uuid --set=root e860e8f0-912f-4874-8f0f-97e343371f12
        fi
        echo    'Loading Linux 5.11.0-37-generic ...'
        linux   /boot/vmlinuz-5.11.0-37-generic root=UUID=e860e8f0-912f-4874-8f0f-97e343371f12 ro recovery nomodeset dis_ucode_ldr
        echo    'Loading initial ramdisk ...'
        initrd  /boot/initrd.img-5.11.0-37-generic
    }
    menuentry 'Ubuntu, with Linux 5.8.0-43-generic' --class ubuntu --class gnu-linux --class gnu --class os $menuentry_id_option 'gnulinux-5.8.0-43-generic-advanced-e860e8f0-912f-4874-8f0f-97e343371f12' {
        recordfail
        load_video
        gfxmode $linux_gfx_mode
        insmod gzio
        if [ x$grub_platform = xxen ]; then insmod xzio; insmod lzopio; fi
        insmod part_gpt
        insmod ext2
        set root='hd0,gpt2'
        if [ x$feature_platform_search_hint = xy ]; then
          search --no-floppy --fs-uuid --set=root --hint-bios=hd0,gpt2 --hint-efi=hd0,gpt2 --hint-baremetal=ahci0,gpt2  e860e8f0-912f-4874-8f0f-97e343371f12
        else
          search --no-floppy --fs-uuid --set=root e860e8f0-912f-4874-8f0f-97e343371f12
        fi
        echo    'Loading Linux 5.8.0-43-generic ...'
        linux   /boot/vmlinuz-5.8.0-43-generic root=UUID=e860e8f0-912f-4874-8f0f-97e343371f12 ro  quiet splash $vt_handoff
        echo    'Loading initial ramdisk ...'
        initrd  /boot/initrd.img-5.8.0-43-generic
    }
    menuentry 'Ubuntu, with Linux 5.8.0-43-generic (recovery mode)' --class ubuntu --class gnu-linux --class gnu --class os $menuentry_id_option 'gnulinux-5.8.0-43-generic-recovery-e860e8f0-912f-4874-8f0f-97e343371f12' {
        recordfail
        load_video
        insmod gzio
        if [ x$grub_platform = xxen ]; then insmod xzio; insmod lzopio; fi
        insmod part_gpt
        insmod ext2
        set root='hd0,gpt2'
        if [ x$feature_platform_search_hint = xy ]; then
          search --no-floppy --fs-uuid --set=root --hint-bios=hd0,gpt2 --hint-efi=hd0,gpt2 --hint-baremetal=ahci0,gpt2  e860e8f0-912f-4874-8f0f-97e343371f12
        else
          search --no-floppy --fs-uuid --set=root e860e8f0-912f-4874-8f0f-97e343371f12
        fi
        echo    'Loading Linux 5.8.0-43-generic ...'
        linux   /boot/vmlinuz-5.8.0-43-generic root=UUID=e860e8f0-912f-4874-8f0f-97e343371f12 ro recovery nomodeset dis_ucode_ldr
        echo    'Loading initial ramdisk ...'
        initrd  /boot/initrd.img-5.8.0-43-generic
    }
}

### END /etc/grub.d/10_linux ###

### BEGIN /etc/grub.d/10_linux_zfs ###
### END /etc/grub.d/10_linux_zfs ###

### BEGIN /etc/grub.d/20_linux_xen ###

### END /etc/grub.d/20_linux_xen ###

### BEGIN /etc/grub.d/20_memtest86+ ###
### END /etc/grub.d/20_memtest86+ ###

### BEGIN /etc/grub.d/30_os-prober ###
### END /etc/grub.d/30_os-prober ###

### BEGIN /etc/grub.d/30_uefi-firmware ###
menuentry 'UEFI Firmware Settings' $menuentry_id_option 'uefi-firmware' {
    fwsetup
}
### END /etc/grub.d/30_uefi-firmware ###

### BEGIN /etc/grub.d/40_custom ###
# This file provides an easy way to add custom menu entries.  Simply type the
# menu entries you want to add after this comment.  Be careful not to change
# the 'exec tail' line above.
### END /etc/grub.d/40_custom ###

### BEGIN /etc/grub.d/41_custom ###
if [ -f  ${config_directory}/custom.cfg ]; then
  source ${config_directory}/custom.cfg
elif [ -z "${config_directory}" -a -f  $prefix/custom.cfg ]; then
  source $prefix/custom.cfg;
fi
### END /etc/grub.d/41_custom ###

Comment: @Aquarius_Girl The grub.cfg file seems ok. what the iso and the flash tool are you using? . please provide us output of `cat /boot/grub/grubenv`.
Comment: Do **not ** use the Grub customizer to change anything - I might brick your bootloader...
Check if  GRUB_DISABLE_OS_PROBER=false in `etc/default/grub` is not commented out
Comment: Not sure if grub can boot installer correctly. You normally boot from UEFI/BIOS boot menu. Issues are most often incorrect flash drive either USB port, flash drive itself, download of ISO not verified or tool used to create bootable flash drive. Some systems also require UEFI setting to allow full USB support or allow USB boot, especially if UEFI Secure Boot is on. https://help.ubuntu.com/community/Installation/iso2usb
Comment: @kanehekili well, that option `GRUB_DISABLE_OS_PROBER` isn't there at all.
Comment: Why don't you just boot directly from USB? I can change it in UEFI or press F11 on my HP ENVY laptop. Then you don't need to change anything. Isn't that much easier?
Comment: @JoepieEs I want to directly boot from USB but don't know how to do it. Please write an answer.
Comment: Please specify your hardware. Motherboard make and model or laptop make and model. Then I will search for it.
Answer: When you enter the black GRUB screen, press C or the escape key (ESC) to access command prompt, then enter the following commands (which should make it so that you can boot):
grub> root (hd0,0)   # first harddrive, first partition
grub> find /[tab]    # type the slash then press [tab], and it will try to list files on this partition
Error 17: Cannot mount selected partition   # Oops no file system here
grub> root (hd0,1)   # first harddrive, second partition
grub> find /[tab]
Possible files are: lost+found var etc media ...   # That was my hard drive with my linux install
grub> root (hd1,0)   # second hard drive usually is the USB drive if you have only one internal drive
grub> find /[tab]
Possible files are: ldlinux.sys mydoc myfile mystick syslinux.cfg  # Bingo, that's the USB stick

Now, boot the drive by entering the following commands:
chainloader +1
boot

For convenience, add these commands to your GRUB configuration (usually in /boot/grub/menu.lst):
# to boot from a USB device
title    Boot USB drive
root     (hd1,0)
chainloader +1
boot

Source: https://help.ubuntu.com/community/BootFromUSB#:~:text=The%20easiest%20way%20to%20boot,key%20to%20enter%20command%20mode.
Answer: In a nutshell: that's the BIOS's job, not GRUB's.
Usually, computers will have a method to go to the BIOS (or UEFI) setup page, for example, ThinkVantage on ThinkPads. On the BIOS setup page, there will be boot order change settings. Place USB HDD onto the top, then reboot the computer.
Use the answer above if there is no BIOS setup page (rare but not zero), or your computer cannot detect USB bootable disks. Never modify your GRUB config file to do so.
If you can provide the actual model of your computer, I can tell you the actual steps. Otherwise, you can also check the manuals about how to change the boot order.


Spring, rendering list with  gives error

Question: HTML:
<select name="myList" id="myList" style="width: 170px;">
    <option value="">All Items</option>
    <c:forEach var="item" items="${items}">
        <c:if test="${item != 'N/A'}">
            <option value="${item}">${item}</option>
        </c:if>
    </c:forEach>
</select>

Controller:
...
List<Item> myItemList = itemDaoImpl.getAll();
...
view.addObject("items", myItemList);

That is just the related part of my controller. And it gives me "error[object Object]" javascript error when I load my page and internal server error on controller call. I do not understand the reason, could you please guide me ?
Comment: Because item(guess model class) is object here, try it with what the `Item` class member(s) say `item.itemName` or `item.itemId`. Post your `Item` class so you can get detailed answer.
Comment: try model.addAttribute("item",myItemList)
Answer: Have look at the sample of iteration,
<c:forEach var="item" items="${items}">
    <c:if test="${item.itemName !='N/A'}">
       <option value="${item.itemId}">${item.itemName}</option>
    </c:if>
</c:forEach>

You must replace (itemName, itemId) it with your class member(s).
Cheers..!
Comment: Thank you very much Vinoth! =) I've missed that part out.

Spring, rendering list with  gives error