text:
Q: Scroll To Item UICollectionView with UIButton programmatically I'm having a moment of confusion and I can't solve a very simple thing.
My CollectionView has 50 cells and I would like to scroll back and forth between the cells using a "Next" button and a "Back" button. I am aware of the scrollToItemAtIndexPath method but I have problems finding the right IndexPath .. Someone can help me ?
This is my Code:
// My personal method

-(void)scrollYearAtIndex:(NSInteger)index {
    NSIndexPath *indexPath = [NSIndexPath indexPathForItem:index inSection:0];
    [_collectionView scrollToItemAtIndexPath:indexPath atScrollPosition:UICollectionViewScrollPositionCenteredHorizontally animated:YES];
}

// Show Next Items
-(void)didScrollNextYear {
    [self scrollYearAtIndex:????];
}

// Show Previous Items
-(void)didScrollPreviousYear {
    [self scrollYearAtIndex:????];
}

A: I've given the answer in Swift. You can write the same logic in Objective-C.
To get the next indexPath, get the last indexPath of the sorted indexPathsForVisibleItems array and increment by 1.
To get the previous indexPath, get the first indexPath of the sorted indexPathsForVisibleItems array and decrement by 1.
func didScrollNextYear() {
    if let index = self.collectionView.indexPathsForVisibleItems.sorted().last?.row {
        let nextIndex = index+1
        if nextIndex < self.collectionView.numberOfItems(inSection: 0) {
            self.collectionView.scrollToItem(at: IndexPath(row: nextIndex, section: 0), at: .centeredHorizontally, animated: true)
        }
    }
}

func didScrollPreviousYear() {
    if let index = self.collectionView.indexPathsForVisibleItems.sorted().first?.row {
        let previousIndex = index-1
        if previousIndex >= 0 {
            self.collectionView.scrollToItem(at: IndexPath(row: previousIndex, section: 0), at: .centeredHorizontally, animated: true)
        }
    }
}

A: let indexPaths : NSArray = self.collectionView!.indexPathsForSelectedItems()
let indexPath : NSIndexPath = indexPaths[0] as NSIndexPath

This will give you current selected index path. In didScrollNextYear method, increment indexPath.row by one. And in didScrollPreviousYear, decrement indexPath.row by one.
Sample code:

// Show Next Items
-(void)didScrollNextYear {
    let indexPaths : NSArray = self.collectionView!.indexPathsForSelectedItems()
    let indexPath : NSIndexPath = indexPaths[0] as NSIndexPath

    [self scrollYearAtIndex: indexPath.row+1];
}

A: Call This function to next and previous button IBAction
 func scrollToNextCell()
{

    let collectionView = yourCollectionView
    let cellSize = CGRect(x: 0, y: 0, width: self.view.frame.width, height: self.view.frame.height)
    let contentOffset = collectionView!.contentOffset;
    collectionView!.scrollRectToVisible(CGRect(x: contentOffset.x + cellSize.width, y: contentOffset.y, width: cellSize.width, height: cellSize.height), animated: true)
}

func scrollToPreviousCell()
{

    let collectionView = yourCollectionView
    let cellSize = CGRect(x: 0, y: 0, width: self.view.frame.width, height: self.view.frame.height)
    let contentOffset = collectionView!.contentOffset;
    collectionView!.scrollRectToVisible(CGRect(x: contentOffset.x - cellSize.width, y: contentOffset.y, width: cellSize.width, height: cellSize.height), animated: true)
}


text:
Q: Can't get the right shape for tf.matmul or tf.squared_difference From a DNA sequence, I one hot encoded every base (A,C,G,T,N) to
{'A': [1, 0, 0, 0, 0],
 'C': [0, 1, 0, 0, 0],
 'G': [0, 0, 1, 0, 0],
 'T': [0, 0, 0, 1, 0],
 'N': [0, 0, 0, 0, 1]}

Every DNA sequence has 400 bases. So my final training data has a shape X_train.shape = (111453, 400, 5) (111453 rows, 400 letters, every letter encoded in a 5 element vector)
My label data is a simple yes/no, so if the DNA sequence has an error it is [1], if not, it is [0], so Y_train.shape is (111453,1)
I'm trying to build a small NN with tensorflow.
layer_1_nodes = 5
layer_2_nodes = 10
layer_3_nodes = 5
learning_rate = 0.001
training_epochs = 5
number_of_outputs = 1

# Input Layer
with tf.variable_scope('input'):
    X = tf.placeholder(tf.float32, shape=(None, 400, 5), name="X")

# Layer 1
with tf.variable_scope('layer_1'):
    weights = tf.get_variable("weights1", shape=[400, 5, layer_1_nodes], initializer=tf.contrib.layers.xavier_initializer())
    biases = tf.get_variable(name="biases1", shape=[layer_1_nodes], initializer=tf.zeros_initializer())
    layer_1_output = tf.nn.relu(tf.matmul(X, weights) + biases)

# Layer 2
with tf.variable_scope('layer_2'):
    weights = tf.get_variable("weights2", shape=[400, layer_1_nodes, layer_2_nodes], initializer=tf.contrib.layers.xavier_initializer())
    biases = tf.get_variable(name="biases2", shape=[layer_2_nodes], initializer=tf.zeros_initializer())
    layer_2_output = tf.nn.relu(tf.matmul(layer_1_output, weights) + biases)

# Layer 3
with tf.variable_scope('layer_3'):
    weights = tf.get_variable("weights3", shape=[400, layer_2_nodes, layer_3_nodes], initializer=tf.contrib.layers.xavier_initializer())
    biases = tf.get_variable(name="biases3", shape=[layer_3_nodes], initializer=tf.zeros_initializer())
    layer_3_output = tf.nn.relu(tf.matmul(layer_2_output, weights) + biases)

with tf.variable_scope('layer_drop'):
  dropout = tf.layers.dropout(
      inputs=layer_3_output, rate=0.4)

# Output Layer
with tf.variable_scope('output'):
    weights = tf.get_variable("weights4", shape=[400, layer_3_nodes, number_of_outputs], initializer=tf.contrib.layers.xavier_initializer())
    biases = tf.get_variable(name="biases4", shape=[number_of_outputs], initializer=tf.zeros_initializer())
    prediction = tf.matmul(dropout, weights) + biases

with tf.variable_scope('cost'):
    Y = tf.placeholder(tf.float32, shape=(None, 1), name="Y")
    cost = tf.reduce_mean(tf.squared_difference(prediction, Y))

But I'm always getting errors regarding to the shape of the tensors. Either the first matmul in layer 1, or the cost squared_difference() (Incompatible shapes: [400,400,1] <- the prediction tensor vs. [111453,1])
Tried a model with keras:
input_shape = (400, 5, 1)

model = Sequential()
model.add(Conv2D(32, kernel_size=(3, 3),
                 activation='relu',
                 input_shape=input_shape))

But I can't get my input shape right.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to calculate a polynomial equation in haskell Basically I need to calculate a polynomial in haskell based on a value x, and the values of the coeficients need to be stored in a list of tupples.
So for example the polynomial f(x) = a·xn + a1·xn−1 + ... + an−1·x + an will be represented in a list of tuples like f = [(a0, n), (a1, n-1), ... , (an-1, 1), (an, 0)] , so if I want to calculate
2*x^2 + 3*x + 3 for x=20 I will need the list [(2,2), (3,1) , (0,3)].
Thanks a lot in advance and sorry if I explained this exercise in a messy way :)

A: If you want a basic solution, try using explicit recursion:
evaluate :: [(Int, Int)] -> Int -> Int
evaluate []             _x = .... -- TODO (1)
evaluate ((a,n) : rest)  x = .... -- TODO (2)
   where
   result = evaluate rest x

Above, in (1) we need to specify what is the result of evaluating an "empty" polynomial (with no coefficients at all). This is the base case of our recursion.
Instead, (2) is the recursive step. Here, we split the coefficients-pairs into the first (a,n), and the rest of the list rest. We then recursively define result = evaluate rest x to evaluate the polynomial "without the first coefficient", that is a1·xn−1 + ... + an−1·x + an.
Then, in line (2) we need to combine this result with the first monomial, evaluated in x.
You should now be able to fill the dots.

A: Easy: just fold over the list. The accumulator function should add the current term (solved for x) to the accumulate. The seed needs to be 0, of course.

A: something like this
> peval p x = foldr (\(a,n) s -> s+(a*x^n)) 0 p
> poly = peval [(2,2),(3,1),(3,0)]
> map poly [0..5]

[3,8,17,30,47,68]


text:
Q: Save array to binary file not working c++ I have an unsigned char array in c++, and I want to save it's bits into a file.
So for example if I have the array below
arr[0] = 0;
arr[1] = 1;
arr[2] = 2;

I want to save this into the file so that the binary data of the file looks like this (without the spaces).
00000000 00000001 00000010

I have tried this code below but it doesn't seem to work. I give the program a blank file that is 0 bytes in size, and after the program runs the file remains 0 bytes in size (nothing gets written to it).
// Create unsigned char array
unsigned char *arrayToWrite= (unsigned char*)malloc(sizeof(unsigned char)*720);

// Populate it with some test values
arrayToWrite[0] = 0;
arrayToWrite[1] = 1;
arrayToWrite[2] = 2;

// Open the file I want to write to
FILE *dat;
dat = fopen("filePath.bin", "wb");

// Write array to file
fwrite(&arrayToWrite, sizeof(char)*720, 1, dat);
fclose(dat);

I would expect after this program runs that the file "filePath.bin" would be 720 bytes long filled with mostly 0's except for the first and second position I filled with test data.
What am I doing wrong? Any help would be much appreciated! Thank you!

A: The basic issue there is that you're passing the pointer to your arrayToWrite variable, rather than to the array itself. Change fwrite(&arrayToWrite... to fwrite(arrayToWrite....
BTW, malloc() does NOT promise to give you zeroed memory. For that, use calloc() to allocate and zero memory or memset() to zero already-allocated memory. (Though all that is more a C thing; for C++ you'd be better off using something like std::vector instead of raw C arrays.)

A: C++ code is written different way:
std::vector<unsigned char> vectorToWrite = { 0, 1, 2 };
vectorToWrite.resize( 720 );
std::ofstream file( "filePath.bin", std::ios::out | std::ios::binary );
if( !file ) {
    // error handling
}
file.write( vectorToWrite.data(), vectorToWrite.size() * sizeof( decltype(vectorToWrite)::value_type ) );

Note: I put sizeof( decltype(vectorToWrite)::value_type ) there so if you later change vector data it will still properly work without further change, but in case of char it can be omitted completely as sizeof(char) is always equal to 1


text:
Q: devolver un char* por funcion enum Month{JANUARY=1,FEBRUARY,MARCH,APRIL,MAY,JUNE,JULY,AUGUST,SEPTEMBER,OCTOBER,NOVEMBER,DECEMBER};
struct Date{
    int Day;
    Month month;
    int Year;
};

char* to_str_date(Date d){
     int i,j=0;
     int lista[8]={(d.Day/10),(d.Day%10),(int(d.month)/10),(int(d.month)%10),(d.Year/1000),((d.Year/100)%10),((d.Year/10)%10),(d.Year%10)};
     char *date="hola";
     for(i=0;i<8;i++){
         if(i==2 || i==4){
             date[j]='/';
             j++;
         }
         date[j]=char(lista[i]+48);
         j++;
     }
return date;
}

esta es una función que debería de recibir una estructura date {dia,mes,año} y devolver un char* con el formato "dd/mm/yyyy" .el problema es que cuando imprimo la cadena a esta le faltan los últimos 2 dígitos correspondientes al año, creo q el problema es porque no se reserva suficiente memoria para usar la cadena date, agradecería cualquier ayuda :).
y también note que si imprimo las variables dentro de la función esta devuelve una cadena vacía quisiera saber a que se debe eso, por que no le encuentro sentido...

A: Varias cosas a notar.
char *date="hola";

Aquí date apunta a un literal, es un valor fijo asignado en tiempo de compilación. Intentar modificarlo puede causar problemas (undefined behavior).
Sería mejor hacer
char *date = (char*) malloc(sizeof(char) *5);
strcpy(date, "hola");

La primera instrucción reserva espacio para el texto, la segunda copia "hola" en ese espacio. Tampoco está claro para qué necesitas asignar el valor "hola".
La segunda cuestión obvia es que estás definiendo el literal con una longitud de 5 chars pero luego quieres asignarle 11 caracteres. Al tener j mayor que 4, hacer date[j]= ... escribe en una posición de memoria no reservada, de nuevo undefined behavior.
Lo más sencillo es simplemente reservar el espacio necesario:
 char *date = (char *) malloc(sizeof(char) * 11);

Y no hay que olvidarse que un string acaba con \0, así que hay que hacer
 date[10] = (char) 0;


text:
Q: Remove variable name from JSON data in ASP.NET MVC I'm trying to send a string of JSON to the client from a database for a JavaScript plugin to highlight the states it gets back. However, in addition to the state information I need, I'm also getting the variable name. Is there anyway I can correct the formatting so that instead of it looking like this:
{"statesHighilght":["California","Washington","Utah","Utah","Florida","Kansas","Utah"]}

I get this:
["California","Washington","Utah","Utah","Florida","Kansas","Utah"]

This is what my controller code looks like:
public ActionResult highlight()
{
    var statesHighlight =
        db.Jobs
            .Select(r => r.State);
    return Json(new { statesHighilght }, JsonRequestBehavior.AllowGet);
}

A: Pass the enumerable directly to the Json method instead of wrapping it in an anonymous object.
return Json(statesHighlight, JsonRequestBehavior.AllowGet);


text:
Q: Lift of a Lie group homomorphism is a Lie group homomorphism Let $\tilde{G},G,H$ be Lie groups with $H$ connected, $f:H\to G$  a Lie group homomorphism, and $p:\tilde{G}\to G$ be a covering map that is also a Lie group homomorphism. Suppose $\tilde{f}:H\to \tilde{G}$ is a (not necessarily continuous) lift of $f$ that is a group homomorphism. Then is it necessarily true that $\tilde{f}$ is continuous, and hence a Lie group homomorphism?
Actually I want this result to show that the map $\rho:U(V)\to \text{Spin}^c(V)$ defined here An embedding of $U(n)\to \text{Spin}^c(n)$ is continuous. This map $\rho$ is a lift of the map $U(V)\to SO(V)\times S^1$ given by $A\mapsto (i(A),\det(A))$ where $i:U(V)\to SO(V)$ is inclusion. (Note that there is a double covering $\text{Spin}^c(V)\to SO(V)\times S^1$.)

A: $\newcommand{\wt}{\widetilde}\newcommand{\by}{\times}\newcommand\R{\mathbb R}\newcommand\Z{\mathbb Z}\newcommand\Q{\mathbb Q}$
The $\wt f$ you describe will not always be continuous. As a simple case, say $G=H=\R$ and let $\wt G=\R\by\Q$ with covering map given by projection onto $\R$. Let $f:\R\to\R$ be the identity, so choosing a lift $\wt f:\R\to\R\by\Q$ amounts to choosing a group homomorphism $\R\to\Q$. There are plenty of these. For example, observe that $\R$ is a $\Q$-vector space and fix an (uncountable) basis $\{e_i\}_{i\in I}$. Let $\lambda_i:\R\to\Q$ be projection onto the $i$th factor, i.e. given $r\in\R$, one has
$$r=\sum_{i\in I}\lambda_i(r)e_i.$$
Then, $\wt f(r):=(r,\lambda_i(r))$ is a lift of $f$ and a group homomorphism for all $i\in I$, but these maps are typically not continuous.


text:
Q: Calculating the integral $\int_0^{\infty} \frac{\cos (kx)}{x^2+a^2} dx$ as an double integral I want to calculate:  $$\int_0^{\infty} \frac{\cos (kx)}{x^2+a^2} \tag{1}  $$
Therefore I can use:  $$\frac{x}{a^2+x^2}=\int_{0}^{\infty}e^{-ay}\sin (xy)dy \tag{2}$$
$2 \ in \  1  $ leads to:
 $$I=\int_{0}^{\infty}\frac{\cos kx}{a^2+x^2}dx=\int_{0}^{\infty}\frac{\cos kx}{x}dx\int_{0}^{\infty}e^{-ay}\sin (xy)dy.$$
Changing the order of integration yields( I'm not sure how to justify that. Maybe I can use Fubini/Tonelli ?!):
$$I=\int_{0}^{\infty}e^{-ay}dy\int_{0}^{\infty}\frac{\sin xy}{x} \cos kx dx. $$
I know: $$ \int_{0}^{\infty}\frac{\sin x}{x} dx = \frac{\pi}{2}  \tag{3}$$
How can I use $3$ to calculate  $$ \int_{0}^{\infty}\frac{\sin xy}{x} \cos kx dx. $$

A: Given the integral:
$$I(k) := \int_0^{\infty} \frac{\cos(k\,x)}{x^2 + a^2}\,\text{d}x $$
with $a,\,k > 0$, differentiating under the integral sign, we have:
$$I'(k) = \int_0^{\infty} -\frac{x\,\sin(k\,x)}{x^2 + a^2}\,\text{d}x \,.$$
Now, adding both members as follows:
$$I'(k) + b = \int_0^{\infty} -\frac{x\,\sin(k\,x)}{x^2 + a^2}\,\text{d}x + \int_0^{\infty} \frac{\sin(k\,x)}{x}\,\text{d}x\,, $$
where $b$ is known but we don't care, we get:
$$I'(k) + b = \int_0^{\infty} \frac{a^2\,\sin(k\,x)}{x\left(x^2 + a^2\right)}\,\text{d}x$$
and therefore it's again possible differentiating under the integral sign, obtaining:
$$I''(k) = a^2\int_0^{\infty} \frac{\cos(k\,x)}{x^2 + a^2}\,\text{d}x\,,$$
ie:
$$I''(k) = a^2\,I(k)\,.$$
Solving this differential equation, we have:
$$I(k) = c_1\,e^{a\,k} + c_2\,e^{-a\,k}$$
where $c_1$ and $c_2$ are two constants to be determined.
In particular, noting that:
$$|I(k)| \le I(0) = \int_0^{\infty} \frac{1}{x^2 + a^2}\,\text{d}x = \frac{\pi}{2\,a}$$
it follows trivially that:
$$I(k) = 0\cdot e^{a\,k} + \frac{\pi}{2\,a}\cdot e^{-a\,k}\,,$$
ie:
$$\int_0^{\infty} \frac{\cos(k\,x)}{x^2 + a^2}\,\text{d}x = \frac{\pi}{2\,a}\,e^{-a\,k}\,,$$
as we wanted to prove.

A slightly different way is to remember that:
$$\frac{a^2}{x^2 + a^2} = \int_0^{\infty} e^{-\frac{x}{a}\,y}\,\sin y\,\text{d}y$$
$$\frac{x}{x^2 + k^2} = \int_0^{\infty} e^{-x\,y}\,\cos (k\,y)\,\text{d}y$$
with $a,\,k,\,x > 0$, then:
$$I(k) = \frac{1}{a^2}\int_0^{\infty} \cos(k\,x)\,\text{d}x \int_0^{\infty} e^{-\frac{x}{a}\,y}\,\sin y\,\text{d}y$$
ie:
$$I(k) = \frac{1}{a^2}\int_0^{\infty} e^{-\frac{y}{a}\,x}\,\cos(k\,x)\,\text{d}x \int_0^{\infty} \sin y\,\text{d}y$$
from which:
$$I(k) = \frac{1}{a^2}\,\int_0^{\infty} \frac{(y/a)\,\sin y}{(y/a)^2 + k^2}\,\text{d}y = -\frac{1}{a} \int_0^{\infty} -\frac{x\,\sin(k\,x)}{x^2 + a^2}\,\text{d}x\,,$$
ie:
$$I(k) = -\frac{1}{a}\,I'(k)\,.$$
Solving this differential equation, we have:
$$I(k) = c_1\,e^{-a\,k}$$
and since:
$$I(0) = \int_0^{\infty} \frac{1}{x^2 + a^2}\,\text{d}x = \frac{\pi}{2\,a}$$
it follows trivially that:
$$I(k) = \frac{\pi}{2\,a}\cdot e^{-a\,k}\,,$$
ie:
$$\int_0^{\infty} \frac{\cos(k\,x)}{x^2 + a^2}\,\text{d}x = \frac{\pi}{2\,a}\,e^{-a\,k}\,,$$
as we wanted to prove.

A: FYI, be careful with how you write your integrals. You've written them to appear like a product of two integrals, whereas you want them to be an iterated integral. See below for the correct way to write that.
Anyways, to answer your question,

$$I=\int_{0}^{\infty}e^{-ay}\left[\int_{0}^{\infty}\frac{\sin xy}{x} \cos (kx) dx\right] dy. $$
I know: $$ \int_{0}^{\infty}\frac{\sin x}{x} dx = \frac{\pi}{2}  \tag{3}$$
How can I use $3$ to calculate  $$ \int_{0}^{\infty}\frac{\sin xy}{x} \cos kx dx. $$

The key is the product-to-sum identity
$$
\sin(xy)\cos(kx) = \frac{\sin([y+k]x)+\sin([y-k]x)}{2}
$$
combined with a change of variables:
$$
\int_0^\infty \frac{\sin(rx)}{x}dx = \int_0^\infty \frac{\sin(\mathrm{sgn}(r)|r|x)}{|r|x}|r|dx = \mathrm{sgn}(r)\int_0^\infty \frac{\sin(u)}{u}du = \frac{\pi}{2}\mathrm{sgn}(r).
$$
$\mathrm{sgn}$ is the signum function, which is $1$ for positive numbers, $-1$ for negative numbers, and $0$ for $0$. Putting these together gives
$$
I=\int_{0}^{\infty}e^{-ay}\left[\int_{0}^{\infty}\frac{\sin xy}{x} \cos (kx) dx\right] dy = \int_0^\infty e^{-ay}\left[\int_0^\infty\frac{\sin([y+k]x)+\sin([y-k]x)}{2x}dx\right]dy \\= \int_0^\infty e^{-ay}\left(\frac{\pi}{4}\left[\mathrm{sgn}(y+k)+\mathrm{sgn}(y-k)\right]\right)dy = \frac{\pi}{2}\int_0^{|k|}e^{-ay}dy = \frac{\pi}{2a}e^{-|k|a}
$$
As for Fubini's theorem, it's not strictly speaking justified here as the double integral isn't absolutely convergent. It is absolutely convergent on every finite subset of the region of integration, though, which might be enough.


text:
Q: How can I get Tampermonkey's Chrome Sync to actually sync? Firstly, the Tampermonkey sync setup is described here.
The above-described process is not working for me, however. I've written a few scripts on one machine, where Chrome Sync is enabled, and have enabled the same sync functionality on a couple of other machines, neither of which are picking up the scripts. On all of the machines, Chrome is logged into my Google account.
I wondered if there might be some kind of delay, but everything has been setup for nearly 24 hrs at this point, so I don't believe that is an issue.

A: The issue is that Chrome Sync requires there to be an @downloadURL or @updateURL tag set where the service can retrieve the script information. The only data actually synced via the Chrome Sync service is the URL to the script, not the script itself.
Since all my scripts were made by myself, this doesn't work. There does not appear to be a working solution for syncing personal scripts conveniently at this time.
Chrome Sync details found here: http://forum.tampermonkey.net/viewtopic.php?f=17&t=312


text:
Q: sql query mass generation in excel I am new here so please take it easy on me :)
I have an update query for SQL, but the problem is that I need to create hundreds of them, the same structure with different values in the columns and ID. The columns DPHExportovano and id_UzivatelDPHExportoval will be the same for all queries but the ones with equal sign will change in every query. Can I generate somehow many queries with these values? For example:
UPDATE p
SET DPHExportovano='2020-02-01'
, id_UzivatelDPHExportoval=2
, CiziProdej=
, NepodlehaDPH=
, ZakladDPH=
, DPH=
FROM Platba p
WHERE p.ID=

these values should be in the query
0     142
0     0.01
17.13 16.27
3.43  3.25
14554 14581


text:
Q: Using loop to create elements in react Based on  the next working code:
var myfields = new Array('id', 'firstName', 'lastName')

const usersd = users;

ReactDOM.render(
<BootstrapTable data={usersd} search={true} cellEdit={ cellEditProp } height='480px' scrollTop={ 'Bottom' } pagination={true}  multiColumnSearch={ true } >
    <TableHeaderColumn isKey dataField={myfields[0]} width='10' dataAlign='left'>{myfields[0]}</TableHeaderColumn>
    <TableHeaderColumn dataField={myfields[1]} dataSort={ true } width='15' dataAlign='left' headerAlign='left'>{myfields[1]}</TableHeaderColumn>
    <TableHeaderColumn dataField={myfields[2]} dataSort={ true }  width='15' dataAlign='left' headerAlign='left'>{myfields[2]}</TableHeaderColumn>
</BootstrapTable>,
document.getElementById('usersModTable')
);

I wanted to use a loop on those react commands that use an index. So I could use a loop like in:
var myfields = new Array('id', 'firstName', 'lastName')

const usersd = users;

ReactDOM.render(
<BootstrapTable data={usersd} search={true} cellEdit={ cellEditProp } height='480px' scrollTop={ 'Bottom' } pagination={true}  multiColumnSearch={ true } >
    <TableHeaderColumn isKey dataField={myfields[0]} width='10' dataAlign='left'>{myfields[0]}</TableHeaderColumn>

    for(var i = 1;i<myfields.length;i++) {
        <TableHeaderColumn dataField={myfields[i]} dataSort={ true } width='15' dataAlign='left' headerAlign='left'>{myfields[i]}</TableHeaderColumn>
    }

</BootstrapTable>, document.getElementById('usersModTable')
);

So far this loop doesn't work, but, is there a working way to do something like  this?

A: First thing is, you forgot to use {}, if you are using any js code inside html element you need to use {}.
You are using the loop in a wrong way, for loop will not return anything, it is used just to iterate the array. Use map for this, it will return the TableHeaderColumn for each element. Like this:
ReactDOM.render(
    <BootstrapTable data={usersd} search={true} cellEdit={ cellEditProp } height='480px' scrollTop={ 'Bottom' } pagination={true}  multiColumnSearch={ true } >
        <TableHeaderColumn isKey dataField={myfields[0]} width='10' dataAlign='left'>{myfields[0]}</TableHeaderColumn>

       {
          myfields.map((el, i) => <TableHeaderColumn
                                      key={i}
                                      dataField={el}
                                      dataSort={ true }
                                      width='15'
                                      dataAlign='left'
                                      headerAlign='left'>
                                      {el}
                                  </TableHeaderColumn>

       }

   </BootstrapTable>, document.getElementById('usersModTable'));

Check this example, how to use map inside jsx:

var App = () => {
   return (

          {
            [1,2,3,4].map(el =>
 {el}
)
          }

   )
}

ReactDOM.render(<App/>, document.getElementById('app'))

A: Code proposed by Mayank Shukla is a pretty way to get what you want (I would do it in the same way). But if what you are looking for is to use loops, the way should be more or less like this:
var myfields = new Array('id', 'firstName', 'lastName')

const usersd = users;

let components = [];
for(var i = 1;i<myfields.length;i++) {
    components.push(<TableHeaderColumn dataField={myfields[i]} dataSort={ true } width='15' dataAlign='left' headerAlign='left'>{myfields[i]}</TableHeaderColumn>);
}

ReactDOM.render(
<BootstrapTable data={usersd} search={true} cellEdit={ cellEditProp } height='480px' scrollTop={ 'Bottom' } pagination={true}  multiColumnSearch={ true } >
    <TableHeaderColumn isKey dataField={myfields[0]} width='10' dataAlign='left'>{myfields[0]}</TableHeaderColumn>
    //for(var i = 1;i<myfields.length;i++) {
    //  <TableHeaderColumn dataField={myfields[i]} dataSort={ true } width='15' dataAlign='left' headerAlign='left'>{myfields[i]}</TableHeaderColumn>;
    //}
    {components}
</BootstrapTable>, document.getElementById('usersModTable')
);

or
var myfields = new Array('id', 'firstName', 'lastName')

const usersd = users;

ReactDOM.render(
<BootstrapTable data={usersd} search={true} cellEdit={ cellEditProp } height='480px' scrollTop={ 'Bottom' } pagination={true}  multiColumnSearch={ true } >
    <TableHeaderColumn isKey dataField={myfields[0]} width='10' dataAlign='left'>{myfields[0]}</TableHeaderColumn>
    {
        let components = [];
        for(var i = 1;i<myfields.length;i++) {
            components.push(<TableHeaderColumn dataField={myfields[i]} dataSort={ true } width='15' dataAlign='left' headerAlign='left'>{myfields[i]}</TableHeaderColumn>);
        }
        return components;
    }
</BootstrapTable>, document.getElementById('usersModTable')
);

A: There are a couple things that you need to pay attention at while working in react - JSX to be specific. Let me walk you through your code.
ReactDOM.render(
// JSX starts here
<BootstrapTable data={usersd} search={true} cellEdit={ cellEditProp } height='480px' scrollTop={ 'Bottom' } pagination={true}  multiColumnSearch={ true } >
    <TableHeaderColumn isKey dataField={myfields[0]} width='10' dataAlign='left'>{myfields[0]}</TableHeaderColumn>
    for(var i = 1;i<myfields.length;i++) {
        <TableHeaderColumn dataField={myfields[i]} dataSort={ true } width='15' dataAlign='left' headerAlign='left'>{myfields[i]}</TableHeaderColumn>
    }
    {
      // You can write javascript code here. However you need to ensure that this will return a react/html component.
     someCondition ?
     positive :
     negative
    }
    {
     // Now might will notice that the for loop that you have used above, doesnt return a valid JSX. To overcome that you need to use the *map* to iterate and return the jsx.
     myfields.map(function() {
      return <TableHeaderColumn dataField={myfields[i]} dataSort={ true } width='15' dataAlign='left' headerAlign='left'>{myfields[i]}</TableHeaderColumn>
     })
    }
</BootstrapTable>
// JSX ends here
, document.getElementById('usersModTable')
);

A: All the ideas you gave me are very interesting and very helpful. Given the nature of BootstrapTable I had to do:
var myfields = new Array('id', 'firstName', 'lastName')

const usersd = users;

let components = [<TableHeaderColumn isKey dataField={myfields[0]} width='10' dataAlign='left'>{myfields[0]}</TableHeaderColumn>];

for(var i = 1; i<myfields.length; i++) {
    components.push(<TableHeaderColumn dataField={myfields[i]} dataSort={ true } width='15' dataAlign='left' headerAlign='left'>{myfields[i]}</TableHeaderColumn>);
}

ReactDOM.render(
<BootstrapTable data={usersd} search={true} cellEdit={ cellEditProp } height='480px' scrollTop={ 'Bottom' } pagination={true}  multiColumnSearch={ true } >

    {components}

</BootstrapTable>,
document.getElementById('usersModTable')
);

placing the first "isKey" component in the array and adding the others as Facundo La Roca mentioned. Thanks!!!


text:
Q: Can I unwrap an observable with the async pipe to a view variable other than with an ngIf? I know I can use *ngIf="obs$ | async as obs" but what if I need to use the value when obs is false?
<ng-container *ngIf="obs$ | async as obs">
  observable is {{ obs | json }}
</ng-container>

https://stackblitz.com/edit/angular-zkbemb?file=src%2Fapp%2Fapp.component.html
I want that line to read observable is false instead of the block disappearing. I know I could use an else block but what I need is to unwrap a readonly$ flag to a view variable readonly and don't want to repeat my whole template in an else block. I can't think of any way that doesn't involve subscribing in the component but this is not the only occasion had have found myself wanting a way in the template to go #boolFlag = boolObs$ | async

A: Thanks to this comment on a Reddit post
https://www.reddit.com/r/Angular2/comments/m2r39u/angular_ngif_learn_all_the_features_available_in/gqku9f9/
<ng-container *ngIf="{ obs: obs$ | async } as data">
  observable is {{ data.obs | json }}
</ng-container>

https://stackblitz.com/edit/angular-ghxtsn?file=src%2Fapp%2Fapp.component.html


text:
Q: How to define a function that using extern "C" modifier In a DLL, a function is exported, and it is defined as:
extern "C" ULONGLONG WINAPI MyFun(CONST LPVOID lpParam);

Now in My app, I need to get the address of the function and invoke it, so I use
typedef ULONGLONG (WINAPI *MyFun) (CONST LPVOID lpParam);

and use
lpMyFun = (MyFun)GetProcAddress(hDLL, "MyFun");

In such a way, there is no way to put the extern "C" modifier in the typedef codeline, I using
extern "C" typedef ULONGLONG (WINAPI *MyFun) (CONST LPVOID lpParam);

but that will cause compiler error.
How to solve the problem?
Thanks


text:
Q: Firefox Vs Chrome from web developers prespective I hope I am asking a question that fits Stack Overflow standards. I am curious to know from web developers point of view, what do you prefer Firefox or Google Chrome. Is Firefox or chrome your best choice of developing web apps and websites. Which one do you prefer and why.

A: I prefer Firefox, as I find it easier thanks mainly to the Web Developer add-on, and a few others.  Interestingly, a recently-leaked Google document for internal testers said they had to use Firefox.

A: Chrome, its built in dev tools are easily as powerful as Firebug, yet no need for an extension.
http://code.google.com/chrome/devtools/docs/overview.html
Chrome also loads up within a few seconds, while Firefox still takes an age to startup, that really bugs me!


text:
Q: Unable to add multiple categories to a post in Wordpress I have just created a page and it is live.
I currently have Freehand as the one category for the page.
However if I then select

*

*Freehand

*Pledge Video

*How To

and then click update, it will notify me that the page has successfully updated. The page will update its state and only Freehand will be selected.

I do have plugins:
Plugin  Description
Advanced Product Search For WooCommerce
Advanced Product Wishlist for Woocomerce
Akismet Anti-Spam
Customer Reviews for WooCommerce
Elementor
EnvoThemes Demo Import
Genesis Layout Extras
Hello Dolly
Image optimisation service by Optimole
Jetpack by WordPress.com
Mailchimp for WooCommerce
One Click Demo Import
Orbit Fox Companion
PayPal PLUS for WooCommerce
Polylang
PowerPack Lite for Elementor
s2Member Framework
Smart Variation Swatches for WooCommerce
Toolbar Extras
WooCommerce
WooCommerce Admin
Woocommerce Events Manager
WooCommerce PayPal Checkout Gateway
WooCommerce Popup Cart + ajax
WooCommerce Services
WooCommerce Subscriptions
WPForms Lite

A: Have you tried the classic debugging process?
(It is better to perform these operations on a local environment rather than on the production environment)

*

*Make a full backup of your website

*Try to disable the plugin one by one and see if the bug disappears.

*Try to change the theme

You can then identify if the bug comes from a plugin or your theme.


text:
Q: Aws cloud formation template: how to provide StreamName for Kinesis resource? I wanted to create a Kinesis resource through cloud formation template and it wouldn't let me provide a "StreamName" as property for the resource.
"KinesisResource":{
"Type" : "AWS::Kinesis::Stream",
"Properties" : {
"ShardCount" : 1
"StreamName":"KinesisStream"
}

},

It says "unrecognizable property "StreamName".
how do I give a Stream Name in my template.
Thanks,
Nithya.

A: Apparently you can't specify a Stream name as of now. The Kinesis Documentation for the CloudFormation supports only ShardCount as the only parameter.
You can perhaps get the Kinesis stream name as part of the CloudFormation Output - using
{ "Ref" : "< resource name of instance of  - AWS::Kinesis::Stream>" }
As of now the name of stream is created in the pattern of <Stack-Name> - <Stream Name - Resoruce Name> - < Arbitrary Info >
Stack Name : MyKinesisStack
{
  "AWSTemplateFormatVersion" : "2010-09-09",
  "Resources" : {
    "KinesisStream1" : {
      "Type" : "AWS::Kinesis::Stream",
      "Properties" : {
        "ShardCount" : "1"
      }
    }
  },
  "Outputs" : {
  "KinesisStreamName" : {
        "Description" : "Kenisis Stream Name",
        "Value" : { "Ref" : "KinesisStream1"}
    }
  }
}

The above stack would create a Kinesis Stream with the name - MyKinesisStack-KinesisStream1-ARTSDY32AS

A: This has been solved with Name in Property.
{
   "Type" : "AWS::Kinesis::Stream",
   "Properties" : {
      "Name" : String,
      "ShardCount" : Integer,
      "Tags" : [ Resource Tag, ... ]
   }
}

http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-kinesis-stream.html


text:
Q: How to pass db info to html template to query db in Flask My homepage queries the database to list all recipes. I wrapped it in an  tag and will build a template to show detailed info, but how do I get info about which one was clicked? I just need to grab the ID or recipe name so I could query the db and get relevant info to populate.
Python:
@views.route('/')
def home():
    rows = recipeMaster.query.all()
    return render_template("index.html", rows=rows)

HTML:
{% for row in rows %}

        {{ row.recipe_name }}

{% endfor %}


text:
Q: Change entity and update app I have a app in app store, but now I added new attribute to entity. How can I update user's entity without deleting app and lose data?
Thanks

A: 1) Click on your xcdatamodel file in Xcode
2) Choose the menu Editor in the upper bar
3) Click on Add version model
4) Create a new model based on the previous one
5) Perform your updates in the new created xcdatamodel file
The app will automatic handle your updates


text:
Q: Node.js exec to build Marp markdowns doesn't work I wrote this simple node.js script to build Marp markdown and convert them to PDF. But it doesn't do anything and doesn't terminate. I added a console.log("test") at the end I see that node.js doesn't wait for all the command executions to finish but exec also doesn't run the Marp build command.
If I run the "cmd" string from the terminal it all works. I think something is wrong with the way I use exec
var glob = require("glob");
var cp = require("child_process");

glob("lab*/*.marp.md", {}, function (err, files) {
  files.forEach((file) => {
    var destination = file.replace(".md", "");
    var cmd = `marp ${file} --allow-local-files --pdf -o ${destination}.pdf`;
    var dir = cp.exec(cmd, (err, stdout, stderr) => {
      if (err) {
        console.log("node couldn't execute the command");
        return;
      }

      // the *entire* stdout and stderr (buffered)
      console.log(`stdout: ${stdout}`);
      console.log(`stderr: ${stderr}`);
    });

    dir.on("exit", function (code) {
      // exit code is code
      console.log(`finished building: ${file}`);
    });
  });
});

A: you can try the execSync() function It'll solve the issue
var glob = require("glob");
var cp = require("child_process");

glob("lab*/*.marp.md", {}, function (err, files) {
  files.forEach((file) => {
    var destination = file.replace(".md", "");
    var cmd = `marp ${file} --allow-local-files --pdf -o ${destination}.pdf`;

    var dir = cp.execSync(cmd, (err, stdout, stderr) => {
      if (err) {
        console.log("node couldn't execute the command");
        return;
      }

      // the *entire* stdout and stderr (buffered)
      console.log(`stdout: ${stdout}`);
      console.log(`stderr: ${stderr}`);
    });

    dir.on("exit", function (code) {
      // exit code is code
      console.log(`finished building: ${file}`);
    });
  });
});


text:
Q: Why VisualStudio2017 gives me an ambiguous variable error and others compilers don't? I am following the cpluplus.com (c++) tutorial using 2 compilers, VisualStudio2017 and MinGW distro.
MinGW distro compiles the following code without errors, but VisualStudio2017 gives me an ambiguous error on the definition/initialization of the variable "size"(line 11).
Why does this happen?
// reading a complete binary file
#include <iostream>
#include <fstream>
using namespace std;

ifstream::pos_type size;
char * memblock;
int main () {
ifstream file ("example.bin", ios::in|ios::binary|ios::ate);
if (file.is_open()){
    size = file.tellg();
    memblock = new char [size];
    file.seekg (0, ios::beg);
    file.read (memblock, size);
    file.close();
    cout << "the complete file content is in memory";
    delete[] memblock;
}else cout << "Unable to open file";
return 0;
}


text:
Q: Issue properly formatting ruby to pass rspec I'm currently working through a set of TestFirst problems. The spec for the problem I'm working on can be found here: http://testfirst.org/live/learn_ruby/book_titles
I've tested the title method outside of the class so I know that it works, but once I place it in the class I get the following error:
 1) Book title should capitalize the first letter
    Failure/Error: @book.title.should == "Inferno"
    ArgumentError:
      wrong number of arguments (0 for 1)

Here's what I have so far:
class Book
  attr_accessor :title

  def initialize(title=nil)
    @title = title
  end

  def title(title)
    first_check = 0
    articles = %w{a the an in and of}
    words = title.split(" ")

    words.each do |word|

      if first_check == 0
        word.capitalize!
        first_check += 1
      elsif !articles.include?(word)
        word.capitalize!
      end

    end
    @title = words.join(" ")
  end

end

If someone could explain how the class should be formatted, it'd be greatly appreciated!

A: Your problem is right here:
def title(title)

Your Book#title method expects an argument but you're not giving it one in your spec:
@book.title.should == "Inferno"
# ----^^^^^ this method call needs an argument

I think you actually want a Book#title= method:
def title=(title)
  # The same method body as you already have
end

Then you'll use the title accessor method that attr_accessor :title supplies and assigning a new title will use your title= method. And since you're supplying your own mutator method, you could use attr_reader instead:
class Book
  attr_reader :title

  def initialize(title=nil)
    @title = title
  end

  def title=(title)
    #...
  end
end


text:
Q: Xamarin Hiding and showing Flyout Item based on value I am currently learning xamarin forms bits by bits when I had this problem. I wanna make an app where a certain flyout item will be hidden if the user is not an admin. However, even after a successful login of an admin, the flyout item stays hidden. Here's the simplified version of the app.
Here's my code for AppShell.xaml:
<Shell.BindingContext>
     <viewmodel:AppShellViewModel></viewmodel:AppShellViewModel>
 </Shell.BindingContext>
 <ShellItem Route="LoginPage" FlyoutItemIsVisible="False">
     <ShellContent ContentTemplate="{DataTemplate view:LoginPage}"/>
 </ShellItem>
 <FlyoutItem Title="Page 1">
     <ShellContent Route="Page" ContentTemplate="{DataTemplate view:Page}"/>
 </FlyoutItem>
 <FlyoutItem Title="Page 2" IsVisible="{Binding isAdmin}">
     <ShellContent Route="Page2" ContentTemplate="{DataTemplate view:Page2}"/>
 </FlyoutItem>
 <MenuItem Text="isAdmin?" Command="{Binding checkCommand}"/>

AppShellViewModel.cs:
public class AppShellViewModel: BindableObject
 {
     public AppShellViewModel()
     {
         MessagingCenter.Subscribe<LoginViewModel>(this, message: "user", (sender) => {
             _isAdmin = false;
         });
         MessagingCenter.Subscribe<LoginViewModel>(this, message: "admin", (sender) => {
             _isAdmin = true;
         });
         checkCommand = new Command(async () => await checkAdmin());
     }
     private bool _isAdmin;
     public bool isAdmin
     {
         get { return _isAdmin; }
         set
         {
             _isAdmin = value;
             OnPropertyChanged();
         }
     }
     public ICommand checkCommand { get; }
     private async Task checkAdmin()
     {
         string str = $"isAdmin: {_isAdmin}";
         await App.Current.MainPage.DisplayAlert("Alert", str, "OK");
     }
 }

As I've said, the isAdmin will be modified through login method. if the user enter 'admin', isAdmin will be set to true and if it's 'user', false.
Here's my LoginPage.xaml:
<ContentPage.BindingContext>
     <viewmodel:LoginViewModel></viewmodel:LoginViewModel>
 </ContentPage.BindingContext>
 <ContentPage.Content>
     <StackLayout>
         <Entry Text="{Binding user}"/>
         <Button Text="Login" Command="{Binding loginCommand}"/>
     </StackLayout>
 </ContentPage.Content>

Here's my LoginViewModel.cs :
public class LoginViewModel: BindableObject
 {
     public LoginViewModel()
     {
         loginCommand = new Command(async () => await LoginFunc());
     }
     public ICommand loginCommand { get; }
     string _user;
     public string user
     {
         get => _user;
         set
         {
             _user = value;
             OnPropertyChanged();
         }
     }

     private async Task LoginFunc()
     {
         if(_user != null)
         {
             MessagingCenter.Send<LoginViewModel>(this, _user);
             await Shell.Current.GoToAsync($"//{nameof(Page)}");
         }
     }
 }

As per code above, I manage (correct me if my method is wrong) to modify the isAdmin by using MessagingCenter, which can be shown if I click the "isAdmin?" MenuItem.
I don't know if the isVisible is working even after the isAdmin property is change (when i tried to initialize isAdmin = true, the flyout item keeps showing even if the user is not an admin).
I would be grateful for any help/tips I will receive.
Thank you in advance

A: The reason it's not working is that you are not updating the Property but the Field which leads to OnPropertyChanged being never called and hence your UI is never updated.
 public AppShellViewModel()
 {
     MessagingCenter.Subscribe<LoginViewModel>(this, message: "user", (sender) => {
         isAdmin = false;
     });
     MessagingCenter.Subscribe<LoginViewModel>(this, message: "admin", (sender) => {
         isAdmin = true;
     });
     checkCommand = new Command(async () => await checkAdmin());
 }

Good luck!

A: Just wanna share that I've just solve this problem. This is how:

*

*I removed the AppShellViewModel.cs completely and put its content in the AppShell.xaml.cs (the code behind)

*Instead of using MessagingCenter, I just used the following (code is included in the login function)
if(_user == "admin")
{
(Shell.Current as AppShell).isAdmin = true;
}
else
{
(Shell.Current as AppShell).isAdmin = false;
}

However, I'm still looking for other solutions so that I can separate the AppShell view and its viewmodel.
So if you have others solutions, kindly post it here ^_^. Thank you


text:
Q: Is it dangerous to have several parallel jobs create the same directory at the same time? Is it dangerous to have several parallel jobs create the same directory using mkdir -p? (This is under Linux.)
In my case, I send many jobs to a SUN grid to process them in parallel, and some of these jobs start by creating a certain directory foo. So, the execution of the different mkdir commands might happen at exactly the same time ...

A: A simple mkdir is atomic (if you are using NTFS, there are chances it is not atomic, need some check).
By deduction, the mkdir -p folder1/folder2/ starts by creating folder1 which is atomic.
I f at the same time another process tries to create folder1 also, it will see that folder1 is created so it will try to create folder2 which will either fail (if the first process already created folder2) or succeed and the first process will fail.
This should not be a problem if this is properly handled (i.e. good error handling).

A: There should be no danger to any POSIX compatible filesystem from multiple concurrent (racing) mkdir -p commands.  I have, in fact, tested my own shell script locking function (wrapped around mkdir ... || ... (but NOT with -p) by using hundreds of racing process in my efforts to detect any failures from the race on Linux and Solaris with a few different local operating systems.  I never saw any failures and my searching and reading suggested that it should be safe.
(Nitpick: in your case it sounds like atomicity is not required.  Atomicity is critical for mutex/locking but not necessary for mere safety --- mkdir() can fail safely when the directory is already there.  Multiple racing mkdir shell commands should each have some their calls fail harmlessly as they traverse the components of the target path attempting to create each.  Atomicity is irrelevant to that).

A: Local fs should be posix and all operations (including creation of directories) should be atomic.
I guess it comes down to what mkdir -p does when it starts creating a path and then suddenly encounters an (further) element of that path that's already created.
If it's sane it will continue independant of what it did before and your operations should be safe. For the details of your particular mkdir tool you should see the sourcecode.
On networked/clustered filesystems it may very well depend on network latency, server load or mount options.
Also, it would not be hard to write a script that tries it a lot of times with a high concurrency, failures should be easy to detect.

A: No, this is not dangerous.
One job will succeed in creating the directory, and the others will fail.


text:
Q: wp_insert_post not working for custom post type? For whatever reason wp_insert_post doesn't work for a custom post type.
Here's the code snippet I'm using.
$new_post = array(
    'post_type' => 'rsp_synonym',
    'post_title' => wp_strip_all_tags( $row['word'] ),
    'post_date' => date('Y-m-d H:i:s'),
    'post_author' => 2,
    'post_content' => '',
    'post_status' => 'publish',
    'comment_status' => 'open',
    'ping_status' => 'open'
);

$post_id = wp_insert_post( $new_post );

if (is_wp_error($post_id)) {
    $errors = $post_id->get_error_messages();
    foreach ($errors as $error) {
        echo "- " . $error . "<br />";
    }
}

Strange enough, it doesn't even return a WP_Error using the if (is_wp_error($post_id)) conditional. But still, no posts are being added.
The custom post type named as rsp_synonym has been registered before using this call.

A: Try add the second parameter like:
$post_id = wp_insert_post( $new_post, true );

If it still won't work, please var_dump the $post_id and paste here.

A: Instead of wp_insert_posts, create your own "call" using $wpdb which you can then set your own database e.g.
$table_name = $wpdb->prefix . 'tablename';
$wpdb->insert(
 $table_name,
 array(
    // data to add
 )
);

You can read more on custom tables at http://codex.wordpress.org/Creating_Tables_with_Plugins


text:
Q: Mixin in Stylus There are two elements with two common properties but their values are various below,
EL_a
  p1 v1_a
  p2 v2_a

EL_b
  p1 v1_b
  p2 v2_b

Can we make a proper mixin in stylus to pass the respective values below?
EL_a
  mixin v1_a v2_a

EL_b
  mixin v1_b v2_b

A: Not sure what you want, maybe this can help you:
<div class="DivD">
   MIX
</div>

mixing0(wid = 20px, col = #e33)
    width: wid
    color: col
.DivD
    mixing0 200px green

http://stylus-lang.com/docs/mixins.html


text:
Q: LWJGL Collision detection 3D? I'm new to lwjgl and openGL and i'm wanting to know how to do collision detection in 3D, I have a 3D sorta world setup but i don't know how to detect collisions.

A: LWJGL is just doing the graphics part. If you need a good collision detection or physics library for Java then JBullet is an option. JBullet is a Java port of the Bullet library used by many games.


text:
Q: Can I use a resistor for overcurrent protection? I have a circuit that draws ~350 mA and uses 6v. Can I put a 5watt 15 ohm resistor in series to prevent overcurrent, (I don't want the current to go over 400 mA in case of a short circuit). Here's my math:
I = 6v / 15
I = 0.4 A

A: No, this won't work since it will disrupt normal operation of the circuit. If the circuit draws the expected 350mA current, the voltage dropped across the resistor will be 5.25 V, so the circuit will only be running on 0.75 V, not 6 V.


text:
Q: Turn a GIT repo subfolder into a branch Is it possible to turn subfolders of a GIT repository into its branches?
Going from one branch with folders
-main
  /Folder_A
  /Folder_B
  readme.md

To many branches
-main
  readme.md
-A
  Content of Folder_A
-B
  Content of Folder_B

The reason for this is an import from a TFVC repository to a GIT repository.

A: Will the branches remain separate from now on? If they will remain separate, fell free to create two new branches from main, say A and B. Then, in main, delete the 2 folders, and in each of the separate branches do the necessary adjustments... say, in A
git checkout A
git rm readme.md
git rm Folder_B
git commit -m "Removing unnecessary stuff from this project"

This should be good enough. This way you get to keep the history of the common development up to this point in all 3 branches. If you don't want that and you would rather have them separate from the  beginning as separate projects, then you should consider using git filter-repo https://github.com/newren/git-filter-repo

A:
Is it possible to turn subfolders of a GIT repository into its branches?

Of course, there is a simple command which will do it, it will convert the folder to a branch with all the history
git subtree split ...

Split the "main" into branches with git subtree split <path> -b <branch> and then add you can push the branch to the remote.
# split the "main repo"
git subtree split -P path -b <branch1>


text:
Q: Extract files with lftp and iterate over the extracted files I am using lftp to extract some CSV data files from a FTP-server, with the following command:
lftp -e 'set ftp:use-mdtm false; set ftp:timezone Europe/Berlin; mirror --newer-than=now-1days --no-recursion --verbose -i "INERGIA.*\.csv" / /mnt/trailstone/itpf/DataInput; bye' -u [USERNAME],[PASSWORD] [SERVER-NAME]

This runs perfectly. However, after extracting the CSV files, I want to iterate over each of them in order to modify some of the data in the files with a Python script. Is there a way via lftp to get a hold of the extracted files directly by for instance assigning them to a variable?
At this moment I just do the following:
cd "/mnt/trailstone/itpf/DataInput/"

for f in $(find *.csv -ctime -1) do
   python /mnt/trailstone/itpf/OnlineDataProcessing/OnlineExtraDataDownloader/changeDelimiter.py $f
done

But I would prefer getting a hold of the files directly through lftp.

A: Not really-- but you can turn on lftp's download log which will track all the files downloaded.  Then parse that log for the file names and use it in your python script.

xfer:log (boolean)  when true, lftp logs transfers to a file from xfer:log-file setting.
xfer:log-file (path to file) the   file  to  log  transfers  to.
  Default  is  ~/.local/share/lftp/transfer_log or             ~/.lftp/transfer_log.

A: I'm supposing you want to do this because find might be hitting files with last status changed accidentally amongst previously fetched cvs files.
I'm not too familiar with lftp but I can think of a workaround:
have lftp download the files to a temporary location, do the python stuff and subsequently move the modified files to their final destination.
Alternatively extract the downloaded file list lftp's standard output (piped trough awk and grep, or whatever suits you best), populate a variable with that and then loop with that instead of $(find *.csv -ctime -1).


text:
Q: The submission form was duplicated in the ajax response page using Django views.py I am trying to use a form to submit the parameter to views.py and get the results back to the html.  However, the form part was repeatedly display in the page.
enter image description here
Here is my views.py

def fund_main_py(request):
    last_trade_date = request.GET['last_trade_date']
    print(last_trade_date)
    plot_div1, plot_div2 = fund_main_main(last_trade_date)
    return render(request, 'optionsfund.html', context={'plot_div1': plot_div1, 'plot_div2': plot_div2})

Here is my stocksettle.js

$(document).ready(function(){
    $("#btn_submit").click(function(){
        document.getElementById("result").innerHTML = '抓取中.... 若期限過長,請稍後1分鐘!';
        var stock_code = $("#stock_code").val();
        var last_trade_date = $("#last_trade_date").val();
        $.ajax({
            type: "GET",
            url: "/fund_main_py",
            data:{
                "stock_code":stock_code,
                "last_trade_date":last_trade_date
            },
            success: function (Data) {
                $("#result").html(Data);
            },
            error: function (e) {
                console.log(e);
            }
        });
    })
});

Here is my optionsfund.html

                <fieldset>
                     指數/股票代號 :
                 <input type="button" id="btn_submit" value=" 查詢 ">
                </fieldset>

                {% autoescape off %}
                    {{ plot_div1 }}
                {% endautoescape %}

                {% autoescape off %}
                    {{ plot_div2 }}
                {% endautoescape %}


text:
Q: Update many rows in a table with a single statement? What is the easiest way to update many rows in a table? I have a csv file that looks like this:
|primary_key |value|
|          1 |  xyz|
|          2 |  abc|
|          3 |  def|
...

Rows with these primary keys already exist in the target table
I would like to update the target table with these values. Is there syntax so that I can write something like:
update mytable set value = ('xyz', 'abc', 'def') where primary key = (1,2,3);

Looking through the MySQL Update Reference, this site (MySQL - csv update), SO (update multiple rows, multiple db updates, update multiple rows), I suspect that the answer is "no", but I'd like to confirm that this is true.

A: Assuming that you don't want to load the data from the CSV file into a database table and then do a correlated UPDATE,
UPDATE mytable t
   SET value = (SELECT value
                  FROM tbl_with_csv_data csv
                 WHERE csv.primary_key = t.primary_key)
 WHERE EXISTS( SELECT 1
                 FROM tbl_with_csv_data csv
                 WHERE csv.primary_key = t.primary_key)

then you should be able to use a CASE
UPDATE mytable t
   SET value = CASE WHEN primary_key = 1 THEN 'xyz'
                    WHEN primary_key = 2 THEN 'abc'
                    WHEN primary_key = 3 THEN 'def'
                    ELSE value
                END
 WHERE primary_key IN (1,2,3);

A: First here is sample data
mysql> drop table if exists mytable;
Query OK, 0 rows affected (0.03 sec)

mysql> create table mytable
    -> (
    ->     id int not null,
    ->     value VARCHAR(255),
    ->     primary key (id)
    -> );
Query OK, 0 rows affected (0.06 sec)

mysql> insert into mytable (id) values (1),(2),(3);
Query OK, 3 rows affected (0.06 sec)
Records: 3  Duplicates: 0  Warnings: 0

mysql> select * from mytable;
+----+-------+
| id | value |
+----+-------+
|  1 | NULL  |
|  2 | NULL  |
|  3 | NULL  |
+----+-------+
3 rows in set (0.00 sec)

mysql>

Here is the new query
update mytable A inner join
(
    SELECT 1 id,'xyz' value UNION
    SELECT 2   ,'abc'       UNION
    SELECT 3   ,'def'

) B USING (id)
SET A.value = B.value;

Here is the new query executed
mysql> update mytable A inner join
    -> (
    ->     SELECT 1 id,'xyz' value UNION
    ->     SELECT 2   ,'abc'       UNION
    ->     SELECT 3   ,'def'
    -> ) B USING (id)
    -> SET A.value = B.value;
Query OK, 0 rows affected (0.06 sec)
Rows matched: 3  Changed: 0  Warnings: 0

mysql> select * from mytable;
+----+-------+
| id | value |
+----+-------+
|  1 | xyz   |
|  2 | abc   |
|  3 | def   |
+----+-------+
3 rows in set (0.00 sec)

mysql>


text:
Q: Where to add new .h and .cpp file in STM32CubeIDE project I used STM32CubeIDE to create a new (C++) project for my nucleo-f411re board by File > New > STM32 Project. The project was created as usual. I renamed "main.c" to "main.cpp" since I selected C++ as the target language. A simple "blinky" compiles and runs correctly on the board. So now I want to begin adding some C++ code to the project.
The "main.cpp" is in the project tree under myproject > Core > Src > main.cpp. If I want to  create some new source/header files, say "foo.h" and "foo.cpp", I think I can right-click on something in the project tree, then New > Header File or New > Source File. But the question is -- what do I right-click on to create the source/header file? I assume the file will be created in the location (= folder) I right-click on. Where do I want to put them? Both of them in the "Core" folder? Separately in "Core > Inc" and "Core > Src" folders? I'm not sure.
Edit: I added the header/source files to Core > Inc and Core > Src respectively, and that seems to work. Is that recommended? I wonder if they will still be there if I change the configuration, causing the code to be regenerated.

A: I know this is a very late answer but I didn't find a lot of tips regarding this question a while ago so here is my take on it.
Basically you can place source file in any source folder.
You can use existing folders or create a new one, however you like.
Header files have to be placed inside a folder that is in the include path (e.g. Core/Inc) or you have to tell the compiler that a specific file should be included.
If you want to create a new folder for your header files you have to add the folder or files inside this folder to the include path via Project -> Properties -> C/C++ Build -> Tool Setting (tab) -> MCU GCC Compiler or MCU G++ Compiler -> Include paths.
Note that you might have to add it twice, once for C files (MCU GCC Compiler) and once for C++ files (MCU G++ Compiler).
To create a file you can simply click on the folder you want to create it in and add a new <whatever>file.
You can also just create files and directories on your local filesystem and refresh the project (right click -> Refresh or F5) to show changes in STM32CubeIDE.

For small projects (like a blinky project) it is probably enough to just use the Core folder.
For bigger projects I personally like to seperate all the autogenerated code from my own files.
Especially for C++ projects it can become very annoying that STM32CubeIDE always renames main.cpp to main.c and deletes code segments you accidentally put outside their comment blocks every time you run the code generation.
I usually create a Project source folder for project specific files and a Lib source folder for libraries.
Then I create a cppmain.h file that simply declares a void cppMain() function and a cppmain.cpp file that I use to write my main program.
The only change to the autogenerated code is that you have to include cppmain.h and call cppMain() before the main loop in main.c.
Directory tree:
Project name
+ Core
| + ...
+ Drivers
| + ...
+ Libs
| + someLib
| | + Inc
| | | + someLib.h or hpp
| | + Src
| |   + someLib.c or cpp
| + ...
+ Program
| + Inc
| | + cppmain.h
| | + ...
| + Src
|   + cppmain.cpp
|   + ...
+ ...

You will have to add Program/Inc and any Lib/Inc folder to the include path.
The changes to main.c then look like this:
...

/* Includes ------------------------------------------------------------------*/
#include "main.h"

/* Private includes ----------------------------------------------------------*/
/* USER CODE BEGIN Includes */
#include "cppmain.h"  // this goes in user includes
/* USER CODE END Includes */

...

  /* USER CODE BEGIN 2 */
  cppMain();  // this goes before the main loop
  // anything after this point will never be reaced
  // when you create a main loop inside cppMain()
  /* USER CODE END 2 */

  /* Infinite loop */
  /* USER CODE BEGIN WHILE */
  while (1)
  {
    /* USER CODE END WHILE */

    /* USER CODE BEGIN 3 */
  }

...

Inside the cppmain.h file I usually #include "main.h" to get all the STM32 HAL stuff and declare all hardware resource handles as extern (e.g. extern UART_HandleTypeDef huart1;)
The full cppmain.h file:
/** @file cppmain.h
 *
 * @author some_author
 * @date some_date
 */

#ifndef PROGRAM_INC_CPPMAIN_H_
#define PROGRAM_INC_CPPMAIN_H_

#ifdef __cplusplus
 extern "C" {
#endif

#include "main.h"

void cppMain(void);

#ifdef __cplusplus
}
#endif

#endif /* PROGRAM_INC_CPPMAIN_H_ */

Some random cppmain.cpp file:
/** @file cppmain.cpp
 *
 * @author some_author
 * @date some_date
 */

#include "cppmain.h"
#include "pins.h"
// pins is useful when you connect some things to a dev board
// and want to have a quick reference where you put stuff
// this just includes things like (for STM32F103xB "blue pill" in this case)
// #define LED_PIN_PORT GPIOC
// #define LED_PIN_PIN GPIO_PIN_13
// #define LED_PIN LED_PIN_PORT, LED_PIN_PIN

extern UART_HandleTypeDef huart1;

int some_variable = 0;

void foo(int input){
  // do something
}

void cppMain(){
  // do stuff

  // main loop
  while(1){
    // do stuff regularly
  }
}

In my Lib folder I usually link to libraries I want to change for all projects while working on them: right click on Libs -> New -> Folder -> Advanced >> -> Link to alternate location.
Note that this will link to an absolute path on your system and you can't simply import your project on a different system this way.
If you work in a team or across different devices you might want to solve this a different way.

A: I am using STM32CubeIDE version 1.8, it can let you add include folder directly from the project menu -> Add/remove include path:

To add source folder, you can create source folder from the project menu -> New -> Source Folder:

If you want to add include and source folders manually:
Project Properties-> C/C++ General->Paths and Symbols:
Select Includes tab to add header folder
Select Source Location to add source folder


text:
Q: Why does the recommended dispose pattern adds a disposed field at each level of the hierarchy? The Dispose pattern is notoriously complicated to get right, especially when we have a hierarchy of classes that needs to dispose things at different levels. The recommended implementation is as follow, took from Implement a Dispose method - Microsoft Docs.
using System;

class BaseClass : IDisposable
{
    // To detect redundant calls
    private bool _disposed = false;

    ~BaseClass() => Dispose(false);

    // Public implementation of Dispose pattern callable by consumers.
    public void Dispose()
    {
        Dispose(true);
        GC.SuppressFinalize(this);
    }

    // Protected implementation of Dispose pattern.
    protected virtual void Dispose(bool disposing)
    {
        if (_disposed)
        {
            return;
        }

        if (disposing)
        {
            // TODO: dispose managed state (managed objects).
        }

        // TODO: free unmanaged resources (unmanaged objects) and override a finalizer below.
        // TODO: set large fields to null.

        _disposed = true;
    }
}

using Microsoft.Win32.SafeHandles;
using System;
using System.Runtime.InteropServices;

class DerivedClass : BaseClass
{
    // To detect redundant calls
    private bool _disposed = false;

    // Instantiate a SafeHandle instance.
    private SafeHandle _safeHandle = new SafeFileHandle(IntPtr.Zero, true);

    // Protected implementation of Dispose pattern.
    protected override void Dispose(bool disposing)
    {
        if (_disposed)
        {
            return;
        }

        if (disposing)
        {
           // Dispose managed state (managed objects).
            _safeHandle?.Dispose();
        }

        _disposed = true;

        // Call base class implementation.
        base.Dispose(disposing);
    }
}

What I don't get in this implementation is what advantage we have in adding a _disposed field at each level of the hierarchy? Instead, we could take care of the _disposed only in the top level of the hierarchy (the one implementing directly IDisposable and not care about it in the derived classes.
Something like this:
using System;

class BaseClass : IDisposable
{
    // To detect redundant calls
    private bool _disposed = false;

    ~BaseClass()
    {
       if (_disposed)
       {
          return;
       }

       Dispose(false);
       _disposed = true;
    }

    // Public implementation of Dispose pattern callable by consumers.
    public void Dispose()
    {
        if (_disposed)
        {
            return;
        }

        Dispose(true);
        GC.SuppressFinalize(this);
        _disposed = true;
    }

    // Protected implementation of Dispose pattern.
    protected virtual void Dispose(bool disposing)
    {
        if (disposing)
        {
            // TODO: dispose managed state (managed objects).
        }

        // TODO: free unmanaged resources (unmanaged objects) and override a finalizer below.
        // TODO: set large fields to null.
    }
}

using Microsoft.Win32.SafeHandles;
using System;
using System.Runtime.InteropServices;

class DerivedClass : BaseClass
{
    // Instantiate a SafeHandle instance.
    private SafeHandle _safeHandle = new SafeFileHandle(IntPtr.Zero, true);

    // Protected implementation of Dispose pattern.
    protected override void Dispose(bool disposing)
    {
        if (disposing)
        {
           // Dispose managed state (managed objects).
            _safeHandle?.Dispose();
        }

        // Call base class implementation.
        base.Dispose(disposing);
    }
}

This is such a widely used code sample that there must certainly be a good reason for it to be implemented with the repeated _disposed at each level, but I just can't find any.
It's a tiny bit more code in the base class, but less to worry about in the derived class, and some repeated information removed.
What else am I missing?
Edit:
As @InBetween correctly says that one drawback of my implementation is that if you'd need to check if your object is disposed in one method of the derived class you won't be able to check it. Let's correct that issue by making it a protected property with a private set.
using System;

class BaseClass : IDisposable
{
    // To detect redundant calls
    protected bool Disposed { get; private set; } = false;

    ~BaseClass()
    {
       if (Disposed)
       {
          return;
       }

       Dispose(false);
       Disposed = true;
    }

    // Public implementation of Dispose pattern callable by consumers.
    public void Dispose()
    {
        if (Disposed)
        {
            return;
        }

        Dispose(true);
        GC.SuppressFinalize(this);
        Disposed = true;
    }

    // Protected implementation of Dispose pattern.
    protected virtual void Dispose(bool disposing)
    {
        if (disposing)
        {
            // TODO: dispose managed state (managed objects).
        }

        // TODO: free unmanaged resources (unmanaged objects) and override a finalizer below.
        // TODO: set large fields to null.
    }
}

using Microsoft.Win32.SafeHandles;
using System;
using System.Runtime.InteropServices;

class DerivedClass : BaseClass
{
    // Instantiate a SafeHandle instance.
    private SafeHandle _safeHandle = new SafeFileHandle(IntPtr.Zero, true);

    public void DoSomething()
    {
       if(Disposed)
       {
           throw new ObjectDisposedException("Cannot access disposed resource");
       }
    }

    // Protected implementation of Dispose pattern.
    protected override void Dispose(bool disposing)
    {
        if (disposing)
        {
           // Dispose managed state (managed objects).
            _safeHandle?.Dispose();
        }

        // Call base class implementation.
        base.Dispose(disposing);
    }
}

A: If you are inheriting from a disposable class, one of two conditions must be true.

*

*Your subcless does not introduce a new disposable resource. In this case you don't need to override Dispose and the question is moot.

*Your subclass introduces a new disposable resource. In this case, you're going to override Dispose, insert your own disposal code, then call base.Dispose. The _disposed flag is there to help you remember to prevent your disposal code from executing twice.
You certainly can remove _disposed if you want. But you probably do not care much about the base class' _disposed flag, if it even has one. It worries about what it is disposing, and you worry about yours.

A: The reason is simple. In your implementation you cant use _disposed in the derived type to check if any method is invoked when the object is already disposed and take the necessary actions. In your implementation you'd need to create your own redundant flag isDisposed which defeats the purpose; you already have one "for free" from the pattern itself following the guidelines.
A case could be made though about making _disposed protected.


text:
Q: Why following code doesn't produce any output? Why the code below doesn't produce any output? I expected it to be 42 s. How to fix it?
#include <cstdio>
#include <cstdlib>
#include <cstdarg>

void foo(const char* format, ...)
{
    va_list args;
    va_start(args, format);
    printf(format, args);
    va_end(args);
}

int main()
{
    foo("%d %s\n", 42, "s");
    return 0;
}

http://ideone.com/EsHsRO
Actually, it produces http://codepad.org/k7ld231E.
Why the foo is wrong?

A: You need to use vprintf instead: int vprintf( const char* format, va_list vlist );
vprintf(format, args);

printf() and friends are for normal use. vprintf() and friends are for when you want to write your own printf()-like functions.


text:
Q: How to plot ROC_AUC curve for each folds in KFold Cross Validation using Keras Neural Network Classifier I really need to find ROC plot for each folds in a 5 fold cross-validation using Keras ANN. I have tried the code from the following link [https://scikit-learn.org/stable/auto_examples/model_selection/plot_roc_crossval.html#sphx-glr-auto-examples-model-selection-plot-roc-crossval-py][1] It works perfectly fine when I'm using the svm classifier as shown here. But when I want to use wrapper to use Keras ANN model it shows errors. I am stuck with this for months now. Can anyone please help me with it? Here's my code:
# Load libraries
import numpy as np
from keras import models
from keras import layers
from keras.wrappers.scikit_learn import KerasClassifier
from sklearn.model_selection import cross_val_score
from sklearn.datasets import load_breast_cancer
from sklearn.model_selection import StratifiedKFold

X, y = load_breast_cancer(return_X_y=True)
# Create function returning a compiled network
def create_network():

    # Start neural network
    network = models.Sequential()

    # Add fully connected layer with a ReLU activation function
    network.add(layers.Dense(units=16, activation='relu', input_shape=(30,)))

    # Add fully connected layer with a ReLU activation function
    network.add(layers.Dense(units=16, activation='relu'))

    # Add fully connected layer with a sigmoid activation function
    network.add(layers.Dense(units=1, activation='sigmoid'))

    # Compile neural network
    network.compile(loss='binary_crossentropy', # Cross-entropy
                    optimizer='rmsprop', # Root Mean Square Propagation
                    metrics=['accuracy']) # Accuracy performance metric

    # Return compiled network
    return network

cv = StratifiedKFold(n_splits=5)
# Wrap Keras model so it can be used by scikit-learn
classifier = KerasClassifier(build_fn=create_network,
                                 epochs=10,
                                 batch_size=100,
                                 verbose=2)
#Plotting the ROC curve
tprs = []
aucs = []
mean_fpr = np.linspace(0, 1, 100)

fig, ax = plt.subplots()
for i, (train, test) in enumerate(cv.split(X, y)):
    classifier.fit(X[train], y[train])
    viz = plot_roc_curve(classifier, X[test], y[test],
                         name='ROC fold {}'.format(i),
                         alpha=0.3, lw=1, ax=ax)
    interp_tpr = np.interp(mean_fpr, viz.fpr, viz.tpr)
    interp_tpr[0] = 0.0
    tprs.append(interp_tpr)
    aucs.append(viz.roc_auc)

ax.plot([0, 1], [0, 1], linestyle='--', lw=2, color='r',
        label='Chance', alpha=.8)

mean_tpr = np.mean(tprs, axis=0)
mean_tpr[-1] = 1.0
mean_auc = auc(mean_fpr, mean_tpr)
std_auc = np.std(aucs)
ax.plot(mean_fpr, mean_tpr, color='b',
        label=r'Mean ROC (AUC = %0.2f $\pm$ %0.2f)' % (mean_auc, std_auc),
        lw=2, alpha=.8)

std_tpr = np.std(tprs, axis=0)
tprs_upper = np.minimum(mean_tpr + std_tpr, 1)
tprs_lower = np.maximum(mean_tpr - std_tpr, 0)
ax.fill_between(mean_fpr, tprs_lower, tprs_upper, color='grey', alpha=.2,
                label=r'$\pm$ 1 std. dev.')

ax.set(xlim=[-0.05, 1.05], ylim=[-0.05, 1.05],
       title="Receiver operating characteristic example")
ax.legend(loc="lower right")
plt.show()

It shows the following error:
Epoch 1/10
5/5 - 0s - loss: 24.0817 - accuracy: 0.3714
Epoch 2/10
5/5 - 0s - loss: 2.7967 - accuracy: 0.5648
Epoch 3/10
5/5 - 0s - loss: 2.0594 - accuracy: 0.5363
Epoch 4/10
5/5 - 0s - loss: 2.4763 - accuracy: 0.5604
Epoch 5/10
5/5 - 0s - loss: 2.5489 - accuracy: 0.5121
Epoch 6/10
5/5 - 0s - loss: 2.0528 - accuracy: 0.6132
Epoch 7/10
5/5 - 0s - loss: 1.5593 - accuracy: 0.6088
Epoch 8/10
5/5 - 0s - loss: 2.0422 - accuracy: 0.5626
Epoch 9/10
5/5 - 0s - loss: 1.9191 - accuracy: 0.6242
Epoch 10/10
5/5 - 0s - loss: 1.9914 - accuracy: 0.5582
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-104-2d127e528fbe> in <module>()
      8     viz = plot_roc_curve(classifier, X[test], y[test],
      9                          name='ROC fold {}'.format(i),
---> 10                          alpha=0.3, lw=1, ax=ax)
     11     interp_tpr = np.interp(mean_fpr, viz.fpr, viz.tpr)
     12     interp_tpr[0] = 0.0

/usr/local/lib/python3.6/dist-packages/sklearn/metrics/_plot/roc_curve.py in plot_roc_curve(estimator, X, y, sample_weight, drop_intermediate, response_method, name, ax, **kwargs)
    170     )
    171     if not is_classifier(estimator):
--> 172         raise ValueError(classification_error)
    173
    174     prediction_method = _check_classifer_response_method(estimator,

ValueError: KerasClassifier should be a binary classifier

A: This is an implementational detail that is (probably) missing in this wrapper library.
Sklearn simply checks whether an attribute called _estimator_type is present on the estimator and is set to string value classifier. You can see that by looking into sklearn's source code on github.
def is_classifier(estimator):
    """Return True if the given estimator is (probably) a classifier.
    Parameters
    ----------
    estimator : object
        Estimator object to test.
    Returns
    -------
    out : bool
        True if estimator is a classifier and False otherwise.
    """
    return getattr(estimator, "_estimator_type", None) == "classifier"

All you need to do is to add this attribute to your classifier object manually.
classifier = KerasClassifier(build_fn=create_network,
                                 epochs=10,
                                 batch_size=100,
                                 verbose=2)

classifier._estimator_type = "classifier"

I have tested it and it works.


text:
Q: How can I index my SQL table? I have two tables, the first is called Hotel and contains the following columns:
hotelID, AverageRating, OverallRating, URL

The second is called Review and contains:
hotelID, Author, Content, Date, No. Reader, No. Helpful, Overall, Value, Rooms, Location, Cleanliness, Checkin / front desk, Service, Business Service

I have been asked to create relevant indexes on my tables based on my queries. Here are my four queries:

*

*Find all the reviews by the same user (i.e., given a user ID, return
the list of all her reviews).

*Find all the users with the number of reviews greater than 2 and
return their name and number of hotels they reviewed for.

*Find all the hotels with the number of reviews greater than 10.

*Find all the hotels with overall rating greater than 3 and average
cleanliness greater or equal to 5 (Note: use the Overall Rating attribute).

Based on these queries I would need to index the following columns (I think):

*

*Author

*OverallRating

I would not need to index cleanliness as this is an average so indexing would have no benefit.
The Author column contains the username for the reviewer. For example, Quoka7. Would it be best to index this column by alphabet perhaps?
The OverallRating column contains a decimal (to 1 d.p) between 1.0 and 5.0. For example, 3.5. Would it be best to index this column to 1 d.p perhaps?
Lastly, would it be beneficial to me to index the hotelID column? This basically has the format hotel_* where * is a unique number for each hotel. Based on my queries I do not think this would be useful.
Thanks for your time, I'm here if you have any questions or need more info.
UPDATE
Author can also start with a number so perhaps alphabet not ideal.

A: You create an index in SQL with CREATE INDEX <nameOfIndex> ON <nameOfTable> (<field>,<field>,...); with one or more fields.
So for the first query how about CREATE INDEX Authors ON Review (Author);?
See if you can do the rest yourself. If you get stuck try looking through the lecture slides we're given and asking Google, you can't expect Stack Overflow to keep doing lots of your university coursework for you.

A: First of all, if you have any foreign keys, any columns used in these should most definitely be indexed.
Normally, you'd have a primary key on one side of the relationship, and a normal index on the other side of the relationship.
With regards to what columns you want to index, there's no correct or right answer to this.
Start by looking at what queries you are going to perform on the data. If you use the hotelID column for lots of queries, index it.
You could also time how long your queries take to run, then see if an index impacts on the time.
If the index reduces the speed, then you can keep it!
With regards to index types, SQLite doesn't have specific index types (as noted here).


text:
Q: Loading Esri ArcGrid export file (e00) in R? I am trying to load an ESRI ArcGrid export file into R. The file is located at- ftp://ftp.epa.gov/castnet/tdep/grids/n_tw/n_tw-2013.zip. The documentation for this file states, "Gridded data of the above variables are available in compressed ESRI ArcGRID export files" and not much else. Link to documentation  here. My major problem is that this is an e00 file, an old output format of Arc.
The most straightforward way to load a raster normally (if this wasn't an e00 file) would be:
require(raster)
require(rgdal)
test <- raster('/path/to/n_tw-2013.e00')

However, you will receive the error: n_tw-2013.e00 not recognised as a supported file format..
The RArcInfo package claims to be able to convert .e00 files into more useful Arc/Info binary coverage. To do this:
require(RArcInfo)
#first argument is the path to the e00 file, and the second argument is the new directory to create
e00toavc('/path/to/n_tw-2013.e00','/path/to/test1')

When I run this command it prints NULL, and creates two directories, test1, and info, however, both are empty. I'm not sure whats going wrong here.
How do I get this loaded into R as a raster so I can extract data to my specific lat/long?
Output of sessionInfo pasted here:
> sessionInfo()
R version 3.2.2 (2015-08-14)
Platform: x86_64-redhat-linux-gnu (64-bit)
Running under: CentOS release 6.7 (Final)

locale:
 [1] LC_CTYPE=en_US.UTF-8       LC_NUMERIC=C
 [3] LC_TIME=en_US.UTF-8        LC_COLLATE=en_US.UTF-8
 [5] LC_MONETARY=en_US.UTF-8    LC_MESSAGES=en_US.UTF-8
 [7] LC_PAPER=en_US.UTF-8       LC_NAME=C
 [9] LC_ADDRESS=C               LC_TELEPHONE=C
[11] LC_MEASUREMENT=en_US.UTF-8 LC_IDENTIFICATION=C

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods
[7] base

other attached packages:
[1] rgdal_1.2-5  raster_2.5-8 sp_1.2-4

loaded via a namespace (and not attached):
[1] tools_3.2.2     Rcpp_0.12.3     grid_3.2.2      lattice_0.20-33

A: It appears you are dealing with an ArcInfo Exchange file - check this out How To: Import an ArcInfo interchange file (E00) in ArcGIS. Your trying to do this using R.
If you wanted to use a command-line approach to unpack e00 you could use E00compr - A Library to Read/Write Compressed E00 Files with is open source.

Using the 'e00conv' Conversion Program
'e00conv' is a command-line executable that takes a E00 file as input (compressed or not) and copies it to a new file with the requested compression level (NONE, PARTIAL or FULL).
e00conv   [NONE|PARTIAL|FULL]
  input_file is the name of the E00 file to read from.
  output_file is the name of the file to create. If the file already exists then it is overwritten.
The last argument is optional and specifies the compression level to use when creating the output file (one of NONE, PARTIAL or FULL). The default is NONE (uncompressed).

If you had access to ArcGIS
The steps in ArcGIS:

ArcGIS 10.x - All ArcGIS licenses

*

*Open ArcMap.

*Click the ArcToolbox icon.
ArcToolbox icon for ArcGIS 10.x

*In ArcToolbox, expand Conversion Tools.

*Expand 'To Coverage'.

*Double-click 'Import from E00'.

*In the 'Input interchange file' (E00 file) entry box, click Browse. Navigate to the desired directory and select the file. Name the output dataset.

Note:
File naming restrictions outlined at the beginning of this article still apply at ArcGIS 10.x.

*Click OK. A dialog window appears and indicates the process has completed. Click Close.

*Click 'Add Data'
[O-Image] ArcMap Add Data button for Desktop 10.x
and navigate to the selected directory.

First convert the file to provide a compatible format for R, then try to reload the raster in R.

A: Use the function readGDAL from library(rgdal)
In your example should work:
n_tw_2013 <- readGDAL("path/to/the/file/n_tw-2013.e00")

A: I have no problem reading in the file using rgdal 1.2-3 and raster 2.5-8:
require(raster)
require(rgdal)
test <- raster('n_tw-2013.e00')
test
class       : RasterLayer
dimensions  : 775, 1440, 1116000  (nrow, ncol, ncell)
resolution  : 4134.354, 4134.354  (x, y)
extent      : -2950369, 3003101, 115686.8, 3319811  (xmin, xmax, ymin, ymax)
coord. ref. : +proj=aea +lat_1=0 +lat_2=29.5 +lat_0=45.5 +lon_0=0 +x_0=0 +y_0=-96 +ellps=WGS84 +towgs84=0,0,0,0,0,0,0 +units=m +no_defs
data source : /Users/Martin/Desktop/n_tw-2013.e00
names       : n_tw.2013
values      : 0.8068619, 70.83445  (min, max)

R version 3.3.1 (2016-06-21)
Platform: x86_64-apple-darwin13.4.0 (64-bit)
Running under: OS X 10.12.2 (Sierra)

locale:
[1] de_DE.UTF-8/de_DE.UTF-8/de_DE.UTF-8/C/de_DE.UTF-8/de_DE.UTF-8

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base

other attached packages:
[1] raster_2.5-8 sp_1.2-3

loaded via a namespace (and not attached):
 [1] Rcpp_0.12.7       plotly_4.5.2      magrittr_1.5      munsell_0.4.3     colorspace_1.2-7
 [6] viridisLite_0.1.3 lattice_0.20-34   R6_2.2.0          httr_1.2.1        plyr_1.8.4
[11] dplyr_0.5.0       tools_3.3.1       rgdal_1.2-3       grid_3.3.1        gtable_0.2.0
[16] DBI_0.5-1         htmltools_0.3.5   lazyeval_0.2.0    assertthat_0.1    digest_0.6.10
[21] tibble_1.2        purrr_0.2.2       ggplot2_2.2.0     tidyr_0.6.0       base64enc_0.1-3
[26] htmlwidgets_0.8   scales_0.4.1      jsonlite_1.1


text:
Q: php functions using with smarty template please give some note about php functions using with smarty template

A: Smarty does allow you to call PHP functions, but it's assumed that you shouldn't need to and so it's not as easy as it could be. The general philosophy of Smarty is that you should avoid tying your templates too closely to your application code (i.e. the PHP), as this would make Smarty itself somewhat redundant.
This thread may be of use:
http://www.smarty.net/forums/viewtopic.php?p=46985

A: Yes, the  smarty template engine does work with PHP. If you wish to have a look at a tutorial have a look at the smarty website.


text:
Q: Find a vector which is perpendicular to both $ti+t²j−2k$ and $si+2j+s²k$. I have to answer this question. However, I don't really know how to get started with this problem.
Thank you for reading and I am eager for your guys response
Oscar

A: From memory, the vector 'cross' product is;
$$\begin{pmatrix} a \\ b \\ c \end{pmatrix} \times \begin{pmatrix} l \\ m \\ n \end{pmatrix}=\begin{pmatrix} bn-cm \\ cl-an \\ am-bl \end{pmatrix}$$
So for this question,
$$\begin{pmatrix} t \\ 2t \\ -2 \end{pmatrix} \times \begin{pmatrix} s \\ 2 \\ 2s \end{pmatrix}=\begin{pmatrix} 4ts+4 \\ -2s-2ts \\ 2t-2ts \end{pmatrix}=2\begin{pmatrix} 2ts+2 \\ -s-ts \\ t-ts \end{pmatrix}$$
Not sure if that's an end in itself or if your question is part of something bigger.


text:
Q: Redirect requests to other IP address in a case of link failure I am looking for possible solutions or ideas how to implement redundancy with connection link from two different ISP s. I have site with web server and this is primary link. I want to have redundancy in a way to get another link from other ISP, so if one link fail, other link will serve web requests. I know that my DNS record can have associate 2 IP address (primary link ip address and secondary link IP address).I know that dns resolver use round robin whan answer to dns requests, but I want to use other IP only in a case of failure primary connection link. Also I know that some browser will wait for 30 seconds and try secondary IP address but this is long time for client to wait.
Is there any other solution beside registering AS Number and routing options.
Thx


text:
Q: How do I get the the file name of the file I uploaded and store that file name into sql, My question is, how do I get the name of the file I uploaded and store it into mysql. Here's my code:
define("UPLOAD_DIR", "../uploads/");

 if (!empty($_FILES["myFile"])) {
$myFile = $_FILES["myFile"]['name'];

if ($myFile["error"] !== UPLOAD_ERR_OK) {
    echo "
An error occurred.
";
    exit;
}

// ensure a safe filename
$name = preg_replace("/[^A-Z0-9._-]/i", "_", $myFile["name"]);

// don't overwrite an existing file
$i = 0;
$parts = pathinfo($name);
while (file_exists(UPLOAD_DIR . $name)) {
    $i++;
    $name = $parts["filename"] . "-" . $i . "." . $parts["extension"];
}

// preserve file from temporary directory
$success = move_uploaded_file($myFile["tmp_name"],
    UPLOAD_DIR . $name);
if (!$success) {
    echo "
Unable to save file.
";
    exit;
}

// set proper permissions on the new file
chmod(UPLOAD_DIR . $name, 0644);

And here's my sql query
$q= "INSERT INTO `discaction`(`posted_by`,`date_posted`,`date_happened`,`document`,`people_involved`,`reason`,`status`,`extra`) VALUES ('$posted_by','$date_posted','$_POST[monthreq]-$_POST[datereq]-$_POST[yearreq]','$name','$_POST[people_involved]','$_POST[reason]','$status','$extra')";

Thank you for your answers.


text:
Q: Do I need to dispose an instance of my custom class to free up memory? Then how? VB.NET I just want to save time and codes to create a custom class in executing my SQL queries so I created just like this:
Imports ADODB

Public Class MySQLConnection
    Private SQLConnection As ADODB.Connection
    Private SQLConnectionString As String = "Provider=SQLOLEDB;Data Source=111.111.10.201;Initial Catalog=dbSample;User ID=User;password=123456;"
    Private SQLRecordSet As ADODB.Recordset
    Public Recordset As ADODB.Recordset
    Public Message As String

    Public Function ExecuteSQLQuery(vQuery As String) As Boolean
        Try
            SQLConnection.Open(SQLConnectionString)

            SQLRecordSet.CursorLocation = ADODB.CursorLocationEnum.adUseClient
            SQLRecordSet.CursorType = ADODB.CursorTypeEnum.adOpenStatic
            SQLRecordSet.LockType = ADODB.LockTypeEnum.adLockBatchOptimistic

            SQLRecordSet.Open(vQuery, SQLConnection)

            Recordset = SQLRecordSet 'passing the content of recordset to a public recordset for later use in my main program.

            SQLRecordSet.Close()

            SQLConnection.Close()

            Message = "Query executed successfully."
            Return True

        Catch ex As Exception
            Message = ex.Message
            Return False

        End Try
    End Function
End Class

QUESTION #1
But since I will be creating multiple instance of this class throughout my program, do I need to somehow dispose the instance to free up the memory immediately after use?
Whenever I need to execute my query, I use my code below in my main program:
    Private Sub COnnectToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles COnnectToolStripMenuItem.Click
        Dim DB_CONN As New MySQLConnection
        If DB_CONN.ExecuteSQLQuery("SELECT * FROM tbl_Stores") Then

            If DB_CONN.Recordset.RecordCount <> 0 Then
                DB_CONN.Recordset.MoveFirst()
                Do While Not DB_CONN.Recordset.EOF
                    'Read each record here
                    DB_CONN.Recordset.MoveNext()
                Loop
            End If

            DB_CONN.Recordset.Close()

            '==============================
            'This is where I think I should dispose my class instance [DB_CON].

            MsgBox("MESSAGE: " & DB_CONN.Message)
        Else
            MsgBox("ERROR: " & DB_CONN.Message)
        End If
    End Sub

QUESTION #2:
How do I dispose the instance of my class after use?
I just want to know this so I can clean up my previous programs.
All I find in Google is for C++ so I'm not sure if it works for VB.Net
Please help! :(

A: If I were you I'd look at making the ExecuteSQLQuery completely self contained such that it takes an Action(Of ADODB.Recordset). Then it can clean up after itself immediately after it has executed.
I'd initially write it like this:
Public Module MySQLConnection
    Private SQLConnectionString As String = "Provider=SQLOLEDB;Data Source=111.111.10.201;Initial Catalog=dbSample;User ID=User;password=123456;"
    Public Function ExecuteSQLQuery(vQuery As String, process As Action(Of ADODB.Recordset), message As Action(Of String)) As Boolean
        Try
            Dim conn As ADODB.Connection = New ADODB.Connection()
            conn.Open(SQLConnectionString)
            Dim rs As ADODB.Recordset = New ADODB.Recordset()
            rs.CursorLocation = ADODB.CursorLocationEnum.adUseClient
            rs.CursorType = ADODB.CursorTypeEnum.adOpenStatic
            rs.LockType = ADODB.LockTypeEnum.adLockBatchOptimistic
            rs.Open(vQuery, conn)
            process?(rs)
            rs.Close()
            conn.Close()
            message?("Query executed successfully.")
            Return True
        Catch ex As Exception
            message?(ex.Message)
            Return False
        End Try
    End Function
End Module

Now you'd use it like this:
Private Sub COnnectToolStripMenuItem_Click2(sender As Object, e As EventArgs) Handles COnnectToolStripMenuItem.Click
    Dim success As Boolean = MySQLConnection.ExecuteSQLQuery("SELECT * FROM tbl_Stores",
        Sub(recordset)
            If recordset.RecordCount <> 0 Then
                recordset.MoveFirst()
                Do While recordset.EOF
                    'Read each record here
                    recordset.MoveNext()
                Loop
            End If
        End Sub, AddressOf MsgBox)
End Sub

Or even better - make the method return an enumerable of some value:
Public Module MySQLConnection
    Private SQLConnectionString As String = "Provider=SQLOLEDB;Data Source=111.111.10.201;Initial Catalog=dbSample;User ID=User;password=123456;"
    Public Iterator Function ExecuteSQLQuery2(Of T)(vQuery As String, process As Func(Of ADODB.Recordset, T)) As IEnumerable(Of T)
        Dim conn As ADODB.Connection = New ADODB.Connection()
        conn.Open(SQLConnectionString)
        Dim rs As ADODB.Recordset = New ADODB.Recordset()
        rs.CursorLocation = ADODB.CursorLocationEnum.adUseClient
        rs.CursorType = ADODB.CursorTypeEnum.adOpenStatic
        rs.LockType = ADODB.LockTypeEnum.adLockBatchOptimistic
        rs.Open(vQuery, conn)
        If rs.RecordCount <> 0 Then
            rs.MoveFirst()
            Do While rs.EOF
                Yield process(rs)
                rs.MoveNext()
            Loop
        End If
        rs.Close()
        conn.Close()
    End Function
End Module

Then you can do this:
Private Sub COnnectToolStripMenuItem_Click2(sender As Object, e As EventArgs) Handles COnnectToolStripMenuItem.Click
    Dim values As IEnumerable(Of Integer) = MySQLConnection.ExecuteSQLQuery2(Of Integer)("SELECT * FROM tbl_Stores", Function(recordset) CType(recordset.Fields("Value").Value, Integer))
End Sub


text:
Q: Select option using Excel Automation with Internet explorer I have been trying for days. I can update the value of text boxes and click on option buttons however I am unable to select the option from a drop down list
To select the drop down option I have tried:
 myHTMLFrame2.all.Item("QSGAA5V0GAFRWAOL34D8OK78W2ZUJO").Focus
    myHTMLFrame2.all.Item("QSGAA5V0GAFRWAOL34D8OK78W2ZUJO").selectedIndex = 1
    myHTMLFrame2.all.Item("QSGAA5V0GAFRWAOL34D8OK78W2ZUJO").FireEvent "onchange"

Nothing happens with the above
Dim myHTMLFrame2 As HTMLDocument
    Set myHTMLFrame2 = HTMLDoc.frames(3).document
    Dim elem As Object

    Set elem = myHTMLFrame2.document.getElementById("QSGAA5V0GAFRWAOL34D8OK78W2ZUJO")
(results in "object not supported error")
    elem.Focus
    elem.selectedIndex = 2

This is the HTML Code:

                        <select id="QSGAA5V0GAFRWAOL34D8OK78W2ZUJO" overwrite="1" level="0"
                            val="$escapeTool.html($!{answerValue})" required="true" questionid="QSGAA5V0GAFRWAOL34D8OK78W2ZUJO" totalorder="0" questiondefid="QDGAA5V0GAFRWAOL34D8OK78W2ZUJP"
                            responsetype="STATIC_MENU" autocomplete="off"
                            aria-activedescendant="" aria-labelledby="QSGAA5V0GAFRWAOL34D8OK78W2ZUJO-label" tabindex="0">
                            <option value=""></option>
                            <option value="New User(s)" ps="0" aria-selected="false">New User(s)</option>
                            <option value="Modify User Details or Applications" ps="1" aria-selected="false">Modify User Details or Applications</option>
                            <option value="Add/Modify User By Attachment" ps="2" aria-selected="false">Add/Modify User By Attachment</option>
                            <option value="clear">(clear)</option>
                        </select>

A: You could try attaching an event to the select element. I have targeted using tag and attribute in case id is dynamic. If id static then use that. If it is inside the iframe then add the appropriate syntax in front to access.
Dim dropDown As Object, onChange As Object
Set dropDown = ie.document.querySelector("select[overwrite='1']")
Set onChange = ie.document.createEvent("htmlevents")
onChange.initEvent "change", True, False
ie.document.querySelector("[value='New User(s)']").Selected = True
links.dispatchEvent onChange

A: Try to make test with code below may help to solve the issue.
Code:
     Sub demo()

            Dim URL As String
            Dim IE As Object

            Set IE = CreateObject("InternetExplorer.Application")

            IE.Visible = True

            URL = "C:\Users\Administrator\Desktop\107.html"

            IE.Navigate URL

            Do While IE.ReadyState = 4: DoEvents: Loop   'Do While
            Do Until IE.ReadyState = 4: DoEvents: Loop   'Do Until

             IE.Document.GetElementByID("QSGAA5V0GAFRWAOL34D8OK78W2ZUJO").Value = "Modify User Details or Applications"

            Set IE = Nothing

End Sub

Output in IE 11:

A: @Qharr & @Deepak -- Thank You
I examined the element and turns out the code creates an "input" element at run time. In order to execute the event I am using send keys. Not very elegant but it works.
myHTMLFrame2.all.Item("QSGAA5V0GAFRWAOL34D8OK78W2ZUJO_input").Focus
myHTMLFrame2.all.Item("QSGAA5V0GAFRWAOL34D8OK78W2ZUJO_input").Value = "New User(s)"
myHTMLFrame2.all.Item("QSGAA5V0GAFRWAOL34D8OK78W2ZUJO_input").Click
Application.SendKeys "{DOWN}"
Application.SendKeys "{DOWN}"
Application.SendKeys "~"


text:
Q: Want to conditionally concatenate strings from a text file using C++ I have a text file which looks like this:
8284734746
pat monahan
8284735406
pat monahan
8277059735
rolling stones black keys
rolling stonesnprudential center newark njn121512
8277167638
keith richards
prudential centernnewark njn15dec2012

So if you notice I have an ID and a phrase in the next line OR an ID and TWO phrases in the next line. My goal is to have IDs in one text file and text (that belongs to that ID) on ONE line and saved as a separate text file. So I need to conditionally concatenate strings in my text file.
The code I have so far doesn't achieve this.
#include <iostream>
#include <fstream>
#include <string.h>
#include <sstream>
#include <iterator>

using namespace std;

bool is_number(const std::string& s)
{
   return( strspn( s.c_str(), "0123456789" ) == s.size() );
}

int main()
{
   ifstream inputFile("title_desc_ids.txt");

     string line;
      vector <string> ids;
      vector <string> desc;

      while (getline(inputFile, line))
      {
          if (is_number(line))
          {
              ids.push_back(line);
          }
          else
              desc.push_back(line);
      }

      string full_file_name = "./title_desc_ids_all.txt";
      string full_file_name_desc = "./title_desc_combined.txt";
      ofstream output_file(full_file_name.c_str());
      ofstream output_file1(full_file_name_desc.c_str());
      copy(ids.begin(), ids.end(), ostream_iterator<string>(output_file, "\n"));
      copy(desc.begin(), desc.end(), ostream_iterator<string>(output_file1, "\n"));
  }

Can anybody please point me in the right direction?
Thanks!

A: You need to keep track of IDs you entered as you input them.  Then the indexes will match up.
int IDCnt = 0;

while (getline(inputFile, line))
{
    if (is_number(line))
    {
        ids.push_back(line);
        IDCnt++;
    }
    else {
        if(IDCnt > desc.size()) desc.push_back(line);
        else desc[IDCnt-1] = desc[IDCnt-1] + line;
    }

}