How to remove padding between AlertDialog and title/text with Compose

Question: Using compose, I want to create something like this :

Problem is using compose AlertDialog I only achieve to get this :

There is a padding between the AlertDialog border and the title that can not be removed. How to remove it using Compose ?
Using Modifier.padding(all = 0.dp) doesn't work. I tried it at every level.
Answer: Properties "title" and "text" are wrapped with AlertDialogBaselineLayout that is adding padding. You can't remove it.
I have made a custom Composable that is acting as an AlertDialog and doesn't use AlertDialogBaselineLayout.
You can copy/paste it and edit it according to your needs :
NoPaddingAlertDialog :
@Composable
fun NoPaddingAlertDialog(
    onDismissRequest: () -> Unit,
    modifier: Modifier = Modifier,
    title: @Composable (() -> Unit)? = null,
    text: @Composable (() -> Unit)? = null,
    confirmButton: @Composable () -> Unit,
    dismissButton: @Composable (() -> Unit)? = null,
    shape: Shape = MaterialTheme.shapes.medium,
    backgroundColor: Color = MaterialTheme.colors.surface,
    contentColor: Color = contentColorFor(backgroundColor),
    properties: DialogProperties = DialogProperties()
) {
    Dialog(
        onDismissRequest = onDismissRequest,
        properties = properties
    ) {
        Surface(
            modifier = modifier,
            shape = shape,
            color = backgroundColor,
            contentColor = contentColor
        ) {
            Column(
                modifier = Modifier
                    .fillMaxWidth()
            ) {
                title?.let {
                    CompositionLocalProvider(LocalContentAlpha provides ContentAlpha.high) {
                        val textStyle = MaterialTheme.typography.subtitle1
                        ProvideTextStyle(textStyle, it)
                    }
                }
                text?.let {
                    CompositionLocalProvider(LocalContentAlpha provides ContentAlpha.high) {
                        val textStyle = MaterialTheme.typography.subtitle1
                        ProvideTextStyle(textStyle, it)
                    }
                }
                Box(
                    Modifier
                        .fillMaxWidth()
                        .padding(all = 8.dp)
                ) {
                    Row(
                        horizontalArrangement = Arrangement.End,
                        modifier = Modifier.fillMaxWidth()
                    ) {
                        dismissButton?.invoke()
                        confirmButton()
                    }
                }
            }
        }
    }
}

You can then easily use it this way :
@Composable
fun MyCustomAlertDialog(openDialog: MutableState<Boolean> = mutableStateOf(true)) {
    if (openDialog.value) {
        NoPaddingAlertDialog(
            title = {
                Surface(
                    color = Color.Blue,
                    contentColor = Color.White,
                    modifier = Modifier
                        .fillMaxWidth()

                ) {
                    Text(
                        text = " Popup Title",
                        textAlign = TextAlign.Center,
                        modifier = Modifier
                            .fillMaxWidth()
                            .padding(horizontal = 8.dp, vertical = 16.dp),
                    )
                }
            },
            text = {
                Column(Modifier.fillMaxWidth()) {
                    OutlinedTextField(
                        modifier = Modifier
                            .align(Alignment.CenterHorizontally)
                            .padding(horizontal = 8.dp, vertical = 16.dp)
                            .fillMaxWidth(),
                        value = "Alert Dialog content ...",
                        onValueChange = { },
                        label = { Text(text = "Content") },
                    )
                }
            },
            onDismissRequest = { /*TODO*/ },
            confirmButton = {
                PopupButton(title = "Ok", setShow = {
                    openDialog.value = false
                })
            },
            dismissButton = {
                PopupButton(
                    title = "Cancel",
                    setShow = {
                        openDialog.value = false
                    }
                )
            }
        )
    }
}

And get this :
Answer: You can use a Dialog() instead of AlertDialog(). It allows you to pass in a composable as the content parameter, so you can set whatever padding you want. Just don't forget to set the background color in the root composable of the content, since it is transparent by default.
Comment: This makes it way easier. Thanks


Difference between aio_write() and O_NONBLOCK write()

Question: What is the difference between aio_write() and O_NONBLOCK write()?
Also, I use write() to a text file using file descriptor using the O_NONBLOCK function and compare the performance with the aio_write() by putting a timer before and after the function.
It seems that the write() function would take longer time to write to file when the length of the string increases but aio_write() still maintain around the same time.
Why is it so? What is the difference between NONBLOCK and asynchronous?
Thanks
Answer: With the O_NONBLOCK write(), the write() call will accept (that is, copy to an in-kernel buffer) all, some, or none of the data you passed to it (if some bytes were accepted, write()'s  return value will indicate how many bytes it accepted... if none were accepted, write() will return -1 and errno will be set to EWOULDBLOCK).  The number of bytes that write() accepts will depend on how much space it has available in its in-kernel buffer at the moment.  After write() returns, it's your responsibility to remember how many of your bytes it accepted, and then call select() (or poll() or some other mechanism) so that you will be notified when there is more space available in the buffer.  When more space becomes available (i.e. at some time in the future) you can then call write() again to pass more bytes to the buffer.
aio_write(), on the other hand, will "take ownership" of the data you pass in to the function, and notify you later on when it has finished writing out the data.  With aio_write(), you don't have to worry about the call accepting only part of your data buffer; it will either accept the entire thing, or error out.  That will make your app's I/O logic a bit simpler in that respect; however I think asynchronous i/o has its own set of complicating factors so it might not always be a win.  (I haven't used aio_*() myself, so I can't give details)
As for why the write() function doesn't seem to be taking more time as the length of data written increases... that's because a non-blocking write() only copies (none, or some, or all) of the data you pass to it into a buffer, and then returns immediately; it doesn't actually wait for the data to get onto the disk.  Copying a (relatively small) sequence of bytes from your app's buffer to an in-kernel buffer will always be fast, and the number of bytes copied will never be greater than the amount of empty space currently available in the in-kernel buffer, so even the number of bytes copied per write() is bounded/small.
Comment: That's a good summary, except that O_NONBLOCK won't necessarily fail... it might instead just take some of the data you offered and leave the rest.
Comment: To summarize: If there's enough space in the kernel buffer, there's no difference.  If there's not, `O_NONBLOCK` will fail, `aio_write` will do it later from outside your thread.
Comment: Is the data in buffer used by aio_write also buffered by kernel? Seems not by POSIX. https://pubs.opengroup.org/onlinepubs/9699919799/ search for unbuffered.


Mouse Pointer Jumps About in Ubuntu 20.04 (dual-boot with Windows 10)

Question: Now that I have loaded Ubuntu 20.04 to dual-boot on a Packard Bell with Windows 10 Home 64-bit, I am unable to stop the mouse pointer from jumping around and leaving a trail of flickering pointers wherever the pointer has gone. When I hover over a button, the pointer jumps around so much, clicking on a button becomes very much a hit and miss affair. Meanwhile, an unmoving pointer sits at the bottom right of the screen, while I am moving a second pointer around the screen. How do I fix this please? Is it a mouse driver compatibility issue?
This is the result of my xinput:
$ lsb_release -a
No LSB modules are available.
Distributor ID: Ubuntu
Description:    Ubuntu 20.04 LTS
Release:    20.04
Codename:   focal

$ xinput
⎡ Virtual core pointer                      id=2    [master pointer  (3)]
⎜   ↳ Virtual core XTEST pointer                id=4    [slave  pointer  (2)]
⎜   ↳ USB Wired Keyboard Consumer Control       id=13   [slave  pointer  (2)]
⎜   ↳ PixArt USB Optical Mouse                  id=10   [slave  pointer  (2)]
⎣ Virtual core keyboard                     id=3    [master keyboard (2)]
    ↳ Virtual core XTEST keyboard               id=5    [slave  keyboard (3)]
    ↳ Power Button                              id=6    [slave  keyboard (3)]
    ↳ Video Bus                                 id=7    [slave  keyboard (3)]
    ↳ Power Button                              id=8    [slave  keyboard (3)]
    ↳ Sleep Button                              id=9    [slave  keyboard (3)]
    ↳ USB Wired Keyboard                        id=11   [slave  keyboard (3)]
    ↳ USB Wired Keyboard System Control         id=12   [slave  keyboard (3)]
    ↳ USB Wired Keyboard Consumer Control       id=14   [slave  keyboard (3)]

I'm shooting in the dark here. I've unplugged the USB mouse and, after plugging it back in, there was no change. I have also done a download because someone said that this worked for his touchpad when his mouse pointer was dancing around after upgrading to Ubuntu 20.04. It worked for him, but it doesn't work for me.
This is what I downloaded:
$ sudo apt install xserver-xorg-input-synaptics

So, it looks as though I'll have to uninstall that.
$ sudo apt-get remove xserver-xorg-input-synaptics

After removing it I have the following message:
Reading package lists... Done
Building dependency tree
Reading state information... Done
Package 'xserver-xorg-input-synaptics' is not installed, so not removed
The following packages were automatically installed and are no longer required:
  linux-headers-5.4.0-26 linux-headers-5.4.0-26-generic linux-image-5.4.0-26-generic
  linux-modules-5.4.0-26-generic linux-modules-extra-5.4.0-26-generic
Use 'sudo apt autoremove' to remove them.
0 to upgrade, 0 to newly install, 0 to remove and 129 not to upgrade.

So, I have autoremoved the packages no longer required. It has not changed anything. I have unplugged the mouse from a USB 3 and plugged it into a USB 2 with no effect.
Let's have a look at the output of:
lsb_release -a; uname -a; lsusb

The output is:
No LSB modules are available.
Distributor ID: Ubuntu
Description:    Ubuntu 20.04 LTS
Release:    20.04
Codename:   focal
Linux charlesb2t-iMedia-S2984 5.4.0-37-generic #41-Ubuntu SMP Wed Jun 3 18:57:02 UTC 2020 x86_64 x86_64 x86_64 GNU/Linux
Bus 002 Device 001: ID 1d6b:0003 Linux Foundation 3.0 root hub
Bus 001 Device 004: ID 0bda:0153 Realtek Semiconductor Corp. 3-in-1 (SD/SDHC/SDXC) Card Reader
Bus 001 Device 007: ID 0461:4e6f Primax Electronics, Ltd Acer Wired Keyboard Model KBAY211
Bus 001 Device 008: ID 0461:4e70 Primax Electronics, Ltd USB Optical Mouse
Bus 001 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub

Is the Primax Electronics Ltd USB Optical Mouse incompatible with Ubuntu?
I have noticed that in the  Linux USB IDs the following list:
0461  Primax Electronics, Ltd
    0010  HP PR1101U / Primax PMX-KPR1101U Keyboard
    0300  G2-300 Scanner
    0301  G2E-300 Scanner
    0302  G2-300 #2 Scanner
    0303  G2E-300 #2 Scanner
    0340  Colorado 9600 Scanner
    0341  Colorado 600u Scanner
    0345  Visioneer 6200 Scanner
    0346  Memorex Maxx 6136u Scanner
    0347  Primascan Colorado 2600u/Visioneer 4400 Scanner
    0360  Colorado 19200 Scanner
    0361  Colorado 1200u Scanner
    0363  VistaScan Astra 3600(ENG)
    0364  LG Electronics Scanworks 600U Scanner
    0365  VistaScan Astra 3600(ENG)
    0366  6400
    0367  VistaScan Astra 3600(ENG)
    0371  Visioneer Onetouch 8920 Scanner
    0374  UMAX Astra 2500
    0375  VistaScan Astra 3600(ENG)
    0377  Medion MD 5345 Scanner
    0378  VistaScan Astra 3600(ENG)
    037b  Medion MD 6190 Scanner
    037c  VistaScan Astra 3600(ENG)
    0380  G2-600 Scanner
    0381  ReadyScan 636i Scanner
    0382  G2-600 #2 Scanner
    0383  G2E-600 Scanner
    038a  UMAX Astra 3000/3600
    038b  Xerox 2400 Onetouch
    038c  UMAX Astra 4100
    0392  Medion/Lifetec/Tevion/Cytron MD 6190
    03a8  9420M
    0813  IBM UltraPort Camera
    0815  Micro Innovations IC200 Webcam
    0819  Fujifilm IX-30 Camera [webcam mode]
    081a  Fujifilm IX-30 Camera [storage mode]
    081c  Elitegroup ECS-C11 Camera
    081d  Elitegroup ECS-C11 Storage
    0a00  Micro Innovations Web Cam 320
    4d01  Comfort Keyboard / Kensington Orbit Elite
    4d02  Mouse-in-a-Box
    4d03  Kensington Mouse-in-a-box
    4d04  Mouse
    4d06  Balless Mouse (HID)
    4d0f  HP Optical Mouse
    4d15  Dell Optical Mouse
    4d17  Optical Mouse
    4d20  HP Optical Mouse
    4d2a  PoPo Elixir Mouse (HID)
    4d2b  Wireless Laser Mini Mouse (HID)
    4d2c  PoPo Mini Pointer Mouse (HID)
    4d2e  Optical Mobile Mouse (HID)
    4d51  0Y357C PMX-MMOCZUL (B) [Dell Laser Mouse]
    4d62  HP Laser Mobile Mini Mouse
    4d75  Rocketfish RF-FLBTAD Bluetooth Adapter
    4d81  Dell N889 Optical Mouse
    4d8a  HP Multimedia Keyboard
    4d91  Laser mouse M-D16DL
    4d92  Optical mouse M-D17DR
    4db1  Dell Laptop Integrated Webcam 2Mpix
    4de3  HP 5-Button Optical Comfort Mouse
    4de7  webcam
    4e04  Lenovo Keyboard KB1021
    4e22  Dell Mouse, 2 Buttons, Modell: MS111-P
    4e6f  Acer Wired Keyboard Model KBAY211

The 4e70 USB Optical Mouse is not listed. Could this be my issue?
To try and answer this I dug up a Xenta Wireless Optical Mouse, but the problem of one jittery mouse pointer, which I can move around, and a second stationary mouse pointer in the bottom right of the screen still persists.
$ lsb_release -a; uname -a; lsusb
No LSB modules are available.
Distributor ID: Ubuntu
Description:    Ubuntu 20.04 LTS
Release:    20.04
Codename:   focal
Linux charlesb2t-iMedia-S2984 5.4.0-37-generic #41-Ubuntu SMP Wed Jun 3 18:57:02 UTC 2020 x86_64 x86_64 x86_64 GNU/Linux
Bus 002 Device 001: ID 1d6b:0003 Linux Foundation 3.0 root hub
Bus 001 Device 004: ID 0bda:0153 Realtek Semiconductor Corp. 3-in-1 (SD/SDHC/SDXC) Card Reader
Bus 001 Device 003: ID 0461:4e6f Primax Electronics, Ltd Acer Wired Keyboard Model KBAY211
Bus 001 Device 002: ID 1d57:0008 Xenta 2.4G Wireless Optical Mouse
Bus 001 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub

I have checked the Packard Bell website to see whether the BIOS is up to date and it looks as though it is. Nothing has changed since I bought the machine in 2016.
After I have the input list:
$ xinput --list
⎡ Virtual core pointer                      id=2    [master pointer  (3)]
⎜   ↳ Virtual core XTEST pointer                id=4    [slave  pointer  (2)]
⎜   ↳ USB Wired Keyboard Consumer Control       id=11   [slave  pointer  (2)]
⎜   ↳ PixArt USB Optical Mouse                  id=14   [slave  pointer  (2)]
⎣ Virtual core keyboard                     id=3    [master keyboard (2)]
    ↳ Virtual core XTEST keyboard               id=5    [slave  keyboard (3)]
    ↳ Power Button                              id=6    [slave  keyboard (3)]
    ↳ Video Bus                                 id=7    [slave  keyboard (3)]
    ↳ Power Button                              id=8    [slave  keyboard (3)]
    ↳ Sleep Button                              id=9    [slave  keyboard (3)]
    ↳ USB Wired Keyboard System Control         id=10   [slave  keyboard (3)]
    ↳ USB Wired Keyboard Consumer Control       id=12   [slave  keyboard (3)]
    ↳ USB Wired Keyboard                        id=13   [slave  keyboard (3)]

I can get a list of properties:
$ xinput --list-props "PixArt USB Optical Mouse"
Device 'PixArt USB Optical Mouse':
    Device Enabled (161):   1
    Coordinate Transformation Matrix (163): 1.000000, 0.000000, 0.000000, 0.000000, 1.000000, 0.000000, 0.000000, 0.000000, 1.000000
    libinput Natural Scrolling Enabled (298):   0
    libinput Natural Scrolling Enabled Default (299):   0
    libinput Scroll Methods Available (300):    0, 0, 1
    libinput Scroll Method Enabled (301):   0, 0, 0
    libinput Scroll Method Enabled Default (302):   0, 0, 0
    libinput Button Scrolling Button (303): 2
    libinput Button Scrolling Button Default (304): 2
    libinput Middle Emulation Enabled (305):    0
    libinput Middle Emulation Enabled Default (306):    0
    libinput Accel Speed (307): -0.014706
    libinput Accel Speed Default (308): 0.000000
    libinput Accel Profiles Available (309):    1, 1
    libinput Accel Profile Enabled (310):   1, 0
    libinput Accel Profile Enabled Default (311):   1, 0
    libinput Left Handed Enabled (312): 0
    libinput Left Handed Enabled Default (313): 0
    libinput Send Events Modes Available (283): 1, 0
    libinput Send Events Mode Enabled (284):    0, 0
    libinput Send Events Mode Enabled Default (285):    0, 0
    Device Node (286):  "/dev/input/event6"
    Device Product ID (287):    1121, 20080
    libinput Drag Lock Buttons (314):   <no items>
    libinput Horizontal Scroll Enabled (315):   1

However, I don't think any changes can be made there that will fix the problem.
As the 4e70 USB Optical Mouse is not listed, in the Linux USB IDs List, but the Kensington 4d03 Mouse-in-a-box is, I'm going to try and get my hands on one of those.
Comment: So, I've now plugged in a "Kensington Mouse-in-a-Box" Wired Optical USB Mouse and the PC has identified it as a ***093a:2510 Pixart Imaging, Inc. Optical Mouse*** (not 4d03 Mouse-in-a-box), but the mouse is on the Linux USB IDs List. However, this different mouse is still showing the same behaviour of jumping the mouse-pointer about; leaving a trail of flickering mouse-pointers wherever one has passed the mouse-pointer; and then there's still another stationary mouse-pointer at the bottom-right of the screen. So, what now?
Comment: The issue seems to be that I have two monitors plugged in to my tower. If only one monitor is plugged in, the mouse-pointer performs perfectly. However, I need two screens / monitors for my work.
Answer: So, all I've solved here is:

It's not down to a dual-boot setup with Windows 10 and Ubuntu 20.04
It's not down to an incompatible mouse driver

However, the problem of the jumping mouse-pointer occurs as soon as I connect another monitor to my PC - https://help.ubuntu.com/stable/ubuntu-help/display-dual-monitors.html


Remove :hover color from text without setting the color

Question: I would like to remove the :hover color from the text. However, knowing what the non-hover color is not possible in this case. Is there a way to set the color to inherit from its non :hover parent self? I can see and modify the element:hover CSS but not the element CSS.
Clarification: I want the link to inherit the color from its non-hovered state so that hovering does not have an effect on the element's color.  I encapsulated a div in a link so that the entire div would be a link, but I don't want that to change the text's color inside the div. I am changing the background color instead.
Comment: Sorry, I think I can't understand the question. What I can't understand is if you don't want to change the color at hovering, you can leave the `:hover` css without adding the `color:` property. Why can't you do it in this case?
Comment: This is what I have: http://jsfiddle.net/WAYZx/ I do not want the color of the text to change when the user hovers over the text, however, I do not have access to the original color to set it back to in the CSS nor can I remove the a:hover attribute.
Comment: Ah, you were referring to taking the non-hover color of the same element, not its parent. I was confused. I've removed my answer since it no longer applies.
Answer: You cannot. There is no undo in CSS. That is, if some style sheet assigns a property to an element, or to a state of an element, there is no way to tell a browser behave as if that rule were not there. You can override its effect, but this means setting the property to a value (which could be inherit, but that won't help here, since inheritance is from a parent).


What is the continuous analogue of a discrete finite automaton?

Question: To fix ideas: let $Q$ be a set of states and $\Sigma$ a set of inputs; let $\delta : Q \times \Sigma \rightarrow Q$ be a transition function. If $Q$ and $\Sigma$ are finite, $\delta$ in conjunction with an initial state $q_0$ and an accepting set $F$ specify a discrete finite automaton.
If $Q$ and $\Sigma$ are continuous, what is the analogue of a DFA called (I am guessing this is some flavor of a "hybrid system" that crops up in the electrical engineering community)? In particular, are there any nontrivial results known for "nice" $\delta$ (e.g., convex, known qualitative properties of derivatives, etc.)?
Comment: Perhaps a [dynamical system](https://en.wikipedia.org/wiki/Dynamical_system#Formal_definition).
Comment: State space representation of control systems. However, you can do a lot more reasoning about FAs than you can about general dynamical systems. Just existence of solutions is an issue in general, something that does not arise with FAs. Noise (in an unspecified sense) is an issue with analogue systems that has no meaning with FAs.
Comment: @user85667 the situation I discuss is more general: it does not require any structure (e.g., semigroup/monoid/what have you) on the sets involved.
Comment: @copper.hat can you elaborate? I am not assuming any system of differential equations here, and not even any differentiable structure.
Comment: @SHuntsman It really isn't more general, since from a finite automaton you can increase $Q$ to $Q'$ by adding some terminating states representing transitions in which the original automaton is not defined, and from $\delta$ define a function on $\delta':Q\times \Sigma^*\to Q$ such that $\delta'(q,w)$ is just the value of $\delta$ after transitioning through all letters of $w$. $\Sigma^*$  is a semigroup.
Comment: @user85667 I do not understand the precise intent of your construction. I also do not understand how adding terminating states doesn't do violence to the DFA-like thing. Perhaps these two failures of mine are related--if you can elaborate I would be grateful.
Comment: @SHuntsman The $\delta'$ is a dynamical system that models the automaton; how it changes along all words in $\Sigma^*$. It contains all the information of the automaton, but now the "time parameter" ranges over the semigroup $\Sigma^*$ as required. In other words, you can replace the study of DFA, by the study of their corresponding dynamical system built this way. This construction probably has a name.
Comment: Presumably by continuous you mean infinite ($\Sigma, Q$). A discrete time state space model fits your description I believe. You are asking a fairly broad question.
Answer: Your question is rather unclear: what do you mean by "If $Q$ and $\Sigma$ are continuous"? Anyway, the closest thing I can think of is a topological transformation semigroup, that is, a transformation semigroup $(Q, S)$ in which $Q$ is a topological space, $S$ is a topological semigroup and the action $Q \times S \to Q$, $(q, s) \to qs$ is continuous. This notion is used for instance in [1], but this is just the first reference I found on Google and there are certainly other sources. In a dynamical system, the definition is the same, but the semigroup is usually commutative.
[1] Haynes, Tyler. Thickness in topological transformation semigroups Internat. J. Math. Math. Sci. 16 (1993), no. 3, 493--502.


Wine "alt tabs" the game everytime there is a video playing

Question: I have a weird issue in Xubuntu 20.04. When I am playing a game and there is a video cutscene, the games "alt tabs" and I am back at the desktop. I need to click the game windows indicator to go back to the game.
Its really annoying and it happens in all the games when they have vide intros.
For instance : USF4, StreetFighterXTekken, Toy Story 3, etc.
How can I avoid this?
Answer: So, as a workaround I was able to "fix" this by running:
<code>winecfg
</code>
and then selecting to run apps "with a Virtual Desktop".
This obviously should not be the right path but I do not have an explanation nor a proper fix.


How to catch FileNotFoundException for new ClassPathXmlApplicationContext()

Question: I am trying to create a program where I want to input the spring configurations file from user just to create some demo application. If I directly call new ClassPathXmlApplicationContext(filePath), it throws FileNotFoundException if the file doesn't exist.
I want to catch this exception and display the user an error message instead of terminating the application. Even if I surround the call to constructor by try-catch or using throws declaration, the exception is not caught and the application terminates printing the stack trace.
Any ideas how can I catch the thrown exception?
This is a Spring MVC application
The caller function (Inside the @Controller class)-
private String getFlavours(ModelMap model, String configFile) {
    FlavourService flavourService = new FlavourService();
    String results = null;

    try {
        results = flavourService.generateFlavour(configFile);
    } catch (FileNotFoundException e) {
        System.out.println("In FNF Execp");
        model.addAttribute("errorMessage", "Requested configurations file not found");
        return "index";
    }

    model.addAttribute("results", results);
    model.addAttribute("configFile", configFile);
    return "springDemo";
}

The called function (Inside other normal class FlavourService from different package)-
public String generateFlavour(String configFile) throws FileNotFoundException {
    String path = "somepath"; //this is path from classpath
    String filename = configFile;

    context = new ClassPathXmlApplicationContext(path + filename);

    //code to generate required output

    return output;
}

I am getting the exception as -
SEVERE: Servlet.service() for servlet HelloWeb threw exception
java.io.FileNotFoundException: class path resource [com/cts/spring/config/dsf] cannot be opened because it does not exist
    at org.springframework.core.io.ClassPathResource.getInputStream(ClassPathResource.java:158)
    at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:329)
    at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:303)
    at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:180)
    at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:216)
    at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:187)
    at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:251)
    at org.springframework.context.support.AbstractXmlApplicationContext.loadBeanDefinitions(AbstractXmlApplicationContext.java:127)
    at org.springframework.context.support.AbstractXmlApplicationContext.loadBeanDefinitions(AbstractXmlApplicationContext.java:93)
    at org.springframework.context.support.AbstractRefreshableApplicationContext.refreshBeanFactory(AbstractRefreshableApplicationContext.java:129)
    at org.springframework.context.support.AbstractApplicationContext.obtainFreshBeanFactory(AbstractApplicationContext.java:540)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:454)
    at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:139)
    at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:83)
    at com.cts.spring.FlavourService.generateFlavour(FlavourService.java:31)
    at com.cts.spring.controller.SpringFlavoursController.getFlavours(SpringFlavoursController.java:38)
    at com.cts.spring.controller.SpringFlavoursController.viewFlavours(SpringFlavoursController.java:30)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.lang.reflect.Method.invoke(Unknown Source)
    at org.springframework.web.method.support.InvocableHandlerMethod.invoke(InvocableHandlerMethod.java:215)
    at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:132)
    at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:104)
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandleMethod(RequestMappingHandlerAdapter.java:749)
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:690)
    at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:83)
    at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:945)
    at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:876)
    at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:961)
    at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:863)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:641)
    at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:837)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:243)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:201)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:163)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:108)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:402)
    at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:249)
    at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:267)
    at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:245)
    at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:260)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
    at java.lang.Thread.run(Unknown Source)

If I try creating a similar problem in Java Project using spring only, I get a different exception where it mentions that FileNotFoundException is nested exception as follows -
Exception in thread "main" org.springframework.beans.factory.BeanDefinitionStoreException: IOException parsing XML document from class path resource [dsf]; nested exception is java.io.FileNotFoundException: class path resource [dsf] cannot be opened because it does not exist
    at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:343)
    at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:303)
    at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:180)
    at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:216)
    at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:187)
    at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:251)
    at org.springframework.context.support.AbstractXmlApplicationContext.loadBeanDefinitions(AbstractXmlApplicationContext.java:127)
    at org.springframework.context.support.AbstractXmlApplicationContext.loadBeanDefinitions(AbstractXmlApplicationContext.java:93)
    at org.springframework.context.support.AbstractRefreshableApplicationContext.refreshBeanFactory(AbstractRefreshableApplicationContext.java:129)
    at org.springframework.context.support.AbstractApplicationContext.obtainFreshBeanFactory(AbstractApplicationContext.java:540)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:454)
    at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:139)
    at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:83)
    at MainApp.main(MainApp.java:16)
Caused by: java.io.FileNotFoundException: class path resource [dsf] cannot be opened because it does not exist
    at org.springframework.core.io.ClassPathResource.getInputStream(ClassPathResource.java:158)
    at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:329)
    ... 13 more

Comment: Clearly, it is not throwing a FileNotFoundException, so of course you can not catch it.
Comment: @Raedwald as you can see in the first case (my actual application) its showing `FileNotFoundException`

In the later case I got to know that its an nested exception. How can i deal with that??? Because I don't want to mess exception handling by just taking some superclass of exception to handle a nested exception
Comment: See also  http://stackoverflow.com/questions/7593535/how-to-catch-a-nested-exception-in-java
Answer:
Use a higher level of Exception for catching, say IOException. It might so happen that you are catching only FileNotFoundException and there might be other type of exception spring might be throwing.
use FileSystemXmlApplicationContext instead, to pass FileSystem paths as parameters.

http://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/context/support/FileSystemXmlApplicationContext.html#FileSystemXmlApplicationContext-java.lang.String-
Comment: thanks for the idea. It didn't work for `IOException` but worked for `Exception` like a charm. It is giving me an nested exception of `FileNotFoundException`.

I want to know, how can I catch the nested exception only because catching exception of type `Exception` may not be effective if some other exception is thrown by the code due to some other reason.
Answer: Create a new File Object before passing the file Path in Constructor and check that file actually exist or not
Try This
File file=new File(filePath);
if(!file.exists) // Check if file Actually Exists or not
 //thow any Exception if file Not Exists

Comment: this is a good idea to deal with the problem (maybe good for real-time applications), but as I am learning the concepts in Java, I want know how the exception can be handled rather than finding an alternative approach to the problem.
Comment: This is not an alternative approach , what would be your first attempt after getting `FileNotFound Exception` ? you will either create that file or just Quit , which you can do from here also .


How to transfer photos from camera to PC over Wi-Fi (Canon S110) Xubuntu 13.10

Question: The Canon S110 comes with an optical disk containing a software bundle for Windows (and of course nothing for Linux), including an utility for connecting to the computer through WiFi.
Also I think worth noting is that in Windows the transfer process requires Media Streaming and Network Discovery to be turned on. I think this would be key points for enabling photo transfer on Ubuntu also, but I cannot find [the equivalent of] these options anywhere.
This link explains the process for Windows.
So the question is how can I transfer my photos from the camera to my Ubuntu PC over wireless?
I love the wireless option on the Canon S110 and have been using it intensely before switching over to Linux, I don't like to mess with cables. Anyway, I already lost the original cable. Also my PC has no card reader.
I am using both Xubuntu and Mint 16 XFCE.
Comment: Thank you for the piece of advice but I'd prefer to use this fabulous, magic, no strings attached method called Wi-Fi transfer;)
Comment: get a cable.they are cheap.
Comment: @brett: thanks for the acceptance!  Favour returned!  ;-)
Answer: Airnef is an open source tool that can be used to transfer files from Canon, Nikon and Sony cameras (at the time of this writing).

Airnef is two applications - a GUI front-end and a command-line app. The GUI front-end allows you to visually select the criteria of which images to download and then launches the command-line app to perform the transfer. You can optionally use the command-line version directly to script your transfers.

Here is the download link to the 1.1 binaries but people interested in python should download the source.
Comment: @azerafati the EOS 1300D is from 2016 and the binaries haven't been updated since 2015, so read the [Airnef FAQ](http://www.testcams.com/airnef/) first. If that doesn't help, contact the developers [here](http://testcams.com/blog/forums/forum/airnef-wireless-download-from-your-nikon-camera/).
Comment: it's perfect but unfortunately not supporting canon 1300D. after connecting just closes with an error
Comment: tanx, though their forum sucks. Wish they had discovered SE


AWS Cloud Front Not Respecting TTL

Question: We recently discovered that Cloudfront deletes files after 1 days regardless of minimum, maximum and default TTL settings in cloudFront or the origin headers.
Is there a way to override this header and force Cloudfront to respect TTL values?
If not, what TTL does Cloudfront really use before deleting files from CDN?
If there is really no SLA, any other reliable CDN with an SLA.
Request 1 HeadersResponse HIT

Response Version - HTTP/2
access-control-allow-origin
*
age
60847
alt-svc
h3=":443"; ma=86400
cache-control
max-age=2592000
content-encoding
gzip
content-type
text/css
date
Sun, 30 Jul 2023 09:57:24 GMT
expires
Tue, 29 Aug 2023 09:57:24 GMT
last-modified
Wed, 20 Jan 1988 04:20:42 GMT
server
nginx
vary
Accept-Encoding
via
1.1 xxx.cloudfront.net (CloudFront)
x-amz-cf-id XXX
x-amz-cf-pop
YVR50-C1
x-cache
Hit from cloudfront

Request 2 HeadersResponse MISS

Response Version - HTTP/2
access-control-allow-origin
*
alt-svc
h3=":443"; ma=86400
cache-control
max-age=315360000
content-encoding
gzip
content-type
text/css
date
Sun, 06 Aug 2023 00:12:08 GMT
expires
Thu, 31 Dec 2037 23:55:55 GMT
last-modified
Wed, 20 Jan 1988 04:20:42 GMT
server
nginx
vary
Accept-Encoding
via
1.1 xxx.cloudfront.net (CloudFront)
x-amz-cf-id
x-amz-cf-id XXX
x-amz-cf-pop
YVR50-C1
x-cache
Miss from cloudfront ```

Answer: After extensive discussions with Cloudfront support, it does appear that TTLs are merely suggestions. Cloudfront tries to respect them depending upon load on their resources etc. but no guarantees unless you have some sort of enterprise agreement with them.
I have moved some of the resources to Cloudflare and seen dramatic improvements.

AWS Cloud Front Not Respecting TTL


Name of a struct to a string

Question: How do I print the name of the type of a struct, i.e. so I can include it in a print statement, i.e. something like
type MyStruct struct { ... }

func main() {
    fmt.Println(MyStruct.className())
}

If this is possible, would it be considered a slow operation? (i.e. reflection)
Comment: Looks similar to http://stackoverflow.com/q/20170275/6309
Answer: For example,
package main

import "fmt"

type MyStruct struct{}

func main() {
    fmt.Printf("%T\n", MyStruct{})
}

Output:
main.MyStruct

The fmt %T print verb gives a Go-syntax representation of the type of the value.
The Go fmt package uses the reflect package for run-time reflection.

Name of a struct to a string


Plotting epicycles by using matplotlib

Question: Why does the following code not working?
I want to display epicycles by using matplotlib like a following image

import matplotlib.pyplot as plt
import numpy as np
from numpy import *
import math

freqList = [1,2,3]
ampList = [1,2,4]
phaseList = [0,10,20]

circles = [] #create list of circles

x = 0
y = 0
for i in range(len(freqList)):
   prevx = x
   prevy = y
   theta = np.linspace( 0 , 2 * np.pi , 150 )
   x += ampList[i] * np.cos( theta*freqList[i] + phaseList[i] )
   y += ampList[i] * np.sin( theta*freqList[i] + phaseList[i] )

   circle = plt.Circle((prevx, prevy), ampList[i], fill=False)
   circles.append(circle)

   plt.figure()
   fig, ax = plt.subplots()
   ax.add_patch(circles[i])
   plt.axis("equal")
   plt.xlim( -10 , 10 )
   plt.ylim( -10 , 10 )
   plt.show()

Thank you in advance to any one who may be able to give me some ideas!
Answer: I applied some changes to your code:

loop over elements of a list with for i in range(len(list_name)) and then get ith element with list_name[i] works, but it is a little awkward; in python you can loop over elements of list directly: for element in list. If you need to loop over element of more than one list, you can use zip: for a, b in zip(list_a, list_b)

within your loop you generates the circles, once at a time, and add it to the plot. Things which are created only once (not once every cycle) have to be generated outside the for loop; that's the case for fig, ax etc.

in your code you have created an array, theta, which is 150 elements. Inside for loop you add up a function of theta, which is an array too, to x and y. So, in the first iteration x and y are int and represent coordinates of the first circle, then they become  arrays. This is the reason why your code throws an error

if you use matplotlib.patches.Circle you need only the coordinates of the center and the radius. No need to compute theta, no need to use freqList (if I interpreted it correctly). For this reason, inside the loop you have only to pass current center coordinates and radius to matplotlib.patches.Circle and compute center coordinates for the next circle using only current amplitude and phase

That being said, your code becomes:
# import
import matplotlib.pyplot as plt
import numpy as np

# amplitude and phase definition
ampList = [1,2,4]
phaseList = [0,10,20]

# center coordinates of the first circle
C_x = 0
C_y = 0

# generate figure and axis
fig, ax = plt.subplots()

# loop over each amplitude and phase
for amp, phase in zip(ampList, phaseList):

    # draw current circle
    circle = plt.Circle((C_x, C_y), amp, fill = False)
    ax.add_patch(circle)
    # draw current circle center
    ax.plot(C_x, C_y, marker = 'o', markerfacecolor = 'k', markeredgecolor = 'k')

    # compute next circle center
    C_x += amp*np.cos(np.deg2rad(phase))
    C_y += amp*np.sin(np.deg2rad(phase))

# adjust axis
plt.axis("equal")
plt.xlim( -10 , 10 )
plt.ylim( -10 , 10 )

# show the plot
plt.show()

Plotting epicycles by using matplotlib


I'm trying to create a qr code scanner through a webcam

Question: In a training project (web application) I want to implement a function for reading a qr code through a webcam. In open sources, I found the code just for this case, but I ran into an error that I can't overcome ... maybe someone can tell me what to do? thanks in advance
upd: webcam not starts working at all. I click a button in my application and immediately get a 500 error
<code>            # set up camera object
            cap = cv2.VideoCapture(0)
            # инициализируем детектор QRCode cv2
            detector = cv2.QRCodeDetector()
            while True:
                _, img = cap.read()
                # обнаружить и декодировать
                data, bbox, _ = detector.detectAndDecode(img)
                # проверяем, есть ли на изображении QRCode
                if bbox is not None:
                    # отображаем изображение с линиями
                    for i in range(len(bbox)):
                        # рисуем все линии
                        cv2.line(img, tuple(bbox[i][0]), tuple(bbox[(i+1) % len(bbox)][0]), color=(255, 0, 0), thickness=2)
                    if data:
                        print("[+] QR Code detected, data:", data)
                # отобразить результат
                cv2.imshow("img", img)
                if cv2.waitKey(1) == ord("q"):
                    break
            cap.release()
            cv2.destroyAllWindows()
</code>
Mistake:
<code>    data, bbox, _ = detector.detectAndDecode(img)
cv2.error: OpenCV(4.5.5) /io/opencv/modules/objdetect/src/qrcode.cpp:29: error: (-215:Assertion failed) !img.empty() in function 'checkQRInputImage'
</code>
Comment: Please redo a question separatly instead of editing this one.
Answer: There is a similar error here:
CV2 Image Error: error: (-215:Assertion failed) !ssize.empty() in function 'cv::resize'
You should check if the img you get actually exist, because the function throwing your error return a none value instead of the expected array if the image does not exist.
<code>if img is None:
    continue
</code>
Comment: thank you. problem is that the webcam does not start at all (most likely this is why it gives an error with the image)
Maybe I asked wrong question from the beginning.
Comment: @real_one If the camera is not working, then it make sense. You should apply the condition I've given in my answer I think. It was the good question, it just led to an other one that's how you progress :)


Can Minecraft PS4 edition connect to local LAN servers without PlayStation Network?

Question: Some context
I have a home LAN where I connect

Wifi Router
Playstation 4
Playstation 3
Desktop with Windows 10
Laptop with Windows 10
Android Tablet
Android Phones

I have bought Minecraft for my PS4. My son loves it. We play in multiplayer in the same screen. I don't pay playstation network and would like to avoid it.
I am thinking on creating a dedicated Minecraft Server in my desktop PC so I am planning to run a dedicated server there to be able to have the same server for all devices and install mods.
Then I plan to have Minecraft clients in the devices listed above.
My questions are

Does Minecraft ps4 edition allow you to play in your local LAN?
Are clients from different platforms able to play in the same server (PS4, PC, PS3, Android Tablet, etc.)
Answer: Unfortunately, it appears (according to some Reddit threads #1, #2, #3, #4), two distinct concepts jump out:

Minecraft on the PlayStation 4 doesn't directly support LAN games. They are considered "cross-play" games.
As such, what you describe would be considered an "online" game, and therefore you'd need an active PlayStation Plus subscription to join one from a PlayStation 4 console.

A "bug report" in Mojang's Jira bug tracker was filed in December 2019 to have developers address this point exactly, but went un-responded to because of a lack of required information on the reporter's part.
Answer: Answer to #1
You can play on a LAN game on PS4, but you will need PS Plus.
Answer to #2
The clients can play on the same server if they are all of Bedrock Edition. Bedrock Edition is Pocket (Mobile), Xbox One, Playstation 4, Nintendo Switch, and Windows 10 Edition. With that said, if you are setting up a LAN game on your PC you must run the Windows 10 Edition, not the Java Edition.

You have Windows 10 Edition if you bought the game from the Windows Store
You have Java Edition if you bought the game from minecraft.net.

Java edition cannot play a LAN game with PlayStation 4. Windows 10 edition can play a LAN game with PlayStation 4.
Comment: This is so strange... basically Sony asks me to pay £50/year for PS+ so I can play my local server at home.


creating a progress bar for a validation test Python

Question: The following code is used to find p-values for a significant test on Cifar-10 database.
Because we need a min of 1000 permutations, it is a very slow process, and I want to inlude a progress bar to show how time for each permutation.
I was thinking of using the tqdm library and sleep function, but am stuck on where to go from here. any help would be greatly appreciated!
'''
def validate_significance(val_loader, model, criterion, args):
model.eval()

vec_acc1 = []
vec_acc1_chance = []
vec_acc5 = []
vec_acc5_chance = []

for ss in range(0, args.num_permutations):

    val_loader = get_rand_sample_loader(val_loader.dataset, args)

    acc1_over_one_permutaion = 0
    acc1_chance_over_one_permutation = 0
    acc5_over_one_permutaion = 0
    acc5_chance_over_one_permutation = 0
    cnt = 0
    with torch.no_grad():
        for i, (images, target) in enumerate(val_loader):

            if args.gpu is not None:
                images = images.cuda(args.gpu, non_blocking=True)
            if torch.cuda.is_available():
                target = target.cuda(args.gpu, non_blocking=True)

            # compute output
            output = model(images)

            # measure accuracy on true labels
            acc1, acc5 = accuracy(output, target, topk=(1, 5))
            acc1_over_one_permutaion += acc1.item()
            acc5_over_one_permutaion += acc5.item()

            # now, measure accuracy on permuted labels
            target = target[torch.randperm(len(target))]  # scrambling the labels
            acc1_perm, acc5_perm = accuracy(output, target, topk=(1, 5))
            acc1_chance_over_one_permutation += acc1_perm.item()
            acc5_chance_over_one_permutation += acc5_perm.item()
            cnt += 1

    vec_acc1.append(acc1_over_one_permutaion / cnt)
    vec_acc1_chance.append(acc1_chance_over_one_permutation / cnt)
    vec_acc5.append(acc5_over_one_permutaion / cnt)
    vec_acc5_chance.append(acc5_chance_over_one_permutation / cnt)

p_acc1 = stats.ttest_ind(vec_acc1, vec_acc1_chance, equal_var=False)
p_acc5 = stats.ttest_ind(vec_acc5, vec_acc5_chance, equal_var=False)

return p_acc1, p_acc5

'''
Comment: a way to do this would be to purge the entire output, and replace it with your update bar, like they do when you are `pip install`ing something
Comment: take a look at the following answer: https://stackoverflow.com/questions/3160699/python-progress-bar
Answer: from tqdm import tqdm

def validate_significance(val_loader, model, criterion, args):
    model.eval()

    vec_acc1 = []
    vec_acc1_chance = []
    vec_acc5 = []
    vec_acc5_chance = []

    for ss in tqdm(range(0, args.num_permutations)):
        ....


Can truth tables be different for equal expressions?

Question: I have a equation (A'B + B'C)C'. If I simplify this down to A'B C' the truth tables are not the same. What am I doing wrong?
Comment: [Here's a MathJax tutorial](https://math.meta.stackexchange.com/q/5020/104041) :)
Comment: It would be helpful to share your truth tables.
Comment: For some reason the post changed my question..
Comment: Edited the post and now question registered normally (:
Comment: Shaun - I'm not doing that particular area at the moment. I'm in college. Doing an electrical engineering course that requires me to use truth tables and logic gates.
Comment: It's not an area; it's format instructions!
Comment: @peterwhy I managed to do the truth tables incorrectly the first time. I redid them and now they are the same.
Answer: No; if 2 expressions are equal, their truth tables also yield the same result. Your simplification is correct so there must have been at least one error in your truth tables.
Comment: Okay, I just did the truth tables wrong...... After redoing them it seems to be correct. Thanks for the help
Comment: Yes what you say seems true and if so, the truth tables must be the same, so there must be an error in your truth table.
Comment: By the way, in the context of your question, you should say 'equal expressions', rather than 'equal equations'. The 2 sides of any equation are equal by definition, unless the equation is erroneous, in which case it's technically not an equation anymore.
Comment: I will take note of that.
Comment: The site doesn't like me using certain characters... Does (A'B+B'C)C' = A'BC'
Comment: Also CC just simplifies to C?
Comment: Edited my post and now it seems to register it normally.
Comment: Yes CC does simplify to C, but now you've edited your post, the new expression simplifies to  A'BC' + B'CC'
Comment: C & C' should always equal 0. Thus eliminating that entire term, I believe. Simplifying the equation to A'BC'. The problem is the truth table for A'BC' and the original equation are different ):
Comment: You're welcome.


Separate odd and even lines in a generator with python

Question: I have a huge data file (~2 G) that needs to be splitted into odd and even lines, processed separately and written into two files, I don't want to read the whole file into RAM, so I think a generator should be a suitable choice. In short I want do something like this:
lines = (l.strip() for l in open(inputfn))
oddlines = somefunction(getodds(lines))
evenlines = somefunction(getevens(lines))
outodds.write(oddlines)
outevens.write(evenlines)

Is this possible? Apparently indexing will not work:
In [75]: lines[::2]
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
/home/kaiyin/Phased/build37/chr22/segments/segment_1/<ipython-input-75-97be680d00e3> in <module>()
----> 1 lines[::2]

TypeError: 'generator' object is not subscriptable

Answer: def oddlines(fileobj):
    return (line for index,line in enumerate(fileobj) if index % 2)

def evenlines(fileobj):
    return (line for index,line in enumerate(fileobj) if not index % 2)

Note that this will require scanning the file twice, since these aren't designed to run in parallel. It does, however, lead to much less complex code. (Also note that an 'odd' line here is one with an index of 1,3,5 - which means that the first line is an 'even' line due to zero-indexing.)
As Ashwini notes, you could also use itertools.islice to do this.
Comment: This is nice, very easy to understand. Only the function names should be switched, since python index counts from 0. :D, thanks!
Answer: Use  itertools.islice to slice an iterator:
from itertools import islice
with open('filename') as f1, open('evens.txt', 'w') as f2:
    for line in islice(f1, 0, None, 2):
        f2.write(line)

with open('filename') as f1, open('odds.txt', 'w') as f2:
    for line in islice(f1, 1, None, 2):
        f2.write(line)

Answer: If you want to read the file just once, write a generator that wraps a file and returns a flag indicating whether the line is even or odd along with the actual line read from the file.
def oddeven(f, even=True):
    for line in f:
        yield even, line
        even = not even

Usage:
with open("infile.txt") as infile, \
     open("odd.txt", "w") as oddfile, \
     open ("even.txt", "w") as evenfile:
         for even, line in oddeven(infile):
            if even:
                evenfile.write(line)
            else:
                oddfile.write(line)

This can be further simplified by storing the output file objects in an indexable container:
with open("infile.txt") as infile, \
     open("odd.txt", "w") as oddfile, \
     open ("even.txt", "w") as evenfile:
         outfiles = (oddfile, evenfile)
         for even, line in oddeven(infile):
             outfiles[even].write(line)

Comment: I don't see any real benefit over using the `enumerate()` built-in straight, for example `for i, line in enumerate(infile): if i % 2 == 0: ...`


Is it possible to bind an event against a menu instead of a menu item in wxPython?

Question: Nothing to add
Answer: Do you want an event when your menu is opened? Use EVT_MENU_OPEN(func) (wxMenuEvent). But it's not in particular precise. As the documentation says, it is only sent once if you open a menu. For another event you have to close it and open another menu again. I.e in between, you can open other menus (by hovering other items in the menubar), and the event won't be sent again.
What do you need this for? Probably there is another way to do it, instead of listening for this kind of event.
If you want an event for all items of a menu, use EVT_MENU_RANGE(id1, id2, func) (it's using wxCommandEvent). All IDs starting from id1 up to and including id2 will be connected to the given event handler. Using a range instead of connecting each item separate will provide for better performance, as there are fewer items in the event-handler list.
Comment: Thanks a bunch this helps-sometimes I struggle to read the documentation.


Installed Ubuntu 12.04 I can't connect with internet. There isn't established a connection with the router

Question: From the USB installed Ubuntu 12.04 in my computer, with Windows XP in the other boot. From USB I have connection with internet without any problem. But from the computer there is the announcement no connection with internet.
Filled in IP address, Device MAC address, the password of the wireless connection. What did I forget?
Answer: You didn't forget any thing. It happened with me also. So you are not able to connect through wifi networks right? Have you tried connecting using a wired cable?
Actually it is the driver issue which is common to many people. What you've to do is:

Connect your system with wired internet connection
Execute following command in terminal to search and install for additional drivers:
<code>sudo jockey-gtk
</code>
It will search available drivers and tried to install the missing one.
When finished you'll get that your wireless drivers has been installed. Just re-start your system once.

Hope it helps you. Reply if you need any clarifications.


The inverse stereographic projection is a conformal map

Question: How can one establish that the inverse stereographic projection $f : \mathbb R^2 \to \mathbb R^3$ given by
$$
f(x,y):= \frac{(2x,2y,x^2+y^2-1)}{x^2+y^2+1}
$$
is a conformal (angle-preserving) map?
I wanted to show by a direct calculation that this map preserves angles. I considered two vectors $(x_1,y_1),(x_2,y_2) \in \mathbb R^2$ as well as two vectors $f(x_1,y_1),f(x_2,y_2) \in \mathbb R^3$.
If I denote $\theta$ to be the angle between $(x_1,y_1),(x_2,y_2)$ and $f(\theta)$ to be the angle between $f(x_1,y_1),f(x_2,y_2)$, then I want to establish $f(\theta)=\theta$.
First, I observe that $f(x,y)$ has unit magnitude:
\begin{align*}
\|f(x,y)\| &= \frac{\sqrt{(2x)^2+(2y)^2+(x^2+y^2-1)^2}}{x^2+y^2+1} \\
&= \frac{\sqrt{4(x^2+y^2)+((x^2+y^2)^2-2(x^2+y^2)+1)}}{x^2+y^2+1} \\
&= \frac{\sqrt{(x^2+y^2)^2+2(x^2+y^2)+1}}{x^2+y^2+1} \\
&= \frac{\sqrt{(x^2+y^2+1)^2}}{x^2+y^2+1} \\
&= 1,
\end{align*}
confirming that the inverse stereographic projection maps the plane back to the unit sphere except the north and south poles.
Well, now I have
\begin{align*}
\cos f(\theta) &= \frac{f(x_1,y_1)\cdot f(x_2,y_2)}{\|f(x_1,y_1)\|\|f(x_2,y_2)\|} \\
&= \frac{(2x_1,2y_1,x_1^2+y_1^2-1) \cdot(2x_2,2y_2,x_2^2+y_2^2-1)}{1 \cdot 1} \\
&= \frac{(2x_1)(2x_2)+(2y_1)(2y_2)+(x_1^2+y_1^2-1)(x_2^2+y_2^2-1)}{(x_1^2+y_1^2+1)(x_2^2+y_2^2+1)}
\end{align*}
and
\begin{align*}
\cos\theta &= \frac{(x_1,y_1)\cdot (x_2,y_2)}{\|(x_1,y_1)\|\|(x_2,y_2)\|} \\
&= \frac{x_1x_2+y_1y_2}{\sqrt{x_1^2+y_1^2}\sqrt{x_2^2+y_2^2}}.
\end{align*}
However, I am stuck on how to get my expressions of $\cos \theta$ and of $\cos f(\theta)$ to equal.
Comment: You need to compute the angle between *tangent vectors* to curves in the plane and correspondingly in the sphere, not the position vectors themselves. (In the plane you can use lines, but you need to find the tangent vectors to the images of those lines at the appropriate point of the sphere.) This argument can be made purely geometrically by observing that lines in the plane map to circles on the sphere and then doing a bit of geometry.
Comment: Would I need to find a general expression of a vector that is tangent to the unit sphere? I can only think of easy examples such as (0,1,0),(0,0,1) which are vectors in R3 that are tangent to the unit sphere at (1,0,0), with the angle between them being $\frac{\pi}2$.
Comment: You need to differentiate the map $f$ at an arbitrary point in directions $v_1$ and $v_2$.
Comment: Since I am dealing with $f(x,y)$ as a vector in $\mathbb R^3$, is it an option for me to parameterize $x,y,z$ in $t \in \mathbb R$ in two different ways (to represent the directions $v_1$ and $v_2$)? Then I might be able to write $f(x,y)$ somehow as $\bf{r}_1(t),\bf{r}_2(t)$ and differentiate both of them in $t$. Then I would find the angle between the two vectors $\bf{r}_1'(t),\bf{r}_2'(t)$.
Comment: Yes, that's the same as what I said. :)
Comment: According to Wikipedia, a tangent vector when written as a directional derivative concerns a parameterized vector at $t=0$:  $$(D_{v} f)(x) ~ \stackrel{\text{def}}{=} ~
  \left. \frac{\mathrm{d}}{\mathrm{d}{t}} [f(x + t v)] \right|_{t = 0}).$$ So should I really find the angle $f(\theta)$ between the two vectors $\mathbf r_1'(0),\mathbf r_2'(0)$ -- rather than $\mathbf r_1'(t),\mathbf r_2'(t)$ in general -- to compare with the angle $\theta$ between $(x_1,y_1),(x_2,y_2)$? In my own calculations right now, I can only get my angles $\theta,f(\theta)$ to be the same at $t=0$.
Comment: I'm still confused a little bit with my intuition here because something is also telling me that maybe I should compute the angle $f(\theta)$ for $\mathbf r_1'(t),\mathbf r_2'(t)$ for all $t \in \mathbb R$ in order to address all parameterized points $(x(t),y(t)) \in \mathbb R^2$, at least after applying transformations such as translation, rotation, dilation, inversion, etc.
Answer: Parametrizing curves and taking derivatives will work, but I prefer to work directly with the tangent spaces. In this case, the tangent space of your domain, which is $\mathbb{R}^2$, it actually $\mathbb{R}^2$ itself. If you want to show that your map $f$ is conformal, you need to show that for vectors $u$ and $v$ in the tangent space of $(x,y)\in\mathbb{R}$ there is a number $\lambda(x,y)$ so that $u\cdot v=\lambda(x,y) df_{(x,y)}(u)\cdot df_{(x,y)}(v)$. The notation here is that $df_{(x,y)}$ is the Jacobian of $f$ evaluated at $(x,y)$. Computing the Jacobian is not so hard: $$df_{(x,y)}=\frac{1}{(x^2+y^2+1)^2}\begin{bmatrix}
2(y^2-x^2+1)& -4xy\\
-4xy & 2(x^2-y^2+1) \\
-4x& -4y\end{bmatrix}$$
Disregard the coefficient in front of this matrix for now and label the entries $f_{i,x}$ and $f_{i,y}$. If $u=(u_1,u_2)$ and $v=(v_1,v_2)$, then evaluating $df_{(x,y)}$ on these vectors in $\mathbb{R}^2$ gives two vectors in $\mathbb{R}^3$ which we can write compactly as
$$df_{(x,y)}(u)=\frac{1}{(x^2+y^2+1)^2}(f_{i,x}u_1+f_{i,y}u_2)_{i=1}^3\quad \quad df_{(x,y)}(v)=\frac{1}{(x^2+y^2+1)^2}(f_{i,x}v_1+f_{i,y}v_2)_{i=1}^3$$
The dot product of these vectors is therefore the sum of the componentwise products
\begin{align}df_{(x,y)}(u)\cdot df_{(x,y)}(v)&=\left[\sum_{i=1}^3 f_{i,x}^2u_1v_1+f_{i,x}f_{i,y}(u_1v_2+u_2v_1)+f_{i,y}^2u_2v_2\right]\frac{1}{(x^2+y^2+1)^4}
\end{align}
But for clarity we will rearrange as
$$\left[u_1v_1\left(\sum_{i=1}^3 f_{i,x}^2\right)+u_2v_2\left(\sum_{i=1}^3f_{i,y}^2\right)+(u_1v_2+u_2v_1)\sum_{i=1}^3 f_{i,x}f_{i,y}\right]\frac{1}{(x^2+y^2+1)^4}$$
It takes some elbow grease, but you can show that $\sum_{i=1}^3 f_{i,x}^2=\sum_{i=1}^3 f_{i,y}^2=4(x^2+y^2+1)^2$ and also that $\sum_{i=1}^3 f_{i,x}f_{i,y}=0$. I will leave the former to you, for the latter:
\begin{align}
\sum_{i=1}^3 f_{i,x}f_{i,y}&=2(y^2-x^2+1)(-4xy)+(-4xy)2(x^2-y^2+1)+(-4x)(-4y)\\
&=(-8xy)\left[y^2-x^2+1+x^2-y^2+1\right]+16xy\\
&=-16xy+16xy=0
\end{align}
In conclusion, we see that $df_{(x,y)}(u)\cdot df_{(x,y)}(v)=\frac{4(u\cdot v)}{(x^2+y^2+1)^2}$. In particular, letting $\lambda(x,y)=\frac{4}{(x^2+y^2+1)^2}$, we see that $f$ is a conformal map. Note that the function $\lambda(x,y)$ is the stretching factor. Near the origin, thinking about the projection itself, we expect little to no stretching. Indeed, we see that near the origin $f$ is nearly the identity, only scaling by $4$. On the other hand, when $(x,y)$ is very far away from the origin, making $x^2+y^2$ large, $\lambda(x,y)$ is very small. This is because the projection is trying to squeeze all of these far away points in $\mathbb{R}^2$ near the north pole of $S^2$.


dequeueReusableHeaderFooterViewWithIdentifier not calling init method in ios9

Question: I am using a custom header cell, and while it works correctly in ios8, when I try it on an ios9 device the table calls dequeueReusableHeaderFooterViewWithIdentifier but it doesn't call the initWithFrame (or any init function that I tried) function, and so I just get a blank space for a header file.
Is there a change in how dequeueReusableHeaderFooterViewWithIdentifier works in ios9 that I should be awear of?
Thanks
Answer: I had the same problem with a subclass of UITableViewHeaderFooterView. Changing from initWithFrame to initWithReuseIdentifier solved the problem for me.
Answer: I could observe the following different behavior under iOS 8 and 9:
Under iOS 8

initWithReuseIdentifier: gets called first then
initWithFrame:

whereas under iOS 9
only

initWithReuseIdentifier:

gets called
Comment: I see the same behavior as you.
It's really strange and checking documentation doesn't say anything about this.
Maybe it's a bug on iOS 9.


What is happening when there is a conversion between types in VB.NET?

Question: I have to convert a VB.NET String variable into a type of SqlChars (a built-in VB.NET type).
The code I am using is:
Dim sqlPolyStr As String
sqlPolyStr = "POLYGON((" & ptsStr & "))"
Dim sqlChrsPoly As New SqlChars(sqlPolyStr)

The code works fine, I just wondered if there is a name for the process of conversion between types that is taking place?
Answer: While I know what you're talking about, this isn't a great example because that's not quite converting the object, it is using a constructor and that constructor is doing stuff in the background.
A better example is dim a as integer = cType("12345", integer) This process is known as typecasting and more details can be found here. My example is still poor because in vb.net you can still do dim a as integer = "12345" but it's a start for you.
The example you gave uses the constructor. Whoever programmed "SqlChars" made a constructor that accepts type String by making a sub such as
Public Sub New(ByVal str as string)
   ' DO something here with the string to make a SqlChars object
End Sub

Comment: Thanks. I was just confused about why a direct conversion from String to SqlChars wasn't working but the example I have given does and wanted to research more into the subject but didn't really know where to begin.


A faster way to evaluate 2D-array items than nested for loops?

Question: I'm using python 2.7
I have a 2-dimensional array that is several hundred elements on each axis. Each element is either '0', or '255' I need to look at each element and write a '0' or '1' into a different array that has the same dimensions. Currently I have a nested for-loop structure iterating over the rows and columns.
This is turning out to be really, really slow. What is a better implementation? What if I multiplied the matrix by a constant 1/255. This would keep the zeros as zeros, and convert the 255 to '1'. but this is just trading the loops for an enormous number of multiplies, which probably has its own speed issues.
Thoughts?
Comment: Sounds like you need [`Numpy.ndarray`](http://docs.scipy.org/doc/numpy/reference/generated/numpy.ndarray.html) here.
Comment: What do you do with the new array? Is there any way around needing `1`s in it?
Comment: Multiplying by 1./255 is not a brilliant idea. Firstly you'd still have to do the copying if you want to keep the old array and you'd change from `int` to `float`
Comment: What do you actually have? A list of lists (`foo[y][x]`), a flat list or array.array (`foo[y * w + x]`), a dict with tuple keys (`foo[x,y]`)? For a flat representation, `[int(bool(x)) for x in foo]` would do the trick.
Comment: can you show us your code? and several hundreds of elements in two dimensions, that should take on  milliseconds to execute? so i dont get the "slowness" ?
Answer: I'd also use numpy.array for fast array manipulation, here's an example :
<code>import numpy as np
# Create an example array of shape (100, 100) filled with either 0 or 255
a = 255*np.random.randint(2, size=10000).reshape(100,100)

# Transform it as you want
1*(a==255)
</code>


Why my calculations are wrong? Java reverse int problem

Question: Here is my function that suppose to reverse and return giver integer:
public static int reverse(int x) {
    List<Integer> digits = new ArrayList<>();
    int result = 0, count = 0;

    while(x != 0)   {
        digits.add(x % 10);
        x /= 10;
        count++;
    }
    System.out.println(digits);
    int i = 0;
    while(count != 0) {
        result += digits.get(i) * (int) Math.pow(10, count - 1);
        System.out.printf("result: %d i: %d, count: %d - ", result,  i, count);
        System.out.printf("%d * %d\n", digits.get(i), (int) Math.pow(10, count - 1));
        count--;
        i++;
    }

    return result;
}

I encountered a problem. For example when I pass value of 1534236469 this is what happens:
    result: 410065408 i: 0, count: 10 - 9 * 1000000000
    .
    .
    .
    1056389759

Why this is happening?
Also all tips on making this function better are welcome.
Comment: The problem is with `9 * 1000000000` which goes beyond the maximum value an `int` variable can hold. When you assign a bigger value than the maximum allowed value, the value gets converted into a value from the other end i.e. `Integer.MAX_VALUE + 1` becomes `Integer.MIN_VALUE`.
Comment: General debugging hint: You have lots of debug output. Does it not help you? When is the output not as you expect.

Switching to string representation, reverting, and switching to integer again might be another approach. `Integer.toString(int,int)` and `Integer(String)` might help.
Answer:
Also all tips on making this function better are welcome.

A simple implementation can be as follows:
public class Main {
    public static void main(String[] args) {
        int x = 123456789;
        int y = reverse(x);
        System.out.println(x);
        System.out.println(y);
    }

    public static int reverse(int x) {
        return Integer.parseInt(new StringBuilder(String.valueOf(x)).reverse().toString());
    }
}

Output:
123456789
987654321

Also, as already mentioned in the comment, when you assign a value bigger than the maximum allowed value to an int variable, the value gets converted into a value from the other end i.e. Integer.MAX_VALUE + 1 becomes Integer.MIN_VALUE. Therefore, for an integer like 1534236469 whose reverse is bigger than an int variable can hold, you should convert the reverse into a long value as shown below:
public class Main {
    public static void main(String[] args) {
        int x = 1534236469;
        long y = reverse(x);
        System.out.println(x);
        System.out.println(y);
    }

    public static long reverse(int x) {
        return Long.parseLong(new StringBuilder(String.valueOf(x)).reverse().toString());
    }
}

Output:
1534236469
9646324351

Comment: I see this an hacky way to do things. But well- it just does the work.
Answer: Marcin, you can implement your reverse method like below,
public static long reverse(int x) {
    long reverseDigit = 0;
    while (x != 0) {
        reverseDigit = reverseDigit * 10 + (x % 10);
        x /= 10;
    }
    return reverseDigit;
}

I hope this helps.
Answer: A more proper way to reverse an integer would be:
int reverse(int n) {
    int reversed = 0;
    Boolean isNegative = n < 0;
    n = Math.abs(n);

    while(n > 0) {
        reversed = reversed * 10 + (n % 10);
        n /= 10;
    }

    if (isNegative)
        reversed *= -1;

    return reversed;
}

Answer: I think the problem could be, that the reverse of an int ist not always an int.
2147483647 is max int so,
9646324351
is too big and 1534236469 has no chance


Call only parent method

Question: Lets imagine example - we have three classes
class A {

  protected function render()
  {
     echo 'class A';
  }

  protected show_error()
  {
     $this->render();
     exit('error');
  }

}

class B extends A {
   protected function render()
   {
     echo 'class B';
     parent::render();
   }

}

class C extends B {
{
}

So I create some code
c = new C();
c->show_error();

Output will be
class B
class A
error

Question is - why "show_error" method call "render" method from class B ?
Why just dont call only "render" from class A itself?
Could somebody explain this? And is it possible to do that in "my way"?
Thanks!
Comment: Yeah u are right, cause using $this-> makes this behavior, so using "self" do the trick! Thanks
Answer: This is basic OOP
class A {

  protected function render()
  {
     echo 'class A';
  }

  public function show_error()
  {
     self::render(); // this is what you're after
     exit('error');
  }

}

The reason it's calling B::render() is because C extends B and B reimplements render()
Also, show_error() should be public. otherwise you'll get an error.
Comment: I am working in develop mode and all error messages on but there is no errors :)

Call only parent method


Haskell - Using State with Alternative

Question: I have a datatype that looks like the following:
type Parser a = ExceptT ParseError (State [Token]) a

As well as state manipulation functions:
consumeToken :: Parser Token
consumeToken = do
    toks <- lift get
    if null toks
        then throwE OutOfTokensError
        else
            do
                lift $ put (tail toks)
                return $ head toks

peekToken :: Parser Token
peekToken = do
    toks <- lift get
    if null toks
        then throwE OutOfTokensError
        else
            do
                return $ head toks

I'm trying to use these functions to help validate production rules in a grammar:
charList :: Parser CharList
charList =
    (return CharListCharacter <*> isToken (Character "<char>") <*> charList)
    <|> (return CharListSpace <*> isToken (Space " ") <*> charList)
    <|> (return EmptyCharList)

It seems that isToken needs to consume the current token (using consumeToken) so that the recursive calls to charList then deal with the following token. However, doing so means that the alternative cases will not start from the same token as the first case.
Is there a standard way to deal with this problem?
Comment: Monadic parsers in Haskell are typically either non-deterministic like [ReadP](https://hackage.haskell.org/package/base-22.214.171.124/docs/Text-ParserCombinators-ReadP.html) (using the list monad to capture all possible parse states and eliminate them as they fail) or backtracking like [Megaparsec](https://hackage.haskell.org/package/megaparsec) (using explicit `try`s in front of sub-parsers that may consume and fail), as Bartek Banachewicz points out. The most efficient alternative is to model your parser after an LL(1) grammar when possible.
Comment: I don't think there's anything ready-made for that. You could, however, observe how [Parsec solves this particular problem](https://hackage.haskell.org/package/parsec-22.214.171.124/docs/src/Text.Parsec.Prim.html#try) (scroll up for explanation). IIRC the main reason it even exists there is because it's a potentially costly operation involving backtracking a lot of data.
Answer: Following the advice from the comments, I remodeled my parser to take advantage of the fact that my grammar is LL(1). Doing this meant I had no need for Alternative.
This is the final version of the charList function (with isToken using consumeToken):
charList :: Parser CharList
charList = do
    tok <- peekToken
    case tok of Character _ -> return CharListCharacter <*> isToken (Character "<char>") <*> charList
                Space _     -> return CharListSpace <*> isToken (Space " ") <*> charList
                _           -> return EmptyCharList

Haskell - Using State with Alternative


MYSQL SLEEP inside EXISTS block

Question: When I execute this SQL code on a SQL server:
SELECT SLEEP(3);

The server sleeps for 3 seconds. But, when I execute this code:
SELECT * FROM costumers WHERE EXISTS(SELECT SLEEP(3));

The server immediately prints the table 'costumers' without waiting for 3 seconds... Is there an explanation for the SLEEP function just returning without waiting for the specified duration when it is called from an EXISTS block? The same happens with the BENCHMARK function in this code:
SELECT * FROM costumers WHERE EXISTS(SELECT BENCHMARK(100, MD5(1)))

I need to execute the 'SLEEP' function in this specific structure because this is used in a SQL injection exercise, more precisely a blind SQL injection exercise.
Also, if you know of another way to write a MYSQL statement which make the server wait, that would be helpful.
Comment: Sub-query probably optimized as always "TRUE", and skipped.
Answer: The query optimizer apparently determines that SELECT SLEEP(3) always returns TRUE, so it removes the code.
This query sleeps:
SELECT * FROM table1 WHERE EXISTS(SELECT SLEEP(3) UNION SELECT 1);

The union is apparently too complex for the MySQL optimizer to figure out, so it executes it. In fact, using EXPLAIN on this query takes 3 seconds -- it realizes that the subquery doesn't depend on any tables, so it executes it while determining the query plan.
Answer: I think you are going to be stuck with a
SELECT SLEEP(3); SELECT * FROM customers;

combo.

MYSQL SLEEP inside EXISTS block


How to remove the TWM desktop environment?

Question: I found the user interface of the TWM desktop environment boring and hard to use. How can I remove it?
Comment: How did you install it?
Comment: `sudo apt-get remove twm`
Comment: These two TWM and Ubuntu(default)were installed by default
Answer: <code>sudo apt-get remove twm
</code>
This worked.


ZLIB inflateMark. What application uses this function?

Question: I am looking for examples and software applications that use inflateMark.
Answer: Here's one:
<code>/* gzindex -- build an index for a gzip file and then test it
 * Copyright (C) 2009 Mark Adler
 * For conditions of distribution and use, see copyright notice in zlib.h
 * Version 1.0  20 December 2009  Mark Adler
 */

/* This code demonstrates the use of new capabilities in zlib 220.127.116.11 or later
   to create and use a random access index.  It is called with the name of a
   gzip file on the command line.  That file is then indexed and the index is
   tested by accessing the blocks in reverse order. */

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <assert.h>
#include "zlib.h"

#define CHUNK 1024      /* distance between random access entry points in the
                           uncompressed data */

#define local static

/* data structure for each random access entry point */
struct point {
    off_t head;         /* starting bit of coded header in input stream (could
                           replace with the actual header bits -- the average
                           dynamic block header length is about 80 bytes), or
                           -1 if not a coded entry point */
    off_t start;        /* starting bit of compressed data in input stream --
                           for a coded block, this may be the start of a code
                           that generates bytes before the entry point, and so
                           those bytes need to be decoded and discarded to get
                           to the entry point */
    unsigned offset;    /* offset of the entry point in output data for a coded
                           block (i.e. the output bytes to discard), or number
                           of bytes remaining in stored block, or zero for an
                           entry at the start of a block if head == -1 */
    int last;           /* true if this access point is in the last block --
                           needed for stored header construction */
};

/* maximum dynamic block header span is less than this -- this also provides
   enough space to read six bytes in and produce 258 bytes out */
#define MAXHEAD 289

/* set up the inflate state and the file pointer to decompress with the output
   starting at entry, where strm is the state to set (assumed to be already
   initialized for raw inflation), the deflate stream is in file gz starting
   at offset, index is the list of index points, entry is the element of index,
   and sofar is the uncompressed data from the beginning of the stream at least
   as far as the entry point -- inflate_entry() will return Z_OK on success, or
   zlib error code on failure, where Z_ERRNO is an error reading or seeking the
   file gz */
local int inflate_entry(z_stream *strm, FILE *gz, off_t offset,
                        struct point *index, size_t entry,
                        unsigned char *sofar)
{
    int ret;
    unsigned len;
    size_t edge;
    struct point *point;
    unsigned char buf[MAXHEAD];

    /* prepare the inflate stream to start anew (assume it's set up for raw) */
    ret = inflateReset(strm);
    if (ret != Z_OK)
        return ret;

    /* set the dictionary history for decompression */
    point = index + entry;
    edge = CHUNK * entry;
    if (point->head != -1)          /* back up for coded block */
        edge -= point->offset;
    len = edge < 32768U ? (unsigned)edge : 32768U;
    ret = inflateSetDictionary(strm, sofar + edge - len, len);
    if (ret != Z_OK)
        return ret;

    /* set up the inflate state and file pointer to start inflation at the
       entry point */
    if (point->head == -1)
        if (point->offset == 0) {
            /* entry point is the start of a deflate block (first block) */
            ret = fseeko(gz, offset + (point->start >> 3), SEEK_SET);
            if (ret)
                return Z_ERRNO;
            ret = fread(buf, 1, 1, gz);
            if (ret < 0)
                return Z_ERRNO;
            if (ret == 0)
                return Z_BUF_ERROR;
            ret = inflatePrime(strm, 8 - ((int)(point->start) & 7),
                               buf[0] >> ((int)(point->start) & 7));
            if (ret != Z_OK)
                return ret;
        }
        else {
            /* entry point is inside a stored block -- build a stored block
               header to start off with the bytes left in that block at the
               entry point */
            buf[0] = (unsigned char)(point->last ? 1 : 0);
            buf[1] = (unsigned char)(point->offset);
            buf[2] = (unsigned char)(point->offset >> 8);
            buf[3] = (unsigned char)(~(point->offset));
            buf[4] = (unsigned char)(~(point->offset) >> 8);
            strm->avail_in = 5;
            strm->next_in = buf;
            strm->avail_out = 0;
            strm->next_out = buf + 5;
            ret = inflate(strm, Z_NO_FLUSH);
            assert(ret != Z_STREAM_ERROR);
            if (ret == Z_DATA_ERROR || ret == Z_MEM_ERROR)
                return ret;

            /* position input file at next byte to read */
            ret = fseeko(gz, offset + (point->start >> 3), SEEK_SET);
            if (ret)
                return Z_ERRNO;
        }
    else {
        /* entry point is inside a coded block -- run the header through
           inflate first */
        ret = fseeko(gz, offset + (point->head >> 3), SEEK_SET);
        if (ret)
            return Z_ERRNO;
        ret = fread(buf, 1, MAXHEAD, gz);
        if (ret < 0)
            return Z_ERRNO;
        if (ret == 0)
            return Z_BUF_ERROR;
        strm->avail_in = (unsigned)ret - 1;
        strm->next_in = buf + 1;
        ret = inflatePrime(strm, 8 - ((int)(point->head) & 7),
                           buf[0] >> ((int)(point->head) & 7));
        if (ret != Z_OK)
            return ret;
        strm->avail_out = 0;
        strm->next_out = buf + MAXHEAD;
        ret = inflate(strm, Z_TREES);
        assert(ret != Z_STREAM_ERROR);
        if (ret == Z_DATA_ERROR || ret == Z_MEM_ERROR)
            return ret;
        if ((strm->data_type & 256) != 256)
            return Z_DATA_ERROR;
        ret = inflatePrime(strm, -1, 0);    /* discard remaining bits */
        if (ret != Z_OK)
            return ret;

        /* set up to inflate, loading the initial 1..8 bits */
        ret = fseeko(gz, offset + (point->start >> 3), SEEK_SET);
        if (ret)
            return Z_ERRNO;
        ret = fread(buf, 1, 1, gz);
        if (ret < 0)
            return Z_ERRNO;
        if (ret == 0)
            return Z_BUF_ERROR;
        ret = inflatePrime(strm, 8 - ((int)(point->start) & 7),
                           buf[0] >> ((int)(point->start) & 7));
        if (ret != Z_OK)
            return ret;

        /* discard extra output bytes from this code, if any, to get to the
           entry point (max length/distance pair is six bytes) -- move file
           pointer back to first unused byte */
        if (point->offset) {
            ret = fread(buf, 1, 6, gz);
            if (ret < 0)
                return Z_ERRNO;
            strm->avail_in = (unsigned)ret;
            strm->next_in = buf;
            strm->avail_out = point->offset;
            strm->next_out = buf + 6;
            ret = inflate(strm, Z_NO_FLUSH);
            assert(ret != Z_STREAM_ERROR);
            if (ret == Z_DATA_ERROR || ret == Z_MEM_ERROR)
                return ret;
            if (strm->avail_out != 0)
                return Z_DATA_ERROR;
            ret = fseeko(gz, -(long)(strm->avail_in), SEEK_CUR);
            if (ret)
                return Z_ERRNO;
        }
    }

    /* return with strm and next byte from gz prepared to decompress starting
       at the requested entry point (reset buffers to make user sets them) */
    strm->avail_in = 0;
    strm->next_in = NULL;
    strm->avail_out = 0;
    strm->next_out = NULL;
    return Z_OK;
}

/* index a raw deflate stream from the file gz starting at offset, and return
   an index with number entries -- the uncompressed data is also returned in
   data[0..length-1] for use in dictionaries and for comparison */
local int inflate_index(FILE *gz, off_t offset, struct point **index,
                        size_t *number, unsigned char **data, size_t *length)
{
    int ret, last;
    size_t size, num, max, n;
    off_t pos, head, here;
    long left, back;
    struct point *list, *list2;
    unsigned char *out, *out2;
    z_stream strm;
    unsigned char in[16384];

    /* position input file */
    ret = fseeko(gz, offset, SEEK_SET);
    if (ret)
        return Z_ERRNO;

    /* allocate output space to save the data, grow as needed later */
    size = 131072L;
    out = malloc(size);
    if (out == NULL)
        return Z_MEM_ERROR;

    /* allocate space for index list -- grow as needed later */
    max = 512;
    list = malloc(max * sizeof(struct point));
    if (list == NULL) {
        free(out);
        return Z_MEM_ERROR;
    }

    /* allocate inflate state for raw decoding */
    strm.zalloc = Z_NULL;
    strm.zfree = Z_NULL;
    strm.opaque = Z_NULL;
    strm.avail_in = 0;
    strm.next_in = Z_NULL;
    ret = inflateInit2(&strm, -15);
    if (ret != Z_OK) {
        free(list);
        free(out);
        return ret;
    }

    /* make first index entry to simply start decompressing at beginning */
    list[0].head = -1;
    list[0].start = 0;
    list[0].offset = 0;
    list[0].last = 0;      /* doesn't matter since not inside stored */
    num = 1;

    /* inflate the input data, CHUNK output bytes at a time, saving enough
       information to randomly access the input data */
    pos = head = 0;
    last = 0;
    strm.next_out = out;
    do {
        /* if needed, allocate more output space */
        if ((size_t)(strm.next_out - out) > size - CHUNK) {
            size <<= 1;
            if (size <= 0 || (out2 = realloc(out, size)) == NULL) {
                (void)inflateEnd(&strm);
                free(list);
                free(out);
                return Z_MEM_ERROR;
            }
            strm.next_out = out2 + (strm.next_out - out);
            out = out2;
        }

        /* decompress CHUNK more output bytes */
        strm.avail_out = CHUNK;

        /* for each output CHUNK, feed input data until there is no progress */
        do {
            /* if needed, get more input data */
            if (strm.avail_in == 0) {
                strm.avail_in = fread(in, 1, sizeof(in), gz);
                if (ferror(gz)) {
                    (void)inflateEnd(&strm);
                    free(list);
                    free(out);
                    return Z_ERRNO;
                }
                /* if we get to EOF here, then Houston, we have a problem */
                if (strm.avail_in == 0) {
                    (void)inflateEnd(&strm);
                    free(list);
                    free(out);
                    return Z_DATA_ERROR;
                }
                pos += strm.avail_in;
                strm.next_in = in;
            }

            /* inflate available input data to fill block, but return early if
               we get to a block boundary */
            ret = inflate(&strm, Z_BLOCK);
            assert(ret != Z_STREAM_ERROR);  /* state not clobbered */
            if (ret == Z_DATA_ERROR || ret == Z_MEM_ERROR) {
                (void)inflateEnd(&strm);
                free(list);
                free(out);
                return ret;
            }

            /* if at a block boundary, note the location of the header */
            if (strm.data_type & 128) {
                head = ((pos - strm.avail_in) << 3) - (strm.data_type & 63);
                last = strm.data_type & 64; /* true at end of last block */
            }
        } while (strm.avail_out != 0 && !last);

        /* if got to end of stream, no more entry points needed */
        if (last)
            break;

        /* filled up a block and there's more -- make a new entry */
        if (num == max) {       /* make more room in list if needed */
            max <<= 1;
            n = max * sizeof(struct point);
            if (n / max != sizeof(struct point) ||
                    (list2 = realloc(list, n)) == NULL) {
                (void)inflateEnd(&strm);
                free(list);
                free(out);
                return Z_MEM_ERROR;
            }
            list = list2;
        }
        here = ((pos - strm.avail_in) << 3) - (strm.data_type & 63);
        left = inflateMark(&strm);
        back = left >> 16;
        left &= 0xffff;
        if ((back & 0xffff) == 0xffff) {    /* signed shift not portable */
            list[num].head = -1;
            list[num].start = here;
        }
        else {
            list[num].head = head;
            list[num].start = here - back;
        }
        list[num].offset = left;
        list[num].last = strm.data_type & 64;
        num++;
    } while (1);
    (void)inflateEnd(&strm);

    /* return results */
    *index = list;
    *number = num;
    if (data == NULL || length == NULL)
        free(out);
    else {
        *data = out;
        *length = strm.next_out - out;
    }
    return Z_OK;
}

/* return the offset of the start of deflate data -- return 0 on failure */
local off_t raw_start(FILE *gz)
{
    int ret;
    off_t pos = 0;
    z_stream strm;
    unsigned char in[512];

    /* set up to decode zlib or gzip header */
    strm.zalloc = Z_NULL;
    strm.zfree = Z_NULL;
    strm.opaque = Z_NULL;
    strm.avail_in = 0;
    strm.next_in = Z_NULL;
    ret = inflateInit2(&strm, 47);
    if (ret != Z_OK)
        return 0;

    /* decode header */
    rewind(gz);
    strm.avail_out = 0;
    strm.next_out = in;
    do {
        if (strm.avail_in == 0) {
            ret = fread(in, 1, sizeof(in), gz);
            if (ret <= 0) {
                (void)inflateEnd(&strm);
                return 0;
            }
            pos += ret;
            strm.avail_in = (unsigned)ret;
            strm.next_in = in;
            ret = inflate(&strm, Z_BLOCK);
            assert(ret != Z_STREAM_ERROR);
            if (ret == Z_DATA_ERROR || ret == Z_MEM_ERROR) {
                (void)inflateEnd(&strm);
                return 0;
            }
        }
    } while ((strm.data_type & 128) != 128);
    (void)inflateEnd(&strm);
    return pos - strm.avail_in;
}

/* create an index for the file on the command line and test it */
int main(int argc, char **argv)
{
    int ret;
    FILE *gz;
    off_t start;
    struct point *index = NULL;
    unsigned char *data = NULL;
    size_t n, number = 0, length = 0;
    z_stream strm;
    unsigned char in[512], out[CHUNK];

    /* check zlib version */
    if (ZLIB_VERNUM < 0x1234 || ZLIB_VERNUM == 0x123f) {
        fputs("gzindex needs zlib version 188.8.131.52 or later", stderr);
        return 1;
    }

    /* set up input file, find start of deflate stream */
    if (argc == 1) {
        fputs("Usage: gzindex <gzipfile>\n", stderr);
        return 1;
    }
    gz = fopen(argv[1], "rb");
    if (gz == NULL) {
        fprintf(stderr, "could not open %s\n", argv[1]);
        return 1;
    }
    start = raw_start(gz);

    /* create index */
    ret = inflate_index(gz, start, &index, &number, &data, &length);
    if (ret != Z_OK) {
        fprintf(stderr, "indexing error %d\n", ret);
        return 1;
    }

    /* set up raw inflate state for accessing entry points */
    strm.zalloc = Z_NULL;
    strm.zfree = Z_NULL;
    strm.opaque = Z_NULL;
    strm.avail_in = 0;
    strm.next_in = Z_NULL;
    ret = inflateInit2(&strm, -15);
    if (ret != Z_OK) {
        free(data);
        free(index);
        fprintf(stderr, "memory error %d\n", ret);
        return 1;
    }

    /* test index in reverse order */
    n = number;
    while (n) {
        n--;

        /* go to entry point n */
        ret = inflate_entry(&strm, gz, start, index, n, data);
        if (ret != Z_OK) {
            (void)inflateEnd(&strm);
            free(data);
            free(index);
            fprintf(stderr, "entry error %d\n", ret);
            return 1;
        }

        /* decompress CHUNK output bytes from here, or what's left */
        strm.avail_out = sizeof(out);
        strm.next_out = out;
        do {
            ret = fread(in, 1, sizeof(in), gz);
            if (ret < 0) {
                (void)inflateEnd(&strm);
                free(data);
                free(index);
                fprintf(stderr, "read error %d\n", errno);
                return 1;
            }
            strm.avail_in = (unsigned)ret;
            strm.next_in = in;
            ret = inflate(&strm, Z_NO_FLUSH);
            assert(ret != Z_STREAM_ERROR);
            if (ret == Z_DATA_ERROR || ret == Z_MEM_ERROR) {
                (void)inflateEnd(&strm);
                free(data);
                free(index);
                fprintf(stderr, "decompression error %d\n", ret);
                return 1;
            }
        } while (strm.avail_out != 0 && ret != Z_STREAM_END);

        /* verify the decompressed data */
        if ((n == number - 1 &&
                sizeof(out) - strm.avail_out != length - n * CHUNK) ||
            (n < number - 1 && strm.avail_out != 0)) {
            (void)inflateEnd(&strm);
            free(data);
            free(index);
            fprintf(stderr, "decompression shortfall at entry %lu\n", n);
            return 1;
        }
        if (memcmp(out, data + n * CHUNK, sizeof(out) - strm.avail_out) != 0) {
            (void)inflateEnd(&strm);
            free(data);
            free(index);
            fprintf(stderr, "compare error for entry %lu\n", n);
            return 1;
        }
    }

    /* clean up */
    (void)inflateEnd(&strm);
    free(data);
    free(index);
    fprintf(stderr, "%lu entry points generated and successfully tested\n",
            number);
    return 0;
}
</code>


Images not loading, IE6 to IE9

Question: I'm having two problems:

My website is not forwarding from index.html on IE6 - IE9
Images are not loading on any page IE6 - IE9

For the first problem, if you go to http://www.matthallock.com/ the website cycles endlessly regardless if I link it to a file (e.g., /hamlet.html) or directly (e.g., http://www.matthallock.com/hamlet.html)
The second problem, more troublesome, is images appearing blank on Internet Explorer. Further, the problem appears to be with the jQuery, as the fixed sidebar also does not work.
I tried the  degrade for the lazy load, but that doesn't solve the problem. Curiously, if you go to my blog at blog.matthallock.com, there is no issue and the styling of the sidebar appears correct.
Appearance and functionality works properly in Chrome, Safari, and Firefox.
Any help is much appreciated.
Comment: I suggest dropping support for IE6 (and probably IE7 too). I know that doesn't answer the problem, but it will solve a lot of other problems for you!
Answer: <META HTTP-EQUIV="refresh" CONTENT="0;http://www.matthallock.com/hamlet.html">

You need to specify url= before actually giving the URL, otherwise it just reloads the current page.
$("img").lazyload({
    effect : "fadeIn",
    /*
      appear : function(elements_left, settings) {
        console.log("appear");
        console.log(elements_left);
        //console.log(this, elements_left, settings);
      },
      load : function(elements_left, settings) {
        console.log("load");
        console.log(elements_left);
        //console.log(this, elements_left, settings);
      }
    */
});

Your browser console gives you this one for free: "Expected identifier, string or number" - IE does not like trailing commas in object definitions, and because of your multiline comment your resulting code is:
$("img").lazyload({effect:"fadeIn",});

See that extra comma? Remove it, and everything magically works.
Comment: +1. yep. that's an IE-specific thing. (in fact IE is technically correct in enforcing it, according to the language specs; the other browsers are being lax in allowing the trailing comma)
Comment: Thank you so much guys, Stack to the rescue as usual.

Images not loading, IE6 to IE9