text:
Q: How to put a graph inside Beamer or Prosper? I am very confused right now as to how to implement what I already have into either Beamer or Prosper for presentation...I have tried using both and putting it in different ways, but it is not working. I got it to work one time but it only showed 2 "Project Boxes" (there are 5 total) on the page. What I have originally is below, and any help with getting it into Beamer/Prosper for presentation would be greatly appreciated. Thanks!
\documentclass[landscape, 12pt]{report}
\usepackage{ocgx}
\usepackage{tikz}
\usepackage{array}

\addtolength{\oddsidemargin}{-2.90in}
\addtolength{\evensidemargin}{-2.90in}
\addtolength{\textwidth}{4in}

\newcommand{\myarrow}{\raisebox{1ex}{\tikz \draw[->, line width=1.25mm] (0,0)--++(1,0);}}

\newcommand{\ocgItem}[2]{%
\colorbox{%
\ifcase#1 \or
red\or
green\fi
}{\huge Item 1}%
}
\begin{document}
\begin{minipage}[t]{5cm}
\switchocg{ocg1}{%
\fcolorbox{black}{white}{%
    \bfseries\Large%
    \resizebox{5cm}{!}{\begin{tabular}{c c c c c c c c c c c c c c}
\\
\\
\\
  {\Huge Project 1} \\
\\
\\
\\
\end{tabular}}}}\\%
    \begin{ocg}{OCG 1}{ocg1}{0}
            \colorbox{white}{%
                \parbox{10cm}{%
                    \colorbox{green}{\begin{center}
\begin{tabular}{m{4.18cm}}
  Step 1
\end{tabular}
\end{center}
}\\%
                    \colorbox{red}{\normalsize \color{white}{\begin{center}
\begin{tabular}{m{4.3cm}}
  Step 2
\end{tabular}
\end{center}}}\\%
                    \colorbox{green}{\normalsize \begin{center}
\begin{tabular}{m{4.3cm}}
  Step 3
\end{tabular}
\end{center}}\\%
                    \colorbox{red}{\normalsize \color{white}{\begin{center}
\begin{tabular}{m{4.3cm}}
  Step 4
\end{tabular}
\end{center}}}\\%
                    \colorbox{green}{\normalsize \begin{center}
\begin{tabular}{m{4.3cm}}
  Step 5
\end{tabular}
\end{center}}\\%
                    \colorbox{green}{\normalsize \begin{center}
\begin{tabular}{m{4.3cm}}
  Step 6
\end{tabular}
\end{center}}%
                    }%
                 }
    \end{ocg}
\end{minipage}%
\indent \myarrow
\indent \begin{minipage}[t]{5cm}
\switchocg{ocg2}{%
\fcolorbox{black}{white}{%
    \bfseries\Large%
    \resizebox{5cm}{!}{\begin{tabular}{c c c c c c c c c c c c c c}
\\
\\
\\
  {\Huge Project 2} \\
\\
\\
\\
\end{tabular}}}}\\%
    \begin{ocg}{OCG 2}{ocg2}{0}
            \colorbox{white}{%
                \parbox{10cm}{%
                     \colorbox{red}{\normalsize \color{white}{\begin{center}
\begin{tabular}{m{4.3cm}}
  Step 1
\end{tabular}
\end{center}}}\\%
                    \colorbox{green}{\normalsize \begin{center}
\begin{tabular}{m{4.3cm}}
  Step 2
\end{tabular}
\end{center}}%
                    }%
                }
    \end{ocg}
\end{minipage}%
\end{document}

A: As your example unfortunately does not compile for me, this answer is based on the answer to your previous question https://tex.stackexchange.com/a/316483/36296
So converting the code to beamer is pretty simple, just replace the outermost minipage by a frame environment:
\documentclass{beamer}
\usepackage{ocgx}
\usepackage{tikz}
\usepackage{lipsum}
\usepackage{calc}
\newlength{\BOXlength}
\setlength{\BOXlength}{%
    \widthof{%
        \fcolorbox{black}{white}{%
            \bfseries\Large%
            \resizebox{2cm}{!}{Box 2}}}%
}

\newcommand{\ocgItem}[2]{%
    % input:
    % #1: colorselection. write 1 here for red, 2 for green
    % #2: The Text displayed.
    % Example: \ocgItem{2}{Item 1}\\% Produces green
    \colorbox{%
        \ifcase#1 \or
        red\or%1
        green\fi%2
    }{\huge #2}%
}
\begin{document}
    \begin{frame}
        \centering
        \begin{minipage}[t]{\BOXlength}
            \switchocg{ocg1}{%
                \fcolorbox{black}{white}{%
                    \bfseries\Large%
                    \resizebox{2cm}{!}{Box 1}}}\\%
            \begin{ocg}{OCG 1}{ocg1}{0}
                \colorbox{white}{%
                    \parbox{10cm}{%
                        \ocgItem{2}{Item 1}\\%
                        \ocgItem{1}{Item 2}\\%
                        \ocgItem{2}{Item 3}\\%
                        \ocgItem{1}{Item 4}%
                    }%
                }
            \end{ocg}
        \end{minipage}\hspace{2em}
        \begin{minipage}[t]{\BOXlength}
            \switchocg{ocg2}{%
                \fcolorbox{black}{white}{%
                    \bfseries\Large%
                    \resizebox{2cm}{!}{Box 2}}}\\%
            \begin{ocg}{OCG 2}{ocg2}{1}
                \colorbox{white}{%
                    \parbox{10cm}{%
                        \ocgItem{1}{Item 1}\\%
                        \ocgItem{2}{Item 2}\\%
                        \ocgItem{1}{Item 3}\\%
                        \ocgItem{2}{Item 4}%
                    }%
                }
            \end{ocg}
        \end{minipage}%
\end{frame}
\end{document}


text:
Q: How to assign allow all action `*/` to a specific role using code in Yii2? I am creating new role using the below code.
use yii\rbac\PhpManager;
$r=new PhpManager;
$r->init();
$r->createRole("admin","Администратор");
$r->save();

I am assigning the above role to specific user.
$r->assign('1','admin');   //1 is user id

So how can i assign allow all action to the above role admin using php code.
Basically after run the migration i want to create a user as admin role and allow all the action's for this role.

A: If you are using the behavior yii\filters\AccessControl in your controllers, you could replace it with your own one in your bootstrap.php:
Yii::$classMap['yii\filters\AccessControl'] = @common/components/filters/AccessControl.php

Add the appropriate role in your AccessControl class, by copying the original AccessControl.php in your AccessControl.php and by extending the init function. At the end of init function just add your role:
public function init()
{
...
...
    $this->rules[] = [
        'allow' => true,
        'roles' => ['admin'],
    ];
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: How can I treat html pages as jsp pages? OS: Windows Server 2008 R2 SP1
Web Server Front-End: IIS 7.5
Web Server Back-End: Tomcat 5.5
AJP Connector is used to pass JSP content from IIS to Tomcat.
I have a number of project folders that get delivered for web consumption every so often. The web pages themselves end with the HTML extension. They need to be hosted on a Tomcat web server and I need session management control via a JSP application. That is, it's not enough for me to check if the session is active for Tomcat. I have some session control specific to the JSP application itself.
I suppose I could run a script which takes the multitude of HTML pages and converts them into JSP, but I'd like to keep things as "drag-and-drop" friendly as I can. I'd rather not make any changes directly to these project folders.
Is there a way I can enforce Tomcat to treat HTML pages as JSP pages? I.e., If, for example, I wanted to include JSP expressions inside the HTML pages, I could do that.
Thank you very much for any help.

A: Jsp pages are similar to html pages they are actually scripts included inside  html pages, they are written in between <html></html> tag
so you can access jsp pages as html
Just save those pages with.html extension


text:
Q: Multiple conditions in an IF statement in Excel VBA "end if without block if"" im total beginner in VBA, i'm working on cleaning web logs from unnecessary data (rows containing .jpg, .gif, ...) I've found code which does exactly what i need to do, but i get ERROR "compile error: end if without block if"
Sub clean()
Dim r As Long, endRow As Long, pasteRowIndex As Long

endRow = 321085

For r = endRow To 1 Step -1
  Select Case Cells(r, Columns("F").Column).Value
        Case "*.jpg*", "*.JPG*", "*.gif*"
            Rows(r).Delete
        Case Else
            ' Do nothing...

    End Select

    End If
 Next r
End Sub

A: To use a wildcard with Select Case, you can use Like:
Sub clean()
Dim r As Long, endRow As Long, pasteRowIndex As Long

' I assume your column F has the most data
endRow = Cells(Rows.Count, "F").End(xlUp).Row

For r = endRow To 1 Step -1
  Select Case True
        Case Cells(r, "F").Value Like "*.jpg*" or Cells(r, "F").Value Like "*.JPG*" or Cells(r, "F").Value Like "*.gif*"
            Rows(r).Delete
        Case Else
            ' Do nothing...
    End Select
 Next r
End Sub

Edit: There's likely a better way, by putting the values you want to find in an Array, then search the array, but the above should work with the current method.


text:
Q: Eclipse Nsight CDT plugin pressing F3 to Open Declaration goes to the wrong line Nsight Eclipse Edition
Version: 5.5.0
CDT version: 8.1.2.nvidia-qualifier
Quick reference upon mouse over pops up the wrong declaration. Usually it's a function, which is located at the same header file, as the one I'm looking for, but it has no relation to it so far. For example:
For cudaMemcpy() it shows me this function from "cuda_runtime_api.h":
extern __host__ cudaError_t CUDARTAPI cudaPointerGetAttributes(struct cudaPointerAttributes *attributes, void *ptr);

For cudaMalloc() it gives me the description of:
extern __host__ cudaError_t CUDARTAPI cudaMemcpy2DToArray(struct cudaArray *dst, size_t wOffset, size_t hOffset, const void *src, size_t spitch, size_t width, size_t height, enum cudaMemcpyKind kind);

Why is indexing behaving this way? I'm getting tired of it after a couple of days working, but still couldn't find any obvious solution for this issue.

A: I will log this issue in our issue tracker. Sorry for the inconvenience. There is no workaround available.
Note that for performance reasons, Nsight does not index those files on your system. Instead, it comes prepackaged with compiled index files - apparently some headers might be different from the versions Nsight index was built from.


text:
Q: Proof about gcd and remainders
Possible Duplicate:
Why is $\gcd(a,b)=\gcd(b,r)$ when $a = qb + r$?

Prove: $\gcd(a, b) = \gcd(a+bq, b)$
Proof:
By the division algorithm we know:
$a = b\cdot q + r \iff r = a -b\cdot q$
Thus, we see it is equivalent to prove $\gcd(a, b) = \gcd(b, r)$
To me the claim seems straight forward, since the term $a+bq$ in the $\gcd(a+bq, b)$ is "dependent" on the $a$. That is, $\gcd(bq, b) = b$, so adding an $a$ really determines the $\gcd(a+bq, b)$.
How can I formalize this and use more mathematical terms?

A: I would suggest proving the result like this:
(i) Show that if $x$ divides $a$ and $b$, then $x$ divides $a+bq$ and $b$.
(ii) Show that if $x$ divides $a+bq$ and $b$, then $x$ divides $a$ and $b$.
Once you have done this, you will have shown that the set of common divisors of $a$ and $b$ is the same as the set of common divisors of $a+bq$ and $b$.
From this the result should follow easily. The final details depend on your official definition of $\gcd$. If, as is likely in your course, it is defined as the largest common divisor, then the result follows immediately. For since the sets of common divisors are the same, their largest element must be the same.

A: Hint $\ $ If $\rm\:c\:|\:b\:$ then $\rm\: c\:|\:a\iff c\:|\:a\!+\!b\,q.\:$ Thus $\rm\:a,\,b\:$ and $\rm\:a\!+\!b\,q,\,b\:$ have the same set C of common divisors $\rm\:c,\:$ hence they have the same greatest common divisor (= max C). $\ $ QED
Or: $\rm\: mod\ c\!:\ if\ \ b\equiv 0\ \ then \ \ a\equiv 0\iff a+b\,q\equiv 0,\ $ using congruence language.

A: One strategy to show that two positive integers are equal is to show that they divide each other. This is common in number theory.
Let $a, b, q\in\mathbb{N}$. Let $d_1=gcd(a+bq, b)$ and $d_2=gcd(a,b)$. We show that $d_1\mid d_2$ and $d_2\mid d_1$; thus showing they are equal.
Since $d_1=gcd(a+bq, b)$ we have that $d_1\mid b$ and $d_1\mid a+bq$ but since $d_1\mid b$ we have $d_1\mid bq$ thus $d_1\mid a$ (You can show this by writing down the congruence). Since $d_1\mid a$ and $d_1\mid b$ we have $d_1\mid d_2$.
Since $d_2=gcd(a,b)$ we have $d_2\mid b$ and $d_2\mid a$. Since $d_2\mid b$ we have $d_2\mid bq$ and hence $d_2\mid a+bq$ and $d_2\mid b$ hence $d_2\mid d_1$.


text:
Q: Using regex in simple if statements? Instead of doing:
puts "what type of input?"
input = gets.chomp
if %W[Int INT i I Ints ints].include?(input)
puts "enter int"
i = gets.to_i

I want to use regex to interpret string user input. For example,
puts "are you entering in a string, an int or a float?"
case gets
when /\A(string|s)\z/i
puts "enter in a string"
gets.chomp
when /\A(int|i)\z/i
puts "enter an int"
gets.to_i
when /\A(float|f)\z/i
puts "enter a float"
gets.to_f
end

What is the syntax in order to get the same result but using  if statements instead of case statement?

A: gets returns a string with a trailing carriage return. What you need is to match the ending against \Z, not \z.
puts "are you entering in a string, an int or a float?"
case gets
when /\As(tring)?\Z/i
puts "enter in a string"
gets.chomp
when /\Ai(nt)?\Z/i
puts "enter an int"
gets.to_i
when /\Af(loat)?\z/i
puts "enter a float"
gets.to_f
else puts "Didn't work"
end

I also slightly updated regexps to clearly show the intent.

A: If you want to turn your case into an if, you have to store the expression intended for the gets into a variable:
response=gets.chomp
if /..../ =~ response
   ...
elsif /.../ =~ response
   ....
....
else
   ...
end


text:
Q: Examples of code successfully compiled in C++11 and pre-C++11 that behave differently C++11 brought new keywords and new changes to core aspects of the language.
So could it be possible to successfully compile the same piece of code in both C++11 and pre-C++11, but get different results from each binary?  By  pre-C++11, I'm referring to C++98, C++03, or C++TR1.
The reason I ask, is because I have a bunch of small programs all written in C++.  I am unaware what standard was in mind for each individual program written.  Is the behaviour of these programs guaranteed to be the same if they all compile in C++11 as well as an earlier standard?  I would like to compile them all in C++11(if they can be), but avoid any subtle changes that may cause the programs to behave differently had an earlier standard been in mind.
Working examples would be greatly appreciated.

A: As chris points out, this is a duplicate of this question.  However I did not see in the answers to that question the following:
#include <vector>
#include <iostream>

struct X
{
    X() {std::cout << "X()\n";}
    X(const X&) {std::cout << "X(const X&)\n";}
};

int
main()
{
    std::vector<X> v(3);
}

In C++03 this outputs:
X()
X(const X&)
X(const X&)
X(const X&)

In C++11 this outputs:
X()
X()
X()

For almost all code, this makes no difference.  However "almost" is not "always", so this is a breaking (behavioral difference) change.  You can blame me personally for this change.  Without it:
std::vector<std::unique_ptr<int>> v(3);

would not have compiled.  And I considered this case sufficiently motivating for the breakage.


text:
Q: Frequent BSOD "THREAD_STUCK_IN_DEVICE_DRIVER" Before anything else, I'd like to inform everyone that this is a redo of an original post I made which was closed due to incomplete details. Now I have included what others have asked me to do in the original. (Original: https://superuser.com/questions/990227/sudden-bsod-at-random-times?)
So I was browsing the internet using Google Chrome and came to a school's website. All of a sudden, a BSOD appeared with the message:

THREAD_STUCK_IN_DEVICE_DRIVER

I ran a full malware scan using Malwarebytes Anti-Malware and it had found 2 Potentially Unwanted Programs (PUPs):

I downloaded BlueScreenView and went to the latest Blue Screen of Death's dump and this is what I found:

It says that it was caused by driver vdrvroot.sys.
If anyone needs my PC's information, I gathered them using Piriform Speccy:

*

*Operating System: Windows 10 Home Single Language 64-bit

*CPU: Intel Core i3 3217U @ 1.80GHz
Ivy Bridge 22nm Technology

*RAM: 4.00GB Single-Channel DDR3 @ 798MHz (11-11-11-28)

*Motherboard: ASUSTeK COMPUTER INC. X450CP (SOCKET 0)

*Graphics: Generic PnP Monitor (1366x768@60Hz)
Intel HD Graphics 4000 (ASUStek Computer Inc)
1024MB ATI AMD Radeon R5 M240 (ASUStek Computer Inc)

*Storage: 465GB Hitachi HGST HTS545050A7E680 (SATA)

*Optical Drives: TSSTcorp CDDVDW SU-228FB

*Audio: Realtek High Definition Audio

This isn't the only time the BSOD with the same message happened. It often happens when my PC is out of my sight, when I connect to the internet, while browsing the internet, and using some programs.
I've updated to Windows 10 from Windows 8.1 last August. Could this be a problem caused by Windows 10's automatic updates?
If anyone knows a solution to this, I'd highly appreciate it. If you guys need more details, please tell me what's missing and I'll add it.
Update:
Here's a link of the dmps from the minidump folder: https://www.dropbox.com/s/8y3g2lpeq57bp0n/Minidump%20copy.zip?dl=0

A: BlueScreenView shows, as always, a wrong cause. When analyzing the dmp in Windbg by running !analyze -v it shows that the crash is caused by the AMD GPU driver atikmdag.sys:
*******************************************************************************
*                                                                             *
*                        Bugcheck Analysis                                    *
*                                                                             *
*******************************************************************************

THREAD_STUCK_IN_DEVICE_DRIVER_M (100000ea)
The device driver is spinning in an infinite loop, most likely waiting for
hardware to become idle. This usually indicates problem with the hardware
itself or with the device driver programming the hardware incorrectly.
If the kernel debugger is connected and running when watchdog detects a
timeout condition then DbgBreakPoint() will be called instead of KeBugCheckEx()
and detailed message including bugcheck arguments will be printed to the
debugger. This way we can identify an offending thread, set breakpoints in it,
and hit go to return to the spinning code to debug it further. Because
KeBugCheckEx() is not called the .bugcheck directive will not return bugcheck
information in this case. The arguments are already printed out to the kernel
debugger. You can also retrieve them from a global variable via
"dd watchdog!g_WdBugCheckData l5" (use dq on NT64).
On MP machines it is possible to hit a timeout when the spinning thread is
interrupted by hardware interrupt and ISR or DPC routine is running at the time
of the bugcheck (this is because the timeout's work item can be delivered and
handled on the second CPU and the same time). If this is the case you will have
to look deeper at the offending thread's stack (e.g. using dds) to determine
spinning code which caused the timeout to occur.
Arguments:
Arg1: ffffe0015134d800, Pointer to a stuck thread object.  Do .thread then kb on it to find
    the hung location.

 # Child-SP          RetAddr           Call Site
00 ffffd001`67194078 fffff801`d7e2e18c nt!KeBugCheckEx
01 ffffd001`67194080 fffff801`d7e2e24e dxgkrnl!TdrTimedOperationBugcheckOnTimeout+0x24
02 ffffd001`671940f0 fffff801`da002463 dxgkrnl!TdrTimedOperationDelay+0xbe
03 ffffd001`67194130 ffffe001`553cf000 atikmdag+0x42463
04 ffffd001`67194138 00000000`00000000 0xffffe001`553cf000

    Image path: \SystemRoot\system32\DRIVERS\atikmdag.sys
    Image name: atikmdag.sys
    Timestamp:        Sat Aug 22 04:10:03 2015

Install the latest AMD Beta driver and look if this fixes it.


text:
Q: 'Proper' rounding in Python, to 3 decimal places I may be missing something essential, but I can't figure out a way to 'properly' round floats/Decimals in Python (2.7), at least to three decimal places.  By 'properly' I mean that 1.2225 should round to 1.223, and 1.2224 should round to 1.222.
I know round won't work for floats in Python, by design, but I can't seem to get Decimal to behave as expected, nor the ceil function.  Looking for built-in functionality rather than custom function workarounds preferably, but open to both.
>>> x = 1.2225                                   # expected: 1.223
>>> round(x, 3)
1.222                                            # incorrect

>>> from math import ceil

>>> ceil(x * 1000.0) / 1000.0
1.223                                            # correct
>>> y = 1.2224                                   # expected: 1.222
>>> ceil(y * 1000.0) / 1000.0
1.223                                            # incorrect

>>> from decimal import Decimal, ROUND_UP, ROUND_HALF_UP

>>> x = Decimal(1.2225)
>>> x.quantize(Decimal('0.001'), ROUND_UP)
Decimal('1.223')                                 # correct
>>> y = Decimal(1.2224)
>>> y.quantize(Decimal('0.001'), ROUND_UP)
Decimal('1.223')                                 # incorrect

>>> y.quantize(Decimal('0.001'), ROUND_HALF_UP)
Decimal('1.222')                                 # correct
>>> x.quantize(Decimal('0.001'), ROUND_HALF_UP)
Decimal('1.222')                                 # incorrect

Is there a way to get the desired result?

A: The problem is that Decimal(1.2225) is not what you expect it to be:
>>> Decimal(1.2225)
Decimal('1.2224999999999999200639422269887290894985198974609375')

You are using a float to the create the decimal, but that float is already too imprecise for your use case. As you can see, it's actually a 1.222499 so it is smaller than 1.2225 and as such would correctly round down.
In order to fix that, you need to create decimals with correct precision, by passing them as strings. Then everything works as expected:
>>> x = Decimal('1.2225')
>>> x.quantize(Decimal('0.001'), ROUND_HALF_UP)
Decimal('1.223')
>>> y = Decimal('1.2224')
>>> y.quantize(Decimal('0.001'), ROUND_HALF_UP)
Decimal('1.222')

A: Here are three solution in this link, I hope this would help you exactly what you want to do.
https://gist.github.com/jackiekazil/6201722
from decimal import Decimal

# First we take a float and convert it to a decimal
x = Decimal(16.0/7)

# Then we round it to 2 places
output = round(x,2)
# Output to screen
print output

A: Is this what you are looking for?
float('{:,.3f}'.format(2.2225))


text:
Q: How do I make document side script conditional? So I'm having trouble breaking my horizontal scroll when the viewport is 480px or below.  My scroll has this document-side script:
    <script>
        $(function () {
            $("#wrapper").wrapInner("<table><tr>");
            $(".post").wrap("<td>");
        });
        $(function () {
            $("body").mousewheel(function (event, delta) {
                this.scrollLeft -= (delta * 50);
                event.preventDefault();
            });
        });
    </script>

When I remove the table wrapping feature then the scroll breaks.  Instead I'm hoping for one of these two possible fixes:

*

*a media query command that forces the removal of a class(es) so I can then display as a block.

*a way to make the above document-side code conditional on viewport size.

Thanks in advance.  I know its not the neatest, but its the only way I was able to get the scroll to work (except on IE)
Thanks in advance.

A: Here is one way to only horizontally scroll if body is more than 480px wide:
        $("body").mousewheel(function (event, delta) {
            var $this = $(this); // 'body' in this case
            var widthLimit = 480;
            if ($this.width() > widthLimit) {
                // horizontal scroll
                this.scrollLeft -= (delta * 50);
                event.preventDefault();
            }
        });

Here is the media query that will display #wrapper as a block if the viewport is less than 480px:
@media only screen and (max-width: 480px) {
    #wrapper {
        display: block;
    }
}

Note that media queries can generally only change styling and not add or remove classes or ids.


text:
Q: Can Kinect for Windows work on an Xbox 360? I realized that this is not a less popular concern (and more popular one being the reverse) so I want to post it here. I have a Kinect for Windows but I don't have an Xbox 360 to test this, so can it work on an Xbox 360?

A: I own an Xbox 360 Slim bundled with Kinect for Xbox, and a Kinect for Windows. I tried plugging in the Kinect for Windows into the Xbox, and the console did NOT recognise it. So I can confirm that the Kinect for Windows will not work on the Xbox. On the other hand, the Kinext for Xbox -using the power adapter- does work on the PC.

A: According to Microsoft...

The Kinect for Windows sensor is a fully-tested and supported Kinect experience on Windows with features such as "near mode," skeletal tracking control, API improvements, improved USB support across a range of Windows computers and Windows-specific 10' acoustic models.
The sensor was specifically designed to be used with PCs, with a shortened USB cable to ensure reliability across a broad range of computers, and the inclusion of a small dongle to improve coexistence with other USB peripherals.
Kinect for Xbox 360, on the other hand, was built for and tested with the Xbox 360 only, not with any other platform, which is why it is not licensed for general commercial use, supported, or under warranty when used on any other platform.
Finally, Microsoft has dedicated a large team of engineers to continual improvements of hardware and software associated with Kinect for Windows, and is committed to providing ongoing access to Microsoft's deep investment in human tracking and speech recognition.

A: There doesn't seem to be a lot of information on this, but a news article on Softpedia suggests that it won't:

"Potential customers shouldn't expect to use this version of the
  sensor on an Xbox 360 console, however, as the Kinect for Windows
  works only on computers that are running the software development
  kit."

Article: Special Kinect for Windows Sensor Out on February 1, Costs $250 (€195)


text:
Q: Zoom center to mouse position image I've been following the most voted answer from here.
Pan & Zoom Image ( the one with ZoomBorder.cs).
Everything works fine if I include that into my project. However my project is a ReactiveUI application, and i struggling to replicate that code using ReactiveUI design patters.
What I have done so far :
Created a new UserControl
<UserControl x:Class="ImageViewer.Controls.ZoomControl"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
             xmlns:local="clr-namespace:ImageViewer.Controls"
             mc:Ignorable="d"
             d:DesignHeight="450" d:DesignWidth="800">
    <Border BorderThickness="10" BorderBrush="Red">
        <Image x:Name="RenderingImage" RenderTransformOrigin="0,0" Stretch="None" Source="{Binding}" ClipToBounds="True">
            <Image.LayoutTransform>
                <TransformGroup>
                    <ScaleTransform x:Name="ImageScale" ScaleX="{Binding}" ScaleY="{Binding}"/>
                    <TranslateTransform x:Name="ImageTranslate" X="{Binding}" Y="{Binding}" />
                </TransformGroup>
            </Image.LayoutTransform>
        </Image>
    </Border>
</UserControl>

Added binding between View->ViewModel
 public partial class ZoomControl : IViewFor<ZoomControlViewModel>
    {
        public static readonly DependencyProperty ViewModelProperty = DependencyProperty
       .Register(nameof(ViewModel), typeof(ZoomControlViewModel), typeof(ZoomControl), null);
        public ZoomControl()
        {
            InitializeComponent();

            this.DataContextChanged += (sender, args) => ViewModel = DataContext as ZoomControlViewModel;

            this.WhenActivated(cleanup =>
            {
                this.OneWayBind(ViewModel, vm => vm.ImageSource, v => v.RenderingImage.Source).DisposeWith(cleanup);

                this.OneWayBind(ViewModel, vm => vm.ScaleX, v => v.ImageScale.ScaleX).DisposeWith(cleanup);
                this.OneWayBind(ViewModel, vm => vm.ScaleY, v => v.ImageScale.ScaleY).DisposeWith(cleanup);
                this.OneWayBind(ViewModel, vm => vm.TranslateX, v => v.ImageTranslate.X).DisposeWith(cleanup);
                this.OneWayBind(ViewModel, vm => vm.TranslateY, v => v.ImageTranslate.Y).DisposeWith(cleanup);

                RenderingImage.Events().MouseWheel.Select(e => new Tuple<int, Point>(e.Delta, e.GetPosition(RenderingImage))).InvokeCommand(ViewModel.ZoomAction).DisposeWith(cleanup);
            });
        }

        public ZoomControlViewModel ViewModel { get => (ZoomControlViewModel)GetValue(ViewModelProperty); set => SetValue(ViewModelProperty, value); }
        object IViewFor.ViewModel { get => ViewModel; set => ViewModel = (ZoomControlViewModel)value; }
    }

In view model I have the zoom command implemented like this .
 public ZoomControlViewModel()
        {
            ZoomAction = ReactiveCommand.Create<Tuple<int, Point>>(z => Zoom(z));
        }

private void Zoom(Tuple<int, Point> deltaArgs)
        {
            int delta = deltaArgs.Item1;
            Point relativePosition = deltaArgs.Item2;

            //var ScaleTransform = GetScaleTransform();
            //var TranslateTransform = GetTranslateTransform();

            double zoom = delta > 0 ? .2 : -.2;
            if (!(delta > 0) && (ScaleX < .4 || ScaleY < .4))
                return;

            double absoluteX;
            double absoluteY;

            absoluteX = relativePosition.X * ScaleX + TranslateX;
            absoluteY = relativePosition.Y * ScaleY + TranslateY;

            ScaleX += zoom;
            ScaleY += zoom;

            TranslateX = absoluteX - relativePosition.X * ScaleX;
            TranslateY = absoluteY - relativePosition.Y * ScaleY;
        }

Now my question. For this example above zooming works fine, but it does not zoom to mouse position it zooms to LeftUp corner of the image.
From my knowledge ( here might be the problem) changing the TranslateTransform of the image (TranslateX and TranslateY) should zoom me to the current mouse position.
Any tips would be appreciated.


text:
Q: Each chapter with own contents?
Possible Duplicate:
List sections of chapter at beginning of that chapter

I'm wondering whether its possible to have each chapter of a thesis with its own
    contents page? I tried it using the next few lines, and everything works...except that the next main page is affected.
\pagestyle{empty}
\maketitle
\thispagestyle{empty}
\pagestyle{empty}

The idea is to have something like this (just an additional page, not to affect the main chapter page). However, the next page shows continuation of 1.3, doing '1.4 Introduction'
    --------------------
    Chapter One

    1.1 Introduction
    1.2 Overview
    1.3 Aims of thesis
    --------------------

Any ideas to break the link between the two pages?

A: Take a look at the minitoc package


text:
Q: How to add content to page right after a fixed navigation bar which has variable height? Currently, if I create a div just after my navigation bar it hides underneath the navigation bar. I'm new to CSS but I'm quite sure this has to do with the fixed navigation bar being taken out of the document flow.
Here is the current situation: https://jsfiddle.net/8pwcobuz/
HTML structure:
<!DOCTYPE html>

    <link rel="stylesheet" href="style.css"/>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">

List item 1

List item 2

            List item 3

List item 3.1111111111111

List item 3.2

List item 3.3

List item 4

List item 5.1

List item 5.2

List item 5.3

Relevant CSS:
#nav    {
    background-color: #333;
    position:fixed;
    width:100%;
    box-shadow: 0px 0px 10px 1px;
}

#content    {
    margin-top:50px;
}

I've tried two approaches.
First of all, I placed the navigation bar outside of the body element and adding a top-margin to the body (if this is terrible please let me know), but it didn't seem to work. My reasoning here was that fixed elements are fixed relative to the viewport, while all other positioned elements are positioned relative to the body. So by giving a margin-top to the body and just adding content like I normally would, it would work right? But it didn't.
Secondly, I tried to create a div that contains the content of the entire page, also with a top-margin to adjust for the space taken up by the fixed navigation element. This didn't work either.
In both cases, the navigation bar moves down as well when I set the margin-top property, and I only want the content to move. What am I missing here?
Additional question: Is there any way right now to do this in a responsive way without using Javascript or jQuery? I'm trying to avoid those for now, since I'm just starting out.
Thanks in advance!


text:
Q: How to delete a file with string.numbers.string format by passing a command in Airflow This is the file format I have ABD.123244.trig , when I try to remove the file in the terminal I used rm -f ABD.+([0-9]).trig, but when I use the same thru Airflow scheduler, it throwserror unexpected token '('
please help
This command rm -f ABD.+([0-9]).trig doesn't work while passing it thru Airflow scheduler. it throws error unexpected token '('

A: Airflow bash operator runs the bash command with:
bash -c "<your bash command>"

To use an extended globbing pattern in bash, you have to enable the extglob shell option. You can try:
BashOperator(task_id="bash_task", bash_command="shopt -s extglob\n rm -f ABD.+([0-9]).trig")

A: The + is not a special character in bash, therefore, your expression +(...) does not make any sense. Neither does .+.
You are thinking regular expressions instead of gobbing patterns.
Try this:
echo ABD.[0-9]*

and the whole command would be:
rm -f ABD.[0-9]*.trig


text:
Q: Powershell random color change Never used Powershell before and im trying to recreate the following Bash script in powershell:
while true; do head -c200 /dev/urandom | od -An -w50 -x | grep -E --color "([[:alpha:]][[:digit:]]){2}"; sleep 0.5; done
Here's what i got, but i want it to turn random lines into red, rather than every five instances;
while(Get-Random)
{
    Start-Sleep -Milliseconds 10
    Write-Host -NoNewline "   " (get-random)
    Start-Sleep -Milliseconds 30
    Write-Host -NoNewline "   " (get-random)
    Start-Sleep -Milliseconds 10
    Write-Host -NoNewline "   " (get-random)
    Start-Sleep -Milliseconds 30
    Write-Host -NoNewline "   " (get-random)
    Start-Sleep -Milliseconds 10
    Write-Host -NoNewline "   " (get-random) -ForegroundColor red
}

Any idea how i can go about setting "-ForegroundColor red" for random lines?

A: $color=@('gray','red')
while(Get-Random)
{   Start-Sleep -Milliseconds 10
    Write-Host -NoNewline "   " (get-random) -ForegroundColor (Get-random $color)
}


text:
Q: Virtualbox guest Ubuntu OS doesn't recognize USB I'm trying to pull a file from my USB drive from the guest OS (ubuntu 14.04) in virtualbox (5.0.10). I tried following this question's best response:
Virtualbox not seeing any usb devices in the usb filters settings
but I don't see "vboxusers" under manage groups.
In virtualbox under settings -> USB  I see the USB filter for my device but it doesn't carry over to the guest ubuntu OS. I also installed the latest virtualbox extension pack which did not solve the problem.
I just want to pull a file from the USB to ubuntu. Any help is greatly appreciated!

A: Did you install the VirtualBox 5.0.12 Oracle VM VirtualBox Extension Pack ?
If not, you can download it here:
https://www.virtualbox.org/wiki/Downloads
This should give you support for USB 2.0 and USB 3.0 devices, VirtualBox RDP and PXE boot for Intel cards.
Gael.


text:
Q: Is it possible to change the bottom layout guide y position? I would like to move the content of the whole screen up to make room for a view that I would add to the main window. Is it possible to adjust the bottom layout guide y coordinate, and make the whole view structure move up?
thanks.
ios8+

A: You can create an outlet to the bottom constraint of the view, and change its value from your code. UIView animations works fine in this case :
UIView.animateWithDuration(0.4, animations: { () -> Void in
    self.verticalBottomConstraint.constant = 44
)

Yep, the constant property of a NSLayoutConstraint is variable while the multiplier property is constant. Logic everywhere.


text:
Q: Passing function argument to retrieve data from an object I am have some trouble with a script I am working on. I have been provided with an object with multiple items from a product catalog.
What I am trying to do is to write a function which to which will allow me to render this data  easily.
<script type="application/javascript">
SKUinfo =
{
  "s238554": {
    "Age": {
      "Description": "Age 18+",
      "Thumbnail": "/productImages/assets/img/icon18.gif"
    },
    "Barcode": {
      "Barcode": "50622132430794"
    },
    "Currency": "£",
    "Description": "Description goes here",
    "Id": 44305,
     "Packshots": [
      "/productImages/238556/1min.jpg",
      "/productImages/238556/2med.jpg",
      "/productImages/238556/3max.jpg"
    ],
    "Pegis": [],
    "Platform": {
      "Button": "Xbox 360",
      "ID": 0
    },
    "Publisher": {
     "Description": null
    },
    "Release": "/Date(1392940800000+0000)/",
    "Screenshots": [
      {
        "ScreenshotMax": "/productImages/238556/5scrmax1.jpg",
        "ScreenshotMin": "/productImages/238556/4scrmin1.jpg"
      }
    ],
    "Title": "Product title 2 goes here",
    "Variants": [
      {
        "Id": 58242,
        "MaxOrderQuantity": 3,
        "Presellable": true,
        "Price": 29.97,
        "PriceCultureFormat": "29.97",
        "PriceWithCurrencyFormat": "£29.97",
        "Sku": 238556,
        "Type": {
          "Description": "New"
        }
      },
    ],
    "Vendor": {
      "Description": ""
    },
  },
  "s238556": {
    "Age": {
      "Description": "Age 18+",
      "Thumbnail": "/productImages/assets/img/pegi/icon18.gif"
    },
    "Barcode": {
      "Barcode": "5060134530794"
    },
    "Currency": "£",
    "Description": "Description here",
    "Id": 654654,
    "Packshots": [
      "/productImages/238556/1min.jpg",
      "/productImages/238556/2med.jpg",
      "/productImages/238556/3max.jpg"
    ],
    "Pegis": [],
    "Platform": {
      "Button": "PlayStation 3",
      "ID": 0
    },
    "Publisher": {
      "Description": null
     },
    "Release": "/Date(1392940800000+0000)/",
    "Screenshots": [
      {
        "ScreenshotMax": "/productImages/238556/5scrmax1.jpg",
        "ScreenshotMin": "/productImages/238556/4scrmin1.jpg"
      },
      {
        "ScreenshotMax": "/productImages/238556/7scrmax2.jpg",
        "ScreenshotMin": "/productImages/238556/6scrmin2.jpg"
      },
    ],
    "Title": "Product title 2 goes here",
    "Variants": [
      {
        "Id": 58242,
        "MaxOrderQuantity": 3,
        "Presellable": true,
        "Price": 29.97,
        "PriceCultureFormat": "29.97",
        "PriceWithCurrencyFormat": "£29.97",
        "Sku": 238556,
        "Type": {
          "Description": "New"
        }
      },
    ],
    "Vendor": {
      "Description": ""
    },
    "VideoHTML": "html here",
    "status": {
      "Response": "product found",
      "Success": true
    }
  }
}
</script>

The above example is the output I get for two products.
If I try to get access to this data this is where I have a problem
<script type="application/javascript">
function getSKU(s)
{
        console.log(SKUinfo.s.Title);
}

getSKU(s238554);

</script>

I imagine this is being caused when I am passing the argument s back to the function getSKU a the node selection in the data object. In this I would expect the console output to be the Title from SKU s238554.
What I get however, is: Uncaught ReferenceError: s238554 is not defined
I would appreciate any guidance that can be offered as I am a javascript novice.

A: Access your property by used[] on SKUinfo.s.Title like SKUinfo[s].Title
And also pass your property name within the quotes 's238554' as it's not variable.
Something like this.
function getSKU(s){
     console.log(SKUinfo[s].Title);
}

getSKU('s238554'); // s238554 within quotes.


text:
Q: GROUP BY in datatable select using c# I have a dataTable which has rows as shown in below image,
I would like to write groupby statement with select on that datatable for getting output as below,

A: select ApplicationName, count(*) from DataTableName
group by ApplicationName

where DataTableName should be replaced by the actual name of your table in the database, and ApplicationName should be replaced by the name of the column in that table that contains applicatin name

A: Simply this...
SELECT ApplicationName, COUNT(*) [Count]
FROM THETABLENAME
GROUP BY ApplicationName

or with ordering and filtering (where there is a duplication and order by the count)...
SELECT ApplicationName, COUNT(*) [Count]
FROM THETABLENAME
GROUP BY ApplicationName
HAVING COUNT(*) > 1
ORDER BY COUNT(*) DESC

A: Try this using LINQ in C#
var result = from tab in dt.AsEnumerable()
             group tab by tab["ApplicationNmae"]
                 into groupDt
                 select new
                 {
                     ApplicationNmae = groupDt.Key,
                     Sum = groupDt.Sum((r) => decimal.Parse(r["Count"].ToString()))
                 };

DataTable dt1 = new DataTable();
dt1 = dt.Clone();

foreach (var item in result)
{
    DataRow newRow = dt1.NewRow();
    newRow["ApplicationNmae"] = item.ApplicationNmae;
    newRow["Count"] = item.Sum;
    dt1.Rows.Add(newRow);
}

Grid.DataSource = dt1;

Ref: Group by in DataTable Column sum


text:
Q: PowerQuery (or PowerPivot): Updated Rows Only? I'm trying to explore PowerPivot, and as far as I can tell it always wants to work with local data.
If the data-download were a one-time hit, then I could work with that - but whenever I want to refresh it appears to go and refetch all the data again.
Is there any way to use PowerBI (or the underlying PowerQuery) so that it can fetch only new or modified rows and add them to it's current dataset? For example, would a OData feed behave this way?
The backend DB in my case will be MSSQL or SSAS. I control the DB and could add change-tracking columns etc...if need be.

A: You could conceivably load in the bulk of your data up to a point in time and use that as a table named Static which you then append another table named Dynamic which only fetches rows that you specify (using a filter on a change-tracking column) that are added after that point in time.
The problem with this is that nothing from the Dynamic table ever makes its way into the Static table and you end up reloading stuff unnecessarily.
It's probably possible to implement a solution to pass rows into the Static table, but at that point, you're basically using the PowerPivot data model as a database, which probably isn't best practice.


text:
Q: Allow User Account to run a single command using SUDO privelages I have a machine running Ubuntu 12.10. I have two user accounts setup, my account, and another user. I am able to run SUDO commands, but the other user isn't in the SUDO'ers list.
What I'm trying to do is give mininal permissions for the other user to run a single SUDO command. Basically to eject an Amazon Kindle USB device.
sudo eject /dev/sdc1

When plugging the Kindle in to the USB port, the device is mounted. If the user simply Ejects the device using the UI, the device is unmounted but not ejected - so the device can pull charge from the PC.
Ejecting the Kindle using the command above works on my account, allowing me to charge the Kindle. But when the other user is logged in, he can't run the command.
Is there a way to allow a user account to run a single command with SUDO permissions?

A: Use sudoedit to edit the file /etc/sudoers
Underneath the line root    ALL=(ALL:ALL) ALL
Enter the line below and replace ejectuser with the actual username
ejectuser ALL=(root)NOPASSWD:/usr/bin/eject


text:
Q: WPF how do I change the binding of a ContextMenu inside an itemControl My goal is to disable/collapse a menuitem if the user does not have the rights to it.
The binding i'm looking for is in my ViewModel as a boolean. I know that it's trying to find the property "IsAdmin" inside of the property "InstructionsUpdates". I just can't find a way to make the menuitem use the datacontext of the window.
Viewmodel:
 Public Property IsAdmin As Boolean
    Get
        Return _IsAdmin
    End Get
    Set
        SetValue(_IsAdmin, Value)
    End Set
End Property

Public Property InstructionsUpdates As ObservableCollection(Of ClsInstruction)
    Get
        Return _InstructionsUpdates
    End Get
    Set
        SetValue(_InstructionsUpdates, Value)
    End Set
End Property

Public Class ClsInstruction
    Public FileName As String = ""
    Public Property Name As String = ""
    Public Property IsChecked As Boolean = False
    Sub New(nName, nFileName)
        Name = nName
        FileName = nFileName
    End Sub
End Class

Public Sub New()
    IsAdmin = False
End Sub

XAML:
<ItemsControl x:Name="InstructionsItemControl"  ItemsSource="{Binding InstructionsUpdates}">
                                <ItemsControl.ItemsPanel>
                                    <ItemsPanelTemplate>
                                        <UniformGrid Columns="2" ScrollViewer.CanContentScroll="True"/>
                                    </ItemsPanelTemplate>
                                </ItemsControl.ItemsPanel>
                                <ItemsControl.ItemTemplate>
                                    <DataTemplate>
                                        <StackPanel Orientation="Horizontal">
                                            <StackPanel.ContextMenu>
                                                <ContextMenu>
                                                    <MenuItem x:Name="MnuViewInstruction"
                                                              Click="MnuViewInstruction_Click"
                                                              Header="Preview">
                                                        <MenuItem.Icon>
                                                            <iconPacks:PackIconMaterialDesign Kind="Pageview"/>
                                                        </MenuItem.Icon>
                                                    </MenuItem>
                                                    <MenuItem x:Name="MnuEdit"
                                                              Click="MnuEdit_Click"
                                                              Header="Edit (Binding not working)"
                                                              IsEnabled="{Binding IsAdmin}">
                                                        <MenuItem.Icon>
                                                            <iconPacks:PackIconMaterial Kind="FileEdit" />
                                                        </MenuItem.Icon>
                                                    </MenuItem>
                                                </ContextMenu>
                                            </StackPanel.ContextMenu>
                                            <CheckBox IsChecked="{Binding IsChecked}"/>
                                            <Label Content="{Binding Name}"/>
                                        </StackPanel>
                                    </DataTemplate>
                                </ItemsControl.ItemTemplate>
                            </ItemsControl>

I've tried:
IsEnabled="{Binding IsAdmin, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type Window}}}">

And:
 IsEnabled="{Binding DataContext.IsAdmin, ElementName=MainWindow1}">

"MainWindow1" being the x:Name I gave to my window to test it out
I've also tried using a window.ressource and then putting it inside my stackpanel, but turns out bindings don't work inside a ressource (form what I've seen)

A: This will work, this is a bit tricky since neither DataTemplate not ContextMenu elements can use ElementName
<ItemsControl x:Name="InstructionsItemControl"  ItemsSource="{Binding InstructionsUpdates}">
        <ItemsControl.ItemsPanel>
            <ItemsPanelTemplate>
                <UniformGrid Columns="2" ScrollViewer.CanContentScroll="True"/>
            </ItemsPanelTemplate>
        </ItemsControl.ItemsPanel>
        <ItemsControl.ItemTemplate>
            <DataTemplate>
                <!--The Tag property of the StackPanel will contain the DataContext of the Window (the viewModel)-->
                <StackPanel Orientation="Horizontal" Background="Green" Tag="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=Window}, Path=DataContext}">
                    <StackPanel.ContextMenu>
                        <!--The Tag of the element posessing the ContextMenu is retrieved and stored in the Tag property of the ContextMenu-->
                        <ContextMenu Tag="{Binding Path=PlacementTarget.Tag, RelativeSource={RelativeSource Mode=Self}}">
                            <MenuItem x:Name="MnuViewInstruction"
                                                          Header="Preview">
                            </MenuItem>
                            <!--The Tag property of the contextMenu contains a reference to the viewModel of the window-->
                            <MenuItem x:Name="MnuEdit"
                                                          Header="Edit (Binding not working)"
                                                          IsEnabled="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=ContextMenu}, Path=Tag.IsAdmin}">
                            </MenuItem>
                        </ContextMenu>
                    </StackPanel.ContextMenu>
                    <CheckBox IsChecked="{Binding IsChecked}"/>
                    <Label Content="{Binding Name}"/>
                </StackPanel>
            </DataTemplate>
        </ItemsControl.ItemTemplate>
    </ItemsControl>

Related answers :
Binding ElementName inside a DataTemplate
and
WPF Databinding ContextMenu of Button inside a DataTemplate inside an ItemsControl


text:
Q: Work with Unions and hexa in C++ I have the following program about Union. I haven't really worked with many but from what i understood elements of a Union share the same memory space. Furthermore when i first looked at my teacher slides i thought it's was something similar in a way like structs but no. Anyway so i attempted to print on of a Union value but i don't understand it. Can someone tells me why it only prints 1 and ignore the first 5 characters? second question;
is there a way to compute a ^= b; without converting a and b in binary? it's a question from a midterm practice and i thought there could be a faster way to solve since it's a C++ course and not a digital system course.
// Example program
#include <iostream>
#include <string>

union Combi {
 int i;
 short s;
};

int main()
{
 unsigned int a = 0xFF, b= 0x0F0F;
a ^= b;

 Combi c;
c.i = 0xFF0001;
std::cout << c.s<<" "<<a;

}

A: I believe short holds less bits than required to show the FF. Think of it like a 0xffff mask, which thus hides all bits higher than that.
Edit: Ok, in more depth, the int and short share the same location in memory. But when you specify the format, you'll get the memory data in that format (in memory, it's just a bunch of bits anyway).
So the whole Union takes up only the size of the biggest component; the int in this case.
Pretend it starts at 0x00000000.
You then set the int (the whole memory segment) to 0xFF0001.
Now it looks like 0x00FF0001.
Now you want to print out the data as a short, but a short normally only looks like 0x0000. So in this case we ignore the top half 0x00FF, and our short is the remaining part: 0x0001.
Hence you get the output of 1.

A: A union is a data structure where the data can be viewed different ways. The compiler gives enough memory to c to store its longest entry. When you assign 0xFF0001 to c.i, that also assigns c.s, because they overlap. When you tell it to print c.s, it prints the memory, but assumes you only want to see a short. That's why you see only 1 and not the other characters.

second question; is there a way to compute a ^= b; without converting a and b in binary?

Yes; in fact, that's what the program does (that's hexadecimal format, not binary). Just assign the corresponding decimal values, if you like, and a ^= b will work exactly the same way. Writing it in binary or hexademical format just makes it easier to read.


text:
Q: How to change the alignment of list bullets I have used an image in place of bullets in my unordered list and I want to make it centered according to the text. My bullet is not in the center. How can I change its position?

.ul {
    list-style-image: url(../images/arrow.svg);
  }//This is code for replacing default bullets with with image

A: try ::before example:
ul {
  position: relative;
}
ul::before {
  position: absolute;
  top: 50%; /* transform image to center */
  transform: translateY(-50%); /*transform image to center */
  left: 20px; /* custom change*/
  background-image: url('../images/arrow.svg');
  background-size: 10px 20px; /* custom size Here  must be same as width and height*/
  display: inline-block;
  width: 10px;  /* custom size Here */
  height: 20px; /* custom size Here */
  content:"";
 }


text:
Q: Weblogic Stuck Thread - ArrayList We have JSF2.1 app deployed in weblogic10.3.4 ,in one of our backing bean ,when we try to assign the reference ArrayList to a List instance ,weblogic ends up in Struck thread ,during peak  traffic to our application.
java.util.ArrayList.indexOf(ArrayList.java:210)
java.util.ArrayList.contains(ArrayList.java:199)

Any one has faced this issue before.

A: It is not entirely clear what you mean, so I'm going to assume that you mean a "stuck thread", and that the thread is stuck in the sense that it is continually executing at that point.
I can think of three plausible causes.

*

*The object that is being searched for has a buggy equals(Object) method that in some circumstances goes into an infinite loop.

*There are two (or more) threads accessing and/or updating the list roughly simultaneously, and you are not synchronizing properly.  If you don't synchronize properly, there is a risk that the threads will see inconsistent views of the data structure, and that that will cause it behave in a way that seems impossible.

*You've somehow set up a pathological situation that is causing one thread to be both reading and updating the list in the (incorrect) belief that it has two distinct lists.
My bet is that it is the second problem, since "heisenbugs" like that are more likely to occur when your server is under heavy load.

Finally, it is possible that the thread is not in an infinite loop, but is just taking a long time to do something.  And it is possible that the loop involves other code, but each time you look at it is at that point.


text:
Q: Why isn't sendKeys working on this Protractor script? Why isn't sendKeys working on this Protractor script?
Almost nothing I try to do in Protractor works, but this seems like it should be written right. What am I missing??
creditCardInformation = function (ccHolderName,ccNumber,ccExpirationDate,ccCvvCode,ccBillingAddress,ccBillingCity,ccBillingState,ccBillingCountry) {
        // ### USER-DEFINED VARIABLES - Credit Card
        var ccHolderName = 'Johann Sebastian';
        var ccNumber = '1111222233334444';
        var ccExpirationDate = '10/2020';
        var ccCvvCode = '896';
        var ccBillingAddress = '1313 Mockingbird Lane';
        var ccBillingCity = 'Chicago';
        var ccBillingState = 'IL';
        var ccBillingCountry = 'USA';
        // ### STATIC VARIABLES - Credit Card
        var creditCardHolderName = element(by.model('cc.cardHolderName'));
        var creditCardNumber = element(by.model('cc.creditCardNumber'));
        var creditCardExpirationDate = element(by.model('cc.expiry'));
        var creditCardCvvCode = element(by.model('cc.cvv'));
        var creditCardBillingAddress = element(by.model('cc.billingAddress'));
        var creditCardBillingCity = element(by.model('cc.billingCity'));
        var creditCardBillingState = element(by.model('cc.billingState'));
        var creditCardBillingCountry = element(by.model('cc.billingCountry'));
        // ### STATIC FUNCTIONS - Credit Card
        creditCardHolderName.sendKeys(ccHolderName);
        creditCardNumber.sendKeys(ccNumber);
        creditCardExpirationDate.sendKeys(ccExpirationDate);
        creditCardCvvCode.sendKeys(ccCvvCode);
        creditCardBillingAddress.sendKeys(ccBillingAddress);
        creditCardBillingCity.sendKeys(ccBillingCity);
        creditCardBillingState.sendKeys(ccBillingState);
        creditCardBillingCountry.sendKeys(ccBillingCountry);
    };

https://jsfiddle.net/quantumspooky/86k6z9pt/

A: Thanks to two people's downvotes without comments, I figured out what I was doing wrong here.
Instead of
creditCardInformation = function (ccHolderName,ccNumber,ccExpirationDate,ccCvvCode,ccBillingAddress,ccBillingCity,ccBillingState,ccBillingCountry)
I should have said creditCardInformation: function(creditCardHolderName,creditCardNumber,creditCardExpirationDate,creditCardCvvCode,creditCardBillingAddress,creditCardBillingCity,creditCardBillingState,creditCardBillingCountry)


text:
Q: c# winForm adding value to number in texbox In my program i have several texboxes and buttons with coresponding names (ex. TextBox1 - buttonPlus1) like on the picture

but there are filled with numbers loaded from text file.
I want to write function that allows me to press button + and enlarge (add fixed number, for example 100) value from textbox. So far i have done:
  private void buttonPlus1_Click(object sender, EventArgs e)
    {
        AddValue(sender,e);
    }

    private void AddValue(object sender, EventArgs e)
    {
        if (!(sender is Button))
            return;

        string controlName = (sender as Button).Name;
        string textBoxName = controlName.Replace("buttonPlus", "textBox");

        TextBox textBox = this.Controls.Find(textBoxName, false)[0] as TextBox;
        int step = 100;

    }

but i have no idea how to take value (as number) from textBox and add that step. Can somebody please help me? I tried to solve it by myself in many different ways, but it does not work

A: Get the value:
Convert.ToInt32(textBox.Text)

Save it to a variable, add 100 and just set it as usual.
P.S. You can also use Int32.Parse("")
textBox.Text = Convert.ToInt32(textBox.Text) + 100;

(You might need to .ToString() it)
EDIT:
As ltiong_sh mentioned, you should use TryParse rather then Parse:
int somevalue;
if(Int32.TryParse(textBox.Text, out somevalue))
{
    textBox.Text = somevalue + 100;
}

A: This is what you are looking for:
int newValue = Convert.ToInt32(textBox.Text) + step;

To put the value back in a textbox you can do the following:
textBox.Text = newValue.ToString();

Edit:
As mentioned by others you should use Int32.TryParse to prevent an error from being thrown.
if(Int32.TryParse(textBox.Text, out newValue))
{
    newValue += step;
    textBox.Text = newValue.ToString();
}

A: You need to convert String to Integer
int txtValue = Convert.ToInt32(textBox.Text) + 100;

A: Make sure your validate the text in the text field. Else at the time of parsing it will throw an exception.
You can do this
int value = 0;
if(Int32.TryParse(textBox.Text, out value))
{
   value += step;
   textBox.Text = value.ToString();
}
else
{
   //inform user to enter int
}

A: in button click get the textbox value and convert it to integer format and add 100 to it. after that reset textbox value to modified one's. Here is what you need.
private void buttonPlus1_Click(object sender, EventArgs e)
{
   try
   {
       int txtValue = Convert.ToInt32(textBox.Text) + 100;
       textBox.Text = txtValue.ToString();
   }
   catch(Exception ex)
   {
     MessageBox.Show(ex.Message.ToString());
   }
}


text:
Q: How to open "Network Connections" window programmatically How to open "Network Connections" window programmatically using C# in Win7, XP??

A: Another alternative:
[...]
System.Diagnostics.Process.Start("NCPA.cpl");

[...]

A: Start a new process using shell execute, and run NCPA.cpl.  Like so:
ProcessStartInfo startInfo = new ProcessStartInfo("NCPA.cpl");
startInfo.UseShellExecute = true;

Process.Start(startInfo);

As an extra reference, wikipedia has a pretty comprehensive list of the applets available to you that you can start in this way: http://en.wikipedia.org/wiki/List_of_Control_Panel_applets.
Edit:
As a small addition, it may be more sensible to invoke the required control panel applet using the string "control appletname".  This is because while most applets can be started with their .cpl name alone, some of them, such as the Administrative Tools, don't have a .cpl name, so you need to use "control admintools" instead.
Edit 2:
As an additional reference, check out this knowledge base article: http://support.microsoft.com/kb/192806.


text:
Q: WCF REST Service POST Error with iOS Client I've published  WCF Service to IIS and can successfully get all the data back with a GET method. I'm not trying to POST data to the service and save this data in the database. The exact error I'm getting is:
The server encountered an error processing the request. The exception message is 'Object reference not set to an instance of an object.'. See server logs for more details.
This error message is always returned in the REST response that comes back to the client after sending the request.
I've gone into the inetpub->wwwroot->logs folder and looked around but did not see anything in the log files that helped me pinpoint the problem. I believe the problem is either how I've structured the server to accept responses or how I'm sending the responses out from the client. I'm new to REST so I'm not quite sure what I'm doing wrong. Below is the code. Any help would be appreciated.
//Server code:
//IService.cs
    [OperationContract]
    [WebInvoke(Method = "POST", BodyStyle = WebMessageBodyStyle.WrappedRequest, ResponseFormat = WebMessageFormat.Json, UriTemplate = "/NewUser")]
    void AddNewUser(NewUser newUser);

[DataContract]
public class NewUser
{
    [DataMember]
    public string name { get; set; }

    [DataMember]
    public string age { get; set; }
}

//Service1.svc.cs
public  void AddNewUser(NewUser newUser)
{
    var userController = new UserController();

    userController.AddNewUser(newUser.name, newUser.age);
}

//Client Side Code on iPhone
 NSArray *propertyNames = [NSArray arrayWithObjects:@"name", @"age",nil];
    NSArray *propertyValues = [NSArray arrayWithObjects:@"Test", @"100",nil];

    NSDictionary *properties = [NSDictionary dictionaryWithObjects: propertyValues forKeys:propertyNames];

    NSMutableDictionary *newUserObject = [NSMutableDictionary dictionary];

    [newUserObject setObject:properties forKey:@"newusermodel"];

    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:newUserObject options:kNilOptions error:nil];

    NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];

       NSString *urlString = [NSString stringWithFormat:@"http://myPublicIPAddress/MyService/Service1.svc/NewUser"];

    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:urlString]];
    [request setValue:jsonString forHTTPHeaderField:@"json"];

    [request setHTTPMethod:@"POST"];
    [request setHTTPBody:jsonData];
    [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];

    NSError *error = nil;
    NSURLResponse *theResponse = [[NSURLResponse alloc]init];
    NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&theResponse error:&error];

    if(error)
    {
        txtData.text = [error localizedDescription];
    }

    else
    {
        NSMutableString *retVal = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
    }

A: Try to Remove BodyStyle = WebMessageBodyStyle.WrappedRequest from WebInvoke attribute and add RequestFormat=WebMessageFormat.Jsoninstead like this.
  [OperationContract]
  [WebInvoke(Method = "POST",RequestFormat=WebMessageFormat.Json, ResponseFormat =        WebMessageFormat.Json, UriTemplate = "/NewUser")]
  void AddNewUser(NewUser newUser);

i had test it and this is working for me.


text:
Q: Script not getting executed eventhough path variable is set properly to node.exe I installed node.js and trying to run a script. Problem is I am not able to run the script which are in other folder.
For Ex:
Path to node.exe is in path C:\Program Files\nodejs. I have updated the same in PATH variable.
I have the script to be executed in D:\TestScript\Test.js
Now when I execute js script from root folder path like >node D:\TestScript\Test.js I get the error Cannot find module webdriverio.
But if I copy the test script to root folder and now execute >node Test.js everthing works fine.
Any pointer would help
Added Script:
var webdriverio = require('webdriverio');
var webdrivercss = require('webdrivercss');
var client = webdriverio.remote({
    desiredCapabilities: {
        browserName: 'firefox'
    }
});
webdrivercss.init(client, {
    screenshotRoot: 'tests/visual/baseline',
    failedComparisonsRoot: 'tests/visual/failures',
});
client
    .init()
    .url('https://www.google.co.in')
    .webdrivercss('login form', [{
        name: 'title',
        elem: '.container h2'
    }, {
        name: 'form',
        elem: '.container form'
    }])
    .end();

When I run npm ls command from D drive I get the output as

`-- (empty)


text:
Q: Alternative to VBA GoalSeek Does there exist an alternative to GoalSeek in VBA? My worksheet is filled with functions that do not like GoalSeek called from subroutines, and I'm looking for a alternative for optimization.

A: How about Excel Solver? It can be automated too and allows for significantly more complicated inputs
https://msdn.microsoft.com/en-us/vba/excel-vba/articles/using-the-solver-vba-functions


text:
Q: EF Core SQL multiple config options I have the following config in startup.cs to setup EF Core with MS SQL:
         services.AddDbContext<AppDbContext>(options =>
            {
                    options.UseSqlServer(
                           Configuration.GetConnectionString("DefaultConnection"),
                           x => x.UseNetTopologySuite()
                    );
            });

I need to increase the timeout because there are some long running queries that will be executed. I understand that I need to add the following, but not sure how to incorporate it into my existing options.UseSqlServer
             x => x.CommandTimeout(300)

A: You can configure this via the connection string.
"Data Source=SqlExpress;Initial Catalog=YourDatabase;Integrated Security=true;Command Timeout=300"

Or like this
services.AddDbContext<YourDbContext>(options => options.UseSqlServer(
    this.Configuration.GetConnectionString("YourConnectionString"),
    sqlServerOptions => sqlServerOptions.CommandTimeout(60))
);


text:
Q: How to Play Video In ListView in Android I want to play video in my application. I created a custom ListView with VideoView. The VideoView displayed successfully but one problem is that when I am move list view VideoView changed its position. This is not looking good in my application. My requirement is that when click on button video should start played in that area of list view only. How could I achieve this?
Here is code of displaying VideoView in ListView:
public class MyVideoAdapter extends BaseAdapter {

    Context context;
    String a[];
    LayoutInflater inflate;
    VideoView vv;
    ImageButton img;

    public MyVideoAdapter(Context context, String[] a) {
        this.context = context;
        this.a = a;
        inflate = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    }

    @Override
    public int getCount() {
        return a.length;
    }

    @Override
    public Object getItem(int position) {
        return position;
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        View v = convertView;
        if (convertView == null)
            v = inflate.inflate(R.layout.row, null);
        img = (ImageButton) v.findViewById(R.id.imageButton1);
        String ans = a[position];

        if (ans.equals("one")) {
            vv = (VideoView) v.findViewById(R.id.VideoView);
            MediaController mc = new MediaController(context);
            mc.setAnchorView(vv);
            mc.setMediaPlayer(vv);
            // Uri uri=Uri.parse("https://www.dropbox.com/s/d5blvemu8yse38s/kesari.mp4");
            // vv.setMediaController(mc);
            String path = "android.resource://com.example.wealthcreation/raw/kesari";
            vv.setVideoURI(Uri.parse(path));

            img.setOnClickListener(new View.OnClickListener() {

                @Override
                public void onClick(View v) {
                    // TODO Auto-generated method stub

                    img.setVisibility(View.INVISIBLE);
                    vv.start();

                }
            });

            // img.setImageResource(R.drawable.k1);
            // ImageButton img=(ImageButton)v.findViewById(R.id.imageButton1);
            // Button btn1=(Button)v.findViewById(R.id.btnplay);

            /*
            img.setOnClickListener(new OnClickListener()
            {

            @Override
            public void onClick(View v)
            {
                vv.setVisibility(View.VISIBLE);
                img.setVisibility(View.GONE);
                MediaController mc = new MediaController(context);
                mc.setAnchorView(vv);
                mc.setMediaPlayer(vv);
                // Uri uri=Uri.parse("https://www.dropbox.com/s/d5blvemu8yse38s/kesari.mp4");
                vv.setMediaController(mc);
                String path = "android.resource://com.example.wealthcreation/raw/kesari";
                vv.setVideoURI(Uri.parse(path));
                vv.start();
                String videoId = "CUuBdtsQx6U";
                Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("vnd.youtube:"
                        + videoId));
                intent.putExtra("VIDEO_ID", videoId);
                context.startActivity(intent);
                // Toast.makeText(context, "Hii",Toast.LENGTH_LONG).show();
                // this intent define an action and and parse the url
                // context.startActivity(new
                // Intent(Intent.ACTION_VIEW,Uri.parse("http://www.youtube.com/watch?v=CUuBdtsQx6U")));

                /*
                WebView webview = new WebView(context);

                String htmlString = "<html> <body> <embed src=\"youtube link\"; type=application/x-shockwave-flash width="
                        + widthOfDevice
                        + " height="
                        + heightOfDevice
                        + "> </embed> </body> </html>";

                webview.loadData(htmlString, "text/html", "UTF-8");

                try
                {
                    MediaPlayer mp = new MediaPlayer();
                    mp.setDataSource("http://www.youtube.com/watch?v=CUuBdtsQx6U");
                    mp.prepare();
                    mp.start();
                }
                catch (Exception e)
                {
                    Log.d("videos", "", e);
                }
            }

            });
            */

        }

        if (ans.equals("two"))
        {
            /*
            img.setImageResource(R.drawable.k2);
            Button btn2 = (Button) v.findViewById(R.id.btnplay);

            btn2.setOnClickListener(new OnClickListener()
            {

            @Override
            public void onClick(View v)
            {
                Toast.makeText(context, "Hii", Toast.LENGTH_LONG).show();
                // context.startActivity(new
                // Intent(Intent.ACTION_VIEW,Uri.parse("http://www.youtube.com/watch?v=f6fmZFDE5EA")));
                // this intent define an action and and parse the url
                // context.startActivity(new
                // Intent(Intent.ACTION_VIEW,Uri.parse("http://www.youtube.com/watch?v=CUuBdtsQx6U")));
                String videoId = "f6fmZFDE5EA";
                Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("vnd.youtube:"
                        + videoId));
                intent.putExtra("VIDEO_ID", videoId);
                context.startActivity(intent);
                // context.startActivity(new
                // Intent(Intent.ACTION_VIEW,Uri.parse("http://www.youtube.com/watch?feature=player_detailpage&v=f6fmZFDE5EA")));
            }

            });
            */
        }

        if (ans.equals("three"))
        {
            /*
            Button btn3 = (Button) v.findViewById(R.id.btnplay);

            btn3.setOnClickListener(new OnClickListener()
            {

                @Override
                public void onClick(View v)
                {
                    String videoId = "f6fmZFDE5EA";
                    Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("vnd.youtube:"
                            + videoId));
                    intent.putExtra("VIDEO_ID", videoId);
                    context.startActivity(intent);

                    // Toast.makeText(context, "three",Toast.LENGTH_LONG).show();
                    // context.startActivity(new
                    // Intent(Intent.ACTION_VIEW,Uri.parse("http://www.youtube.com/watch?v=f6fmZFDE5EA")));
                    // this intent define an action and and parse the url
                    // context.startActivity(new
                    // Intent(Intent.ACTION_VIEW,Uri.parse("http://www.youtube.com/watch?v=CUuBdtsQx6U")));
                }

            });
            */
        }
        if (ans.equals("four"))
        {
            /*
            img.setImageResource(R.drawable.k4);
            Button btn4 = (Button) v.findViewById(R.id.btnplay);

            btn4.setOnClickListener(new OnClickListener()
            {

            @Override
            public void onClick(View v)
            {
                String videoId = "VBMuzOrVD18";
                Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("vnd.youtube:"
                        + videoId));
                intent.putExtra("VIDEO_ID", videoId);
                context.startActivity(intent);

                // Toast.makeText(context, "four",Toast.LENGTH_LONG).show();
                // context.startActivity(new
                // Intent(Intent.ACTION_VIEW,Uri.parse("http://www.youtube.com/watch?v=VBMuzOrVD18")));
                // this intent define an action and and parse the url
                // context.startActivity(new
                // Intent(Intent.ACTION_VIEW,Uri.parse("http://www.youtube.com/watch?v=CUuBdtsQx6U")));
            }

            });
            */
        }
        if (ans.equals("fifth"))
        {
            /*
            img.setImageResource(R.drawable.k5);
            Button btn5 = (Button) v.findViewById(R.id.btnplay);
            btn5.setOnClickListener(new OnClickListener()
            {

                @Override
                public void onClick(View v)
                {
                    String videoId = "-UlSAYhHqqc";
                    Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("vnd.youtube:"
                            + videoId));
                    intent.putExtra("VIDEO_ID", videoId);
                    context.startActivity(intent);

                    // Toast.makeText(context, "fith",Toast.LENGTH_LONG).show();
                    // context.startActivity(new
                    // Intent(Intent.ACTION_VIEW,Uri.parse("http://www.youtube.com/watch?v=-UlSAYhHqqc")));
                    // this intent define an action and and parse the url
                    // context.startActivity(new
                    // Intent(Intent.ACTION_VIEW,Uri.parse("http://www.youtube.com/watch?v=CUuBdtsQx6U")));
                }

            });
            */
        }
        return v;
    }

}

A: In your case,You have already parse your data in XML format so difinately you have to store all your data in HashMap Arraylist with particular key for your Video url.
Now, what can do, If you need to open Video on Item Click of ListView then you can retrieve your video url in String like
String  myUrl = urHashMaparraylist.get(position).get("videolocation");

Now pass this myUrl to next Activity and just set this String as a
 Uri video = Uri.parse(myUrl);
 videoView.setVideoURI(video);

listView.setOnItemClickListener(new OnItemClickListener() {
    @Override
    public void onItemClick(AdapterView<?> parent, View view,
            int position, long id) {

        String  myUrl = urHashMaparraylist.get(position).get("videolocation");
        Intent n = new Intent(YourActivityName.this , NewActivityName.class);
        n.putExtra("videolocation",myUrl);
        startActivity(n);

    }

});

Now in your next Activity retrieve it as a
Uri video = Uri.parse(url);
videoView.setVideoURI(video);

For more reference for video streaming ... you can check the following url:
http://developer.samsung.com/android/technical-docs/Android-Media-Streaming-Tutorial
you can even check my answer at
How Do I Play Video in ListView like Instagram and Vine?

A: I was stumped with this too until I found this post:
https://stackoverflow.com/a/6832598/3367142
In short set a transparent background for your VideoView
android:background="#0000"


text:
Q: Serial Port WindowsError(5, 'Access is denied.') with multiprocessing I have a python program using serial port to connect with Arduino. I want to plot some data in real time without slowing down the execution, so I try multiprocessing. However, I got the error
    serial.serialutil.SerialException: could not open port 'COM6': WindowsError(5, 'Access is denied.') # COM6 is the port connected to Arduino

Surprisingly, the connection between Arduino is still alive while the function in multiprocessing is not running. My code is as follows,
class ArduinoThread(threading.Thread):
    def __init__(self, portnum):
        threading.Thread.__init__(self)
        self.setName("Arduino")
        self.Arduino = serial.Serial(port="COM"+str(portnum), baudrate=19200)
    def run(self):
        # some function

def MyPlot_realtime(DATA):
    while True:
        data = DATA.get(False)
        plt.plot(data)

UNO = ArduinoThread(6)
UNO.start()

plt.ion()
pltQ = multiprocessing.Queue()
pltP = multiprocessing.Process(target=MyPlot_realtime, args=(pltQ,))
pltP.start()

while True:
    # some calculation on data
    UNO.update(data)

    if pltQ.empty():
        pltQ.put(data)

Simply commenting the multiprocessing part the code can work well. The error pop out when there is multiprocessing but the UNO.update(data) is still working while MyPlt_realtime is not working at all.
(My code is quite complicated so I simplified it. I am using another serial port to connect another device. I am using Tkinter as well. Hope the problem didn't come from those part)

A: Put your main code in an if condition as follows:
if __name__ == '__main__':

I am not sure why, but it solved the problem for me and most examples seem to do it like that as well.


text:
Q: Ehcache getting out of sync with database On a Java EE server using CMT, I am using ehcache to implement a caching layer between the business object layer (EJBs) and the Data Access layer (POJOs using JDBC).  I seem to be experiencing a race condition between two threads accessing the same record while using a self-populating Ehcache.  The cache is keyed on the primary key of the record.
The scenario is:

*

*The first thread updates the record in the database and removes the record from cache (but the database commit doesn't necessarily happen immediately - there may be other queries to follow.)

*The second thread reads the record, causing the cache to be re-populated.

*The first thread commits transaction.

This is all happening in a fraction of a second.  It results in the cache being out of sync with the database, and subsequent reads of the record returning the stale cached data until another update is performed, or the entry expires from the cache.  I can handle stale data for short periods (the typical length of a transaction), but not minutes, which is how long I would like to cache objects.
Any suggestions for avoiding this race condition?
UPDATE:
Clearing the cache after the transaction has committed would certainly be ideal.  The question is, in a J2EE environment using CMT, when the caching layer is sandwiched between the business layer (stateless session EJBs) and the data access layer, how to do this?
To be clear about the constraints this imposes, the method call in question may or may not be in the same transaction as additional method calls that happen before or after.  I can't force a commit (or do this work in a separate transaction) since that would change the transaction boundaries from what the client code expects.  Any subsequent exceptions would not roll back the entire transaction (unneseccarily clearing the cache in this case is an acceptable side-effect).  I can't control the entry points into the transaction, as it is essentially an API that clients can use.  It is not reasonable to push the resonsiblity of clearing the cache to the client application.
I would like to be able to defer any cache clearing operations until the entire transaction is committed by the EJB container, but I have found no way to hook into that logic and run my own code with a stateless session bean.
UPDATE #2:
The most promising solution so far, short of a major design change, is to use ehcache 2.0's JTA support: http://ehcache.org/documentation/apis/jta
This means upgrading to ehcache 2.x and enabling XA transactions for the database as well, which could potentially have negative side-effects.  But it seems like the "right" way.

A: You are using transactions - it makes more sense to remove the cache after the commit, that is when the change really happens.
That way you see the old data only during the length of the transaction, and all reads afterwards have the latest view.
Update: Since this is CMT specific, you should look at the SessionSynchronization interface, and it's afterCompletion() method. This is showed in this tutorial.


text:
Q: I am trying to create an error bar on only one point in my graph? I am trying to create an error bar on only one point (132, 172) in my graph, because it's the only one that matters for what I'm trying to show. I am not sure how to make it so that that is the only error bar that shows. Here's my regular code with traditional error bar:
ggplot(weather_data, aes(x = snow.melt.date, y = Speyeria.atalantis)) +
 geom_errorbar(aes(ymin=Speyeria.atalantis-12.09, ymax=Speyeria.atalantis + 12.09), width=.2, position=position_dodge(0.05)) +
geom_point(color = "grey35") +
geom_point(aes(x=132, y=172), colour="#00AFBB", shape = 17, size = 2.5) +
geom_point(aes(x=132, y=176), colour="#FFDB6D") +
stat_smooth(method = "lm", formula = y ~ x, geom = "smooth", color = "steelblue4", se=FALSE) +
theme_minimal() +labs(x="Snowmelt Date", y="Emergence Date") +
  stat_regline_equation(label.y = 150.0, aes(label = ..eq.label..) ) +
ggtitle("Speyeria atalantis")

Any thoughts?
I could find no info on this problem so I haven't tried much. I considered grouping my data and then plotting by group? I tried putting arrows on the graph point instead of error bars but it wasn't the same.


text:
Q: Nodejs, how to pass parameters to Javascript in PUG/jade views I want to pass a variable when rendering my view and use this variable in client side Javascript. I already got partially, but it's rendering wrong. I use PUG view (or Jade).
Example:
Server Side
res.render('xyzView', { xyzVal: 'my_values_xyz'});

Client Side: PUG view
extends ../layout
block content
    script(type='text/javascript')
        var getVal= #{xyzVal};

It's creating a tag <var></var> on output instead var only, like this:
//- other HTML tags and codes
//-..
//-..
<script type="text/javascript">
    <var>getVal = 'my_values_xyz'</var>   /// <<<<<====== THE PROBLEM IT'S HERE
</script>

The right way should be:
//- other HTML tags and codes
//-..
//-..
<script type="text/javascript">
    var getVal = 'my_values_xyz';
</script>

How to fix that?

A: You want to add plain text
extends ../layout
block content
    script(type='text/javascript')
        | var getVal= #{xyzVal};

A: Add a '.' after script like this:
script(type='text/javascript').
    var getVal= #{xyzVal};


text:
Q: XSD to define complex type OR array of elements How can define OR logic for elements in my XSD file?
Unfortunately I can't make changes in "OLD STYLE BLOCK" structure, I am just extending existing XML structure.
The  only idea I have is something like this example XSD below but I have parser error
I hoped I can include xsd:choice and xsd:sequence to xs:complexType
Can I use Version="2.0" somehow to add extra logic to xsd ?
<?xml version="1.0"?>
<MyStruct Version="2.0">

   <!-- xs should allow "NEW STYLE BLOCK" OR "OLD STYLE BLOCK" with array of id -->
   <!-- one of them should present !!!! -->

  <!-- NEW STYLE BLOCK my complex type-->
  <IDArray> <
    <IDSet>
        <ID>89</ID>
        <ID>1</ID>
        <ID>2</ID>
    </IDSet>
    <IDSet>
        <ID>3</ID>
        <ID>4</ID>
    </IDSet>
  </IDArray>
  <!-- end of NEW STYLE BLOCK -->

  <!-- OLD STYLE BLOCK  array of elements  -->
  <ID>5</ID>
  <ID>7</ID>
  <!-- end of OLD STYLE BLOCK -->

  <Type>Some type</Type>  <!-- mandatory element -->
  <ReadableName>Human readable name</ReadableName>  <!-- mandatory element -->
</MyStruct>

Proposed XSD
<?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" version="1.1">

  <xs:element name="MyStruct">
    <xs:complexType>

        <xs:choice>
            <xs:element name="IDArray" minOccurs="0" maxOccurs="1">
                <xs:complexType>
                      <xs:choice maxOccurs="unbounded">
                        <xs:element name="IDSet" minOccurs="1" maxOccurs="unbounded">
                            <xs:complexType>
                                  <xs:choice maxOccurs="unbounded">
                                      <xs:element name="ID" minOccurs="1" maxOccurs="unbounded" />
                                  </xs:choice>
                            </xs:complexType>
                        </xs:element>
                      </xs:choice>
                </xs:complexType>
            </xs:element>

            <xs:element name="ID" minOccurs="0" maxOccurs="unbounded" />
        </xs:choice>

        <xs:sequence>
            <xs:element name="Type" type="xs:string" />
            <xs:element name="ReadableName" type="xs:string" />
        </xs:sequence>  <!--  error in this line  -->

      <xs:attribute name="Version" type="xs:string" />

    </xs:complexType>
  </xs:element>
</xs:schema>

Error message , I assume xsd:choice and xs:sequence are not allowed simultaneously
./MyStruct.xsd:: element sequence: Schemas parser error : Element '{http://www.w3.org/2001/XMLSchema}complexType': The content is not valid. Expected is (annotation?, (simpleContent | complexContent | ((group | all | choice | sequence)?, ((attribute | attributeGroup)*, anyAttribute?)))).

A: Try
  <xs:element name="MyStruct">
    <xs:complexType>
      <xs:sequence>

        <xs:choice>
            <xs:element name="IDArray" minOccurs="0" maxOccurs="1">
                <xs:complexType>
                      <xs:choice maxOccurs="unbounded">
                        <xs:element name="IDSet" minOccurs="1" maxOccurs="unbounded">
                            <xs:complexType>
                                  <xs:choice maxOccurs="unbounded">
                                      <xs:element name="ID" minOccurs="1" maxOccurs="unbounded" />
                                  </xs:choice>
                            </xs:complexType>
                        </xs:element>
                      </xs:choice>
                </xs:complexType>
            </xs:element>

            <xs:element name="ID" minOccurs="0" maxOccurs="unbounded" />
        </xs:choice>

        <xs:element name="Type" type="xs:string" />
        <xs:element name="ReadableName" type="xs:string" />

     </xs:sequence>

     <xs:attribute name="Version" type="xs:string" />

    </xs:complexType>
  </xs:element>


text:
Q: Connecting to MySQL from a Django project in Visual Studio Community 2019 I'm trying to connect to MySQL database from a Django project and I have this error:  "django.core.exceptions.ImproperlyConfigured: Error loading MySQLdb module.
Did you install mysqlclient?".
I have already installed mysqlclient with this command:
pip install mysqlclient
In my Django project's settings.py file I have changed the database to this:
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'db_django',
        'USER': 'root',
        'PASSWORD': '',
        'HOST': '127.0.0.1',
        'PORT': '3306',
    }
}

I'm using Visual Studio Community 2019. Django version: 2.2.9. Python version: 3.8.1 & Xampp for the MySQL.
Any help would be appreciated!


text:
Q: Checking if email already exists in MySQLdb utilizing python My goal is to check if an e-mail already exists in the mysql database. I am pulling the information into the variable from a webform (string). I currently have the following code:
import MySQLdb

db = MySQLdb.connect("localhost","username","password","databasename")
cursor = db.cursor()
if cursor.execute("select count(*) from registrants where email = " + "'"emailvar"'") == 0:
    print "it doesn't exist"

When I attempt to access the page I get an internal server error. I narrowed down the error to the "'"emailvar"'", and the code works fine, but e-mails have "@" and "." which cause SQL syntax errors. I attempt to escape them utilizing "'" "'" opening and closing parenthesis, but it does not work and crashes the web page.

A: You want:
query = 'select count(*) from registrants where email=%s'
cursor.execute(query, emailvar)
if next(cursor, None) is None:
    # whatever

But would look at .fetchone() which should work, and also EXISTS in SQL (whereby it should have a unique constraint and let the DB work it out) and return a boolean-esque empty result.


text:
Q: Check corrective QR code scanner with pyzbar I want to check that QR code data is correct by confirm it 3 time.
I compare new QR code data and saved QR code data but it not same.
here is my code:

from __future__ import print_function
import pyzbar.pyzbar as pyzbar
import numpy as np
import cv2
import simplejson as json
import os

def decode(im):
    # Find barcodes and QR codes
    decodedObjects = pyzbar.decode(im)
    return decodedObjects

# Read image
cap = cv2.VideoCapture(0)

c = 0
while (True):
    # Capture frame-by-frame
    ret, im = cap.read()

    #Decode QR
    decodedObjects = decode(im)

    #check QR
    if os.path.isfile("QR.json") and decodedObjects != [] and os.stat("QR.json").st_size != 0 :
        for obj in decodedObjects:
            QRdata = obj.data

        QRc = open("QR.json", "r+")
        QRcdata = json.loads(QRc.read())
        QRc.close()
        print(QRcdata)
        if QRcdata == QRdata:
            c = c + 1
            print("confirm ", QRdata, " : ", c)

        else:
            c = 0
            print("reset , ", c)
            QR = open("QR.json", "w+")
            data = QRdata
            QR.seek(0)
            QR.write(json.dumps(data))
            QR.close()
            print("saved new QR ", QRdata)

    elif decodedObjects != [] :
        for obj in decodedObjects:
            QRdata = obj.data

        QR = open("QR.json", "w+")
        data = QRdata
        QR.seek(0)
        QR.write(json.dumps(data))
        QR.close()
        print("saved new QR ", QRdata)

    # Display the resulting frame
    cv2.imshow("Results", im)

    # press "q" to exit
    if cv2.waitKey(1) & 0xFF == ord('q') or c == 3:
        break

When it run. It have QR data is "b'QRCodedata'" but in file it is "QRCodedata".
How i delete "b" in fornt of 'QRCodedata'.
Thank for help!


text:
Q: Proving mean of two odd squares is sum of two squares. From Fermat's two squares theorem we know that an odd prime p ≡ 1 (mod 4) is the sum of two squares. How do we prove a more general case: The average of two odd squares which is also congruent to 1 mod 4 is the sum of two squares.
Actually, this arises from the problem of requiring to prove m is the sum of two triangular numbers iff 4m + 1 is the sum of two squares.

A: $$\dfrac{p^2+q^2}{2}=\left(\dfrac{p+q}{2}\right)^2+\left(\dfrac{p-q}{2}\right)^2$$


text:
Q: xslt regular expressions more problems with processing nessus xml files.
I have some xml data from nessus that stores information such as host names etc in xml tags that can be extracted using this xsl tag:
<xsl:value-of select="../ReportItem[(@pluginID=12053)]/description"/>

Then only problem is this tag stores it with a bunch of garbage in it besides the host name.  For example, the tag usually has this information in it:

Synopsis : It is possible to obtain the network name of the remote
  host. Description : The remote host listens on UDP port 137 or TCP
  port 445 and replies to NetBIOS nbtscan or SMB requests. Note that
  this plugin gathers information to be used in other plugins but does
  not itself generate a report. Solution : n/a Risk factor : None Plugin
  output : The following 6 NetBIOS names have been gathered : VOODOO1 =
  Computer name VOODOO = Workgroup / Domain name VOODOO1 = File Server
  Service VOODOO = Browser Service Elections VOODOO = Master Browser
  MSBROWSE = Master Browser The remote host has the following MAC address on its adapter : 10:50:56:ab:10:02

The only part I'm interested in is the part "VOODOO1 = Computer name".  Actually whats before the '=' sign to be more precise.  I was wondering if it was possible to have a regular expression function within the 'select' for the tag, something like:
<xsl:value-of select="regexp(../ReportItem[(@pluginID=12053)]/description,'\w =')"/>

That would extract the only the contents of the tag that matches the regular expression and display it.  Right now I have the whole contents of the tag display which is annoying.  I have tried to use various variations of
<xsl:analyze-string select="$elValue" regex="\w = ">

tags with no luck.  I keep getting errors saying 'cant be subtag of <td> or any other xslt element I have tried, ie for-each etc.
Thanks in advance.
Based on feedback so far, here is some of the xml that's generated by nessus
<ReportItem port="137" svc_name="netbios-ns?" protocol="udp" severity="1"     pluginID="10150" pluginName="Windows NetBIOS / SMB Remote Host Information Disclosure" pluginFamily="Windows">
<description>Synopsis :

It is possible to obtain the network name of the remote host.

Description :

The remote host listens on UDP port 137 or TCP port 445 and replies to NetBIOS nbtscan or SMB requests.

Note that this plugin gathers information to be used in other plugins but does not itself generate a report.

Solution :

n/a

Risk factor :

None

Plugin output :
The following 6 NetBIOS names have been gathered :

 VOODOO1       = Computer name  VOODOO              = Workgroup / Domain name     VOODOO1       = File Server Service  VOODOO              = Browser Service Elections     VOODOO              = Master Browser
 __MSBROWSE__     = Master Browser

The remote host has the following MAC address on its adapter :
   01:a0:52:bf:0a:02

</description>
</ReportItem>`

<xsl:value-of select="regexp(../ReportItem[(@pluginID=12053)]/description,'\w =')"/>  This line doesn't really work.  I made it up to see if anyone knew if there was something similar to it.  It only generates an error because I made it up.

A: You need XSLT 2.0 for this. I suspect the error messages you were getting with xsl:analyze-string were because you were using an XSLT 1.0 processor.

A: As Mike Kay noted this won't work with XSLT 1.0. Get the .NET version of Saxon so you can use a more modern version of XSLT. You can call it from the command line or Powershell.  Here is a sample to get you started:
 <xsl:stylesheet
  xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
  version="2.0">
    <xsl:template match="description">
        <xsl:analyze-string select="."
            regex="(\w+)\s+=\s*Computer name">
            <xsl:matching-substring>
                <xsl:value-of select="regex-group(1)" />
            </xsl:matching-substring>
            <xsl:non-matching-substring>
            </xsl:non-matching-substring>
        </xsl:analyze-string>
    </xsl:template>
</xsl:stylesheet>


text:
Q: Background image displayed multiple times on mobile device When I use the chrome responsive tools on my computer the background image of my website is displayed only one time : the browser is just zooming on the image, top of the page correspond to the top of the image etc.. However when I go on my mobile device, the background image is displayed in his integrality so if the page is long, the background image will be displayed multiple times.
This is how it works in my CSS stylesheet :
html, body {
    height: 100%;
    background: url(img/bg.jpg) no-repeat center fixed;
    -webkit-background-size: cover;
    background-size: cover;
}

A: html, body {
  background-image: url(img/bg.jpg);
  background-repeat: no-repeat;
  background-attachment: fixed;
  background-position: center;
  -webkit-background-size: cover;
  background-size: cover;
}


text:
Q: How to Test Recovery in HBase? I wanted to test the recovery of data in HBase (Standalone mode), How can i do that? Will recovery works in Stand-alone mode?
After executing the put command from shell with out closing the HBase i switched of my VM and
restarted, it's not showing the newly added data. Even i tried from eclipse also it's not showing. How can i test recovery in HBase? I am able to see the Hfiles, but not Hlog does i need to set any path for this?
This is the code i had written..
Put p=new Put(Bytes.toBytes("name10"));
p.setWriteAheadLog(true);
p.add(Bytes.toBytes("cf"), Bytes.toBytes("name"),Bytes.toBytes("Some Value 10"));
table.setAutoFlush(true);
table.put(p);

Thanx in advance

A: HLog files are stored in .logs folder(Rootdir), In Stand alone mode it takes time to write into WAL where as in Pseudo Distributed or Distributed mode it will updates immediately