text:
Q: Let $S = \{(a,b] \cup [−b,−a) : a < b\text{ are real numbers}\}$. Show that $\sigma(S)$ is smaller than the Borel $\sigma$-algebra of $\mathbb R$.
Let $S = \{(a,b] \cup [−b,−a) : a < b\text{ are real numbers}\}$. Show that $\sigma(S)$ is smaller than the Borel $\sigma$-algebra of $\mathbb R$.

How can I find a Borel set which is not in the sigma algebra generated by $S$?
If not that, can I use any cardinality argument?
Kindly help.

A: Hint: Any (nonempty) union or intersection of elements of this $S$ contains both positive and negative reals. This is true of the generating "double intervals" which are symmetrically chosen unions of two half intervals. So when these are combined to fill out the generated sigma algebra, one only gets sets having both positive and negative reals in them (or the empty set). So it would seem one could not generate say the interval $(1,2).$
Added: In a comment to Asaf's answer the OP has asked for clarification. Call any set $Y$ of reals "symmetric"
 provided $y \in Y$ iff $ -y \in Y.$ Note now that each generator of your sigma algebra $S$ is symmetric in this sense. Let $T$ denote the subset of $S$ consisting of its symmetric sets. Show that $T$ is closed under complement, under countable union, and under countable intersection. [These are fairly straightforward to show.] Then $T$ is a sigma algebra, and contains all the generating sets of $S$, and you can conclude that $T=S,$ so that in fact each subset in $S$ is symmetric. Then since $(1,2)$ is not symmetric it does not lie in the sigma algebra $S$.

A: Right off the bat, you can't use cardinality arguments. There are only $2^{\aleph_0}$ Borel sets, and there are clearly $2^{\aleph_0}$ sets in $S$ as well.
For a more explicit set, note that if you could have generated all the open intervals, then you could have generated all the Borel sets. So it suffices to try and find an open interval that cannot be generated by these sets; or alternatively note that you can generate every open interval and disprove that statement.
Note that the elements in $S$ are all symmetric around $0$. What happened when you intersect things which are symmetric around $0$, or take unions of them?
Now find a counterexample.

A: Let $\Sigma = \{ A \subset \mathbb{R}| x \in A \Rightarrow -x \in A \}$. It is easy to check that $\Sigma$ is a $\sigma$-algebra.
It is clear that $S \subset \Sigma$, hence $\sigma(S) \subset \Sigma$.
It is also clear that $\sigma(S) \subset {\cal B}$.
We have $\{1\} \in {\cal B}$ and $\{1\} \notin \Sigma$, so we see that
$\sigma(S) \neq {\cal B}$.


text:
Q: How do I import the D3 library into my project file structure? I am trying to not rely on the basic code as follows in my file:
<script src="//d3js.org/d3.v3.min.js"></script>

I am trying to include the d3 library in my file structure. I have created a "libs" file in my project. Here is the link to the page to download the d3 library: https://github.com/d3/d3 My question is after downloading the necessary files from github, do I simply create a d3 folder in my libs folder and place the files there? If so, do I reference a specific file or just the folder?

A: You must include your local copy of D3 like so:
<script src="libs/d3.v3.min.js"></script>

No need to create a separate folder if you'll use just D3. If you need other dependencies use like this:
    <script src="libs/d3/d3.min.js" charset="utf-8"></script>
    <script src="libs/d3/topojson.v1.min.js"></script>
    <script src="libs/d3/d3-queue.v2.min.js"></script>

A: There are a few different ways of importing other people's code. You could, as you suggested, just download the latest release and copy the d3.js or d3.min.js into a lib/ directory, then import it like so:
<script src="lib/d3.min.js"></script>

Alternatively, if you're using a package manager like npm or bower, you could just install it using that, as recommended in the README. There's also a resource showing how you could use a bundler like Rollup to package D3 with all of your other libraries.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to implement a LinkedList from scratch that only accepts String Value? I am new to data structure and now want to implement a LinkedList from scratch  that only accepts String values. How should i do it?

A: Ok, I am not providing you with the code but a few tips  which should help you get started.
Structure of a linked list is usually like
nd1 -> nd2 -> nd3-> null, where nd is a node.
a. Create a Node class with attributes String value, Node next. Thus it would look like.
class Node{
String value;//place holder for your String
Node next;//pointer to your next node.
}

b. To add a new node, you need following method addNode(Node nd) .You will need to iterate till the last node of your list and add the nd after that. i.e last.next=nd;
Similarly you can go ahead and implemene tyour own methods.


text:
Q: Query whether file exists in different application I have I have two applications. I have a menu button on one application (service A) that is used to trigger an action in a different service (service B).
I want to make the menu item (service A) visible only if a file is present in service B.
Is there a clean mechanism for achieving this, rather than using absolute paths with File?

A: There are two ways to achieve this:

*

*Use remote binding across services. You'd need to define an interface using AIDL and then invoke methods on the interface to delegate the responsibility for checking if the file exists to service B.

*Define a ContentProvider in the application that "owns" the file and query the content provider to see whether the file exists or not.


text:
Q: Como puedo alinear dos  dentro de un  Estoy haciendo una firma para Outlook usando una tabla HTML, la cuestion es que estoy tratando de posicionar dos
 dentro de un  y que queden alineados.
Probé usando un display:flex pero Outlook no me reconoce esa propiedad.
¿Ideas para solucionarlo? ¿Que otra propiedad debería usar?
Dejo abajo el código actual por las dudas, los  en cuestión tienen una class="nomYdir" para identificarlos mas rápido:

Hola como estas

Dr. Atilio
                Silvio Maculus

+54
                1141192

maculus@gmail.com

                Parana
                600
                3° Piso Of. 8

                C.A.B.A (1017)

                Tel/Fax: 4373-6340/6418 - 4375-5499

                Panamericana Ramal Pilar Km
                50.5

                1er Piso Of.1008.
 Pilar, Bs.As (1629)

                Tel: 0230-437456

                Este E-mail es
                confidencial y
                puede tener informacion amparada por el
                secreto profesional. No debera
                copiar o divulgar su contenido a ninguna persona. Si usted ha recibido este E-,ail por error,
                porfavor informenoslo por este medio y eliminelo de su sistema. Muchas gracias.

                This message is
                confidential and
                contains priviliged information legalle exempt from disclosure. You should not copy this message or
                disclose it to anyone. If you have recieved it by mistake please let us know by e-mail immeadiately
                and delete it from your computer. Thank you very much.

A: He modificado tú código.
Verifiquemos si ese es el resultado que necesitas.

<!DOCTYPE html>

  <title>Bootstrap Example</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">

Hola como estas

Dr. Atilio
                Silvio Maculus

+54
                1141192

maculus@gmail.com

                Parana
                600
                3° Piso Of. 8

                C.A.B.A (1017)

                Tel/Fax: 4373-6340/6418 - 4375-5499

                Panamericana Ramal Pilar Km
                50.5

                1er Piso Of.1008.
 Pilar, Bs.As (1629)

                Tel: 0230-437456

                Este E-mail es
                confidencial y
                puede tener informacion amparada por el
                secreto profesional. No debera
                copiar o divulgar su contenido a ninguna persona. Si usted ha recibido este E-,ail por error,
                porfavor informenoslo por este medio y eliminelo de su sistema. Muchas gracias.

                This message is
                confidential and
                contains priviliged information legalle exempt from disclosure. You should not copy this message or
                disclose it to anyone. If you have recieved it by mistake please let us know by e-mail immeadiately
                and delete it from your computer. Thank you very much.


text:
Q: Seleccionar tipos de valores para añadirlos a una variable he empezado hace poco con flask y estoy llevando a cabo un proyecto, el caso es que he llegado a un punto en el que no sé como seguir.
Tengo una base de datos llamada preguntas, con los parámetros de id, enunciado, y tipo (INT)
En una página se deben seleccionar los tipos de preguntas que se quieren, para que en otra página se muestren
solo las seleccionadas. Por lo tanto entiendo que debo hacer algo así como crear una variable que solo almacene
los tipos de preguntas marcadas, para mandarla directamente a la página donde se deben mostrar
PÁGINA DONDE SE DEBEN SELECCIONAR LOS TIPOS

Activar tipos de preguntas...

              <input class="check" type="checkbox" value="" id="flexCheckChecked" checked>

                Estándar

              <input class="check" type="checkbox" value="" id="flexCheckDefault" checked>

               Canciones

Es decir, por ejemplo, el tipo de pregunta canciones, es el tipo 3, pues biem, yo, mediante un check, quiero agregar los tipos de pregunta 3 de mi base de datos a la variable que mostrare en otra página


text:
Q: Using beautifulsoup to separate strings separated by `` I want to get some data from a website that uses
. In the html parsed using beautifulsoup4 sometimes I have the following pattern:
"
text_1. text_2 (text_3)

text_4,
text_5.
"

But if the website was written in a nicer way, it would have looked like:
"
text_1. text_2(text_3)</span

text_4,
text_5.

To extract the strings I want, I would have extracted all text within each
.
However, now the strings I want to separate are separated by
.
My question is the following: how can I use
 to disentangle the parts of the string I am interested in? I mean, I want something like [text_1.+text_2+text_3, text_4+text_5.].
I'm explicitly asking about the use of
 since is the only element I have found that separates the strings I'm interested. Moreover, in some others parts of the website, I have
 separating the strings I'm interested in, instead of
.
I cannot solve this by using the replace() function since my object is a Tag froom bs4. Also, using find("br") from bs4 gives me "
" and not the text I want. In this way, the answers in this question are not exactly what I want. I think that one way would be to transform the tag from bs4 that I have to html, then change the "
" using replace() function, and finally transform it back to a bs4 element. However, I do not know how to make this change, and I also want to know if there is an easier and shorter way to do this.

A: This is a solution I found but it's long and inefficient since it does not use any feature of bs4. Though, it works.
html_doc = """
"
text_1. text_2 (text_3)

text_4,
text_5.
"
"""

def replace_br(soup_object):
    html1=str(soup_object)
    html1=html1.replace("
", "

")
    soup_html1 = BeautifulSoup(html1, 'html.parser')
    return soup_html1.find_all("p")

replace_br(html_doc)
[
text_1. text_2 (text_3)

,

text_4,
text_5.
]


text:
Q: How to decide whether a drag&drop operation points to somewhere outside the browser window? I'd like to handle dragend events differently depending on whether an element has been just dragged inside the browser window (or site resp.) or or outside, e.g. to an external file manager.
After I didn't find any attribute of the DragEvent instance indicating whether it's inside or outside the sites context I started to arithmetically figure out if the corresponding mouse event still takes place inside the geometry of the site.
Eventually I might succeed with that approach (currently not working yet) but it has one major disadvantage (leaving alone its ugliness): the drop target window might be on top of the browser, so the geometry is no real indicator at all..
so.. how do I find out if a dragend (or any other event I could use to store some state) is pointing outside of the browser window (or source site)?

A: I couldn't find any super straightforward ways to do this, but I could do it fairly concisely with a handful of listeners. If you're ok with having a variable to assist with the state then you can do something like this.
First, listen for the mouse leaving on a drag event. I've found the most reliable way to do this is to use a dragleave listener and then examine the event data to make sure it's really leaving the window. This event runs a ton though, so we need to filter out the ones we need.
dragleave runs every time any element's drop zone is left. To make sure that the drag event is just leaving the page, we can check the target to make sure leaving the html or body tag and going to null. This explains how to see the correct targets for the event.
Right before the dragend event, dragleave is ran as though it left the window. This is problematic because it makes every drop seem as though it were out of the window. It seems that this behavior isn't well defined in the specs and there is some variation between how Firefox and Chrome handle this.
For Chrome, we can make the code in dragleave run a cycle after the code in dragend by wrapping it in a timeout with 0 seconds.
This doesn't work well in Firefox though because the dragend event doesn't come as fast. Firefox does, however, set buttons to 0 so we know it's the end of an event.
Here is what the dragleave event listener might look like
window.addEventListener('dragleave', (e) => {
    window.setTimeout(() => {
        if ((e.target === document.documentElement || e.target === document.body) && e.relatedTarget == null && e.buttons != 0) {
            outside = true;
        }
    });
});

From here we just need to do something similar to see when the drag re-enters the viewport. This won't run before dragend like dragleave so it is simpler.
window.addEventListener('dragenter', (e) => {
    if ((e.target === document.documentElement || e.target === document.body) && e.relatedTarget == null) {
        outside = false;
    }
});

It's also a good idea to reset outside every time the drag event starts.
element.addEventListener('dragstart', (e) => {
    outside = false;
});

Now it's possible in the dragend event listener to see where the drop ended.
element.addEventListener('dragend', (e) => {
    console.log('Ended ' + (outside ? 'Outside' : 'Inside'));
});

Here is a snippet with everything put together (or fiddle)
Note #1: You'll need to drag the element out of the browser window, not just the demo window for it to appear as "outside".
Note #2: There has to be a better way for stopping the last dragleave event, but after a few hours of trying other things, this seemed the most consistent and reliable.

const element = document.querySelector('div');
var outside = false;

element.addEventListener('dragend', (e) => {
    console.log('Ended ' + (outside ? 'Outside' : 'Inside'));
});

element.addEventListener('dragstart', (e) => {
    outside = false;
});

window.addEventListener('dragleave', (e) => {
    window.setTimeout(() => {
        if ((e.target === document.documentElement || e.target === document.body) && e.relatedTarget == null && e.buttons != 0) {
            outside = true;
        }
    });
});

window.addEventListener('dragenter', (e) => {
    if ((e.target === document.documentElement || e.target === document.body) && e.relatedTarget == null) {
        outside = false;
    }
});
div[draggable] {
    width: fit-content;
    margin-bottom: 32px;
    padding: 16px 32px;
    background-color: black;
    color: white;
}

Drag Me

A: This might help. You can click 'Run code snippet' to see how it works
Note: Increasing the offset would help detect the drag out sooner, but might affect precision (whether is has actually been dragged out or right on the edge)

/* events fired on the draggable target */
let offset = 2; // in case required
let width = window.innerWidth;
let height = window.innerHeight;
console.log('Starting screen width: ' + width);
console.log('Starting screen height: ' + height);
document.addEventListener("drag", function(event) {
  let posX = event.pageX;
  let posY = event.pageY;
  console.log('X:' + posX + ' Y:' + posY)
  let isExceedingWidth = posX >= (width - offset) || posX <= (0 + offset);
  let isExceedingHeight = posY >= (height - offset) || posY <= (0 + offset);
  if (isExceedingWidth || isExceedingHeight) {
    console.log('dragged out');
  } else {
    console.log('in');
  }
}, false);
#draggable {
  width: fit-content;
  padding: 1px;
  height: fit-content;
  text-align: center;
  background: black;
  color: white;
}

  Drag Me

A: Here is a possibly controversial, but more programmatic alternative that worked well for me.
Create a function wrapper that takes a callback that will fire every time something is dragged into or out of the window:
export interface OutsideWindow {(outside: boolean): void}
export interface OutsideCleanup {(): {(): void}}
export const whenOutsideWindow = (onChangeCB: OutsideWindow): OutsideCleanup => {
    const windowDragLeaveHandler = () => onChangeCB(true);
    window.addEventListener('dragleave', windowDragLeaveHandler);

    const bodyDragLeaveHandler = (e: DragEvent) => e.stopPropagation();
    document.body.addEventListener('dragleave', bodyDragLeaveHandler);

    const windowDragEnterHandler = () => onChangeCB(false);
    window.addEventListener('dragenter', windowDragEnterHandler);

    return () => () => {
        window.removeEventListener('dragleave', windowDragLeaveHandler);
        document.body.removeEventListener('dragleave', bodyDragLeaveHandler);
        window.removeEventListener('dragenter', windowDragEnterHandler);
    }
}

A few things to note:

*

*This function passes a boolean value into its callback. In this case, it will pass a value, true, when outside the browser window and false when inside it

*It helps to know a little about bubbling and stopPrapogation(), but basically, we are making the window's child element, body, stop propagating the dragleave event, so it will never reach its parent, window

*This only works in one direction, so there is no way to do a similar thing for the dragenter event, thus this will fire every time the draggable is dragged iinto a child element.

*It is a good idea to cleanup any events you add to the DOM, so this function returns its cleanup function for you to call later.

*The return value of this function is a function that returns a function. More on that below

That all looks a little messy, but it provides a relatively clean interface to use
let outside = false;
let cleanup = () => {};

// Probably inside onDragStart()
const foo = (out) => { outside = out; }
cleanup = whenOutsideWindow( outside => foo(outside) );

...

// Later in your code, when you want to cleanup...
// Probably inside onDragEnd()
cleanup()();

No, the multiple calls to cleanup is not a mistake. Remember that whenOutsideWindow returns a function that returns a function. This is because when a function is returned in javascript, it is run immediately. I have no idea why. Hopefully someone in the comments can shed some light on that.
But the important things is that if whenOutsideWindow returned a simple void function...
export interface OutsideCleanup {(): void}

...our dragstart and dragend events would be added and removed immediately. We get around this by calling the function that is returned from the function that is returned by whenOutsideWindow.
cleanup()();


text:
Q: MAX14830 not flushing TX So after a day of struggling I managed to get Debian 11 on a IMX7D, 5.4.129 kernel to recognize the MAX14830 and talk to it via the MAX310X driver. But when I try to send data with echo a > /dev/ttyMAX0 nothing happens. Well except the Tx count going up.
Looking at the SPI traffic this seems to be going correctly and the chip is sending the expected responses (Tx FIFO count returns three if three characters are being send) but nothing seems to happen to the buffer. The driver keeps interrogating the max but the FIFO stays at 3. Then the driver reaches a timeout I guess. Because it then sends 0x81,0x00 which clears the IRQen register, followed by 0x9B 0x40 which sets the baudrate register... which makes it all the more confusing.
So far I've gone through all the stty settings and used -ixon to disable XON/XOFF but that didn't make a difference.
Is there a way/place/file that holds the settings for the driver? Or am I forgetting something? RX doesn't seem to work either but not sure if the max isn't receiving it or just not informing the driver.
The relevant portion of the DTS
&ecspi3 {
    max14830: max14830@3 {
        compatible = "maxim,max14830";
        spi-max-frequency = <15000000>;
        reg = <0>; // SPI chip select number
        clocks = <&clk16m0>;
        clock-names = "osc";
        interrupt-parent = <&gpio5>;
        interrupts = <7 IRQ_TYPE_EDGE_FALLING>;
        gpio-controller; // Marks the device node as a GPIO controller
        #gpio-cells = <2>;
        clk16m0: clk16m0 {
            compatible = "fixed-clock";
            #clock-cells = <0>;
            clock-frequency = <3686400>; // freq of external xtal
            clock-accuracy = <100>;
        };
   };
};

And the comms during startup
OUT          IN            MEANING
0x9F 0xCE               -> Write globalCmd = Enable Extend register map acces
0x05 0x00 -> 0x0F 0xB4  -> Clear SpclChrIntEn= RevID is B4
0x9F 0xCD               -> Write globalCmd = Disable Extend register map access

0x8A 0x01               -> Write UART0 Mode2 = Set RST
0x8A 0x00               -> Write UART0 Mode2 = Clear RST
0x1C 0x00 -> 0x0F 0x01  -> Read UART0 DivLSB = Div0 set
0x89 0x80               -> Set UART0 MODE1 =  ~RTS0 is three state

0xAA 0x01               -> Write UART1 Mode2 = Set RST
0xAA 0x00               -> Write UART1 Mode2 = Clear RST
0x3C 0x00 -> 0x0F 0x01  -> Read UART1 DivLSB = Div0 set
0xA9 0x80               -> Set UART1 MODE1 =  ~RTS1 is three state

0xCA 0x01               -> Write UART2 Mode2 = Set RST
0xCA 0x00               -> Write UART2 Mode2 = Clear RST
0x5C 0x00 -> 0xF 0x01   -> Read UART2 DivLSB = Div0 set
0xC9 0x80               -> Set UART2 MODE1 =  ~RTS2 is three state

0xEA 0x01               -> Write UART3 Mode2 = Set RST
0xEA 0x00               -> Write UART3 Mode2 = Clear RST
0x7C 0x00 -> 0x0F 0x01  -> Read UART3 DivLSB = Div0 set
0xE9 0x80               -> Set UART3 MODE1 = ~RTS3 is three state

0x9A 0x44               -> Write PLLConfig = Set PreDiv5 and PreDiv2
0x9E 0x14               -> Write ClockSource = 0001 0100 -> first 1 at dont care, second PLLen

0x81 0x00              -> Clear IRQen UART0
0x02 0x00 -> 0x0F 0x60 -> Read ISR UART0 = both fifo empty
0x1B 0x00 -> 0x0F 0x00 -> Read BRConfig UART0 -> all clear
0x9B 0x40              -> Write BRConfig UART0 -> FRACT2 Set

0xA1 0x00              -> Clear IRQen UART1
0x22 0x00 -> 0x0F 0x60 -> Read ISR UART1 = both fifo empty
0x3B 0x00 -> 0x0F 0x00 -> Read BRConfig UART1 -> all clear
0xBB 0x40              -> Write BRConfig UART1 -> FRACT2 Set

0xC1 0x00              -> Clear IRQen UART2
0x42 0x00 -> 0x0F 0x60 -> Read ISR UART2 = both fifo empty
0x58 0x00 -> 0x0F 0x00 -> Read BRConfig UART2 -> all clear
0xDB 0x40              -> Write BRConfig UART2 -> FRACT2 Set

0xE1 0x00              -> Clear IRQen UART3
0x62 0x00 -> 0x0F 0x60 -> Read ISR UART3 = both fifo empty
0x7B 0x00 -> 0x0F 0x00 -> Read BRConfig UART3 -> all clear
0xFB 0x40              -> Write BRConfig UART3 -> FRACT2 Set

ttyMAX0 setup according to stty
Result of stty -F /dev/ttyMAX0
-parenb -> don't generate parity
-parodd -> Even parity?
-cmspar -> No stick parity
cs8     -> character size 8 bits
hupcl   -> don't send hangup signal
-cstopb -> use one bit per character
cread   -> allow input to be received
clocal  -> disable modem control signals
-crtscts -> dont enable rts/cts handschaking
-ignbr  -> don't ignore break characters
-brkint -> breaks don't cause an interrupt signal
-ignpar -> don't ignore characters with parity errors
-parmrk -> don't mark parity errors
-inpck  -> don't enable parity checking
-istrip -> don't clear high (8th) bit of input characters
-inlcr  -> dont translate newline to carriage return
-igncr  -> don't ignore carriage return
icrnl   -> don't translate carriage return to newline
-ixon   -> disable XON/XOFF flow control
-ixoff  -> disable sending of start/stop characters
-iuclc  -> don't translate uppercase to lowercase
-ixany  -> Don't let any character restart output
-imaxbel -> don't beep and flush
-iutf8   -> don't assume characters are utf8 encoded
OUTPUT SETTINGS
opost   -> post process output
-olcuc  -> don't translate lower to upper
-ocrnl  -> don't translate carriage return to newline
onlcr   -> translate newline to carriage return newline
-onocr  -> print carriage return in the first column
-onlret -> newline doesn't perform a carriage return
-ofill -> don't use fill characters instead of timing for delays
-ofdel -> don't use delete character for fill instead of null
nl0
cr0
tab0 -> horizontal tab delay style 0
bs0
vt0
ff0    -> form feed delay style
isig   -> enable interrpt,
icanon -> enable special characters: erase, kill, werase, rprnt
iexten -> enable non-POSIX special characters
echo   -> echo input characters
echoe  -> echo erase characters as backspace-space-backspace
echok  -> echo a newline after a kill character
-echonl
-noflsh -> don't disable flushing after interrupt & quit special
              chars
-xcase
-tostop
-echoprt
echoctl   -> echo control characters in hat notation ('^c')
echoke    -> kill all line by obeying the echoprt and echoe settings
-flusho
-extproc

A: *

*TX wasn't working because clock-names should have been xtal

*RX wasn't working because i never opened the port but checked /proc/tty/driver/max310x for received data and the driver disables rx if a port isn't open.

Working node.
&ecspi3 {

    /delete-node/spidev@0;

    max14830: max14830@3 {
        compatible = "maxim,max14830";
        spi-max-frequency = <15000000>;
        reg = <0>; // SPI chip select number
        clocks = <&clk16m0>;
        clock-names = "xtal"; /* because using external xtal */
        interrupt-parent = <&gpio5>;
        interrupts = <11 IRQ_TYPE_EDGE_FALLING>;
        gpio-controller;  /* Marks the device node as a GPIO controller */
        #gpio-cells = <2>;
        clk16m0: clk16m0 {
            compatible = "fixed-clock";
            #clock-cells = <0>;
            clock-frequency = <3686400>; /* external xtal frequency */
            clock-accuracy = <100>;
        };
     };
};
```


text:
Q: Is there any way to disable the Touch ID prompt (UIAlertview)? Trying to Integrate TouchId in my application, and i was successful too.
The Question is
Can we customize the Default TouchID UIalertview ?
Can we Disable it?

A: No, you cannot. As Popeye said in a comment, the system controls that prompt, not your app – you simply request that the system display it for you. This is due to obvious security concerns.
For example, what if you initiated a $100 in-app purchase, but changed the prompt to say, "Place your thumb on the home button to start the game!" Clearly that would not go over well.

A: You can customized it the message in the alert can be set with the localizedReason parameter
- (void)evaluatePolicy:(LAPolicy)policy localizedReason:(NSString *)localizedReason reply:(void (^)(BOOL success, NSError *error))reply
You can also set the action button (default is "Enter Password") with
LAContext *context = [[LAContext alloc] init];
  context.localizedFallbackTitle = [your message]
The "localizedFallbackTitle" is not in the docs but part of the LAContext .h file


text:
Q: Remove tabs from product data in woocommerce I need to remove the below tabs from the product data
1- 'Get more option' Tab
2- 'woocommerce tab'
3- Upsell
4- Cross-sell
As shown in the screenshot  https://prnt.sc/pp1oyy
I wrote the below function but not working
function remove_tab($tabs){
unset($tabs['get_more_options']); // it is to remove general tab
unset($tabs['woocommerce_tab']); // it is to remove variations tab
return($tabs);
}
add_filter('woocommerce_product_data_tabs', 'remove_tab', 10, 1);

A: The "Get more options" suggestions tab were added in Woocommerce 3.6 and you can disable it by either going to Woocommerce -> Settings -> Advanced -> "Woocommerce.com" and untick the checkbox "Show suggestions".
Another way is to add the following code to your themes functions.php:
add_filter( 'woocommerce_allow_marketplace_suggestions', '__return_false' );

In terms of the "Woocommerce tab" - if you want to remove upsells & cross sells you can add the follow code:
function remove_tab($tabs){
    unset($tabs['linked_product']); // Removes the tab section for cross & upsells
    return($tabs);
}
add_filter('woocommerce_product_data_tabs', 'remove_tab', 10, 1);


text:
Q: How to have a view travel the path of an inverted parabola? I have an inverted parabola and i need to have a view traverse through the path of the parabola.The view should slightly rotate and translate along the path of the parabola.
I did some research and found that BezierPath (quadcurve with control points) could be used to lay the path of the parabola out and then we could use CAKeyFramAnimation to move the object along the path.Animating the view object along the path of the parabola is whats confusing me.
How do i keep changing the starting points of the object within the parabola and retain the latest state of the view
Here's a brief description of what i want to achieve with the view in the parabola
The view starts from a particular point in the parabola and then traverses the parabola till the specified end point.
How do i find out the end point within the parabola?
Once the view reaches its end point.For the next traversal it can start from that point and then move on to any other point within the parabola.This happens continuously based on the next end point.
This is a rough sketch oh how the path and the view would look like

And also i would like both the rotation and translation of the view traversing the path to happen simultaneously
How can this be done?
Thank you!

A: *

*Draw parabola with UIBezierPath and convert it to CGPath or Create a CGPath.

*Use CAKeyFrameAnimation to move UIView's position.

Look at the below source code,
Drawing Parabola
CGMutablePathRef path = CGPathCreateMutable();
CGPathMoveToPoint(path,NULL,50.0,120.0);

CGPathAddCurveToPoint(path,NULL,50.0,275.0,
                      150.0,275.0,
                      150.0,120.0);
CGPathAddCurveToPoint(path,NULL,150.0,275.0,
                      250.0,275.0,
                      250.0,120.0);
CGPathAddCurveToPoint(path,NULL,250.0,275.0,
                      350.0,275.0,
                      350.0,120.0);
CGPathAddCurveToPoint(path,NULL,350.0,275.0,
                      450.0,275.0,
                      450.0,120.0);

CAKeyFrameAnimation along a path.
CAKeyframeAnimation* AniLoc = [CAKeyframeAnimation animationWithKeyPath:@"position"]; // notice key change

// rest is the same
AniLoc.path = thePath;
AniLoc.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseOut];
AniLoc.keyTimes= [NSArray arrayWithObjects:[NSNumber numberWithFloat:0.0f],
                  [NSNumber numberWithFloat:0.3f],
                  [NSNumber numberWithFloat:1.0f],nil];
AniLoc.duration = 2.0;

CFRelease(thePath);

[self.logo.layer addAnimation:AniLoc forKey:nil];


text:
Q: Finding the average from an array I'm here learning javascript. And I'm trying to make a function that will take in all the gpa of each student, find the average and console log it.
var stuObj = [{
        name: " Alexandra Williams",
        address: {
            address: " 297 S Wilton Drive, Somewhere AR"
        },
        gpa: [2.5 + ', ' + 3.5 + ', ' + 4.0]
    },

    {
        name: "Kallie Johnson",
        address: {
            address: " 84B NNE 332 Street', Queens NY"
        },
        gpa: [2.3 + ', ' + 3.7 + ', ' + 4.0]
    }
];

A: *

*You are constructing your arrays the wrong way:
gpa: [2.3, 3.7, 4.0] // no need for string concatenation here

*Sum up all the values using a simple for loop

*Divide the sum by the length of the array


text:
Q: How to use my own library in another js file (vanilla js) I've made my library and want to use these methods in my front-end app. How do I do this?
This is a simple front-end app with vanilla js, I'm not using any framework, neither nodejs...
this is my library antecipacao.js:
var _ = (function (val, parc, taxaMdr) {

    'use strict';
    var valor=val;
    var parcela=parc;
    var mdr=taxaMdr;
    valorParc = (valor - (((valor / parcela) * mdr)) * parcela) / parcela;
    valorTotalAntecipado = valorParc * parcela;
    valorParcela = 0

    // Create the methods object
    var methods = {};

    methods.parcelaCalculo = function (valor, parcelas, mdr, numero){
        return (valorParc - ((numero * mdr) * valorParc));
    }

    methods.umDia = function (valorTotalAntecipado, parcelas, mdr) {
        for (var i = 0; i < parcelas; i++) {
            if(i == 0){
                valorParcela += parcelaCalculo(valorParc,parcelas, (mdr / 30 * 29), i+1);
            }else if(i != 0){
                valorParcela += parcelaCalculo(valorParc,parcelas,mdr, i+1);
            }
        }
        return console.log(valorParcela);
    };

    methods.trintaDias = function (valorTotalAntecipado, parcelas, mdr) {
        for (var i = 0; i < parcelas; i++) {
            if(i > 0){
                valorParcela += parcelaCalculo(valorParc,parcelas,mdr, i);
            }else{
                valorParcela += valorParc;
            }
        }
        return console.log(valorParcela);
    };

    methods.quinzeDias = function (valorTotalAntecipado, parcelas, mdr) {
        for (var i = 0; i < parcelas; i++) {
            if(i == 0){
                valorParcela += parcelaCalculo(valorParc,parcelas,mdr, 0.5);
            }else if(i != 0){
                valorParcela += parcelaCalculo(valorParc,parcelas,mdr, i+0.5);
            }
        }
        return console.log(valorParcela);
    };

    methods.noventaDias = function (valorTotalAntecipado, parcelas, mdr) {
        for (var i = 0; i < parcelas; i++) {
            if(i > 3){
                valorParcela += parcelaCalculo(valorParc,parcelas,mdr, i);
            }else{
                valorParcela += valorParc;
            }
        }
        return console.log(valorParcela);
    };

    // Expose the public methods
    return methods;

})();

_.umDia();
_.quinzeDias();
_.trintaDias();
_.quarentaDias();

this is my js.js:

function calcular(){
  var valor = document.getElementById("valor").value;
  var parcelas = document.getElementById("parcelas").value;
  var mdr = document.getElementById("mdr").value;

  if(valor != "" && parcelas != "" && mdr != ""){
    console.log("test")
  }
}

So How could I use the library methods in my html page through js.js?

A: I think the best way to it is to include your library in your html file like jQuery
<html>
<body>
  <script src='antecipacao.js'></script>
  <script src='myJS.js'></script>
</body>
</html>


text:
Q: Private home lan with one wireless router possible? Is it possible with a few laptops (with wifi cards) and a working BT Home Hub* (all machines can connect to internet) to get a simple private home lan going?
From one machine I can ping another by IP address (and I see that the Home Hub can give static addresses to the same machine). But how would I - for example - set up a web server locally on one of the machines and then access those web pages from another machine?
Is this possible? Does it need some kind of hardware or DNS tinkering?
I can I simply play with /etc/hosts files? [nothing but linux over here ;-) ]
I'm a web developer by trade you see and my vision is that I have my regular worksation BUT with another laptop being used as a web/database server.
Possible or just a pipe dream?

*Or for non-Brits a "wireless broadband router" ;-)

A: You shouldn't have any problems with this.  As you said, HOSTS file can be used for DNS resolution.  Hell, you could access the website by IP address if you really wanted.  Since you don't sound like the sysadmin type, you probably don't want to bother setting up a local DNS server, although that's certainly an option too.
Actually setting up the webserver itself is relatively straightforward.  In Linux, you can probably pull down Apache from your distribution's repository.  (eg: yum install httpd)  Then you simply need to get it configured to serve up your content.  A basic httpd.conf doesn't need too much to provide basic html.
More effort needs to be put into setting up PHP, MySQL, and other apps.  But it's all definitely possible.
If you don't mind starting from scratch, I know RHEL/CentOS has options during install for a webserver, which will probably include a good number of components you'll want.
And a word of security, you'll want to use WPA2 encryption on your wireless, with a good long key.  You'd probably rather not have any random wardriver to have access to your webserver.

A: If the computers are connected to a router and they have IP addresses within a subnet your LAN is set up. It is private unless something like DMZ, NAT port forwarding or some other mechanism to allow public access is enabled.
You can set up a web server (including PHP) and MySQL server installing the packages for your distribution (e.g. called apache and mysql-server on Ubuntu). Everything will probably just work, but there may be additional configuration step that must be followed (see documentation specific to your distribution).
To access other computers you don't need to set up a DNS server and it probably doesn't make sense to do it unless there is a specific feature you need to test. You can access/refer to other computers by their IP addresses or by a hostname after adding it to the hosts file.
On Ubuntu (and probably other distributions), avahi-daemon runs by default. This means that mDNS (multicast DNS) service is available by default and you can access other computers on the LAN like this: hostname.local. (e.g. christopher-desktop.local.).


text:
Q: Read complex json file in python Actual Json is:
{
  "title1": {
    "titleID": "1234",
    "titlename": "a-b-c",
  },
  "title2": [
    {
      "block": "0.0.0.0/26",
      "abc_id": "abc-0123",
      "tags": [{ "key": "Name", "value": "abc-name"},
               { "key": "env", "value": "dev"}]
    },
    {
      "block": "1.2.0.0/26",
      "abc_id": "abc-4567"
    },
    {
      "block": "0.0.0.0/26",
      "abc_id": "abc-8999",
      "tags": [{ "key": "Name", "value": "xyz-name"}]
    },
    {
      "block": "0.0.0.0/26",
      "abc_id": "abc-7766",
      "tags": [{ "app": "Name", "value": "web-app"}]
    }

  ]
}

My Code is
with open('/tmp/temp.json') as access_json:
    read_content = json.load(access_json)
    for key1, value1 in read_content.items():
        if key1 == "title1":
            title_id = value1['titleID']
        if key1 == "title2":
            title2_access = read_content['title2']
            for title2_data in title2_access:
                for key2, value2 in title2_data.items():
                    if key2 == "abc_id":
                        abc_id = value2
                    if key2 == "tags":
                        tags_access = read_content['tags']
                        for tags_data in tags_access:
                            for key3, value3 in tags_data.items():
                                if key3 == "Name":
                                    abc_name = value3

and the error is:
Traceback (most recent call last):
  File "/tmp/runscript.py", line 123, in <module>
    runpy.run_path(temp_file_path, run_name='__main__')
  File "/usr/local/lib/python3.6/runpy.py", line 263, in run_path
    pkg_name=pkg_name, script_name=fname)
  File "/usr/local/lib/python3.6/runpy.py", line 96, in _run_module_code
    mod_name, mod_spec, pkg_name, script_name)
  File "/usr/local/lib/python3.6/runpy.py", line 85, in _run_code
    exec(code, run_globals)
  File "/tmp/glue-python-scripts-lw031e0z/tsf_dev.py", line 160, in <module>
KeyError: 'tags'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/tmp/runscript.py", line 142, in <module>
    raise e_type(e_value).with_traceback(new_stack)
  File "/tmp/glue-python-scripts-lw031e0z/tsf_dev.py", line 160, in <module>
KeyError: KeyError('tags',)

Reason: All the items in the title2 dict will not contain "tags". so, if there is no 'tags' or the tags['name'], then the abc_name = ''
i need the list of lists
(titleID, abc_id, abc_name).
Expected output :
['1234','abc-0123','abc-name']
['1234','abc-4567','']
['1234','abc-8999','xyz-name']
['1234','abc-7766','']

There is a dictionary of "title2",
and it contains abc_id and few items contains "tags" as well.
If there is no tags, then the abc-name should be ''.
If there is no Key: "name", then the abc-name should be ''.
If there is tags and the key: "name" in the dict, then the abc-name should be the value present in the title2[tags][value: ""] where title2[tags][key is "name"]

A: You have too many if statements and for-loops to properly handle your code. Use the default option for the dictionary get method to handle the cases where the data doesn't exist like shown below.
title_id = read_content.get('title1', {}).get('titleID', '')

for block in read_content['title2']:
    id_ = block.get('abc_id', '')
    tags = block.get('tags', [{}])
    for tag in tags:
        if tag.get('key', '') == 'Name':
            name = tag.get('value', '')
        else:
            name = ''
        vals = [title_id, id_, name]
        print(vals)

['1234', 'abc-0123', 'abc-name']
['1234', 'abc-0123', '']
['1234', 'abc-4567', '']
['1234', 'abc-8999', 'xyz-name']
['1234', 'abc-7766', '']


text:
Q: Android Styling Design I have to create below style for my Android Page is it possible to make through it styling
using (Shape etc)

 if(getResources().getConfiguration().orientation==Configuration.ORIENTATION_PORTRAIT){

        ScrollView sv = (ScrollView) findViewById(R.id.scroll_vw);
        sv.setBackgroundResource(R.drawable.login_image_portrait);
    }
    else{
        ScrollView sv = (ScrollView) findViewById(R.id.scroll_vw);
        sv.setBackgroundResource(R.drawable.login_image_landscape);

    }

Currently I have taken it as Image and run time I look for orientation and set the drawable . I tried it a lot through XML and using custom view but couldn't get it (In this I have to put the Edit Box and Buttons at specific position after using custom view only layout i can use was frame that didnt give me the control over the widgets position)


text:
Q: Visual C++/MFC: getting Japanese characters to work without UNICODE I have software originally developed 20 years ago in Visual C++ using MFC without UNICODE.  Currently strings are held either in char[] or CString, and it works on English and Japanese Windows PCs until Japanese characters are used, as these tend to get converted to strange characters or empty boxes.
Setting UNICODE is presumably the way forward but will require a massive code change, whereas quite a lot seems to work simply by setting System Locale to Japan (in "Window's Language for non-Unicode programs" setting). I have no idea how Windows does this, but some Japanese character things now work on my English Windows PC, e.g. I can open and save Japanese filenames with no code changes. And in Japan they set System Locale to English and again much works, but not everything.
I get the impression the problems are due to using a font that doesn't include Japanese characters. Currently I am using Arial / MS Sans Serif and charset set to ANSI_CHARSET or DEFAULT_CHARSET. Is there a different font I should be using, or can I extend these fonts to include Japanese characters? Or am I barking up the wrong tree in which case what do I do next?  Am very new to all this unfortunately …

A: That's a common question (OK I guess not so common any more in 2015, as MBCS programs luckily are a dying breed - I still maintain several though...)
Either way, I'm afraid that, depending on your definition of 'working', to get this working you'll have to bite the bullet and convert to a Unicode build. If you can't make a business case for that, then you'll have to set the right locale (well, worse, have the user set the 'right' one) and test what works and what doesn't, and ask more specific questions on what doesn't.
If your goal is to make one application that correctly displays strings in various encodings in the 'right' way regardless of the locale settings on the computer, and compatible with every input data set / database content without the user having to be aware of encoding issues, then you're out of luck with an MBCS build.
The font missing characters is most likely not the problem. Before you go any further and/or ask further questions, you should read http://www.joelonsoftware.com/articles/Unicode.html, read it again, sleep on it, read it again, explain to somebody else what the relationship is between 'encoding', 'locale', 'character set', 'font' and 'Unicode code point', because only after you can do that, you can decide on how to progress with your application. Sorry, it's not what you want to hear, but it's the reality if you've been tasked with handling internationalization.


text:
Q: Template Helper Functions Is it possible to pass a variable into a template helper function to determine which object is returned, without creating a new template for each? Something like this, maybe?
{{#each frame}}

{{name}}

{{description}}

{{/each}}

Template.templateName.helpers({
classic : [
   {
    name : 'first option',
    description : 'this is option 1'
   },
   {
    name : 'second option',
    description : 'this is option 2'
   }],
versions : [
   {
    name : 'first option',
    description : 'this is option 1'
   },
   {
    name : 'second option',
    description : 'this is option 2'
   }],
{
'frame' : function(boardSpecs){
    if (boardSpecs[0] == "classic"){
        return classic;
    }
    else if (boardSpecs[0] == "versions"){
        return versions;
    }
}
})

A: You can probably play with {{#if}}.
For example only with classic and versions:
Template:
{{#each frame}}
    {{#if classic.active}}

{{classic.name}}

{{classic.description}}

    {{/if}}
    {{#if versions.active}}

{{versions.name}}

{{versions.description}}

    {{/if}}
{{/each}}

Helpers:
Template.templateName.helpers({
    active: {
        classic: function(){ return Session.get("active") == "classic"; }
        versions: function(){ return Session.get("active") == "versions"; }
    },
    classic : [
       {
           name : 'first option',
           description : 'this is option 1'
       },
       {
           name : 'second option',
           description : 'this is option 2'
       }],
     versions : [
       {
           name : 'first option',
           description : 'this is option 1'
       },
       {
           name : 'second option',
           description : 'this is option 2'
       }]
    })

Then you can set Session.set("active", "name of the one you want") when you need to change view.


text:
Q: How to send a notification to my android app through my already-made website, that isn't a web app by google I already have my website built. I decided to make an app to broadcast a notification to all users and give them a score update for my high school, I cannot find any sources on how to implement code into my previous-built website. My website is not a firebase web app. I want to be able to click the "Touchdown" button and it will send a notification to everyone with a title of "Blah scored a touchdown!", and a body of "Blah 42 - Blah2.0 41" Any help will be much appreciated!
Update:
My website: www.yorkcougars.com
My website is a site that people can go to to get scores, roster, team records, live scoring, etc. of my high school football team. I created an app so that way I can send notifications to people's phones whenever a team scores. So I want it to be where when I click on "Touchdown" it will send a notification to everyone's phone giving them a score update.
P.S. I am new to this, so I apologize in advance for bad communication skills, and/or lack of clarification!
Thanks for you help!


text:
Q: MongoDB: $match on a nested document after $lookup I need to query a collection of timecards which are linked to jobs, while jobs are linked to facilities with a specific facility ID. I have the following aggregation query:
Timecard.aggregate([
    { $match: query }, //some query parameters set before, doesn't matter here
    {
        $lookup: {
            from: 'jobs',
            as: 'job',
            localField: 'job',
            foreignField: '_id'
        }
    },
    { $unwind: '$job' },
    {
        $lookup: {
            from: 'facilities',
            localField: 'job.facilityId'
            foreignField: '_id',
            as: 'job.facilityId'
        }
    },
    { $unwind: '$job.facilityId' },
    { $match: {'job.facilityId._id':'5cad048d95d61a002f5a9edb'}}
];)

Everything before the last $match works just fine, jobs are populated into timecards, facilities are populated into jobs. But the match doesn't work for some reason. However, if I add facilityId field with
{$addFields: {facilityId: '$job.facilityId._id'}}

and change the $match to
{$match: 'facilityId':'5cad048d95d61a002f5a9edb'}

then it works.
The question is, is there a way to query a subdocument's field with dot notation this way?

A: Your last line likely needs to be an ObjectId
{ $match: {'job.facilityId._id': ObjectId('5cad048d95d61a002f5a9edb')}}


text:
Q: Blocking artefacts with DCT decompression Opencv I'm attempting to compress an image using DCT in opencv and getting more artefacts on decompression than I expected.
My compression process is:
Take DCT of 8x8 blocks in image
Do element-wise division of each 8x8 block by the given quantisation matrix
Round all elements to the nearest whole number

My decompression process is:
Take 8x8 blocks of the DCT and do element-wise multiplication by the quantisation matrix
Perform an inverse DCT

I do this in YCrCb space on each channel and for element-wise division and multiplication I'm using the cv::divide and cv::multiply. For quantisation matrices I'm using the JPEG standard matrices shown here http://www.impulseadventure.com/photo/jpeg-quantization.html (under the heading JPEG Standard). I'm applying the luminance matrix to the Y channel and the chrominance matrices to the Cr and Cb channels.
Finally here are the images:

Unfortunately I can't share the code otherwise I would. But I will answer any questions people have to the best of my abilities.

A: The DCT coefficients of an image are signed doubles with negative values. After quantising and rounding the elements I converted the matrix from a CV_64FC3 type to CV_8UC3 expecting the equivalent of a static_cast to be applied to the elements.
However OpenCV when converting from 64F to 8UC zeroed out all negative values resulting in information loss that caused the blockiness.
The solution was apply a static cast converting the double to an unsigned char and writing it into the returned array instead of utilising the opencv convert function.

A: May be this is how it should look, its possible that you have quantized the coefficients a lot which is leading to this pattern. Such artifacts do arize in jpeg compression when you want to throw away a lot of information for saving more on the size of the image.
Your results look similar to the images shown at the bottom of this wiki page
http://en.wikipedia.org/wiki/JPEG
May be you should reduce the quantization level for getting better quality images.


text:
Q: Refactoring js for multiple menus that are not siblings I have created a header section that contains two menus that are not in the same ul. I would like the menu to open up the sub-menu on click and add a class (menu-open). Only one menu should be open at a time. I have achieved that using jQuery. However, I feel like it can be shorter or written better. I have researched this and people are using the sibling element. However, in my code the two uls for the menu are separate and are float to the edges of a div.
Here is my html:

Menu 1

Item 1

Item 2

link1

link2

Menu 2

Item 1

Item 2

This is my jsfiddle:
https://jsfiddle.net/8b8Lzm7v/10/
Any advice/help is appreciated. Thank you in advance

A: This is perhaps a little bit shorter but shouldn't have to get any longer should you add more menu's. Would suggest closing all menus and before opening the specific clicked menu after checking whether or not it's already open, optionally add another click handler to close all menu's if a non menu div is clicked...

(function($) {

  function hideMenus() {
      $("ul.sub-menu").slideUp(100); // slide up all menus
      $(".menu-link").removeClass("menu-open"); // no menus are open
    } // hide all menu's as a function

  $(".menu-link").on("click", function() {
    var $this = $(this),
      menuOpen = $this.hasClass("menu-open") || false;

    hideMenus();

    if (!menuOpen) { // if the menu is closed...
      $this.siblings('ul.sub-menu').slideDown(100); // this opens all .submenu's adjacent
      $this.addClass("menu-open");
    }
    return false;
  });

  $('body').not('.menu-btn').on('click', function() {
    hideMenus();
    return false;
  }); // optional to hide menu's if any other div is clicked

}(jQuery));
div {
  display: inline-block;
  width: 100%;
}
a {
  display: block;
}
.menu-btn {
  display: inline-block;
  list-style: none;
}
.menu-btn li {
  display: inline-block;
}
.sub-menu {
  display: none;
  width: 100px;
  position: absolute;
  border: 1px solid gray;
}
.menu-1 .sub-menu {
  left: 0;
}
.menu-2 .sub-menu {
  right: 0;
}
.menu-2 {
  float: right;
}

Menu 1

Item 1

Item 2

link1

link2

Menu 2

Item 1

Item 2


text:
Q: parse string date to jodaDateTime I am having an issue converting a string date to joda DateTime object
my date format is
   fromDate:2015-10-16T00:00:00.000+05:30
   toDate:2015-10-17T00:00:00.000+05:30

i dont know which date format pattern to use , convert this to datetime object , i m able to convert when i have separate integers coming like this
       fromDate = new DateTime().withDate(params?.fromDate_year.toInteger(), params?.fromDate_month.toInteger(), params?.fromDate_day.toInteger()).withTimeAtStartOfDay()
        toDate =  new DateTime().withDate(params?.toDate_year.toInteger(), params?.toDate_month.toInteger(), params?.toDate_day.toInteger()).withTimeAtStartOfDay()

how can i convert my string to date ??

A: To continue on what @roanjain said, Joda will take care of parsing such a string just fine, however, the DateTime object created will show the default timezone. If your computer is not in the "Asia/Kolkata" timezone you need to tell Joda that you want a DateTime in that timezone, like this:
public static void main(String[] args) {
    String time = "2015-10-16T00:00:00.000+05:30";
    DateTime dt = new DateTime(time);
    // Will show whatever time zone you are in
    System.out.println(dt);
    // Same point in time, but represented in a different time zone
    System.out.println(dt.withZone(DateTimeZone.forID("Asia/Kolkata")));
    // Create a DateTime object in the requested timezone
    dt = new DateTime(time).withZone(DateTimeZone.forID("Asia/Kolkata"));
    System.out.println(dt);
}

Note that both timestamps represent the same point in time, and will remain properly comparable.

A: Do this simply, joda library will handle everything for you, you just need to pass your string date to DateTime()
  String fromDate = "2015-10-16T00:00:00.000+05:30"
  String toDate = "2015-10-17T00:00:00.000+05:30"
  fromDate = new DateTime(fromDate);
  toDate = new DateTime(toDate);

Cheers !


text:
Q: playing video's sound on mouseover hello i have a problem with a script I have a video and I want to play the sound of the video on mouse over and mute it on  mouse out
I tried this script but doesn't work
he return for me this error

Uncaught TypeError: Cannot set property 'muted' of undefined

<script>
    window.onload = function(){
    document.getElementById("sos").onmouseover = function() {mouseOver()};
   document.getElementById("sos").onmouseout = function() {mouseOut()};
        function mouseOver() {
          document.getElementById("sos").video.muted = "false";
        };
    function mouseOut() {
          document.getElementById("sos").video.muted = "true";
    };}
  </script>
<video id="sos" width="100%" height="100%" autoplay muted loop src="https://cdn.shopify.com/s/files/1/0329/9960/4283/files/Bird_jingle_compress.mp4?v=1591684742"></video>

thanks

A: Consider the following example.

function toggleMute(el) {
  el.muted = !(el.muted);
}

window.onload = function() {
  document.getElementById("sos").onmouseover = function() {
    toggleMute(this);
  };
  document.getElementById("sos").onmouseout = function() {
    toggleMute(this)
  };
}
<video id="sos" width="100%" height="100%" autoplay muted loop src="https://cdn.shopify.com/s/files/1/0329/9960/4283/files/Bird_jingle_compress.mp4?v=1591684742"></video>

I do not hear the Video's audio, but when I show controls, I can see it changes from Muted to Volume Full. Unsure if the video has an audio track, so I would test with another video maybe.
Alternate
You asked about using MouseOver / MouseOut events with Mobile Browsers. This simply does not exist as there is no "mouse" and therefore, no mouse movement to track.
jQuery Mobile offers this:

The jQuery Mobile "vmouseover" event handler simulates the "onmouseover" event handler on mobile devices.
This plugin extends jQuery's built-in method. If jQuery Mobile is not loaded, calling the .vmouseover() method may not fail directly, as the method still exists. However, the expected behavior will not occur.

Example

$(function() {
  function toggleMute(el) {
    el.muted = !(el.muted);
  }
  $(document).on("vmouseover mouseover", "#sos", function(e) {
    console.log(e.type);
    toggleMute(this);
  });
  $(document).on("vmouseout mouseout", "#sos", function(e) {
    console.log(e.type);
    toggleMute(this);
  });
})
<script src="https://code.jquery.com/jquery-2.2.4.js"></script>
<script src="https://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.js"></script>

<video id="sos" width="100%" height="100%" autoplay muted loop src="https://cdn.shopify.com/s/files/1/0329/9960/4283/files/Bird_jingle_compress.mp4?v=1591684742"></video>

As you can see, both events get triggered in a normal browser. When testing with Mobile Browser, only the virtual mouse events should be triggered. Results may vary and this library has not been updated since 2014.


text:
Q: C++ - Right shift not evaluated correctly inside IF I have the following piece of code,
if (index > ((v.size() >> 1) - 1)) { }

v.size() is 0 and index is 1. The execution does not get into the if block. But if I change the above code to,
int limit = (v.size() >> 1) - 1;
if (index > limit) { }

and with the same values of v.size() and index, the execution does get into the if block.
Why does this behavior happen? Thanks.

A: You are obviously performing unsigned comparison. The return type of v.size() is likely size_t, which is an unsigned integer. Thus, the expression (v.size() >> 1) - 1 yields the largest possible unsigned integer. Unless you convert that back to a signed integer type, you won't get positive comparison results.
A simple cast to ssize_t before the subtraction will fix your problem:
if (index > (((ssize_t)v.size() >> 1) - 1)) { }

I have used ssize_t because that type is guaranteed to be able to hold any size_t value, reinterpreting it to negative if its most significant bit is set. That cannot be said for int, as that is usually only 32 bits on 64 bit platforms. So, using int as you did in your second example, may cut off some bits.


text:
Q: the first query and duplicating elements in a list in Prolog I am new to Prolog. I wrote the basic code below.
flight(acompany, paris, 7).
flight(bcompany,paris,7).
flight(ccompany,paris,7).
flight(dcompany,paris,7).

search([X],Y,Z) :- flight(X,Y,Z).

search([X|T],Y,Z) :- search(T,Y,Z) , flight(X,Y,Z).

I want to do two things.
First when I query as
?- search(X, paris,7).

the first thing prolog show me is
X = [acompany]

But I want to see all element in the list at the first query.
i.e
X = [acompany, bcompany, ccompany, dcompany]

And the second thing I want is avoiding duplicating the elements in the list.
For example;
X = [acompany] ;
X = [bcompany] ;
X = [ccompany] ;
X = [dcompany] ;
X = [acompany, acompany] ;

I don't want such a last list.
How can I fix these two things? Thanks.

A: ?- setof(X, flight(X, _, _), Xs).
Xs = [acompany, bcompany, ccompany, dcompany].


text:
Q: Read CMD console output for keyword I have a simple .bat script that runs an external console program and when it completes it outputs a couple lines of data.
Is there a way to look for a keyword in the console output after external program has completed.
For instance:
The external program completes, the .bat file looks for the keyword: success, and if it's found it saves the console output conversely if the keyword is: failed then the .bat program exits.

A: Usually checks for success are done by directly checking the external process's return code with the IF ERRORLEVEL construct:
external.exe
IF ERRORLEVEL 4 GOTO error1
IF ERRORLEVEL 3 GOTO error2
IF ERRORLEVEL 2 GOTO error3
IF ERRORLEVEL 1 GOTO error4
REM if you reached this point, external.exe reported success

Of course this is dependent on the external program, so you might simply not be able to use it. In that case you can redirecting the output of the external program and using find to look for it; find uses a nonzero (don't remember exactly) return code to signify that the target string was not found. So you can write:
external.exe | find >nul "success"
IF ERRORLEVEL 1 GOTO notfound
REM if you reached this point, "success" was present in the output

The >nul redirection makes sure that find will not actually output any matching text, since that's not what you want to do.


text:
Q: Inequality with Laplacian I'm trying to solve a larger problem and have reduced it to showing that $$\int_\Omega (u-v) \Delta v dx \geq 0$$ Here $u, v$ are both continuous on $\overline\Omega$, $C^2$ on $\Omega$, which is an open region in $\mathbb{R}^n$ with smooth boundary. How can I prove this to be true?
EDIT: Additional information about the problem is that $u$ and $v$ agree on $\delta \Omega$ and $u$ is harmonic. I used this info to reduce my original problem (showing that $\int_\Omega |\nabla u|^2 \leq \int_\Omega |\nabla v|^2$) to the one I have now, but it might still be relevant.

A: Since $u$ is harmonic we can write
$$\int_{\Omega} (u-v) \nabla^2 v \,\,dV = -\int_{\Omega} (u-v) \nabla^2 (u-v) \,\,dV $$
Now, we use the vector identity $\phi \nabla^2 \psi=\nabla \cdot (\phi \nabla \psi)-\nabla \phi \cdot \nabla \psi$ with $\phi =\psi = u-v$ to reveal that
$$\begin{align}
\int_{\Omega} (u-v) \nabla^2 v \,\,dV &= \int_{\Omega}\{ \nabla (u-v)\cdot \nabla (u-v)-\nabla \cdot \left((u-v) \nabla (v-u)\right) \}\,\,dV \\\\
&=\int_{\Omega} \left|\nabla (u-v)\right|^2\,\,dV-\int_{\partial \Omega}(u-v)\frac{\partial (u-v)}{\partial n} \,\,dS
\end{align}$$
where we applied the divergence theorem to the second term on the right-hand side.
Note that $|\nabla (u-v)|^2\ge 0$, while the surface integral is zero since $u=v$ on $\partial \Omega$.
Thus, we arrive at
$$\begin{align}
\int_{\Omega} (u-v) \nabla^2 v \,\,dV &=\int_{\Omega} \left|\nabla (u-v)\right|^2\,\,dV\\\\
&\ge 0
\end{align}$$
which was to be shown!
Note that the same inequality obtains if $\frac{\partial u}{\partial n}=\frac{\partial v}{\partial n}$,instead of $u=v$, on $\partial \Omega$.


text:
Q: `nohup` issue with submitting `SLURM` job I have a python code main.py that runs bash script, the bash script inturn submits a job job.bash and obtains its JOBID using echo $JOBID | awk {'print $4'}. If I run python in the terminal, the bash script works and I am able to obtain and echo the JOBID as follows:
#!/bin/bash
JOBID=`sbatch ~/job.bash  | tee  output.log`
JOBID=`echo $JOBID | awk {'print $4'}`
echo $JOBID

Running above as part of python works in terminal python main.py, but doing nohup python main.py &, the echo does not print or store JOBID.
Any reason for this?

I am submitting a slurm job hence the JOBID is the pid from slurm

(Update Jul 17) Looks like the issue is with the command sbatch ~/job.bash  | tee  output.log, it doesnt get submitted using nohup and hence JOBID never gets stored and echo'd.
(Update Jul 18) As per the comments from @pynexj adding set -x in the script results:
nohup: ignoring input and redirecting stderr to stdout
+ date
Mon Jul 18 21:46:35 +03 2022
++ sbatch ~/job.bash
++ tee output.log
+ JOBID=
++ echo
++ awk '{print $4}'
+ JOBID=
+ echo

The issue still persists. It appears that nohup is incompatible with sbatch.

Question: Why should nohup prevent submission of slurm job? Its objective is merely to capture terminate signal?

A: If this problem only happens with nohup present, you can get the benefits of nohup without actually using it with:
yourscript </dev/null >file.log 2>&1 & disown -h "$!"

This does the following:

*

*Redirects stdin from /dev/null with </dev/null

*Redirects stdout and stderr to a log file with >file.log 2>&1

*Tells the shell not to forward HUP signals to the background process with disown -h "$!"
...which is everything nohup does.


text:
Q: Windchill nested loops python code equation I started python only a few months ago and I have been given a task to use a nested loops to calculate wind chill.
I have most of the code completed (I think), however the equation is not working the way it want it to work.
Here is my code at the moment:
def main():
temp = 0
wind = 0
windChill = 13.12 + (.6215 * temp) - (11.37 * wind ** 770.16) + (.3965 * temp * wind **0.16)

for temp in range(-35,15,5):
    print 'temperature is %d' % temp
    for wind in range(0,85,5):
         answer = float(windChill)
         print 'wind is %d calculated wind chill is: %d' % (wind, answer)

main()

This comes out with this:
temperature is -35
wind is 0 calculated wind chill is: 13
wind is 5 calculated wind chill is: 13
wind is 10 calculated wind chill is: 13
wind is 15 calculated wind chill is: 13
wind is 20 calculated wind chill is: 13
wind is 25 calculated wind chill is: 13
wind is 30 calculated wind chill is: 13
wind is 35 calculated wind chill is: 13
wind is 40 calculated wind chill is: 13
wind is 45 calculated wind chill is: 13
wind is 50 calculated wind chill is: 13
wind is 55 calculated wind chill is: 13
wind is 60 calculated wind chill is: 13
wind is 65 calculated wind chill is: 13
wind is 70 calculated wind chill is: 13
wind is 75 calculated wind chill is: 13
wind is 80 calculated wind chill is: 13
temperature is -30
wind is 0 calculated wind chill is: 13

I understand why 13 is spited out, it's because if the temp and wind are 0, it comes to the answer 13.12. But if I do the range for the definition of temp and wind, it will not accept a list for the definition.
How do I make it so that the wind chill isn't 13, but the answer which the equation should spit out.
e.g. comes out with this:
temperature is -35
wind is 0 calculated wind chill is: -8.63
wind is 5 calculated wind chill is: -41.29
wind is 10 calculated wind chill is: -45.12
etc.
etc.

Thank you very much!
If what I have put is simple, and I should just google it, I tried googling it but it makes a table, instead of statements.
Carny.

A: You must define an actual function. What you have is just an assignment:
temp = 0
wind = 0
windChill = 13.12 + (.6215 * temp) - (11.37 * wind ** 770.16) + (.3965 * temp * wind **0.16)
print(windChill)  # 13.12

Basically, temp and wind are used with their current values to resolve the expression. windChill then just gets that fixed value assigned to it.
A function would look like this:
def windChill(temp, wind):
    return 13.12 + (.6215 * temp) - (11.37 * wind ** 770.16) + (.3965 * temp * wind **0.16)

Then call that function in your loop:
for temp in range(-35,15,5):
    print 'temperature is %d' % temp
    for wind in range(0,85,5):
        answer = float(windChill(temp, wind))  # note me!
        print 'wind is %d calculated wind chill is: %d' % (wind, answer)

Alternatively, you can move the definition of windChill into both loops, so it gets reevaluated every time.
for temp in range(-35,15,5):
    print 'temperature is %d' % temp
    for wind in range(0,85,5):
        answer = 13.12 + (.6215 * temp) - (11.37 * wind ** 770.16) + (.3965 * temp * wind **0.16)
        print 'wind is %d calculated wind chill is: %d' % (wind, answer)

A: def windspeed_calculation ():
    for x in range (0, 60, 5 ):
        x += 5
        if si_temperature == "C":
            temperature_new = (temperature *9/5) + 32
            Wind_Chill = 35.74 + (0.6215*temperature_new) - 35.75*(x**0.16) + (0.4275*temperature_new *(x**0.16))
            print (f"At temperature {temperature_new}F, wind speed at {x}MPH. The windchill is: {Wind_Chill:.2f}F")
        elif si_temperature == "F":
            Wind_Chill = 35.74 + (0.6215*temperature) - (35.75* (x**0.16)) + (0.4275*temperature*(x**0.16))
            print (f"At temperature {temperature}F, and wind speed at {x}MPH. The windchill is: {Wind_Chill:.2f}F. ")

temperature = float(input("What is the temperature? "))
si_temperature = input ("Fahrenheit or Celsius (F/C)? " ).upper()
print()
windspeed_calculation()

A: import math
wind = float (input ("Input wind speed in kilometres/hour: "))

temp = float (input ("Input air temperature in degrees Celsius: "))

wind_chill = 14.12 + 5.2210*t - 11.47*math.pow(v, 5.12) + 5.4320*t*math.pow(v,5.12)

print("The wind chill index is", int(round(wci, 5)))


text:
Q: Add objects to list on or after creation In java I would like to have every object created, added to a list of objectsamples.
Is there a way to do it in the constructor itself like:
public ObjectSample() {
    mObjectSamples.add(this);
}

or do I have to call the add method after creation.

A: You can't change the constructor of Object class.
You can have a constructor in one of your classes that adds the newly created instance to a static Collection.
public YourClass
{
    public static List<YourClass> list = new ArrayList<>();
    public YourClass()
    {
        list.add(this);
    }
}

A: Add a new instance of you object to the list.
public class Foo{

    public static List<Foo> list = new List<Foo>();
    public Foo(){
        //Do whatever
    }

    public stativ void main(String args[]){
        list.add(new Foo());
    }

}

This will add the object to the list by passing a new instance as an argument to the add() method.

A: Create you object first then add this object to List,
class MyClass{

    private static List<Object> mObjectSamples = new ArrayList<Object>();
    private int a,b;

      MyClass(int a, int b){  // initialize your object using parametrized constructor
       this.a = a;  // suppose you have to initialize you a and b member of class.
       this.b= b;
       mObjectSamples.add(this);
      }
 }

A: First of all, you cannot modify the constructor of a library class, especially not the one of Object. However, I absolutely do not recommend putting every new Object in a list anyway, since there is an enourmous amount of objects that you do not even need to care about, and I can't think of any case where you would want to put all of them in a list.
If you want every object of a specific type, e.g. Element in your list, you could simply define the Element class like this:
public class Element
{
    public Element()
    {
        elements.add(this);
        ...
    }
    ...
}

A: Consider a static factory method, as recommended by Joshua Block's Effective Java, and also described in this Baeldung post. If you make the constructor private, then your class can only be instantiated by the static factory method. It's often a good idea to limit constructors to doing the instantiation of an object's class-specified fields, and let a more general bit of code handle anything outside the class. A static factory method is one good place to put such external instantiation.
For the notional Element class, it might look like this:
public class Element {
    private final List<Element> trackedElements = new ArrayList<>();

    public static Element newTrackedElement(...) {
        var e = new Element(...);
        trackedElements.add(e);
        ...other out-of-class instantiation...
        return e;
    }

    private Element(...) {
        ...in-class instantiation...
    }
    ...
}

With this approach, the collection only contains fully-instantiated objects, and those objects are guaranteed to be in the collection by the time the factory method call completes. It's simpler than having a fully-implemented factory class, which could be useful if there's enough extra work involved in creating the new object.


text:
Q: Empty .mp4 file created after making video from matplotlib using matplotlib.animation I found this little code, and I am able to save a video (random colors changing in a grid) using it:
import numpy as np
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
import matplotlib.animation as animation
from scipy import rand

Writer = animation.writers['ffmpeg']
writer = Writer(fps=15, metadata=dict(artist='xy'), bitrate=3600)

fig = plt.figure()
frames = []
for add in np.arange(15):
    base = rand(10, 10)
    frames.append((plt.pcolormesh(base, ),))

im_ani = animation.ArtistAnimation(fig, frames, interval=500, repeat_delay=3000,
                               blit=True)
im_ani.save('Vid.mp4', writer=writer)

I tried to insert it into my simulation, I get no errors, but the video is empty, the whole picture is white. Can you help me with that? This is the simplest case where I got it:
class Dummy():

    def __init__(self):
        self.video=[]

    def addFrame(self):

        Frame=rand(10,10)
        print (Frame)
        self.video.append((plt.pcolormesh(Frame),))

    def saveVideo(self):

        Writer = animation.writers['ffmpeg']
        writer = Writer(fps=15, metadata=dict(artist='XY'), bitrate=3600)
        fig = plt.figure()

        im_ani = animation.ArtistAnimation(fig, self.video, interval=500, repeat_delay=3000,
                               blit=True)
        im_ani.save('myVid.mp4', writer=writer, dpi=dpi)

You can try it out:
from scipy import rand

foo=Dummy()

for i in range(20):
   foo.addFrame()

foo.saveVideo()

A: Your self.video.append((plt.pcolormesh(Frame),)) line is fine. You just changed the order of statements.
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
import matplotlib.animation as animation
import numpy as np

class Dummy():
    def __init__(self, fname):
        self.fname = fname
        self.video = []
        self.fig, self.ax = plt.subplots()  # Create new figure here

    def addFrame(self):
        Frame = np.random.rand(10, 10)
        self.video.append((self.ax.pcolormesh(Frame), ))

    def saveVideo(self):
        Writer = animation.writers['ffmpeg']
        writer = Writer(fps=15, metadata=dict(artist='XY'), bitrate=3600)
        im_ani = animation.ArtistAnimation(self.fig, self.video, interval=500,
                                           repeat_delay=3000, blit=True)
        im_ani.save(self.fname, writer=writer)

foo1 = Dummy('foo1.mp4')
for i in range(20):
   foo1.addFrame()
foo1.saveVideo()

foo2 = Dummy('foo2.mp4')
for i in range(40):
   foo2.addFrame()
foo2.saveVideo()


text:
Q: Rewiring my own Vect but encountering issues I was trying to re-implement the Vect data type to become more familiar with the dependent types. This is what I wrote:
data Vect : (len : Nat) -> (elem : Type) -> Type where
  Nil : Vect Z elem
  (::) : (x : elem) -> (xs : Vect len elem) -> Vect (S len) elem

append : Vect n elem -> Vect m elem -> Vect (n + m) elem
append [] y = y
append (x :: xs) y = x :: append xs y

I can define, for example Vect 4 Nat and others as well. But if I try append (Vect 4 Nat) (Vect 3 Nat) I get an error that I am not able to parse:
When checking an application of function Main.append:
        Type mismatch between
                Type (Type of Vect len elem)
        and
                Vect n elem (Expected type)

Clearly there is something wrong in the way I think about this.
Any suggestion?
Also when I try to create Vect 4 [1,2,3,4] I get an error:
When checking argument elem to type constructor Main.Vect:
        Can't disambiguate since no name has a suitable type:
                Prelude.List.::, Main.::, Prelude.Stream.::

So I guess I am quite lost ...

A: Your definition of Vect and append look fine to me, but it's how you're creating values that's the problem. You're mixing up the type constructor Vect with the data constructors Nil and ::. You should create values of type Vect len elem with calls to Nil and ::.
In particular, Vect 4 Nat is a type, but append expects a value of that type, like 1 :: 2 :: 3 :: 4 :: Nil (or [1,2,3,4] which is just syntactic sugar for the former).
And Vect 4 [1,2,3,4] isn't possible since [1,2,3,4] is a value not a Type


text:
Q: change column name in pandas, which will be used to change name for 1 column change column name in pandas, which will be used to change name for 1 column.
import numpy as np
import pandas as pd
from openpyxl.workbook import Workbook
df = pd.read_excel(r'C:\Users\Desktop\testing.xlsx')
df.loc[((df.spin== 'sor') | (df.spin== r'f/r')), 'mtm' ] = df["mtm"] + df["wes"] *100000
df.rename(columns={'mtm':'mtm_new'}, inplace=True)
writer =pd.ExcelWriter(r'C:\Users\Desktop\output.xlsx')
df.to_excel(writer,'Sheet1')
writer.save()

A: df.loc[((df.SPIN == 'COR') | (df.SPIN == r'F/R')), 'MTM'] = (df["MARKET PRICE"] - df["TRADE PRICE"]) * (
df["QTY"] / 100)
df.rename(columns={'MTM': 'Market to Market'}, inplace=True)
reportName = "Output"
reportFileOut = rptDirPath + '\\' + reportName + '.xlsx'
writer = pd.ExcelWriter(reportFileOut)
df.to_excel(writer, 'Sheet1')
writer.save()

A: df = pd.read_excel(reportFileOut)df.sort_values(by=['DOF'],inplace=True, ascending=False)writer = pd.ExcelWriter(reportFileOut)df.to_excel(writer, 'Sheet1')writer.save()

A: df.loc[((df.SPIN == 'COR') | (df.SPIN == 'F/R')), 'MTM' = ((df["MARKET PRICE"] -
df["TRADE PRICE"]) * (df["QTY"]/100))

This is actual formulla , please check- If
spin = F/R or COR , MTM = ([MKT PRICE]-[trade price])*([qty]/100)

A: df.loc[(df.SPIN == 'COR') | (df.SPIN == 'F/R')]
  df["MTM"] = (df["MARKET PRICE"] - df["TRADE PRICE"]) * (df["QTY"]/100)
this is actual formulla , please check- If spin = F/R or COR , MTM = ([MKT PRICE]-[trade price])*([qty]/100)


text:
Q: Can we call a hexagonal system with two different atoms as inversion symmetric? Graphene is two-dimensional honeycomb crystal lattice with the two Carbon atoms in its unit cell. Clearly, it is inversion symmetric. But, suppose we have two different atoms in the hexagonal system like in case of SiGe, then can we call it an inversion-symmetric system? If yes, then how?
Thanks in advance!

A: Perhaps it would help to draw a picture! Once you have a picture, pick a convenient point upon which to carry out the inversion, and see if the structure is different. If it is the same it has inversion symmetry, if not then no inversion symmetry.

A: No, such a lattice is not inversion symmetric. For graphene, the inversion needs to be done at the center of a bond (because otherwise the lattice sites move) and the only thing that happens is that you swap carbon for carbon, so nothing changes, but if you put different atoms on the two sites, then that is no longer true.


text:
Q: Provide Authentication in a Yii2 Application using Reactjs frontend I am working with a Yii2 API and a reactjs fronted. I want to implement authentication in my api such that only authenticated users using the Bear authentication class can access my API functions.
I have implemented my Before actions as follows :
//Yii::$app->response->format = Response::FORMAT_JSON;
    /*directly include pagination info in the request body to simplify client development*/
public $serializer = [
    'class' => 'yii\rest\Serializer',
    'collectionEnvelope' => 'items',
];

public static function allowedDomains()
{
    return [
      // '*'   // star allows all domains
       'http://localhost:3000',
       'http://localhost:4200',
       'http://192.168.8.101:3000',
    ];
}

public function behaviors()
{
    return array_merge(parent::behaviors(), [
        // For cross-domain AJAX request
        'corsFilter'  => [
            'class' => \yii\filters\Cors::className(),
            'cors'  => [
                // restrict access to domains:
                'Origin'=> static::allowedDomains(),
                'Access-Control-Request-Method'    => ['POST','GET','PUT','OPTIONS', 'PATCH','DELETE'],
                'Access-Control-Allow-Credentials' => true,
                'Access-Control-Max-Age'           => 3600,// Cache (seconds)
               'Access-Control-Request-Headers' => ['Origin', 'X-Requested-With', 'Content-Type', 'accept', 'Authorization'],
                //'Access-Control-Allow-Credentials' => true,
                'Access-Control-Allow-Origin' => false,
            ],
        ],
        //authenticate the user before execute the actions
        'authenticator'=>[
            'class' => CompositeAuth::className(),
            'authMethods' => [
                HttpBasicAuth::className(),
                HttpBearerAuth::className(),
                //QueryParamAuth::className(),
            ],
            'except' => ['search'],
        ],

    ]);
}

In my reactjs frontend, I make an API call to get data from the api using a function call getposts which is
function getposts(userId) {
const requestOptions = {
    method: 'POST',
    headers: {
        'Authorization': 'Bearer ' + user.auth_key,
        'Content-Type': 'application/json'
    },
    body: JSON.stringify(userId)
};
//console.log('we are about to login');
return fetch(apiConstants.API_POST_URL, requestOptions)
     .then(handleResponse)
    .then(json => {
        console.log(json);
        return json;
    });

}
where auth_key is the authorization key to be used for verification.
When I use the chrome browser for debug, I get a 401 error ( Unauthorized). With Access to fetch from { my URL } has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.
Note, I use that key in postman to get the data I need and it works well. I have changed multiple user keys ( and even pass default values) and they don't work.
Any heads on or help on this issue will be greatly appreciated.
thanks

A: Yii2 Bearer authentication class does not work with JavaScript frontends such as Reactjs and Angular JS. I solved this problem by changing the authentication method to QueryParmas so My fetch looks like
 return fetch(apiConstants.API_POST_URL+'?access-token='+user.auth_key, requestOptions)
     .then(handleResponse)
    .then(json => {
        console.log(json);
        return json;
    });

then in my Yii2 behaviors, I had to activated Query authentication
'authenticator'=>[
        'class' => CompositeAuth::className(),
        'authMethods' => [
            HttpBasicAuth::className(),
            HttpBearerAuth::className(),
            QueryParamAuth::className(),
        ],


text:
Q: How many undirected graphs are there with N vertices, at least one vertex being isolated? I got this qustion in a test, the answer says N * 2^((N-1)*(N-2)/2), because for each of the N vertices, it calculates the number of undirected graphs with N-1 vertices. But I think this answer is wrong. For N=3 it results 6, when, in fact, only 4 out of the 8 possible graphs have at least one isolated vertex.
So, am I wrong? What is the correct formula?


text:
Q: How to remove object from NSMutableArray in iPhone I am trying to delete row of UITableView and removing the object from NSMutableArray. Here is my code for deleting row.
    [myArray removeObjectAtIndex:indexPath.row];

after this I am reloading my tableView.Using this Its delete that object.But, Problem is when I am running application second time that deleted object is showing again in tableview. How can I delete the object from array?? Please help me. Thanks in advance.

A: i think you are re-initializing the array again , thats why it happening.
[myArray removeObjectAtIndex:indexPath.row];

surely this line removes the object from myArray. you can check this by help of breakpoint or NSLOg after this line execution

A: Simply Check the Part of your myArray Initialization.
1) Check that your Initialization of myArray is called when you loads that particular view or Not !
2) Check for your viewDidLoad Method , if you have initialized your myArray there then the element will never be removed.
Answer : Use Break Points and NSLogs

A: You have loaded the myArray from somewhere and now data is in RAM, deleting the object will remove it from RAM but it is already present at that place where you loaded that array. Remove from that place as well.

A: First tell me ... Whence you get Array.. i mean from database or plist or coredata or locally?? if you locally create array in viewDid method and you get array item from it then it get all time of full list of array item as you created in viewDid.. if you get array from database or plist or coredata then send query(for database) or refere for plist and core data (for how to delete data )  [tableView reloadData]; at end.


text:
Q: NVIDIA Parallel Nsight and OpenCL I'm little confuse with NVIDIA Parallel Nsight and OpenCL, can anyone confirm me that it is possible to debug OpenCL code using NVIDIA Parallel Nsight 1.5 or 2.0RC?

A: Currently it is not possible to debug OpenCL kernels with Parallel Nsight yet. Parallel Nsight 2.0 (the latest release as of Jun 2011) only supports the debugging of CUDA kernel. However OpenCL debugging is one of the features that is likely to go into the product in future releases.

A: Yes, it is possible, I've did it my self, the only problem is that you will need two computers connected to network, having two identical video cards. One will be executing your kernel step by step(due to this fact the graphical adapter won't be able to display results, the display will stall) this is where the second computer comes in to play, it displays results in Visual Studio like you were debugging ordinary program.
Personally I found NVIDIA Parallel Nsight as a useless tool. Any kernel debugging can be done via adding additional argument to a kernel and outputting any subject data there.

A: Parallel Nsight 2.1 include API for trace OpenCL 1.1 now
@see http://nvidia.com/object/parallel-nsight.html


text:
Q: Passing arguments to the generic views Django queryset I would like to make a queryset on a generic view in this way:
 category_info = {
      'queryset' : ModelObject.objects.filter(category=category_id)
 }

where the category_id will be stated on the URL
 (r'^category/(?P<category_id>\d+)$', 'object_list', category_info )

But I don't know how to take the data from the URL and pass it to the category info...

A: You'll have to define your own view and return the generic view from within:
urls.py:
(r'^category/(?P<category_id>\d+)$', 'myapp.views.category_list')

myapp/views.py
from django.views.generic.list_detail import object_list
def category_list(request, category_id):
    queryset = ModelObject.objects.filter(category=category_id)
    return object_list(request, queryset=queryset)

You can also customise the generic view further, using the parameters mentioned in the documentation. (You may like to also verify that the category exists, throwing a 404 when it doesn't)


text:
Q: Check whether an app is installed in a paired device Is there a way to search another devices installed application using bluetooth? Actual requirement is, is there a way to search the paired devices installed applications.
Any help is really appreciated.

A: Sorry, but this is not possible, unless you specifically have your own app on both sides and are somehow enabling this yourself. There is nothing built into Android to allow an arbitrary device to attack another arbitrary device (e.g., get at private information like installed applications).


text:
Q: Save multiple selection and retrieve selected using select2 I have a profile edit form below in which I am asking the user to select multiple cities (I left 4, but on my page I am looking to add around 29,000) from a select2 dropdown menu using the following code, but the selected values do not save when I press the submit button and therefore when the page reloads there are no selected values.
  <form action="/edit-my-profile/?action=edit&job_id=5792" method="post" id="submit-job-form" class="job-manager-form" enctype="multipart/form-data">
<fieldset class="fieldset-html">
                HTML

                    <select name='job_listing_region[]' id='regions' style='width:300px' multiple>
  <option>Boca Raton,FL</option>
  <option>New York City, NY</option>
  <option>Los Angeles, CA</option>
  <option>Boone, NC</option>
</select>

</fieldset>

            <input type="hidden" name="job_manager_form" value="edit-job" />
            <input type="hidden" name="job_id" value="5792" />
            <input type="hidden" name="step" value="0" />
            <input type="submit" name="submit_job" class="button" value="Save changes" />

</form>

and the following jquery script

Is there a way I can have the selection box save the selected values?


text:
Q: migrate from local sqlite3 to mysql : django.db.utils.ProgrammingError: (1146, "Table '' doesn't exist") At the moment my app is working with a local database sqlite  db.sqlite3 my goal is to migrate (without losing data ) to a mysql database hosted in AWS. I follow the steps below, but  at step 3 I get the Programming Error: the table schema.tablename doesn't exist.

*

*python manage.py dumpdata > db.json

*Change the database settings to new database such as of MySQL.

#DATABASES = {
#    'default': {
#        'ENGINE': 'django.db.backends.sqlite3',
#        'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
#    }
#}

DATABASES = {
    'default':{
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'guidemeto',
        'HOST':'----',
        'PORT': '3306',
        'USER': 'dbmasteruser',
        'PASSWORD': '----',
    }
}

*python manage.py migrate

*python manage.py shell

*Enter the following in the shell

from django.contrib.contenttypes.models import ContentType
ContentType.objects.all().delete()

*python manage.py loaddata db.json
At step 3 I get the following error:
    _mysql.connection.query(self, query)
    MySQLdb._exceptions.ProgrammingError: (1146, "Table 'mydb.mytable' doesn't exist")

    The above exception was the direct cause of the following exception:
    ...
    django.db.utils.ProgrammingError: (1146, "Table 'mydb.mytable' doesn't exist")

A: Not sure if I understood correctly but you're first changing the database in step 2, and then trying to delete tables from database that django is no longer connected to?
In any case if you're trying to just delete the sqllite DB along with the tables once you're done with import, you can just delete the local file and that should be it.

A: The solution that worked for me is
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
    },
    'new':{
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'guidemeto',
        'HOST':'----',
        'PORT': '3306',
        'USER': 'dbmasteruser',
        'PASSWORD': '----',
    }
}

*

*python manage.py makemigrations

*python manage.py migrate --database=new

*python manage.py shell
Enter the following in the shell

from django.contrib.contenttypes.models import ContentType
ContentType.objects.all().delete()

*python manage.py loaddata db.json --database=new

and finally, the new database can be set as default.


text:
Q: Problem book recommendations on complex manifolds I came across the book on Cauchy Riemann manifolds, "CR manifolds and tangential Cauchy Riemann complexes". The book does not have a problem section. I would be grateful if anyone recommends some problem books on this topic "Complex manifold" and that would also serve as a supplement to this book.

A: My book, https://www.jirka.org/scv has a little bit on the topic with exercises, but really only for hypersurfaces.  It may be good to go through something like Lee's Smooth Manifolds.  Lots of exercises, though on manifolds in general, not CR manifolds specifically.  CR manifolds are really just smooth manifolds with a certain structure defined.
Krantz also covers CR manifolds to a certain extent and has lots of exercises.  So does D'Angelo.  Though, I can't think of an elementary textbook with exercises specifically on CR manifolds.
I learned CR geometry from the Baouendi, Ebenfelt, Rothschild.  But no exercises there either.


text:
Q: Does JPA over Hibernate maintain a pool of objects for entity beans like EJB does for stateless session beans? I do know that EJB, and I guess Spring does the same, maintain a pool of instances of stateless session beans, my question is if JPA implemetations maintain a pool for Entity beans as well?
It seems to me that it could be useful when there is a need for retrieving a large quantity of instances as the instances would be polled form the pool instead of being create on demand.
Any opinions on if it would have a major impact on big lists of objects are also welcome.


text:
Q: Prove that $||x-y||·||x+y|| < ||x||^2+||y||^2$ I have a doubt to prove this exercise:
$$||x-y||·||x+y|| < ||x||^2+||y||^2 \;\;\;\;\; \forall\; x,y \in R^n$$
What I've done:
$$||x-y||·||x+y|| = \sqrt{(x-y,x-y)(x+y,x+y)} = \sqrt{((x,x)+(-y,-y))((x,x)+(y,y)}) = \sqrt{((x,x)+(y,y))^2} = (x,x)+(y,y) = ||x||^2+||y||^2$$
But then, $||x-y||·||x+y|| = ||x||^2+||y||^2$, not $<$.
Why?
Thanks in advance

A: Let us do it by parts. To start with, we have
\begin{align*}
\lVert x-y\rVert^{2} = \langle x - y,x - y\rangle = \lVert x\rVert^{2} - 2\langle x,y\rangle + \lVert y\rVert^{2}
\end{align*}
Analogously,
\begin{align*}
\lVert x+y\rVert^{2}= \langle x + y,x + y\rangle = \lVert x\rVert^{2} + 2\langle x,y\rangle + \lVert y\rVert^{2}
\end{align*}
which implies that
\begin{align*}
\lVert x-y\rVert^{2}\times\lVert x+y\rVert^{2} = (\lVert x\rVert^{2} + \lVert y\rVert^{2})^{2} - 4\langle x,y\rangle^{2} \leq (\lVert x\rVert^{2} + \lVert y\rVert^{2})^{2}
\end{align*}
from whence the result holds.


text:
Q: How can I split the content of a tag to multiple tags via regex? I have a XML file with hundreds of tags which looks like this:
<entry id="1">
  <title>Title 1</title>
  <tags>kw1,kw2,kw3</tags>
</entry>

[...]

<entry id="200">
  <title>Title 200</title>
  <tags>kw3</tags>
</entry>

Now, instead of the tags tags I have to add tag tags for every entry inside:
<entry id="1">
  <title>Title 1</title>
  <tag>kw1</tag>
  <tag>kw2</tag>
  <tag>kw3</tag>
</entry>

...

<entry id="200">
  <title>Title 200</title>
  <tag>kw3</tag>
</entry>

So is it possible to split the original tags and add its contents to new ones via regex?

A: Use a parser as per this answer: RegEx match open tags except XHTML self-contained tags
There are a lot of problems using regex to doing this.

A: Since you just want to replace tags with tag..you can use the following to match:
(<\/?)tags>

and replace with:
$1tag>

See DEMO


text:
Q: Heartbeat (Linux HA) and NetApp? Does anyone have any experience setting up a high availability two node Linux cluster using heartbeat (linux-ha.org) and NetApp storage (preferably using SnapDrive for Linux)?
Basically I would like to mount the same NetApp LUN over Fibre Channel to two servers in an Active/Passive mode (only one server can access the LUN at a time)
Thanks!

A: What's your question?  It's technically possible.
Unless there's a requirement otherwise, I would probably have the storage mounted in a resource script as opposed to keeping it mounted at all times.

A: So as you have specified using a LUN via fibre channel, then you would also need to have a clustered file system. At that point is there a reason you are not using nfs ?
As warner says why would you want to do it ? I am pretty sure you could do it but you would treat as any other system. eg

*

*Create the lun

*Present the lun to the hosts

*Format clustered filesystem

*Mount on each host.

However what are you trying to do that needs a clustered file system rather than simple nfs ?

A: You don't need a clustered file system for what you are trying to do (at least not on Linux). What you want to do is mount that file system from the LUN only once wich heartbeat/pacemaker should do just fine as your file system is a resource with defined ownership. Presenting a LUN to two hosts at the same time is generally not a problem (on Linux).