text:
Q: Integral $\lim _{n\to \infty}\int _0^1\sqrt{\frac{1}{x}+n^2x^{2n}}\,dx$ Evaluate $\displaystyle \lim \limits _{n\to \infty}\int \limits _0^1\sqrt{\frac{1}{x}+n^2x^{2n}}\,dx$.
The integral is non asymptotic. The convergence is non uniform at both $x=0$ and $x=1$. I'm not sure how to proceed.

A: We have
\begin{align}
I_n &= \int_0^1 \sqrt{\frac{1}{x} + n^2 x^{2n}} \mathrm{d} x \\
&\le \int_0^1 \left(\sqrt{\frac{1}{x}} + nx^n\right) \mathrm{d} x \\
&\le \int_0^1 \left(\sqrt{\frac{1}{x}} + (n+1)x^n\right) \mathrm{d} x \\
&= \left(2\sqrt{x} + x^{n+1}\right)\Big\vert_0^1 \\
&= 3.
\end{align}
Also, we have
\begin{align}
I_n &= \int_0^{1-\frac{1}{\sqrt{n}}} \sqrt{\frac{1}{x} + n^2 x^{2n}}\ \mathrm{d} x
+ \int_{1-\frac{1}{\sqrt{n}}}^1 \sqrt{\frac{1}{x} + n^2 x^{2n}}\ \mathrm{d} x\\
&\ge \int_0^{1-\frac{1}{\sqrt{n}}} \sqrt{\frac{1}{x}}\ \mathrm{d} x
+ \int_{1-\frac{1}{\sqrt{n}}}^1 nx^n \mathrm{d} x \\
&= 2\sqrt{1 - \frac{1}{\sqrt{n}}} + \frac{n}{n+1} \left[1 - \left(1-\frac{1}{\sqrt{n}}\right)^{n+1}\right].
\end{align}
Combining the above results, we have
$$2\sqrt{1 - \frac{1}{\sqrt{n}}} + \frac{n}{n+1} \left[1 - \left(1-\frac{1}{\sqrt{n}}\right)^{n+1}\right] \le I_n \le 3.$$
Note that
$$\lim_{n\to \infty} 2\sqrt{1 - \frac{1}{\sqrt{n}}} + \frac{n}{n+1} \left[1 - \left(1-\frac{1}{\sqrt{n}}\right)^{n+1}\right] = 3.$$
By the squeeze theorem, we have
$\lim_{n\to \infty} I_n = 3$. We are done.

A: Let
\begin{align}
I = \int^1_0 \sqrt{\frac{1}{x}+n^2x^{2n}}\ dx.
\end{align}
Observe
\begin{align}
I_2=I-\int^1_0 \frac{dx}{\sqrt{x}} = \int^1_0 \frac{\sqrt{1+n^2x^{2n}}-1}{\sqrt{x}}\ dx = \int^1_0 \frac{n^2x^{2n}}{\sqrt{x}(\sqrt{1+n^2x^{2n}}+1)}\ dx.
\end{align}
To evaluate $I_2$, we will divided the interval. Fix $\delta=\frac{1}{n^2}$. Then we see that
\begin{align}
I_2 = \int^1_{1-\delta}+\int^{1-\delta}_\delta+ \int^\delta_0 \cdots\ dx =J_1+J_2+J_3.
\end{align}
For $J_2$, the integrand converges uniformly to zero pointwise every where on the interval. Hence $\lim_{n\rightarrow \infty} J_2 = 0$.
For $J_3$, we see that for $n$ sufficiently large we have the estimate
\begin{align}
J_3 \le&\ \int^\delta_0 \frac{\delta}{\sqrt{x}(\sqrt{1+\delta}+1)}\ dx
\leq\ \frac{2\delta\sqrt{\delta}}{\sqrt{1+\delta}+1}.
\end{align}
Finally, for $J_1$. Observe that
\begin{align}
|J_1-1| \leq&\ \int^1_{1-\delta} dx\ \left|\frac{n^2}{\sqrt{1-\delta}(\sqrt{1+n^2x^{2n}}+1)}-\frac{1}{\delta}\right|\\
\leq& \left|\frac{n^2\delta}{\sqrt{1-\delta}(\sqrt{1+n^2(1-\delta)^{2n}}+1)}-1\right|.
\end{align}
Hence, if you take $n\rightarrow \infty$, we see that $J_1 \rightarrow 1$, $J_2\rightarrow 0$ and $J_3\rightarrow 0$.
Thus $\lim_{n\rightarrow \infty} I_2 =1$ which means $I = 3$ since $\int^1_0 dx/\sqrt{x} = 2$.
Remark: Heuristically, we see that for $f_n(x) \rightarrow \frac{1}{\sqrt{x}}$ pointwise for any fixed point on $(0, 1)$. In fact, on $[\delta, 1-\delta]$ the convergence is uniform. Hence the integral of $\lim_n \int f_n$ coincides with the integral of $1/\sqrt{x}$ on that interval.
However, outside of the interval things get tricky. For the interval $[0, \delta]$, this is not a big problem since $n$ doesn't affect the integrand as long as $\delta$ is small. In particular, I chose $\delta = n^{-2}$ which is small enough for this to work (in fact, $n^{-2}$ was chosen so that the next part would work).
The most tricky part is the interval $[1-\delta, 1]$ because the area of $f_n$ concentrates around $1$ making the integral over the small interval not negligible. In fact, the main point is that $f_n \rightarrow  \frac{1}{\sqrt{x}}+\delta(x-1)$ where $\delta(x)$ is the Dirac delta function. In fact, we see that
\begin{align}
\lim_{n\rightarrow \infty} \int^1_0 f_n(x)\ dx = \int^1_0 \frac{1}{\sqrt{x}}+\delta(x-1)\ dx = 2+1 = 3
\end{align}

A: Hint :
Let $f_{n} := \sqrt{\frac{1}{x}+n^{2}{x^{2n}}}$, when $x$ is fixed, since $x \in (0,1)$ we note that $\lim\limits_{n \to +\infty} f_{n} = \frac{1}{\sqrt x}$, which is integrable on $(0,1)$.
If we can find an integrable function  $g$,  such that $|f_{n}(x)|\leq g(x)$, we can conclude by Dominated convergence Theorem the $\lim\limits_{n\to +\infty} \int_{0}^{1} f_{n} = \int_{0}^{1} \lim\limits_{n\to +\infty} f_{n} = \int_{0}^{1} \frac{1}{\sqrt x} = 2$.


text:
Q: Trying to understand move semantics I'm studying the 'move semantics' introduced since C++11. I wrote a sample code for creating class objects using normal constructors, a copy constructor, and a move constructor.
/* Useless.cpp */
#include <iostream>

using namespace std;

// interface
class Useless {
private:
    int n; // number of elements
    char* pc; // pointer to data
    static int ct; // number of objects
    void ShowObject() const;
public:
    Useless();
    explicit Useless(int k);
    Useless(int k, char ch);
    Useless(const Useless & f); // regular copy constructor
    Useless(Useless && f); // move constructor
    ~Useless();

    Useless operator+(const Useless & f) const;
    void ShowData() const;
};

int Useless::ct = 0;

Useless::Useless() {
    ++ct;
    n = 0;
    pc =nullptr;
    cout << "default constructor called; number of objects" << ct << endl;
    ShowObject();
}

Useless::Useless(int k) : n(k) {
    ++ct;
    pc = new char[n];
    cout << "int constructor called; number of objects: " << ct << endl;
    ShowObject();
}

Useless::Useless(int k, char ch) : n(k) {
    ++ct;
    pc = new char[n];
    for (int i=0; i< n; i++) {
        pc[i] =  ch;
    }
    cout <<"int, char constructor called; number of objects: " << ct << endl;
    ShowObject();
}

Useless::Useless(const Useless & f) : n(f.n) {
    ++ct;
    pc = new char[n];

    for (int i =0; i< n; i++) {
        pc[i] = f.pc[i]; // deep copy
    }
    cout << "copy const called; number of objects: " << ct << endl;
    ShowObject();
}

Useless::Useless(Useless && f) : n(f.n) {
    ++ct;
    pc = f.pc; // steal address (shallow copy)
    f.pc = nullptr;
    f.n = 0;
    cout << "move const called; number of objects: " << ct << endl;
    ShowObject();
}

Useless::~Useless() {
    cout << "destructor called; objects left: " << --ct << endl;
    cout << "deleted object:\n";
    ShowObject();
    delete [] pc;
}

Useless Useless::operator+(const Useless & f) const {
    cout << "Entering operator+() \n";
    Useless temp = Useless (n+f.n);

    for (int i=0; i < n; i++) {
        temp.pc[i] = pc[i]; // copy the current object's characters
    }

    for (int i=n; i < temp.n; i++) {
        temp.pc[i] = f.pc[i-n]; // copy the argument object's characters
    }
    cout << "temp object:\n";
    cout <<  "leaving operator+()\n";
    return temp;
}

void Useless::ShowObject() const {
    cout << "Number of elements: " << n;
    cout << "Data address: " << (void *) pc << endl;
}

void Useless::ShowData() const {
    if (n==0) {
        cout << "(object empty)";
    }
    else {
        cout << "data: ";

        for (int i = 0; i < n; i++) {
            cout << pc[i] ;
        }
    }
    cout << endl;
}

int main() {
    Useless one (10, 'x');
    Useless two = one; // call the copy constructor
    Useless three(20, 'o');
    Useless four(one+three); // it should call operator+() and then the move constructor

    cout << "object one: ";
    one.ShowData();
    cout << "object two: ";
    two.ShowData();
    cout << "object three: ";
    three.ShowData();
    cout << "object four: ";
    four.ShowData();
    return 0;
}

I expected the code generates five Useless objects
(i.e., object 'one', 'two' 'three', a temporary object made by operator+() function,
and the object 'four' created by calling the move constructor). However, the result is different from my expectation. The actual result was as follow:
int, char constructor called; number of objects: 1
Number of elements: 10Data address: 0x56230b195eb0
copy const called; number of objects: 2
Number of elements: 10Data address: 0x56230b1962e0
int, char constructor called; number of objects: 3
Number of elements: 20Data address: 0x56230b196300
Entering operator+()
int constructor called; number of objects: 4
Number of elements: 30Data address: 0x56230b196320
temp object:
**leaving operator+()**
object one: data: xxxxxxxxxx
object two: data: xxxxxxxxxx
object three: data: oooooooooooooooooooo
object four: data: xxxxxxxxxxoooooooooooooooooooo
destructor called; objects left: 3
deleted object:
Number of elements: 30Data address: 0x56230b196320
destructor called; objects left: 2
deleted object:
Number of elements: 20Data address: 0x56230b196300
destructor called; objects left: 1
deleted object:
Number of elements: 10Data address: 0x56230b1962e0
destructor called; objects left: 0
deleted object:
Number of elements: 10Data address: 0x56230b195eb0

My expectation was the program generates the fifth object (object 'four') by calling the move constructor defined above (with the result of 'one + three' as input argument). I would appreciate any clue for understanding the result.

A: That's copy elision and return value optimization in action. See copy elision.
In gcc/clang you can disable it using -fno-elide-constructors and then you'll get your 5th object.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Redis: How to HMSET a dictionary from a Lua script? I am trying to pass a Python dict as an argument to a Lua script and HMSET it to a Redis key from the script.
I have two questions.
How am I supposed to pass the dict from Python to Lua script and from the Lua script to Redis?
Passing it to Lua seems straightforward, with a json.dumps(). However, how do I convert it back to a dict (or Lua table I guess?) in Lua (I can not use Lua's require inside Redis' EVAL).
Although I still don't know how to pass a real dict to Redis from Lua, I am still playing with HMSET inside the Lua script and trying to assign to the key a string.
Why am I getting this error:
redis.exceptions.ResponseError: Error running script (call to f_2591f0a1987b36dd027b752af3591c92be845cd4):
@user_script:7: @user_script: 7: Wrong number of args calling Redis command From Lua script

provided that my Lua code uses the same number of args as my Python HMSET:
local key_name = KEYS[1]
redis.call('hmset', key_name, "some_val")

A: First, please note that a Pythonic dict is not the same as a Redis Hash: while a dict can store any type as value and supports nesting, hashes are only 1-level deep and store strings. So, if your dict is nested and/or contains non-string values the mapping is non-trivial.
Now, assuming that the dict is indeed non-nested.

How am I supposed to pass the dict from Python to Lua script and from the Lua script to Redis?

As you're passing the JSONified representation, you can use Redis' Lua cjson library to parse it into a Lua table, likeso:
local dict = cjson.decode(ARGS[1])

Why am I getting this error:

The error is raised because you're calling HMSET (deprecated btw, replaced by HSET) without the field name argument. A correct way to do it (i.e. save the dict to a hash) would be something like the following:
local key_name = KEYS[1]
local dict = cjson.decode(ARGS[1])
for k, v in pairs(dict) do
  redis.call('HSET', key_name, k, v)
end

Or perhaps this slightly faster variant:
local key_name = KEYS[1]
local dict = cjson.decode(ARGS[1])
local payload = {}
for k, v in pairs(dict) do
  table.insert(payload, k)
  table.insert(payload, v)
end
redis.call('HSET', key_name, unpack(payload))


text:
Q: Why does setuptools not understand git+https URLs? According to Dependency section in the setuptools manual git repository URLs can be specified in the dependency_links argument to setup with git+URL. Yet,
cd /tmp
mkdir py-test
cd py-test
touch __init__.py

and creation of a setup.py file with
from setuptools import setup, find_packages
from pkg_resources import parse_version

setup(
    name = "py-test",
    version = "1.0",
    packages = ["."],
    dependency_links = [
        "git+https://github.com/wxWidgets/wxPython.git"
    ],
    install_requires = ["wxPython"],
)

causes the error Download error on git+https://github.com/wxWidgets/wxPython.git: unknown url type: git+https -- Some packages may not be found! when I run python setup.py build && sudo setup.py install.
The installation of the package python-setuptools-git doesn't help.
I'm using setuptools 18.2 with python 2.7 on Ubuntu 15.04.

A: From the setuptools docs:

In the case of a VCS checkout, you should also append #egg=project-version in order to identify for what package that checkout should be used

So the fix is just to append the #egg=wxPython fragment onto the end:
dependency_links = [
    "git+https://github.com/wxWidgets/wxPython.git#egg=wxPython"
]


text:
Q: injecting `sessionScoped` `managedBean` doesn't work I have a  sessionScoped managedBean called UserManager, when I try to print #{UserManager.loggedIn} in the view, It work, but in my servlet-filter the injection of this managedBean doesn't work.
I tried to inject it like this:
@ManagedProperty(value="#{userManager}")
private UserManager userManager;

And in userManager I have null pointer.


text:
Q: MSTest from command line I am trying to run MSTest from command line in powershell.
mstest /testcontainer:Common.Tests.dll

I am in the project bin/debug folder.  It opens a new command window and the window closes either with no output or output that I can't read, as a result of the window immediately closing.  The test run successfully in Visual Studio and the project builds successfully using MSBuild and in Visual Studio.  I assume that something is breaking but I have no idea how to determine what it could be.
I am using VS 14.0.
I have also tried vstest.console with the same result.

A: Well, one way to do that would be:
mstest /testcontainer:Common.Tests.dll > result.txt 2>&1

that would redirect all output to the result.txt

A: You can assign the output to a variable and then use it however you wish, like just outputting it to screen...
$mstest = Invoke-Expression "mstest /testcontainer:Common.Tests.dll"
Write-Output $mstest


text:
Q: Closing a fragment that is inflated inside the FrameLayout In my code, I have a button on OnClick of which I inflate a FrameLayout with a fragment by starting a Fragment Transaction. Now the fragment is inflated into the frame layout.
But I have a button inside the fragment view on click of which i want to close that fragment and show the activity where the button clicked open the fragment.

A: while opening your fragment in Activty
getSupportFragmentManager()
                .beginTransaction()
                .add(R.id.framelayout, yourFragment, "your_frag")
                .addToBackStack(null)
                .commit();

btnInFragment.setOnClickListener(v -> getActivity().onBackPressed());

Override your onBackPressed method of Activity
@Override
public void onBackPressed() {
   if(getSupportFragmentManager().getBackStackEntryCount()>0){
       getSupportFragmentManager().popBackStack();
   }
   else {
      super.onBackPressed();
   }
}


text:
Q: How do you re-merge a reverted merge In our past life we had a branching system that was .. incorrect.
We had to revert a merge because we decided to not release the feature.
Now we are ready to release the feature and i'm having a hard time figuring out how to get them remerged.
I made a new branch from that previous branch just for tracking purposes and merged in the latest from our main line. But I haven't been able to figure out how to merge it back into the main line.

A: There are a couple of ways to go about doing it.

*

*You could use git revert on the revert commit for the merge.  Make sure any later changes are not overwritten.

*Depending on the what files are changed in the feature, you can checkout the files from the original with git checkout.  Then you can do a single commit that introduces the feature.  This can be tricky if later changes would be overwritten by the past files.

*git cherry-pick the commits that make the changes for the features.  If there are only a couple of commits that you can easily identify for the feature, this can work.  It will create new commits reintroducing the changes.  Just make sure that you apply the commits in the correct order.

No matter what, you will need to have one or more new commits that reintroduce the change.  It isn't going to be a matter of remerging the branch.
IMO, the easiest option would probably be the first.  Just make sure that you verify everything on your local repo before pushing.  That way you can modify the commit without causing any trouble.

A: With a clean working tree on that branch, switch back to the main line (master?) and git merge <branchname> or you can use rebase to apply all the changes of that other branch on top of the current "main line" (master?)


text:
Q: How to navigate to another page with id param on Ag-grid? I am trying to edit the record displaying in Ag-Grid table. I want to navigate to edit page while clicking on particular cell of Ag-grid and the ID param of that record has to be pushed for populating edit page.
My app is built with Vue.Js .Can any one help with solution to this? Please.!

A: This worked for me. I hope it might work for you as well.
{
          headerName: "ID",
          field: "idvalue",
          cellRenderer: params => {
            const route = {
              name: "editpage",  // name will be same as stated in the route by you
              params: { id: params.value }
            };

            const link = document.createElement("a");
            link.href = this.$router.resolve(route).href;
            link.innerText = params.value;
            link.addEventListener("click", e => {
              e.preventDefault();
              this.$router.push(route);
            });
            return link;
          }
},


text:
Q: Tensorflow session.run feed dict mechanism So I am new to tensor flow, and my error is that I am feeding in
invalid argument to x for train_neural_network(x).
What I am trying to do is for 4999 iterations, input a [1,400] array that are
the bit values for a picture. So input 4999 pictures. I read the images in with
scipy.io as matrixes not tensors.
I am confused about how the placeholders are used and what is generally wrong with my code. since I feed in x and y's to the placeholders, shouldn't the input x to train_neural_network(x) be the placeholder values?
x = tf.placeholder('float',[1,400])
y = tf.placeholder('float',[1,10])

def neural_network_model(data):

        hidden_layer1 = {'weights':tf.Variable(tf.random_normal([400,n_nodes_hl1])),
                        'biases':tf.Variable(tf.random_normal(n_nodes_hl1))}

        hidden_layer2 = {'weights':tf.Variable(tf.random_normal([n_nodes_hl1,n_nodes_hl2])),
                        'biases':tf.Variable(tf.random_normal(n_nodes_hl2))}

        hidden_layer3 = {'weights':tf.Variable(tf.random_normal([n_nodes_hl2,n_nodes_hl3])),
                        'biases':tf.Variable(tf.random_normal(n_nodes_hl3))}

        output_layer = {'weights':tf.Variable(tf.random_normal([n_nodes_hl3,n_classes])),
                        'biases':tf.Variable(tf.random_normal([n_classes]))}

        #(input * weights) + biases

        l1 = tf.add(tf.matmul(data, hidden_layer1['weights']),hidden_layer1['biases'])
        l1 = tf.nn.relu(l1)

        l2 = tf.add(tf.matmul(l1, hidden_layer2['weights']),hidden_layer2['biases'])
        l2 = tf.nn.relu(l2)

        l3 = tf.add(tf.matmul(l2, hidden_layer3['weights']),hidden_layer3['biases'])
        l3 = tf.nn.relu(l3)

        output = tf.add(tf.matmul(l3, output_layer['weights']),output_layer['biases'])

        return output

def train_neural_network(x):

        prediction = neural_network_model(x)
        cost = tf.reduce_mean( tf.nn.softmax_cross_entropy_with_logits(prediction,y))
        optimizer = tf.train.AdamOptimizer().minimize(cost)

        hm_epochs = 4999

        with tf.Session() as sess:
            sess.run(tf.initialize_all_variables())

            for epoch in range(hm_epochs):

                sess.run([optimizer,cost], feed_dict = {x: input_X[epoch], y: encoded_y[epoch]})
                print('Epoch',epoch,'completed out of', hm_epochs)

The actual Error looks like:
%run "/Users/JaeWoo/Desktop/research/tensorpractice/DeepNeural.py"

train_neural_network(x)

W tensorflow/core/framework/op_kernel.cc:940] Invalid argument: shape must be a vector of {int32,int64}, got shape []

W tensorflow/core/framework/op_kernel.cc:940] Invalid argument: shape must be a vector of {int32,int64}, got shape []
... repeated for several times

InvalidArgumentError                      Traceback (most recent call last)

<ipython-input-86-7c7cbdae9b34> in <module>()

----> 1 train_neural_network(x)

/Users/JaeWoo/Desktop/research/tensorpractice/DeepNeural.py in

train_neural_network(x)

     67
     68         with tf.Session() as sess:
---> 69             sess.run(tf.initialize_all_variables())
     70
     71             for epoch in range(hm_epochs):

A: I think the error is how you defined the tf.placeholder. Try this instead
x = tf.placeholder(tf.float32,shape=[1,400])

if you're dealing with batches you might also want to define it like so
x = tf.placeholder(tf.float32,shape=[None,400])


text:
Q: Как собрать проект со всеми необходимыми библиотеками? Всем привет,в общем,я написал свой софт и продаю его.Но у большинства возникают проблемы,программа требует vcruntime140.dll.Можно ли как нибудь прикомпилировать ее к проекту или сделать чтоб программа не требовала никакие внешние библиотеки?Почему вообще программа на с++ требует какие то внешние библиотеки?Как это исправить?Устал каждому просто говорить скачивать все версии visual c++.Почему тогда другие программы у них не требуют эту библиотеку?

A: Я конечно удивлён что вы что то продаёте но при этом не знаете о рантайм либах но да ладно. Все эти либы идут вместе с инсталятором, самый простой вариант это тупо класть их рядом со своим софтом в инсталяторе. Более сложный это определять установлен ли необходимый vc runtime. Возможно вы встречали сообщение "Установить распространяемый компонент Microsoft Visual C++?" это вот оно.
Конкретных рекомендаций "Как собрать проект со всеми необходимыми библиотеками", дать сложно, всё зависит от конкретно вашего цикла CI/CD.


text:
Q: TimescaleDB timestamp types I have been using TimescaleDB for quite some time now and I was just wondering what the data types are for the timeseries data that it supports.
More specifically, I was wondering if UNIX timestamps are supported as time series data.

A: https://docs.timescale.com/api/latest/hypertable/create_hypertable/#returns -> units section a little further down

The 'time' column supports the following data types:
Timestamp (TIMESTAMP, TIMESTAMPTZ),
DATE,
Integer (SMALLINT, INT, BIGINT)


text:
Q: joomla tinymce editor problem hi i am using joomla 1.5 for my site.
in this i  fetched the problem of tinymce editor when i clicked on any article the image button are not shown. when i clicked on edit html source button It showing only "{$lang_theme_code_title}" on the Title bar and all body is blank.
so plz help me to resolved out from this problem.
thanks in advance

A: See this thread:
http://forum.joomla.org/viewtopic.php?t=62545
Try adding www. to your domain. Most often this is the problem.
I searched joomla project for vars $lang_theme_code_title... and related... There are not. Looked at Tinymce editor, it has javascript driven language file...
Most likely problem is cause by JavaScript. Try using different browser (firefox or chrome).
I read info on some other forums, some claim that temporarily disabling the antivirus solved the problem. I don't think that this will work, but you can try.
If none of this helps, you will need to give more information. Load firefox with firebug and see the NET tab for JavaScript files and Ajax Requests, most likely you'll find something interesting there (i think 500 Error)

A: You should consider trying the JCE editor instead of trying to debug Tinymce. I'm running JCE error free on over 40 sites. It has a superior image manager, link manager, and code view. It installs easily and is highly configurable. The only caveat is that you should disable the Joomla insert image, page break, and read more buttons as JCE has those built in.
http://extensions.joomla.org/extensions/edition/editors/88


text:
Q: Custom ArrayAdapter messing up views, with NullPointerException I am currently developing a content-creation application for Android. It´s main purpose is to let the user generate a list out of text and image entries (represented in the end by EditText and ImageView).
I hooked this list up to a ListView by writing a custom ArrayAdapter whilst using the ViewHolder Pattern
@Override
public View getView(int position, View convertView, ViewGroup parent) {

    // get current Entry
    Entry e = getItem(position);
    // variable for holding the view
    ViewHolder holder;

    // check if there is no view created
    if (convertView == null) {
        // prepare holder for view to be saved in
        holder = new ViewHolder();

        // get layout inflater
        LayoutInflater inflater = (LayoutInflater) super.getContext()
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);

        // if current entry is an image entry
        if (e.getType().equals(Entry.Type.IMAGE_ENTRY)) {
            // inflate layout with ImageView
            convertView = inflater.inflate(R.layout.image_list_item,
                    parent, false);
            ImageView iView = (ImageView) convertView
                    .findViewById(R.id.imageDisplay);

            // save inflated view in holder
            holder.imageViewItem = iView;

            // store the holder with the view
            convertView.setTag(holder);

            // if it is a text entry
        } else if (e.getType().equals(Entry.Type.TEXT_ENTRY)) {
            // inflate layout with EditText
            convertView = inflater.inflate(R.layout.text_list_item, parent,
                    false);
            EditText tView = (EditText) convertView
                    .findViewById(R.id.textField);

            // save inflated view in holder
            holder.editTextItem = tView;

            // store the holder with the view
            convertView.setTag(holder);

        }
    } else {
        // get holder from existing view
        holder = (ViewHolder) convertView.getTag();
    }
    if (e != null) {
        if (e.getType().equals(Entry.Type.IMAGE_ENTRY)) {
            // load corresponding image
            holder.imageViewItem.setImageBitmap(((ImageEntry) e).getImage());
        } else if (e.getType().equals(Entry.Type.TEXT_ENTRY)) {
            // load corresponding text
            holder.editTextItem.setText(((TextEntry) e).getText());
        }
    }
    return convertView;
}

Contrary to tutorials and examples I´ve seen I need to distinguish between the layouts I inflate due to the difference between text and image entries. And this seems to be causing some trouble because sometimes after adding different entries after another I get these exceptions
E/AndroidRuntime(15812): java.lang.NullPointerException: Attempt to     invoke virtual method 'void android.widget.EditText.setText(java.lang.CharSequence)' on a null object reference
E/AndroidRuntime(15812):    at <project>.util.EntryListAdapter.getView(EntryListAdapter.java:104)

So, it seems to me that the method gets called on the wrong view because otherwise there has to be an object of the type 'EditText'. I´m not quite certain when the ListView triggers all its views to be redrawn and I´ve been experimenting with my adapter and list a lot but I can´t work out why it sometimes messes up the calls for my entries. Can anyone help me there?

A: if you don't override getViewTypeCount, you will get only one null convertView, so you will initialize it with image_list_item.xml or text_list_item.xml. If you want to handle differnt types of views override
 public int getViewTypeCount() {
       return 2;
 }

to handle two different types of view, and getItemViewType
public int getItemViewType (int position) {
    Entry e = getItem(position);
    if (e.getType().equals(Entry.Type.IMAGE_ENTRY)) {
        return 0;
    }
    return 1;
}

and in getView check for the return value of getItemViewType

A: The ViewHolder pattern for ListView should be used when you know the view types of the positions before hand. If they are going to change dynamically when new positions are added (in essence if notifyDataSetChanged() is being called) then there are problems with the recycling.
For dynamically changing collections with different types of views it is better to use RecyclerView


text:
Q: Javascript: Render PNG stored as Uint8Array onto Canvas element without Data URI I'm trying to render a PNG image that is stored in a javascript Uint8Array.  The code that I originally tried was the following:
var imgByteStr = String.fromCharCode.apply(null, this.imgBytes);

var pageImg = new Image();
pageImg.onload = function(e) {

    // Draw onto the canvas
    canvasContext.drawImage(pageImg, 0, 0);

};

// Attempt to generate the Data URI from the binary
// 3rd-party library adds toBase64() as a string function
pageImg.src="data:image/png;base64,"+encodeURIComponent(imgByteStr.toBase64());

However, I found that for some reason the onload function was never running (I had breakpoints set up in chrome and it simply never hit).  I found that if I set the src to a URL instead of Data URI, it worked correctly.  However, due to some constraints, I cannot directly refer to the image's URL, i.e., it must be loaded from the UInt8Array.
Also, to complicate things slightly more, these images may be megabytes in size.  From what I have read, there are compatibility issues with attempting to use Data URIs for very large images.  Because of this, I am extremely hesitant to utilize them.
The question, therefore, is how do I render this byte array as a PNG onto a canvas context without using Data URIs or referring directly to the image URL?

I've also tried using something like the following to manipulate the image data directly using the putImageData function.  Keep in mind that I don't 100% understand how this function works
var imgdata = canvasContext.createImageData(this.baseHeight, this.baseWidth);
var imgdatalen = imgdata.data.length;
for(var i=0; i<imgdatalen; i++) {
    imgdata.data[i] = _this.imgBytes[i];
}
canvasContext.putImageData(imgdata, 0, 0);

It was lifted from a blog whose tab I have since closed, so apologies to the inspiration for not giving appropriate credit.

Also, while slowly hammering away at this thing, I ran into an error in Chrome SECURITY_ERR: DOM Exception 18.  Turns out that, as soon as an image is loaded inot a canvas using drawImage, it cannot be retrieved without some additional workarounds.  A Chromium Blog post on the topic was especially useful

A: Full Working Example: (save as .html file and open)
1: Creates Uint8Array.
2: Fills it with debug pattern.
3: Pastes it to canvas element on page.
Output should like like below:

<!DOCTYPE HTML >
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title> U8A_TO_CANVAS </title>
    <meta name   ="author"
          content="John Mark Isaac Madison">
    <!-- EMAIL: J4M4I5M7@HOTMAIL.com           -->
</head>
<body>
<canvas id="CANVAS_ID"
         width ="512"
         height="512">
</canvas>
<script>

var com     =  4 ; //:4 components( RGBA )
var wid     = 512;
var hig     = 512;
var tot_com = wid*hig*com;//:total#components
var u8a     = new Uint8Array( tot_com );

DrawDebugPattern  ( u8a , wid, hig              );
Uint8ArrayToCanvas( u8a , wid, hig, "CANVAS_ID" );

function Uint8ArrayToCanvas(
    u8a, //:uint8Array
    wid, //:width__of_u8a_data_in_pixels
    hig, //:height_of_u8a_data_in_pixels
    nam, //:name_id_of_canvas_on_dom
){

    //:Get Canvas:
    var can = document.getElementById( nam );
    if(!can){ throw "[FailedToGetCanvas]"; }

    //:Get Canvas's 2D Context:
    var ctx = can.getContext("2d");
    if(!ctx){ throw "[FailedToGetContext]"; }

    //:Use U8A to create image data object:
    var UAC = new Uint8ClampedArray( u8a,wid,hig);
    var DAT = new ImageData(UAC, wid, hig);

    //:Paste Data Into Canvas:
    var ORG_X = 0;
    var ORG_Y = 0;
    ctx.putImageData( DAT, ORG_X, ORG_Y );
}

function DrawDebugPattern(u8a,wid,hig){

    var com     = 4      ; //:RGBA==4components.
    var tot_pix = wid*hig;//:total#pixels

    //:Calculate point in center of canvas:
    var cen_x = wid/2;
    var cen_y = hig/2;

    //:Define a circle's radius:
    var rad_c = Math.min(wid,hig) / 2;

    //:Make a pattern on array:
    var d   = 0; //:d_is_for_distance
    var ci  = 0; //:Component_Index
    var pi  = 0; //:Pixel_Index
    var px  = 0; //:Pixel_X_Coord
    var py  = 0; //:Pixel_Y_Coord
    for( pi = 0; pi < tot_pix; pi++ ){

        //:Calculate index of first component
        //:of current pixel:
        ci = pi * com;

        //:Index_To_XY_Formula:
        px =  pi    % wid ;
        py = (pi-px)/ wid ;

        //:Decide if pixel is inside circle:
        var dx = (cen_x-px); //:delta_x
        var dy = (cen_y-py); //:delta_y
        d=Math.sqrt( (dx*dx)+(dy*dy) );
        if( d < rad_c ){
            //:INSIDE_CIRCLE:
            u8a[ ci + 0 ] = 0  ; //:Red
            u8a[ ci + 1 ] = 255; //:Green
            u8a[ ci + 2 ] = 0  ; //:Blue
            u8a[ ci + 3 ] = 255; //:Alpha
        }else{
            //:OUTSIDE_CIRCLE:
            u8a[ ci + 0 ] = 0  ; //:Red
            u8a[ ci + 1 ] = 0  ; //:Green
            u8a[ ci + 2 ] = 64 ; //:Blue
            u8a[ ci + 3 ] = 255; //:Alpha
        }

    }
}
</script>
</body>
<!-- In IE: Script cannot be outside of body.  -->
</html>

A: If you already have a UInt8Array, you should consider using Blob and createObjectURL; createObjectURL allocates a special URL that allows the browser to access an internally created blob of binary data as though it were a file being loaded externally.
Where it is supported, createObjectURL is an excellent alternative to huge data URIs. You may still need to fall back to use of data URIs in Opera, IE<10, and all but the most recent versions of mobile browsers.
var myArray; //= your data in a UInt8Array
var blob = new Blob([myArray], {'type': 'image/png'});
var url = URL.createObjectURL(blob); //possibly `webkitURL` or another vendor prefix for old browsers.

A: If you have the PNG data in memory (which I think is what you're describing) then you can create an image from it. In HTML it would look like:
 <img src="data:image/png;base64,KSjs9JdldhAlisflAkshf==" />

In JavaScript you can do the same:
var image = document.createElement('img');
    image.src = 'data:image/png;base64,' + base64Data;

Note that you can change the MIME type if you don't have PNG data.
You could then draw the image onto your canvas using context.drawImage(image, 0, 0) or similar.
So the remaining part of the puzzle is to encode the contents of your Uint8Array into Base 64 data.
var array = new Uint8Array(),
    base64Data = btoa(String.fromCharCode.apply(null, array));

The function btoa isn't standard, so some browsers might not support it. However it seems that most do. Otherwise you might find some code I use helpful.
I haven't tested any of this myself!


text:
Q: Jena getNsPrefixUri returning null (how to define base URI for OWL ontologies?) I'm trying to create a individual (instance) using Jena with the method below:
public void createInstance(String name) {
        String NS = ontology.getNsPrefixURI("http://james.miranda.br/Onto");
        OntClass class = ontology.createClass(NS + "Requisito");
        Individual instance = class.createIndividual(NS + name);
        System.out.println("Instance created:" + instance.getURI());
    }

ontology is a OntModel instance based on this ontology (some terms are in Portuguese). This method is not working, because the getNsPrefixURI is returning null.
When I iterate over the classes using the code below:
ExtendedIterator<OntClass> classIterator = ontology.listClasses();
        while (classIterator.hasNext()) {
            OntClass ontClass = classIterator.next();
            System.out.println(ontClass.toString());
        }

the (partial) result is:

http://james.miranda.br/Onto#Requisito
http://james.miranda.br/Onto#Micro
http://james.miranda.br/Onto#Certo
http://james.miranda.br/Onto#Objetivo
http://james.miranda.br/Onto#Individuo

Using getNsPrefixURI("") I have the NS http://www.w3.org/2002/07/owl and my method does not work too. I was looking for how to define the base uri here in SO, but the solution did not work in my case.
Trying to get the all the namespaces, I used the code:
Map<String,String> list = ontology.getNsPrefixMap();
System.out.println(list.toString());

The result is: {=http://www.w3.org/2002/07/owl#, xsd=http://www.w3.org/2001/XMLSchema#, rdfs=http://www.w3.org/2000/01/rdf-schema#, owl=http://www.w3.org/2002/07/owl#, rdf=http://www.w3.org/1999/02/22-rdf-syntax-ns#}.
I didn't receive the prefix for "http://james.miranda.br/Onto". Should it be declared anywhere?
Are there anything wrong with my code?

A: The documentation of getNsPrefixURI says "Get the URI bound to a specific prefix, null if there isn't one."  i.e. prefix in, URI out.
"http://james.miranda.br/Onto" is not a legal prefix.
There is no namespace prefix for http://james.miranda.br/Onto.
This does not set a prefix:
<Ontology rdf:about="http://james.miranda.br/Onto">

We would expect to see:
xmlns:onto="http://james.miranda.br/Onto#"


text:
Q: Ldap and Kerberos username correlation I am proxy between user and DB.
I got users list from Ldap.
I need to find the user connected using Kerberos to my proxy in the ldap users list.
What is data in Kerberos ticket that could be used for this search.
Or what is the way to implement such search?
Window, AD, MS Sql.

A: SID could be used as a unique identifier.
DB holds it but a binary representation of the SID.
SID should be converted to the string format.
In ldap it's "objectSID"


text:
Q: Name of numerical methods for second-order differential equation Numerical methods that try to solve first-order differential equations of the form:
$$    \frac{\partial}{\partial t} y = f(y,t) $$
are often Runge-Kutta methods, and there is a whole family of reasonably similar approaches.
Is there also an overarching name for numerical methods that try to solve the second-order-in-time differential equation?
$$    \frac{\partial^2}{\partial t^2} y = f(y,t) $$
Are there (families of?) methods to solve this problem in the same way that RK methods approach the first-order problem?


text:
Q: IntelliJ - compile all CoffeeScript files at once I use a CoffeeScript file watcher in IntelliJ to compile my CoffeeScript files. However, when I start the IDE, it does not interpret the files immediately. In the project structure, there are two files visible:

When I open the coffee file and change something, then the watcher is launched and compiles my script, which is also visible in the project structure:

Is there a way to tell IntelliJ that it should "precompile" all .coffee scripts in a project?
The problem is not only about the visibility of both .js and .coffee files. I want to store only .coffee files in the repository so initial compilation will be mandatory after the checkout.
I know I might use Grunt or even a coffee watcher to compile them, but my project involves a few really non-consoleable folks.


text:
Q: Problem with collision images, collision before touch Hi everyone I'm french so scuse me for my english.My problem is the following: I have an image in the center of the screen called viewToRotate, then I have an image called flakeView that is created outside of the screen and then it is moving to the center, and every  second a Timer does this(create a flakeView outside the screen and then move it to the center of the screen).
What I wanted to do was : if flakeView and viewToRotate collide reduce the alpha of viewToRotate to 0.5. But when flakeView appears on the screen the action of reducing the alpha is called without the collision of viewToRotate and flakeView, so they collide before they touches. I don't know why. How can I solve this please . Here is the code :
UIImageView* flakeView = [[[UIImageView alloc] initWithImage:flakeImage] autorelease];

// use the random() function to randomize up our flake attributes
int startY = round(random() % 320);

// set the flake start position
flakeView.center = CGPointMake(490, startY);
flakeView.alpha = 1;

// put the flake in our main view
[self.view addSubview:flakeView];

[UIView animateWithDuration:7
                 animations:^{
                     // set the postion where flake will move to
                     flakeView.center = viewToRotate.center;
                 }];
}

-(void)checkCollision{

if(CGRectIntersectsRect(flakeView.frame, viewToRotate.frame) == 1)
{
    viewToRotate.alpha=0.5;
}
}

A: I would not suggest using a timer on viewDidLoad. I believe that you should set the timer at some other function. Even if you do not use viewDidLoad for anything else.
The other thing is the UIView animations. Even if you have a timer at every 60fps the attributes of the animated objects are not changed by the animation. So before you create the animation you set those properties once. And when you create the animation you set the same properties for the second time. And that's it. From now on while the animation is running if you do checks on the properties you will always get the second values.
To have a working code one option is to create the UIView animations (and perform the property checks) for every step at a certain time interval. Or use OpenGL.

A: Before getting too deep into this issue, please also make sure that your viewToRotate.frame is actually sized the way you expect it (see my comment).
Once you are certain about those attributes, you might want to check the collision on the current presentationLayer of your animated objects and not on their original state.

UIView.layer.presentationLayer
  Returns a copy of
  the layer containing all properties as
  they were at the start of the current
  transaction, with any active
  animations applied.

So you might adapt your collision detection like this:
-(void)checkCollision
{
    if(CGRectIntersectsRect(flakeView.layer.presentationLayer.frame, viewToRotate.layer.presentationLayer.frame) == 1)
    {
        viewToRotate.alpha=0.5;
    }
}

Also consider using the CoreAnimation Layer method hitTest: instead of your handmade collision detection.

hitTest: Returns the farthest
  descendant of the receiver in the
  layer hierarchy (including itself)
  that contains a specified point.

A: These are the following things you would want to check.

*

*Dont init with image, use init with frame and then do
flakeView.image = ----; Because your image could be wide enough
initially , and hence colliding from the time you initialize.

*Try alternatives to .center, like .frame.size.x , because I have had
problems with .center as well

*You could probably NSLog the bounds of both ur imageviews before and
after reducing alpha


text:
Q: export CSV file, and downloaded by the browser, using express js var csv = require('fast-csv');
var fs = require('fs');
const app = express();

exportCSVfile: function(req, res){
    var ws = fs.createWriteStream('my.xls');
    console.log(req.body.save);
    session = req.session;
    if(session.uniqueID){
        if(session.uniqueID.access == 2){
            csv.write([
                ["a1","b1"],
                ["a2","b2"]
            ],{headers:true}).pipe(ws);
        }
    }
}

that is my current code, i can get the csv file, but rather than directly write on my disk, i want to make the browser download it. how can i to do that?

A: First write out a response header setting proper content type and disposition for download.
res.writeHead(200, {
    'Content-Type': 'text/csv',
    'Content-Disposition': 'attachment; filename=' + csvFileName
});

Then simply pipe the stream created by csv() to response.
csv.write([...]).pipe(res);

A: You can use attachment() function to attach your file to response. You can try something like this
var stream = fs.createReadStream(filename);
res.attachment(filename);
stream.pipe(res);


text:
Q: How to change the text of a label using tkinter by clicking a button I am quite new to Python, but when I click on one of the buttons, I want the text of the label (the label that has "ctext" in the buttonClicked function) to change based on what formula I want it to be. I tried adding a value to the buttonClicked function, but when I did that it made the "command=buttonClicked(value)" static and didn't happen after I clicked the button.
Here's a portion of my code:
def buttonClicked():

    formulac = tk.Label(root, text='Formula:')

    formula = tk.Label(root, text= ctext) #"Insert formula" must be a string variable

    formulac.config(font=("helvetica", 30))

    canvas1.create_window(1500, 150, window = formulac)

    formula.config(font=("helvetica", 30))

    canvas1.create_window(1500, 200, window=formula)

    entry1 = tk.Entry(root)

    canvas1.create_window(1500, 250, window=entry1)

ctext = "Square"

formula1 = tk.Button(text= "Formula", command= buttonClicked, bg="brown", fg = "white", font =("helvetica", 9))

canvas1.create_window(120, 100, window = formula1)

formula2 = tk.Button(text= "Formula", command= buttonClicked, bg="brown", fg = "white", font =("helvetica", 9))

canvas1.create_window(120, 130, window = formula2)

A: "How to change the text of a label using tkinter by clicking a button" You can use label.config(text='something'):
from tkinter import *

root = Tk()

def change():
    label.config(text='changed')

button = Button(root, text='click', command=change)
label = Label(root, text='click button')

button.pack()
label.pack()

root.mainloop()


text:
Q: Question about curves and Puiseux series Let $f\in\mathbb{Z}[x,y]$ be an irreducible over $\mathbb{Z}$ polynomial such that $f(0,0)=0$. I'm trying to understand the uses of Puiseaux series $y(x)$ in the variable $x$ to solve the equation $f(x,y)=0$ i.e. to find points in the curve $X=\{(x,y)\in\mathbb{C}:f(x,y)=0\}$.  My question is that is it true that it can be done globally, more precise, i.e. are Puiseaux series $y_1,\dots,y_n$ such that
$$f(x,y)=(y-y_1(x))\dots(y-y_n(x))\tag{$\star$}$$
for all $(x,y)\in X$  (independently of this point being a singularity of the curve or not)? If not, what are the requirements on the point $(x,y)\in X$ so that the decomposition $(\star)$ holds.


text:
Q: prevent POST-request from caching When I try to make a jquery ajax "Type:Post" request, I get an 404 not found (from cache) error. I've tried several workarounds to fix this problem but it doesn't worked. This are the workarounds I've tried:

*

*Adding header information in ajax call:
"Cache-Control" : "private, no-cache, no-store, must-revalidate",
"Expires" : "0",

*jquery ajax "cache:false"

*add rnd URL param, "?nocache=' + new Date().getTime()",

*tried to disable AppCache (nativ):
"super.appView.getSettings().setAppCacheEnabled(false);"
This is the response I get from this POST request when I debug my Cordova App with dev tools:
http://pl.vc/59s6o

A: Try setting your headers in the $.ajaxSetup
$.ajaxSetup({
   type: 'POST',
   headers: { "cache-control": "no-cache" }
});

We can help you more if you tell us more about your situation and include your code.


text:
Q: Conditional subsetting by group Example data:
mydf<-data.frame(Group_ID=c("337", "337", "201", "201", "470", "470", "999", "999"),
                              Timestamp=c("A", "A", "B", "B", "C", "D", "E", "F"),
                              MU=as.numeric(c("1", "1", "2", "3", "4", "4", "5", "6")))

Gives:
    Group_ID Timestamp MU
         337         A  1
         337         A  1
         201         B  2
         201         B  3
         470         C  4
         470         D  4
         999         E  5
         999         F  6

Where MU is greater than 1, I would like to only retain the first entry within Group_ID. Where MU is <= 1, I would like to keep all entries for that group. Thus,
Desired result:
    Group_ID Timestamp MU
         337         A  1
         337         A  1
         201         B  2
         470         C  4
         999         E  5

I've made many attempts, the closest being the example below. However, this solution is wrong because it excludes all entries where MU <= 1.
Best attempt:
mydf <- mydf[(mydf$MU >= 1),] %>%
  group_by(Group_ID) %>%
  slice(1:1)

Returns undesired result (all MU <= 1 excluded rather than retained):
Group_ID Timestamp    MU
     201         B     2
     337         A     1
     470         C     4
     999         E     5

I'm surprised this attempt doesn't work, what's it missing? I've also tried ifelse statements. Many thanks in advance

A: mydf %>%
    group_by(Group_ID) %>%
    filter(cumsum(MU > 1) <= 1) %>%
    ungroup()
## A tibble: 5 x 3
#  Group_ID Timestamp    MU
#  <fct>    <fct>     <dbl>
#1 337      A             1
#2 337      A             1
#3 201      B             2
#4 470      C             4
#5 999      E             5

Base R equivalent would be
mydf[with(mydf, ave(MU > 1, Group_ID, FUN = cumsum) <= 1),]

A: You can use which within slice to select the desired row indices.
edit: not clear to me what to do when there are rows with MU <= 1 and rows with MU > 1 in the same group. This answer keeps the MU <= 1 rows for that group and the first MU > 1 row.
mydf %>%
  group_by(Group_ID) %>%
  slice(c(which(MU <= 1), head(which(MU > 1), 1)))

# # A tibble: 5 x 3
# # Groups:   Group_ID [4]
#   Group_ID Timestamp    MU
#   <fct>    <fct>     <dbl>
# 1 201      B             2
# 2 337      A             1
# 3 337      A             1
# 4 470      C             4
# 5 999      E             5

A: We can do a group by 'Group_ID' and slice based on whether there are any element in 'MU' greater than 1
library(dplyr)
mydf %>%
  group_by(Group_ID = factor(Group_ID, levels = unique(Group_ID))) %>%
  slice(if(any(MU> 1)) 1 else row_number() )
# A tibble: 5 x 3
# Groups:   Group_ID [4]
#  Group_ID Timestamp    MU
#  <fct>    <fct>     <dbl>
#1 337      A             1
#2 337      A             1
#3 201      B             2
#4 470      C             4
#5 999      E             5

A: This should work for you. It adds a couple lines, so it's not quite as concise, but it's still quick and easy.
mydf1 <- mydf[(mydf$MU > 1),] %>%
    group_by(Group_ID) %>%
    slice(1:1)
mydf2 <- rbind(mydf[(mydf$MU <= 1),],as.data.frame(mydf1))
mydf2


text:
Q: In Eclipse Debugger, getting the index location of a variable in an embeded list hierachy Is anyone familiar with a debugging option that has the feature? I have a list of items in a JComboBox deeply embedded in a swing app that is buried withing multiple lists. Is there is away to find the index of these items in the Eclipse Debugger without writing code? I could manually write down the index of every list, but I'm looking for an easier way to tell me that this location is at parent[2].layer[0].child[3].layer[1].child[0].combobox[4].item[5]
without looking scrolling through the variable list.
Thanks!

A: When debugging, in the variables/Expressions pane, at the top right there should be a button with an arrow going to the right called "Show Logical Structure".
If you tick/untick that it should change the display of list structures. It might help you out.


text:
Q: Wifi is not working in hcl me laptop I'm using a HCL ME notebook l 1044. previously i had Windows 8 32 bit installed, and the hotkeys for activating and deactivating wifi are working properly  fn + F2.
until I upgraded to Windows 8.1 64 bit. Now the hotkey does not work, even after I've installed the 64 bit hot key program.
i am using dual operating system while turning on wifi from another os i can use wifi in  windows 8.1.
it mean the wifi driver is working fine , but i am not able to turn on or off the wifi via hotkey (Keyboard).
How would I solved it please help.
thanks in advance.

A: You need to install the wifi driver in your HCL ME Notebook in order to your wireless connection to work.


text:
Q: probability of the product of drawn numbers is positive We have just started learning probability in class, and have done one lesson on basic combinatorics, I'm going through some practice questions and have stumbled upon a few.
The first is:

A box contains $20$ numbers, of which $8$ are negative and $12$ are positive. If $6$ numbers are picked without replacement, find the probability their product will be positive.

Rough solution I have so far: probability of the product being positive is
$$ \frac{\binom 6{12}}{\binom 6{20}}$$
Am I headed in the right direction ?

A: First count the number of total ways to pick the $6$ numbers. Since you have $20$ to choose from, this is simply $\dbinom{20}{6}.$
Now count the successful ways using casework. To end up with a positive number, you can have all negative, $2$ positive and $4$ negative, $4$ positive or $2$ negative, or all positive. Using summation notation, this count is
$$\sum_{n = 0}^{3}\dbinom{12}{2n}\dbinom{8}{6 - 2n}.$$
If we evaluate that summation, we get a total of $19,432$ ways to have a positive product.
Our probability is $P = \frac{19,432}{\dbinom{20}{6}} = \boxed{\frac{2429}{4845}}.$


text:
Q: How to use angular material select with string map I am trying to use the angular material with a string map which is filled from my backend (works) it after getting filled it has the following values: {key: ..., value: ...} but my select stays empty if I click on it it does not show me any values to select from. Can someone from you look at it and tell me what is wrong?
This is my html (only select):
<mat-select formControlName="legitimiertGwg" multiple >
    <mat-option *ngFor="let person of personArray" [value]="person.key">{{person.value}}</mat-option>
  </mat-select>

This is my ts file (only map):
  personArray = new Map<string, number>();

A: You have to tell Angular to get for...loop iterations as [key, value] pair by adding the pipe "keyvalue" like below:
<mat-select formControlName="legitimiertGwg" multiple >
    <mat-option *ngFor="let person of personArray | keyvalue" [value]="person.key">
        {{person.value}}
    </mat-option>
</mat-select>


text:
Q: Question on Guard Clause (error message) I am not sure why these codes (where Guard Clauses (for FirstName and LastName) are) do not show the result of data on the VF page.
Am I missing something on VF page or is the order of logic causing the issue?
public PageReference searchPatients(){

    RowList = new List<TableRow2>();
    TableRow2 tr;

    if (lname != null && lname.length() < 3)
    {
        ApexPages.addMessage(new ApexPages.Message(
        ApexPages.Severity.ERROR, 'Please specify at least three characters of Last Name'
        ));
        return null;
    }

    if (fname != null && fname.length() < 3)
    {
        ApexPages.addMessage(new ApexPages.Message(
        ApexPages.Severity.ERROR, 'Please specify at least three characters of First Name'
        ));
        return null;
    }

    String bind_fname = string.isBlank(fName) || fname.length() <3 ? null : (fname.left(3) + '%');
    String bind_lname = string.isBlank(lname) || lname.length() <3 ? null : (lname.left(3) + '%');

    for(Patient__c con : [SELECT sfprn__c,
                                mrn__c,
                                LName__c,
                                FName__c,
                                (select SurveySelection__c.SurveySelection__c from SurveySelections__r)
                                FROM Patient__c
                                where ( mrn__c =:mrn )
                                or ( LName__c LIKE :bind_lname and FName__c LIKE :bind_fname ) LIMIT 1
                                ]){
        tr = new TableRow2();
        tr.sfprn = con.sfprn__c;
        tr.mrn = con.mrn__c;
        tr.lname = con.LName__c;
        tr.fname = con.FName__c;
        tr.SurveySelection = con.SurveySelections__r.isEmpty() ? null : con.SurveySelections__r[0].SurveySelection__c;

        RowList.add(tr);
        return null;

Here is VF markup.
<apex:page Controller="psw" showHeader="false" sidebar="false">
<apex:form >
<apex:pageBlock >

    <apex:pageBlockButtons location="top">
        <apex:pageMessages id="msgs" />

        <apex:commandButton value="Search" action="{!searchPatients}" rerender="msgs"/>
    </apex:pageBlockButtons>

    <!-- Other stuff -->

 </apex:pageBlock >
</apex:form >

A: It should be an or condition:
if (lname == null || lname.length() < 3)

In plain English, "if lname is empty, or lname's length is less than 3, then..."

A: I found the solution. It was due to location of "apex:pageMessages" was in VF page.  I had to move  "apex:pageMessages id="msgs"/
from inside "apex:pageBlockButtons" to "apex:pageBlockSection".


text:
Q: how to stop re-rendering components (React-redux )? I'm using react-router-redux and have nested connect()ed components. This seems to work fine, except that my nested components are re-rendering when state changes.
Probs:
Root have 5 children:
All components are re-rendering if there is any state changes in any one of the children because all components are connect()ed.
How can I render only the required children alone?
(is there any way to using connectAdvanced life cycle method for resolve this probs?

A: To prevent the nested children from being re-rendered every time your state changes in the parent component you should use shouldComponentUpdate life cycle.
shouldComponentUpdate takes in 2 parameters shouldComponentUpdate(nextProps, nextState)
So anywhere you want to stop re rendering you should return false. As per the docs "Returning false does not prevent child components from re-rendering when their state changes."
ShouldComponentUpdate Docs


text:
Q: Shuffling buttons I am trying to shuffle buttons on empty border with a shuffle key. All buttons positions set manually. I want to be like that "banks' virtual keyboards". Just numbers between 0-9.
int [][]b = {{6, 5},{66, 5},{126, 5},{6, 68},{66, 68},{126, 68},{6, 131},{66, 131},{126, 131},{6, 194}};

They are my coordinates. Just shuffle them on my empty border. I know how do I on grid layout.


text:
Q: Two point boundary with odeint I am trying to solve two point boundary problem with odeint. My equation has the form of
y'' + a*y' + b*y + c = 0

It is pretty trivial when I have boundary conditions of y(x_1) = y_1 , y'(x_2) = y_2, but when boundary conditions are y(x_1) = y_1 , y(x_2) = y_2 I am lost. Does anybody know the way to deal with problems like this with odeint or other scientific library?

A: In this case you need a shooting method. odeint does not have such a method, it solved the initial value problem (IVP) which is your first case. I think in the Numerical Recipies this method is explained and you can use Boost.Odeint to do the time stepping.

A: An alternative and more efficient method to solve this type of problem is finite differences or finite elements method. For finite differences you can check Numerical Recipes. For finite elements I recommend dealii library.
Another approach is to use b-splines: Assuming you do know the initial x0 and final xfinal points of integration, then you can expand the solution y(x) in a b-spline basis, defined over (x0,xfinal), i.e.
y(x)= \sum_{i=1}^n A_i*B_i(x),

where A_i are constant coefficients to be determined, and B_i(x) are b-spline basis (well defined polynomial functions, that can be differentiated numerically). For scientific applications you can find an implementation of b-splines in GSL.
With this substitution the boundary value problem is reduced to a linear problem, since (am using Einstein summation for repeated indices):
A_i*[ B_i''(x) + a*B_i'(x) + b*B_i(x)] + c =0

You can choose a set of points x and create a linear system from the above equation. You can find information for this type of method in the following review paper "Applications of B-splines in Atomic and Molecular Physics"  - H Bachau, E Cormier, P Decleva, J E Hansen and F Martín
http://iopscience.iop.org/0034-4885/64/12/205/
I do not know of any library solving directly this problem, but there are several libraries for B-splines (I recommend GSL for your needs), that will allow you to form the linear system. See this stackoverflow question:
Spline, B-Spline and NURBS C++ library


text:
Q: Two side Printing issue in vb6 Hi guys i am developing a vb6 application to print an ID card for students. I need to print on both sides of the card. I write the code in the way as shown below
Printer.Duplex = vbPRDPHorizontal
"Printing front side function"
Printer.NewPage
"Printing backside Function"
Printer.EndDoc

While executing the code i getting an error cannot assign a value to printer.Duplex, also can't able to print on both sides
Kindly help me guys to resolve the issue...!


text:
Q: How can i change Feature Importance so it isn't random anymore? in Python I am doing feature selection using feature importance which is based on a decision tree.
#Feature importance (source: https://towardsdatascience.com/feature-selection-techniques-in-machine-learning-with-python-f24e7da3f36e)
X = df.iloc[:,1:31]  #independent columns
y = df.iloc[:,0]    #target column = diagnosis

model = ExtraTreesClassifier()
model.fit(X,y)
print(model.feature_importances_) #use inbuilt class feature_importances of tree based classifiers

feat_importances = pd.Series(model.feature_importances_, index=X.columns)
feat_importances.nlargest(10).plot(kind='barh', color="lightskyblue")
plt.show()

But the results change everytime i start it again, probably somewhere there is a random number somewhere. Is there a way to set this once and then keep it the same so that the results don't change everytime the kernel is restarted?
Thank you.
UPDATE: I think I managed it using:
model = ExtraTreesClassifier(random_state=1)
is that the right way to do it?

A: You can set a random_state parameter of ExtraTreesClassifier to some value. In this case you will get reproducible results.
For example:
model = ExtraTreesClassifier(random_state=0)


text:
Q: setInterval stops after reload browser I'm making auto-logout feature in Angular.
So I use setInterval for this, but, setInterval doesn't work after reloading the browser. I mean the timer disappears after reloading.
If not reload, everything is fine.
If you have any ideas to resolve this issue, please reply to me. Thank you.
Here's my code
this.ngZone.runOutsideAngular(() => {
      this.timer = setInterval(() => {
        this.check();
      }, CHECK_INTERVALL);
    })


text:
Q: Android schedule fast task I have a problem with events schedulation. I need to change text color every fixed time. Range of this is between 100ms and 300ms. I've tried to use Android Timer - TimerTask but after 10-15 Thread the rendering is delayed then I lost real time update. I've tried also to use Thread.sleep() but I've had an exception with MainThreadActivity. Timer problem I think that is JVM Thread allocation or at most a concurrency problem. I asked you what is the best way for scheduling fast event with fixed delay in Android and if my approach is correct.
Thank you in advance.
Fabio

A: Try something like this:
final static int REFRESH_TIME_MS = 100;
final static int REFRESH_TIME_MS_2 = 200;

Runnable mPeriodicTask = new Runnable() {
    public void run() {
        //do what you want
    }
};

Runnable mPeriodicTask_2 = new Runnable() {
    public void run() {
        //do what you want
    }
};

@Override
public void onCreate(Bundle savedInstanceState) {
    ScheduledExecutorService executor = Executors.newScheduledThreadPool(2);
    executor.scheduleAtFixedRate(mPeriodicTask, 0, REFRESH_TIME_MS, TimeUnit.MILLISECONDS);
    executor.scheduleAtFixedRate(mPeriodicTask_2, 0, REFRESH_TIME_MS_2, TimeUnit.MILLISECONDS);
}

A: Try the CountDownTimer. It's executed on the UI Thread and gives you information on exactly how much time passed since the last invocation.
Adding an example to be more clear:
Let's say you want to update the view after 300 ms ,150 ms and 75 ms
that makes the total time 525ms and the minimum interval 50ms
so:
    private class TestCT extends CountDownTimer{

            private long mFirstTime;
            private long mTotalTime;
            private long mLastRecognizedEvent=0;

            public TestCT(long millisInFuture, long countDownInterval, long firstEventTime) {
                super(millisInFuture, countDownInterval);
                mTotalTime=millisInFuture;
                mFirstTime=firstEventTime;
            }

            @Override
            public void onTick(long millisUntilFinished) {
                long elapsed=mTotalTime-millisUntilFinished;
                elapsed-=mLastRecognizedEvent;
                if(elapsed>=mFirstTime){
                    updateTheView();
                    mLastRecognizedEvent+=mFirstTime;
                    mFirstTime=mFirstTime/2;
                }
            }

            @Override
            public void onFinish() {
                updateTheView();

            }

        }

new TestCT(525,50,300).start();

Not tested this so not 100% sure will work but it should give you an idea


text:
Q: Error: NoSuchMethdError: La clase '_InternalLinkedHashMap' no tiene no tiene captador de instancias 'fecha' Please help me with my code.
The code is written in flutter.
I am trying to request appointments through APIREST in laravel using the table_calendar method in flutter. The problem is that when requesting  the day the appointment is cited, the following error appears:
Error
I am using this method and put it in my FutureBuilder to compare it with my snapshot inside my getData() class (which is the one that receives the data from my API to send to call the database).
I want to see nothing but the appointment is marked on the date that the appointment has
class CitaList extends StatefulWidget {
  @override
  _CitaListState createState() => _CitaListState();
}

class _CitaListState extends State<CitaList> {
  List<dynamic> list;
  Future<List> getData() async {
    final response = await http.get("http://192.168.0.6:8000/api/auth/cita");
    return json.decode(response.body);
  }

  CalendarController _calendarController;
  UsuarioProvider usuarioProvider;
  Map<DateTime, List<dynamic>> _groupedEvents;
  @override
  void initState() {
    super.initState();
    _calendarController = CalendarController();
    // getData().th-en((value) => _fetchEvents());
  }

  _groupEvents(List<dynamic> events) {
    _groupedEvents = {};
    events.forEach((event) {
      event = event["Fecha"].split("/");
      final eventDay = int.parse(event[1]);
      DateTime date = DateTime.utc(eventDay);
      if (_groupedEvents[date] == null) _groupedEvents[date] = [];
      _groupedEvents[date].add(eventDay);
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Citas'),
      ),
      body: SingleChildScrollView(
        child: FutureBuilder<List>(
            future: getData(),
            builder: (context, snapshot) {
              if (snapshot.hasData) {
                final events = snapshot.data;
                _groupEvents(events);
                DateTime selectedDate = _calendarController.selectedDay;
                list = _groupedEvents[selectedDate] ?? [snapshot.data];
                return SizedBox(
                  child: Column(
                    children: [
                      Card(
                        clipBehavior: Clip.antiAlias,
                        margin: EdgeInsets.all(8.0),
                        child: TableCalendar(
                          events: _groupedEvents,
                          weekendDays: [6],
                          initialCalendarFormat: CalendarFormat.month,
                          availableCalendarFormats: {
                            CalendarFormat.month: 'Meses',
                            CalendarFormat.week: 'Semanas'
                          },
                          locale: 'es_ES',
                          calendarStyle: CalendarStyle(
                            todayColor: Colors.orange,
                            selectedColor: Theme.of(context).primaryColor,
                            todayStyle: TextStyle(
                                fontWeight: FontWeight.bold,
                                fontSize: 18.0,
                                color: Colors.white),
                          ),
                          headerStyle: HeaderStyle(
                              decoration: BoxDecoration(
                                color: Theme.of(context).primaryColor,
                              ),
                              headerMargin: EdgeInsets.only(bottom: 8.0),
                              titleTextStyle: TextStyle(
                                  color: Colors.white, fontSize: 18.0),
                              centerHeaderTitle: true,
                              formatButtonDecoration: BoxDecoration(
                                color: Colors.orange,
                                borderRadius: BorderRadius.circular(20.0),
                              ),
                              formatButtonTextStyle: TextStyle(
                                  color: Colors.white, fontSize: 15.0),
                              formatButtonShowsNext: false,
                              leftChevronIcon:
                                  Icon(Icons.chevron_left, color: Colors.white),
                              rightChevronIcon: Icon(
                                Icons.chevron_right,
                                color: Colors.white,
                              )),
                          startingDayOfWeek: StartingDayOfWeek.monday,
                          onDaySelected: (date, events, holidays) {
                            setState(() {});
                          },
                          builders: CalendarBuilders(
                            selectedDayBuilder: (context, day, events) =>
                                Container(
                              margin: const EdgeInsets.all(4.0),
                              alignment: Alignment.center,
                              decoration: BoxDecoration(
                                  color: Theme.of(context).primaryColor,
                                  borderRadius: BorderRadius.circular(10.0)),
                              child: Text(
                                day.day.toString(),
                                style: TextStyle(color: Colors.white),
                              ),
                            ),
                            todayDayBuilder: (context, day, events) =>
                                Container(
                              margin: const EdgeInsets.all(4.0),
                              alignment: Alignment.center,
                              decoration: BoxDecoration(
                                  color: Colors.orange,
                                  borderRadius: BorderRadius.circular(10.0)),
                              child: Text(
                                day.day.toString(),
                                style: TextStyle(color: Colors.white),
                              ),
                            ),
                          ),
                          calendarController: _calendarController,
                        ),
                      ),
                      Padding(
                        padding: const EdgeInsets.only(left: 12.0, top: 8.0),
                        child: Text(
                          DateFormat('M/dd/yyyy').format(selectedDate),
                          style: Theme.of(context).textTheme.headline6,
                        ),
                      ),
                      ListView.builder(
                        shrinkWrap: true,
                        physics: NeverScrollableScrollPhysics(),
                        itemCount: list == null ? 0 : list.length,
                        itemBuilder: (context, i) {
                          return Container(
                            padding: EdgeInsets.all(10.0),
                            child: GestureDetector(
                                child: ListTile(
                              title: Text('Titulo'),
                              subtitle: Text(list[i]['Fecha']),
                              trailing: IconButton(
                                icon: Icon(Icons.edit),
                                onPressed: () => Navigator.of(context).push(
                                    MaterialPageRoute(
                                        builder: (BuildContext context) =>
                                            DetailCita(
                                              list: list,
                                              index: i,
                                            ))),
                              ),
                            )),
                          );
                        },
                      ),
                    ],
                  ),
                );
              }
              return CircularProgressIndicator();
            }),
      ),
      floatingActionButton: FloatingActionButton(
        child: Icon(Icons.add),
        backgroundColor: Theme.of(context).primaryColor,
        onPressed: () {
          Navigator.push(
            context,
            MaterialPageRoute(
              builder: (context) => AddCita(
                selectedDate: _calendarController.selectedDay,
              ),
            ),
          );
        },
      ),
    );
  }
}

I would really appreciate your help as I am stuck.

A: The issue is in method _groupEvents().
In your getData() method, you retrieve a JSON and parse/decode it. I assume that JSON you get from the API is a list. That's OK. But when you json.decode it, that returns a List<Map<String, dynamic>>. That's the standard return type. It isn't any weird type, it's the standard.
So, in your FutureBuilder builder property, you pass the retrieved snapshot (remember the type: List<Map<String, dynamic>>) to the _groupEvents() method, which then treats it as a List of some object type that you didn't specify. You have a type mismatch there.
In order to solve it: Inside your events.forEach loop, you have to cast each element of your events List to the correct object type before calling the date property on it.


text:
Q: str() functions and return str object from int object The python documentation explains the str() function.
But what do mean by
"Return a string version of object."
if i do this
i=1
j=str(i)

function str() make copy of int object i and return str object as presentation?

A: The str() method returns the string representation of a given object.
i=1
j=str(i)

This means that j is a string representation of i (j is a copy of a but as string)
For the encoding, it is used with byte objects which are defined by the bytes() method.
# declare a byte object
b = bytes('pythön', encoding='utf-8')
# convert a utf-8 byte object to ascii with errors ignored
print(str(b, encoding='ascii', errors='ignore'))

# convert a utf-8 byte object to ascii with strict error
print(str(b, encoding='ascii', errors='strict'))

Output :
pythn
UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 4: ordinal not in range(128)

A: No in the sense that str() returns an object, it doesn't directly copy it into a new variable.
Yes in the sense that your code makes a variable named j and stores i converted to a string in it ("copy").
"Return" means a function changes to become a value. str(1) returned "1" (string) and you assigned it (with =) to j, so j is "1".


text:
Q: Use MongoDB as internal analytics tools all
I was reading a real-world system design doc
http://highscalability.com/blog/2010/3/16/justintvs-live-video-broadcasting-architecture.html?lastPage=true&postSubmitted=true
Important detail is
1.MongoDB - used for their internal analytics tools.
2.They have added monitoring to everything. Every click, page view, and action is measured to help improve service. Log messages from the front-end, web call, or from an application server are converted to syslog messages and forwarded through syslog-ngto a single log host. They scan through the data, load it into MongoDB, and run queries on MongoDB.
Q:
It mentioned that MongoDB is used for store monitoring message.
Why we use MongoDB here? I know MongoDB is best for document-store.
So is industry logging message a document format?


text:
Q: AlphaBlend a child form I'm looking after a way to AlphaBlend a child form, if possible using layered windows as there will be interactive controls behind it.
The problem is I have a component in a regular TForm that paints multiple visual layers (drawings, pictures...). At some point I need to instantiate an editor control on this form (in-place), this control will involve a variety of standard input controls outside of my control (edit box, check box, etc.), however I would like to overlay the layers in front of the layer being edited using alpha blending (and WS_EX_TRANSPARENT to make it click-through).
I first thought of using child forms for that (borderless TForms parented to the component), and that works alright, up to the point where the AlphaBlended TForm isn't alphablended at all, but turns opaque as soon as parented...
I then tried to unparent the alphablended form, set it to fsStayOnTop, and by reacting to the relevant events, keep it in front of the component on screen, that works, but that isn't a truly satisfying solution: the alphablended StayOnTop form is also in front of other modal and modeless forms of the application, should the user decide to move them in front of the component...
So, any other ideas on a way to have a child form be alphablended? (or behave like it is)

A: According to MSDN you are out of luck, as WS_EX_LAYERED cannot be used for child windows.
Maybe you could hide all editor forms when your form / application loses focus, that would at least keep them from being on top of other windows. Still, it's unsatisfactory...


text:
Q: Closing application after pressing back button, not returning to previous activity problem:
Working scenario:
I have a MainMenuActivity and when i start another activity and press Back Button it return to previous activity,but...
Problem scenario: When I start Activity B, from Activity A, and then press Home button and i after few seconds back to application, and then press Back button application is closed/minimalized. But i want after minimalized application can go back to Activity A.
Any idea how to do it?


text:
Q: Two-way binding in custom component not working I've created a component like this:
templates/components/files-dropzone.hbs

Awesome text

<textarea id="drop-textarea" rows="10" cols="50">
  {{value}}
</textarea>

components/files-dropzone.js
import Ember from 'ember';

export default Ember.Component.extend({
  value: '',

  valueChanged: function() {
    console.log("yup")  // is never triggered
  }.observes('value'),
})

I'm using this component like this in another template:
<div class="large-7 columns padding-left-reset"
  {{files-dropzone value=body}}

While the textarea contains the correct value for body when I load the page it doesn't bind it. I'm observing body and it doesn't change when I change the text inside the textarea.
EDIT: The value-attribute in the component itself doesn't change as well
What am I doing wrong?

A: I don't think that Ember knows that it should bind the {{value}} to the text area.
It should work, using the textarea helper:
{{textarea value=value id="drop-textarea" rows="10" cols="50"}}

Do you want to adapt the behaviour of the text area in some way?


text:
Q: caching of generated xml in asp.net I am generating XML using linq to XML (XElements etc) from the database and with specific times.  The biggest issue is that this XML will not change that often so i am trying to cache it in the code behind.
Basically my code looks something like this:
XDocument x = new XDocument(
    new XElement(ns + "SomeRandomDate", DateTime.Now())
);

Response.Clear();
Response.ContentType = "application/xml";
Response.Cache.SetExpires(DateTime.Now.AddSeconds(60));
Response.Cache.SetCacheability(HttpCacheability.Public);
Response.Cache.SetValidUntilExpires(false);
Response.Cache.VaryByParams["Category"] = true;
x.Save(Response.Output);
Response.End();

My biggest issue is that this does not seem to be working.
Any ideas?

A: Why not use the HTTP cache?
XDocument x = (XDocument)HttpContext.Current.Cache[ns + "SomeRandomDate"];
if (x == null)
{
  x = new XDocument(new XElement(ns + "SomeRandomDate", DateTime.Now()));
  HttpContext.Current.Cache.Insert(ns + "SomeRandomDate", x, null,
    DateTime.Now.AddHours(12d), Cache.NoSlidingExpiration);
}


text:
Q: Pyspark "due to data type mismatch: differing types" error in Boolean column creation I am creating boolean columns and filtering if anyone is false in the downstream.
I created the below boolean column in my Pyspark code and it working. I am
df = spark.read.parquet(data_url)
df = df\
    .withColumn('d1d3_filter', (df.d1_submit_date.isNotNull() &
                                (df.d1_review_date.isNull())))\
    .withColumn('d41_filter', (df.d4_submit_date.isNotNull() &
                               (df.d4_review_date.isNull())))\
    .withColumn('d42_filter', (df.d42_submit_date.isNotNull() &
                               (df.d42_review_date.isNull())))\
    .withColumn('d45_filter', (df.d5_submit_date.isNotNull() &
                               (df.d5_review_date.isNull())))\
    .withColumn('d6_filter', (df.d8_submit_date.isNotNull() &
                              (df.d8_review_date.isNull())))

But I need to add another condition, it's throwing an error "due to data type mismatch: differing types  in d1_review_date IS NULL) OR d1_status)' (boolean and string)"
df = spark.read.parquet(data_url)
df = df\
    .withColumn('d1d3_filter', (df.d1_submit_date.isNotNull() &
                                (df.d1_review_date.isNull() |
                                 df.d1_status != 'Approved')))\
    .withColumn('d41_filter', (df.d4_submit_date.isNotNull() &
                               (df.d4_review_date.isNull() |
                                 df.d4_status != 'Approved')))\
    .withColumn('d42_filter', (df.d42_submit_date.isNotNull() &
                               (df.d42_review_date.isNull() |
                                 df.d42_status != 'Approved')))\
    .withColumn('d45_filter', (df.d5_submit_date.isNotNull() &
                               (df.d5_review_date.isNull() |
                                 df.d5_status != 'Approved')))\
    .withColumn('d6_filter', (df.d8_submit_date.isNotNull() &
                              (df.d8_review_date.isNull() |
                                 df.d8_status != 'Approved')))

All the columns might have null values.
Why new WithColumn expression is not working? What I am missing here?


text:
Q: colortbl, multicolumn and settototalheight don't work together I have a script that generates super-complicated tables, which need individual cells with coloured backgrounds. At the moment I'm using my own macro to generate the coloured cells, but I would rather use the much better macros in colortbl. However, importing the colortbl package causes my latex documents to fail with:
$ pdflatex  tbl_example.tex
! Undefined control sequence.
<template> ...@setup \CT@row@color \CT@cell@color
                                                  \CT@do@color \endgroup \@t...
l.23 \multicolumn{1}{c}{\multirow{2}{*}{}}&&
                                            &\multicolumn{1}{c}{} &\multicol...

?

In the MWE below, commenting out either usepackage{colortbl}, or the definition of \blankheight or the table column causes this document to compile with no errors. What have I done wrong?
\documentclass{article}
\usepackage{booktabs}
\usepackage{colortbl}
\usepackage{longtable}
\usepackage{mathtools}
\usepackage{multicol}
\usepackage{multirow}
\usepackage{xspace}

\newlength{\blankheight}%
\settototalheight{\blankheight}{%
$\begin{array}{rr}%
\scriptstyle{0} \\[-6pt]%
\scriptscriptstyle{0}%
\end{array}%
$%
}

\begin{document}

\begin{longtable}{ll@{\hspace{0cm}}ll@{\hspace{-1cm}}r@{\hspace{0cm}}r@{\hspace{0cm}}r@{\hspace{0cm}}r@{\hspace{0cm}}l@{\hspace{.3cm}}ll@{\hspace{-1cm}}r@{\hspace{0cm}}r@{\hspace{0cm}}rr@{\hspace{0cm}}r}

\multicolumn{1}{c}{\multirow{2}{*}{}}&&&\multicolumn{1}{c}{} &\multicolumn{1}{c}{Column} &\multicolumn{1}{c}{Column} &\multicolumn{1}{c}{Column} &\multicolumn{1}{c}{Column} &\multicolumn{1}{c}{Column}\\
\endhead
\hline

\end{longtable}

\end{document}

A: You can delay the setting:
\documentclass{article}
\usepackage{booktabs}
\usepackage{colortbl}
\usepackage{longtable}
\usepackage{mathtools}
\usepackage{multicol}
\usepackage{multirow}
\usepackage{xspace}

\newlength{\blankheight}%

\AtBeginDocument{%
\settototalheight{\blankheight}{%
$\begin{array}{rr}%
\scriptstyle{0} \\[-6pt]%
\scriptscriptstyle{0}%
\end{array}%
$%
}}

\begin{document}

\begin{longtable}{ll@{\hspace{0cm}}ll@{\hspace{-1cm}}r@{\hspace{0cm}}r@{\hspace{0cm}}r@{\hspace{0cm}}r@{\hspace{0cm}}l@{\hspace{.3cm}}ll@{\hspace{-1cm}}r@{\hspace{0cm}}r@{\hspace{0cm}}rr@{\hspace{0cm}}r}

\multicolumn{1}{c}{\multirow{2}{*}{}}&&&\multicolumn{1}{c}{} &\multicolumn{1}{c}{Column} &\multicolumn{1}{c}{Column} &\multicolumn{1}{c}{Column} &\multicolumn{1}{c}{Column} &\multicolumn{1}{c}{Column}\\
\endhead
\hline

\end{longtable}

\end{document}


text:
Q: Getting Image Height with FancyBox 3 I'm having trouble creating an If/then in fancybox, using the height of an image that will be going into the fancybox.
setBigImage : function ( slide ) {
var self = this;
var $img = $('<img />');

slide.$image = $img
.one('error', function() {

self.setError( slide );

})
.one('load', function() {

slide.width  = this.naturalWidth;
slide.height = this.naturalHeight;

.addClass( 'fancybox-image ' )
.attr('src', slide.src)
.appendTo( slide.$content );

In essence, I'm looking to add an if/then before the .addClass call that checks to see if the image's height is greater than 500px. I have tried to use:
if ( slide.Width > 500)
and if ( this.NaturalHeight > 500)

Neither worked. I tried both slide.Width and this.NaturalHeight inside of p tags to see what text they were putting out. Unfortunately, they created a second instance of the image. What would be the best way to get the image's height?
Thank you for your patience and help.

A: First, let the clarify this misunderstanding - " Unfortunately, they created a second instance of the image". When using some basic lightbox script, user would see black overlay with loading icon right after clicking thumbnail and then the image would just pop in. But fancybox displays thumbnail (first image) while actual image is still loading. Then real image (2nd image) gradually appears over the first one and user most likely will not see or notice loading indicator.
The answer to your question is also simple, just replace
if ( slide.Width > 500)
with
if ( slide.width > 500)
btw, next version of fancybox will allow more customization based on image size, see these demos - https://codepen.io/anon/pen/mqQLVm?editors=1010 and https://codepen.io/anon/pen/yPQjbw?editors=1010


text:
Q: PM2 cron process restarting too many times, not every 15 minutes I'm using pm2 to run a script every 15 minutes, or at least I'm trying. The code I used to start the process and keep it restarting is the on that follows:
pm2 start dist/scripts/updatePowerDemandGeneration.js --name script-UpdatePowerDemandGeneration --cron "*/15 * * * *" --log /home/lkuratani/projects/prisma-logs/updatePowerGeneration.log

I cleaned the logs file, and this is what I got after some minutes:
Started Tue Nov 17 2020 14:18:51 GMT+0000 (Coordinated Universal Time)
Finished Tue Nov 17 2020 14:19:13 GMT+0000 (Coordinated Universal Time)
Started Tue Nov 17 2020 14:19:15 GMT+0000 (Coordinated Universal Time)
Started Tue Nov 17 2020 14:19:48 GMT+0000 (Coordinated Universal Time)
Finished Tue Nov 17 2020 14:20:25 GMT+0000 (Coordinated Universal Time)
Started Tue Nov 17 2020 14:20:27 GMT+0000 (Coordinated Universal Time)
Finished Tue Nov 17 2020 14:20:47 GMT+0000 (Coordinated Universal Time)
Started Tue Nov 17 2020 14:20:49 GMT+0000 (Coordinated Universal Time)
Finished Tue Nov 17 2020 14:21:07 GMT+0000 (Coordinated Universal Time)
Started Tue Nov 17 2020 14:21:10 GMT+0000 (Coordinated Universal Time)
Finished Tue Nov 17 2020 14:21:29 GMT+0000 (Coordinated Universal Time)
Started Tue Nov 17 2020 14:21:31 GMT+0000 (Coordinated Universal Time)
Finished Tue Nov 17 2020 14:21:50 GMT+0000 (Coordinated Universal Time)
Started Tue Nov 17 2020 14:21:52 GMT+0000 (Coordinated Universal Time)
Finished Tue Nov 17 2020 14:22:11 GMT+0000 (Coordinated Universal Time)
Started Tue Nov 17 2020 14:22:13 GMT+0000 (Coordinated Universal Time)
Finished Tue Nov 17 2020 14:22:33 GMT+0000 (Coordinated Universal Time)
Started Tue Nov 17 2020 14:22:34 GMT+0000 (Coordinated Universal Time)
Finished Tue Nov 17 2020 14:22:53 GMT+0000 (Coordinated Universal Time)
Started Tue Nov 17 2020 14:22:55 GMT+0000 (Coordinated Universal Time)
Finished Tue Nov 17 2020 14:23:15 GMT+0000 (Coordinated Universal Time)
Started Tue Nov 17 2020 14:23:16 GMT+0000 (Coordinated Universal Time)
Finished Tue Nov 17 2020 14:23:35 GMT+0000 (Coordinated Universal Time)
Started Tue Nov 17 2020 14:23:37 GMT+0000 (Coordinated Universal Time)
Finished Tue Nov 17 2020 14:23:56 GMT+0000 (Coordinated Universal Time)
Started Tue Nov 17 2020 14:23:58 GMT+0000 (Coordinated Universal Time)
Finished Tue Nov 17 2020 14:24:18 GMT+0000 (Coordinated Universal Time)
Started Tue Nov 17 2020 14:24:20 GMT+0000 (Coordinated Universal Time)
Finished Tue Nov 17 2020 14:24:39 GMT+0000 (Coordinated Universal Time)
Started Tue Nov 17 2020 14:24:41 GMT+0000 (Coordinated Universal Time)
Finished Tue Nov 17 2020 14:25:00 GMT+0000 (Coordinated Universal Time)
Started Tue Nov 17 2020 14:25:02 GMT+0000 (Coordinated Universal Time)
Finished Tue Nov 17 2020 14:25:21 GMT+0000 (Coordinated Universal Time)
Started Tue Nov 17 2020 14:25:23 GMT+0000 (Coordinated Universal Time)
Finished Tue Nov 17 2020 14:25:42 GMT+0000 (Coordinated Universal Time)
Started Tue Nov 17 2020 14:25:44 GMT+0000 (Coordinated Universal Time)
Finished Tue Nov 17 2020 14:26:03 GMT+0000 (Coordinated Universal Time)
Started Tue Nov 17 2020 14:26:05 GMT+0000 (Coordinated Universal Time)
Finished Tue Nov 17 2020 14:26:25 GMT+0000 (Coordinated Universal Time)
Started Tue Nov 17 2020 14:26:26 GMT+0000 (Coordinated Universal Time)
Finished Tue Nov 17 2020 14:26:46 GMT+0000 (Coordinated Universal Time)
Started Tue Nov 17 2020 14:26:47 GMT+0000 (Coordinated Universal Time)
Finished Tue Nov 17 2020 14:27:07 GMT+0000 (Coordinated Universal Time)
Started Tue Nov 17 2020 14:27:08 GMT+0000 (Coordinated Universal Time)

I logged the date with:
console.log(`Started ${new Date().toString()}`)
// code
console.log(`Finished ${new Date().toString()}`)

I can't seem to know what's happening, the process restarts after some seconds, not 15 minutes. I'm using PM2 as root. To generate this cron string, I used this website: [Crontab.guru][1]
[1]: https://crontab.guru/#*/15_*_*_*_*


text:
Q: c# group by multiple columns then select all fields where count > 1 I have a lambda query like this,
        List<string> ticketStatusOrder = new List<string>() { "Attended", "Issued", "Unpaid", "Cancelled" };

        var duplicate = dt.AsEnumerable()
            .OrderBy(x => ticketStatusOrder.IndexOf(x["TicketStatus"].ToString()))
            .GroupBy(x => new {EventID = x["EventID"].ToString(), ContactID = x["ContactID"].ToString()})
            .Select(x =>
            {
                var first = x.First();
                //return new {first.ItemArray};
                return new
                {
                    Type = first["type"],
                    Name = first["name"],
                    EventID = first["EventID"],
                    ContactID = first["ContactID"],
                    TicketStatus = first["TicketStatus"]
                };
            }).ToDataTable();

Its not returning the correct order by number, anyhelp? thanks

A: found the solution by doing
  var duplicate = dt.AsEnumerable()
            .GroupBy(x => new {EventID = x["EventID"].ToString(), ContactID = x["ContactID"].ToString()})
            .Where(x => x.Count() == 1)
            .Select(x =>
            {
                var first = x.First();
                return new
                {
                    Type = first["type"],
                    Name = first["name"],
                    EventID = first["EventID"],
                    ContactID = first["ContactID"]
                };
            }).ToDataTable()

Another question,can we return new first.ItemArray something like that to return whatever is in first? thanks


text:
Q: How to increment a counter for a while loop within the loop? I have a feeling I'm gonna feel really stupid here, but I'm just learning about using ++ and -- to increment and decrements variables for while loops, and was wondering why this piece of code works and why this doesn't?
Bad code:
int ctr = 0;
while (ctr < 10)
  printf("%d",ctr);
  ctr=ctr+1;

The bad code outputs zeros indefinitely.
Working code:
int ctr=0;
while (ctr++ < 10)
    printf("%d",ctr);

The idea is for the output to be 012345678910 but even in the working code, it starts at 1 and goes to 10, instead of starting at 0. Even though the initial value of ctr is 0.

A: In the first case
while (ctr < 10)
  printf("%d",ctr);
  ctr=ctr+1;

the while loop body is considered only the printf() statement. ctr=ctr+1; is not part of the loop body. So you have an unchanged variable in loop condition check, which makes it infinite loop.
You need to enclose both the statements in a block scope, using {} so that both the statements become part of the loop body. Something like
while (ctr < 10) {
  printf("%d",ctr);
  ctr=ctr+1;
}

will do.

In the second case
int ctr=0;
while (ctr++ < 10)
    printf("%d",ctr);

ctr is already incremented as the side effect of the postfix increment operator, in the while condition checking expression. Thus, while printing the value, the already incremented value is being printed.

A: It is quite simple, indeed.
int ctr = 0;
while (ctr < 10)
  printf("%d",ctr);
  ctr=ctr+1;

In this first piece of code, in spite of the indentation, your while is only involving printf("%d",ctr);, because there is no block making ctr=ctr+1; belong to the while.
It could be written:
int ctr = 0;
while (ctr < 10)
  printf("%d",ctr);
ctr=ctr+1;     // This is not in the loop, even with the previous indentation.

There is no increment to ctr in this loop and then it will run forever printing zeros.
In this second piece of code
int ctr=0;
while (ctr++ < 10)
    printf("%d",ctr);

you do increment ctr every pass and it will work fine.
If you want to make the first loop work, write it like this:
int ctr = 0;
while (ctr < 10) {
  printf("%d",ctr);
  ctr=ctr+1;
}

Now ctr=ctr+1; is really inside the while loop.

A: int ctr = 0;
while (ctr++ <= 10)
{
    printf("%d",ctr-1);
}

Output to be 012345678910.


text:
Q: I can't figure out why my fibonacci sequence isn't working I have to make a little program to calculate a certain iteration of the fibonacci sequence. right now, it always gives out a 2, no matter what i do...
public partial class Form1 : Form
       {
        int num1=0;
        int num2=1;
        int sum=0;

        public Form1()
        {
            InitializeComponent();
        }

        private void btnCal_Click(object sender, EventArgs e)
        {
            for (int z = 0; z <= Convert.ToInt32(txtCal.Text); z++)
            {
                sum = num1 + num2;

                lblErg.Text = Convert.ToString(sum);
                num1 = num2;
                sum = num1;
            }
        }

A: You were setting num1 to sum not sum to num2.
            sum = num1 + num2;
            num1 = num2;
            num2 = sum;

            lblErg.Text = Convert.ToString(sum);


text:
Q: Matrix multiplication not working- Tensorflow I am begginer in using tensorflow and am using for a school project. Here I am attempting to make a house identifier, where I made some data on an excel sheet, turned it into a csv file and I was testing if the data would be read. The data was read but it produces multiple errors when I do the matrix multiplication and says.... "ValueError: Shape must be rank 2 but is rank 0 for 'MatMul' (op: 'MatMul') with input shapes: [], [1,1]." Thank you so much!
import tensorflow as tf
import os
dir_path = os.path.dirname(os.path.realpath(__file__))
filename = dir_path+ "\House Price Data .csv"
w1=tf.Variable(tf.zeros([1,1]))
w2=tf.Variable(tf.zeros([1,1])) #Feature 1's weight
w3=tf.Variable(tf.zeros([1,1])) #Feature 1's weight
b=tf.Variable(tf.zeros([1])) #bias for various features
x1= tf.placeholder(tf.float32,[None, 1])
x2= tf.placeholder(tf.float32,[None, 1])
x3= tf.placeholder(tf.float32,[None, 1])
Y= tf.placeholder(tf.float32,[None, 1])
y_=tf.placeholder(tf.float32,[None,1])
with tf.Session() as sess:
    sess.run( tf.global_variables_initializer())
    with open(filename) as inf:
        # Skip header
        next(inf)
        for line in inf:
            # Read data, using python, into our features
            housenumber, x1, x2, x3, y_ = line.strip().split(",")
            x1 = float(x1)
            product = tf.matmul(x1, w1)
            y = product + b

A: @Aaron is right, you are overwriting the variables when you loading the data from the csv file.
You need to save the loaded value into a separate variable, say _x1 instead of x1, and then use feed_dict to feed the value to the placeholder. And because the shape of your x1 is [None,1], you need to convert your string scalar _x1 into a float with the same shape, which is [1,1] in this case.
import tensorflow as tf
import os
dir_path = os.path.dirname(os.path.realpath(__file__))
filename = dir_path+ "\House Price Data .csv"
w1=tf.Variable(tf.zeros([1,1]))
b=tf.Variable(tf.zeros([1])) #bias for various features
x1= tf.placeholder(tf.float32,[None, 1])

y_pred = tf.matmul(x1, w1) + b

with tf.Session() as sess:
    sess.run( tf.global_variables_initializer())
    with open(filename) as inf:
        # Skip header
        next(inf)
        for line in inf:
            # Read data, using python, into our features
            housenumber, _x1, _x2, _x3, _y_ = line.strip().split(",")
            sess.run(y_pred, feed_dict={x1:[[float(_x1)]]})