text:
Q: Use regex to skip a word I am using sublime to list all my .js files in my application but I want to use regex to show only the files that are not minified. I want files returned that are [NOT].min[/NOT].js I am using [^(\.min)]\.js and it appears to work but am not sure if it is going to miss any files. Is there a better piece of regex to use here?
/showhouse-bootstrap-datepicker.js      want returned
/dataTables.bootstrap.js                want returned
/additional-methods.min.js              dont want returned
/bootstrap-switch.min.js                dont want returned

I thought the following would work but it returns all .js
(?!\.min)\.js

A: instead of doing it the not way , do it as a positive search.
[^(\.min)]\.js is what you have done. this will not match any file ending in js which have m or n or i in them. check it .
Use a regex like this .
(?<!\.min)\.js

demo here : http://regex101.com/r/rJ1jN3

A: Sublime Text uses the Boost regex syntax, so you could use a pattern that grouped the items matching *.min.js and/or *.js then use a backreference to match the sub-expression:
^(.+w+\.js)|(.+\w+\.min\.js)\1$

The first pattern ^(.+\w+\.js) groups anything matching *.js into sub-expression 1, the second pattern (.+\w+\.min\.js) puts any matching *.min.js into sub-expression 2. The final step is to use a back-reference to sub-expression 1which is escaped as\1.
string:
something.min.js
min.js
1234.js
submin.js
file.js
admin.js
script.min.js
gar.min.js
garmin.min.js
harmin.marmin.min.js
garmin.js

matched:
min.js
1234.js
submin.js
file.js
admin.js
garmin.js


text:
Q: How to create relationships with many fact tables in Power BI?
How do I create a relationship between these 4 fact tables and 2 dim tables? How do I slice them based on quarter of the year? How to insert Q1 2023 into the fact tables?
When I change from Q1 to Q2 on the slicer, the count of MemberID doesn't change accordingly. Why is that? Thank you so much in advance.

A: You need to reshape your data in Power Query. Append your 4 tables so you have a single fact table. You can also remove MemberName from your fact table as it is already in your dimension table so just retain MemberID in your fact.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to Implement PUSH NOTIFICATION in Windows Universal App 10? This may be a duplicate question. But I did not find any solution yet. Can you please provide any example or sample code for registering App for PUSH NOTIFICATION on uwp 10?
Client code needed and Push notification type is Server to client. Client should register for receiving Server PUSH and Handle the push coming from server.

A: Here is the link for localpush: http://blogs.msdn.com/b/tiles_and_toasts/archive/2015/10/05/sending-a-local-tile-notification-in-windows-10.aspx
For push notification from server to work, read here https://msdn.microsoft.com/en-us/windows/uwp/controls-and-patterns/tiles-and-notifications-windows-push-notification-services--wns--overview

A: I have implemented push notification. So, It may help someone.
Add a new method in App.xaml.cs:
private async Task InitNotificationsAsync()
{
    // Get a channel URI from WNS.
    var channel = await PushNotificationChannelManager
                .CreatePushNotificationChannelForApplicationAsync();
    channel.PushNotificationReceived += Channel_PushNotificationReceived;
}

Call this method inside OnLaunched method:
protected async override void OnLaunched(LaunchActivatedEventArgs e)
{
     await InitNotificationsAsync();
     ...
}

Hope this will help.


text:
Q: What is armeabi and why they use it? I see this library (armeabi) many times when I explore open sources.
I net searched for an explanation of it, but all the results I found are talking ABOUT it and not defining it.
What is this armeabi and why are they using it in Android applications?

A: ABI - Application Binary Interface
EABI - Embedded Application Binary Interface
So ARMEABI are compiled binaries matching your android device's CPU architecture.
e.g.
arm64-v8a (Nexus 5x) - 64bit - ARM Cortex-A35, ARM Cortex-A53, ARM Cortex-A57, ARM Cortex-A72, ARM Cortex-A73
armeabi-v7a - 32bit - ARM Cortex-A5, ARM Cortex-A7, ARM Cortex-A8, ARM Cortex-A9, ARM Cortex-A12, ARM Cortex-A15, ARM Cortex-A17

To include *.so binary jniLibs using Android Studio 2.3 place them in src/main/jniLibs folder and add the following configuration to your *.gradle file:
android {
    sourceSets {
        main {
            jniLibs.srcDirs = ['src/main/jniLibs']
        }
    }
}

dependencies {
    compile fileTree(dir: 'jniLibs', include: ['*.so'])
}

A: I recently saw a pretty good article related to the different CPUs and suggestions on maintaining APK size while supporting them. The report provides some info for the following at the end:

*

*armeabi

*armeabi-v7a

*arm64-v8a

*X86

*X86-64

*mips

*mips64

A: Android devices have CPUs. Many of those CPUs are based on the ARM architecture, while some are based on x86, and a few others are based on other stuff like MIPS.
Some Android apps use the Native Development Kit (NDK) to create C/C++ code to link into their app. C/C++ code needs to be compiled for a specific CPU architecture. The NDK places the version of the C/C++ code compiled for each architecture into an architecture-specific directory. One of those directories is armeabi/, which is for a generic ARM CPU. There is also armeabi-v7/ (for an ARM v7-compatible CPU), x86/ (for x86 CPUs), etc.


text:
Q: Finding State Transition Matrix Can someone help me compute the State Transition Matrix for the following system of linear differential equations?
$$\vec x=\begin{bmatrix}2 & -t\\-t & 2\end{bmatrix} \vec x$$
My attempt:
Compute $A(t) = \begin{bmatrix}2 & -t\\-t & 2\end{bmatrix}$ so $\int A(t)=\begin{bmatrix}2t & \frac{-t^2}{2}\\ \frac{-t^2}{2}& 2t\end{bmatrix}$
Then I checked the equality of multiplications:
$$A(t)\cdot\int A(t)d(t) =\int A(t) d(t) \cdot A(t)$$
and indeed they are equal.
Then I calculated the Eigenvalues as:
$$\lambda=\frac{4t\pm t^2}{2}$$
Plugging the Eigenvalues into the matrix:
$$\alpha  \begin{bmatrix}1 \\1 \end{bmatrix}$$ and $$\beta \begin{bmatrix}1 \\-1 \end{bmatrix}$$
which gives $$H=\begin{bmatrix}1 & 1 \\ 1 & -1\end{bmatrix}$$
How do I proceed from here?

A: Hint: Take $HAH^{-1}$ and then review your solution


text:
Q: Javascript conditionals based on cookies Im trying to set up some conditional statements that detect whether or not a cookie has been set when the page loads and applies some classes to a div based on the value of that cookie:
<script>
        $(function(){
            if ($.cookie('view_size', 'large')) {
                $('#primary').removeClass('medium_content');
                $('#primary').addClass('large_content');
            };

            if ($.cookie('view_size', 'medium')) {
                $('#primary').removeClass('large_content');
                $('#primary').addClass('medium_content');
            };

            if ($.cookie('view_size', 'small')) {
                $('#primary').removeClass('large_content');
                $('#primary').removeClass('medium_content');
            };
        });
        </script>

I am using the jquery cookie plugin and I know the cookies are getting successfully set, so the issue must have to do with the way I have set up these conditional statements. Any ideas?

A: I believe that the syntax
$.cookie('view_size', 'large')

is the way that you create a cookie, and isn't meant to check the value of a cookie.  I believe you want
if ($.cookie('view_size')=='large')


text:
Q: Avoid implementing unused Listener methods I'm developing an Android app, and used this tutorial to achieve catching double tap events on my map. But I think is a more general problem. So, to get notified about specific events, I have to implement lot of listeners. These have plentiful of methods I won't use ever, so these are just "polluting" my code. Yes, I could use a listener adapter class, but i have to inherit from an other superclass, too, and multiple inheritance is not available in Java, unfortunately. Also, I cannot use delegation in this case, because my Activity class have to be the listener, too (at least I think).
So, is there any way in Java, to implement the used methods, and get rid of the others, somehow?
This is the example code what is describing the problem:
// ...

public class MainActivity extends MapActivity implements OnItemSelectedListener, OnGestureListener, OnDoubleTapListener {

    // ... my methods

    public boolean onDoubleTap(MotionEvent e) {
        // actually this method is used by me only
    }

    // ... lots of other implemented listener methods what I do not use
}

A: No. Once an interface is implemented, all its methods must be overridden.

A: Yes, with Java 8 you can use default to effectively ignore unused/unwanted methods.
Here is an example that extends OnDoubleTapListener to only care about the onDoubleTap() method
interface OnDoubleTapOnlyListener extends GestureDetector.OnDoubleTapListener
{
    default boolean onSingleTapConfirmed(MotionEvent e) { return false; }

    boolean onDoubleTap(MotionEvent e);

    default boolean onDoubleTapEvent(MotionEvent e) { return false; }
}

And then you can just implement onDoubleTap and the others will be ignored.
Unfortunately, Android doesn't support Java 8 out of the box yet.
It is not impossible however, you can use Java 8 via Retrolambda https://github.com/orfjackal/retrolambda

A: I think you may need to rethink the design a bit.
There is clearly a need for your app to respond to various events, those events are generated by mechanism requiring different listeners, but you care only about subset of triggers.
What I would do is to implement MyAppEventTriggerQueue (it can use
http://developer.android.com/reference/java/util/concurrent/ConcurrentLinkedQueue.html internally).

*

*The object will have to have a worker thread that would listen on the queue changes and trigger YOUR custom call backs.

*All the different listeners like MapActivity and SimpleGestureListener will populate the shared queue to which your MyAppEventTriggerQueue will respond by firing your custom events.
That way you are untying your self from the various interfaces and implementations, abstracting out everything except the events you need.
This is a bit more work, but it ultimately should be a cleaner solution.

A: You can use abstract class :
 abstract  class DoubleTapListener implements   GestureDetector.OnDoubleTapListener {
    @Override
    public boolean onSingleTapConfirmed(MotionEvent e) {
        return false;
    }

    @Override
    abstract public boolean onDoubleTap(MotionEvent e);

    @Override
    public boolean onDoubleTapEvent(MotionEvent e) {
        return false;
    }

}
public class MainActivity extends DoubleTapListener{

    @Override
    public boolean onDoubleTap(MotionEvent e) {
        return false;
    }
}


text:
Q: Unbiased Estimator for $\log\left[\int p(x\mid z)p(z) \, dz\right]$ The naive Monte Carlo estimator is an unbiased estimator for $\int p(x\mid z)p(z) \, dz$, is there a convenient unbiased estimator for $\log \left[\int p(x\mid z)p(z)\,dz \right]$

A: Path sampling is a way to evaluate the log integral by an unbiased estimator. Let us introduce a temperature index $0\le t\le 1$ and a sequence of conditional functions $p_t(x|z)$ such that
$$p_0(x|z)=1\qquad\qquad\text{and}\qquad\qquad p_1(x|z)=p(x|z)$$
Then, if $$\mathfrak{Z}_t(x)=\int p_t(x|z)\,q(z)\text{d}z$$
\begin{align*}\frac{\text{d}}{\text{d}t} \log(\mathfrak{Z}_t(x))
&= \frac{1}{\mathfrak{Z}_t(x)}\frac{\text{d}}{\text{d}t}\mathfrak{Z}_t(x)\\
&=\frac{1}{\mathfrak{Z}_t(x)}\int\frac{\text{d}}{\text{d}t}p_t(x|z)\,q(z)\text{d}z\\
&=\frac{1}{\mathfrak{Z}_t(x)}\int\frac{\text{d}}{\text{d}t}p_t(x|z)\,q(z)\text{d}z\\
&=\frac{1}{\mathfrak{Z}_t(x)}\int\frac{\text{d}}{\text{d}t}\log(p_t(x|z))\,p_t(x|z)q(z)\text{d}z\\
&=\mathbb{E}\left[\left.\frac{\text{d}}{\text{d}t}\log(p_t(x|Z))\right| X=x\right]\end{align*}
Therefore, since
$$\log(\mathfrak{Z}_1(x)/\mathfrak{Z}_0(x)) = \int_0^1 \frac{\text{d}}{\text{d}t} \log(\mathfrak{Z}_t(x))\,\text{d}t$$
and $\mathfrak{Z}_0(x)=1$, a remarkable identity is that
$$\log(\mathfrak{Z}_1(x))=\log\left\{\int p(x|z) q(z)\text{d}z\right\}=\int_0^1  \mathbb{E}\left[\left.\frac{\text{d}}{\text{d}t}\log(p_t(x|Z))\right| X=x\right]\,\text{d}t$$
Hence, assuming simulations $z_i=\zeta(x,t,\epsilon_i)$ ($i=1,\ldots,I$) from $$q(z|x)=\frac{q(z) p(x|z)}{\mathfrak{Z}_1(x))}$$ are available (e.g. by MCMC), an unbiased estimator of $\log(\mathfrak{Z}_1(x))$ is
$$\int_0^1 \frac{1}{I}\sum_{i=1}^I\frac{\text{d}}{\text{d}t}\log(p_t(x|\zeta(x,t,\epsilon_i)))\,\text{d}t$$

A: It can be shown that by using sufficiently large sample sizes for the MC approximation, a lower bound to the marginal log-likelihood is tightened. While this estimator is hence biased, in can serve the same practical purposes. It was shown in [1] that
$$
\log p(x) \ge \mathcal{L}_{K+1} \ge \mathcal{L}_{K}
$$
for $\mathcal{L}_K = \mathbb E_{z_1, \ldots, z_K \sim q^K} \left[\log \frac{1}{K} \sum_{k=1}^K \frac{p(x, z_k)}{q(z_k)}\right]$, where $q^K \equiv \underbrace{q \otimes q \otimes \cdots \otimes q}_{K times}$.
This also holds for $q(z) = p(z)$.
[1] Burda, Yuri, Roger Grosse, and Ruslan Salakhutdinov. "Importance weighted autoencoders." arXiv preprint arXiv:1509.00519 (2015).

A: The Monte Carlo estimator using $n$ samples of
$$l = \int p(x \mid z) g(z) dz = E(p(x \mid Z))$$
with $Z\sim g$ is
$$\hat l_n = \frac 1n \sum_{i = 1}p(x\mid Z_i) \qquad Z_i\sim g$$
Following Durbin and Koopman
(1997), the error of the log
marginal likelihood is given by
$$\begin{align*}
\log\hat l_n - \log l
  &= \log\left(1 + \frac{\hat l_n - l}{l}\right) \\
  &= \frac{\hat l_n - l}{l}
    - \frac 12\left(\frac{\hat l_n - l}{l}\right)^2 +
    O\left(\left(\frac{\hat l_n - l}{l}\right)^3\right)
\end{align*}$$
implying that the bias is
$$
E(\log\hat l_n) =  \log l
  - \frac 12\frac{E\left((\hat l_n - l)^2\right)}{l^2} +
    O\left(\frac{E\left((\hat l_n - l)^3\right)}{l^3}\right)
$$
Thus, the bias is approximately proportional to the variance
of the estimated log-likelihood using the delta method and
that $E(\hat l_n) =l$.
The bias corrected version from Durbin and Koopman (1997) is
therefor
$$
\log\hat l_n + \frac 12 \frac{\widehat{\text{Var}}(\hat l_n)}{\hat l_n^2}
$$
where $\widehat{\text{Var}}$ is the estimated variance. That is,
$$\widehat{\text{Var}}(\hat l_n) = \frac 1{n(n -1)} \sum_{i = 1}^n\left(p(x\mid Z_i) - \hat l_n\right)^2.$$
The adjusted estimator is convenient as we already have all the quantities we need from the standard Monte Carlo estimator.
The above can also be
extended to importance sampling. Pick an importance distribution with density $h$ with the same support as $g$. Then replace $p(x\mid Z_i)$ in $\hat l_n$ (and the variance estimate) with
$$
\frac{p(x\mid Z_i)g(Z_i)}{h(Z_i)}
$$
and sample $Z_i\sim h$.
Example
Take $g(z) = \phi(z)$ where $\phi$ is the standard normal
distribution's density function and
$$
p(x\mid z) = \Phi(0.5 + z)\Phi(-0.25 - z)
$$
where $\Phi$ is the standard normal distribution's cumulative density function. In this case $l$ is the bivariate normal CDF integrated up to 0.5 and -0.25 with covariance matrix
$$\begin{pmatrix} 2 & -1 \\ -1 & 2 \end{pmatrix}$$
which can be computed to floating point precision which makes this example nice.
A small simulation study investigating the bias of the adjusted and unadjusted Monte Carlo estimator as a function of the sample size is run below.
# the true value of l
truth <- mvtnorm::pmvnorm(
  upper = c(.5, -.25), sigma = matrix(c(2, -1, -1, 2), 2))

n_reps <- 100000L # the number of replications
# the sample sizes
n_samples <- seq(log(10), log(1000), length.out = 40) |> exp() |> floor()

# compute the estimates
set.seed(1)
ests <- sapply(n_samples, \(n_samp){
  smps <- matrix(rnorm(n_samp * n_reps), n_samp)
  weight <- pnorm(.5 + smps) * pnorm(-0.25 - smps)
  rbind(Estimate = colMeans(weight), Var = apply(weight, 2L, var) / n_samp)
}, simplify = "array")

# compute the bias estimates
err_unadjusted <- log(ests["Estimate", , ]) - log(truth)
bias_ests_unadjusted <- colMeans(err_unadjusted)
err_adjusted <-
  log(ests["Estimate", , ]) + ests["Var", , ] / (2 * ests["Estimate", , ]^2) -
  log(truth)
bias_ests_adjusted <- colMeans(err_adjusted)

# plot the bias estimates versus the sample size
ylim <- range(bias_ests_unadjusted, bias_ests_adjusted)
par(mar = c(5, 5, 1, 1))
plot(n_samples, bias_ests_unadjusted, pch = 16, bty = "l", ylim = ylim,
     ylab = "Bias estimate (unadjusted)", xlab = "Sample size", log = "x")
abline(h = 0, lty = 2)
plot(n_samples, bias_ests_adjusted, pch = 16, bty = "l", ylim = ylim,
     ylab = "Bias estimate (adjusted)", xlab = "Sample size", log = "x")
abline(h = 0, lty = 2)

The plots show that the adjusted estimator seems to be unbiased but the standard Monte Carlo estimator is downward biased consistent with the answer by bayerj. However, the bias of the latter gets smaller as the number of samples is increased also consistent with the answer by bayerj.
A side note, the plot above shows that the variance of the log-likelihood estimator is about $2 \cdot 0.012$ in the worst case when we use $n = 10$ samples. Thus,
the standard error of the estimator is $\sqrt{2 \cdot 0.012} = 0.125$. Hence, a bias of $0.012$ may not be the main concern.


text:
Q: Calling Curl API on Python I want to call CURL API on python.
curl -X POST -H "Authorization:Token 00d2e3a10c82420414b2d36d28fb5afc2cd8e8a5" \
-H "Content-Type: application/json" \
-d '{"module_id":"[MODULE_ID]", "text": "example text"}' \
-D - \
https://api.tocall.com/

I used requests module for making request and json module for converting object to string. But I'm getting 404.
Where am I wrong?
import requests
import json
headers = {
    'Authorization': 'Token 00d2e3a10c82420414b2d36d28fb5afc2cd8e8a5',
    'Content-Type': 'application/json',
}
url = "https://api.tocall.com/"
data = '{"module_id":"[MODULE_ID]", "text": "example text"}'
response= requests.post(url, data=json.dumps(data), headers=headers)
print(response.status_code)

A: Add the Host header, so that the final server knows on which virtual host to route the request,
Change:
headers = {
    'Authorization': 'Token 00d2e3a10c82420414b2d36d28fb5afc2cd8e8a5',
    'Content-Type': 'application/json',
}

For:
headers = {
    'Authorization': 'Token 00d2e3a10c82420414b2d36d28fb5afc2cd8e8a5',
    'Content-Type': 'application/json',
    'Host' : 'api.tocall.com'
}

I think this will fix your issue. Eventually you might want to update the default headers, not craft your own ones. Try to use the session features of requests to perform consistent queries.
Note: as stated by other answers, you have other JSON encoding issues, but that's not the reason why you are getting 404.

A: You are encoding your data as JSON twice. json.dumps() takes an object and converts to JSON. In this case, you are converting a string to JSON. This should work better:
import requests
headers = {
    'Authorization': 'Token 00d2e3a10c82420414b2d36d28fb5afc2cd8e8a5',
}
url = "https://api.tocall.com/"
data = {"module_id":"[MODULE_ID]", "text": "example text"}
response= requests.post(url, json=data, headers=headers)
print(response.status_code)

If it still doesn't work and you need more help, you should include real details about your API so we can reproduce the issue.

A: json.dumps turns a Python dict to a string, but your data is already a string. The easiest thing to do is write data as a dict then use json.dumps on that.


text:
Q: Clearing the last graphic drawn? (Undo/Redo drawing) public function drag(e:MouseEvent)
    {
        lineDraw(mouseX, mouseY);
        e.updateAfterEvent();

    }
    public function lineDraw(X:int, Y:int):void
    {
        currentX = X;
        currentY = Y;

        graphics.lineStyle(size, color)
        graphics.moveTo(previousX, previousY)
        graphics.lineTo(currentX, currentY)

        previousX = currentX;
        previousY = currentY;
    }

Very simple code I made that allows me to draw lines with my mouse. Function drag is triggered on MOUSE_MOVE after MOUSE_DOWN.
My question is: how would I go about clearing the last line drawn? Basically, a ctrl+z/undo function that can be repeat as many times as i want.
Would I have to rewrite my code completely and push every single line drawn into an array, and then work my way backwards through the array, removing lines as I click "undo"? Or is there another better, easier solution to this?
Thanks! :)

A: Here is an example:  See code comments for explanations
private var undoStates:Vector.<Shape> = new Vector.<Shape>(); //holds all your undo states (HAS TO BE SHAPE SINCE AS3 DOESN"T LET YOU ISNTANTIATE A GRAPHICS OBJECT DIRECTLY)
private var redoStates:Vector.<Shape> = new Vector.<Shape>(); //holds all your redo states
private var undoLevels:int = 1; //how many undo levels you'd like to have
private var redoLevels:int = 1;

public function undo() {
    if (undoStates.length > 0) {  //make sure there is an undo state before preceeding
        //add redo state
        redoStates.push(getState());

        //if redo states are more than redoLevels, remove the oldest one
        if (redoStates.length > redoLevels) redoStates.splice(0, 1);

        //make the the last undo state the current graphics
        graphics.clear(); //not sure if this line is required, can't recall if copyFrom clears first
        graphics.copyFrom(undoStates.pop().graphics); //pop removes the last item from the array and returns it
    }
}

public function redo() {
    if (redoStates.length > 0) {
        //add undo state
        addUndo();

        //make the the last undo state the current graphics
        graphics.clear(); //not sure if copy from (the next line) clears or not
        graphics.copyFrom(redoStates.pop().graphics);
    }
}

private function getState():Shape{
    var state:Shape = new Shape();
    state.graphics.copyFrom(graphics);  //copy the current graphics into a new Graphics object
    return state;
}

private function addUndo():void {
    undoStates.push(getState()); //add the current state to the undo array

    //if more undo states than undoLevels, remove the oldest one
    if (undoStates.length > undoLevels) undoStates.splice(0, 1);
}

public function lineDraw(X:int, Y:int):void {
    currentX = X;
    currentY = Y;

    //create undo state before we draw more
    addUndo();

    graphics.lineStyle(size, color)
    graphics.moveTo(previousX, previousY)
    graphics.lineTo(currentX, currentY)

    previousX = currentX;
    previousY = currentY;
}


text:
Q: fat free framework find and cast I am familiarising myself with the Fat Free Framework. I am trying to query a database and return the result in json format.
$user=new DB\SQL\Mapper($db,'wilt');
 $filter = array();
    $option = array(
            'order' => 'created DESC',
            'limit' => 7
    );
    $list=$user->find($filter,$option);
    echo json_encode($list);

When I use $list=$user->find($filter,$option);, it returns 3 empty records. When I use $list=$user->cast(), it returns the one record with the fields, but the values are null.
How can I combine find and cast?

A: try this one:
$list = array_map(array($user,'cast'),$user->find($filter,$option));
echo json_encode($list);


text:
Q: Find all positive integral solutions of $\tan^{-1}x+\cos^{-1}\frac{y}{\sqrt{y^2+1}}=\sin^{-1}\frac{3}{\sqrt{10}}$ Find all the positive integral solutions of, $\tan^{-1}x+\cos^{-1}\dfrac{y}{\sqrt{y^2+1}}=\sin^{-1}\dfrac{3}{\sqrt{10}}$
Assuming $x\ge1,y\ge1$ as we have to find positive integral solutions of $(x,y)$
$$\tan^{-1}x=\tan^{-1}3-\tan^{-1}\dfrac{1}{y}$$
As $3>0$ and $\dfrac{1}{y}>0$
$$\tan^{-1}x=\tan^{-1}\left(\dfrac{3-\dfrac{1}{y}}{1+\dfrac{3}{y}}\right)$$
$$\tan^{-1}x=\tan^{-1}\dfrac{3y-1}{y+3}$$
$$x=\dfrac{3y-1}{y+3}$$
$y+3\in[4,\infty)$ as $y\ge1$, $3y-1\in [2,\infty)$ as $y\ge1$
For $x$ to be positive integer, $3y-1$ should be multiple of $y+3$
$$3y-1=m(y+3) \text { where } m\in Z^{+}$$
$$3y-my=3m-1$$
$$(3-m)y=3m-1$$
Here R.H.S is positive, so L.H.S should also be positive.
So $3-m>0$, hence $m<3$
So possible values of $m$ are {$1$,$2$}.
For $m=1$, $$3y-1=y+3$$
$$2y=4$$
$$y=2$$
$$x=\dfrac{3\cdot2-1}{2+3}$$
$$x=1$$
For $m=2$, $$3y-1=2(y+3)$$
$$3y-1=2y+6$$
$$y=7$$
$$x=\dfrac{3\cdot7-1}{7+3}$$
$$x=\dfrac{20}{10}$$
$$x=2$$
Is there some other nicer way to solve this problem.

A: Your method seems decent. Here I propose another way to ensure the integer-ness of $x$ and $y$.
Note from a rough sketch and limits that the range of $f:\mathbb{R^+} \mapsto X,~f(y)= {3y-1\over y+3}$ is $\left[-\frac 13, 3\right)$. The only positive integers that lie in this range are ${1,2}$. You may use the inverse process $y={3x+1\over 3-x}$ and,use $x\in \{1,2\}$ to see  for which of these $y$, $x$ is also a positive integer.
For $x=1$, $y=\frac 42 = 2$, which is a positive integer. So one solution is $(x,y)\equiv (1,2)$. For $x=2$, $y=\frac 71 = 7$, also a positive integer. So another solution is $(2,7)$. We have exhausted all possibilities for $y$. Our solution set is $\left\{(1,2),(2,7)\right\}$.

A: We can actually utilize $x,y$ are positive integers
$$\tan^{-1}x=\tan^{-1}3-\tan^{-1}\dfrac1y<\tan^{-1}3$$
As $\tan^{-1}x$ is an increasing function
$$\implies x<3$$
So, $x$ can be $1$ or $2$
Check which ones make $y$ positive integer

A: Another way
As we need $x,y>0$
If $x/y<1$
$$\tan^{-1}x+\tan^{-1}(1/y)=\tan^{-1}\dfrac{xy+1}{y-x}$$
$$xy+1=3(y-x)$$
$$\iff x=\dfrac{3y-1}{y+3}=3-\dfrac{10}{y+3}$$
So, $y+3(>3), $ must divide $10$ and must honor $x<y$
If $x/y >1,x>y$ as $x,y>0$
$$\tan^{-1}x+\tan^{-1}\dfrac1y>\tan^{-1}y+\cot^{-1}y=\dfrac\pi2>\tan^{-1}3$$


text:
Q: Git: Converting tag to branch in remote repo I have a tag called latest and I want that to be a branch instead. Opposite of this. I need to remove it from the remote repo as well.
Background: This is currently a problem for many golang packages, where goinstall looks for a release tag or branch, which corresponds with the latest official release of the language. Many people mistakenly used git tags, by analogy with other VCSes, when they should have used git branches.

A: git checkout latest
git tag -d latest  # delete tag locally
git push origin :refs/tags/latest  # delete tag in repo
git checkout -b latest
git push origin latest

The danger of removing a tag is described here, but that is why a branch should have been used in the first place.

A: Instead of deleting the tag use a branch of a different name. Use different naming conventions for your branches and your tags. This will better allow you to fullfil the spirit of

*

*Branches are for changes, tags are for releases

*Don't delete tags


text:
Q: Infinite recursion using micronaut and gorm I come from Grails background and have recently started a project in Micronaut using GORM.
I have the following code:
package micronaut.query.association.domain
import org.grails.datastore.gorm.GormEntity
@grails.gorm.annotation.Entity
class Author implements GormEntity<Author> {
    String name
    static hasMany = [
        books: Book
    ]
    static mapping = {
        books fetch: 'join'
    }
}

package micronaut.query.association.domain

import org.grails.datastore.gorm.GormEntity

@grails.gorm.annotation.Entity
class Book implements GormEntity<Book> {
    String name
    Author author
}

package micronaut.query.association
import io.micronaut.http.annotation.Controller
import io.micronaut.http.annotation.Get
import io.micronaut.http.HttpStatus
import micronaut.query.association.domain.Author
import grails.gorm.transactions.ReadOnly

@groovy.transform.CompileStatic
@Controller("/author")
class AuthorController {

    @Get("/")
    @ReadOnly
    List<Author> index() {
        return Author.list()
    }
}

The app compiles and starts without problems, but when I try to access  the url http:localhost:8080/author, I receive the following error:

10:25:29.431 [nioEventLoopGroup-1-2] ERROR
  i.m.h.s.netty.RoutingInBoundHandler - Unexpected error occurred: Error
  encoding object [[micronaut.query.association.domain.Author : 1,
  micronaut.query.association.domain.Author : 2]] to JSON: Infinite
  recursion (StackOverflowError) (through reference chain:
  micronaut.query.association.domain.Book["author"]-

| Micronaut Version: 1.0.1
| JVM Version: 1.8.0_192
OS: Linux 4.19.4-arch1-1-ARCH
Am  I doing something wrong?
Thanks and please forgive me if my message was not posted in the correct way. This is my first try in stack overflow.

A: Thanks to the excellent article suggested, I was able to solve the problem.
The solution was decorate the books declaration in the Author class with the @JsonManagedReference annotation and decorate the author declaration in the Book class withe the @JsonBackReference annotation.


text:
Q: Windows 10: 'gpresult' not recognized windows novice here, running windows 10 on a dell i7 inspiron. In command prompt, I am able to run neither gpresult nor gpresult /v which both seem to be common uses. I can't find any installation instructions (or proof of the necessity of installation). Any such command issued returns what I presume is boilerplate, 'gpresult' is not recognized as an internal or external command, operable program or batch file.
Is there a way to install it; am I issuing the prompt incorrectly or missing some prior step; or does the absence of built-in gpresult indicate something interesting?

A: I am able to run neither gpresult nor gpresult /v

'gpresult' is not recognized as an internal or external command, operable program or batch file.

Your path is broken.
Look for spaces in your path which shouldn't be there.
See What are PATH and other environment variables, and how can I set or use them? for instructions on how to edit your path.
The default path on Windows 10 is:
%SystemRoot%\system32;%SystemRoot%;%SystemRoot%\System32\Wbem;%SYSTEMROOT%\System32\WindowsPowerShell\v1.0\


text:
Q: Unable to connect to SQL LocalDB I have a native C++ app within which I am trying to connect to a localdb instance using ADO.  Having manually started my instance I can run sqllocaldb info v11.0 and see the database instance is running.
My code is as follows.
ADO::_ConnectionPtr spConnection (__uuidof (ADO::Connection));
spConnection->Open (L"Provider=SQLNCLI11;Server=(localdb)\\v11.0;Integrated Security=true", L"", L"", 0);

The error code is DB_E_ERRORSOCCURRED (0x80040e21) and the error message is Multiple-step OLE DB operation generated errors. Check each OLE DB status value, if available. No work was done.
I am able to successfully connect to the database using SQL Server Management Studio and I've tried it both with and without the provider in the connection string as well as specifying an initial catalog.

A: I found my issue.  The security must be set to sspi as shown below.
ADO::_ConnectionPtr spConnection (__uuidof (ADO::Connection));
spConnection->Open (L"Provider=SQLNCLI11;Server=(localdb)\\v11.0;Integrated Security=SSPI", L"", L"", 0);

A: ADO connection object has an Error collection that holds the list oft error that has occured so far. You can take a look at these error to see what's wrong.
Usually two things can go wrong while connecting to SQL Server.
1.Login Failed.
2.SQL Server is not configured so that you can connect to it remotely.
Since you are trying to connect to a local server it can hardly be the second reason.
As you might now there are two different type of authentication when it comes to SQL Server:Windows and SQL Server.You can use one of therm if each of them is set in your SQL Server options or both of them if the mixed mode is selected.
According to your connection string you are using windows mode authentication therefor you should be logged in using a windows user that can login to SQL Server.If that's not the case with your SQL Server then you should provide a SQL user credentials in your connection string.
Anyway check the Error collection of connection object as see if there's anything else is wrong with your local db.


text:
Q: Probability variance Let ${X_{n}}$ be a sequence of independent identically distributed random variables with mean $\mu$ and finite variance. So,
$$\operatorname{Var} \left(\sum_{1\leqslant i< j\leqslant n} X_i X_j \right) = \binom{n}{2} \operatorname{Var}(X) \text{ ?} $$
Thank you

A: \begin{align}
\operatorname{var}(X_1 X_2) & = \operatorname{E}(X_1^2 X_2^2) - (\operatorname{E}(X_1 X_2))^2 \\[6pt]
& = \operatorname{E}(X_1^2)\operatorname{E}(X_2^2) - (\operatorname{E}(X_1) \operatorname{E}(X_2))^2 = (\mu^2+\sigma^2)^2 - \mu^2 \\[10pt]
\operatorname{cov}(X_1 X_2,X_2 X_3) & = \operatorname{E}(X_1 X_2^2 X_3) - \operatorname{E}(X_1 X_2) \operatorname{E}(X_2 X_3) \\[6pt]
& = \mu(\mu^2+\sigma^2)\mu - (\mu^2)(\mu^2) \\[10pt]
\operatorname{cov}(X_1 X_2,X_3 X_4) & = 0.
\end{align}
Figure out how many terms of each of these three kinds you need to add up.


text:
Q: PhoneGap and Backbone Ajax call taking very long time I have a phonegap app built in Backbone and the ajax call is taking an incredibly long time. The load time is about 2min or longer to load a 46kb json file.
I am using the ios simulator which is pinging my local node.js server. The node.js server does a https.get() request to a weather service and returns it. The call works very quickly when I go to the url in a bowser.
Is the problem something to do with mobile memory management or underscore templating?  Help me! Thanks!
// views/weather.js
template: _.template($('#hero-1').html()),

render: function() {
    var view = this;
    $(this.el).html(this.template(view.model.toJSON()));
},

getWeatherData: function(lat, long){
      view.weatherModel = new this.model();
      view.weatherModel.fetch({
      data: {
        longitude: lat,
        latitude: long
      },
      success: function(data) {
          view.dataReturned(data.attributes);
          view.render();
      }
    });
 },

//  models/weather.js
return Backbone.Model.extend({

    url: 'http://127.0.0.1:3000/weather',

    parse: function(response){
        console.log("Parsing Response", response);
        response.weather.currently.avgTemp = Math.round(response.weather.currently.temperature);
        return response;
    }

});

// html/Template
<script type="text/template" id="hero-1">
   <div id="weather-temp" class="weather-temp">
      <%= weather.currently.avgTemp %>
   </div>
</script>

Thank you!
PLEASE NOTE:
If i do a standard call like this:
$.ajax({
            type: "GET",
            crossDomain:true,
            async: false,
            contentType:"application/json; charset=utf-8",
            url:"http://127.0.0.1:3000/weather?longitude=-122.406417&latitude=37.785834",
            success:function(data) {
               console.log('success');
               console.log(data);
            }
         });

It just times out quickly but will work if i do it in the safari console for the simulator.

A: I didn't realize that XCODE will reset the ios Simulators location.
Open the Simulator:
window>Debug>Location>Custom Location
Set a new location.


text:
Q: Cuda reusing events to determine execution time of multiple sections I wish to calculate the execution time for two different sections of my cuda code. In order to do so, I am trying to use CudaEvent_t start, stop.
My question is, can I use the same two events 'start' and 'stop' for calculating execution time in some other section?
For example:
cudaEvent_t start, stop;
cudaEventCreate(&start);
cudaEventCreate(&stop);

// SECTION 1
cudaEventRecord(start, 0);
cudaMemcpy(..., ..., ..., cudaMemcpyHostToDevice);
cudaEventRecord(stop, 0);

cudaEventSynchronize(stop);
cudaEventElapsedTime(&executionTime, start, stop);
printf("SECTION 1 executionTime: %f", executionTime);
// SECTION 1

// SECTION 2
cudaEventRecord(start, 0);    // Reusing start event
cudaMemcpy(..., ..., ..., cudaMemcpyDeviceToHost);
cudaEventRecord(stop, 0);     // Reusing stop event

cudaEventSynchronize(stop);
cudaEventElapsedTime(&executionTime, start, stop);
printf("SECTION 2 executionTime: %f", executionTime);
// SECTION 2

Would this code give accurate estimates for execution time for section 1 and section 2 since I'm trying to resue the cudaEvent_t start, stop for section 2 as well? Or do I need to create two additional events start1 and stop1 for the second section?

A: You can re-use events.  The ability to do this is afforded by the fact that you can record an event more than once:

If cudaEventRecord() has previously been called on event, then this call will overwrite any existing state in event. Any subsequent calls which examine the status of event will only examine the completion of this most recent call to cudaEventRecord().

So this means that any timing measured using events will only pertain to the most recently recorded events.  In your case/example, that is basically self-evident, but in more complex cases, it should be noted that only the most recently recorded "version" of an event is "active".


text:
Q: Posso converter a saída de um objeto ao usar o get()? Como posso converter a saída de um objeto ao usar a função get()? Visto que ela sempre retorna um valor
em string.
Aqui vai um código que estou escrevendo:
import tkinter as tk
import Sistema_backend

top = tk.Tk()
canvas = tk.Canvas(top, bg = "#159BA0", height = 500, width = 500)
canvas.pack()

Label1 = tk.Label(canvas, text = "Digite sua nota:")
Label1.place(x = 10,y = 10)
Entry1 = tk.Entry(canvas)
Entry1.place(x = 100,y = 10)

Label2 = tk.Label(canvas, text = "Digite sua nota:")
Label2.place(x = 10,y = 50)
Entry2 = tk.Entry(canvas)
Entry2.place(x = 100,y = 50)

Label3 = tk.Label(canvas, text = "Digite sua nota:")
Label3.place(x = 10, y = 90)
Entry3 = tk.Entry(canvas)
Entry3.place(x = 100, y = 90)

Label4 = tk.Label(canvas, text = "Digite sua nota:" )
Label4.place(x = 10, y = 130)
Entry4 = tk.Entry(canvas)
Entry4.place(x = 100, y = 130)

Label5 = tk.Label(canvas, text = "Média mínima: ")
Label5.place(x=10, y = 170)
Entry5 = tk.Entry(canvas)
Entry5.place(x=100, y = 170)

Label5 = tk.Label(canvas, text = "Total:")
Label5.place(x = 10,y = 210)
Label6 = tk.Label(canvas, text = "Resultado")
Label6.place(x = 10,y = 250)

try:
    Button1 = tk.Button(canvas, text = "Enviar notas",
    command = Sistema_backend.Sistema(Entry1.get(float),
    Entry2.get(float), Entry3.get(float), Entry4.get(float), Entry5.get(float)))
except:
    print('Algo de errado aconteceu!')
finally:
    Button1 = tk.Button(canvas, text = "Enviar notas")
    Button1.place(x = 10, y = 210)

Button2 = tk.Button(canvas, text = "Passou?")
Button2.place(x=10 , y= 290)

Label_result = tk.Label(canvas,text = "Resultado")
Label_result.place(x=10, y = 330)

canvas.mainloop()

Mais precisamente nesta parte:
try:
    Button1 = tk.Button(canvas, text = "Enviar notas",
    command = Sistema_backend.Sistema(Entry1.get(),
    Entry2.get(), Entry3.get(), Entry4.get(), Entry5.get()))
except:
    print('Algo de errado aconteceu!')
finally:
    Button1 = tk.Button(canvas, text = "Enviar notas")
    Button1.place(x = 10, y = 210)

Basicamente, na GUI que eu importei, quando o user apertar o "Button1", ele vai enviar os dados. Estes
dados são obtidos a partir das "Entry" (tipo um input, Entry é só o nome que a biblioteca dá). A função
get() aí vai permitir que eu "extraia" os dados nos Entry, mas o problema é que ela retorna em STR, e
eu quero trabalhar com FLOAT, mas não sei como converter.

A: Utilize a função float(). Vai ficar assim:
command = Sistema_backend.Sistema(float(Entry1.get()),
    float(Entry2.get()), float(Entry3.get()), float(Entry4.get()), float(Entry5.get()))

Caso não seja inserido um valor numérico na Entry vai ser levantada uma exceção.
O número deve ser inserido usando ponto para separar a casa decimal. Se você usar vírgula vai dar erro também.


text:
Q: owl-carousel never shows items i have a problem with owl-carousel that only the prev and next button is shown but the items which i add into the owl-carousel never show (always display:none)
this is my HTML code
$(document).ready(function(){
$('.owl-carousel').owlCarousel({
    loop:true,
    margin:10,
    nav:true,
    autoplay:true,
    autoplayTimeout:10000,
    autoplayHoverPause:true,
    responsive:{
        0:{
            items:1
        },
        600:{
            items:3
        },
        1000:{
            items:5
        }
    }
   });
 });

this is item 1

this is item 2

this is item 3

this is item 4

this is item 5

this is item 6

this is item 7

this is item 8

this is item 9

this is item 10

this is item 11

this is item 12

A: I think .owl-carousel class needs to be placed in jquery initialization. Please check this fiddle and let me know.
 $('.owl-carousel').owlCarousel({
    loop:true,
    margin:10,
    nav:true,
    autoplay:true,
    autoplayTimeout:10000,
    autoplayHoverPause:true,
    responsive:{
        0:{
            items:1
        },
        600:{
            items:3
        },
        1000:{
            items:5
        }
    }
   });

A: Your .js is correct. You just need add owl.carousel.min.css into  and owl.carousel.js into  tag.
Add this
<link href="https://owlcarousel2.github.io/OwlCarousel2/assets/owlcarousel/assets/owl.carousel.min.css" rel="stylesheet"/>

in  tag.
Then,
Add this

on bottom of  tag (before ).

A: I think You have forgot Add owl-carousel css and js file.
Please add owl-carousel css and js file
 <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/OwlCarousel2/2.2.0/assets/owl.carousel.css">

$('.owl-carousel').owlCarousel({
    loop:true,
    margin:10,
    nav:true,
    autoplay:true,
    autoplayTimeout:10000,
    autoplayHoverPause:true,
    responsive:{
        0:{
            items:1
        },
        600:{
            items:3
        },
        1000:{
            items:5
        }
    }
   });
 <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/OwlCarousel2/2.2.0/assets/owl.carousel.css">

this is item 1

this is item 2

this is item 3

this is item 4

this is item 5

this is item 6

this is item 7

this is item 8

this is item 9

this is item 10

this is item 11

this is item 12

A: You didn't included jquery in the question and owlcarousel css file. including those files to your code will fix the issue. Please see below code.

$('.owl-carousel').owlCarousel({
    loop:true,
    margin:10,
    nav:true,
    autoplay:true,
    autoplayTimeout:10000,
    autoplayHoverPause:true,
    responsive:{
        0:{
            items:1
        },
        600:{
            items:3
        },
        1000:{
            items:5
        }
    }
   });
<link href="https://owlcarousel2.github.io/OwlCarousel2/assets/owlcarousel/assets/owl.carousel.min.css" rel="stylesheet"/>

this is item 1

this is item 2

this is item 3

this is item 4

this is item 5

this is item 6

this is item 7

this is item 8

this is item 9

this is item 10

this is item 11

this is item 12


text:
Q: Does JW player support HTTP2? I am currently working on a project where we are using JW Player 7.11.1, we are planning to support http2 for our website, could you please help me understand, Does JW player support HTTP2?

A: You will not have problems, HTTP2 maintains high-level compatibility with HTTP 1.1.
doc: https://http2.github.io/faq/

we can work on new mechanisms that are version-independent, as long as
  they're backwards-compatible with the existing Web

I'm using JwPLyer 7.x with HTTP2 without problems.


text:
Q: Best practices for Domain Service classes in RIA Silverlight projects I would like to ask whether or not is a good practice, to hold the CRUD operations for business objects, in a single domain service class. Should we provide a domain service class for each BO?
ProductDomainService.cs
CustomerDomainService.cs
...
or a single
BusinessObjectDomainService.cs

A: I went with a single domain object beause my model is not that complex.  I would think it might be better to cluster the domain services together ie user services logging services.  That kind of logical clumping would be better than 1 for each business object.


text:
Q: Create dictionary from splitted strings from list of strings I feel that this is very simple and I'm close to solution, but I got stacked, and can't find suggestion in the Internet.
I have list that looks like:
my_list = ['name1@1111', 'name2@2222', 'name3@3333']

In general, each element of the list has the form: namex@some_number.
I want to make dictionary in pretty way, that has key = namex and value = some_number. I can do it by:
md = {}
for item in arguments:
    md[item.split('@')[0]] = item.split('@')[1]

But I would like to do it in one line, with list comprehension or something. I tried do following, and I think I'm not far from what I want.
md2 = dict( (k,v) for k,v in item.split('@') for item in arguments )

However, I'm getting error: ValueError: too many values to unpack. No idea how to get out of this.

A: You actually don't need the extra step of creating the tuple
>>> my_list = ['name1@1111', 'name2@2222', 'name3@3333']
>>> dict(i.split('@') for i in my_list)
{'name3': '3333', 'name1': '1111', 'name2': '2222'}


text:
Q: Кастомизация Snackbar Задача в следующем. Есть xml файл с разметкой. Можно ли запихнуть его в Snakbar так как это допустим делается с помощю адаптера для ListView? Если да то подскажите пожалуйста как. Заранее Благодарю)

A: Snackbar не должен содержать ничего кроме текста и кнопки

A: Есть несколько способов. Самый простой - получить доступ к разметке SnackBar-а и изменить её:
// Create the Snackbar
Snackbar snackbar = Snackbar.make(containerLayout, "", Snackbar.LENGTH_LONG);
// Get the Snackbar's layout view
Snackbar.SnackbarLayout layout = (Snackbar.SnackbarLayout) snackbar.getView();
// Hide the text
TextView textView = (TextView) layout.findViewById(android.support.design.R.id.snackbar_text);
textView.setVisibility(View.INVISIBLE);

// Inflate our custom view
View snackView = mInflater.inflate(R.layout.my_snackbar, null);
// Configure the view
ImageView imageView = (ImageView) snackView.findViewById(R.id.image);
imageView.setImageBitmap(image);
TextView textViewTop = (TextView) snackView.findViewById(R.id.text);
textViewTop.setText(text);
textViewTop.setTextColor(Color.WHITE);

// Add the view to the Snackbar's layout
layout.addView(snackView, 0);
// Show the Snackbar
snackbar.show();

Этот способ опасен тем, что вмешиваясь в стандартное поведение можно получить баги и падения на разных ОС и девайсах.

Также есть сложный способ переопределения почти всего в SnackBar - вот он. По идее он самый надёжный, ибо страхует от внезапных изменений на уровне ОС.

Вот ещё вариант переопределения разметки через xml и ресурсы: тык. Но в комментах пишут, что может и не сработать, т.к. в системе что-то поменялось.


text:
Q: How do i find the click event on indicator in radar chart? My project uses echart to create radar chart and i have to find click event for indicators around radar chart.
It is implemented like this.
createradarchart() {
  this.theme.getJsTheme()
    .pipe(
      takeWhile(() => this.alive),
      delay(1),
    )
    .subscribe(config => {
        this.options = {
          name: 'KPI Radar',
          grid: {
                left: '5%',
                right: '5%',
                top: 0,
                bottom: 0
          },
          // label: {
          //   distance: 5
          // },
          type: 'radar',
          color: ['red', 'green', 'blue'],
          legend: {
                  bottom: 5,
                  itemGap: 20,
                  data: ['Baseline', 'Threshold', 'Actual'],
                  textStyle: {
                      color: 'black',
                      fontSize: 10
                  }
          },
          radar: {
            indicator: this.indicator,
            nameGap: 5,
            shape: 'circle',
            radius: '43%',
            name: {
              textStyle: {
                  color: 'black',
                  fontSize: 10
              }
          }
        },
        tooltip: {
          show: true,
          textStyle: {fontSize:10},
          trigger: 'item',
          formatter: (params => {
             return params['name']+'-'+params['value'][1];
        })
        },
        series: this.seriesdata,
      };

       this.ctx = this.echartsIntance.getRenderedCanvas();
       this.chart = new Chart(this.ctx,{type:'radar', options: this.options})
        // this.ctx = canvas.getContext("2d");
    });
}

where data and options are in format, with data being fetched from server:
seriesdata: any = {type: 'radar', data:[{name:'Baseline',value:[1,2,3,4,5]},{name:'Threshold',value:[1,2,3,4,5]},{name:'Actual',value:[1,2,3,4,5]}]};
  indicator = [
    { name: 'DL User Thpt_Kbps[CDBH]', max: 100 },
    { name: 'ERAB SSR[CDBH]', max: 100 },
    { name: 'PS DCR %[CDBH]', max: 100 },
    { name: 'VoLTE CSSR', max: 100 },
    { name: 'VoLTE DCR[CBBH]', max: 100 }
  ];
  options: EChartOption = {
          name: 'KPI Radar',
          grid: {
            left: '2%',
            right: '2%',
            top: 0,
            bottom: 0
          },
          // label:{
          //   distance: 5
          // },
          type: 'radar',
          color: ['red', 'green', 'blue'],
          legend: {
                  orient: 'vertical',
                  align: 'left',
                  right: 20,
                  data: ['Baseline', 'Threshold', 'Actual'],
                  textStyle: {
                    color: 'black',
                    fontSize: 10
                }
          },
          radar: {
            indicator: this.indicator,
            nameGap: 5,
            shape: 'circle',
            radius:'60%',

        },
        tooltip: {
          show: false,
        //   trigger: 'item',
        //   formatter: (params => {
        //     return params['name']+'-'+params['value'][1];
        // })
      }
  };

This is where i want click event to be triggered, having the name of label which is clicked.
Approach i found to do this is this, but it didnt work, i debugged and found that scale.pointLabels is empty.
labelClicked(e:any){
  var self = this;
  var helpers = Chart.helpers;
  var scale = self.chart.scale;
  var opts = scale.options;
  var tickOpts = opts.ticks;

  // Position of click relative to canvas.
  var mouseX = e.offsetX;
  var mouseY = e.offsetY;

  var labelPadding = 5; // number pixels to expand label bounding box by

  // get the label render position
  // calcs taken from drawPointLabels() in scale.radialLinear.js
  var tickBackdropHeight = (tickOpts.display && opts.display) ?
      helpers.valueOrDefault(tickOpts.fontSize, Chart.defaults.global.defaultFontSize)
      + 5: 0;
  var outerDistance = scale.getDistanceFromCenterForValue(opts.ticks.reverse ? scale.min : scale.max);
  for (var i = 0; i < scale.pointLabels.length; i++) {
      // Extra spacing for top value due to axis labels
      var extra = (i === 0 ? tickBackdropHeight / 2 : 0);
      var pointLabelPosition = scale.getPointPosition(i, outerDistance + extra + 5);

      // get label size info.
      // TODO fix width=0 calc in Brave?
      // https://github.com/brave/brave-browser/issues/1738
      var plSize = scale._pointLabelSizes[i];

      // get label textAlign info
      var angleRadians = scale.getIndexAngle(i);
      var angle = helpers.toDegrees(angleRadians);
      var textAlign = 'right';
      if (angle == 0 || angle == 180) {
          textAlign = 'center';
      } else if (angle < 180) {
          textAlign = 'left';
      }

      // get label vertical offset info
      // also from drawPointLabels() calcs
      var verticalTextOffset = 0;
      if (angle === 90 || angle === 270) {
          verticalTextOffset = plSize.h / 2;
      } else if (angle > 270 || angle < 90) {
          verticalTextOffset = plSize.h;
      }

      // Calculate bounding box based on textAlign
      var labelTop = pointLabelPosition.y - verticalTextOffset - labelPadding;
      var labelHeight = 2*labelPadding + plSize.h;
      var labelBottom = labelTop + labelHeight;

      var labelWidth = plSize.w + 2*labelPadding;
      var labelLeft;
      switch (textAlign) {
      case 'center':
         labelLeft = pointLabelPosition.x - labelWidth/2;
        break;
      case 'left':
         labelLeft = pointLabelPosition.x - labelPadding;

        break;
      case 'right':
         labelLeft = pointLabelPosition.x - labelWidth + labelPadding;
        break;
      default:
        console.log('ERROR: unknown textAlign '+textAlign);
      }
      var labelRight = labelLeft + labelWidth;

      // Render a rectangle for testing purposes
      self.ctx.save();
      self.ctx.strokeStyle = 'red';
      self.ctx.lineWidth = 1;
      self.ctx.strokeRect(labelLeft, labelTop, labelWidth, labelHeight);
      self.ctx.restore();

      // compare to the current click
      if (mouseX >= labelLeft && mouseX <= labelRight && mouseY <= labelBottom && mouseY >= labelTop) {
          alert(scale.pointLabels[i]+' clicked');
          // Break loop to prevent multiple clicks, if they overlap we take the first one.
          break;
      }
  }
}

Thanks in advance


text:
Q: SSRS Parse Error local report processing Please I need your help 4 days i'm searching about solution for this error i have this code :
SELECT NON EMPTY { [Measures].[T POND], [Measures].[FACT TABLE Count],
 [Measures].[disponibilite], [Measures].[POND], [Measures].[T] }

 ON COLUMNS, NON EMPTY { ([DIM AXE GEO 2].[VILLLE].[VILLLE].ALLMEMBERS ) }
 DIMENSION PROPERTIES MEMBER_CAPTION, MEMBER_UNIQUE_NAME ON ROWS FROM (
     SELECT (
     STRTOMEMBER("[dim_date_Debut].[PK_Date].&["+ Format(CDate(Parameters!FromDimDateDebutPKDate.Value),
     "yyyy-MM-dd")+"T00:00:00]") : STRTOMEMBER("[dim_date_fin].[PK_Date_fin].&
     ["+Format(CDate(Parameters!ToDimDateDebutPKDate.Value),"yyyy-MM-dd")+"T00:00:00]"))
 ON  COLUMNS FROM [CubeDispo])

CELL PROPERTIES VALUE, BACK_COLOR, FORE_COLOR, FORMATTED_VALUE, FORMAT_STRING, FONT_NAME, FONT_SIZE, FONT_FLAGS

This is the error when  i deploy
query execution failed for dataset 'dataset1' query(4,93) Parser: the syntax for '.' is incorrect

Thank you in advance

A: Is something wrong with your parameter replacement in SSRS? It looks like maybe they are not being passed down? When I change:
STRTOMEMBER("[dim_date_Debut].[PK_Date].&["+ Format(CDate(Parameters!FromDimDateDebutPKDate.Value),
     "yyyy-MM-dd")+"T00:00:00]")

To
STRTOMEMBER("[dim_date_Debut].[PK_Date].&[2010-01-01T00:00:00]")

The syntax is fine.
Firstly, run SQL Server Profiler, do an Analysis Services trace and capture the MDX that is being sent to SSAS from SSRS.
If the "Parameters!ToDimDateDebutPKDate.Value" is still in the MDX, then check how your parameters are being assigned to the dataset.

A: I see you are doing string concatenation to form your query. Make sure you use = operation to tell RS that its not a static query but an expression.
For example if i use this as a query in query designer, i would get an error.
"Select * from table where col =" & Parameters!FromDimDateDebutPKDate.Value
while the same thing with = operator before it becomes an expression which RS would evaluate before sending it to SQL
="Select * from table where col =" & Parameters!FromDimDateDebutPKDate.Value


text:
Q: SharePoint Content Query Web Part - Ignoring Current Level Consider this SharePoint site hierarchy:
- Site Collection
 - Site1
     - Subsite1
         - AnotherSubsite1
             - Page1
             - Page2
         - AnotherSubsite2
     - Subsite2
         - Page3
         - Page4
 - Site2

You can assume that every Site in the above hierarchy has a default page.
If I place a CQWP on Site1's default page, can I instruct it to start getting data one level below where it was placed? i.e. ignore the page/site it's currently on, so that it returns:
     - Subsite1
         - AnotherSubsite1
             - Page1
             - Page2
         - AnotherSubsite2
     - Subsite2
         - Page3
         - Page4

Thank you

A: I would extend the CQWP and then hook up my own ProcessDataDelegate to remove the data that's not required. For example:
protected override void OnInit(EventArgs e)
{
    this.ProcessDataDelegate += ProcessItems;
}

public DataTable ProcessItems(DataTable data)
{
    // Query the DataTable and remove unnecessary information
}

The WebId column in data is the GUID for the SPWeb object of each returned item. Look up SPWeb.ID of the sites you no longer want and then remove these rows. Note that the GUIDs in the WebId column are upper-case and in "D" format as described in Guid.ToString().
Remember to use AcceptChanges() at the end to ensure the DataTable is updated.


text:
Q: Is a cross-validation list needed when there are no hyperparameters Original problem formulation - 12/04/2019:
I have a data set of 14 observations with six features each and an output variable of two classes. I applied a logistic regression model with the following workflow:

*

*Do not specify any hyperparameters, thus have a first degree decision boundary and a regularization parameter of zero.

*Split the data set into a training set (8 observations) and a test set (6 observations).

*Fit a model on the  training set and calculate the  test error from test set (by averaging over +-1000 random lists)

*Plot the learning curves and observe that we have a high variance/low bias issue

*Conclude that the model complexity cannot be reduced since the decision boundary is already of the first degree and thus I can only examine the effect of removing certain features or try to get a larger data set (which is not possible in the foreseeable future)

The questions if have are the following:

*

*Can I conclude 5. from my previous points?

*Is it correct to say that I am calculating the test error (and not approximating it) as I did not have the need to finetune any hyperparameters and thus my test set still qualifies as truly unseen?

*Is it strange to have a model of such low complexity and then still have a high variance/low bias error type?

*Assuming the second bullet point is correct, can I apply LOOCV (leave one out cross validation) to calculate the test error (or am I then approximating the test error again)?

The following was added after reading the answer by EdM - 14/04/2019
Model adjustments made: Following the comments by EdM and by Reading up on "An introduction to statistical learning". I realized that I need to incorperate some sort of feature shrinkage/selection, as I am working with a high-dimensionality problem. This was done by applying ridge-regression in combination with the Leave-One-Out Cross-Validation method (feature standardization was also applied). The graph below indicates thus the error on the cross validation set for different k-order polynomial decision boundaries and different values for the tuning parameter. The higher order-polynomials are given as an informative feature, as I don't really want to use these because it would only enlarge my high-dimensionality problem (as also indicated by EdM above).
note: I am not trying to convince a skeptical reader with my model. The goal is more to provide a proof-of-concept of application of Machine Learning in my research field.
Question: Ridge aregression still indicates that with a tuning parameter (lambda) of zero and a first degree factorization (k), the lowest error on the CV set is obtaind. This would thus effectively reduce the problem again to a least squares fit. Which, as I understood from the literature, cannot be used due to the high dimensionality. Am I missing something here or should I just do what the graph indicates and stick with the least squares fit?

A: Although you might think that a model with only 6 features is low in complexity, it's too complex for the data at hand. You do not have enough data to fit a logistic regression model reliably with 6 unpenalized features.
The high variance/low bias behavior you observe on multiple random train/test splits is what is expected with an overfitted model: too many parameter values estimated for the number of cases available. The usual rule of thumb for avoiding overfitting in unpenalized logistic regression is to have 10-20 cases of the least prevalent class per feature considered. With only 14 cases total you have no more than 7 in the least prevalent class, so you would be hard pressed to evaluate even a single unpenalized feature reliably.
If you were nevertheless to go on to investigate transformations of predictors (e.g., splines or other polynomial fits) to try to improve performance, you would be compounding your problems. In applying that rule of thumb for avoiding overfitting, you need to count each additional estimated parameter as an additional feature. So without additional precautions you would be heading even further down the overfitting path. As John von Neumann is alleged to have said: "With four parameters I can fit an elephant, and with five I can make him wiggle his trunk."
One possible way around this problem would be to use a penalized approach like ridge regression or LASSO. These approaches deliberately trade off increased bias for reduced variance by lowering the magnitudes of regression coefficients or (in LASSO) removing some features completely. That could, in principle, be combined with evaluation of polynomial or other transformations of features. With only 14 cases total, however, it would be difficult to convince a skeptical reader that your conclusions were correct.
With respect to hyperparameter choices, remember that standard unpenalized logistic regression has no hyperparameters to choose. It provides a model of class-membership probabilities. You only produce a decision boundary when you impose a probability cutoff for predicting class membership, based on some decision about relative costs and benefits of different misclassifications. That choice of cutoff might be considered a hyperparameter, but that comes after the logistic regression per se.
You do have hyperparameter choices to make if you choose the complexity of feature transformations by cross-validation or if you use penalization. In either case, however, the predictor function provided by the logistic regression model will still be linear in the coefficients of the features, however the features were transformed and however the coefficients were penalized. So the nature of the ultimate decision boundary remains the same as for standard logistic regression even if its location, the dimensions of its feature space, or its direction in feature space are different. Is that still a "first degree decision boundary" if some of the features have been non-linearly transformed from their originally observed values? I wouldn't worry too much about that terminology.
See section 4.2 of Harrell's Regression Modeling Strategies or of his associated class notes for guidance on cases per feature in different types of regressions. Chapters 6 and 7 of An Introduction to Statistical Learning provide one introduction to penalized methods. See Chapter 7 of The Elements of Statistical Learning for extensive discussion of what types of error you can estimate with these approaches even if you had more data. An important and difficult question is how well your "test error" would generalize to a new sample from the same underlying population.
Where to go from here
You want to "provide a proof-of-concept of application of Machine Learning in my research field." So you have to set up tests that will fairly represent how machine learning might be applied.
Note that with 14 cases and 6 features it is possible to include all predictors in an unpenalized linear model. The theoretical impossibility of an unpenalized linear model arises when the number of features exceeds the number of cases. So your model including all features is not violating a strict "high dimensionality" cutoff, although the unpenalized model will probably be overfit.
Also, there are 3 potential problems in the way you are performing cross validation.
First, leave-one-out cross validation is not always a good choice, as discussed in detail on this page.
Second you seem to be using classification error as the measure of model quality. If so, that is probably not wise as misclassification error depends on your particular choice of a cutoff for the probabilities returned by your logistic regression model. A proper scoring rule like the Brier score is probably a better choice. It's best to first optimize the probability predictions, then apply whatever cutoff makes sense for classification (if classification is necessary). Although the Brier score is the mean-square error between predicted probabilities from the logistic model and the actual (0,1) values, note that no logistic regression is a "least squares fit," as a logistic model has no closed-form solution and the fit is based on maximum likelihood.
Third, it's not clear whether you standardized your continuous features before the ridge regression analysis. As the ridge penalty is applied to the sum of squares of all coefficients, without standardization you get different results if a predictor based on length, say, is measured in miles versus millimeters. (Some software does this automatically for you, then transforms coefficients back to the original scales.)
When studies in your field involve such a low ratio of cases to predictors, then there is not much hope of doing substantially better than what you already have done. As you might expect, the more complex models tend to require more penalization and it's not really clear that any of them will outperform the standard unpenalized (and likely overfit) model even if you use a proper scoring rule like the Brier score.
You could, however, consider using your knowledge of the subject matter to design simulations of data sets (with appropriate choices of coefficients and error terms) to evaluate how machine learning techniques might be of value in larger-scale studies.


text:
Q: При объявлении переменной в функции она не видна при импорте в другой файл У меня есть файл main где объявляется переменная phonenumber

Далее она импортируется в другой файл from index.telegram.main import phonenumber и используется
В данной функции ей присваиваются значения в файле main

Но т.к переменная объявляется в самом начале, то у неё всегда значение no, а если её объявить в какой-то функции, то при импорте возникает ошибка cannot import name 'phonenumber' from 'index.telegram.main' (/mnt/c/WEB/codepython/PaymentForParking/index/telegram/main.py). Как можно решить данную проблему?

A: То есть нужно, как-то вычислять значение переменной до её импорта?
Это можно делать так:
def get_value():
    value = 'no'
    return value

phonenum = get_value()

И дальше импортируем переменную и используем как обычно:
from global_var import phonenum

print(phonenum) # 'no'

Update
Сделал файл main.py и в нём определил phonenumber таким образом
# @bot.message_handler(content_types=['contact'])

def contact(message):
    if message is not None:
        keyboard2 = types.ReplyKeyboardRemove()
        bot.send_message(message.chat.id, 'Вы успешно отправили свой номер', reply_markup=keyboard2)
        phonenumber = message.contact.phone_number
        # print(phonenumber)
    else:
        phonenumber = "Hi there"
    return phonenumber

phonenumber = contact(None)

Сделал другой файл и в нёго импортировал phonenumber и распечатал:
from main import phonenumber

print(phonenumber) # it prints "Hi there"

Всё работает. В чём подвох?


text:
Q: Parsing XML Response in R I currently have an XML Response from a SOAP API call which I have parsed into an XMLInternalDocument fine. I am having trouble extracting specific nodes from the parsed response.
Below is the approach I have taken to try to get the elements out of the XML response.
library(XML)

responseparsed <- XML::xmlParse("response2.xml")
getNodeSet(responseparsed, "//Category")

The response I get is an empty list (i.e. no content to my understanding)
# list()
# attr(,"class")
# [1] "XMLNodeSet"

I am ultimately wanting to get my XML response into a data.frame if possible, so would really appreciate some pointers because I also couldn't get xmlToList to work either because of the <header> and <body> both being in the XML packet.
If you take the below excerpt and create an XML file called response2.xml then you should be able to reproduce my problem.
<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:wsa="http://schemas.xmlsoap.org/ws/2004/08/addressing" xmlns:wsse="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd" xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd">
  <soap:Header>
    <wsa:Action>RetrieveResponse</wsa:Action>
    <wsa:MessageID>urn:uuid:mymessageid</wsa:MessageID>
    <wsa:RelatesTo>urn:uuid:relatestoid</wsa:RelatesTo>
    <wsa:To>http://schemas.xmlsoap.org/ws/2004/08/addressing/role/anonymous</wsa:To>
    <wsse:Security><wsu:Timestamp wsu:Id="Timestamp-c74b9126-8c79-4624-abd1-de4021ce1096">
      <wsu:Created>2015-08-13T12:38:54Z</wsu:Created>
      <wsu:Expires>2015-08-13T12:43:54Z</wsu:Expires>
    </wsu:Timestamp></wsse:Security>
  </soap:Header>
  <soap:Body>
    <RetrieveResponseMsg xmlns="http://exacttarget.com/wsdl/partnerAPI">
      <OverallStatus>OK</OverallStatus>
      <RequestID>myanonrequestid</RequestID>
      <Results xsi:type="List">
        <Client>
          <ID>6212693</ID>
        </Client>
        <PartnerKey xsi:nil="true" />
        <ID>537</ID>
        <ObjectID xsi:nil="true" />
        <ListName>All Subscribers</ListName>
        <Category>2151</Category>
        <Type>Private</Type>
      </Results>
      <Results xsi:type="List">
        <Client>
          <ID>6212693</ID>
        </Client>
        <PartnerKey xsi:nil="true" />
        <ID>1217</ID>
        <ObjectID xsi:nil="true" />
        <ListName>list A</ListName>
        <Category>3038</Category>
        <Type>Private</Type>
      </Results>
      <Results xsi:type="List">
        <Client>
          <ID>6212693</ID>
        </Client><PartnerKey xsi:nil="true" />
        <ID>1434</ID><ObjectID xsi:nil="true" />
        <ListName>List B</ListName>
        <Category>6362</Category>
        <Type>Private</Type>
      </Results>
      <Results xsi:type="List">
        <Client>
          <ID>6212693</ID>
        </Client>
        <PartnerKey xsi:nil="true" />
        <ID>1435</ID>
        <ObjectID xsi:nil="true" />
        <ListName> List C</ListName>
        <Category>6362</Category>
        <Type>Private</Type>
      </Results>
    </RetrieveResponseMsg>
  </soap:Body>
</soap:Envelope>

A: Category inherits default namespace from RetrieveResponseMsg ancestor element. To reference element in namespace using XPath, you need to map a prefix to point to the namespace uri, and use that prefix in your XPath. I'm not very familiar with r, but I think it will be something like :
getNodeSet(responseparsed, "//d:Category", c(d="http://exacttarget.com/wsdl/partnerAPI"))


text:
Q: Finding minima and maxima to $f(x,y) = x^2 + x(y^2 - 1)$ in the area $x^2 + y^2 \leq 1$ I'm asked to find minima and maxima on the function
$$f(x,y) = x^2 + x(y^2 - 1)$$
in the area
$$x^2 + y^2 \leq 1.$$
My solution:
$$\nabla (f) = (2x + y^2 - 1, 2xy)$$
Finding stationary points
$$2xy = 0$$
$$2x + y^2 - 1 = 0$$
gets me $(0,1),(0,-1),(\frac{1}{2},0)$.
Stuyding the boundary:
$$x^2 + y^2 = 1$$
$$y^2 = 1 - x^2 $$
$$f(x,y) = f(x, 1-x^2) = x^2 -x^3$$
Finding stationary points on the boundary:
$$f'(x,y) = 2x - 3x^2 = 0$$
gives $(0, 1), (0,-1), (\frac{2}{3}, \sqrt{\frac{5}{9}}),(\frac{2}{3}, -\sqrt{\frac{5}{9}})$.
So in total i've got the stationary points
$$(\frac{1}{2} , 0) | (0,1)| (0,-1)| (\frac{2}{3},\sqrt{\frac{5}{9}})|(\frac{2}{3}, -\sqrt{\frac{5}{9}}).$$
which give the function values of:
$$-\frac{1}{4}, 0,0,0.15,0.15$$.
which gives the minima: $-\frac{1}{4}$ and maxima $0.15$.
The minima is correct but the maxima should be 2. Why? What stationary point am I missing?

A: Just as you check the boundary of the 2_D region, you also have to check the endpoints of your interval.  $f(x)=x^2-x^3$ on the interval $[-1,1]$.  You find that $x=-1, y=0$ is your max.

A: HINT: the searched maximum is given by $2$ and will be attained for $$x=-1,y=0$$

A: You have a small problem. When you consider $f(x,1-x^2)$ it should be considered over the closed interval $x \in [-1,1]$, which means its endpoints must also be included into the possible list of points.
$f(-1)=2$...


text:
Q: Increase touch target size jQuery ui slider I want to make the jQuery UI Slider more user friendly on mobile devices.
This is why I want to increase the size of the touch target area to move the slider. I don´t want to increase the actual size of the button. I just want to increase the box around the button. So even clumsy users or users with big thumbs can easily controle the slider.

A: You can play around with CSS to increase padding around the button.
.ui-slider-handle{
  padding: 10px;
}

However, increasing the padding around button without making the button size bigger will be little tricky.
.ui-slider-handle{
  padding: 10px;
  margin-top: -11px;
  border: none !importnat;
  background: 0 !important;
}
.ui-state-default,
.ui-widget-content .ui-state-default,
.ui-widget-header .ui-state-default,
.ui-slider-handle:hover{
  border: none !important;
}
.ui-slider-handle:after{
  content: "";
  width: 24px;
  height: 24px;
  background: #ccc;
  display: inline-block;
  border: 1px solid #666;
  border-radius: 4px;
  -moz-border-radius: 4px;
}

Please see the example below.
https://jsfiddle.net/Ohsik/k57o3em4/2/
You probably have to play around with CSS to make it look the way you want it to be.


text:
Q: How to store the keystrokes of clients (Windows Xp) on a linux server (RHEL 5)? How to store the keystrokes of clients (Windows Xp) on a linux server (RHEL 5)?
I want to monitor my employees every action in office at working time,

*

*Keystroke Recorder Application

*Activity Recorder

*Record keystrokes typed in any chat, internet messengers or e-mail clients

*Clipboard Monitoring Screen shots

*Maker Sends logs to email

How can I do it?

A: If you're going to do this (and I would also advise against) the first thing I would recommend is that you check the employment, company, privacy and data protection laws of your country to ensure that it's not illegal.  Secondly you need to check your employee's contracts and ensure that you're not breaking them.
Next you need to think hard about your reasons for doing this.  I'm giving you the benefit of the doubt here and assuming that you have grounds to suspect that one of them might be engaged in some kind of fraud or other nasty activity.  If not, I'd advise you to back away and forget that you ever thought of it right now.
After that you need to check what legal recourse you have.  A good and honest company or employment lawyer (one who isn't just out to grab money) will be able to advise on legal means of obtaining the evidence you need.  Above all else, you need to stay on the right side of the law.  If it came to a court case (e.g. if an employee claimed unfair dismissal) you would be in a whole heap of trouble if the evidence you used was obtained illegally.
While we're on the legal side, you need to also be certain about laws relating to monitoring employees.  You may be obliged by law to inform them that you're monitoring them, you may be obliged by law to inform them of what you're monitoring, you may be obliged by law to inform them of the reasons why you're monitoring them, and you may be obliged by law to hand over any data you collect to an employee who requests it.
If you're still determined to go down this route, you need to know that installing keylogging, screengrabbing, etc software on PCs is basically installing software that mimics (or exactly replicates!) the behaviour of viruses and other nasties.  This may not play nicely with your AV software (you do use AV software?) and it might be the case that one of them would have to go.  Do you want that?  Really?

A: While the technology does exist for doing each of these things I would strongly discourage trying to use them in a productive environment.
Among other things these tools would be providing a security nightmare ... passing sensitive data back across your network and storing it on an extremely high value target.  All your security eggs will be in one basket; anyone gaining access to that can find every password, pass phrase and every other bit of potentially sensitive data from every other system in your network over a some fairly long period of time.
They are likely to have a horrible impact on employee morale ... similar to the effect of posting burly thugs to stand over them watching every keystroke and listen to every word they utter with a stopwatch in one hand (and perhaps a whip in the other).
Additionally loading a number of these tools on everyone's desktop machines is likely to impact the stability and performance of workstations ... and passing every keystroke and periodic snapshots over network could generate quite a bit of traffic.  (In fact the most obvious way to enforce the use of these tools would be for the desktop/workstations to be thin clients with all productivity applications, chat/IM clients and so on all installed on centralized servers ... running Citrix or "Terminal Server Edition" or Red Hat's "Virtualization for Desktops" product (based on their Qumranet acquisition if I recall correctly).
Moreover if you are capturing all this data who are you going to assign to review it?  How much are you going to spend looking at a gnat's eye view of your employee behavior?
Finally consider that no combination of these tools that you install on your employees computers are is going to be foolproof.  Some of your employees will probably find ways to bypass them.  In other cases they are likely to fail for various innocuous reasons.  They are likely to create additional layers of complexity and support overhead.
If you really want to ensure that your employees are working then perhaps you should focus on meaningful productivity metrics and processes.  How much work did they accomplish?  How accurately did they do it?  Are they generating complaints from customers?  From co-workers?
There are effective and efficient ways to manage your staff.  Playing proctologist and crawling through their alimentary canals with a microscope is not among them!

A: Umm I am sorry your language is a little confusing.
Do you want to monitor what the users are doing when they are connected to the RHEL5 server? OR Do you just want to monitor their XP desktops with something that will store the data on your RHEL5 server?
Either way you could use squid to control how users connect to the internet on your RHEL, and set the XP clients to connect to REHL5 server before going to the internet.
Other than that you could use something like this
http://www.xp-tools.com/xpkeylogger/index.htm
But in the end if your that concerned about your employees, possibly getting a higher caliber of employee might be a less painful option.


text:
Q: How to configure custom PYTHONPATH with VM and PyCharm? I am using IntelliJ with the Python plugin and the Remote Interpreter feature to communicate with my Vagrant VM. It sets up the remote interpreter correctly to use my VM's interpreter. But, I use a custom PYTHONPATH in my VM, and I would like IntelliJ to recognize that path and include the modules in that path when developing.
How do I configure IntelliJ/PyCharm's remote interpreter to use a custom PYTHONPATH on the VM?

A: Instructions for editing your PYTHONPATH or fixing import resolution problems for code inspection are as follows:

*

*Open Preferences (On a Mac the keyboard short cut is ⌘,).

*Look for Project Structure in the sidebar on the left under Project: Your Project Name

*Add or remove modules on the right sidebar

EDIT: I have updated this screen shot for PyCharm 4.5

A: An update to the correct answer phil provided, for more recent versions of Pycharm (e.g. 2019.2).
Go to File > Settings and find your project, then select Project Interpreter. Now click the button with a cog to the right of the selected project interpreter (used to be a ...).

From the drop-down menu select Show All... and in the dialog that opens click the icon with a folder and two sub-folders.

You are presented with a dialog with the current interpreter paths, click on + to add one more.

A: In my experience, using a PYTHONPATH variable at all is usually the wrong approach, because it does not play nicely with VENV on windows. PYTHON on loading will prepare the path by prepending PYTHONPATH to the path, which can result in your carefully prepared Venv preferentially fetching global site packages.
Instead of using PYTHON path, include a pythonpath.pth file in the relevant site-packages directory (although beware custom pythons occasionally look for them in different locations, e.g. enthought looks in the same directory as python.exe for its .pth files) with each virtual environment. This will act like a PYTHONPATH only it will be specific to the python installation, so you can have a separate one for each python installation/environment. Pycharm integrates strongly with VENV if you just go to yse the VENV's python as your python installation.
See e.g. this SO question for more details on .pth files....

A: To me the solution was to go to
Run > Edit Configuration > Defaults > Python

then manage the

*

*"Add content roots to PYTHONPATH" and

*"Add source root to PYTHONPATH"

checkboxes, as well as setting the "Working directory" field.
If you have set up your own Run/Debug Configurations then you might want to go to
Run > Edit Configuration > Python > [Whatever you called your config]

and edit it there.
My problem was that I wanted to have my whole repository included in my PyCharm 2016.2 project, but only a subfolder was the actual python source code root. I added it as "Source Root" by right clicking the folder then
Mark directory as > Source Root

Then unchecking "Add content roots to PYTHONPATH" and checking "Add source root to PYTHONPATH" in the Run/Debug config menu. I then checked the folder pathing by doing:
import sys
logger.info(sys.path)

This outputed:
[
    '/usr/local/my_project_root/my_sources_root',
    '/usr/local/my_project_root/my_sources_root',
    '/usr/lib/python3.4', '/usr/lib/python3.4/plat-x86_64-linux-gnu',
    '/usr/lib/python3.4/lib-dynload',
    '/usr/local/lib/python3.4/dist-packages',
    '/usr/lib/python3/dist-packages'
]

However, without the fix it said:
[
    '/usr/local/my_project_root/my_sources_root',
    '/usr/local/my_project_root',                   <-- NOT WANTED
    '/usr/lib/python3.4',
    '/usr/lib/python3.4/plat-x86_64-linux-gnu',
    '/usr/lib/python3.4/lib-dynload',
    '/usr/local/lib/python3.4/dist-packages',
    '/usr/lib/python3/dist-packages'
]

Which meant I got the project root folder included. This messed up the pathing for me.

A: This was done with PyCharm Community 2019.1

*

*Go to Project Settings

*Go to Project Structure and right click on the directory you want to add and click "Sources"
This should add the directory to your pythonpath

A: For PyCharm 5 (or 2016.1), you can:

*

*select Preferences > Project Interpreter

*to the right of interpreter selector there is a "..." button, click it

*select "more..."

*pop up a new "Project Interpreters" window

*select the rightest button (named "show paths for the selected interpreter")

*pop up a "Interpreter Paths" window

*click the "+" buttom > select your desired PYTHONPATH directory (the folder which contains python modules) and click OK

*Done! Enjoy it!

A: Latest 12/2019 selections for PYTHONPATH for a given interpreter.

A: Well you can do this by going to the interpreter's dialogue box. Click on the interpreter that you are using, and underneath it, you should see two tabs, one called Packages, and the other called Path.
Click on Path, and add your VM path to it.

A: In pycharm 5 follow this,
https://www.jetbrains.com/pycharm/help/configuring-python-interpreter-for-a-project.html
1)Open the Settings dialog box, and click Project Interpreter page.
2)In the Projects pane, choose the desired project.
3)For the selected project, choose SDK from the list of available Python interpreters and virtual environments.

A: In Intellij v2017.2 you can go to:
run > edit configurations > click ... next to the field 'Environment variables' > click the green + sign
Name= PYTHONPATH
value= your_python_path

A: Pycharm 2020.3.3 CE ZorinOS(Linux) File>Settings > Project Structure > {select the folder} > Mark as Source(blue folder icon) > Apply
To verify:
import sys
print(sys.path)

Selected path should be listed here.


text:
Q: Do magnetic domains constitute a current? If a magnetic material is exposed to a magnetic field, and all of the the magnetic dipoles align in the same direction, then the bound currents, while in the inside the material, cancel each other out, on the boundary of the material, there is nothing to cancel them out, meaning we could interpret this so individual tiny loops of bound current constitute one large loop of current on the outside of the object.
So what about domains then? Are they not the same way? Could a magnetic domain, with all of it's loops of bound current, be interpreted as one large loop of current around the domain? Forming some sort of "domain current", even though this would be cancelled out in the end by all of the adjacent domains anyway?
Also, are there any other forms of current that can be found within magnetic materials? Apart from free  and bound currents?

A: Yes, the field produced by the alignment of atomic dipoles within a domain is the same as the one that would be produced by a current flowing around the the boundary of the domain.
As far as I know, the only other currents associate with a permanent magnet are those associated with individual atomic dipoles.


text:
Q: AVR programmer necessary? I have an atmega168pb and I've noticed that there is a difference in how the board can be programmed between Windows and Linux.
On Windows using Atmel Studio you can select an ISP interface and it automagically programs the board through the USB port. However since Atmel Studio is not available on Linux an external programmer is needed. This irks me because hypothetically I would need to buy hardware to provide a solution that is already exists in a software implementation.
Is there a way to flash an AVR chip on Linux without the need for an external programmer, like an AVR-ISP for example?

A: The ATmega168PB does not feature an USB interface. What you have there is either

*

*an evaluation board with a built-in ISP programmer

or

*

*a board with a USB-RS232 converter and a pre-flashed bootloader on the µC which employs self-programming of the other parts of the on-chip flash ROM through the RS232 pins.

You cannot flash an ATmega168 coming fresh from factory without an external programmer.
I strongly recommend to buy or build an ISP programmer. You will need it from some point on.


text:
Q: delete last item in all rows and columns numpy.ndarray I am trying to delete the last item in both the rows and columns in my numpy.ndarray (type = class numpy.ndarray). My array has 30 rows and 180 columns (i.e. 180 values per row). I have tried numpy.delete but this simply removes the whole row/column.
To illustrate what I want to achieve I created the following example in Python using and array and nested for loops:
a = np.array([[[1,2,3,4,5,6],[1,2,3,4],[1,2,3,4]],[[1,2,3,4,5,6],[1,2,3,4],[1,2,3,4]],[[1,2,3,4],[1,2,3,4],[1,2,3,4]],[[1,2,3,4],[1,2,3,4],[1,2,3,4]],[[1,2,3,4],[1,2,3,4],[1,2,3,4]],[[1,2,3,4],[1,2,3,4],[1,2,3,4]],[[1,2,3,4],[1,2,3,4]],[[1,2,3,4],[1,2,3,4]],[[1,2,3,4],[1,2,3,4]],[[1,2,3,4],[1,2,3,4]],[[1,2,3,4],[1,2,3,4]]])
for list in a:
    for sublist in list:
        del sublist[-1]

Using
print(a)

Gives the following array:

[[[1, 2, 3, 4, 5, 6], [1, 2, 3, 4], [1, 2, 3, 4]]
 [[1, 2, 3, 4, 5, 6], [1, 2, 3, 4], [1, 2, 3, 4]]
 [[1, 2, 3, 4], [1, 2, 3, 4], [1, 2, 3, 4]]
 [[1, 2, 3, 4], [1, 2, 3, 4], [1, 2, 3, 4]]
 [[1, 2, 3, 4], [1, 2, 3, 4], [1, 2, 3, 4]]
 [[1, 2, 3, 4], [1, 2, 3, 4], [1, 2, 3, 4]] [[1, 2, 3, 4], [1, 2, 3, 4]]
 [[1, 2, 3, 4], [1, 2, 3, 4]] [[1, 2, 3, 4], [1, 2, 3, 4]]
 [[1, 2, 3, 4], [1, 2, 3, 4]] [[1, 2, 3, 4], [1, 2, 3, 4]]]

Using
print(list)

after the for loops gives:
[[1, 2, 3, 4, 5], [1, 2, 3], [1, 2, 3]]
[[1, 2, 3, 4, 5], [1, 2, 3], [1, 2, 3]]
[[1, 2, 3], [1, 2, 3], [1, 2, 3]]
[[1, 2, 3], [1, 2, 3], [1, 2, 3]]
[[1, 2, 3], [1, 2, 3], [1, 2, 3]]
[[1, 2, 3], [1, 2, 3], [1, 2, 3]]
[[1, 2, 3], [1, 2, 3]]
[[1, 2, 3], [1, 2, 3]]
[[1, 2, 3], [1, 2, 3]]
[[1, 2, 3], [1, 2, 3]]
[[1, 2, 3], [1, 2, 3]]

Unfortunately using this on my array gives the following error:

TypeError: 'numpy.float64' object does not support item deletion

Thanks

Update:
I am extracting my information from a grid NetCDF file. I have changed the word list to l since list is a Python keyword. This didn't change it for me.
This provides a good example of my array:
c = np.arange(5400).reshape(30,180)
for l in c:
    for i in l:
        del i[-1]

When I run this code I get the following error:
Traceback (most recent call last):   File "main.py", line 18, in <module>
    del i[-1]
 TypeError: 'numpy.int64' object does not support item deletion

A: del i[-1] is a list operation.  np.array does not support that.
Count the occurrences of a specific value and remove them at the same time demonstrates the differences between lists and arrays when it comes to deletion.
Your example a is object dtype, containing lists
In [111]: a.shape
Out[111]: (11,)
In [112]: [len(i) for i in a]
Out[112]: [3, 3, 3, 3, 3, 3, 2, 2, 2, 2, 2]
In [113]: a[0]
Out[113]: [[1, 2, 3, 4, 5, 6], [1, 2, 3, 4], [1, 2, 3, 4]]

a[0] is a 3 element list, with sublists of different length.
It's not clear what you want to delete.  Delete elements from a, or elements from each element of a, or elements from the sublists of those elements.
Furthermore, if the real data is from NetCDF it might actually a multidimensional array.  Or if object dtype, the elements might themselves be (2d) arrays.
In case, slicing is the right way to remove rows/columns from an array:
In [114]: a = np.arange(12).reshape(3,4)
In [115]: a
Out[115]:
array([[ 0,  1,  2,  3],
       [ 4,  5,  6,  7],
       [ 8,  9, 10, 11]])
In [116]: a[:-1, :-1]
Out[116]:
array([[0, 1, 2],
       [4, 5, 6]])

The result is a view; it does not change a itself.  a = a[:-1, :-1].copy() is the cleanest way to creates a reduced size array without leaving the any of the original around.


text:
Q: Live Sass Compiler not compiling I have used the live sass compiler a few hours back, it worked fine, but now it's not working. Can you please let me know what can be the problem?
This is what I see when I hit ctrl + s

This is my project folder structure

This is settings in settings.json
Thanks for your help in advance.

A: Do you have any other folders open at the same time in Visual Studio? This happened to me one day and by closing all the folders started working again. It doesn't work by just restarting Visual Studio, you have to close them by hand.
The settings.json seems alright and the compiler isn't showing any errors.


text:
Q: How to handle test tags/karate options from ci/cd gitlab? I was trying to run the test from CI/CD gitlab runner file but it is causing issue while executing from gitlab.
I have sucessfully executed the test locally using the karate option
Working fine in Local Run:
mvn test -Dkarate.env=stg +-DKarate.options=--tags @Ui" -Dtest.run.mode=localtest -Dtest.run.group=OKCUtest -Dtest=OKCUtest -Dtest.gitlabRunner=false -DbuildDirectory=stg-target/OKCUtest -Dtest.run.testSource=localtest
There are 5 test feature files which were executed using the @Api tags and now I have identified that one should be @Ui and changed the respective feature file and created the new pipeline OKCU-UI and have updated the command line syntax to address @Ui tests.

A: can you try this command ?
mvn test -Dkarate.options="--tags ~@Ui"

if still not try same command with version 0.9.6.RC3


text:
Q: Consider the Cambridge English examinations, does "productive vocabulary" have a higher priority than "receptive vocabulary" A Cambridge English vocabulary says

The list covers vocabulary appropriate to the B1 level on the Common European Framework of Reference (CEFR) and includes receptive vocabulary (words that the candidate is expected to understand but which is not the focus of a question) and productive vocabulary (words that the candidate needs to know to answer a question).

If some candidates know only part of the receptive vocabulary, they may guess what the question is; if they know only part of the productive vocabulary, they may have enough vocabulary to constitute the answer.
So, consider only the examinations, does "productive vocabulary" have a higher priority than "receptive vocabulary"?

A: Well suppose "pinnacle" is part of the receptive vocabulary, and "mountain" is part of the productive vocabulary. This means that you would be expected to understand a question like

When did the climbers reach the pinnacle of the mountain?"

If "pinnacle" is not in your receptive vocabulary then you would not understand the question. You might guess, and you might be right.
However you would not be expected to answer a question using "pinnacle", though no marks would be lost if you use it correctly.
You would also be expected to be able to answer a question like:

What did he do during his vacation?
  He climbed a mountain.

If you don't know the word "mountain" you can't answer in this way. If you can think on your feet you might be able to say "He climbed a big hill". So it is possible that you could still answer this question, but not using the precise term can cause you to be marked down.
If a word is in your "productive vocabulary" then it must also be in your "receptive vocabulary".  You are expected to be know all the words in the productive list well enough to use them yourself, even though you won't be tested on all the words, you don't know which ones you won't need.
You should know all the words in the "receptive vocabulary" list too, but don't worry about using them, you only need to understand sentences that use these words.


text:
Q: Rails log is not logging anything on production server I have setup my application on ubuntu server but it is not logging logs in production.log file.
Here is my production.rb file contents.
# Send deprecation notices to registered listeners.
  config.active_support.deprecation = :notify

  # Use default logging formatter so that PID and timestamp are not suppressed.
  config.log_formatter = ::Logger::Formatter.new

  # Use a different logger for distributed setups.
  # require 'syslog/logger'
  # config.logger = ActiveSupport::TaggedLogging.new(Syslog::Logger.new 'app-name')

  if ENV["RAILS_LOG_TO_STDOUT"].present?
    logger           = ActiveSupport::Logger.new(STDOUT)
    logger.formatter = config.log_formatter
    config.logger    = ActiveSupport::TaggedLogging.new(logger)
  end

  # Do not dump schema after migrations.
  config.active_record.dump_schema_after_migration = false

I made changes below but still file is empty on server.
# Send deprecation notices to registered listeners.
  config.active_support.deprecation = :notify

  # Use default logging formatter so that PID and timestamp are not suppressed.
  config.log_formatter = ::Logger::Formatter.new

  # Use a different logger for distributed setups.
  # require 'syslog/logger'
  # config.logger = ActiveSupport::TaggedLogging.new(Syslog::Logger.new 'app-name')

  if ENV["RAILS_LOG_TO_STDOUT"].present?
    logger           = ActiveSupport::Logger.new('log/production.log')
    logger.formatter = config.log_formatter
    config.log_level = :debug
    config.logger    = ActiveSupport::TaggedLogging.new(logger)
  end

  # Do not dump schema after migrations.
  config.active_record.dump_schema_after_migration = false

Is this related to file permission on production server? Or what is the problem?