text:
Q: How to create an external Hive table if the field value has comma separated values I had used sqoop-import command to sqoop the data into Hive from teradata. Sqoop-import command is creating a text file with comma(,) as the delimiter.
After Sqooping, I had created an external table as shown below:
CREATE EXTERNAL TABLE IF NOT EXISTS employee ( eid int, name String,
salary String, description String)
COMMENT 'Employee details'
ROW FORMAT DELIMITED
FIELDS TERMINATED BY ','
LINES TERMINATED BY '\n'
STORED AS TEXTFILE;

But description column has values like this:"abc,xyz,mnl". Due to this,loading of data into a hive table is not proper. Then how to create a text file with a delimiter other than comma while sqooping.
Then how to delimit the fields while creating an external table of Hive?

A: Use --fields-terminated-by in your Sqoop job if you want to avoid the default delimiter.
--fields-terminated-by -  This parameter is used for field separator character in output.
Example: --fields-terminated-by |
and then change fields separator in create table statement by  FIELDS TERMINATED BY '|'


text:
Q: Separation of variables for nonhomogeneous equations I'm trying to learn PDE from
An introduction to partial differential equations, Pinchover and Rubinstein.
On page 114 section 5.4 it explains the use of separation of variables for nonhomogeneous equations.
For example, consider the problem$$u_{tt}-u_{xx}=\cos(2\pi x)\cos(2\pi t), x>0, x<1 ,t>0$$
$$u_x(0,t)=u_x(1,t)=0, t\geqslant 0$$
$$u(x,0)=f(x)= \cos^2(\pi x), x\geqslant 0, x\leq 1$$
$$u_t(x,0)=g(x)=2\cos(2\pi x), x\geqslant 0, x\leq 1.$$
The system of all eigenfunctions and the corresponding eigenvalues of the homogeneous problem are:
$$X_n(x)=\cos(n\pi x), \lambda_n=(n\pi)^2, n=0,1,2,...$$
For a fixed $t$ the solution $u$ can be represented as
$$u(x,t)=(\frac{1}{2}) T_0(t) + \sum_{n=1} ^ {\infty} T_n(t)\cos(n\pi x)$$ where $T_n(t)$ are the (time dependent) Fourier coefficients of the function $u(.,t)$!!!
Can anyone please explain what is going on? How one can solve a nonhomogeneous wave equation using separation of variables method and the idea behind it ?
Thanks.

A: Consider the initial boundary problem
 $$
 \left\{
\begin{array}{lll}
&u_{tt}-c^2u_{xx}=F(x,t),\; a<x<b,\; t>0,\\
&\text{homogeneous boundary conditions on } (a,b),\\
&u(x,0)=f(x),\; a<x<b,\\
&u_t(x,0)=g(x),\; a<x<b.
\end{array}
\right.
\qquad(1)
$$
Solving steps:

*

*Solve eigenvalue problem
$$-X_k''=\lambda_k X_k,$$
with homogeneous boundary conditions on $(a,b)$.

*Find  Fourier series expansions
$$F=\sum F_kX_k,$$
$$f=\sum f_kX_k,$$
$$g=\sum g_kX_k.$$

*Solve ODE problems
$$T''_k(t)+c^2\lambda_kT_k(t)=F_k,\; T_k(0)=f_k,\;T'_k(0)=g_k.$$

*Then solution of $(1)$ is
$$u=\sum T_k(t)X_k$$
For example, consider the problem(Pinchover and Rubinstein, An introduction to partial differential equations, p. 114, section 5.4)
\begin{equation}
\begin{split}
&u_{tt}-u_{xx}=\cos2\pi x\cos2\pi t,\; 0<x<1,\; t>0,\\
&u_x(0,t)=u_x(1,t)=0,\;t\ge0,\\
&u(x,0)=\cos^2\pi x,\; 0\le x\le 1,\\
&u_t(x,0)=2\cos2\pi x,\; 0\le x\le 1.\\
\end{split}
\end{equation}

*

*Solutions of eigenvalue problem
$$-X_k''=\lambda_k X_k,\;X'_k(0)=X'_k(1)=0$$
is
$$X_k(x)=\cos(k\pi x),\quad \lambda_k=(k\pi)^2,\quad k=0,1,2,\dots$$

*$F=\cos2\pi x\cos2\pi t$.  Then
$$F_k=\begin{cases} \cos2\pi t \text{ if } k=2, & \\ 0 \text{ if } k\neq2. \end{cases}$$
$f=\cos^2\pi x=\frac12+\frac{\cos2\pi x}{2}$. Then
$$f_k=\begin{cases} \frac12 \text{ if } k=0\quad \text{or} \quad k=2, & \\ 0 \text{ in other cases} \end{cases}$$
$g=2\cos2\pi x$. Then
$$g_k=\begin{cases} 2\text{ if } k=2, & \\ 0 \text{ if } k\neq2. \end{cases}$$

*If $k=0$ then $X_0=1$, $\lambda_0=0$, ODE problem is
$$T''_0(t)=0,\; T_k(0)=\frac12,\;T'_k(0)=0.$$
If $k=2$ then  $\lambda_2=4\pi^2$, ODE problem is
$$T''_2(t)+4\pi^2T_2(t)=\cos2\pi t,\; T_2(0)=\frac12,\;T'_2(0)=2.$$
We obtain $$T_0(t)=\frac12,$$
$$T_2(t)=\frac{\left( t+4\right)  \sin{ 2\pi  t }}{4\pi }+\frac{\cos{ 2\pi  t }}{2},$$
$$T_k(t)=0 \text{ if } k\neq0,\;2.$$

*

*Final solution is
$$u=T_0(t)X_0+T_2(t)X_2=
\frac12+\left(\frac{\left( t+4\right)  \sin{ 2\pi  t }}{4\pi }+\frac{\cos{ 2\pi  t }}{2}\right)\cos 2\pi x$$

redpajama_set_name: RedPajamaStackExchange


text:
Q: Problems with this-parent and this I am trying to make a little quiz in jquery. So I'll have several div-blocks with each 2 li-elements (one for yes, one for no). Clicking one of these li-elements updates a variable, gives visual feedback and toggles the display of either the current div and the next div. That's the plan.
I do use this js-code:
var ergebnis = 0;
$(this).click(function () {
    console.log(this.className);
    if ($(this).hasClass("ja")) {
        ergebnis++;
        $(".ergebnis").html(ergebnis);
        console.log(ergebnis);
    } else {
        ergebnis = ergebnis + 5;
        $(".ergebnis").html(ergebnis);
        console.log(ergebnis);
    }
    //Styles updaten
    $("#frage__1 li").not(this).css({
        opacity: '0.2',
        transition: '1s'
    });
    $(this).css({
        background: 'green',
        transition: '1s'
    });
    $("#frage__1").slideToggle("slow", function () {});
    $("#frage__2").slideToggle("slow", function () {});
});

And this html-code:

1. So you ever wanted to get alongside?

Yes

Extra Text

Nope

Extra Text 2

2. So you ever wanted to get alongside?

Yes

Again text

Nope

And another one

So you may already see that this is not really functional, as I always need to toggle all div-blocks in the very end of the code by hand; and currently do only get a result from the else-part. The console also logs me "undefined" at the very beginning and I always get my result always updated by 5, no matter what I click.
So I am looking for a solution how to exactly use this.parent() and something like not(this).parent at the very end of the code and what I did wrong at the very beginning with "this"
Thanks so much!

A: I'd try with these two small changes. First change your selector on the click handler from the following:
$(this).click(function () {

to the one below which uses the li element selector:
 $("li").click(function () {
     $li =  $(this); //save a reference of the clicked li element

also above saves a reference to the clicked li element. With $li you can you to obtain the grandparent div reference in of the two following ways to change css:
 $li.parent().parent().css({
        background: 'green',
        transition: '1s'
 });

alternative:
 $li.closest("div").css({
        background: 'green',
        transition: '1s'
  });

More info about .parent() and .closest() methods. I hope this helps a bit :-)


text:
Q: Manifold for Schwarzschild and Bertotti-Robinson In short: what is the manifold in discussion for Schwarzschild metric $$ ds^2 = -(1-\frac {2M}r)dt^2 + \frac1{1-\frac{2M}r} dr^2 + r^2 (d\theta^2 + \sin^2 \theta d\phi^2)$$
and Bertotti-Robinson metric (cf. Thorne and Blandford, "Applications of Classical Physics" http://www.pma.caltech.edu/Courses/ph136/yr2011/1025.1.K.pdf, Exercise 24.2) $$ ds^2 = Q^2(-dt^2 + \sin^2 t dz^2 + d\theta^2 + \sin ^2 \theta d\phi^2)$$
(where $Q=$const, $0\leq t \leq \pi, -\infty < z < +\infty, 0\leq \theta \leq \pi, , 0\leq \phi \leq 2\pi$)?
More description:
It seems that often, in general relativity, spacetimes are discussed purely by describing their metric tensors but not the manifold in question. This is very troublesome for me, since as far as I know, a manifold must be defined before describing metric tensor on it. For example, if one is to talk about metric tensor of a sphere $ds^2 = r^2 d\theta^2 + r^2 \sin^2 \theta d\phi^2$ before defining what a sphere is, then it would be ambiguous to see what exactly $\theta$ and $\phi$ means (unless one is judging from the context, which somewhat works in this case because $\theta,\phi$ usually means angle)
So when I saw Schwarzschild metric and Bertotti-Robinson metric suddenly showing up without giving any description of which manifold we are talking about, I became very confused (and still am, having been unable to find any fruitful answer to such question of mine).
My guess for Schwarzschild is that, judging from the context, $r$ is "radius", $\theta,\phi$ are "angles" so it is
"obviously true" that Schwarzschild metric is defined on the manifold $\mathbb R^4$ endowed with spherical polar coordinates for the spatial part. For Bertotti-Robinson, I'm guessing that $z,\theta,\phi$ together describe a somewhat alternative spherical polar coordinate where $z$ is height and so on, and thus that Bertotti-Robinson is also defined on $\mathbb R^4$.

A: There are many manifolds that admit the Schwarzschild metric, but the standard manifold to discuss it is the maximally extended Schwarzschild solution, which is $\mathbb R^2 \times S^2$. The easiest way to see this is to pick the Kruskal coordinates, which cover the whole manifold
$$ds^{2} = \frac{32M^3}{r}e^{-r/2M}(-dT^2 + dX^2) + r^2 d\Omega^2$$
with coordinates $(T,X,\theta,\varphi)$, with the angular coordinates describing a 2-sphere while $(T,X)$ indeed describe a region homeomorphic to $\mathbb R^2$. Since we have
$$X \in \mathbb R,\ T^2 - X^2 \in (-\infty, 1)$$
and
$$\frac {r}{2GM}=1+W_{0}\left({\frac {X^{2}-T^{2}}{e}}\right)$$
with $W_0$ the Lambert function, this means that the argument of the Lambert function is in the range $(-e^{-1}, \infty)$, so that $r \in (0, \infty)$, the metric never runs into any singularity (the values $T^2 - X^2 = 1$ corresponding to the actual singularities of the metric).
Once you have the maximally extended Schwarzschild solution, you can define a lot of other manifolds from it, either subsets or quotients. The exterior Schwarzschild solution still has the same topology : it's just a restriction to a quadrant of $(T,X)$, and in Schwarzschild coordinates you can easily see that it is just $\mathbb R^4$ with a sphere removed from every Cauchy surface, which is also equal to $\mathbb R^2 \times S^2$. The same goes for the interior Schwarzschild solution, or the Schwarzschild-Eddington-Finkelstein coordinate patch.
There are weirder topologies for the Schwarzschild solution, such as the elliptic Schwarzschild solution, which corresponds to the quotient by identification of the black hole and white hole solution (which is not causal or time-orientable), which I think has topology $\mathbb R \times S \times S^2$


text:
Q: Como por uma cor padrão no input color Bom dia, eu tenho um <input type='color' /> e ele só vem na cor preta, quero que ele venha na cor white.

A: Basta definir o atributo value do seu campo:

<input type='color' value='#FFFFFF' />

O valor que indicar no atributo será a cor exibida inicialmente.


text:
Q: Check if the series $\sum^{\infty}_{n=1} \frac{\ln^{100}n}{n}\sin\frac{n\pi}{4}$ converges Which test should I use to check that the series $$\sum^{\infty}_{n=1} \frac{\ln^{100}n}{n}\left(\sin\frac{n\pi}{4}\right)$$ converges?

A: Dirichlet's test provides an efficient way: the sequence $\left\{\sin\frac{\pi n}{4}\right\}_{n\geq 1}$ has bounded partial sums and $\frac{\log^{100}n}{n}$ is decreasing to zero from some point on.


text:
Q: Toggle sets of Vim plugins Is there a trick or script that allows me to switch between sets of vim-plugins and -settings easily?
I use vim for very different development and writing. It can be really annoying to have certain webdevelopment-specific plugins turn up, when writing a report in LaTeX, for example.
What I'd like to see is something like RVM.

*

*Have a set of "global" plugins and settings; plugins and settings that are always enabled or used.

*Per project plugins and settings; pluginss, configurations and settings that will be loaded after activating that "environment".

A: You may find localvimrc to be useful for point number two.  It allows you to have a .lvimrc in your project folder with settings for that specific project.  In that file you could load your project-specific plugins by manipulating the runtimepath or by using pathogen/vundle/whatever.
Using this method you would configure your "global" settings and plugins as you would normally.

A: Nice question IMHO. By the way, using a plugin manager could simplify this kind of stuff too. For example, with pathogen you can do something like:
" To disable a plugin, add it's bundle name to the following list
let g:pathogen_disabled = []

if your_condition
   call add(g:pathogen_disabled, 'myplugin')
   call add(g:pathogen_disabled, 'myplugin2')
end

See this answer for a good example about conditional loading. It would be very nice to see this feature implemented in pathogen.

A: I'd just make aliases
alias mvim='vim -u myvimrc'

alias ovim='gvim -U someothervimrc'

Ans yes you could use runtimepath inside the vimrc-s to setup very different configurations


text:
Q: UITableViewCell is not expanding to fit height of UILabel, what am I doing wrong? What I want is my UITableViewCell to expand/shrink based on the height of the UILabel inside.
I have tried just about every solution I could find and it's not working. Maybe I have some setting that's preventing it.
Here is a screenshot of the UITableViewCell settings:

For the UILabel inside, Lines is set to 0 and Line Break to Word Wrap.
In the UIViewController where I'm showing the table view, I am setting this in viewDidLoad():
tableView.rowHeight = UITableView.automaticDimension
tableView.estimatedRowHeight = 44
tableView.reloadData()

And in cellForRowAt after dequeuing the cell I'm doing (instructionText being the UILabel):
cell.instructionText.numberOfLines = 0
I've seen this in many tutorials and it works, why not for these cells? The content comes out like this:

This is driving me crazy! Thanks for any help!
EDIT: Here are the UILabel settings:

A: Please check your label constraints


text:
Q: GCE VM Instance utilizing only 30% CPU and training of NN runs 3 times slower than on my Notebook I have free trial of GCE for next few months so I wanted to train my first DL model on it.
I chose E2-highmem-8 standard that is: 8vCPU and 64GB of memory.
Now when I am trying to run my NN alorithm on this instance one epoch takes 12 seconds to complete, but on my pc it takes only 3-4 seconds. So basically I have to wait 3-4 times longer for single training to complete.
I have tried using:
tf.compat.v1.ConfigProto(device_count={"CPU": 8},
                            inter_op_parallelism_threads=1,
                            intra_op_parallelism_threads=16,
                            )

and
sess = tf.compat.v1.Session(tf.compat.v1.ConfigProto(
                              inter_op_parallelism_threads=1))

But both didn't worked.
Since I am the begginer, both regarding DL programming and using GCE, I am not sure if I used correct settings for VM to utilze 100% of CPUs.
Since I have no idea if I wrongly used tf settings or my code is bad I am putting in my code below. But firstly I will introduce to you why I've used loops over NN code.
Due to the fact that I am the begginer and I've had a hard time with tunning of hyperparameters, so I've put NN code in three loops where each loop changes number of neurons, lr, and epochs, that is why the computing time is kind of important.
I am adding my code below, because I don't know if it's something in there that's causing so slow computing.
code:
import sys
import os
import sklearn
import math
import tensorflow as tf
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib as mpl
from datetime import datetime
from sklearn.preprocessing import LabelEncoder
from sklearn.preprocessing import MinMaxScaler
from sklearn.metrics import mean_squared_error
from tensorflow import keras
from contextlib import contextmanager
np.set_printoptions(linewidth=3000)
import joblib

@contextmanager
def show_complete_array():
    oldoptions = np.get_printoptions()
    np.set_printoptions(threshold=np.inf)
    try:
        yield
    finally:
        np.set_printoptions(**oldoptions)

def split_dataset(data, output_len):
    input_len = len(data)
    samples = []
    for i in range(0, input_len, output_len):
        sample = data[i : i + input_len, :]
        samples.append(sample)
    return samples

n_steps = 60
def plot_series(series, y=None, y_pred=None, x_label="$t$", y_label="$x(t)$"):
    plt.plot(series, ".-")
    if y is not None:
        plt.plot(n_steps, y, "bx", markersize=10)
    if y_pred is not None:
        plt.plot(n_steps, y_pred, "ro")
    plt.grid(True)
    if x_label:
        plt.xlabel(x_label, fontsize=16)
    if y_label:
        plt.ylabel(y_label, fontsize=16, rotation=0)
    plt.hlines(0, 0, 100, linewidth=1)
    mini = min(series) - 0.1*min(series)
    maxi = max(series) + 0.1*max(series)
    plt.axis([0, n_steps + 1, mini, maxi])

FILE = 'TVCSILVER60.csv'
FOLDER = 'Data SLV'
PROJECT_ROOT_DIR = '.'
csv_path = os.path.join(PROJECT_ROOT_DIR, FOLDER, FILE)
print(csv_path)

def save_fig(fig_id, tight_layout=True, fig_extension="png", resolution=300):
    path = os.path.join(PROJECT_ROOT_DIR, fig_id + "." + fig_extension)
    print("Zapisywanie rysunku", fig_id)
    if tight_layout:
        plt.tight_layout()
    plt.savefig(path, format=fig_extension, dpi=resolution)

Silver_CFD = pd.read_csv(csv_path, delimiter=',')
Silver_CFD.rename(columns={'Date' : 'Date', 'O' : 'Open', 'H' : 'High', 'L' : 'Low',
                           'C' : 'Close', 'Volume' : 'Volume', 'Volume MA' : 'Volume MA'}, inplace=True)

# Przygotowanie danych do lasu losowego
Silver_CFD_prepared = Silver_CFD.drop('Date', axis=1)
Silver_CFD_prepared = Silver_CFD_prepared.drop('High', axis=1)
Silver_CFD_prepared = Silver_CFD_prepared.drop('Low', axis=1)
Silver_CFD_prepared = Silver_CFD_prepared.drop('Open', axis=1)
Silver_CFD_prepared = Silver_CFD_prepared.drop('Volume', axis=1)
Silver_CFD_prepared = Silver_CFD_prepared.drop('Volume MA', axis=1)

#Silver_CFD_prepared_High = Silver_CFD_prepared['High']
#Silver_CFD_prepared_Low = Silver_CFD_prepared['Low']
#Silver_CFD_prepared_Open = Silver_CFD_prepared['Open']
#Silver_CFD_prepared_Close = Silver_CFD_prepared['Close']

scaler = MinMaxScaler(feature_range=(0.1,0.9), copy=False)

Silver_CFD_prepared = Silver_CFD_prepared.to_numpy(dtype='float32')

data_to_plot = Silver_CFD_prepared

Silver_CFD_prepared = scaler.fit_transform(Silver_CFD_prepared)

joblib.dump(scaler, 'scaler.joblib')

data_train = Silver_CFD_prepared[:12530]
#data_train = data_train.to_numpy(dtype='float32')
data_valid = Silver_CFD_prepared[:12530]
#data_valid = data_valid.to_numpy(dtype='float32')
data_test = Silver_CFD_prepared[:12530]
#data_test = data_test.to_numpy(dtype='float32')
data_to_operate = Silver_CFD_prepared

to_y = Silver_CFD_prepared.copy()

print(data_train.shape)

x_train = np.empty((12470, 60, 1))
y_train = np.empty((12470, 20))
index = 0
to_file = np.empty((12470))
for i in range(12470):
    for j in range(60):
        x_train[i, j, 0] = data_train[index]
        index += 1

    for k in range(20):
        y_train[i, k] = to_y[i + 60 + k]
    index = 1
    index += i

print(x_train.shape)
print(y_train.shape)

x_valid = np.empty((12470, 60, 1))
y_valid = np.empty((12470, 20))
index = 0
for i in range(12470):
    for j in range(60):
        x_valid[i, j, 0] = data_valid[index]
        index += 1
    for k in range(20):
        y_valid[i, k] = to_y[i + 60 + k]
    index = 1
    index += i

x_test = np.empty((12470, 60, 1))
y_test = np.empty((12470, 20))
index = 0
for i in range(12470):
    for j in range(60):
        x_test[i, j, 0] = data_test[index]
        index += 1
    for k in range(20):
        y_test[i, k] = to_y[i + 60 + k]
    index = 1
    index += i

print('x_train.shape', x_train.shape, 'x_valid.shape', x_valid.shape, 'x_test.shape', x_test.shape)
print('y_train.shape', y_train.shape, 'y_valid.shape', y_valid.shape, 'y_test.shape', y_test.shape)

#x_train = x_train[:, :-1, :]
#x_valid = x_valid[:, :-1, :]
#x_test = x_test[:, :-1, :]
#print('x_train.shape', x_train.shape, 'x_valid.shape', x_valid.shape, 'x_test.shape', x_test.shape)

'''
# prognozowanie naiwne
y_naive_pred = x_valid[:, -1]
naive_mse = np.mean(keras.losses.mean_squared_error(y_valid, y_naive_pred))
print(naive_mse)
plot_series(x_valid[0, :, 0], y_valid[0, 0], y_naive_pred[0, 0])
plt.show()
'''

n_neurons = 16
epochs = 50
lr = 0.0000
for trial in range(12):
    model = keras.models.Sequential([
        keras.layers.SimpleRNN(n_neurons, activation='relu', return_sequences=True, input_shape=[None, 1]),
        keras.layers.Dropout(0.2),
        keras.layers.SimpleRNN(n_neurons),
        keras.layers.Dropout(0.2),
        keras.layers.Dense(20, activation='linear')
    ])
    for iters in range(50):
        lr = 0
        for rates in range(10):
            lr = lr + 0.0005
            optimizer = keras.optimizers.Adam(lr=lr)
            model.compile(loss='mse', optimizer=optimizer)
            history = model.fit(x_train, y_train, epochs=epochs,
                                validation_data=(x_valid, y_valid))

            train_predict = model.predict(x_train)
            valid_predict = model.predict(x_valid)
            test_predict = model.predict(x_test)
            print(test_predict.shape)

            w1, w2 = y_test.shape
            for i in range(w2-1):
                train_score = math.sqrt(mean_squared_error(y_train[:, i], train_predict[:, i]))
                valid_score = math.sqrt(mean_squared_error(y_valid[:, i], valid_predict[:, i]))
                test_score = math.sqrt(mean_squared_error(y_test[:, i], test_predict[:, i]))
                print('Train Score: %3f RMSE' % (train_score))
                print('Valid Score: %3f RMSE' % (valid_score))
                print('Test Score: %3f RMSE' % (test_score))

            sc = joblib.load('scaler.joblib')

            print(x_test.shape)
            print(y_test.shape)
            print(test_predict.shape)

            y_test_temp = y_test.copy()
            x_test_temp = x_test.copy()
            x_test_to_plot = x_test_temp.reshape(12470, 60) #[-1, :, :]
            y_test_to_plot = y_test_temp # [-1, :]
            test_predict_to_plot = test_predict #[-1, :]

            print(x_test_to_plot.shape)
            print(y_test_to_plot.shape)
            print(test_predict_to_plot.shape)

            x_test_inv = sc.inverse_transform(x_test_to_plot)
            y_test_inv = sc.inverse_transform(y_test_to_plot)
            test_predict_inv = sc.inverse_transform(test_predict_to_plot)

            print(x_test_inv.shape)
            print(y_test_inv.shape)
            print(test_predict_inv.shape)

            n_steps_to_plot = np.empty((20))
            for i in range(20):
                n_steps_to_plot[i] = n_steps + i
            plt.subplot(1, 2, 1)
            plt.plot(history.history['loss'], label='loss')
            plt.plot(history.history['val_loss'], label='val_loss')
            plt.legend()
            plt.xlabel('Epochs')
            plt.ylabel('loss function value')
            plt.grid()

            plt.subplot(1, 2, 2)
            plt.plot(x_test_inv[-1, :], label='input prices')
            plt.plot(n_steps_to_plot, y_test_inv[-1, :], 'b', label='real price')
            plt.plot(n_steps_to_plot, test_predict_inv[-1, :], 'r', label='predicted price')
            plt.grid()
            plt.xlabel('time')
            plt.ylabel('Price')
            plt.legend()
            save_fig(f'loss_and_prediction_n_neurons_{n_neurons}_epochs_{epochs}_lr_{lr}')
            plt.close()

            plt.subplot(3, 3, 1)
            plt.plot(n_steps_to_plot, y_test_inv[35, :], 'b', label='real price')
            plt.plot(n_steps_to_plot, test_predict_inv[35, :], 'r', label='predicted price')
            plt.grid()
            plt.xlabel('time')
            plt.ylabel('Price')
            plt.legend()

            plt.subplot(3, 3, 2)
            plt.plot(n_steps_to_plot, y_test_inv[87, :], 'b', label='real price')
            plt.plot(n_steps_to_plot, test_predict_inv[87, :], 'r', label='predicted price')
            plt.grid()
            plt.xlabel('time')
            plt.ylabel('Price')
            plt.legend()

            plt.subplot(3, 3, 3)
            plt.plot(n_steps_to_plot, y_test_inv[457, :], 'b', label='real price')
            plt.plot(n_steps_to_plot, test_predict_inv[457, :], 'r', label='predicted price')
            plt.grid()
            plt.xlabel('time')
            plt.ylabel('Price')
            plt.legend()

            plt.subplot(3, 3, 4)
            plt.plot(n_steps_to_plot, y_test_inv[990, :], 'b', label='real price')
            plt.plot(n_steps_to_plot, test_predict_inv[990, :], 'r', label='predicted price')
            plt.grid()
            plt.xlabel('time')
            plt.ylabel('Price')
            plt.legend()

            plt.subplot(3, 3, 5)
            plt.plot(n_steps_to_plot, y_test_inv[3524, :], 'b', label='real price')
            plt.plot(n_steps_to_plot, test_predict_inv[3524, :], 'r', label='predicted price')
            plt.grid()
            plt.xlabel('time')
            plt.ylabel('Price')
            plt.legend()

            plt.subplot(3, 3, 6)
            plt.plot(n_steps_to_plot, y_test_inv[7896, :], 'b', label='real price')
            plt.plot(n_steps_to_plot, test_predict_inv[7896, :], 'r', label='predicted price')
            plt.grid()
            plt.xlabel('time')
            plt.ylabel('Price')
            plt.legend()

            plt.subplot(3, 3, 7)
            plt.plot(n_steps_to_plot, y_test_inv[12422, :], 'b', label='real price')
            plt.plot(n_steps_to_plot, test_predict_inv[1422, :], 'r', label='predicted price')
            plt.grid()
            plt.xlabel('time')
            plt.ylabel('Price')
            plt.legend()

            plt.subplot(3, 3, 8)
            plt.plot(n_steps_to_plot, y_test_inv[-1, :], 'b', label='real price')
            plt.plot(n_steps_to_plot, test_predict_inv[-1, :], 'r', label='predicted price')
            plt.grid()
            plt.xlabel('time')
            plt.ylabel('Price')
            plt.legend()

            plt.subplot(3, 3, 9)
            plt.plot(n_steps_to_plot, y_test_inv[9544, :], 'b', label='real price')
            plt.plot(n_steps_to_plot, test_predict_inv[9554, :], 'r', label='predicted price')
            plt.grid()
            plt.xlabel('time')
            plt.ylabel('Price')
            plt.legend()
            save_fig(f'predictions_neurons_{n_neurons}_epochs_{epochs}_lr_{lr}')
            plt.close()

        epochs = epochs + 50
    n_neurons = n_neurons + 16
    epochs = 50

EDIT:
I've created the second VM on which I use the same script as above except this one doesnt't have the loop in it, but the utilization haven't changed and still is capped at 30%.
On both VMs I've checked for zombie processes and there were none to be found.
However both machines have a lot of sleeping processes.
for example:
VM2 - the instance which runs the script w/o loops, has total of 120 processes, 1 running, 119 sleeping,
VM3 - the instance which runs the script with loops, has total of 117 processes, 1 running 116 sleeping.
but the free cpu for each instance is still around 70%(id value) and 7%(sy value) is used by other processes - displayed by top command
EDIT2:
I've changed VM2 to c2d-highmem-8 standard with AMD milan CPUs.
The time for one epoch to complete is 6 seconds now. Utilization rised up to 45% and is stuck there.
(I don't know why utilization growed up ¯_( ཀ ʖ̯ ཀ)_/¯)
I've also tried adding this code:
from keras import backend as K

import tensorflow as tf

config = tf.ConfigProto(intra_op_parallelism_threads=8, inter_op_parallelism_threads=2, allow_soft_placement=True, device_count = {'CPU': 8 })

session = tf.Session(config=config)

K.set_session(session)

os.environ["OMP_NUM_THREADS"] = "8"

os.environ["KMP_BLOCKTIME"] = "30"

os.environ["KMP_SETTINGS"] = "1"

os.environ["KMP_AFFINITY"]= "granularity=fine,verbose,compact,1,0"

But the computing time of one epoch didn't change, when I've changed digit '8' (that represents number of cores) to '4' nothing changed as well.
I've searched through every site on 1 google page with multiple keywords.
I don't know what else I can do.
Maybe someone will know how to deal with this problem...
To be honest since one epoch takes avg 4 seconds for my pc I was hoping for 1 second or below for one epoch on VM instance.


text:
Q: How do I examine the Crime Scene during the "Blood on Ice" quest in Skyrim? I am trying to solve the "Blood on the ice"-quest and am told to examine the crime scene. But I cannot find any trigger to activate or object to collect.
What am I supposed to find/do here?

A: Follow the blood trail to Hjerim (the name of the house) and pick the lock (master). You can also go to the steward and he will tell you where to get the key to the house.

A: I watched this youtube video and followed that exact path to reach the clue house as I was not able to find it even after reading the spoiler in the accepted answer.
If you are running Skyrim on a seven year old laptop using a dozen performance mods, most likely, you won't see the blood stains.

A: You are supposed to follow the trail of blood

 It will eventually lead to a house where you can find various pieces of evidence.


text:
Q: Can every recursion be converted into iteration? A reddit thread brought up an apparently interesting question:

Tail recursive functions can trivially be converted into iterative functions. Other ones, can be transformed by using an explicit stack. Can every recursion be transformed into iteration?

The (counter?)example in the post is the pair:
(define (num-ways x y)
  (case ((= x 0) 1)
        ((= y 0) 1)
        (num-ways2 x y) ))

(define (num-ways2 x y)
  (+ (num-ways (- x 1) y)
     (num-ways x (- y 1))

A: Yes, it's always possible to write a non-recursive version. The trivial solution is to use a stack data structure and simulate the recursive execution.

A:
Is it always possible to write a non-recursive form for every recursive function?

Yes. A simple formal proof is to show that both µ recursion and a non-recursive calculus such as GOTO are both Turing complete. Since all Turing complete calculi are strictly equivalent in their expressive power, all recursive functions can be implemented by the non-recursive Turing-complete calculus.
Unfortunately, I'm unable to find a good, formal definition of GOTO online so here's one:
A GOTO program is a sequence of commands P executed on a register machine such that P is one of the following:

*

*HALT, which halts execution

*r = r + 1 where r is any register

*r = r – 1 where r is any register

*GOTO x where x is a label

*IF r ≠ 0 GOTO x where r is any register and x is a label

*A label, followed by any of the above commands.

However, the conversions between recursive and non-recursive functions isn't always trivial (except by mindless manual re-implementation of the call stack).
For further information see this answer.

A: In principle it is always possible to remove recursion and replace it with iteration in a language that has infinite state both for data structures and for the call stack. This is a basic consequence of the Church-Turing thesis.
Given an actual programming language, the answer is not as obvious. The problem is that it is quite possible to have a language where the amount of memory that can be allocated in the program is limited but where the amount of call stack that can be used is unbounded (32-bit C where the address of stack variables is not accessible). In this case, recursion is more powerful simply because it has more memory it can use; there is not enough explicitly allocatable memory to emulate the call stack. For a detailed discussion on this, see this discussion.

A: Recursion is implemented as stacks or similar constructs in the actual interpreters or compilers. So you certainly can convert a recursive function to an iterative counterpart because that's how it's always done (if automatically). You'll just be duplicating the compiler's work in an ad-hoc and probably in a very ugly and inefficient manner.

A: All computable functions can be computed by Turing Machines and hence the recursive systems and Turing machines (iterative systems) are equivalent.

A: Can you always turn a recursive function into an iterative one? Yes, absolutely, and the Church-Turing thesis proves it if memory serves. In lay terms, it states that what is computable by recursive functions is computable by an iterative model (such as the Turing machine) and vice versa. The thesis does not tell you precisely how to do the conversion, but it does say that it's definitely possible.
In many cases, converting a recursive function is easy. Knuth offers several techniques in "The Art of Computer Programming". And often, a thing computed recursively can be computed by a completely different approach in less time and space. The classic example of this is Fibonacci numbers or sequences thereof. You've surely met this problem in your degree plan.
On the flip side of this coin, we can certainly imagine a programming system so advanced as to treat a recursive definition of a formula as an invitation to memoize prior results, thus offering the speed benefit without the hassle of telling the computer exactly which steps to follow in the computation of a formula with a recursive definition. Dijkstra almost certainly did imagine such a system. He spent a long time trying to separate the implementation from the semantics of a programming language. Then again, his non-deterministic and multiprocessing programming languages are in a league above the practicing professional programmer.
In the final analysis, many functions are just plain easier to understand, read, and write in recursive form. Unless there's a compelling reason, you probably shouldn't (manually) convert these functions to an explicitly iterative algorithm. Your computer will handle that job correctly.
I can see one compelling reason. Suppose you've a prototype system in a super-high level language like [donning asbestos underwear] Scheme, Lisp, Haskell, OCaml, Perl, or Pascal. Suppose conditions are such that you need an implementation in C or Java. (Perhaps it's politics.) Then you could certainly have some functions written recursively but which, translated literally, would explode your runtime system. For example, infinite tail recursion is possible in Scheme, but the same idiom causes a problem for existing C environments. Another example is the use of lexically nested functions and static scope, which Pascal supports but C doesn't.
In these circumstances, you might try to overcome political resistance to the original language. You might find yourself reimplementing Lisp badly, as in Greenspun's (tongue-in-cheek) tenth law. Or you might just find a completely different approach to solution. But in any event, there is surely a way.

A: Basically yes, in essence what you end up having to do is replace method calls (which implicitly push state onto the stack) into explicit stack pushes to remember where the 'previous call' had gotten up to, and then execute the 'called method' instead.
I'd imagine that the combination of a loop, a stack and a state-machine could be used for all scenarios by basically simulating the method calls. Whether or not this is going to be 'better' (either faster, or more efficient in some sense) is not really possible to say in general.

A: *

*Recursive function execution flow can be represented as a tree.

*The same logic can be done by a loop, which uses a data-structure to traverse that tree.

*Depth-first traversal can be done using a stack, breadth-first traversal can be done using a queue.
So, the answer is: yes. Why: https://stackoverflow.com/a/531721/2128327.

Can any recursion be done in a single loop? Yes, because
a Turing machine does everything it does by executing a single loop:

*

*fetch an instruction,

*evaluate it,

*goto 1.

A: Yes, using explicitly a stack (but recursion is far more pleasant to read, IMHO).

A: Sometimes replacing recursion is much easier than that.  Recursion used to be the fashionable thing taught in CS in the 1990's, and so a lot of average developers from that time figured if you solved something with recursion, it was a better solution.  So they would use recursion instead of looping backwards to reverse order, or silly things like that.  So sometimes removing recursion is a simple "duh, that was obvious" type of exercise.
This is less of a problem now, as the fashion has shifted towards other technologies.

A: Recursion is nothing just calling the same function on the stack and once function dies out it is removed from the stack. So one can always use an explicit stack to manage this calling of the same operation using iteration.
So, yes all-recursive code can be converted to iteration.

A: Removing recursion is a complex problem and is feasible under well defined circumstances.
The below cases are among the easy:

*

*tail recursion

*direct linear recursion

A: Appart from the explicit stack, another pattern for converting recursion into iteration is with the use of a trampoline.
Here, the functions either return the final result, or a closure of the function call that it would otherwise have performed. Then, the initiating (trampolining) function keep invoking the closures returned until the final result is reached.
This approach works for mutually recursive functions, but I'm afraid it only works for tail-calls.
http://en.wikipedia.org/wiki/Trampoline_(computers)

A: I'd say yes - a function call is nothing but a goto and a stack operation (roughly speaking). All you need to do is imitate the stack that's built while invoking functions and do something similar as a goto (you may imitate gotos with languages that don't explicitly have this keyword too).

A: Have a look at the following entries on wikipedia, you can use them as a starting point to find a complete answer to your question.

*

*Recursion in computer science

*Recurrence relation
Follows a paragraph that may give you some hint on where to start:

Solving a recurrence relation means obtaining a closed-form solution: a non-recursive function of n.

Also have a look at the last paragraph of this entry.

A:
It is possible to convert any recursive algorithm to a non-recursive
  one, but often the logic is much more complex and doing so requires
  the use of a stack. In fact, recursion itself uses a stack: the
  function stack.

More Details: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Functions

A: Here is an iterative algorithm:
def howmany(x,y)
  a = {}
  for n in (0..x+y)
    for m in (0..n)
      a[[m,n-m]] = if m==0 or n-m==0 then 1 else a[[m-1,n-m]] + a[[m,n-m-1]] end
    end
  end
  return a[[x,y]]
end

A: tazzego, recursion means that a function will call itself whether you like it or not. When people are talking about whether or not things can be done without recursion, they mean this and you cannot say "no, that is not true, because I do not agree with the definition of recursion" as a valid statement.
With that in mind, just about everything else you say is nonsense. The only other thing that you say that is not nonsense is the idea that you cannot imagine programming without a callstack. That is something that had been done for decades until using a callstack became popular. Old versions of FORTRAN lacked a callstack and they worked just fine.
By the way, there exist Turing-complete languages that only implement recursion (e.g. SML) as a means of looping. There also exist Turing-complete languages that only implement iteration as a means of looping (e.g. FORTRAN IV). The Church-Turing thesis proves that anything possible in a recursion-only languages can be done in a non-recursive language and vica-versa by the fact that they both have the property of turing-completeness.


text:
Q: Как в LyX добавить/убрать сообщения какой-либо группы сообщений в View Messages? Вот, когда через Вид>View Meseages (или через Вид>Просмотреть сообщения - название зависит от используемого файла локализации LyX2.0.mo) открываешь в нижней части окна прогры LyX область Сообщения прогресса/отладки, в этой части окна бывает чрезмерно много выводится сообщений, бывает, просто мышкой пошевелишь, а там выводится километровая последовательность строк, в которой отыскать что-то нужное (например, чтобы получить подсказку, как вводить ту или иную команду через Буфер команды, там оно будет, конечно, не в буквальной форме, но подсказку это дать может, я, быть может, скоро немного об этом расскажу, что мне удалось накопать по этому поводу) бывает крайне затруднительно. Может быть, можно как-то регулировать количество этих сообщений?

A: Чтобы уменьшить (или, наоборот, добавить сообщения какой-либо группы сообщений), делаем вот что. В той нижней области окна щелкаем левой кнопкой мышки Натройки, там переключатель Отладочные сообщения устанавливаем в Выделенное:

А потом тут же в правой части выполняем двойной щелчок (с такой скоростью, с которой это делается при открытии какого-нибудь файла, эту скорость при необходимости можно изменить в настройках самого компа, вне прогры LyX) по группе сообщений, сообщения из которой мы хотим сделать не отображающимися в области Сообщения прогресса/отладки или, наоборот, сообщения этой группы сообщений мы хотим сделать отображающимися в этой области. После этого двойного щелчка статус группы сообщений, например, Общая информация, Инициализация программы, меняется на противоположный: если до двойного щелчка он был Да, то после этого двойного щелчка он станет Нет и сообщения этой группы перестают отображаться в этой области окна прогры LyX и наоборот. Все, щелкаем по Вывод и наслаждаемся работой в программе, в которой еще один момент удалось настроить так, как нужно нам.


text:
Q: AutoFocusComplete event windows phone So I am trying to develop a Windows Phone mobile application that utilizes Microsoft TAG technology.
I'm starting from the base of using the TagSdkSample project provided with the Microsoft TAG SDK.
I cannot get the program to spit anything out when debugging (I am debugging on my Windows 8 phone) and I'm assuming it has to do with the auto focus capabilities (its recognizes the TAG but gets really blurry right before the picture is snapped).  In the code there is a comment mentioning how this is a bad way for autofocus to work:
    private void GetImageAndDecode()
    {
        // This is not a good way to auto focus. It is better to have an AutoFocusCompleted event
        // handler to start capturing after focus is made. This sample code is not for
        // full application demonstration.
        camera.Focus();
        camera.GetPreviewBufferArgb32(previewPixels);
        imageToDecode = new ImageToDecode(previewPixels, ImageFormat.ARGB32, previewWidth, previewHeight);
        TagContext.Current.ScanFromFrame(imageToDecode);
    }

How would I implement that event handler within this code?

A: Add the following line to the PhotoCamera object initialization:
camera.AutoFocusCompleted += new EventHandler<CameraOperationCompletedEventArgs>(Camera_AutoFocusCompleted);

Then add the following method:
void cam_AutoFocusCompleted(object sender, CameraOperationCompletedEventArgs e)
{
    // Do what you want here
}


text:
Q: Why is my session expiring every time I close the browser? I set up the session maxAge of express like documented.
Here is my code:
app.use(session({
    secret: process.env.SESSION_SECRET,
    saveUninitialized: true,
    resave: true,
    maxAge: 1000* 60 * 60 *24 * 365,
    store: new MongoStore({mongooseConnection:mongoose.connection})
}));

But every time I close the browser, I find myself logged out.
Also, note that I am using Passport local, facebook, and google authentications.
They all expire.
In the console, I can see that the connect.sid in the expires/maxAge section lists "Session" while other cookies have dates...
What am I doing wrong?

A: you need to configure your express-session, and set maxAge on session-cookie
app.use(express.session({
    cookie : {
        maxAge: 1000* 60 * 60 *24 * 365
    },
    store : new MongoStore({mongooseConnection:mongoose.connection})
});
//.....
app.use(passport.session());


text:
Q: Proving that every increasing function is injective?
So, here's the theorem that I'm trying to prove. The thing is, the book I'm using is somewhat older than other textbooks, so I'm trying to put into language that I'm more familiar with. I'm going to try and rewrite the statement of the theorem in my own words and then I'll try to prove it.
I'm hoping that someone can point towards any mistakes I'm making in my interpretation of the language being used. I'm only going to do it for the first portion, as the second part is going to be analogous.
Let $I \subset \mathbb{R}$ be an interval and let $f: I \to \mathbb{R}$ be a function defined on that interval. Suppose that $f$ is increasing. Then, the following hold:

*

*$f$ is injective

*$f^{-1}$, if it exists, is increasing.

Proof Attempt:
We have to show that:
$$\forall x,y \in I: x \neq y \implies f(x) \neq f(y)$$
Let $x \neq y$. Then, by the trichotomy law, $x > y$ or $y > x$. Since $f$ is increasing, we have either $f(x) > f(y)$ or $f(y) > f(x)$. In any case, we have $f(x) \neq f(y)$. That proves that $f$ is injective.
Now, if $f^{-1}$ exists, then $f$ is bijective and $f^{-1}$ is also bijective. Since $f$ is increasing, we have:
$x<y \implies f(x)<f(y)$
Let $b_1,b_2 \in f(I)$. By the bijectivity of $f$, there exist $a_1,a_2 \in I$ such that $f(a_1) = b_1$ and $f(a_2) = b_2$. Now, we have to show that:
$b_2 > b_1 \implies a_2 > a_1$
Let $a_1 \geq a_2$. Since, $f(a_1) = f(a_2) \iff a_1 = a_2$ and $a_1 > a_2 \implies f(a_1) > f(a_2)$, it must be the case that $a_1 \geq a_2 \implies f(a_1) \geq f(a_2)$. That is precisely the contrapositive of the statement we wanted to show, so we have proven that the inverse is increasing.
This proves the desired result.


text:
Q: Zelig: #Error in attr(tt, "depFactors")$depFactorVar : # $ operator is invalid for atomic vectors I'm running a logit model using the Zelig package. I get the following error...what could be wrong?
anes96two <- zelig(trade962a ~ age962 + education962 + personal962 + economy962 + partisan962 + employment962 + union962 + home962 + market962 + race962 + income962, model="mlogit", data=data96)

 #Error in attr(tt, "depFactors")$depFactorVar :
#  $ operator is invalid for atomic vectors

A: Are you sure your dependent variable is as factor?
I think the error is because your dependent variable is not a factor.
Try str(data96), or summary(data96) to see if trade962a has levels and how many levels.
If not, then, just set as a factor. For example: data96$trade962a.f = as.factor(data96$trade962a)
Finally, if you wanna run a logistic regression, you should use 'model="logit"', not "mlogit". Mlogit is for multinomial logit. Thus, if your variable is binary, using mlogit may cause the cited error. If so, just use model="logit".
If none of the above solve your problem, try to plot your dependent variable to see if the data is all right.
regards,
Manoel


text:
Q: Dropbox use of "ListFolderAsync" with a filter I would like to list the directories at the root of my Dropbox application.
To do that I use the ListFolderAsync function of the Dropbox API and it works.
var list = await dbx.Files.ListFolderAsync ("");
Is it possible to add a filter to this function to retrieve only directories belonging to the filter?
Something like all directories whose names begin with "ABCD"
Thank you for your answers.
YC

A: You can't use ListFolderAsync method at the dropbox side the folder methods are fairly restrictive, however you can filter them after the fact with Linq
Another would be to use, either

*

*SearchAsync Method (SearchArg)

*FilesUserRoutes.SearchAsync Method (String, String, UInt64, UInt64, SearchMode)

Searches for files and folders.

Though this may not be optimal as you will get files as well.


text:
Q: Show adds related to only food category in admob I am developing an android app in which I want to show the adds only related to food products using the admob. But I am not sure whether it is possible.
I tried to add restriction to the ads currently showing in my app. But as I am only in the development mode of the application I can't test the filters on the application.
I tried searching for the list of the general category of ads, but unable to find the list. Can someone help me with my question?

A: You Can Block or Add Advertisements from Specific Category within Admob console.
-Login to Admob -> Select App you want to update
-Select Allow & Blocked Ads ( As shown below ) and select category Food as allowed and block all other categories.


text:
Q: What mean ref in mongoose? I have traveled the mongoose's docs but they don't provide deep explanation AFAIK:
here a snippet with the ref element:
 author: { type: Schema.Types.ObjectId, ref: 'Person' }

any hint would be great,
thanks

A: It stands for Reference. The value, in your case Person is the model it references. It means that the author is of type Person


text:
Q: Is it necessary to export and import stored procedures, triggers and indexes while dumping sql database? I use WordPress and I have always exported my database using the following command:
mysqldump -u user_name -p database_name > backup.sql

I never used --routines
Just wondering if I am doing something wrong, missing out on any advantages by not adding --routines while exporting my database.
P.S., I never had any server failure, hacking attempt or any misfortune needed to import those databases yet, but I want to make sure those database work when I need them to. Thanks

A: I'd think a normal basic wordpress wouldn't include stored procedures or triggers.
You can check by adding --routines to the mysqldump and seeing if the output is different.
Adding --routines when there is none is quite harmless and probably a good thing to add just in case a plugin adds starts using those features.
--single-transaction would also be a good option to add to mysqldump if you are using innodb tables (and you should be).
Indexes are supported in your dump currently.
PS: checking a backup properly involved attempting a restore and checking the final result. Don't rely on static analysis of your scripts/procedures - test them.


text:
Q: How to open a MODAL with REACT because what I'm doing is not working and the data is coming back AFTER I call the openModal() function I have code with REACT, and I'm trying to open a modal using REACT. I'm NOT a REACT programmer but Angular. That being said, however, I'm not doing too badly.
Here are the issues:

Now the code:
export const TableActions = (props) => {
...
  let messageObj = object
  let modalMessage = object;
  let titleMsg = '';
  const { row, userId, setShowCIQ, showCIQ, siteDetails, setShowMessageModal } = props
  const [setCancelValues] = useState(null)
...
  const { mutate: getMessages } = useMutation((requestid) => getSomeMessages(requestid), {
    onSuccess: (res) => {
      console.log('RES MESSAGES: ', res.messages),
        messageObj = res.messages
    },
    onError: (e) => toastEachError(e)
  })
...
  const handleGetMessages = async (e) => {
    const requestid = row.itential_cfg_header_id
    messageObj = getMessages(requestid) // THIS gets the messages but it's happening LATER
    console.log("REQID: ", requestid);
    if (requestid) {
      console.log('Message OBJ: ', messageObj)
      if (messageObj) {
        console.log("MSG OBJ: ", messageObj);
      } else {
        console.log("NO MESSAGE OBJ YET!", e);
      }
      openModal(); // THIS HAPPENS BUT THERE'S NO DATA YET
    }
  }
...
  const openModal = () => {
    console.log("************* Ready to go inside OPEN MODAL FUNCTION", siteDetails);
    if (row.actions.message === true) {
      console.log("************* INSIDE OPEN MODAL FUNCTION");
      titleMsg = 'Messsages for Request ID: ' + row.cfg_header_id;
    } else {
      titleMsg = 'No Messsages for Request ID: ' + row.cfg_header_id;
    }
    modalMessage =
      <ECAMPrompt
        handleClick={handleCancel}
        setDisplayPrompt={setCancelValues}
        messageObj={'There was a problem retrieving the error messages.'}
        close
      />

    return modalMessage;
  }
...
return (
    <div key={`icon-${row.cfg_header_id}`}>

        {row.actions.view && <FileIcon className={style.actionIcon} onClick={handleGetCiq} />}
        {row.actions.delete && <RemoveIcon className={style.actionIcon} onClick={handleDelete} />}
        {row.actions.execute && <CDIcon className={style.actionIcon} onClick={handleExecute} />}
        {row.actions.download && !siteDetails && (
          <a
            href={`${config.apiBaseUrl}/routercfg/table/download/${row.cfg_header_id}`}
            target='_blank'
            title='Download'
            rel='noreferrer'
          >
            <DownloadIcon className={style.actionIcon} />

        )}
        **// THIS IS MY CODE that's NOT WORKING not opening!**
        {row.actions.message && (
          <ModalPortal>
            <Modal title={titleMsg} handleHideModal={() => setCancelValues(false)}>
              modalMessage // THIS IS THE MODAL MESSAGE I want to send... but...
            </Modal>
          </ModalPortal>,
          <BookIcon className={style.actionIcon} onClick={handleGetMessages} />
        )}
        {row.actions.download && siteDetails && row.status.toLowerCase() === 'success' && (
          <a
            href={`${config.apiBaseUrl}/routercfg/table/download/${row.cfg_header_id}`}
            target='_blank'
            title='Download'
            rel='noreferrer'
          >
            <DownloadIcon className={style.actionIcon} />

        )}
        {siteDetails && row.status.toLowerCase() === 'success' && (
          <UploadIcon className={style.actionIcon} onClick={handleUpload} />
        )}

  )
}
TableActions.propTypes = {
  row: PropTypes.object,
  userId: PropTypes.string,
  setShowCIQ: PropTypes.func,
  setCancelValues: PropTypes.func,
  setShowMessageModal: PropTypes.func,
  showCIQ: PropTypes.string,
  userItentialMessages: PropTypes.string,
  siteDetails: PropTypes.bool,
  task: PropTypes.instanceOf(Map),
  showConfigModal: PropTypes.object
}

UPDATE: I tried putting AWAIT before getMessages(), but I get this in VSCode, and it has no effect

UPDATE 2:
So, I redid the function for getMessages
export function getSomeMessages(requestId) {
  return new Promise(resolve => {
    resolve(config.ajax.get(`/routercfg/table/requests/${requestId}/messages`).then(res => res.data || []))
  })
}

But when I call it in my other code it still won't allow async or await...
UPDATE 3:
Good news! I got the call to the function pinging BEFORE the openModal function.   My only remaining issue is:

*

*opening the modal

*displaying the JSON in the modal

The messagObj contains the JSON with two objects.
Here's my modified code for the Modal
        {row.actions.message && (
          <ModalPortal>
            <Modal title={titleMsg} handleHideModal={() => setCancelValues(false)}>
              messageObj <--- THIS IS NOW POPULATED but is it coded correctly?
            </Modal>
          </ModalPortal>,
          <BookIcon className={style.actionIcon} onClick={handleGetMessages} />
        )}


text:
Q: How to calculate $2 ^ {-1} \pmod{10}$ I want to know how to compute the inverse of a number when the module is composite and the number is not coprime.
Can anyone give me the options with an example of how to compute with $2 ^ {-1} \pmod{10}$?
Is there a way to do factorisation or some similar technique that ends with the same result like: $1/9  \pmod{10} = 1/3 \times 1/3  \pmod{10}$ and because 3 is comprime of 10 then is possible?
Thanks

A: There is no answer.  You would be looking for what to multiply $2$ by to get $1$.  Just like in the integers, there is no such number.  The integers modulo $10$ form a ring (with zero divisors) and there is no guarantee you can divide in one of those.

A: Note that since $\gcd(10,2)=2$ by Bezout's identity for any $a,b \in \mathbb{Z}$
$$a\cdot 10+b\cdot 2 \equiv 0 \pmod 2$$
then we can't find $a,b$ such that
$$a\cdot 10+b\cdot 2 = 1$$
and therefore $2$ is not invertible $\pmod{10}$.
More in general the modular equation
$$x\cdot n \equiv 1 \pmod m$$
has solution if and only if $\gcd(m,n)=1$.

A: Here a general fact and a possibly useful idea to find quickly a multiplicative inverse.
Let's $m$ denote the module and $x,y$ integers. Note that
$$x\cdot y \equiv 1 \mod m \Leftrightarrow x\cdot y - 1 = k\cdot m \Leftrightarrow x\cdot y - k\cdot m = 1 \Leftrightarrow (x,m) = (y,m) = 1$$
So, in your example that's not the case.
Concerning how to find the inverse note that provided that $x$ and $m$ are coprime according to Euler's theorem you have
$$x^{\varphi(m)} \equiv 1 \mod m \Rightarrow x^{-1}\equiv x^{\varphi(m)-1} \mod m$$

A: Suppose that you could some $x \in \mathbb{Z}_{10}$ such that $2^{-1} = x\pmod{10}$, or equivalently (multiplying both sides by $2$): $1 = 2x \pmod{10}$. Multiplying both sides by $5$ gives $5 = 10x = 0 \pmod{10}$ which is a contradiction.
So no such $x$ exists.


text:
Q: Expected declaration error( c error) this is my code
#include<stdio.h>

int main( int argc ,char *argv[] )
{
    FILE *fp;
    void filecopy( FILE * a, FILE *b )

    if (argc == 1)
    {
        filecopy(stdin,stdout);
    }

    else
    {
        while(--argc > 0)
        {
            if ((fp = fopen(*++argv,"r")) == NULL)
            {
                printf("no open".*argv);
            }
            else
            {
                filecopy(fp,stdout);
                fclose(fp);
            }
        }
    }
    return 0;
}

void filecopy ( FILE *ifp ,FILE *ofp )
{
    int c;
    while ( (c = getc(ifp)) != EOF)
    {
        putc(c , ofp);
    }
}

these are my error:
con.c: In function 'filecopy':
con.c:8: error: expected declaration specifiers before 'if'
con.c:13: error: expected declaration specifiers before 'else'
con.c:29: error: expected declaration specifiers before 'return'
con.c:30: error: expected declaration specifiers before '}' token
con.c:33: error: expected '=', ',', ';', 'asm' or '__attribute__' before '{' token
con.c:39: error: expected '{' at end of input
con.c: In function 'main':
con.c:39: error: expected declaration or statement at end of input

Why am i getting these error please tell me ?
thank you
sudhanshu

A: You're missing a semicolon at the end of this line:
void filecopy( FILE * a, FILE *b )

This should be
void filecopy( FILE * a, FILE *b );

Because this is a function prototype.
Also, this line is not legal C:
printf("no open".*argv);

This should probably just be something like
printf("no open");

Hope this helps!

A: The declaration needs to end with a semicolon
void filecopy( FILE * a, FILE *b );

(That's the declaration inside the main function, not the function definition which comes later.)

A: You are missing a semi-colon.
void filecopy( FILE * a, FILE *b );  /* Put semi-colon on the end! */

This line:

printf("no open".*argv);

Makes no sense.  What did you mean for it to do?


text:
Q: Subclassing UICollectionView Does anybody know how to subclass a UICollectionView in Xamarin.iOS?
I tried this
public class MyCustomUICollectionView : UICollectionView
{

    [Export ("initWithFrame:")]
    public InfinitiveScrollingUICollectionView (CGRect frame) : base(frame)
    {
        // initialization
    }
}

but I get

The best overloaded method match for UIKit.UICollectionView.UICollection(Foundation.NSCoder) has some invalid arguments
  Argument #1 cannot convertCoreGraphics.CGRectexpression to typeFoundation.NSCoder`.

I also tried to use public InfinitiveScrollingUICollectionView () but I get

The type UIKit.UICollectionView does not contain a constructor that takes '0' arguments

I want to override LayoutSubviews. Or should the UICollectionViewController be used for such a purpose?

A: UICollectionView has no constructor that accepts a single CGRect, so you have to pass a layout, too:
public class MyCustomUICollectionView : UICollectionView
{
    public MyCustomUICollectionView(CGRect frame, UICollectionViewLayout layout)
        : base(frame, layout)
    {
    }
}

If you want to, you can also create the layout internally, so you don't have to pass it from the outside:
public class MyCustomUICollectionView : UICollectionView
{
    private static readonly UICollectionViewLayout _layout;

    static MyCustomUICollectionView()
    {
        // Just an example
        _layout = new UICollectionViewFlowLayout();
    }

    public MyCustomUICollectionView(CGRect frame) : base(frame, _layout)
    {
    }
}


text:
Q: Running time of this pseudocode 1 for i = 1 to n
2    for j = i to n
3       for k = 1 to j
4          statements which take O(1) time

Please help me find the time complexity of the following segment of code. Is it O(n^3)? I think not because line 3 depends on line 2. I'm really having a hard time and I need your help. Please provide solution. Thank you very much!

A: initial thought:  n*n*logN I think?
Edit: the inner most, k, will hit 1 then next time, 1 and 2, then next time, 1 and 2 and 3...   which is linear... it just stops at a certain interval.  With it being linear, i would naturally say N...
So, after thinking about, O(n^3)?

A: You can think about it like this:
Take half way in the loop when
 i = n/2
for i = 1 to n
    for j = i to n
       for k = 1 to j
          statements which take O(1) time

the first one is running
n/2 times

the second one also runs
n/2 times(n-n/2)

and the third one also runs
n/2 times (1 to n/2)

Hence in this case n/2*n/2*n/2 which is giving (n^3)/8 which is
O(n^3)


text:
Q: python lxml find  tag I'm using lxml to parse an html that has a facebook comments tag that looks like that:
<fb:comments id="fb_comments"  href="http://example.com" num_posts="5" width="600"></fb:comments>

I am trying to select it to get the href value but when i do a cssselect('fb:comments') i get the following error:
The pseudo-class Symbol(u'comments', 3) is unknown

Is there a way to do it?
Edit:
The code:
from lxml.html import fromstring
html = '...'
parser = fromstring(html)
parser.cssselect('fb:comments')  #raises the exception

A: The cssselect() method parses the document using given CSS selector expression. In your case the colon character (:) is a XML namespace prefix separator (i.e. <namespace:tagname/>) which is confused with CSS pseudo-class syntax (i.e. tagname:pseudo-class).
According to lxml manual you should use namespace-prefix|element syntax in cssselect()in order to to find a tag (comments) with a namespace prefix (fb). So:
from lxml.html import fromstring
html = '...'
parser = fromstring(html)
parser.cssselect('fb|comments')


text:
Q: nginX - 301 Redirect a subdomain from multiple domains I have a small web server and am providing email services for a few clients.
They all have their own domains and my mail server is set up at mail.sgenov.com (I am talking about roundcube).
I need to redirect all of their domains to https at mail.sgenov.com,when the subdomain is "mail"
i.e.
http://mail.example1.com -> https://mail.sgenov.com
http://mail.blah-123-woohoo.co.uk -> https://mail.sgenov.com

This should apply to any current or future domains I might add.
What is the proper way to do this in nginX?
Thanks in advance!

A: You could have an http server block receive requests for any host name beginning with mail. and redirect those to https://mail.sgenov.com:
server {
    listen       80;
    server_name  mail.*;
    return 301 https://mail.sgenov.com;
}


text:
Q: javascript how to pass function results into the same function along with a value from array I have a function called findLCM, which takes 2 arguments (a,b).
I also have an array with an unknown number of elements (all numbers). For the purpose of explanation let's say:
var values = [c, d, e, f]

now what I need to build is this:
var result = findLCM(findLCM(findLCM(c,d),e),f);

I tried to write a for loop that would do this, but got stuck and can't figure it out. Can somebody point out the correct way to do this?
My code so far:
var result = 0;

for(f = 0; f < values.length -2; f++) {
  result *= findLCM(findLCM(values[f], values[f+1]),values[f+2]);
}

A: This sounds like a good case to use Array.prototype.reduce():
var values = [c, d, e, f];
var lcm = values.reduce(function(previous, currentValue, currentIndex, arr) {
    return findLCM(previous, currentValue);
});
alert(lcm);

A: I think that what you are looking is to use reduce.
var findLCM = function(a,b) {
  ...
};

var result = [a, b, c, d, e].reduce(findLCM);

A: try this recursive function
function findLCMArray (arr)
{
  if ( arr.length > 2 )
  {
     return findLCM( arr.shift() , findLCMArray (arr) );
  }
  else
  {
     return findLCM( arr.shift(), arr.shift() );
  }

  function findLCM( x, y )
  {
    //logic to do LCM
  }
}

Or you can loop through like this
var arr = [2,4,6,8];
var lcmValue = arr[0];
arr.forEach ( function(value){

  lcmValue = findLCM( lcmValue, value);

} );
alert(lcmValue);


text:
Q: java setAudioSource failed Всем доброго времени суток! При написании пробного диктофона-проигрывателя(Приложение записывает аудио файл с микрофона и сохраняет его в формате.3gpp) столкнулся с такой проблемой: при запуске приложение крашится со следующей ошибкой:
E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.example.myapplication, PID: 5795
    java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.myapplication/com.example.myapplication.MainActivity}: java.lang.RuntimeException: setAudioSource failed.
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2572)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2654)
        at android.app.ActivityThread.-wrap11(ActivityThread.java)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1488)
        at android.os.Handler.dispatchMessage(Handler.java:111)
        at android.os.Looper.loop(Looper.java:207)
        at android.app.ActivityThread.main(ActivityThread.java:5728)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:789)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:679)
     Caused by: java.lang.RuntimeException: setAudioSource failed.
        at android.media.MediaRecorder.setAudioSource(Native Method)
        at com.example.myapplication.MainActivity.onCreate(MainActivity.java:33)
        at android.app.Activity.performCreate(Activity.java:6368)
        at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1113)
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2519)

Мой код приведён ниже
MainActivity.java
package com.example.myapplication;

import android.media.MediaPlayer;
import android.media.MediaRecorder;
import android.os.Environment;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import java.io.IOException;

public class MainActivity extends AppCompatActivity {

    private Button play, stop, record;
    private MediaRecorder myAudioRecorder;
    private String outputFile;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        play = (Button) findViewById(R.id.play);
        stop = (Button) findViewById(R.id.stop);
        record = (Button) findViewById(R.id.record);
        stop.setEnabled(false);
        play.setEnabled(false);
        outputFile = Environment.getExternalStorageDirectory().getAbsolutePath() + "/recording.3gp";
        myAudioRecorder = new MediaRecorder();
        myAudioRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
        myAudioRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
        myAudioRecorder.setAudioEncoder(MediaRecorder.OutputFormat.AMR_NB);
        myAudioRecorder.setOutputFile(outputFile);
        record.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                try {
                    myAudioRecorder.prepare();
                    myAudioRecorder.start();
                } catch (IllegalStateException ise) {
                    // make something ...
                } catch (IOException ioe) {
                    // make something
                }
                record.setEnabled(false);
                stop.setEnabled(true);
                Toast.makeText(getApplicationContext(), "Recording started", Toast.LENGTH_LONG).show();
            }
        });

        stop.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                myAudioRecorder.stop();
                myAudioRecorder.release();
                myAudioRecorder = null;
                record.setEnabled(true);
                stop.setEnabled(false);
                play.setEnabled(true);
                Toast.makeText(getApplicationContext(), "Audio Recorder successfully", Toast.LENGTH_LONG).show();
            }
        });

        play.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                MediaPlayer mediaPlayer = new MediaPlayer();
                try {
                    mediaPlayer.setDataSource(outputFile);
                    mediaPlayer.prepare();
                    mediaPlayer.start();
                    Toast.makeText(getApplicationContext(), "Playing Audio", Toast.LENGTH_LONG).show();
                } catch (Exception e) {
                    // make something
                }
            }
        });

    }

}

Разметка
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <Button
        android:id="@+id/record"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_marginStart="8dp"
        android:layout_marginLeft="8dp"
        android:layout_marginTop="8dp"
        android:layout_marginEnd="8dp"
        android:layout_marginRight="8dp"
        android:layout_marginBottom="8dp"
        android:text="Record"
        android:textSize="20sp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <Button
        android:id="@+id/stop"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@id/record"
        android:layout_centerHorizontal="true"
        android:layout_marginStart="8dp"
        android:layout_marginLeft="8dp"
        android:layout_marginTop="8dp"
        android:layout_marginEnd="8dp"
        android:layout_marginRight="8dp"
        android:layout_marginBottom="8dp"
        android:text="Stop"
        android:textSize="20sp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.498"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.356" />

    <Button
        android:id="@+id/play"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@id/stop"
        android:layout_centerHorizontal="true"
        android:layout_marginStart="8dp"
        android:layout_marginLeft="8dp"
        android:layout_marginTop="8dp"
        android:layout_marginEnd="8dp"
        android:layout_marginRight="8dp"
        android:layout_marginBottom="8dp"
        android:text="Play"
        android:textSize="20sp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.498"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.247" />
</android.support.constraint.ConstraintLayout>

AndroidManifest
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.myapplication">
    <uses-permission android:name="android.permission.RECORD_AUDIO"></uses-permission>
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission>

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

В чём проблема? Где копать?


text:
Q: how click a button on a web site in vb 6.0 how can i click a button on website given that i have the web browser control in my visual basic 6.0 i need it for my project where i want to automatically click a button from a series of buttons

A: You need to invoke the "click" event on the element.
This will cause all the client-side actions to happen as if the user clicked it with the mouse.


text:
Q: Can I store a set of strings of a multiple line using regex on java? If I have an input of
this is a string
this is also a string
i am a string

can i store them in an array like
[0] this is a string
[1] this is also a string
[2] i am a string

If so, how can I achieve this kind of output?

A: You could use:
String[] output = input.split"\\r?\\n");

That would split the lines if \r\n or \n is used for line breaks.


text:
Q: displaying search results JAVA ArrayLists I am supposed to use the method exactly(all my methods have to return void)
public void searchByPriceRange(double minPrice, double maxPrice)

The method will search the ArrayList<Property> for properties where the asking price is between the minPrice and maxPrice and add each match to a local ArrayList<Property> that will then be passed to another method that has to be
displaySearchResults(ArrayList<Property> searchResults)

How would I create a local ArrayList<Property> that is accessible outside the scope of the first method?(if thats what I am supposed to do)
my instance variable and initialization of ArrayList
 private ArrayList<Property> properties = new ArrayList<Property>();

my method in AgentListing class
public void searchByPriceRange(double minPrice, double maxPrice){

    ArrayList<Property> searchResults;
    searchResults = new ArrayList<Property>();
    for (Property property : properties){
        if (property.getAskingPrice() > minPrice &&
                property.getAskingPrice() < maxPrice){

            searchResults.add(property);

        }
    }
}

my display method AgentListing class
public void displaySearchResults(ArrayList<Property> searchResults){

    for(Property result: searchResults) {

        System.out.println(result);
    }

}

my driver class that I am trying to access the local arraylist with
AgentListings CharlesListings = new AgentListings();

        Property one = new Property("1ListingNumber", "777 Imaginary Drive, Nowhere, British Columbia", 1.00, "Single Family", "House",
            "1.1 Acre", 2007);

    one.setNumberOfBedrooms(1);
    one.setNumberOfBathrooms(1);

    Property two = new Property("2ListingNumber", "777 Imaginary Drive, Nowhere, British Columbia", 2.00, "Single Family", "House",
            "2.2 Acre", 2007);

    two.setNumberOfBedrooms(2);
    two.setNumberOfBathrooms(3);

CharlesListings.addProperty(one);
CharlesListings.addProperty(two);

CharlesListings.searchByPriceRange(1.0, 2.0);

CharlesListings.displaySearchResults(searchResults); //searchResults is not reachable

I added the full instructions to my assignment if I am not clear

A:
How would I create a local ArrayList that is accessible outside the scope of the first method?(if thats what I am supposed to do)

here:
public void searchByPriceRange(double minPrice, double maxPrice)

return a list (searchResults) instead of void...
you can define a temp variable, or just queue the returned value as param to the display method
ArrayList<Property> x = searchByPriceRange(min, max);
displaySearchResults(x);

or
displaySearchResults(searchByPriceRange(min, max));

A: searchResult is a local variable, so it's not visible outside the method it is declared in. A possible solution would be to change the signature of the searchByPriceRange method from:
public void searchByPriceRange(double minPrice, double maxPrice)
to
public List<Property> searchByPriceRange(double minPrice, double maxPrice).
Now you can return the searchResults list, so it can be stored in a variable or passed to another method. Since you only need to pass it to the displaySearchResults method, you could write:
CharlesListings.displaySearchResults(CharlesListings.searchByPriceRange(1.0, 2.0));

A: Modify searchByPrice(...) method like this:
public ArrayList<Property> searchByPriceRange(double minPrice, double maxPrice){

    ArrayList<Property> searchResults;
    searchResults = new ArrayList<Property>();
    for (Property property : properties){
        if (property.getAskingPrice() > minPrice &&
                property.getAskingPrice() < maxPrice){

              searchResults.add(property);
        }
    }
    return searchResults;
}

Now, when it returns searchResults array, you can use the returned value as a parameter for displaySearchResults(searchResults) method.
Like this:
ArrayList<Property> searchResultsList = CharlesListings.searchByPriceRange(1.0, 2.0);
CharlesListings.displaySearchResults(searchResultsList);


text:
Q: Joining HDF files with multi bands and no attribute tables to a shapefile I have a HDF file showing raster data and I want to join this to a shapefile (in ArcGIS) so I can aggregate the values to areas rather than cells.  Unfortunately the HDF has no attribute table so I cannot join. When I try to create one it says it can't be done as isn't a single band file.
Is there a way around it so I can join the data?

A: Use Extract Subdataset to convert the HDF to a raster. Then use Zonal Statistics as Table with your shapefile to aggregate the statistics you would like. Lastly, join the relevant fields in this output table back to the shapefile using Join Field. For multiband HDF, you will need to extract each HDF subdataset index (single band) to individual rasters and apply these tools for as many times as needed. If the HDF sundataset index contains integer values, you may be able to access its attribute table and perform a join by attributes, but zonal statistics is typically used for aggregating raster values to features (shapefiles).


text:
Q: How to typeset and annotate a polynomial long division I need to type a paper for a teacher, who hasn't seen the European division method, so that she could possibly use it in her curriculum.
I need something to look like this
x^2+4x+4       Box(x+2)
-(x^2 + 2x)
----------------
2x+4
-(2x + 4)
-----------------
0

A: Try looking at the package polynom.sty (CTAN, TeXdoc). It can even do the division for you.

A: Here is one way to do this:

Notes:

*

*The booktabs package was used to provide flexible horizontal rules.

*The \Ph macro uses \hphantom{)} to insert a horizontal space equivalent to the closing bracket to get things all aligned.

Code:
\documentclass{article}
\usepackage{amsmath}
\usepackage{booktabs}
\usepackage{array}
\newcommand*{\Ph}{\hphantom{)}}%
\begin{document}
$\begin{array}{r@{} r@{} r r}
  x^2 &{}+4x\Ph&{}+4\Ph       &\fbox{$(x+2)$} \\
-(x^2 &{}+ 2x) &\\
\cmidrule{1-2}
      & 2x\Ph &{}+4\Ph\\
      &-(2x\Ph &{}+4) \\
\cmidrule{2-3}
      & &0\Ph
\end{array}$
\end{document}


text:
Q: How to pull rows from different csv files based on a word I have 36 different csv files with 8 columns in each.
For each csv file I want to only pull rows that contain the words "liver" and "lung" from the column labeled tissue type.
I then want to write a new csv file for each of the 36 files with only the pulled rows.
I'm trying to see if a for loop will work? I am just still really new to this so I am not sure how to combine it all together.

A: You probably want something like this. Note that I cant check this since you didn't provide a reproducible example:
library(tidyverse)

liv_lun_data <- tibble(file = list.files(pattern = "\\.csv")) |>
  mutate(data = map(file, read_csv),
         filtered = map(data, ~filter(.x, `tissue type` %in% c("liver","lung")))) |>
  select(file, filtered) |>
  unnest(filtered)


text:
Q: flash progress bar in webpage? Using javascript How to make progress bar in my page, that show how much flash file got progress in dwonload.

A: I'm guessing you mean just a normal flash preloader inside flash? There are loads of different tutorials on Google each showing you examples of how to do it in AS2 and AS3 with example code.
AS2:
http://the-dude.co.uk/tutorials/basic-flash-preloader-as2/
AS3
http://www.republicofcode.com/tutorials/flash/as3preloader/

A: This loading bar tutorial will get you started.


text:
Q: Data Submit Interruption of html Form inserting data in mysql I have this problem where in my Applicant Quiz using php, javascript, mysql. Its a simple quiz created from html forms, with a .php for inserting in the database for the applicants answer. It has a timer of 10 minutes that auto-submits the form and sets the value of 0 to blank fields and get inserted into the database.
But the problem here is, sometimes, when submitting, it was not get inserted into the database, but sometimes it was succesfully submitted, I am using WAMP server, I have a desktop as the admin for monitoring submitted exams, and 6 laptops all connected through the same client network I created in the router, I am using ASUS BRT-AC828 Router.
should I connect all the devices on the original ASUS 2.4 network? rather than creating a client network named, GHS_Exams? could this be the one that affects why sometimes the submission didnt get inserted in the database?


text:
Q: Non-Scientific questions solved by mathematics I have a general question about the applications of mathematics.
What are some applications of mathematics that are not scientific, perhaps maybe literary or philosophical, or political.
I am basically asking for the scope of mathematics, and looking for concrete examples.

A: Gödel's theorem had a great impact in logic and, hence, in philosophy.

A: As a simple example I would cite the Seven Bridges of Königsberg problem solved by Euler. At that time, Euler was mailed by a politician of the city of Königsberg asking him to help in a problem of finding the "touristically" best walk through some bridges of the city. Euler, at first, argued that such a problem was not a mathematical problem. But the politician insisted writing back to Euler saying that no engineer that was consulted had a conclusive answer. So, after reviewing the problem, Euler realized that the problem was asking for a solution that had nothing to do with geometry (I mean, a solution that is not metric related) as everybody was expecting. At the end, Euler proofed topologically the existence of a solution and gave rise to a new branch of mathematics: topology.

A: Michael Harris's article An automorphic reading of Thomas Pynchon's Against the Day describes some applications of mathematics to literature.  (On the same page, the article Do android's prove theorems in their sleep? gives some applications of literature to mathematics.)

A: In my opinion, the application of mathematics outside of fields where its use is well-established like physics is dangerous.
Mathematics cannot prove anything about the world: it can only prove things about models of the world.  Some people take their models too seriously. Sometimes, mathematics which approximate reality or some portion thereof—with caveats—are interpreted (by mistake, or willfully) as authoritative and correct descriptions of reality. For example, the Gaussian copula approximation of David X. Li was putatively abused by mortgage-bond traders in investment banks antecedent to the financial-market crash of 2008.
By literary applications,  do you mean applications to the study of literature, or to its creation?  And does the latter mean inspiration or something else?  Certainly art draws its inspiration from many sources.

A: Through computer science and finally software develeopment, almost all questions people post these days are solved "by" (rather "with the help of") mathematics. Take Google as a prominent example.

A: Breaking the Enigma code was an application of mathematics to warfare, which would probably not be regarded as a scientific application.  My understanding is that mathematics continues to play a large role in modern cryptanalysis (such as in the work of the NSA in the United States).

A: One example of the influence of mathematics on politics would be Arrow's Impossibility Theorem, which states something like "no voting system is perfectly fair".
Similarly, game theory has applications to economics and politics.

A: Mathematics expands one's imagination. As such, while it might not solve philosophical, literary, or political "problems", it can give one a different perspective on questions from those fields.
Here are some examples of applications of mathematics outside science. I blog about this topic, so several of the links will be to short essays I have written that directly address your question.

*

*Christopher Alexander's essay A City Is Not A Tree relates graph theory, posets, lattice theory, and order theory to the design of cities.

*C. Alexander's book Notes on the Synthesis of Form more generally relates the mathematical structure of objects to design problems and architecture. Alexander's book was the basis for a movement in software programming (another kind of architecture).

*An application of Andrei Kolmogorov's axioms of probability has been to literary analysis. One can do probabilistic analysis of texts to bolster or attack theories about a text. I think Kolmogorov actually developed his axioms so that they would be applicable to text (Tolstoy was a big deal in Kolmogorov's time, as well as ours).

*Generalisations about groups of people ("men", "feminists", "vegetarians") are often better understood using a distribution or probability theory. (E.g., "women sprint slower than men" should be understood to mean "the average woman sprints slower than the average man", or perhaps a statement about the relative skew of the two populations, etc.)

*The post-structural "critique of binary opposition" meets an alternative within group theory. $SU(3)$ is an example of a "trichotomy" and finite group theory offers many other relational alternatives besides binary opposition.

*Some postmodern philosophers are interested in applying topology to cultural analysis.

*There is a branch of political science called spatial voting theory which models voting patterns of citizens and legislators using mathematics.

*As mentioned in another answer, Arrow's impossibility theorem bears on politics as well. Other applications of mathematics to politics include fair division problems and optimal gerrymandering.

*Economics and psychology are not really sciences and both have adapted mathematical modelling.

*As mentioned elsewhere, some 20th-century authors (Borges, Pynchon, and Neal Stephenson come to mind) incorporated mathematics into their fiction.

*Finance is not a science either and the geometric series is daily applied there to compute net present value.

*The geometric series / analysis of $\sum_0^{\infty} {1 \over 2^n}$ also resolves Zeno's Paradox.

*Ancient (e.g. Pythagorean) and modern (e.g. La Monte Young's) theories & practices of music have involved mathematics.

*Stephen Wolfram, John Rhodes, and Kenneth Krohn have all applied semigroup theory (finite state automata) to philosophical problems. The Church-Turing thesis has implications for philosophy as well.

*Epistemology and the problem of causality is addressed by statistics and probability, as well as graph theory.

*John Gottman famously applied dynamical systems theory to the question of love -- which is far from scientific!

*The philosophical problem of mutual causation ("which came first, the chicken or the egg?") is addressed by dynamical systems theory.

*Dynamical systems are also used in philosophy to address questions about the mind, the body, and the environment within which a mind/body finds itself.

*The field of computational linguistics has implications for literature and philosophy and is mathematically posed.

*The philosophy of language and philosophy of logic are both strongly influenced by mathematics (graph theory, category theory, boolean algebra, heyting algebra, ...)

*The religious and philosophical implications and meanings of "infinity" have been addressed in mathematics (calculus, cardinality of sets, transfinite arithmetic, the continuum hypothesis, ...).

*Quantum mechanics has many implications for philosophy and is quite mathematical (you may object that it's science, but there is a philosophical side which is less scientific).

*Nietzsche proposed (I think in The Eternal Return) that after an infinite amount of time, a complex system must repeat itself. Cantor disproved this with a dynamical system that evolves according to $(\exp i \cdot \omega t, \exp i \cdot 2 \omega t, \exp i \cdot {\omega \over \pi} t )$ (such a system, despite having only three parts, will never exactly repeat itself).

*Dmitri Tymoczko has written a book about how the harmonic value system of Western music (typical theory of music for Western Europe 17th-19th centuries) corresponds to an orbifold.

A: Lacan applied Topology to Psychoanalysis, to great acclaim (at least of his multitudinous followers).

A: A professor gave a talk in our seminar about using math to find a proto-language, a language that is an earlier ancestor of many modern languages.  Among other techniques they used the "killing fish" method to try to find correlations between two now distinct languages.  The method is described as such:  If you want to find the deepest part of the ocean you can place a single fish in the water and slowly drain the water.  As the water level lowers, the fist will seek out deeper and deeper places.  Eventually the fish will get stuck in a local minimum.

A: I believe that Tarski's truth undefinability theorem has uses in philosophy, as the mentioned incompleteness theorems, and that's besides cranks attributing it to proofs that god exists, that mathematics is just a bunch of crap etc etc.
I have a friend who's studying cognitive science (as well as a math degree) and he says that there's some good math modeling there, and we all saw the financial Nobel prizes that were given to mathematicians.
However, I have a quarrel with the idea of using mathematics outside the ideal realm of mathematical objects. This is because mathematics is inherently precise and perfect, you can define notions that capture exactly what you want them to capture, while our "real" world is inherently imperfect and imprecise - and we can never judge what's true in the real world, as Tarski's theorem tells us.
The above argument means that taking mathematics into the real world is to allow imperfect and imprecise definitions and "latitude" for things to change beyond our original meaning. This is not mathematics anymore, in my eyes anyway.
In the very first math class I had in the academia, the teacher came in and said "Mathematics is the science of deducing from certain assumptions." and three and a half years later, I only grow to understand deeper and deeper how true this is. In the real world, i.e. outside of mathematical idealism, you can't prove anything - only find evidence to supposedly support a claim, or disprove it. So the ability to assume things and deduce things with absolute certainty becomes problematic. Which is non-mathematical in my eyes anyway.

A: Some literary works are attributed to famous writers but doubtfully so. One way of checking whether they're genuine is by extracting and comparing statistical "fingerprints". The field is called "computational stylometry". One of the standard challenges is identifying which works are genuine Shakespeare and which should be attributed to Fletcher (as if it mattered who wrote the piece, rather than its "artistic worth").

A: Interestingly, I saw this video a couple of days back and I think this is relevant to the question though it may not directly answer your question.
"L'importance des mathématiques" by Timothy Gowers at The Millennium Meeting

A: Although from physics (not necessarily mathematics), the second law of thermodynamics is often applied to topics outside of its strict application domain (heat and work) to state that chaos and disorder generally increase.

A: (adding the comment as answer)
If it can be formulated in the symbolic language of mathematics, it becomes scientific parlance, hey even if sth is not formulated in symbolic language it can still be scientific.

A: These are some (intuitive?) ideas, by no means I advocate them as they lack any type of rigor/sound philosophical reasoning that might justify them, read with extreme suspicion/scepticism/disapproval/disbelief : (This is a non scientific drawing of analogies/hand waving post between math and non scientific things)
Philosophy : Set theory (when dealing with infinities), shows the limits of human knowledge.
e.g. even if the universe was infinite and we could use every single particle to store information, then the relationship between every object in the universe is in the power set and Just like the real line is beyond any description in a list/book/linear manner.
Philosophy/Religion Gödel's theorem : Many religions use the selling point : "ultimate/absolute truth and complete set of rules to live by" , where as Gödel's theorem shows mush simpler set of rules are incomplete,inconsistent or both.
Philosophy/Religion : Game of life is a good example of determinism does not imply predictability, give very few simple rules,  there is no way to figure out what will happen by the rules alone.

A: APPORTIONMENT of seats in a legislature to districts.  I don't mean drawing the districts.  For example, given that the 50 states are what they are, and the House of Representatives shall have 535 members, how many representatives should each state be given?


text:
Q: Deployment configured as YAML as part of a Pipeline We have been using a YAML file to do our CI in Azure DevOps for a few months with the idea that we would get our release configured using YAML in the future.
Well that time is now and I'm confused by how you would introduce a CD process. With the MyProject-CI.yml being a Build Pipeline and our Releases being Classic Pipelines I assumed that when the time came to get the CD process down as YAML we would create a MyProject-CD.yml. That would be triggered by the dropping of an Artifact within the MyProject-CI.yml CI.
However I think that was just a misunderstanding on my behalf and what we are supposed to do is convert the original MyProject-CI.yml into a multi-stage pipeline that has the following stages

*

*Build and Run Unit Tests

*Deploy to Development and run WebTests

*Deploy to Production and run WebTests

Is the switch to a multi stage CI/CD in one file correct rtaher than Release and Build in separate files?

A: The short answer is yes, you got the idea. A single multi-stage pipeline yml is the way to do both build and deploy, and that is the base intention. Here is an exercise that parallels your case that might help.
As your pipelines get more complex, you will likely get into scenarios with multiple files, as you can template parts of your pipeline for reuse in multiple places, or to enforce conventions from a central location.


text:
Q: Get every year last date values from data frame I have a Data frame like this(from 1971 to 2021).
             date  AUDUSD Close
 42    2020-12-29        0.7608
 41    2020-12-30        0.7676
 40    2020-12-31        0.7709
 39    2021-01-04        0.7664
 38    2021-01-05        0.7767
 37    2021-01-06        0.7799
 36    2021-01-07        0.7767

now i want to get every year last date values from data frame. above example i want line No 40. Any one know how to do this?
Thanks.

A: Use GroupBy.last by years:
df['date'] = pd.to_datetime(df['date'])

df = df.groupby(df['date'].dt.year).last().reset_index(drop=True)
print (df)
        date  AUDUSD Close
0 2020-12-31        0.7709
1 2021-01-07        0.7767


text:
Q: 404 for Custom ttf Font on Azure (.NET MVC 5) I have an issue that I have seen previously answered.  I implemented the solutions, but the problem persists.
I downloaded two custom ttf fonts to use in my project, Monterey and Bakery.
Both fonts are installed.  Both fronts are in my content folder.  I've updated the font properties for both so that content copies "if newer" on build.  I added necessary language to my web config file.  I create font-face rules in my CSS.
On my local machine, even when accessing the AzureSites version of my app, the custom fonts appear.  On every other computer, they do not appear and present a 404 in the console.
Please see the pictures below.  Thanks in advance for the help!

EDITED to add images of the CSS files.

A: My suspicion is that the issue is the ..  in ..\fonts/baker.ttf.
Let's say that your directory structure is
content/
   styles/
     stylesheet.css
   fonts/
     baker.ttf

so when your html contains
<link rel="stylesheet" href="/content/styles/stylesheet.css"/>

the resolved url is /content/styles/../fonts/baker.ttf and everything works great.
But with mvc when its deployed, your stylesheet is probably getting bundled and compiled with bundler. The link is probably something like
<link href="/bundles/css?v=Mny4y0TdpT_Ey6yWlayc6zrqhuQE-XSEh-dK8IJOsqc1" rel="stylesheet">

so then the resolved url is /bundles/../fonts/baker.ttf which does not exist. I cannot see from the screenshot if that is the case but that is my guess.
Try using an absolute url such as /content/fonts/baker.ttf for the font-face import rather than a relative one.
Also, that backslash is highly suspect. Use a forward slash, backslashes are not a valid separator in urls.


text:
Q: Are Imaged that are not being displayed downloaded? Let's say I have an Image, use it with display: none;
Are Client Browser downloding that image?

A: Yes, display: none only hides it on the screen, the CSS does not stop the request from image being downloaded to client.