text:
Q: How to get values OpenGL calculated between given height levels? I need the coordinates that OpenGL calculate between different height levels linearly.
I have a high level map in the size 64 x 64 px and a texture that I present corresponding to the height map. This representation is substantially greater than 64 x 64 px, so OpenGL calculated intermediate values (probably linear), so that no steps are formed in the 3D space.
I could use this intermediate values to use the marching squares algorithm optimally, without to perform a linear interpolation by myself, as the graphics card has already done this to adjust the texture to the heights.
Is it possible to get the z coordinate using a function stating the x and y coordinates?

A: OpenGL just draws points, lines and triangles. There's no such thing as a "scene" or "models" in OpenGL. Interpolation happens merely on the primitive (= lines or triangles) level. Inside the shader stages lots of things can happen, but as far as OpenGL is concerned it's totally agnostic about what the shader programs do. You can read back the computations of vertex shaders using transform feedback. The output of fragment shaders are images (which you can read with glReadPixels) and compute shaders operate directly on memory.

Is it possible to get the z coordinate using a function stating the x and y coordinates?

Certainly, if you're able to define in program how the Z coordinate depends on the x,y pair and the input data (= height map). So you as a programmer have to program this and thus can also program how to read it back. OpenGL is completely agnostic about this but gives you all the low level operations required to implement this.
OpenGL is not some kind of "magic" geometry processor.


text:
Q: Is my application of Bayes' Theorem here correct? I am new to Bayes' theorem and like many others, am having a hard time wrapping my head around it. Here's a question that I am trying to answer:
Question:
Imagine there's a bot detection tool that identifies a rare automated attack:

*

*Only 1 in 100,000 website visits involve the type of attack this tool detects

*The tool will correctly classify the automated attack 100% of the times when the attack is occurring

*The tool incorrectly classifies 0.01% of site visits as involving the attack type when it is not occurring i.e. false positive rate

If the tool classifies the random site visit as this rare attack, what is the probability that the attack is actually occurring?
My approach:
I am referring to this article on Bayes' theorem. My approach is to plug values in this formula:
P(A|X) = P(X|A) * P(A) / (P(X|A)*P(A) + P(X|~A)*P(~A) )

Assuming X is the event of detection and A is the event of attack. My values would be:
P(A) = 0.00001, since that's the number of times the attack happens
P(~A) = 0.99999
P(X|~A) = 0.0001 i.e the false positive rate
P(X|A) = 1
Plugging these values in, I get the answer: 0.090909917 or 9.09%. Somehow this seems far too low and I am not sure if there's an error in my calculations. Could someone kindly highlight if there's an error here?

A: Given that:
$$
A= "\text{the request is an attack}"\\
X= "\text{antivirus detected it}"\\
$$
then the probability is given by:
$$
\begin{align*}
P(A|X)&= \frac{P(X|A)P(A)}{P(X)}\\
&= \frac{P(X|A)P(A)}{P(X|A)P(A)+P(X|A^c)P(A^c)}\\
&=\frac{1\cdot0.00001}{1\cdot0.00001 + 0.0001\cdot0.99999}\\
&\approx 9.09\%
\end{align*}
$$
Therefore your calculation is correct.
you classifier/antivirus looks good if taken individually, however, when you actually see that you have a ton of request that are "no attacks" that your antivirus will mark them as "attack", the fact that it has $0.01%$ false positive rate, makes the prediction very uncertain
In other words, if you take all the requests that your antivirus will mark as "attack", you will have a lot of false positive
... and this is not because your antivirus is bad, but just because you have a lot of "normal" request
Which is the whole point of Bayes theorem, in other words, you should also consider your prior in the calculation of the probability

redpajama_set_name: RedPajamaStackExchange


text:
Q: Compilation of Hadoop Java program with additional dependencies I'm attempting to build a Hadoop program, the purpose of which is to cat files that I've previously uploaded to HDFS, based largely on this tutorial, the program looks like this:
import java.io.*;
import java.net.URI;
import org.apache.hadoop.fs.*;
import org.apache.hadoop.conf.*;
import org.apache.hadoop.io.*;

public class ReadHDFS {
    public static void main(String[] args) throws IOException {

        String uri = args[0];

        Configuration conf = new Configuration();
        FileSystem fs = FileSystem.get(URI.create(uri), conf);
        FSDataInputStream in = null ;

        try
        {
            in = fs.open(new Path(uri));
            IOUtils.copyBytes(in, System.out, 4096, false);
        }
        finally
        {
            IOUtils.closeStream(in);
        }
    }
}

It seems to me that the tutorial is flawed, because- according to my understanding- IOUtils is part of the apache.commons library. However, although I added the following line to the program I've been trying to deploy:
import org.apache.commons.compress.utils.IOUtils;

I'm still met with the following error:

That is:
FileSystemCat.java:37: error: cannot find symbol
        IOUtils.copyBytes(in, System.out, 4096, false);
               ^
  symbol:   method copyBytes(InputStream,PrintStream,int,boolean)
  location: class IOUtils
FileSystemCat.java:40: error: cannot find symbol
        IOUtils.closeStream(in);
                            ^
  symbol:   variable in
  location: class FileSystemCat
2 errors

I'm executing it on the NameNode with this command:
javac -cp /usr/local/hadoop/share/hadoop/common/hadoop-common-2.8.1.jar:/home/ubuntu/job_program/commons-io-2.5/commons-io-2.5.jar FileSystemCat.java

A: Necessary appendix to ~/.bashrc:
# Classpath for Java

# export HADOOP_CLASSPATH=$($HADOOP_HOME/bin/hadoop classpath)
export HADOOP_CLASSPATH=$($HADOOP_HOME/bin/hadoop classpath)

How to compule the program at the bottom:
javac -cp ${HADOOP_CLASSPATH}:commons-io-2.5.jar ReaderHDFS.java

How to generate the jar file for that program:
jar cf rhdfs.jar ReaderHDFS*.class

Run the command:
$HADOOP_HOME/bin/hadoop jar rhdfs.jar ReaderHDFS hdfs://master:9000/input_1/codes.txt

This is the program:
import org.apache.hadoop.io.IOUtils;
//import org.apache.commons.io.IOUtils;
import java.io.*;
import java.net.URI;
import org.apache.hadoop.fs.*;
import org.apache.hadoop.conf.*;
import org.apache.hadoop.io.*;

public class ReaderHDFS {
    public static void main(String[] args) throws IOException {

        String uri = args[0];

        Configuration conf = new Configuration();
        FileSystem fs = FileSystem.get(URI.create(uri), conf);
        FSDataInputStream in = null ;

        try
        {
            in = fs.open(new Path(uri));
            IOUtils.copyBytes(in, System.out, 4096, false);
        }
        finally
        {
            IOUtils.closeStream(in);
        }
    }
}


text:
Q: Firebase Cloud Messaging registration token - Flutter and Django I am trying to send push notifications (iOS, Android, Web) to specific users when certain events happen in my app.
I am using the firebase_admin python plugin with Django, working properly for authentication and verifying jwt, but it is giving me this error when trying to send a Message/Notification from Django:
firebase_admin.exceptions.InvalidArgumentError: The registration token is not a valid FCM registration token

I am getting the token directly from my Flutter instance and sending it in the request body from Flutter to Django.
My method for getting the token from Flutter:
await FirebaseMessaging.instance.getToken().then((token) async {
    fcm_token = token!;
  }).catchError((e) {
    print(e);
  });

My python code that sends notification:
registration_token = self.context['request'].data["token"],

        # See documentation on defining a message payload.
        message = Message(
            notification=Notification(
                title='New Product Added',
                body='A new product called ' + validated_data['name'] + ' has been added to your account.',
            ),
            token=str(registration_token)
        )

        # Send a message to the device corresponding to the provided
        # registration token.
        response = send(message)

I have verified that the token being passed to Django is correct, by comparing it to what I am getting from Flutter

A: The problem was that registration_token was a tuple generated by Django, I just indexed into the first item in the tuple and the FCM error went away.


text:
Q: Asymptotics in differential equations While learning about Bessel functions I've came up with the following argument:

Since the Bessel equation is $$y''+\frac{1}{x} y'+ \left(1-\frac{\alpha^2}{x^2} \right) y=0, $$
  one might expect that in the limit $x \to \infty$ we have $y''+y \approx 0$, which is the equation modelling simple harmonic motion (aka linear combinations of sines and cosines) of period $2 \pi$. Thus, we should have $y \approx C_1 \cos x+ C_2 \sin x$ for large $x$.

I'm aware that there is a branch of mathematics, called asymptotics (?) that deals with such ideas. Nonetheless I have several questions:

*

*How can you know what terms are to be omitted as $x$ gets large? perhaps $y'$ grows faster than $\frac{1}{x}$ decays (so that the middle term cannot be omitted).

*Looking at the graph of the Bessel function $J_0(x)$ one can see that the amplitude of the oscillation decays. Is there a way to predict that, and know the rate at which $C_1,C_2$ decay?

*In general, is there a rigorous statement of the form: If $y' \approx G(x,y)$ is an approximation of the differential equation $y'=F(x,y)$ at the point $x_0$, with a solution $y=\varphi$, then the original equation has a solution $y$ which is $\approx \varphi$ near $x_0$? Hopefully with a precise notion of what "$\approx$" means.
Thank you!

A: I do not know how much this will help you; so, please, forgive me if I am off-topic.
The solution of the differential equation $$y''+\frac{1}{x} y'+ \left(1-\frac{\alpha^2}{x^2} \right) y=0$$ is given by $$y=c_1 J_{\alpha }(x)+c_2 Y_{\alpha }(x)$$ where appears the Bessel functions of the first and second kinds.
Considering the case where $x$ is large, the following first order approximations are available $$J_{\alpha }(x)\approx \sqrt{\frac{2}{\pi x }}  \cos \left(\frac{\pi  \alpha
   }{2}+\frac{\pi }{4}-x\right)$$ $$Y_{\alpha }(x)\approx -\sqrt{\frac{2}{\pi x }}  \sin \left(\frac{\pi  a}{2}+\frac{\pi
   }{4}-x\right)$$
Have a look here and here for more details about Hankel's expansions.


text:
Q: How do I change the bad action I selected as default on USB stick insertion? I inserted my smartphone in my laptop with a usb cable, and I wrongly checked the "Set this action as default" (or "Remember this action", I don't remember the exact sentence) after I selected a bad action (Open folder) because it is the system partition of the smartphone. I do I revert this action so that ubuntu ask me again what to do and I can instruct him to always do nothing?
I just want to auto open the data partition.
Thank you very much.

A: You didn't mention what version of Ubuntu you are using.
See if the system menu/indicator (button in the top-right corner) has an About this computer item (or something like that).
If yes, press it. That's where you can do what you are asking.
If not, then you'll have to search in the System Preferences for those option (I don't remember where they were in older Ubuntu versions).


text:
Q: Defining function signature in GHCi Defining a function signature in Haskell's interpreter GHCi doesn't work. Copying an example from this page:
Prelude> square :: Int -> Int

<interactive>:60:1: error:
    • No instance for (Show (Int -> Int)) arising from a use of 'print'
        (maybe you haven't applied a function to enough arguments?)
    • In a stmt of an interactive GHCi command: print it
Prelude> square x = x * x

How can I declare a function signature and then give function definition in Haskell interactively? also: why can't I simply evaluate the function and see its type (e.g. Prelude> square) once it has been defined?

A: You can define a function signature in the ghc interactive shell. The problem however is that you need to define functions in a single command.
You can use a semicolon (;) to split between two parts:
Prelude> square :: Int -> Int; square x = x * x
Note that the same holds for a function with multiple clauses. If you write:
Prelude> is_empty [] = True
Prelude> is_empty (_:_) = False

You have actually overwritten the previous is_empty function with the second statement. If we then query with an empty list, we get:
Prelude> is_empty []
*** Exception: <interactive>:4:1-22: Non-exhaustive patterns in function is_empty

So ghci took the last definition as a single clause function definition.
Again you have to write it like:
Prelude> is_empty[] = True; is_empty (_:_) = False

A: Multi-line input needs to be wrapped in the :{ and :} commands.
λ> :{
 > square :: Int -> Int
 > square x = x * x
 > :}
square :: Int -> Int

A: Here are three ways:
>>> square :: Int -> Int; square = (^2)
>>> let square :: Int -> Int
...     square = (^2)
...
>>> :{
... square :: Int -> Int
... square = (^2)
... :}

The second one requires you to :set +m; I include this in my ~/.ghci so that it is always on.


text:
Q: After cancelling the file uploading,shows the name? I want to remove the file name,if cancel button is clicked.
my code is :

Download CSV

      <md-button class="md-raised" ng-click="showBulkEntries()">
        Browse
      </md-button>
      <input type = "file" id="file-upload-input-{{themeObj.name}}" file-model = "mcqEditCtrl.fileUploadObj['{{themeObj.name}}'].csvUploadFile" ng-hide="inputHide=true" ngf-pattern="'*.csv'" accept="application/csv" multiple/>
      {{mcqEditCtrl.fileUploadObj[themeObj.name].csvUploadFile.name}}
      <md-button flex-offset="5" class="md-hue-3 md-raised" ng-click="mcqEditCtrl.uploadFile(themeObj)">Preview/Upload</md-button>


text:
Q: unable to pull/push to remote repo on github from mac terminal I clone existing github repo to my local from mac terminal and I pulled a few times without a problem. I modified some of the code then add . and commit and now I cannot pull or push without getting "Permission denied (publickey)." I have tried using both ssh and https and there is a ton of information on how to resolve this but nothing seems to work for me and it is driving me crazy.
When I enter ssh -vT git@github.com
I get:
debug1: Reading configuration data /etc/ssh/ssh_config
debug1: /etc/ssh/ssh_config line 21: Applying options for *
debug1: Connecting to github.com [....ip....] port 22.
debug1: Connection established.
debug1: identity file /Users/macbookpro/.ssh/id_rsa type 1
debug1: key_load_public: No such file or directory

My id_rsa is actually in path:
/Users/macbookpro/Documents/pub_key/id_rsa

If this is the problem how do I update the path?
Shouldn't I be able to just type git pull since I cloned the repo?

A: Move the ssh keys to the ~/.ssh folder
Another option is to create .ssh/config file with the following:
Host name github.com
   HostName github.com
   IdentityFile /Users/macbookpro/Documents/pub_key/id_rsa
   User <username>

Or simply add the key to ssh-agent:
ssh-add /Users/macbookpro/Documents/pub_key/id_rsa
eval $(ssh-agent)


text:
Q: Adjusting fitted line increment by stat_smooth of ggplot2? I am using the loess method of stat_smooth of ggplot2 to fit my data. The X increment of my original data is 1 year. However, the fitted line by loess of stat_smooth gives me X' increment of 0.522. I am wondering is there a way to adjust the increments of the fitted line returned from stat_smooth? Basically, to keep the X increment as its original length. Thanks so much!
print(ggplot(orig_data, aes(Year,Value, col=County)) + geom_point(na.rm = T) +
    stat_smooth(alpha=.2,size=1,se=F,method="loess",formula = y~x, span = 0.5,
      aes(outfit=fit<<-..y..,outx=fit_x<<-..x..)) + theme(legend.position="none"))

enter image description here

A: To fit a loess smooth to different segments of data, we need to split up the data. Using the built-in mtcars as an example, fitting a loess line smoothing mpg in terms of wt with a separate smooth for each cyl value, we can do this:
# split the data
data_list = split(mtcars, f = mtcars$cyl)
# fit loess to each piece
mods = lapply(X = data_list, FUN = function(dat) loess(mpg ~ wt, data = dat))
# predict on each piece (the default predictions will be only
# at the data points)
predictions = lapply(mods, predict)

# combine things back together
library(dplyr)
result = bind_rows(data_list)
result$pred = unlist(predictions)

Demonstrating the results in a plot:
ggplot(result, aes(x = wt, y = mpg, color = factor(cyl))) +
    geom_point() +
    geom_point(aes(y = pred), shape = 1) +
    geom_line(aes(y = pred))

I used dplyr only for the nice bind_rows function, but this whole process could be done with a dplyr::group_by and dplyr::do instead of splitting the data. I'd encourage you to read more about dplyr if you're interested in that.


text:
Q: Getting Xcode 5 variable inspector to show custom summary and/or synthetic children I have some C++ classes from a library which have opaque data types. Xcode doesn't understand them and so can't show them in the variable inspector. I've written Python scripts for lldb which can decompose these opaque types correctly and return synthetic children. I have a Python class OpaqVector_syntheticChildren which implements get_child_at_index(), num_children() and so on.
For example, at the lldb prompt when the program is paused at a breakpoint in Xcode:
    (lldb) frame variable sarr
    (OpaqueVector) sarr = {
      [0] = 1
      [1] = 2
      [2] = 3
    }
However, in the variable inspector, sarr shows the pink 'S' to show it's a structure and has no summary nor expansion arrow. I can right-click and choose 'Print description of "sarr"' and get the correct (matching above) output in the lldb console. Is there some extra trick to get Xcode itself show the structure's synthetic children?

A: Xcode calls the has_children() method of the class you provide to generate the synthetic children. If that function does not return True, it won't call num_children() or get_child_at_index(), whereas the lldb command prompt doesn't seem to do that check. Hence, if you have a bug in that function you'll get the behaviour I described in the question.


text:
Q: Convert c++ vector to char ** without memory leak I'm trying to convert a vector of string to a char ** to pass into another method that makes a hostent struct. I have been trying to figure this out, but don't know what to do. Here's what I am doing
#include <stdlib.h>
#include <sys/types.h>
#include <string.h>
#include <stdio.h>
#include <iostream>
#include <fstream>
#include <netdb.h>
#include <vector>
#include <algorithm>
#include <iterator>

using namespace std;

static struct hostent host;

#define INADDRSZ 4
#define _UNCONST(a) ((void *)(unsigned long)(const void *)(a))

void tokenize(string const &str, const char delim, vector<std::string> &out) {
    size_t start;
    size_t end = 0;

    while ((start = str.find_first_not_of(delim, end)) != std::string::npos){
        end = str.find(delim, start);
        out.push_back(str.substr(start, end - start));
    }
}

static struct hostent * mk_hostent (const char *name, char **aliases, char **haddress, int addrsz, int af) {
    host.h_name = const_cast<char*> (name);
    host.h_addr_list = haddress;
    host.h_aliases = aliases;
    //host.h_addr_list[index] = (char *)_UNCONST(&host_addr[index]);
    host.h_length = addrsz;
    host.h_addrtype = af;
    //host.h_aliases = _UNCONST(aliases);
    return (&host);
}

void getHostAddrList (string hostname, vector<string> ipsAndHost, vector<string> &addrs) {
    cout << "I reached here" << "\n";
    vector<string> tokens;
    for (int i = 0; i < ipsAndHost.size(); i++) {
        tokenize(ipsAndHost[i], ' ', tokens);
        // comparing if hostname same then pushing ip to host addrs list
        if (hostname.compare(tokens[1]) == 0) {
            addrs.push_back(tokens[0]);
        }
        tokens.clear();
    }
}

void getAliasList (string hostip, vector<string> ipsAndHost, vector<string> &aliases) {
    vector<string> tokens;
    for (int i = 0; i < ipsAndHost.size(); i++) {
        tokenize(ipsAndHost[i], ' ', tokens);
        // comparing if host ip same then pushing host alias to aliases list
        if (hostip.compare(tokens[0]) == 0) {
            aliases.push_back(tokens[1]);
        }
        tokens.clear();
    }
}

char ** vector2string (vector<string> &input) {
    char ** arr = new char*[input.size()];
    for(size_t i = 0; i < input.size(); i++){
        arr[i] = new char[input[i].size() + 1];
        strcpy(arr[i], input[i].c_str());
    }
    return arr;
}

static struct hostent * gethostbyaddr_iri (const char *addr, int af) {
//void printLines(const char * addr){
    fstream file("sampleFile");
    string line;
    vector<string> readLines;

    while (getline(file, line)) {
        // skipping empty line
            if (line.empty()) {
                continue;
            }
        // skipping comments
        if (line[0] == '#') {
            continue;
        }

        readLines.push_back(line);

    }

    vector<string> ips;
    vector<string> hostAddresses;
    vector<string> hostAliases;

    for (int i = 0; i < readLines.size(); i++) {
        tokenize(readLines[i], ' ', ips);
        //ips[0] will have ip address to compare
        if (strcmp(ips[0].c_str(), addr) == 0) {
            cout << "one was same" << "\n";
            getHostAddrList(ips[1], readLines, hostAddresses);
            getAliasList(ips[0], readLines, hostAliases);
            //return mk_hostent(ips[1],
        }
        // clearing vector for next loop
        ips.clear();

        char ** hAddr = vector2string(hostAddresses);
        char ** hAlias = vector2string(hostAliases);

        return mk_hostent(ips[1].c_str(), hAlias, hAddr, INADDRSZ, AF_INET);
    }

}

int main() {
    gethostbyaddr_iri("128.0.0.16", 2);
}

So if you see I call the vector2string method to convert my vector string into char ** that I then pass to the mk_hostent method. The memory is never being freed and I need a way to convert my vectors to char ** without causing this memory leak

A: All you need is an array of char* to hold the addresses of the various strings. To avoid memory leaks you can use std::vector<char*> to point into your vector of strings like this:
std::vector<char*> vector2string (std::vector<string>& input) {

    std::vector<char*> arr;

    for(auto& s: input)
        arr.push_back(&s[0]); // add the address of each string array

    return arr;
}

And use it like this:
std::vector<char*> hAddr = vector2string(hostAddresses);
std::vector<char*> hAlias = vector2string(hostAliases);

hostent host = mk_hostent(ips[1].c_str(), hAlias.data(), hAddr.data(), INADDRSZ, AF_INET);

Be sure that hAddr and hAlias are unused after hostAddresses & hostAliases respectively are changed because they point into the live data. The same goes for the returned host object which has pointers to their data.


text:
Q: Domain of Orthogonality of Legendre Polynomials? In my Numerical Analysis Course, under the topic Theory of Orthogonal Polynomials We are following the book Numerical Analysis by Kendall E Atkinson.
The problem is the author keeps saying "The Legendre Polynomials are orthogonal in $(-1,1)$"
According to me a polynomial is defined everywhere and is Orthogonal With respect to a Inner-product which might have some integral and limit.
It makes no sense for me to talk about orthogonality in a Domain.
The course is combined for Physics and Mathematics students and I am a Mathematics Major.
Each Physics major believes the polynomial are orthogonal only in the domain.
for example Legendre polynomials are orthogonal in $(-1,1)$ only and you cant use them outside the $(-1,1)$ to study them or to find the coefficients using recursive relation outside $(-1,1)$ using Gaussian Elimination.
I want to know if there is meaning of Polynomials being orthogonal in a domain. If Yes, what does it mean?

A:
"The Legendre Polynomials are orthogonal in (-1,1)"

The Legendre Polynomials are orthogonal with respect to the inner product $\langle f,g\rangle=\int_\mathbb R w(x)f(x) g(x)\, dx$ for a certain weight function $w(x).$

A: The orthogonality of Legendre polynomials is typically defined with respect to the inner product
$$
\langle p,q\rangle = \int_{-1}^1 p(x)q(x)\,dx
$$
Thus, they are said to be orthogonal on $(-1,1)$.
Of course, through a linear change of variables you could define them to be orthogonal on any bounded interval $(a,b)$.

A: What it means is that they are orthogonal with respect to the "uniform" probability distribution on $(-1,1)$, i.e. the measure $m$ defined by
$$
m(A) = \begin{cases}
1 & \text{if } A = (-1,1), \\
0 & \text{if } A \text{ is disjoint from } (-1,1), \\
\cdots & \text{(see below for other sets.)}
\end{cases}
$$
The measure assigned by $m$ to intervals that are subsets of $(-1,1)$ is proportional to the length of the interval (and from the above you can see what the constant of proportionality is).

A: they are orthogonal with respect to the inner product in the interval [-1,1],


text:
Q: md5sum of /dev/sr1 different than ISO image? After writing an ISO image using Brasero, I discovered that the md5sum of the target DVD is different than the ISO image, despite no readability errors.
What has caused that difference?

A: When you do this kind of verification  , md5sum or sha1sum you must be sure that your reading the same amount of data .
stat --printf '%s\n'  file.iso

blockdev --getsize64 /dev/sr1

if the data does have the size , you must compute on the smallest size .
to do this :
dd if=file.iso bs=2k count=9000 | md5sum

dd if=/dev/sr1 bs=2k count=9000 | md5sum


text:
Q: Spring boot annotations @springbootapplication
Can I create more than one application class with @springbootApplicatio annotations in our project.
    Or a projects has Only one application class.

A: Take a look on what @SpringBootApplication does for your application. From that you can understand that this annotation is a shortcut to simplify the use of a few other annotations. Those other annotations are more flexible and allow you to configure more options than @SpringBootApplication.


text:
Q: Setting Windows Service's Status I'm trying to create a windows service that runs an exe that I have. I have been using this guide from msdn.
I run my exe as a Process that is started in OnStart and stopped in OnStop.
I want to know how the service status, the status sc query *name*, is updated.
I've tried following the status section, here, of the guide above, but calling
serviceStatus.dwCurrentState = ServiceState.SERVICE_STOPPED;
SetServiceStatus(this.ServiceHandle, ref serviceStatus);

and those type of functions from the guide don't seem to do anything.
I want to be able to set the status of the service to be stopped, if my exe that the service runs crashes or is killed.
One idea I have in mind is to have a separate function that is run in a thread from OnStart that will block using process.WaitForExit();. And after thread stops blocking, I wanted to use the functions above to set the service status as stopped.
Does anyone have any idea on why I can't set the service status, or how to link the service status to the exe that the service runs? Thanks

A: Do not set the service status. It sounds like you should stop your service when the exe crashes or is killed.
To stop the service, use ServiceBase.Stop()
https://msdn.microsoft.com/en-us/library/system.serviceprocess.servicebase.stop.aspx
This will change the service status to stopped.


text:
Q: JavaScript / case-insensitive I have this function to filter values in order to implement an auto-complete feature:
 store.filter(new Ext.util.Filter({
    filterFn: function (object) {
        var match = false;
        Ext.Object.each(object.data, function (property, value) {
        match = match || value.match(Ext.getCmp('search_input_text').getValue());

        });
        return match;
      }

I need it to be case-insensitive so that both upper and lower cases would be the same.
value.match(Ext.getCmp('search_input_text').getValue());

something like LIKE in sql. How can I do that ?

A: var a = "ABC"
a = a.toLowerCase();
//a == "abc"

Convert both values to lowercase, then compare them. If they're equal letters, regardless of capitalisation, it will return true:
Assuming your value is a String:
var input = Ext.getCmp('search_input_text').getValue();
match = value.toLowerCase().match(input.toLowerCase()) ? input : match;

This uses temporary variables to return the value with it's original capitalisation.

A: If you want a case-insensitive search, you can write
match = (match.toLowerCase().indexOf("search_input_text") >= 0) ? "search_input_text" : match;

A: *

*Regexp have a constructor using string arguments.

*if you need a boolean result don't use match, use test instead.
store.filter(new Ext.util.Filter({
    filterFn: function (object) {
        var match = false;
        Ext.Object.each(object.data, function (property, value) {
            var filterValue = Ext.getCmp('search_input_text').getValue();
            var r = new RegExp(filterValue, 'i');
            match = match || r.test(value);
        });
        return match;
    }
 ...
 }


text:
Q: How to validate decimal value I am working on SharePoint list validation. In column A, it should only allowed whole number/integer to be entered and any decimal should return an error.
I tried to set the number of decimal place to zero but it turn out the column will round it off when decimals value entered. This is not the desired validation, it should return error.

It is much appreciated if anyone can help me out with this.
Thank you.

A: You could add this to your column validation(change the number to your column name).
=number=ROUND(number,0)

Test result:

A: Try using below formula in column validation:
=IF([Number Column] = ROUND([Number Column], 0), true, false)

Note:

*

*Sometimes comma(,) does not work in formula (I am not sure but it is based on something language or regional settings on your site). So in that case use semicolon(;) instead of comma(,).

*Replace [Number Column] in formula by display name of your column.


text:
Q: How to access elements with specific class as soon as document has loaded I have several occurrences of the following html:
<label class="control-label translate">Color </label>

I want to grab the text of each label with the class translate as soon as the document has loaded and put together the following jQuery to test how to do that.
$(document).ready(function () {

$(".translate").each(function(index,item) {
    alert("text: " + $(item).text());
})
});

Doesn't look like the function is being executed because I don;t see any alert messages.  There are no errors in the js console.
What did I miss?

A: Your code works fine, but I think you forgot to include jQuery.  Just add this to the beginning of the HTML page.  I suspect this is the case if you're getting no feed back. You can also see if $ is defined in console.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

$(document).ready(function () {
  $(".translate").each(function(index,item) {
      alert("text: " + $(item).text());
  })
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label class="control-label translate">Color </label>

A: Sorry guys, stupid mistake on my part which I just noticed.  All working fine now.
Pete


text:
Q: How to apply filter on table contents in react

import React, { Component } from 'react';

import {Doughnut} from "react-chartjs-2"

import {bindActionCreators} from "redux";
import {connect} from 'react-redux';

import {fetchBeacons} from '../actions/';

const DummyDoughnutData = {
  labels: ['beacon 1 - zone a', 'beacon 2 - zone c', 'beacon 3 - zone a', 'beacon 4 - zone b', 'beacon 5 - zone b'],
  datasets: [
    {
      borderColor: 'rgba(255,255,255,.55)',
      data: [ 30, 9, 17, 22, 11],
      backgroundColor: [
  '#063e70',
  '#107bb5',
  '#1A1C1D',
  '#666666',
  '#2F4F4F'

  ]
    }
  ],
};

// const beacons=[
//         {zone:"zone a", status: "active", _id:1},
//         {zone:"zone c", status: "active", _id:2},
//         {zone:"zone a", status: "active", _id:3},
//         {zone:"zone b", status: "active", _id:4},
//         {zone:"zone b", status: "active", _id:5},
//         {zone:"zone b", status: "active", _id:6},
//         {zone:"zone c", status: "active", _id:7}
// ];

// class BeaconZoneRow extends Component {
//     render() {
//         return (
//

//
//                     {this.props.zone}
//
//

//         )

//     }

// }

class BeaconRow extends Component {
    render() {
        return (

                 {this.props.beacon.name}
                {JSON.stringify(this.props.beacon.status)}
                 {this.props.beacon.zone.name}

        )
    }
}

class BeaconList extends Component {

    // Sort = (prop) => { return (a,b) => a[prop].localeCompare(b[prop])};

    render() {
        const rows = [];

        this.props.beacons.map( beacon => {
            return rows.push(<BeaconRow beacon={beacon} key={beacon._id}/>)
        });

        return (

                            Name
                            Status
                            Zone

                        {rows}

        )

    }
}

class BeaconDoughnutAnalysis extends Component {
    render() {
        return (

                <Doughnut data={DummyDoughnutData} />

                visits

        )
    }
}

class BeaconListComponent extends Component {
  constructor(props) {
    super(props);
    this.handleSubmit = this.handleSubmit.bind(this)
  }

  handleSubmit(){
    this.props.router.push('/new-beacon');
  }

  componentWillMount = () => {
        this.props.fetchBeacons();
    };

    render() {
        return (

                        <button className="btn btn-sm btn-info" onClick={this.handleSubmit}> Add Beacon</button>

                { this.props.beacons && this.props.beacons.length > 0 ?

                        <BeaconList beacons={this.props.beacons}/>
                        <BeaconDoughnutAnalysis/>

 :

...Loading

                }

        )
    }
}

function mapStateToProps(state) {
    return {
        beacons: state.beacons
    }
}

function matchDispatchToProps(dispatch){
    return bindActionCreators({fetchBeacons: fetchBeacons}, dispatch);
}

export default connect(mapStateToProps, matchDispatchToProps)(BeaconListComponent);

i had fetched data from the server and i wanted to know how to filter that data in the table using react redux
the code is shown above using which table is being displayed and i wanted to filter its contents

A: Assuming you are providing the zone as a prop to the BeaconList component you just need to provide a check while mapping like below
class BeaconList extends Component {

    // Sort = (prop) => { return (a,b) => a[prop].localeCompare(b[prop])};

    render() {
        const rows = [];
        //Assuming you are filtering based on zone and you are giving the zone you want to filter as a prop zone

        this.props.beacons.map( beacon => {
            if(beacon.zone === this.props.zone) {
              return rows.push(<BeaconRow beacon={beacon} key={beacon._id}/>)
            }
        });

        return (

                            Name
                            Status
                            Zone

                        {rows}

        )

    }
}

I hope this helps


text:
Q: Share data between "request scope" and HttpMessageHandler without HttpContext I am using IHttpClientFactory and want to share ("request-")scoped data with a custom HttpMessageHandler.
As MessageHandlers maintain their own lifecycle (they are shared across HttpClients and expire after 2mins, and especially run in their own DI scope, see this blogpost here), I cannot use a scoped service to share data.
The usual workaround is to use HttpContext and either store data in the Items property or access the IServiceProvider of the request scope via HttpContext.RequestServices property.
In my case this is not working as I am working with a framework build by a colleague which lets you work with ServiceBus events just like you are used to work with REST calls in .NET core: It will create scopes and execute workers for incoming requests, you get an EventContext etc...
But: There is no resemblance of IHttpContextAccessor...
That means I cannot rely on something like HttpContext in my custom HttpMessageHandler for pulling event scoped data...
The concrete use case here is:
A inbound correlation id from a service bus event should be transparently attached to outbound HttpClient calls as a header...


text:
Q: Delete one marker in googlemap api v3 When I search for a location with the zip code, I center the googlemap with with the zip code and I add a marker. When I do a new search I would delete the old marker.
     $('body').on('blur', '#CodePostalA', function(){

        var zipcode = $('#CodePostalA').val();
        var $this = $(this);
        var geocoder = new google.maps.Geocoder;

            geocoder.geocode({'address': zipcode}, function(results, status) {
                if (status == google.maps.GeocoderStatus.OK) {
                    map.setCenter(results[0].geometry.location);
                    map.setZoom(20);

                }

                if ($('#adresse').length > 0) {
                    newMarker = new google.maps.Marker({
                        position: results[0].geometry.location,
                        map: map,
                        icon: new google.maps.MarkerImage(
                            'images/marker-new.png',
                            null,
                            null,
                            null,
                            new google.maps.Size(36, 36)
                        ),
                        draggable: true,

                        animation: google.maps.Animation.DROP,
                    });

                    google.maps.event.addListener(newMarker, "mouseup", function(event) {
                        var latitude = this.position.lat();
                        var longitude = this.position.lng();

                        geocoder.geocode({'location': this.position}, function(results, status) {
                            if (status === google.maps.GeocoderStatus.OK) {
                                if (results[1]) {
                                    $('#adresse').val(results[0].formatted_address);
                                } else {
                                    console.log('Aucun résulat trouvé');
                                }
                            } else {
                                console.log('Echec géolocation: ' + status);
                            }
                        });
                    });

                }

            });

    });

    addMarkers(props, map);
}, 300);

A: Keep track of your marker with a variable, and when it is time to delete it, remove it from the map with marker.setMap(null).
Once all references have been removed the old marker object will be garbage collected behind the scenes.
You could also consider reusing the marker object rather than making a new one every time.


text:
Q: moving a mysql slave to a new host : Failed to open the relay log I have a master-master setup which I want to move to a new pair of servers (from linux to opensolaris).
linux boxes names are shard1-1 and shard1-2, and osol boxes names are shard1-1-osol and shard1-2-osol.
this is what I did:
 1. took down mysql server on both linux boxes, copied the data to the osol boxes.
 2. edited master.info on each of the osol boxes, changed master from shard1-1 to shard1-1-osol and vice versa on both machines.
when I started mysql on the first osol machine, I see this in the error log:
looks like mysql does not like the host name change, and it's bitching about it.
the mysqld-relay-bin.000707 file exists in the datadir, so it's not clear what mysql is whining about.
090902  2:26:03  InnoDB: Started; log sequence number 246 3528553673
090902  2:26:03 [Warning] Neither --relay-log nor --relay-log-index were used; so replication may break when this MySQL server acts as a slave and has his hostname changed!! Please use '--relay-log=shard1-1-osol-relay-bin' to avoid this problem.
090902  2:26:03 [ERROR] Failed to open the relay log './mysqld-relay-bin.000707' (relay_log_pos 19653396)
090902  2:26:03 [ERROR] Could not find target log during relay log initialization
090902  2:26:03 [ERROR] Failed to initialize the master info structure

A: The server can't find the relay logs because they are named based in part upon the host name.  You are going to have ALL KINDS of problems trying to bring the slave up using that technique.  I suggest reinitializing the slave from the new master.  Just drop all the databases on the slave, take a dump from the master using mysqldump, import it onto the slave and then use CHANGE MASTER TO in order to set up replication from the new master.  It is WAY easier then trying to troubleshoot all the problems you are going to run into.

A: I have to disagree to an extent. You can rename the log files and update the relay-log.info,  relevant .index file and/or set 'log-bin' set in my.cnf to make it work.

A: A useful guide to a problem which has similar effects to yours is Watch out for hostname changes when using replication!, by Trent from Sun/MySQL.

A: If it is just complaining about the relay logs, in most cases, they are disposable if the master still has the binary logs around.  You can just run CHANGE MASTER TO on the slave  and it will flush the existing relay logs and start anew.  You don't need to make a new fresh copy.


text:
Q: swift - cocoa class handling I'm new in swift-ios. I'm studying this
when I'm trying to create cocoa file,

import cocoa

is giving error.
I've searched in google and found cocoa class not work in ios-swift. it works in osx.
So I'm not getting what'll I do now. Any help appreciated.

A: Cocoa is a framework for macOS. However, CocoaTouch is an umbrella module for iOS. To import the main module dependency for an iOS app, you use
import Foundation

And to import the main UI module for an iOS app, you use
import UIKit

A: The term "Cocoa" has been used to refer generically to any class or object that is based on the Objective-C runtime and inherits from the root class, NSObject.


text:
Q: how can i read @Pathvariable name and value using HandlerInterceptor in spring? My code is :
@RequestMapping(value = "productDescription/{productId}/{competitorList}", method = RequestMethod.GET)
@ResponseBody
public ProductDescription getProductDescription(
        @PathVariable String productId, @PathVariable String competitorList) {
    return service.getProductDescription(productId, competitorList);
}

Using HttpServletRequest request in postHandler method, I want to read the pathvariable names and values.
I am able to get parameter name and values using request.getParameterMap() method if I'm using @RequestParam instead @Pathvariable.

A: Try this:
@RequestMapping(value = "productDescription/{productId}/{competitorList}", method = RequestMethod.GET)
@ResponseBody
public ProductDescription getProductDescription(@PathVariable("productId") String productId, @PathVariable("competitorList") String competitorList) {
    return service.getProductDescription(productId, competitorList);
}


text:
Q: Reason for unwanted implicit reference to dll in c# project build I have a solution with quite a few projects in it and several dependencies to external DLLs. While trying to build a x64 version of the solution, I found that when building one project several libraries are copied into the output directory which are not mentioned in the project's references or anywhere else within the solution. I figured out that there is a collection of file names called _CopyFilesMarkedCopyLocal, which contains these DLLs. In the concrete case the copied library was used indeed, but it is a x86 library, which overwrites the existing x64 file in the output folder. How does a DLL, which is not mentioned in any project of the solution, become part of this collection? Can some referenced DLL induce further implicit references? Can I control this behavior?
Update: In the x86 build the set of file names contained in _CopyFilesMarkedCopyLocal is what I expected, namely one reference explicitly mentioned.


text:
Q: calculate percentages of levels - add column name This code:
tips <- data.frame(
        gender = c("female", "male", "male")
        ,smoker = c("yes", "no", "no")
     )

tblFun <- function(x) {
    tbl <- table(x)
    res <- cbind(tbl, round(prop.table(tbl) * 100, 2))
    colnames(res) <- c('Count', 'Percentage')
    res
}

do.call(rbind, lapply(tips[1:2], tblFun))

produces this:
       Count Percentage
female     1      33.33
male       2      66.67
no         2      66.67
yes        1      33.33

which is great. However, I would like to produce this:
key_value_pair       Count Percentage
gender=female     1      33.33
gender=male       2      66.67
smoker=no         2      66.67
smoker=yes        1      33.33

Could someone please be so kind and suggest a solution? Thanks!

A: I would use the tidyverse and some data manipulation:
library(tidyverse)

tips %>%
    gather(key_value, value) %>% # wide to long
    count(key_value, value) %>%
    group_by(key_value) %>%
    mutate(percentage = n / sum(n)) %>%
    unite(key_value_pair, key_value, value, sep = "=") # convert 2 cols into 1

#   key_value_pair     n percentage
#   <chr>          <int>      <dbl>
# 1 gender=female      1      0.333
# 2 gender=male        2      0.667
# 3 smoker=no          2      0.667
# 4 smoker=yes         1      0.333

A: One way is to expand your tblFun function to accept the category name and prepend it to the labels.
tblFun <- function(x, nm = character(0)) {
  tbl <- table(x)
  if (length(nm)) names(tbl) <- paste(nm[[1]], names(tbl), sep = "=")
  res <- cbind(tbl, round(prop.table(tbl) * 100, 2))
  colnames(res) <- c('Count', 'Percentage')
  res
}

Given no change, it behaves as before:
do.call(rbind, lapply(tips[1:2], tblFun))
#        Count Percentage
# female     1      33.33
# male       2      66.67
# no         2      66.67
# yes        1      33.33

In order to pass each column's name with each column, you need to use the multi-argument version of lapply, Map:
do.call(rbind, Map(tblFun, tips[1:2], names(tips[1:2])))
#               Count Percentage
# gender=female     1      33.33
# gender=male       2      66.67
# smoker=no         2      66.67
# smoker=yes        1      33.33

An alternative is to use purrr::imap, which passes both the object and its name (as a second argument) to the function:
do.call(rbind, purrr::imap(tips[1:2], tblFun))
#               Count Percentage
# gender=female     1      33.33
# gender=male       2      66.67
# smoker=no         2      66.67
# smoker=yes        1      33.33

One advantage I see is no need to include both tips[1:2] and names(tips[1:2]), though if you aren't already using purrr or tidyverse-packages, then adding another package just for this might not be desired (esp when Map does the same thing with the explicit names()).

As a brief demonstration of what Map is doing: it "zips" arguments together.
As a comparison, lapply (and family) run a function once for each element of its input vector/list. So lapply(1:3, myfunc) "unrolls" to
list(
  myfunc(1),
  myfunc(2),
  myfunc(3)
)

If you try to provide multiple vectors, however, it does not perform as one "might" want/think: lapply(1:3, myfunc, 11:13) unrolls to:
list(
  myfunc(1, 11:13),
  myfunc(2, 11:13),
  myfunc(3, 11:13)
)

Map does it for an arbitrary number of vectors/lists, so Map(myfunc, 1:3, 11:13, 21:23, 99) unrolls to
list(
  myfunc(1, 11, 21, 99),
  myfunc(2, 12, 22, 99),
  myfunc(3, 13, 23, 99)
)

(Notice how length-one vectors are recycled. Though it does do recycling of lengths between 1 and the length of the longest vector, I don't recommend relying on it unless you strictly control the fact that the shorter vectors should multiply out to the length of the longest with no remainder.)
myfunc in this case must accept (at least) three arguments. Two notable differences between lapply and Map:

*

*lapply puts data-first, function-second; because Map accepts one or more vectors/lists, it puts the function-first, one-or-more data second+;

*Map will recycle a singular list argument, so Map(myfunc, 1:3, list(11:13) unrolls to list(myfunc(1, 11:13), myfunc(2, 11:13), myfunc(3, 11:13)), which on the surface looks very similar to lapply(1:3, myfunc, 11:13) but can be handy when you have more than two vectors of inputs.

*Because it doesn't care how many vectors/lists, one can send arbitrary/unknown lengths of vectors/lists to Map with do.call, as in

l <- list(1:3, 11:13, 21:21)
do.call("Map", c(f = myfunc, l))

(as long as myfunc accepts arbitrary number of arguments, likely via ... mechanics). The first and only named argument of Map is f= for the function; it isn't required to name it here, but I like to for clarity.

*Just like lapply has the optionally-simplifying version sapply, Map has the optionally-simplifying version mapply. I tend to prefer explicit -- there's nothing more frustrating than expecting vector output but one input causes the output to be a list ...


text:
Q: angular customized validation - input parameter unchanged There are two date inputs: d1 and d2.
The requirement is d2 must be greater than or equal to d1.
By default, the minimum date of d2 is 2018-09-03, which is stored in the minDate variable.
[A good case] If user inputs d1 first,
it will trigger the function onChange and update minDate to the value of d1. In this case, if user wants to update d2, all dates before minDate are disabled.
[A bad case] If user inputs d2 first,
and input d1 later with d1 > d2, I want the program to display an error msg by using the validation function settledateValidator.
However, minDate passed to settledateValidator is not updated (still equals to its default value 2018-09-03 instead of the value of d1).
My questions:
1. why minDate does not get updated in [A bad case]? It is updated successfully in [A good case].
2. how to fix [A bad case]?
Thanks for your help in advance!
in .html:
<mat-form-field>
    <input matInput [matDatepicker]="picker_d1" placeholder="d1" [formControl]="d1" (dateChange)="onChange(d1)">
    <mat-datepicker-toggle matSuffix [for]="picker_d1"></mat-datepicker-toggle>
    <mat-datepicker #picker_d1 ></mat-datepicker>
</mat-form-field>

<mat-form-field>
    <input matInput [min]="minDate" [matDatepicker]="picker_d2" placeholder="d2" [formControl]="d2">
    <mat-datepicker-toggle matSuffix [for]="picker_d2" ></mat-datepicker-toggle>
    <mat-datepicker #picker_d2 > </mat-datepicker>
    <mat-hint *ngIf="!myform_fg.controls['d2'].valid"> d2 is smaller than d1 </mat-hint>
</mat-form-field>

in .ts:
function settledateValidator(min: Date): ValidatorFn {
  return (control: AbstractControl): { [key: string]: boolean } => {

    var sd = new Date(control.value);

    console.log(min);  //minDate does not change. it is still equal to its default value.

    if (sd < min){
      return {invalid_toosmall: true};
    }
  };
}

export class MyformComponent implements OnInit {

  minDate = new Date(2018, 8, 3);

  constructor(fb: FormBuilder) {

    this.myform_fg = fb.group({
      'd1': ['', Validators.compose([Validators.required])],
      'd2': ['', Validators.compose([Validators.required, settledateValidator(this.minDate)])],
    });

    this.d1 = this.myform_fg.controls['d1'];
    this.d2 = this.myform_fg.controls['d2'];

  }

  onChange(value: string): void {
    this.minDate = this.d1.value;
  }

}

A: You validators in initialize in the constructor and you give the "this.minDate". When this one change you change is reference but the validator to still have the old one.
I faced the case and a way to do what you want to do would be to give the reference to an object which never change like this to your validator :
//global
const minDateValid = { date : new Date(2018, 8, 3)};

//constructor
settledateValidator(minDateValid);

//on change
this.minDateValid.date = this.d1.value;

For more exemple, I personnaly do it by passing the formControl for exemple : (see minDateFromControl)
https://github.com/xrobert35/asi-ngtools/blob/master/src/validators/asi-validators.ts
and make it work like this :
    this.myForm = fb.group({
      from: [null],
      to: [null]
    });

    this.myForm.controls.from.setValidators([Validators.required,
    AsiValidators.maxDateFromControl(this.myForm.controls.to)]);
    this.myForm.controls.to.setValidators([Validators.required,
    AsiValidators.minDateFromControl(this.myForm.controls.from)]);


text:
Q: ACTUALIZAR ELEMENTOS DE UN MAP POR SEPARADO tengo un filtro por años en una pagina.
La informacion que debe contener este filtro se la paso mediante props en el elemento padre:
{emisionYear === undefined ? " cargando..." :
                      emisionYear.map((v, i) => {
                        return (

                          <FilterYear key={i} year={v}
                          />
                        )
                      }
                      )

                    }

Lo recibo por props y pinto tantos Li como resultados recibo. En este caso dos botones
export default function FilterYear(props) {
// const years = (props.emisionYear)
// console.log(props.year)

 const year = props.year

const [colorClick, setColorClick] = useState('gray')
const [yearClick, setyearClick] = useState('')

  const handleChangeYear = e =>{
    setyearClick(year)
    setColorClick('purple')
  }
   console.log(yearClick)
return (

                    <button onClick={handleChangeYear} className='inline-flex items-center justify-center text-sm font-medium leading-5 rounded-full px-3 py-1 border border-transparent shadow-sm bg-indigo-500 text-white duration-150 ease-in-out'
                     style={{backgroundColor:`${colorClick}`}}
                    >
                        {year}
                        </button>

)

}
Visualmente tengo  estos dos botones. cuando pulso uno de ellos en el console.log si me cambia de 2021 a 2022, pero solo la primera vez , al igual que el color

Necesitaria que el valor, en este caso es yearClick, que actualizo con setyearClick cambiara cuando le doy uno u otro boton y que el color tambien variara en funcion del boton pulsado.
gracias!


text:
Q: Convert Event StartDateTime and EndDateTime from GMT to the local timezone This is the query I'm making:
 public List<event> evtList{get;set;}

  evtList = [select Id, subject, Who.Name, Location, StartDateTime, EndDateTime from Event where ActivityDate = TODAY and OwnerId =: UserInfo.getUserId() order by StartDateTime];

However when I call {!evt.StartDateTime} in the VF page the time is always in GMT for all of the events. Can I convert this to the local timezone?

A: If you just want to display in the current user's time zone, just use inputfield or outputfield for the DateTime fields. These tags should display the local time zone equivalent of the raw GMT Datetime.
If you need to be able to choose which Time Zone to display in rather than just using the current user's, you can use the Apex TimeZone Class to determine the time zone offset for a particular time zone. This becomes a little complicated, but I could add some detail here if that sounds useful.

A: there is format function which will convert datetime from GMT to current logged in  user's time zone.
here is the code.
date_time.format(); //return the full date/time in user's locale and time zone
u can also use the following to get datetime in any timezone..
   public DateTime date_time { get; set; } // var to hold datetime
   public String defined_format { get; set;}  // define if u want in any
  //specific format

    Public String getFormattedDatetime()
       {
   if (date_time == null)
     {
      return '';
      }
    else {

        if (defined_format == null) {
           return date_time.format(); //return the full date/time in user's locale and time zone
        }
      else
         {
         return date_time.format(defined_format,'IST');  //Specify Time zone like IST,CST
        }
    }

    }

You can replace date_time variable with stardatetime and enddatetime.
I hope it will be helpfull to you.

A: SOQL queries in a client application return dateTime field values as Coordinated Universal Time (UTC) values. You can use convertTimezone() in a date function to convert dateTime fields to the user's time zone.
SELECT HOUR_IN_DAY(convertTimezone(CreatedDate)), SUM(Amount)
FROM Opportunity
GROUP BY HOUR_IN_DAY(convertTimezone(CreatedDate))


text:
Q: How to extract first letter from each line from a file using batch? This is my code so far:
FOR /f %%G IN (temp.file) DO (
    echo %%G > temp
    first_char.exe temp > letter
    set /p myLetter =<letter
    echo %myLetter%
)

first_char.exe prints to the stdout the first char from the input file.
It prints:
ECHO is off.
ECHO is off.
ECHO is off.
ECHO is off.
ECHO is off.
ECHO is off.

(because I have 6 lines of text in temp.file).

A: I can't see why you need a first_char exe file to extract a single char, a simple var:~0,1 should also work.
Your ECHO is off. problem is a problem of the expansion time of %myLetter%.
It's expanded when the complete parenthesis block is parsed, at this time myLetter% is empty, therefor you got only empty lines.
setlocal EnableDelayedExpansion
FOR /f %%G IN (temp.file) DO (
    set "var=%%G"
    set "myLetter=!var:~0,1!"
    echo !myLetter!
)


text:
Q: export data is not working for more then 4 Dimensions in icCube-7.9 we tried to export the data (in excel format) from a table with 5 Dimensions, but it did not work. However, when we reduced the number of the dimensions to 4, it did work.
is there any thing to do to increase the number of the dimension and be able to export the data?

A: It appears that the problem has been fixed in the latest version of the icCube reporting application.

A: yes, we can confirm that! it is working now.


text:
Q: Poll list of objects from a file by multiple processes synchronously Use case:
I have a file with ids in it (approx 500k)
My application reads these files and processes them (processing for each id is huge).  So overall it takes a lot of time and memory for this processing.
What we need to achieve is by expanding the number of processes (run the Java processes on separate boxes/machines) and divide the entire list of ids in some fixed batch sizes such that 5 processes start processing items from the file and pick up the next batch whenever its processing is finished.
eg. if total items in the file are 100 and my batch size is 5 with total 3 processes then processing should be like

*

*Process 1: 1-5

*Process 2: 6-10

*Process 3: 11-15

such that if Process 2 finishes before other processes then it starts processing 16-20 and notify other about this so that next available process picks items 21-25.
Kindly note due to memory constraints we cannot do it using mulitple threads on single process/host.
Can someone please suggest solutions/references how it can be achieved.

A: It sounds like you have a distributed computing problem. You have a set of "things to process", and want to do that processing across multiple machines. The simplest and most typical way to do that is to put those "things to process" into a distributed queue like Amazon SQS or RabbitMQ (a file won't work).

*

*Have one process (and only one) be responsible for transferring the file to the distributed queue. If you can avoid the file entirely (and have whatever is writing to the file just write to the queue), do this instead.

*Setup multiple hosts (consider Amazon EC2) to read from that queue, and do the processing.

*

*Make sure to delete the item from the queue after processing is complete (and set reasonable visibilty timeouts based on how long processing should take) to avoid another worker host picking up the item when it shouldn't.

*If you want, you can pull from the queue one at a time, or in batches. I suggest setting up a thread pool on each host to perform the poll/work/delete loop, so the amount of concurrency per host can be easily tweaked just by changing the thread pool size.

By using a distributed queue like this, items taken by one host will not be seen by other hosts (thus avoiding double-processing).


text:
Q: how to customize jTable header column font size in Netbeans? I tried to change jtable header font size in Netbeans. but couldn't yet. anyway the table rows font size is changed successfully.
Here is the way I used:

The output after changes:

Problem : The Header font size is not changed. but I want to change that also. so pls help me how to do.

A: One way would be to use the UIManager and replace the default Font with the one you want
Font font = UIManager.getFont("TableHeader.font");
font = font.deriveFont(48f);
UIManager.put("TableHeader.font", font);

Which will replace the font used by all the tables in the system

Another way is to provide a custom TableCellRenderer for the columns you want to change, it's a little more work, but provides more flexibility as you can decide where you want to apply them.  You could wrap this inside your own custom JTableHeader, but I'm just providing some basic ideas.
public class HeaderRenderer implements UIResource, TableCellRenderer {

    private TableCellRenderer original;

    public HeaderRenderer(TableCellRenderer original) {
        this.original = original;
    }

    @Override
    public Component getTableCellRendererComponent(JTable table,
                                                                                Object value, boolean isSelected, boolean hasFocus, int row,
                                                                                int column) {
        Component comp = original.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
        comp.setFont(comp.getFont().deriveFont(Font.BOLD));
        return comp;
    }

}

Which is installed using something like...
HeaderRenderer header = new HeaderRenderer(table.getTableHeader().getDefaultRenderer());
TableColumnModel columnModel = table.getColumnModel();
columnModel.getColumn(0).setHeaderRenderer(header);

And produces something like...

Credit to Kleopatra for this idea
The long and short of it is, you're going to have to get your hands dirty and write some code, the form editor won't do everything for you


text:
Q: socket.io reconnecting should break after n attempts I am working on socket.io and i am new to this. I am trying to disconnect after n number of attempts to reconnect.
Server Side Code:
       var io = require('socket.io').listen(4000);
  io.sockets.on('connection', function (socket) {
  socket.emit('news', { hello: 'world' });
   socket.on('my other event', function (data) {
     console.log(data);
   });
  });

Client side code is:
  <script src="http://localhost:4000/socket.io/socket.io.js"></script>
    <script>
     //var max_reconnects, socket;

     var max_reconnects = 5;
      var socket = io.connect('http://localhost:4000',
          {'reconnection delay': 100,
           'max reconnection attempts': max_reconnects,
             'reconnection limit' : 10});

     socket.on('news', function (data) {
      console.log(data);
      socket.emit('my other event', { my: 'data' });
    });

           socket.on("reconnecting", function(delay, attempt) {
        console.log("attempting reconnect - " + attempt + "-->" + delay);
         if (delay === max_reconnects) {
          //return console.log("all reconnect attempts failed");
            //socket.disconnect();
            //socket.server.close();
            socket.emit('forceDisconnect');
            console.log("Limited end");
         }

       });

Please guide me how to terminate the reconnecting activity after number of attempts. the given code is not working properly. and reconnecting call back attempts is also undefined. Please guide me

A: Are you using socket.io >= 1.0 but using an example from before (there were some changes)?
Check here for the correct parameters: https://github.com/Automattic/socket.io-client#managerurlstring-optsobject
var socket = io.connect('http://localhost:4000',
      {'reconnectionDelay': 100,
       'reconnectionAttempts': max_reconnects});


text: Q: Can you update redis in place while redis is running without causing any downtime? I have some redis instances running on Ubuntu servers. Is it possible to update the version of redis installed on those servers from 3.2.9 to 3.2.13 (https://raw.githubusercontent.com/antirez/redis/3.2/00-RELEASENOTES) without causing any downtime for users? Users currently interact with the redis instances running on the servers through a proxy.


text:
Q: How Changing BIOS boot order pogrammatically? I want to change BIOS boot order in my bootsector code. How I can change the boot order of BIOS with assembly programming?
Z.z

A: BIOS is on what is called of ROM-BIOS. ROM means is only readable. So, if you want to change it you need to flash your BIOS but that's not recommended. Also, you can't access like a file and change it like it were somekind of configuration file.
If you want to change boot order in windows go to the msconfig and select the boot order. In linux you can use grub customizer. So, you can't actually program BIOS.
You can access, maybe, on RAM the address where the BIOS reserved address are and then see what is programmed. Once again, you can't just edit it. Maybe you get a ACCESS_VIOLATION error or similar error.
see this how BIOS works and see this
It maybe help you a better understanding. :)
EDIT:
On this topic maybe you find how to program your BIOS. but you really need to know what are you doing.

A: Look at the "BIOS Boot Specification", however it seem to be impossible to relate the identifiers used in the API with actual devices.
EFI has a proper interface for this.


text:
Q: How to force pandoc to number all ordered lists starting from one (1)? I have a Markdown document which is generated by some application. All things go correct, but there are some problems with ordered lists.
Below is minimal reproducible example of such Markdown document:
# Heading 1

Some text

## Heading 1.1

1. list item
1. list item

## Heading 1.2

3. list item
1. list item

## Heading 1.3

7. list item
3. list item

The output format really does not matter, but for PDF (produced by pandoc list-test.md -o list.pdf) I get the following:

But for example ReText renders the code as expected:

Why this happens?

A: The reason here is that ReText uses Python Markdown.
Comparison using Babelmark 2 gives a clue that we need to switch Pandoc to the markdown_strict mode by:
pandoc list-test.md -o list.pdf --from=markdown_strict

to get expected rendering.
Also using markdown_phpextra or markdown_mmd by:
pandoc list-test.md -o list.pdf --from=markdown_phpextra
pandoc list-test.md -o list.pdf --from=markdown_mmd

will fix the issue too.


text:
Q: No response from $.post WordPress ajax I have a form which I am trying to submit and receive data via WordPress AJAX.
I get no errors in the console but I also do not get any of the logging within the .post function
Live link (form under price): http://e390b6a4.ngrok.io//product/test-product-1/
Javascript:
function checkZipInstall(zipCode) {
console.log(zipCode);
    jQuery.post(rzcc_ajax_script.ajaxurl, zipCode
    ,
        function(response_from_rzcc_action_function){
            response = jQuery.parseJSON(response_from_rzcc_action_function);
            console.log(response);
            console.log(response.install_possible);
            if(response.install_possible === "true") {
                console.log('true');
            } else {
                console.log('false');
                //window.location.replace(response.redirect_url);
            }

        }
    );
}

jQuery('#vehicle-group').repeater({
    btnAddClass: 'r-btnAdd',
    btnRemoveClass: 'r-btnRemove',
    groupClass: 'r-group',
    minItems: 1,
    maxItems: 0,
    startingIndex: 0,
    showMinItemsOnLoad: true,
    reindexOnDelete: true,
    repeatMode: 'append',
    animation: 'fade',
    animationSpeed: 400,
    animationEasing: 'swing',
    clearValues: true
});

/* Prevent Add Button Refreshing */
jQuery( ".repeater-add-btn" ).click(function( e ) {
    e.preventDefault();
});

jQuery('#product_form').on('submit', function(e) {
    e.preventDefault();

    var formData3 = jQuery(this).serializeJSON();

    checkZipInstall(formData3);

});

Solved
As suggested by @charlietfl I needed to include an action parameter to the request. Updated function here:
function checkZipInstall(zipCode) {
    jQuery.post(rzcc_ajax_script.ajaxurl,
        {
            'action': 'the_ajax_hook',
            'zipCode': zipCode['zipCode']
        },
        function(response_from_rzcc_action_function){
            response = jQuery.parseJSON(response_from_rzcc_action_function);
            console.log(response);
            console.log(response.install_possible);
            if(response.install_possible === "true") {
                console.log('true');
            } else {
                console.log('false');
                //window.location.replace(response.redirect_url);
            }

        }
    );
}


text:
Q: Where to find Generic.xaml for native WPF controls? Where to find Generic.xaml (or other code with the default look) for native WPF controls such as Button, CheckBox, TextBox, etc?

A: In Silverlight (and I know that your question is about WPF) this information is more accessible than in WPF. You can get this information from any of these sources:

*

*Control Styles and Templates on MSDN.

*You can look at the resources of the relevant Silverlight assembly and extract the themes/generic.xaml embedded in a resource. I use Reflector to do this.

*You can extract the control template of a specific control using a tool. I use Expression Blend to do this. This also works for WPF.

A: Unfortunately the XAML for native controls is not directly available as a file. You need to use a program for peeking into the WPF assemblies and extracting that info. I personally have used the Mole for Visual Studio tool, which has done the job very well. It integrates as a debugger-visualiser, which is quite handy.


text:
Q: Optimizar dos llamadas a la base de datos con Moongose Tengo una función que sirve para editar un producto. De este se puede editar campos como nombre, categoría, y especialmente precioCosto y precioVenta. Si se edita alguno de estos dos campos, debe ir a otra función que guarda los precios anteriores en un histórico de precios. Para realizar esto, trate de hacerlo de esta forma:
let editProduct = (req, res) => {
  let id = req.params.id;
  let body = _.pick(req.body, ['codigo', 'descripcion', 'nombre', 'precioCosto', 'precioVenta', 'categoria', 'marca']);
  Producto.findByIdAndUpdate(id, body, { new: true, runValidators: true, context: 'query', useFindAndModify: false }, (err, productoUpdate) => {
    if (err) {
      return res.status(500).json({
        ok: false,
        error: 'Error interno'
      });
    }
    if (!productoUpdate) {
      return res.status(400).json({
        ok: false,
        error: {
          message: 'Producto no encontrado'
        }
      });
    }
    if(body.precioCosto != productoEncontrado.precioCosto || body.precioVenta != productoEncontrado.precioVenta) {
      closePriceHistory(productoUpdate);
      addPriceHistory(productoUpdate);
    }
    res.json({
      ok: true,
      producto: productoUpdate._id
    });
  });
}

El problema de este código, es que nunca entraba a:
if(
  productoUpdate.precioCosto != productoEncontrado.precioCosto ||
  productoUpdate.precioVenta != productoEncontrado.precioVenta
) { ... }

porque el producto se editaba y luego miraba esas propiedades. Lo solucioné de esta manera:
let editProduct = (req, res) => {
  let id = req.params.id;
  let body = _.pick(req.body, ['codigo', 'descripcion', 'nombre', 'precioCosto', 'precioVenta', 'categoria', 'marca']);
  Producto.findById(id, '_id nombre precioCosto precioVenta').exec((err, productoEncontrado) => {
    if (err){
      res.status(500).json({
        ok: false,
        error: 'Error interno'
      });
    }
    if(!productoEncontrado) {
      res.status(400).json({
        ok: false,
        error: 'Producto no encontrado'
      });
    }
    Producto.findByIdAndUpdate(id, body, { new: true, runValidators: true, context: 'query', useFindAndModify: false }, (err, productoUpdate) => {
      if(err) {
        return res.status(500).json({
          ok: false,
          error: 'Error interno'
        });
      }
      if (!productoUpdate) {
        return res.status(400).json({
          ok: false,
          error: {
            message: 'Producto no encontrado'
          }
        });
      }
      if (productoUpdate.precioCosto != productoEncontrado.precioCosto || productoUpdate.precioVenta != productoEncontrado.precioVenta) {
        closePriceHistory(productoUpdate);
        addPriceHistory(productoUpdate);
      }
      res.json({
        ok: true,
        producto: productoUpdate._id
      });
    });
  });
}

Funcionar, funciona. Pero ¿hay alguna mejor manera de hacerlo? Para no realizar dos queries a Mongo.
Gracias.


text:
Q: How can I know that whether user has received the pop up dialog for location access permission check or not in Android? I am having a Google map in fragment where I am fetching the current location of user. When I am.using the fragment in one of my activities,  whenever the activity will load Everytime it is showing the pop-up dialog to take the permission for location access from user. How to make sure that user should get the permission pop-up dialog for accessing the current location only once. Please help I am strucked here. Thanks in advance.

A: Simply check if you need to ask for the permission first, as the documentation desscribes.
if (ContextCompat.checkSelfPermission(YourActivity.this, Manifest.permission.READ_CONTACTS)
        != PackageManager.PERMISSION_GRANTED) {
    // Request permission
}


text:
Q: How to split string into rows based on condition in plsql i have a comma separated string as below
M1: TestString1, M2: TestString2, M3: TestString3, M4: TestString4, M5: TestString5, M6: TestString6, M7: TestString7
i need output as

code
String

M1
TestString1

M2
TestString2

M3
TestString3

M4
TestString4

M5
TestString5

M6
TestString6

M7
TestString7

can any1 help me in getting the query


text:
Q: How do i change the value of a checkboxed item in react? (changing one value in sql) First of all, sorry if the title is worded badly, i wasn't sure how to state it any better.
So my problem is that i have a database in mysql with different Bikes (imagine i have two bikes from diamond, one bike from scott etc) which in my database are stored on different physical locations with the tag FK_LocationID.
And i want to be able to "move" these bikes from one location to another by checking the bikes i want to move and selecting the location i want to move them two by picking from a dropdown (not neccessary). Tldr i want to change the FK_LocationID of checkboxed bikes. I have 5 arrays of bikes (there are 5 different locations, Santa Ana being locationID number 1)
export default class Locations extends Component {
  bikes1 = [];
  bikes2 = [];
  bikes3 = [];
  bikes4 = [];
  bikes5 = [];
  render() {
    return (

        <Card title="Locations">
          <Row>
            <Column>

1 - Haugastøl
 // i have 5 of these
              <List>
                {this.bikes1.map(bike1 => (
                  <List.Item key={bike1.BikeID}>
                    <input type="checkbox" checked={bike1.checked} onChange={e
         => bike1.checked = e.target.checked}/> {bike1.BikeID} - {bike1.Brand}
                  </List.Item>
                ))}
              </List>

          <select id="Location" value={this.FK_LocationID} onChange={e => (this.FK_LocationID= e.target.value)}>
            <option value={0}>Choose location..</option>
            <option value={1}>Haugastøl</option>
            <option value={2}>Finse </option>
            <option value={3}>Flåm </option>
            <option value={4}>Voss </option>
            <option value={5}>Myrdal </option>
          </select>

  mounted() {
    locationService.getBikesLocation1(bikes1 => { // 5 of these aswell
      for(let bike of bikes1) bike.checked = false;
      this.bikes1 = bikes1;
    });
    locationService.getBikesLocation2(bikes2 => {
      for(let bike of bikes2) bike.checked = false;
      this.bikes2 = bikes2;
    });

Basically ive made a dropdown, checkboxes and now im not sure how to actually change the FK_LocationID of the checked items. I would really appreciate any help here, im new to React and also javascript really.
Greetings

A: You don't really need state. What you could/should do is put the check boxes in a form or json object, and post it to your backend, and from there make the changes in your db. Local state won't help make changes to the back end, and since you mentioned sql I am assuming that you have one. If I'm wrong sorry, but just realize  that local state is not persistent so when you restart your app you will need to redo the changes.


text:
Q: Formatting JSON data in R I'm really new to working with JSON data, so I had a question about formatting.
Here's the link to the data I was trying to work with
I was using JSONlite and did this:
shot<-"http://stats.nba.com/stats/playerdashptshotlog?DateFrom=&DateTo=&
GameSegment=&LastNGames=0&LeagueID=00&Location=&Month=0&OpponentTeamID=0&
Outcome=&Period=0&PlayerID=202322&Season=2014-15&SeasonSegment=&
SeasonType=Regular+Season&TeamID=0&VsConference=&VsDivision="

I then did fromJSON:
json_data <- fromJSON(paste(readLines(shot), collapse=""))

This gives me the data in a list. My issue (although for all I know I messed up working towards this) is trying to create a data frame out of this info. I was able to make a data frame with code I read under similar questions on the site, but it is all of the data in just one column. Any recommendations would be appreciated!
Thanks

A: Normally, first thing to do when you get a JSON, you look at the structure.
str(json_data)

Doing so will reveal that your data has a very simple structure: is is a dataframe with rows, a line of headers, wrapped in some metadata about what each column means. Using the $ will allow you to address those specific components. In other words, your specific json is already a data frame structure, all you gotta to is take it out of json
library(jsonlite)
json_data <- fromJSON(paste(readLines(shot), collapse=""))
str(json_data)
mydf <- data.frame(json_data$resultSets$rowSet)
colnames(mydf) <- unlist(json_data$resultSets$headers)

You ought to get something like this:
head(mydf)

     GAME_ID                  MATCHUP LOCATION W FINAL_MARGIN SHOT_NUMBER PERIOD
1 0021401215 APR 14, 2015 - WAS @ IND        A L           -4           1      1
2 0021401215 APR 14, 2015 - WAS @ IND        A L           -4           2      1
3 0021401215 APR 14, 2015 - WAS @ IND        A L           -4           3      1
4 0021401215 APR 14, 2015 - WAS @ IND        A L           -4           4      1
5 0021401215 APR 14, 2015 - WAS @ IND        A L           -4           5      1
6 0021401215 APR 14, 2015 - WAS @ IND        A L           -4           6      1
  GAME_CLOCK SHOT_CLOCK DRIBBLES TOUCH_TIME SHOT_DIST PTS_TYPE SHOT_RESULT
1      10:33        7.7        0          1        25        3      missed
2       8:41         14       10        9.6      10.7        2        made
3       6:42       14.9       11        9.7      18.2        2      missed
4       5:16         19        3        3.5       4.2        2        made
5       4:45       19.8        3        3.7       3.3        2      missed
6       3:08       13.5       10        9.7        18        2      missed
  CLOSEST_DEFENDER CLOSEST_DEFENDER_PLAYER_ID CLOSE_DEF_DIST FGM PTS
1     Hill, George                     201588            4.3   0   0
2     Hill, George                     201588            5.7   1   2
3     Hill, George                     201588              3   0   0
4        Miles, CJ                     101139              4   1   2
5    Hill, Solomon                     203524              3   0   0
6     Hill, George                     201588            4.5   0   0


text:
Q: как сделать ограничение области нажатия экрана? Попробовал создать изображение, сделал его прозрачным и растянул в местах где хочу чтобы искались тачи игрока и накинул на него скрипт. Но мой скрипт ищет тачи по всему экрану. Как ограничить скрипт в пределах объекта или сделать так чтобы он не взаимодействовал например со слоем UI? Заранее спасибо!
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class ScreenD : MonoBehaviour
{
    GameObject gm;
    private Attack1 at1;
    private int dir = 0; //if -1=left,0=stay,1=right

    public int Dir
    {
        get { return dir; }
        set { dir = value; }
    }

    public void Start()
    {
        at1 = GameObject.Find("Ronin").GetComponent<Attack1>();
    }

    private void Update()
    {
        if (Input.touchCount > 0 && at1.Pressed == true) // поиск тачей, at1 это кнопка из другого скрипта нужная для того чтобы поиск тачей активировался только когда она нажата
        {
            var touch = Input.GetTouch(0);
            if (touch.position.x < Screen.width / 2)
            {
                dir = -1;
            }
            else if (touch.position.x > Screen.width / 2)
            {
                dir = 1;
            }
        }
    }

}

A: Используйте метод OnMouseDown() для вашего изображения


text:
Q: Can't get auto-disconnect bot to disconnect users already in voice I'm currently trying to get a discord bot running which will disconnect a specific user from the afk channel on my server whenever they try to enter it.
I admittedly am not very good at coding, and most of what I've got going is pieced together from other help sections I've looked through.
I've managed to get the bot to the state where it'll disconnect the user when they enter the afk channel directly from not being connected, but I am unable to figure out how to get it to do the same when the user moves from a channel to the afk channel.
The section I'm having trouble with is here:
client.on("voiceStateUpdate", (oldMember, newMember) => {
  const newUserChannel = newMember.voiceChannel;
  const oldUserChannel = oldMember.voiceChannel;

  if (
    oldUserChannel === undefined &&
    newUserChannel.name === "afk" &&
    data.find(
      guild =>
        guild.id === newMember.guild.id &&
        guild.blacklist.find(id => newMember.id === id)
    )
  ) {
    newMember.setVoiceChannel(null);
  }

I've tried setting oldUserChannel === undefined && to specific channels, and !== undefined, but anything other than === undefined gives me a TypeError: Cannot read property 'name' of undefined.
I've also tried user newUserChannel.id instead of .name, but that just gives me the same error with 'name' changing to 'id'.
I'm really very new to this, so I'm struggling to think of what I can do to fix the error.

A: If the user is being moved to the AFK channel from another channel, oldUserChannel will be defined as a VoiceChannel.
You should check if newUserChannel exists (if that's the case, we know the user is still connected to a VoiceChannel, and check if the channel's id/name equals to "AFK" / "Channel ID".
Note: I encourage you to switch to Discord JS v12.

client.on("voiceStateUpdate", (oldMember, newMember) => {
    if (!newMember.voiceChannel) return false; // The GuildMember is not in a VoiceChannel.
    if (newMember.voiceChannel.guild.id !== "GUILD ID") return false; // Making sure this works in a certain Guild. I don't think you want this to happen in every Guild your bot is in which has a VoiceChannel called "AFK".

    if (newMember.voiceChannel.name == "AFK" && newMember.id == "USER ID") { // Checking if the channel's name is AFK and making sure the user is the one you want to disconnect.
        newMember.setVoiceChannel(null);
        // I'm not sure if Discord JS v11 has a method of disconnecting the user from a VoiceChannel.
        // But setting the voice channel to null will work.
    };
});


text:
Q: Why does my function always return 1? I'm writing a function that's supposed to check whether there is a winner or not in a game of "noughts and crosses", or "three in a row".
The game works by first drawing out 3 x 3 squares in the command prompt. The user then moves the cursor between the squares, and presses enter to place an "X". The next selected square gets an "O" placed in it, and then an "X" again, and so on. After turn 5 (the first possible turn there could be a winner) the program checks if there is a winner after every turn, and if none is found after 9 turns (when all squares have something in them) the program declares a draw.
However, the function I've written to check for a winner always returns 1 when it's called, which means there is a winner (X more specifically, since thatäs the one that made the last move). Therefore the game ends on turn 5, no matter what the squares contain.
Here is my code:
int control(char p[3][3]) {
    int i;
    for (i = 0; i <= 3; i++)    //Checks if any of the horizontals have 3 of the same markers in a row
        if (p[i][1] == p[i][2] && p[i][2] == p[i][3])
            return 1;

    for (i = 0; i <= 3; i++)    //Checks if any of the vertical columns have 3 of the same markers
        if (p[1][i] == p[2][i] && p[2][i] == p[3][i])
            return 1;
        else if (p[1][1] == p[2][2] && p[2][2] == p[3][3])    //Checks if top left, middle and bottom right squares have the same marker
            return 1;
        else if (p[3][1] == p[2][2] && p[2][2] == p[1][3])    //Checks if the top right, middle and bottom left have the same marker
            return 1;
        else               //If none of the above have the same 3 markers, the game keeps going
            return 0;
}

A: You are passing in a 3x3 array (with indices 0, 1 and 2 in each dimension), but in your loops you are iterating 4 times (indices 0, 1, 2 and 3). Try for (i = 0; i < 3; i++) in your loops instead, as your loops will now check values beyond the boundaries of the p array, and if you are unlucky the contents of that memory causes your control function to return 1.
Finally, I think the final else-block should not be in the loop, but rather outside of it: If both loops have run and you have not returned yet, you can safely return 0, but you wouldn't want to return a 0 prematurely before you have checked all your verticals.
Here is the function with the changes to the indices and the diagonal checks and final else-block fished out of the second for-loop:
int control(char p[3][3]) {
    int i;

    /* Check horizontals */
    for (i = 0; i < 3; i++)
        if (p[i][0] == p[i][1] && p[i][1] == p[i][2])
            return 1;

    /* Check verticals */
    for (i = 0; i < 3; i++)
        if (p[0][i] == p[1][i] && p[1][i] == p[2][i])
            return 1;

    /* Check diagonals */
    if (p[0][0] == p[1][1] && p[1][1] == p[2][2])
        return 1;
    if (p[2][0] == p[1][1] && p[1][1] == p[0][2])
        return 1;

    return 0;
}


text:
Q: Lipschitz continuity for a bounded linear functional When trying to prove that a linear functional is bounded iff it is Lipschitz continuous, is it true that if we assume that a linear functional is Lipschitz continuous on a normed linear space $X$, then it is also continuous on $X$?

A: In view of t.b.'s comment, the answer is concluded to be yes. In essence, a sequential continuity argument seems sufficient.


text:
Q: Circles related My question needs a diagram. But, being a new user I cannot upload images in questions. So, below is the link to the diagram. [Diagram not to scale]
https://photos.app.goo.gl/2jsB35Rp5Dc6vni13
In the figure, $O$ is the centre of the circle. If $ AB = 6 cm$ and $ AC = 5 cm$, then the product of $AO$ and $AX$ is?

A: Let $a,b,c$ be the lengths of sides $BC,AC,AB$, respectively.

Let $R$ be the length of $AO$, and let $h$ be the length of $AX$.

Given $b=5$ and $c = 6$, the goal is to find $hR$.

By the extended law of sines, ${\large{\frac{a}{\sin A}}} = 2R$, hence $R = {\large{\frac{a}{2\sin A}}}$.

Let $k$ denote the area of triangle $ABC$.
\begin{align*}
\text{Then}\;\;&\frac{1}{2}ah = k = \frac{1}{2}bc\sin A\\[4pt]
\implies\;&h = \left(\frac{bc}{a}\right)\sin A\\[4pt]
\implies\;&hR = \left(\left(\frac{bc}{a}\right)\sin A\right)\left(\frac{a}{2\sin A}\right)\\[4pt]
&{\phantom{hR}}=\frac{1}{2}bc\\[4pt]
&{\phantom{hR}}=15\\[4pt]
\end{align*}

A:
Let's denote $a=|BC|$, $b=|AC|$, $c=|AB|$, $h=|AX|$,
$R=|OA|=|OB|=|OC|$
and let $[ABC]$ be the area of $\triangle ABC$.
To find the value of $h\cdot R$, we can use
the two well-known
expressions for $[ABC]$,
\begin{align}
\text{1) in terms of the base $a$ and height $h$ }\quad
[ABC]&=\tfrac12 a\,h
,\\
\text{and 2) in terms of the sides $a,b,c$ and the circumradius $R$ }\quad
[ABC]&=\frac{abc}{4R}
,\\
\text{hence, }\quad
\require{cancel}\tfrac12 \cancel{a}\,h &=\frac{\cancel{a}\,b\,c}{4R}
,\\
h\,R&=\tfrac12\,b\,c
=\tfrac12\,5\cdot6=15
.
\end{align}

A: Let $H$ be the midpoint of $AB$. We have $\angle ACX=\angle AOH$ (inscribed and half central angle subtending the same arc), hence triangles $CAX$ and $AOH$ are similar and:
$$
AO:BH=AC:AX,
\quad\hbox{that is:}\quad
AO\cdot AX=BH\cdot AC=3\cdot5=15.
$$


text:
Q: Margins displays correctly in Opera, Chrome and IE but not in FF I have tried about every option I could think of but I still can't make this page display correctly in FF.  When you click inside the square, a menu with images appears on the right which is properly aligned in every browser but FF.  I've tweaked the CSS here and there but haven't found a solution.
If I remove the width property from #acabados_main .image_carousel on the stylesheet all browsers show the same margins, albeit non-aligned.  But as soon as I give it a width FF is the only one that displays that section differently.
Can someone please take a look and help me see what's wrong?

A: try adding float: left; to .general
#acabados_main .image_carousel .general {
    float: left;
    position: relative;
}


text:
Q: Is it possible to rename a Presto view? Is it possible to rename a Presto view?
I know I can accomplish this via dropping the view and recreating it with the new name, but I'd prefer to be able to rename the view directly.
Something like this would be nice, but from what I can tell so far this is not supported:
-- rename view
ALTER VIEW hive.foo.my_view RENAME TO hive.foo.renamed_view;

-- move view to a different schema
ALTER VIEW hive.foo.my_view RENAME TO hive.bar.my_view;

The relevant version is Presto 0.212.

A: This isn't possible today in Presto, but is a good feature request. I filed an issue to track it: https://github.com/prestosql/presto/issues/1037
For views in the Hive connector, it might be possible to rename them using Hive, since they are stored in the metastore as a Hive view (although they are Presto syntax and format so not queryable by Hive).


text:
Q: How to post MySql row variable using Javascript on button click I have a html table populated with mysql data. Each row has an id (e.g 001, 002 etc). Within each table row I have created a button. I'd like to be able to post the current time in milliseconds (working fine) as well as the relevant id of the row (which the button clicked is in) to an Ajax file. My Ajax file works fine I just can't get the right id to post.
I have tried using <?php echo $row=$REQUEST ['id']?> but it only returns the first value in the table not the respective one.

      ID Number
      Class
      Crew
      Start
      Finish

      <?php echo $row["number"];?>
      <?php echo $row["class"];?>
      <?php echo $row["crew"]?>
       <input type="hidden" id="boatnumber" name="custId" value="<?php echo $row["number"];?>"<button id="startbutton" type="submit" class="newbutton">

It only sends the id of the first row in the table not the id of the row where the button (that is clicked) is.

A: You are getting the value of an element with the ID of #boatnumber, you can't have multiple elements with the same ID.
A better way maybe to use a data attribute on the button that holds the number and then retreive it in your script.
HTML:
<button type="submit" class="newbutton" data-number="<?php echo $row['number'] ?>">

Script:
var boatnumber = $(this).data('number);


text:
Q: How to store the previous value of a user in a loop? import javax.swing.JOptionPane;

public class Hello {

    public static int s1;

    public static void main(String [] args){

            userInput();
    }

    public static void userInput() {

        do {
            String str1 = JOptionPane.showInputDialog("Enter a positive integer. Enter 0 to quit. ");

            s1 = Integer.parseInt(str1);

            if (s1 == 0)
                break;

        } while (s1 > 0);

    }
}

I want to find the greatest number from the user input. How to store the previous values of the user's input in a do-while loop?
Thank you!

A: The easiest fix is probably this:
public static void userInput() {

  do {
    String str1 = JOptionPane.showInputDialog("Enter a positive integer. Enter 0 to quit. ");

    // s1 = Integer.parseInt(str1); // don't save directly to this variable
    int newValue = Integer.parseInt(str1);
    if (newValue > s1) {
      s1 = newValue;
    }

    if (newValue == 0)
      break;

  } while (s1 > 0);

}

A quick note: the while(s1 > 0) check isn't really doing anything here. Since you have the break statement above, you can simplify this to while(true)

A: When saving numbers, you have to be careful not to lose them. Imagine for a minute that you've purchased a lottery ticket using your lucky numbers. Later in the week, when the drawing happens, your lucky numbers are the winner! You go to find your ticket but...what's that? You can't remember where you put it? Well what's a few hundred million, right?
Did you see where you went wrong? It wasn't remembering the numbers. It was remembering where you put the numbers! You don't want to lose them. So the first thing you need to do is save your numbers to a file, like this:
String filename = "your_filename.txt";
FileWriter file = null;
BufferedWriter writer = null;

try
{
    file = new FileWriter(filename);
    writer = new BufferedWriter(file);

    do {
        String str1 = JOptionPane.showInputDialog("Enter a positive integer. Enter 0 to quit. ");

        s1 = Integer.parseInt(str1);
        writer.write(Integer.toString(str1));
        writer.newLine();

        if (s1 == 0)
            break;

    } while (s1 > 0);

    writer.close();
}
catch (IOException e)
{
    // Common practice is to ignore exceptions since they probably won't happen
}

So now you've got a file to save your numbers, but what if you have a hard drive failure? Or your computer gets stolen? Or you download a virus while playing illegal foreign online lotteries? You're going to want to back it up. A common service for doing just that is S3.
After including the S3 library for Java and initializing your S3 client, add the following code.
String bucketName = "important-numbers";
File localNumbers = new File(filename);
s3client.putObject(bucketName, filename, localNumbers);

Congrats! Now for a nominal fee (don't worry your lottery winnings will more than cover), you'll never lose your numbers again.


text:
Q: Chai / Expect - how to work while developing? Seems really hard to go from expect().to.throw to logging the error I have this code
expect(function() {
   //some error
}).to.throw(Error);

How do I easily go from this to logging the error right here in the test?
Do I really have to type try/catch and console.log? Doesn't that go against the fact that I will need to remove them eventually for the test to pass?

A: The Chai .toThrow() matcher can be used to ways:

*

*to check of the error throws is of a particular instance
expect(function() {
  throw SyntaxError('sample error message');
}).to.throw(SyntaxError);

*to check text of the error message
expect(function() {
  throw SyntaxError('sample error message');
}).to.throw(/sample error message/);

If this doesn't suite your use-case, you can always try/catch and inspect/make assertions on the object of the caught error:
try {
  throw SyntaxError('sample error message');
} catch(e) {
  expect(e.message).to.equal('sample error message');
}


text:
Q: How to embed modules on pages? I have created my own extension and modules. I can view the modules fine, by going to their URL. However, now I want to embed them on a page, much like a content class. How do I go about doing that?
Thanks!

A: You have to create template operator or function and use them in template.

A: It is not possible to "embed" a module in a page except if the module which is called do it at the PHP level.
For instance, it's possible to write this :
$module = eZModule::findModule( 'content' );
$result = $module->run( 'history', array( 1 ) );

But if you want to display anything related to your module, you should declare that your extension contains some templates and override some templates.
Let's say that you would like to make your own register module.
Step 1, you may have to add this in your_extension/settings/design.ini.append.php :
[ExtensionSettings]
DesignExtensions[]=your_extension

So you are now able to add your own user/register.tpl
This template contains a form like this :
<form action={'/user/register'|ezurl}...

So you just need to copy the template but with :
<form action={'/your_module/register'|ezurl}...

Now let's say that your template is supposed to display some informations related to your module. You may have to define some fetch functions so you would be able to write something like this:
{def $nb = fetch('your_module','beta_accounts')}

Hurry up! There are only {$nb|wash} available accounts for free!

<form action={'/your_module/register'|ezurl} method="POST">
   ...
</form>

I hope that it will help...