text:
Q: What does "A1:A4^{1,2,3}" mean in an Excel formula? What does the caret operand in Excel do to a range when it is followed by some other numbers in brackets? For example lets say we have the following table:
      A    B    C
1    1.5   0    0
2   -0.5   0    0
3    4     0    0
4    5     0    0

Then, what is the following formula doing?
= A1:A4^{1,2,3}

A: The caret operator is for specifying an exponent.  For instance, 2^4 will return 2 to the 4th power (2*2*2*2), which is 16.
Curly brackets like this are a way of defining an array, which could be used wherever a range could also be specified.  For instance, using the INDEX formula with an array like so: =INDEX({2,5,7,9}, 4) will return the 4th item in the array: 9.
I have no idea what this formula is attempting to do.  As it is, it results in an error.  You can enter it as an array formula by pressing CTRL and SHIFT while pressing ENTER, but that will only return the value of the first cell (A1) raised to the first value in the given array (1), which is the same as 1.5 to the 1st power, which is 1.5.

A: The caret signifies a power operation. The curly bracketed expression, {1,2,3}, is an array containing the values 1, 2, and 3.
As noted by @JasonClement, this formula only returns a value when entered as an array formula with Ctrl+Shift+Enter. As an array formula, the result is a 4-by-3 matrix containing the values below.
A1^1  A1^2  A1^3
A2^1  A2^2  A2^3
A3^1  A3^2  A3^3
A4^1  A4^2  A4^3

When entered in a single cell, however, only the top-left value of the matrix is returned.
The secret to this formula is that it must be entered as a single formula into a range the same size as the matrix. To do this, select an empty 4-by-3 range, e.g. D1:F4. Without changing the selection, click in the formula bar and type the formula. Then press Ctrl+Shift+Enter. You'll see the full matrix of results printed in the range you selected.


text:
Q: syntax error for ruby using array I tried if I use 2*(2-1), that works, but if I need the value of x.(x.count/2), and then it said syntax error. how can I use the array correctly?
thanks!
x = ["2,", "5", "7", "10", "20", "30", "50", "90", "101", "120"]
x.(x.count/2)

NoMethodError: undefined method `call' for ["2,", "5", "7", "10", "20", "30", "50", "90", "101", "120"]:Array
    from (irb):10

A: I think you mean to call the [] operator. Instead you are using () to perform indexing on the array which results in calling x.(5) or x(5). This operator is not defined for an array. You should instead write x.[](x.count/2) or more simply x[x.count/2].

A: You need to use brackets instead of parenthesis for an array.
 x = ["2,", "5", "7", "10", "20", "30", "50", "90", "101", "120"]
 x[x.count/2]

redpajama_set_name: RedPajamaStackExchange


text:
Q: best way to dynamically change the UITableViewCell for the first row only I'd like to be able to dynamically change the first cell of my UITableView.
Basically, when I'm scrolling, I'd like the first row to  be "highlighted" when it is scrolled to first visible position in the table. I found at least one way involving
indexPathsForVisibleRows

and
reloadRows at:indexPath:

but the results are less than optimal.
Is there a clean way to achieve this?

A: As I understand that you are creating a thing that look like dateTimePicker/Picker. So, I think the implement are the same between these. First, Delegate from scrollView must be handle to know when will the TableView is stopped scrolling. Then, we have to snap to the first cell visible fully visible (in case it just visible a little bit). Then we need to update that first cell to hight light. Hope this will help you.


text:
Q: How to speed up this DP? I was trying to solve this problem from codechef and created a top-down DP solution that utilises memoization. The following is the code for this problem:
#include <iostream>
#include <cstdio>
#include <cmath>
#include <vector>
using namespace std;

vector<int> height;
vector<int> memo;

int jump(int i)
{
    if(memo[i] != -1)
        return memo[i];
    else
    {
        int min = 987654321, res;
        for(int j = (i - 1);j >= 0;j--)
        {
            if(!(height[i]-height[j] == 0) && !(height[i]-height[j] & (height[i]-height[j] - 1)))
            {
                res = jump(j) + height[i]-height[j];
                if(res < min)
                    min= res;
            }
        }
        memo[i] = min;
        return min;
    }
}

int main(void)
{
    int n;
    scanf("%d", &n);
    height.resize(n, 0);
    memo.resize(n, -1);
    memo[0] = 0;
    for(int i = 0;i < n;i++)
    {
        scanf("%d", &height[i]);
    }
    int ans = jump(n-1);
    printf("%d\n", ans);
}

The time limit for the problem is 1 second and I saw a number of solutions doing nearly the same thing(int bottom up DP) and passing... But I read that bottom-up DP and top-down DP are exactly the same in terms of time complexity, and sometimes, in few cases, better. But, this seems to violate the law...
I feel I'm not memoizing the solutions correctly, and or, am defining the subproblems in an in-efficient way. Can someone help me here ?


text: Q: Can a multivariable function be defined at a certain point where the limit does not exist? I watched Professor Leonard's lecture on limits and continuity of multivariable functions, where he said that a two-variable function is continuous everywhere it is defined, that is, the entire domain (if I understood correctly). And I was wondering: is it possible to have something like a jump discontinuity in a graph of three or more dimensions such that the function is defined at a certain point, but the limit doesn't exist there?


text:
Q: Showing / Hiding nested divs Hi and I hope someone can help.
I'm building a website which will have a main horizontal tabbed menu and a secondary horizontal tabbed menu when one of the items above is clicked. Off the second tabbed menu there will be another sub menu which bring up links where, once clicked, will reveal content to the right. Pictorially this is shown below.

To try and get the logic working I've built some very simple test pages to try out showing and hiding divs but I only seem to be able to get the equivalent of   the first sub menu showing.
Because (ultimately) this will be a large site with multiple pages I've organised the first menu in the root folder of the site, the sub menu in a sub folder called 'pages' and the sub sub menu in a folder called 'pages/resource_pages'.
Here's my test code, 1 the top level - nest.html in the root folder

Nested Div Test

 Nest 1 - located in root folder

Second level code - nest2.html in the pages folder

 Nest 2 - located in root/pages folder

Third level code - nest3.html in the pages/resource_pages sub folder

 Nest 3 - located in root/pages/resource_pages folder

Here' my javascript
function openLevel2(evt, scriptName) {
    // Declare all variables
    var i, level1Hyperlink, level1HiddenDiv;

    // Get all elements with class="level1HiddenDiv" and hide them
    level1HiddenDiv = document.getElementsByClassName("level1HiddenDiv");
    for (i = 0; i < level1HiddenDiv.length; i++) {
        level1HiddenDiv[i].style.display = "none";
    }

    // Get all elements with class="level1Hyperlink" and remove the class "active"
    level1Hyperlink = document.getElementsByClassName("level1Hyperlink");
    for (i = 0; i < level1Hyperlink.length; i++) {
        level1Hyperlink[i].className = level1Hyperlink[i].className.replace(" active", "");
    }

    // Show the current tab, and add an "active" class to the link that opened the tab
    document.getElementById(scriptName).style.display = "block";
    evt.currentTarget.className += " active";
}

// Script for showing resource letter menu tabs
function openLevel3(evt, resourceName) {
    // Declare all variables
    var i, level2Hyperlink, level2HiddenDiv;

    // Get all elements with class="level2Hyperlink" and hide them
    level2HiddenDiv = document.getElementsByClassName("level2HiddenDiv");
    for (i = 0; i < level2HiddenDiv.length; i++) {
        level2HiddenDiv[i].style.display = "none";
    }

    // Get all elements with class="level2Hyperlink" and remove the class "active"
    level2Hyperlink = document.getElementsByClassName("level2Hyperlink");
    for (i = 0; i < level2Hyperlink.length; i++) {
        level2Hyperlink[i].className = level2Hyperlink[i].className.replace(" active", "");
    }

    // Show the current tab, and add an "active" class to the link that opened the tab
    document.getElementById(resourceName).style.display = "block";
    evt.currentTarget.className += " active";
}

// Script for showing resource letter sub menu tabs
function openLevel4(evt, letterName) {
    // Declare all variables
    var i, level3Hyperlink, level3HiddenDiv;

    // Get all elements with class="level3HiddenDiv" and hide them
    level3HiddenDiv = document.getElementsByClassName("level3HiddenDiv");
    for (i = 0; i < level3HiddenDiv.length; i++) {
        level3HiddenDiv[i].style.display = "none";
    }

    // Get all elements with class="level3Hyperlink" and remove the class "active"
    level3Hyperlink = document.getElementsByClassName("level3Hyperlink");
    for (i = 0; i < level3Hyperlink.length; i++) {
        level3Hyperlink[i].className = level3Hyperlink[i].className.replace(" active", "");
    }

    // Show the current tab, and add an "active" class to the link that opened the tab
    document.getElementById(letterName).style.display = "block";
    evt.currentTarget.className += " active";
}

Can anyone spot what I'm doing wrong?
Thanks for your interest.

A: Messing around with a lot js and html, you can run into problems concerning readability, so i would prefer a pure js solution, wich will make it more readable /better debuggable:
var structure={
    name:"level1",
    links:[
         {
         name:"level2-1",
         links:[
                     {
                      name:"level3-1",
                      links:[]
                     },
                     {
                     name:"level3-2",
                     links:[]
                     }
                  ]
          },
          { name:"level2-2", ...
          }
       ]
     };

function show(element){
//add the name to header
 document.GetElementById("header").innerHTML=element.name;
linkcontainer=document.getElementById("linkcontainer");
linkcontainer.innerHTML="";
counter=0;
element.links.forEach(function(link){
    l=document.createElement("span");
    l.onclick=(function(element,counter){
         //this should create an onclick element
      return  function(){show(element.links[counter])};
    })(element,counter);
    l.innerHTML=element.links[counter].name;
    linkcontainer.appendChild(l);
    counter++;
    }
    }
 window.onload=function(){show(structure);}
 </script>

should contain name

should contain links

This should create:
Level1
Level2.1
Level2.2

And if you click on level 2.1:
Level2.1
Level3.3
Level3.4

I had problems with the onclick statement: http://www.howtocreate.co.uk/referencedvariables.html


text:
Q: Neural Network for XOR approximation always outputs 0.5 for all inputs I've tried to implement the following neural network for XOR gate approximation. I've used the binary cross entropy for cost function. The cost always goes to around 0.69 and gets saturated. And for all inputs the network outputs 0.5. I've tried varying number of epochs, learning rate, number of layers but got no change. Where am I going wrong?
import numpy as np
import matplotlib.pyplot as plt

epsilon = 1e-15

def sigmoid(x):
    return 1 / (1 + np.exp(-x))

def relu(x):
    return np.maximum(0, x)

def sigmoid_backwards(A):
    return A * (1 - A)

def relu_backwards(A):
    return A >= 0

def init_parameters(layer_dims):
    paramters = {}
    L = len(layer_dims)
    for i in range(1, L):
        paramters['W' + str(i)] = np.random.randn(layer_dims[i], layer_dims[i-1]) * 0.001
        paramters['b' + str(i)] = np.zeros((layer_dims[i], 1))
    return paramters

def forward_pass(X, paramters, g):
    layer_vals = [X]
    A = X
    L = len(g)
    for i in range(1, L):
        A_prev = A
        Z = np.dot(paramters['W' + str(i)], A_prev) + paramters['b' + str(i)]
        A = activations[g[i]](Z)
        layer_vals.append(A)

    return layer_vals

def predict(X, paramters, g):
    layer_vals = [X]
    A = X
    L = len(g)
    for i in range(1, L):
        A_prev = A
        Z = np.dot(paramters['W' + str(i)], A_prev) + paramters['b' + str(i)]
        A = activations[g[i]](Z)
        layer_vals.append(A)

    return layer_vals[-1][0]

def backward_pass(y_true, layer_vals, paramters, g, learning_rate=0.01):
    m = y_true.shape[1]
    dA = -y_true/(layer_vals[-1] + epsilon) + (1-y_true)/(1-layer_vals[-1] + epsilon)
    for i in range(len(layer_vals)-1, 0, -1):
        dZ = dA * activations_backwards[g[i]](layer_vals[i])
        dA_prev = np.dot(paramters['W' + str(i)].T, dZ)
        dW = 1/m * np.dot(dZ, layer_vals[i-1].T)
        db = 1/m * np.sum(dZ, axis=1, keepdims=True)
        dA = dA_prev

        paramters['W' + str(i)] -= learning_rate * dW
        paramters['b' + str(i)] -= learning_rate * db

    return paramters

def compute_cost(y, output):
    m = y.shape[1]
    return -1/m * np.sum(y * np.log(output+epsilon) + (1-y) * np.log(1-output+epsilon))

activations = {
    'sigmoid': sigmoid,
    'relu': relu
}

activations_backwards = {
    'sigmoid': sigmoid_backwards,
    'relu': relu_backwards
}

X = np.array([[0.000000, 0.000000, 1.000000, 1.000000],
              [0.000000, 1.000000, 0.000000, 1.000000]], dtype=float)
y = np.array([[0.0, 1.0, 1.0, 0.0]], dtype=float)

layer_dims = (2, 3, 3, 1)
#g = ['linear', 'sigmoid', 'sigmoid', 'sigmoid']
g = ['linear', 'relu', 'relu', 'sigmoid']
epochs = 1000
learning_rate = 0.01
paramters = init_parameters(layer_dims)
layer_vals = forward_pass(X, paramters, g)
costs = []
for i in range(epochs):
    parameters = backward_pass(y, layer_vals, paramters, g, learning_rate=learning_rate)
    layer_vals = forward_pass(X, paramters, g)
    cost = compute_cost(y, layer_vals[-1])
    costs.append(cost)
    if (i+1) % 10 == 0:
        print(f"After {i+1} epochs at learning rate {learning_rate:.4f}, cost: ", cost)

plt.plot(costs)
plt.show()
print(predict(X, paramters, g))

Here is the curve for cost function value
Cost Curve.
And the output is always
[0.5 0.5 0.5 0.5]

A: Nice try on neural nets; you're very close! Doing the following fixes your code:

*

*You have a typo in parameters = backward_pass() that causes your parameters not do be updated.

*Fixing this makes your network only converge in 1/1000 cases. Initializing your weights with std deviation of 1. and increasing #units per layer makes your code work perfectly!

Here's the working code:
import numpy as np
import matplotlib.pyplot as plt

epsilon = 1e-15

def sigmoid(x):
    return 1. / (1. + np.exp(-x))

def relu(x):
    return np.maximum(0, x)

def sigmoid_backwards(A):
    return A * (1 - A)

def relu_backwards(A):
    return A >= 0

def init_parameters(layer_dims):
    paramters = {}
    L = len(layer_dims)
    for i in range(1, L):
        paramters['W' + str(i)] = np.random.randn(layer_dims[i], layer_dims[i-1]) * 1.
        paramters['b' + str(i)] = np.random.randn(layer_dims[i], 1) * 1. # np.zeros((layer_dims[i], 1))
    return paramters

def forward_pass(X, paramters, g):
    layer_vals = [X]
    A = X
    L = len(g)
    for i in range(1, L):
        A_prev = A
        Z = np.dot(paramters['W' + str(i)], A_prev) + paramters['b' + str(i)]
        A = activations[g[i]](Z)
        layer_vals.append(A)

    return layer_vals

def predict(X, paramters, g):
    layer_vals = [X]
    A = X
    L = len(g)
    for i in range(1, L):
        A_prev = A
        Z = np.dot(paramters['W' + str(i)], A_prev) + paramters['b' + str(i)]
        A = activations[g[i]](Z)
        layer_vals.append(A)

    return layer_vals[-1][0]

def backward_pass(y_true, layer_vals, paramters, g, learning_rate=0.01):
    m = y_true.shape[1]
    dA = -y_true/(layer_vals[-1] + epsilon) + (1-y_true)/(1-layer_vals[-1] + epsilon)
    #dA = -y_true * np.log(layer_vals[-1]+epsilon) + (1.-y_true) * np.log(1-layer_vals[-1]+epsilon)
    #print('dAnew', dA)
    for i in range(len(layer_vals)-1, 0, -1):
        #import pdb;pdb.set_trace()
        dZ = dA * activations_backwards[g[i]](layer_vals[i])
        dA_prev = np.dot(paramters['W' + str(i)].T, dZ)
        dW = 1/m * np.dot(dZ, layer_vals[i-1].T)
        db = 1/m * np.sum(dZ, axis=1, keepdims=True)
        dA = dA_prev
        paramters['W' + str(i)] -= learning_rate * dW
        paramters['b' + str(i)] -= learning_rate * db

    return paramters

def compute_cost(y, output):
    m = y.shape[1]
    return -1/m * np.sum(y * np.log(output+epsilon) + (1-y) * np.log(1-output+epsilon))

activations = {
    'sigmoid': sigmoid,
    'relu': relu
}

activations_backwards = {
    'sigmoid': sigmoid_backwards,
    'relu': relu_backwards
}

X = np.array([[0.000000, 0.000000, 1.000000, 1.000000],
              [0.000000, 1.000000, 0.000000, 1.000000]], dtype=float)
y = np.array([[0.0, 1.0, 1.0, 0.0]], dtype=float)

layer_dims = (2, 32, 32, 1)
#g = ['linear', 'sigmoid', 'sigmoid', 'sigmoid']
g = ['linear', 'relu', 'relu', 'sigmoid']
epochs = 10000
learning_rate = 0.001
paramters = init_parameters(layer_dims)
layer_vals = forward_pass(X, paramters, g)
costs = []
for i in range(epochs):
    paramters = backward_pass(y, layer_vals, paramters, g, learning_rate=learning_rate)
    layer_vals = forward_pass(X, paramters, g)
    cost = compute_cost(y, layer_vals[-1])
    costs.append(cost)
    if (i+1) % 10 == 0:
        print(f"After {i+1} epochs at learning rate {learning_rate:.4f}, cost: ", cost)

plt.plot(costs)
plt.savefig("delete.png")
print(predict(X, paramters, g))


text:
Q: Is there a name for this type of wavevector? When we say wavevector we often mean a vector $\mathbf k$ that is related to the direction and wavelength of a plane wave, given by $e^{i\,\mathbf k\cdot\mathbf x}$. I have to write something about Fourier transforms and I define the following vector:
$$\boldsymbol \lambda=\frac{2\pi}{k^2}\mathbf k=\frac{2\pi}{k}\hat{\mathbf k}$$
In other words a vector which is in the same direction as $\mathbf k$ and whose magnitude is the wavelength. When you draw the wavefronts of the plane wave it points from one wavefront to the next as shown here (please ignore $\mathbf a_1,\mathbf a_2$)

Is this is a known quantity and does it have a name?

A: $\vec\lambda$ is a vector that describes the wavelength.
It's the displacement from one wavefront to the next along the perpendicular to the wavefront. It essentially describes the direction of a "ray".


text:
Q: How to view movies frame by frame or move smoothly through a video sequence (golf swing!) How do I control display of a movie so I can move it smoothly through a sequence and stop at any point?  I have a Go Pro that can take 400 frames/sec and a video cam that takes ? frames/sec, but all I can do is hit Start/Stop real fast to try to stop it where I want to, or move a few frames farther on.  Specifically, I'm talking about viewing my golf swing, and I see them do it all the time on TV or on the instructional videos on line.  Do I have to buy a special video viewer to do this?  Does the GoPro suite have a feature to do this that I don't know about?

A: VLC Media Player can do it [freeware, all platforms]
Using default key-commands, can be changed in prefs.
Spacebar to pause
ctrl, alt or shift plus arrow key to jump differing amounts back & forwards to get the right start point
E key will then frame-by-frame


text:
Q: How did the Baker-Gill-Solovay paper come to be? How did the Baker-Gill-Solovay paper come to be? Why were those three people talking together about "Relativizations of the $P=?NP$" question, and what was their collaboration like for the paper submitted July 16, 1973?
The paper itself, as published in the 1975 SIAM Journal of Computation, does not cite any prior work of any of Ted Baker, John Gill or Robert Solovay.
Furthermore, it says that half of the famous result (theorem 1, an oracle $A$ such that $P^A = NP^A$) "was also discovered, independently, by Albert Meyer with Michael Fischer and by H. B. Hunt III", and the other half (theorem 3, an oracle $B$ such that $P^B \neq NP^B$) "was obtained independently by Richard Ladner". Apparently we would have gotten the BGS result in some form without any of the three named authors.
For what it's worth, here are webpages about Baker (from Florida State), Gill (from Stanford), and Solovay (from Wikipedia). Here is a book about the JSEP, an organization listed as funding Gill, with detail on Stanford in 1973 in the area of acoustic microscopy but not in logic.
All in all I see few historical hints, but the BGS result is well-enough known to seem worth a couple paragraphs of history here. Does anyone have good information? Or want to contact the people involved? Has this been written about elsewhere already?

A: Here is more about the result of M. Dekhtiar. There are several references to him proving the existence of an oracle $A$ with $P^{A} \ne NP^{A}$ (e.g. the Trakhtenbrot notes mentioned in another answer and L. Stockmeyer). His result is stated in 'On the impossibility of eliminating complete enumeration in computing a function relative to its graph', which is in Russian, and states theorems without proofs, sometimes mentioning a master's thesis which may contain all the proofs. If this is the only source, then I can't agree that an oracle with $P^{A} \ne NP^{A}$ was found or that the work is comparable to those parts of Baker-Gill-Solovay theorem.
Briefly, Dekhtiar considered the problem of an oracle machine which has access to an unknown oracle, where we know that the oracle calculates some partial recursive function $f \colon \mathbb{N} \to \mathbb{N}$ (which can be considered in the language of function graphs as $(x, f(x))$ iff $f(x)$ is defined). Without knowledge of that oracle, we should construct the oracle Turing machine to calculate the value $f(y)$ for some input word $y$, if it is defined. The main result of Dekhtiar is proving by diagonalization over all partial recursive functions that 'the best way' is to make sequential queries to the oracle $(y, 0)$, $(y, 1)$, $(y, 2)$ ... until we either get the value of the function or loop if it is undefined. Here 'the best' means with the fewest queries to the oracle, by comparison with the whole set of possible oracles (graphs of all partial recursive functions). So,

*

*polynomial bounds were not considered;

*nondeterministic Turing machines were not considered;

*the only resource bound considered was the number of queries to the oracle;

*diagonalization over all partial recursive functions was used;

*the main idea was not oracle separation but a class of oracles used to show that for each 'better machine' we can find some oracle where it's not true (not that it will make a mistake but will use more queries).

Sometimes it is said that this work can be considered as solving $P^{A} \ne NP^{A}$ problem implicitly. For that, we would need to add polynomial bounded functions, and nondeterministic machines, which are not so hard. The proof explicitly uses estimation of the 'best machine' over all partial recursive functions, and this could be fixed with diagonalization over bounded functions. However, we can't change the formulation of the problem from Dekhtiar and it differs from the  $P^{A} \ne NP^{A}$ problem. There is no trying to construct one oracle for oracle separation but only choosing for each machine another oracle to show that it's better (in some way and only for this oracle with that machine) to use exhaustive search with sequential queries.
So it sounds better to say: 'In 1969, M.Dekhtyar' showed that nondeterminism can be more powerful than determinism if access to an oracle is allowed', which is from  J. Buss, Relativized Alternation and Space —- Bounded Computation, and sounds even better if we add "implicitly". As Buss also said: "Independently in 1975, Baker, Gill, and Solovay exhibited oracles A, B, C, and D such that
\begin{align}
& P^{A} \ne NP^{A}\\
& P^{B} = NP^{B}\\
& P^{C} = NP^{C} \cap coNP^{C} \ne NP^{C}\\
& P^{D} \ne NP^{D} = coNP^{D}
\end{align}  They suggested that their results give evidence of the difficulty of the unrelativized $P =? NP$ problem."

A: Apparently, we would have gotten at least half of the BGS result without any of the three named authors and also without any of the 4 people they credit, all we needed was Dekhtiar.
The Annals of the History of Computing (1984) has a historical account by Trakhtenbrot of the proof by Dekhtiar (1969) that we can have $P^A\ne NP^A$.
Trakhtenbrot also explains that the $P^A\ne NP^A (\exists A)$ question was for him the main question they had been investigating, and was not viewed as a relativization of something else.

*

*$P\ne NP$ says that there is no way to short-circuit an exhaustive search through a mathematical space defined by the input string;

*$P^A\ne NP^A (\exists A)$ says that there is no way to short-circuit an exhaustive search through a mathematical space defined by a combination of (i) the input string and (ii) an external database.


text:
Q: Isekai manga where a guy and a girl are transported into an otome game (not "The World of Otome Games is Tough for Mobs") So I'm trying to found a manga that I read a while ago, but I don't know the title or the characters name of the same.
What I can remember from the manga is that the protagonist confesses to a girl but gets rejected, after that he walks away depressed and gets hit by a car.
After that he wakes up in a boy's body in another world. Knowing that he is in another world, he thinks that he has a cheat ability like in the manga and books he knew in his world, but when he tries to use it, nothing happens. He accepts this and continues with his life.
After that, he knows about a woman that is blackmailing his family with an item (idk what the item is), but he intimidates her and says that she is a liar (before that, he talked to a friend/soldier to attack her after she tries to attack him or something like that).
What I also remember is that there's a girl (presumably the same age as the MC) who is also a reincarnater, and she died in the same accident as the MC. She reveals that she knows the world that she is in and that it is an otome game she played a lot.
She also reveals that she is the main heroine (the main heroine or the friend of the heroine, I think) and that she has 4 or 5 boys (the routes) to choose from and that MC is one of them.
This is what I remember. So, if you guys know the title, please send me the name. xD

A: I suspect what you're looking for is Ikemen ni Tenseishita kedo, Cheat ha Dekimasenseshita.

Here are some parts of the manga which somewhat match what you've stated:

the protagonist confesses to a girl but gets rejected

he walks away depressed and gets hit by a car

a woman that is blackmailing his family with an item

he talked to a friend/soldier to attack her after she tries to attack him

So it appears that it hasn't been revealed in the manga (that's been translated so far) that the protagonist is in an otome game. However, it has been confirmed in the light novel, and the other events seem to align with everything else you outlined.
Hope that is what you're looking for.

A: Idk about the first part about getting hit by a car, but the later parts of your description pretty much match a manga called Otome Game Sekai wa Mob ni Kibishii Sekai Desu (Trapped in a Dating Sim: The World of Otome Games is Tough for Mobs).

Leon, a former Japanese worker, was reincarnated into an "otome game" world, and despaired at how it was a world where females hold dominance over males. It was as if men were just livestock that served as stepping stones for females in this world. The only exceptions were the game's romantic targets, a group of handsome men led by the crown prince. In these bizarre circumstances, Leon held one weapon: his knowledge from his previous world, where his brazen sister had forced him to complete this game. Leon, who really just wants to to live as a shut-in in the countryside, uses that knowledge to raise a ferocious revolt against the women and handsome men.


text:
Q: Spray.io case class extraction error I'm learning spray.io, and I'm stuck in a problem.. I'm trying to test the case class extraction of several GET parameters. My code is inspired by the examples from the documentation page :
package com.example

import akka.actor.Actor
import spray.routing._
import spray.http._
import MediaTypes._

class ServiceActor extends Actor
with ServiceHello {
    def actorRefFactory = context
    def receive = runRoute(testRoute)

trait ServiceHello extends HttpService with Controls {

case class Color(keyword: String, sort_order: Int, sort_key: String)

val route =
    path("test") {
        parameters('keyword.as[String], 'sort_order.as[Int], 'sort_key.as[String]).as(Color) { color =>
            handleTestRoute(color) // route working with the Color instance
        }
    }
}

This code should be ok, but when I try to run it, I got the following errors :
Cannot resolve symbol as (on top of "as(Color)" )
Missing parameter type: color (on top of "{ color =>")
I understand these errors, but i do not understand why they come...
I'm running Scala 2.10.3
Am I doing something wrong ?

A: Thats working for me (scala 2.10.4, spray 1.3.1):
import akka.actor.Actor
import spray.routing._
import spray.http._
import MediaTypes._

class ServiceActor extends Actor with ServiceHello {
  def actorRefFactory = context

  def receive = runRoute(testRoute)
}

trait ServiceHello extends HttpService {

  case class Color(keyword: String, sort_order: Int, sort_key: String)

  val testRoute =
    path("test") {
      parameters('keyword.as[String], 'sort_order.as[Int], 'sort_key.as[String]).as(Color) { color =>
        //handleTestRoute(color) // route working with the Color instance
        complete {

test route

        }
      }
    }
}

Don't know what Controls is, so I just commented it.


text:
Q: SQL relationship for database of Property/Estates I need to help with school project and Iam starting to being really desperate.
Assignment was ->
Create SQL database with relations for Property evidention(It must be able to properly register Propertys - Tenants, Repairs, Costs, etc...)

I made relations like this:
Relations

Teacher said that mine design of relations is extremly bad, and this was the reasons:
1)Tenant must be able to have more than 1 property (So switch Tenants and Propertys)
2)He said I should add table for Cost Category
3)He also said that I should redesign table with Costs ->that there should be Cost and PropertyID(Cost category)???? - I dont know if I uderstanded correctly about this one.
4) He said that I should delete Cost table
5) He wondered why I have RepairPrice in 2 tables

We need to use Microsoft SQL server
Can someone show me how proper relation sheme should look like?
Help would be greatly appreciated.
Thanks


text:
Q: How to map the Mixins for the nested JSON response I am using Jackson APIs for Mapping my JSON response into a java object.
For example,
for the response { name :'karthikeyan',age:'24',gender:'Male'}
@JsonProperty("name")
public String _name;
@JsonProperty("age")
public int _age;
@JsonProperty("gender")
public String _gender;

is the Mix-in and it works fine.(internally we will be mapping this pojo and Mix-in).Now how can i represent the following response in a Mix-in?
{
name :'karthikeyan',
age:'24',
gender:'Male',
interest:
      {
        books:'xxx',
        music:'yyy',
        movie:'zzz'
      }
}

i have tried with the following, but no luck.
@JsonProperty("name")
public String _name;
@JsonProperty("age")
public int _age;
@JsonProperty("gender")
public String _gender;

@JsonProperty("interest")
public InterestPojo interestPojo;  //created same format mix-in and pojo for interest params as well.

but unable to map them exactly, give your comments and thoughts on how to do it ?

A: I tried the following:
    ObjectMapper mapper = new ObjectMapper();
    System.out.println(mapper.writeValueAsString(new Something("Name", 12, "male", new Nested("books", "Music", "Movie"))));

public class Something {

    @JsonProperty("name")
    public String name;
    @JsonProperty("age")
    public int age;
    @JsonProperty("gender")
    public String gender;
    @JsonProperty("interest")
    public Nested nested;
    //Constructor
}

public class Nested {

    @JsonProperty("books")
    public String books;
    @JsonProperty("music")
    public String music;
    @JsonProperty("movie")
    public String movie;

    //Constructor
}

and the Output is:
{
"name":"Name",
"age":12,
"gender":"male",
"interest":
    {
        "books":"books",
        "music":"Music",
        "movie":"Movie"
    }
}

So everything is working as expected. I already checked if theres a difference if you provide some setters and getters and setting the visibility of the fields on private but that doas not make a difference.
Maybe you want to show us your InterestPojo or your output/stacktrace?
EDIT:
Okay i think i got it ;)
I tried the following:
public void start() throws IOException {
    ObjectMapper mapper = new ObjectMapper();
    mapper.getSerializationConfig().addMixInAnnotations(Something.class, Nested.class);
    mapper.getDeserializationConfig().addMixInAnnotations(Something.class, Nested.class);
    System.out.println(mapper.writeValueAsString(new Something("Name", 12, "male", new NestedImpl("name", null))));
}
public final class Something {
    private final String name;
    private int age;
    private String gender;
    // thats your interest thing
    public Nested nested;

    public Something(String name, int age, String gender, Nested nested) {
        this.name = name;
        this.age = age;
        this.gender = gender;
        this.nested = nested;
    }
    String getName() {
        return name;
    }
    Nested getNested() {
        return nested;
    }
}
public abstract class Nested {
    @JsonProperty("name-ext")
    abstract String getName();
    @JsonProperty("interest-ext")
    abstract Nested getNested();
}
public class NestedImpl extends Nested {
    private String name;
    private Nested nested;
    private NestedImpl(String name, Nested nested) {
        this.name = name;
        this.nested = nested;
    }
    @Override
    String getName() {
        return name;
    }
    @Override
    Nested getNested() {
        return nested;
    }
}

Output:
{
    "age":12,
    "gender":"male",
    "name-ext":"Name",
    "interest-ext":
    {
        "name-ext":"name",
        "interest-ext":null
    }
}

Thats not exactly your structure, but I think thats what you want. Am I right?
EDIT2: I Tested the following structure with JSON->Object and Object->JSON.
ObjectMapper mapper = new ObjectMapper();
mapper.getSerializationConfig().addMixInAnnotations(Something.class, Mixin.class);
mapper.getSerializationConfig().addMixInAnnotations(Nested.class, NestedMixin.class);
mapper.getDeserializationConfig().addMixInAnnotations(Something.class, Mixin.class);
mapper.getDeserializationConfig().addMixInAnnotations(Nested.class, NestedMixin.class);

Nested nested = new Nested();
nested.setName("Nested");
nested.setNumber(12);

Something some = new Something();
some.setName("Something");
some.setAge(24);
some.setGender("Male");
some.setNested(nested);

String json = mapper.writeValueAsString(some);
System.out.println(json);
Something some2 = mapper.readValue(json, Something.class);
System.out.println("Object: " + some2);

public abstract class Mixin {

    @JsonProperty("name")
    private String _name;
    @JsonProperty("age")
    private int _age;
    @JsonProperty("gender")
    private String _gender;
    @JsonProperty("interest")
    private Nested nested;
}

public class Something {
    private String _name;
    private int _age;
    private String _gender;
    private Nested nested;

    // You have to provide Setters and Getters!!
}

public abstract class NestedMixin {

    @JsonProperty("nameNested")
    private String name;
    @JsonProperty("numberNested")
    private int number;
}

public class Nested {
    private String name;
    private int number;

    // You have to provide Setters and Getters!!
}

Output:
{"age":24,"gender":"Male","name":"Something","interest":{"nameNested":"Nested","numberNested":12}}
Object: Something{name=Something, age=24, gender=Male, nested=Nested{name=Nested, number=12}}
Note: It seems that jackson got problems with inner classes. So if you test that examples in an extra project create extra class-files ;)
EDIT3: If you are using a Module, try the following:
public class JacksonMixinModule extends SimpleModule {
    public JacksonMixinModule() {
        super("JacksonMixinModule", new Version(0, 1, 0, "SNAPSHOT"));
    }
    @Override
    public void setupModule(SetupContext context) {
        super.setupModule(context);
        context.setMixInAnnotations(Something.class, Mixin.class);
        context.setMixInAnnotations(Nested.class, NestedMixin.class);
    }
}

...
ObjectMapper mapper = new ObjectMapper();
mapper.registerModule(new JacksonMixinModule());


text:
Q: How do I access the emulator control line in Android? I'm trying to change the time zone on my Android emulator. I'm using Eclipse on a Windows 7 machine. To do this it says to enter some commands in the command line, but doesn't say how to access the command line!
So how do I access the command line in Windows 7 using Eclipse?

A: Hit windows + r type in cmd
then type in
adb shell

A: Command line means the windows command line.  Click the windows orb and search cmd.  It might not work initially because you have to set the PATH variables properly.
Instructions from Android Developers site here
On Windows, right-click on My Computer, and select Properties. Under the Advanced tab, hit the Environment Variables button, and in the dialog that comes up, double-click on Path (under System Variables). Add the full path to the tools/ directory to the path.


text:
Q: Why it is possible to assign partial methods to delegates in spite of other constraints? I know the title might not be totally clear, but I didn't want to make it too long.
One thing boggles me when thinking about restrictions placed on partial methods. It seems to me that the rules are inconsistent. As you probably know:

Partial methods must always have a return type of void, and they
  cannot have any parameters  marked with the out modifier. These
  restrictions are in place because at run time, the method  may not
  exist and so you can't initialize a variable to what the method might
  return because  the method might not exist. Similarly, you can't have
  an out parameter because the method  would have to initialize it and
  the method might not exist. [1]

It sounds sensible to me. But at the same time:

If there is no implementing partial method declaration, then you
  cannot have any code that  attempts to create a delegate that refers
  to the partial method. Again, the reason is that the  method doesn't
  exist at run time. [1]

At first, all these rules seem to follow the same compiler logic. There is a difference, though. As stated in the second quotation, compiler issues an error only when there is no method implementation of the partial method. Why can't it also check for the implementation at compile-time in other scenarios? This would allow much more flexibility when using partial methods and the logic behind all rules would be identical.
I am afraid that the only answer I can get is "Because that's how it was implemented", but maybe there is something more to it?
[1] CLR via C#, Fourth Edition

A: The whole point of partial methods is to facilitate extensibility in generated code scenarios without runtime performance impact. The code generator emits a partial method signature, and then emits code that calls this partial method.
Now, at compile time, if the method isn't implemented, these call sites get entirely removed, and the remaining code has to be valid. The quotes are confusing in this regard, because they're talking about "runtime existence" of the method. That's nonsense: everything is resolved at compile time.
This is the reason for the difference: the rules you quoted first impose restrictions on the method signature, whereas the delegate rule imposes a restriction on method usage.
The rules about the signature make sure you can call the method in a manner the code will remain valid if the method call is removed. And the intended use case for partial methods is for them to be absent 99% of the time. If you require them to be implemented then that's not the feature you should be using in the first place. Use an abstract method or something alike.
Building a delegate to a method is like taking the pointer to the method, and you can't do that if the method doesn't exist (well, I suppose you could argue the compiler could just replace the delegate with null at this point, but you can't write, say, new Action(null)), yet there is no reason to disallow it if the method does exist, for the implementer's convenience. But the code generator shouldn't emit code that creates delegates to the method.

A: Keep in mind that the reason for partial methods is so they can be used in designer-generated code, i.e. the designer can generate calls to the methods and leave their (optional) implementation to a human developer (who will later compile the code). If, as you suggest, the calls gave compile-time errors when the method is not implemented, then there are cases where the generated code would not compile until the developer either changed the generated code (usually a bad idea) or until he implemented all the methods.
C# already has interfaces and abstract methods to force method implementation, partial methods try to do something else.


text:
Q: QuerySet basic methods typing Lets say i have a model Event, i want Event.objects.filter(blablabla) to return a QuerySet[Event], not just a QuerySet.
For this purpouse, i created a Manager. I need the manager in a separate file, since i have many Managers.
So an ideal thing to do would be something like
class EventManager(models.Manager):
    def filter(self, *args, **kwargs) -> QuerySet[Event]:
        return super().filter(*args, **kwargs)

But i can't import the Event model, since it would be a circular import (Event.objects is the EventManager).
How can i provide type hints for the filter and get functions?.

A: You need to use the TYPE_CHECKING constant from the typing module. The constant will be False at run time, but assumed to be True by type checkers.
from __future__ import annotations
from typing import TYPE_CHECKING
if TYPE_CHECKING:
    import Event

class EventManager(models.Manager):
    def filter(self, *args, **kwargs) -> QuerySet[Event]:
        return super().filter(*args, **kwargs)


text: Q: How to enable Google Cloud Secret Manager audit logging via Terraform? I have a Google Cloud project with secrets stored in Secret Manager. I want to audit Secret Manager data access. I want to enable this auditing via Terraform, as opposed to clicking around in the UI. How do I do that?


text:
Q: changing global variable with thread in Python I am trying to write a script updating a global variable every 10 seconds.  For simplicity let's just increment q once teach time
import time, threading

q = 0
def f(q):
    # get asset position every 10 seconds:
    q += 1
    print q

    # call f() again in 10 seconds
    threading.Timer(10, f).start()

# start calling f now and every 10 sec thereafter
f(q)

Instead python says:
UnboundLocalError: local variable 'q' referenced before assignment

What is the correct way to change the variable q?

this example uses threading, doesn't update any values.
Run certain code every n seconds

A: You need to explicitly declare q as a global. q += 1 confuses the interpreter otherwise.
import threading

q = 0
def f():
    global q
    q += 1
    print q
    threading.Timer(10, f).start()

f()


text:
Q: using parseInt to get a div element property always returns NAN I hopw the answer is simple, but I swear I've wasted hours on this.
I'm trying to change the position of a div element using regular ol' javascript. First I need the element's initial top and left property values as an integer. I'm trying to use parseInt(element.style.top, 10)
The problem I have is that the initial (default) element.style.top and left values always return NaN. If I  specify a top and left value before trying to parse the values, it works fine... I'd like to be able to handle a situation where the values haven't been specified yet...
Please help

A: The value may be coming out "NaN" because the CSS property value is "auto".  That happens a lot in IE.

A: element.offsetTop or element.offsetLeft return integers (no parsing needed), have you tried that? element.style.top can be a number of things, like auto, 3em, 20%. In the case of auto parseInt returns NaN, in the other cases it may return a number, but not the number you need.

A: You are querying for the style property (as set by for example CSS). However, you want the actual position of the element. Take a look here on how to do that with Javascript.


text:
Q: Uninstalling PowerShell 1.0 before installing Sharepoint 2010 While going through the book "Beginning Sharepoint 2010 Administration", the author was discussing on how to prepare for SharePoint 2010 server installation on win2008 R2 server. In that one of the step being uninstalling powershell 1.0, I don't understand the reason behind this.
Please help me to understand why one should uninstall this?
Thanks in advance.

A: PowerShell V1.0 was present on Windows Server 2008.
On Windows server 2008 R2 PowerShell 2.0 is natively present, so no need to upgrade it. You can refer to these StackOverflow articles:
Why is Powershell 2.0 installed in the same location as Powershell 1.0?
Determine What Version of PowerShell is Installed?


text:
Q: invalid literal for int() with base 10: in python I am taking a python course on www.adex.org. During course exercise I need to write a code for the following.
Exercise: Write a function that accepts a number as argument and returns the square of the number. For example if the number passed to the function is 5 then your function should return 25.
I have written the following code
def mysquare(n):

  result = n**2

  return result

a = int(input("Please enter the number: "))

print (mysquare(a))

Error Message:
Error in executing student function:

ValueError at line 4
invalid literal for int() with base 10: ''

The same code is working fine in python IDLE but not working fine on adex.org's editor. Any idea what could be reason for this error?

A: You were not handling the condition where a wrong input that is other than integer is provided. Try this. It will fix your issue as till such user fulfills the requirements it will not be allowed to move forward :
def mysquare(n):
    result = n**2
    return result
while True :
    try :
        a = int(input("Please enter the number: "))
        break
    except :
        print("You provided wrong data. Try again.")

print (mysquare(a))


text:
Q: Node.JS - How to identify which async HTTP GET response is returning data in a callback? I'm trying to follow the NodeSchool tutorials on async principles.  There is a lesson with the requirement to:

*

*make asynchronous GET requests to 3 URLs

*collect the data returned in HTTP responses using callbacks

*print the data collected from each response, preserving the order of the correlating input URLs
One way I thought of doing this was to make 3 separate callbacks, each writing to its own dedicated buffer.  But this seemed like a poor solution to me, because it requires code duplication and is not scalable.  However, I am stuck on figuring out another way to get a callback to remember "where it came from" for lack of a better term.  Or what order it was called in, etc.
I feel like I'm close, but I've been stuck at 'close' for long enough to look for help.  Here's the closest I've felt so far:
var http = require('http');

var replies = 0;
var results = ['','',''];
var running = '';

for(var i = 2; i < 5; i++) {
    http.get(process.argv[i], function (response) {
        response.setEncoding('utf8');
        response.on('data', handleGet);
        response.on('error', handleError);
        response.on('end', handleEnd);
    });
}

function handleGet(data) {
    running += data;
}

function handleError(error) {
    console.log(error);
}

function handleEnd() {
    results[replies] = running;
    running = '';
    replies++;
    if(replies === 3) {
        for(var i = 0; i < 3; i++) {
            console.log(totals[i]);
        }
    }
}

How can I get the callback to recognize which GET its response is a response to?
Note: the assignment specifically prohibits the use of 3rd party libs such as async or after.
Edit: another thing I tried (that also obviously failed), was inlining the callback definition for handleGet like so, to try and preserve the 'index' of the callback:
response.on('data', function(data) {
    results[i-2] += data;
});

On execution, this always indexes to results[3] because the async callbacks don't happen until after the for loop is already long done.  (Actually I'm not sure why the value of i is preserved at 5 at all, since the completed for loop would go out of scope, as I understand it... I would have thought it'd be undefined in retrospect.)

A: I will suggest using your second solution but passing the value of i and creating another function which encloses that variable. By this I mean the following:
(function(){
  var index = i;
  http.get(process.argv[i], function (response) {
        response.setEncoding('utf8');
        response.on('data', handleGetFrom(index));
        response.on('error', handleError);
        response.on('end', handleEnd);
    })
}());

and the handleGetFrom:
var handleGetFrom = function(i) {
    return function(data) {
     results[i-2] += data;
    }
}

Edited my original answer.

A: You can use the 'this' object:
var http = require('http');

http.get('http://www.google.com', function (response) {
    response.setEncoding('utf8');
    response.on('data', function(chunk) {
        console.log(this); // Holds the respons object
        console.log(this.headers.location); // Holds the request url
    });
});


text:
Q: android opengl set bitmap to sprite im trying to set a new bitmap to a sprite every 2 seconds. The code im using requires a GL10 object but can not be done in onDraw() because it reduces the framerate too much. I tried  setting a gl object to equal the one passed in onSurfaceCreated(), but it doesnt work. How can i do this?

A: Allocate all your textures in onSurfaceCreated(), create a Texture object (which contains a GL pointer for your texture) and assign that loaded texture (from OpenGL memory) to your Texture object's GL pointer id.
Later, in onDrawFrame(), just change glBindTexture(GL10.GL_TEXTURE_2D, textureObjectId) to glBindTexture(GL10.GL_TEXTURE_2D, anotherTextureObjectId).
This is how you change a texture without allocating during runtime using simple images/sprites.


text:
Q: MySQL and PHP Unexpected T_Variable Okay, so I have a register.php script written and I get an unexpected T Variable when the command tries to execute.
The error lies on line 15 at
('$_Post[username]','$_Post[sha_pass_hash]','$_Post[email]','2')";

I also have a second error in my syntax according to Dreamweaver at line 20 for
    die('Error: ' . mysql_error());

If anyone could help it would be greatly appreciated. Thank you in advance.

A: STOP
Inserting into a database directly from post is always a bad idea. This is the reason PHP is currently stuck with the very un-intuitive magic quotes.
You should at the very least be using mysql_real_escape_string() to escape your data. For example:
$link = mysql_connect('mysql_host', 'mysql_user', 'mysql_password')
OR die(mysql_error());

$query = "INSERT INTO users VALUES (
    '" . mysql_real_escape_string($_POST["username"]) . "',
    '" . mysql_real_escape_string($_POST["sha_pass_hash"]) . "',
    '" . mysql_real_escape_string($_POST["email"]) . "',
    '2'
)";

mysql_query($query);

The reason you have to do this is security based. For example if some malicious set the username field to '); DROP TABLE users; without first escaping your data. You would end up blindly running the following query:
INSERT INTO users VALUES (''); DROP TABLE users;

Which of course isn't going to end well for your application.
This is the minimum you should be doing.
In reality you should really be moving onto MySQLi Which is a much more modern MySQL interface.
Here is an example
$mysqli = new mysqli('mysql_host', 'mysql_user', 'mysql_password', 'mysql_database');

$query = "INSERT INTO users VALUES (
    '" . $mysqli->real_escape_string($_POST["username"]) . "',
    '" . $mysqli->real_escape_string($_POST["sha_pass_hash"]) . "',
    '" . $mysqli->real_escape_string($_POST["email"]) . "',
    '2'
)";

$mysqli->query($query);

You can even use MySQL in a procedural style. So if Object orientated programing isn't with in your reach yet you will have no problems with MySQLi.
Hope that helps.

A: ($_Post["username"],$_Post["sha_pass_hash"],$_Post["email"],'2')";

Remove the quotes..

A: ($_Post["username"],$_Post["sha_pass_hash"],$_Post["email"],'2')";

A: ($_POST["username"],$_POST["sha_pass_hash"],$_POST["email"],'2')";

Lose the single quotes around the variables :)

A: use this:
('".$_Post[username]."','".$_Post[sha_pass_hash]."','".$_Post[email]."','2')


text:
Q: React big calendar, render component when clicking on an event I would like to render a component next to an event when it is clicked to show more information. Something like this https://i.stack.imgur.com/jOVsE.png
I can use onSelectEvent to create a modal but I have no idea how to put the modal next to the event that was just clicked. I have looked into creating custom events with a popover contained within the event text but there seems to be no way to fire the click event from with in the event and I cannot work out how to do it from onSelectEvent.

A: import React from 'react';
import { Button, Popover, PopoverHeader, PopoverBody } from 'reactstrap';

export default class Example extends React.Component {
  constructor(props) {
    super(props);

    this.toggle = this.toggle.bind(this);
    this.state = {
      popoverOpen: false
    };
  }

  toggle() {
    this.setState({
      popoverOpen: !this.state.popoverOpen
    });
  }

  render() {
    return (
      <div>
        <Button id="Popover1" type="button">
          Launch Popover
        </Button>
        <Popover placement="bottom" isOpen={this.state.popoverOpen} target="Popover1" toggle={this.toggle}>
          <PopoverBody>/*Your date picker code goes here*/</PopoverBody>
        </Popover>
      </div>
    );
  }
}

Check for refrence (reactstrap)


text:
Q: JQuery Unobtrusive Validation Get Error with MVC For loop Hi I am trying to using  Unobtrusive Validation on my MVC application but got error.
Jquery files referenced
"~/Scripts/libs/jquery-1.9.1.js",
"~/Scripts/libs/jquery.browser.min.js",
"~/Scripts/libs/bootstrap.min.js",
"~/Scripts/libs/jquery.validate.min.js",
"~/Scripts/libs/jquery.validate.unobtrusive.min.js",
"~/Scripts/libs/jquery.unobtrusive-ajax.min.js",

ViewModel
public class UserGroupNameMappingViewModel
{
    public string GeneralName { set; get; }

    [Required(ErrorMessage = "This Field is required")]
    public string MappingName { set; get; }

    public UserGroupNameMappingViewModel() { }
}

Client Side Form
@model List<UserGroupNameMappingViewModel>

@using (Html.BeginForm()){

@Html.AntiForgeryToken()

        for (int i = 0; i < Model.Count(); i++)
        {

                @Html.DisplayFor(m => Model[i].GeneralName)
                @Html.ValidationMessageFor(m => Model[i].MappingName)
                @Html.HiddenFor(m => Model[i].GeneralName)
                @Html.LabelFor(m => Model[i].MappingName)
                @Html.TextBoxFor(m => Model[i].MappingName)

        }

        <button type="submit" class="btn btn-success">Update</button>
    }

Javascript Error I got(which thrown from Jquery.validate.unobtrusive.min.js)
Uncaught Error: Syntax error, unrecognized expression: label[for='[0].MappingName'], label[for='[0].MappingName'] *, #[0].MappingName-error

Please let me know your thoughts and Thanks!!

A: I think I found a solution,
for each
@Html.TextBoxFor(m => Model[i].MappingName)
I need give a good formatted id. for example
@Html.TextBoxFor(m => Model[i].MappingName, new{id = "Model_MappingName_"+ @i})


text:
Q: Flutter How I could setState when variable change? How I could setState when variable change?
I can't find a way to do this, and I'm a beginner in Flutter.
My code:
// i need to setState when width change
Container(
  width: MediaQuery.of(context).size.width - 40,

  child: Text(content,
  overflow: TextOverflow.clip,
    maxLines: 50,
  ),
)

A: you don't need do anything, flutter will automatically rebuild the widget when MediaQuery.of(context).size.width/height changes.


text:
Q: PHP: \r character being ignored I have a string $s="one\rtwo\rthree\rfour\rfive" and when I do print $s I expect to see five only because the linefeed resets the line.
Instead I seem to be seeing one  two  three  four   five.
What's going on?

A: If you want to rewrite a line in a console window (like it appears you are trying to do) you can do something like this:
#!/c/PHP/php-7.0/php.exe
    <?php
    for($i = 0; $i < 100; $i++){
        fwrite(STDOUT, "\r$i%");
    }
or if you want only the last portion of a string separated by Carriage returns you can do something like this:
$endVal = end(explode("\r", $s));
    print($endVal);


text:
Q: How does AppEngine(or its embedded-server) processes different urls I created a simple appengine project that accesses a restful webservice hosted in http://commerce.qa.mycomp.com (mycomp should be replaced with my actual company name).
I am using the Jersey Client to make the client request. I do a POST request to the above url.
When I run the application locally, it always returns 404 Not Found response. For experimenting, I did a POST request to http://www.bbc.co.uk/news/ and this works fine, and returns 200 as the status.
I just decoupled my app from appengine and ran it in the separately-configured tomcat server, and there it works fine and returns 200 status code. I think appengine uses Jetty as the server. Does Jetty have any bugs processing urls like commerce.qa.mycomp.com. Why I am asking this is urls that start with www.any.com seems to be working fine.
The two code snippets shown below is not working when run within appengine locally(not running even if I host it to appspot).
Client client = Client.create();
WebResource service = client.resource("http://commerce.qa.mycomp.com/rest");
ClientResponse response = service
    .header("Content-Type", "text/xml; Charset=utf-8")
.header("Authorization", "Basic dwt3hkl553lsfsfssf3")
.post(ClientResponse.class, "does not need to be actual xml");

URL url = new URL("http://commerce.qa.mycomp.com/rest");
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
conn.setDoOutput(true);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "text/xml; Charset=utf-8");
conn.addRequestProperty("Authorization", "Basic dwt3hkl553lsfsfssf3");
OutputStream os = conn.getOutputStream();
os.write("no need to be actual xml".getBytes());
os.flush();
System.out.println("Response Code: " + conn.getResponseCode());

But when run with tomcat, it just works.
My installations are:
Google App Engine Java SDK 1.6.1
Google Plugin for Eclipse 3.7
jersey-client-1.12, jersey-core-1.12, jersey-json-1.8
Please share thoughts.


text:
Q: Let $L = F(S)$ for $S \subseteq L$. Does there exists a transcendental basis $T \subseteq S$ with $F(S) = F(T)$? Let $L/F$ be a field extension with $L = F(S)$ for a subset $S \subseteq L$. My first question is:

*

*Is there a subset $T \subseteq S$ such that $T$ is a transcendental basis?

Now let's say we have $I \subseteq S$ such that $I$ is algebraic independent. My second question is then:

*

*Is there a subset $T$ with $I \subseteq T \subseteq S$ such that $T$ is a transcendental basis?


text:
Q: Imperatives with "more" and "less" I'm really confused about where to put the words "more" and "less" in an imperative sentence.
For example, in the imperative "Wash your hands more", MORE is written after the noun.
However, in "Eat less candy" we put LESS before the noun.
As far as I know, MORE and LESS are adverbs in this context, so should we always put them after the verbs?
I also wish to know if both "Do more exercise" and "Do exercise more" are grammatically correct?
Can you guys show me where to put MORE and LESS in imperatives?

A: In the examples you give, moving the adverb of "more" or "less" alters what word it is modifying. Compare:

Eat less candy
Eat candy less

Either of these are grammatically correct and convey different meanings.
In the first, less is more describing candy, saying that "you should eat a smaller amount of candy". This can either in general (eg. going from eating 5 candy bars a day to 2 candy bars a week), or in the specific event this statement would be said (eg. a group is sharing a bowl of candy and one person has taken half of the candy bars for themselves).
In the second, less feels like it is describing the phrase eat candy. It is a shorter way of saying "Eat candy less [often]". It more describes the amount of candy-eating times, as opposed the amount of candy eaten (i.e. going from eating 5 candy bars a day to 6 candy bars once a week). In this sense "eating candy" is being treated as an activity, and one that someone should do less often.

When making statements like these, it then becomes important to identify whether the action you want "less" or "more" of is more of a discrete activity or a continuous habit. In the case of "washing hand" compare:

Wash more [of your] hands
Wash your hand more

The first sense sounds strange, mostly because you only have as many hands as you have (usu. two). You can't wash more of your hands. This then has a meaning toward " wash further up your arm" or "wash for more time". Note, that if the intended meaning is to do a more thorough job of washing one's hands, then Wash your hands better would probably be used.
The second sense makes sense, as more is modifying "wash" and treating "wash your hands" as an activity. It is stating that one should wash their hands more often than they currently do (eg. twice a day to 5 times a day).

For the "do more exercise" (which doen't currently make sense)" here are some options with their nuance in parenthesis.

*

*Exercise more (exercise[verb] should be done more often or a longer period of time)

*Do more exercises (do more types of excercises[noun])

*Do the exercises more (do a specific set of exercises[noun] more often)

This again follows the same pattern (for simple commands) that when a modifier comes between a verb and its object, it modifies just the object (usu. in terms of degree). On the other hand if it comes after the object, typically the verb-object phrase is treated as an activity and the modifier describes how often.


text:
Q: Spatial resolution change after Extract by Mask in ArcGIS I have cell size (x, y)=(2.5, 2) spatial resolution of a raster file. When I use Extract by Mask function in ArcGIS then the resolution changes
I want to know why extact by mask function changes or makes the x and y components same by default. I have used the function for different products raster files. Every time the extract by mask function makes the resolution same from different (x, y) resolution.

A: I am afraid that it is not possible with ArcGIS desktop to generate output raster with rectangular cells (see here ). A workaround in your case could be to resample your raster at 0.5 m resolution with a nearest neighbour algorithm in order not to modify your input information (but this will multiply your uncompressed size by 6). Alternatively, you should target another application (e.g. gdal_calc.py or otbcli_BandMath.) that will not modify the size of your pixel (but then you need to resample your mask layer to 2.5/2m first, which might increase the area of NoData).


text:
Q: How to get derived interface without having a property/function that returns it (OLE/COM) I'm interfacing with a VB application using a C++ client code. I'm totally a novice in this (I'm just a Chemical Engineer), so please excuse me if the question is dumb.
So the following code in VB is required to access "BackDoor" interface, I can get all other interfaces because I follow the hierarchy (like  strm = hyApp.ActiveDocument.Flowsheet.Streams.Item(strmName)
But as you can see in below code, the BackDoor interface was equaled to ProcessStream interface!! I don't understand this and don't know how to implement in in C++... Could you please help?
Code in VB:
Function GetMassExergy(strmName As String) As Double

GetMassExergy = EmptyValue_enum.HEmpty 'initialize to empty

Dim strm As ProcessStream

Dim bd As BackDoor

Dim corrNamesVar As TextFlexVariable

Dim corrNames() As String

Dim i As Integer

Dim exergMoniker As String

Dim exerg As RealVariable

Dim Bval As Double

strm = hyApp.ActiveDocument.Flowsheet.Streams.Item(strmName)

bd = strm

corrNamesVar = bd.BackDoorTextVariable("HysysCorrelation.300.[]:Name.0").Variable

corrNames = corrNamesVar.Values

For i = 0 To corrNames.Count - 1

If corrNames(i) = "Mass Exergy" Then

Exit For

End If

Next i

If i = corrNames.Count Then

'failed to find Mass Exergy Correlation

Exit Function

End If

exergMoniker = String.Format("HysysCorrelation.300.{0}:ExtraData.550.0", i)

exerg = bd.BackDoorVariable(exergMoniker).Variable

Bval = exerg.GetValue("kJ/kg")

GetMassExergy = Bval

End Function

Code in C++ :
 void ConnectToHYSYS::GetBackDoor() {
//HyStream is already acquired using Hierarchy
IDispatch* hyStream;
// Try to Query BackDoor from hyCase interface
    HRESULT hr = hyStream->QueryInterface(__uuidof(hyBackDoor), (void**)&hyBackDoorDisp);

//Last hr returns S_OK
    if (SUCCEEDED(hr))
    {
        cout << "Got the BackDoor safely" << endl;
        //Get BackDoor Text Variable,

            VARIANT result;
            VariantInit(&result);
// Try to Get a property from BackDoor interface (to make sure that it returned //an actual interface)
            hr = COMMethod(DISPATCH_PROPERTYGET, &result, hyBackDoorDisp, L"BackDoorTextVariable", 1, "HysysCorrelation.300.[]:Name.0");
            CheckForHr(hr);
            BackDoorTextVariable = result.pdispVal;
            if (SUCCEEDED(hr))
            {
                cout << "Got the BackDoor Text Variable safely" << endl;

            }

            if (FAILED(hr)) {
                cout << "Couldnt get the BackDoor Text Variable" << endl;

            }
    }

        if (FAILED(hr)) {
            cout << "Couldnt get the BackDoor" << endl;
        }

}

The following is COMMethod that I use to access properties inside interfaces (it works properly with all other interfaces)
    HRESULT ConnectToHYSYS::COMMethod(int nType, VARIANT * pvResult, IDispatch * pDisp, LPOLESTR ptName, int cArgs...)
{
    if (!pDisp) return E_FAIL;

    va_list marker;
    va_start(marker, cArgs);

    DISPPARAMS dp = { NULL, NULL, 0, 0 };
    DISPID dispidNamed = DISPID_PROPERTYPUT;
    DISPID dispID;
    char szName[200];

    // Convert down to ANSI
    WideCharToMultiByte(CP_ACP, 0, ptName, -1, szName, 256, NULL, NULL);

    // Get DISPID for name passed...
    HRESULT hr = pDisp->GetIDsOfNames(IID_NULL, &ptName, 1, LOCALE_USER_DEFAULT, &dispID);
    if (FAILED(hr)) {
        return hr;
    }
    // Allocate memory for arguments...
    VARIANT * pArgs = new VARIANT[cArgs + 1];
    // Extract arguments...
    for (int i = 0; i < cArgs; i++) {
        pArgs[i] = va_arg(marker, VARIANT);
    }

    // Build DISPPARAMS
    dp.cArgs = cArgs;
    dp.rgvarg = pArgs;

    // Handle special-case for property-puts!
    if (nType & DISPATCH_PROPERTYPUT) {
        dp.cNamedArgs = 1;
        dp.rgdispidNamedArgs = &dispidNamed;
    }

    // Make the call!
    hr = pDisp->Invoke(dispID, IID_NULL, LOCALE_SYSTEM_DEFAULT, nType, &dp, pvResult, NULL, NULL);
    if (FAILED(hr)) {
        return hr;
    }

    // End variable-argument section...
    va_end(marker);
    delete[] pArgs;
    return hr;
}

The line where I make the call is the only one that returns an error "0x80020008 Bad variable type"... I mean last hr line I wrote in COMMethod "hr = pDisp->Invoke(dispID, IID_NULL, LOCALE_SYSTEM_DEFAULT, nType, &dp, pvResult, NULL, NULL);"

A: The VB code that you have is using early binding, and the C++ code that you have is using late binding.
Switch your C++ code to something similar to your VB code, e.g:
void ConnectToHYSYS::GetBackDoor() {
    IDispatch* hyStream = ...;

    // Use an actual hyBackDoor
    hyBackDoor* hyBackDoorDisp;
    HRESULT hr = hyStream->QueryInterface(IID_PPV_ARGS(&hyBackDoorDisp));

    if (SUCCEEDED(hr)) {
        cout << "Got the BackDoor safely" << endl;

        // From the VB code, it seems BackDoorTextVariable is a TextFlexVariable
        hr = hyBackDoorDisp->get_BackDoorTextVariable(&BackDoorTextVariable);

        CheckForHr(hr);
        if (SUCCEEDED(hr)) {
            cout << "Got the BackDoor Text Variable safely" << endl;
        }

        if (FAILED(hr)) {
            cout << "Couldnt get the BackDoor Text Variable" << endl;
        }
    }

    if (FAILED(hr)) {
        cout << "Couldnt get the BackDoor" << endl;
    }
}

The reason that the dispatch object you get doesn't work is that usually only the first interface is handled by standard dispatchers.  Even for custom or manual dispatchers that handle multiple interfaces, usually they don't dispatch hidden (or otherwise for private use) interfaces.

A: Both Mr. Igor and Mr. Acelent answers were successful (Sorry don't know how to accept a comment as an answer from Mr. Igor so I will just copy it here and accept it as an answer for anyone else facing the same problem.
pArgs[i] = va_arg(marker, VARIANT); This exhibits undefined behavior, as the actual argument you pass to COMMethod is not in fact a VARIANT: COMMethod(..., 1, "HysysCorrelation.300.[]:Name.0"); – Igor Tandetnik
Thank you everyone..


text:
Q: Как мне правильно разделить товар на женский и мужской? Есть две большие категории (Женские и Мужские товары)
До этого у меня не было этого разделения (товар просто делился на кат.), сейчас появилась такая потребность
Что именно мне нужно изменить в моем коде, чтобы товар разделялся на женский и мужской и при клике например на женскую категорию товар разделялся и в самих категориях только для женщин  ?
models.py
class Category(models.Model):
  name = models.CharField(max_length=200, db_index=True, verbose_name='Название')
  slug = models.SlugField(max_length=200, unique=True)

  class Meta:
    ordering = ('name',)
    verbose_name = 'категория'
    verbose_name_plural = 'категории'

  def __str__(self):
    return self.name

  def get_absolute_url(self):
    return reverse('shop:product_list_by_category', args=[self.slug])

class Product(models.Model):
  category = models.ForeignKey(Category, related_name='products', on_delete=models.CASCADE,
  verbose_name='Категория')
  gender = models.CharField(max_length=15, choices=[('Ж', 'Женская'), ('М', 'Мужская'), ('У',
 'Унисекс'), (None, 'Выберите принадлежность')], verbose_name='Принадлежность', blank=False,
  null=True)
  name = models.CharField(max_length=200, db_index=True, verbose_name='Название')
  slug = models.SlugField(max_length=200, db_index=True)
  image = models.ImageField(upload_to='products/%Y/%m/%d', blank=True, verbose_name='Фото')
  image_2 = models.ImageField(upload_to='products/%Y/%m/%d', blank=True, verbose_name='Фото №2')
  image_3 = models.ImageField(upload_to='products/%Y/%m/%d', blank=True, verbose_name='Фото №3')
  image_4 = models.ImageField(upload_to='products/%Y/%m/%d', blank=True, verbose_name='Фото №4')
  description = models.TextField(blank=True, verbose_name='Описание')
  price = models.DecimalField(max_digits=10, decimal_places=2, verbose_name='Цена')
  available = models.BooleanField(default=True, verbose_name='Наличие')
  created = models.DateTimeField(auto_now_add=True, verbose_name='Создан')
  updated = models.DateTimeField(auto_now=True, verbose_name='Обновлен')

  class Meta:
    ordering = ('name',)
    index_together = (('id', 'slug'),)
    verbose_name_plural = 'Продукты'

  def __str__(self):
    return self.name

  def get_absolute_url(self):
    return reverse('shop:product_detail', args=[self.id, self.slug])

views.py
def product_list(request, category_slug=None):
  categories = Category.objects.all()
  products = Product.objects.filter(available=True)

  if category_slug:
    category = get_object_or_404(Category, slug=category_slug)
    products = products.filter(category=category)
  else:
    category = None

  sort_form = SortForm(request.POST or {'sort_form': request.session.get("need_sort")})
  if request.POST:
    if sort_form.is_valid():
        request.session["need_sort"] = sort_form.cleaned_data.get("sort_form")
  need_sort = request.session.get("need_sort")
  if need_sort == 'ПУ':
    products = products.order_by('name')
  elif need_sort == 'ДТ':
    products = products.order_by('-created')
  elif need_sort == "ДЕД":
    products = products.order_by("price")
  elif need_sort == "ДОД":
    products = products.order_by("-price")

pages = Paginator(products, 18)
page_number = request.GET.get('page')
page_object = pages.get_page(page_number)

context = {'category': category, 'categories': categories, 'products': products, 'page_object':
page_object, 'sort_form': sort_form}
return render(request, 'shop/product_list.html', context)

A: Весь код писать не буду, покажу не примере категорий. Рекомендую использовать mptt.
class Category(MPTTModel):
        """Определяем категории для товара"""
        name = models.CharField(max_length=70, unique=True, verbose_name='Подкатегория')
        slug = models.CharField(max_length=100, unique='title', verbose_name='url')
        objects = models.Manager()
        parent = TreeForeignKey('self', on_delete=models.CASCADE, null=True, blank=True, related_name='children',
                                verbose_name='Главная категория')

        class Meta:
            ordering = ('tree_id','name')

        def get_absolute_url(self):
            if self.parent:
                return reverse('shop:category_url_with_subcat', args=[self.parent.slug, self.slug])
            else:
                return reverse('shop:category_url', args=[self.slug])

        def __str__(self):
            return self.name

    mptt.register(Category, order_insertion_by=['title'])

В модели Product лучше использовать TreeManyToManyField вместо models.ForeignKey, например, если это магазин обуви, то товар может относиться к нескольким категориям (например, обувь может быть женская, зимняя). Надеюсь суть ясна


text:
Q: Why does Jython not enforce the interface requirements of a Java Interface In Java, I am used to compiler errors when failing to implement all the required methods of an interface.  I was surprised when I made an Object in Jython that did not implement all the required methods (getRowCount, getColumnCount, getValueAt) of the javax.Swing.AbstractTableModel which implements the interface TableModel.  From the Javadocs of AbstractTableModel:

To create a concrete TableModel as a subclass of AbstractTableModel you need only provide implementations for the following three methods:

Jython class that should fail:
class ResourceTableModel(AbstractTableModel):
    COLUMN_NAMES = ('path','filename','parametername', 'parametervalue')
    def __init__(self, *rows):
        self.data = list(rows)
    def getRowCount(self):
        return len(self.data)
    def getColumnCount(self):
        return len(self.COLUMN_NAMES)

Testing the above:
 def test_column_count(self):
        e = mySwingGUI.ResourceTableModel()
        column_count = e.getColumnCount()
        self.assertEqual(column_count,4)

Then I read that you can use isinstance() to see if an object is an instance of a specific interface.
so I tried this:
 def test_column_count(self):
        e = mySwingGUI.ResourceTableModel()
        if isinstance(e,javax.swing.table.AbstractTableModel):
            print("true")
        else:
            print("false")
        column_count = e.getColumnCount()
        self.assertEqual(column_count,4)

but it prints true even though I have not implemented all the methods.  Is there a way to make Jython enforce interface contracts or is this only enforced by the Java compiler?


text:
Q: I can't update image in BLOB mysqli php I can't update image in BLOB mysqli php.
CODE:
<?php

    // connect to the database
    include('connect-db.php');
    if (isset($_POST['submit']))
    {
    // confirm that the 'id' variable has been set
    if (isset($_GET['id']) && is_numeric($_GET['id']))
    {
        // get the 'id' variable from the URL
        $id = $_GET['id'];
$file=$_POST['image'];
$file = mysql_real_escape_string($file);

    if ($stmt = $mysqli->prepare("UPDATE studentdata SET image= ?
                        WHERE id=?"))
    {
        $stmt->bind_param("bi", $file, $id);
        $stmt->execute();
        $stmt->close();
    }
        else
        {
            echo "ERROR: could not prepare SQL statement.";
        }
        $mysqli->close();

        // redirect user after delete is successful
        header("Location: loginsuccess_student.php");
    }

}

?>

A: If the image file is uploaded using input type='file' name='image' ( using enctype="multipart/form-data" form) try this:
$id = (int) $_GET[ "id" ];
$image = $_FILES[ "image" ][ "tmp_name" ];
$mysqli->query( "UPDATE `studentdata` SET `image` = LOAD_FILE( '$image' ) WHERE id = '$id' ");

If the image file is just a link (public path) you don't need a BLOB at all, a VARCHAR(256) is enough and you can use your example with file input source as :
$file = $_POST[ "image" ];


text:
Q: List of object access in Professional Edition I have Professional Edition.
I have installed one App and I have one VF page which has one picklist with a list of
Contact, Account, Opportunity and Lead out of these I am able to access only Contact none of the rest.
This works fine in developer org.
So can I have list of Objects accessibility in Professional Edition ? or There is there some other issue ?

A: You should have access to Contacts, Accounts, Opportunities and Leads in PE.
You can watch a video on the key features (which cover most of these) here,
and the "feature" breakdown comparison can be read here - I can't actually seem to get my hands on a specific list of object access!!
I would suspect the problem you are seeing is connected to security or app settings instead?


text:
Q: CakePHP how to set conditions on contain table I have 2 tables, Drivers and Cars. The Drivers table hasMany association with cars. I created a controller called SearchController. In search controller I load the Driver model using $this->loadModel('Drivers');
When I enter a search, I want it to only return cars that are automatic and the drivers details but it is returning all values including cars which are not automatic.
$drivers = $this->paginate($this->Drivers, [
        'contain' => ['Cars']], [
        'conditions' => ['Cars.transmission' => 'Automatic'] ] );

 $this->set(compact('drivers'));
 $this->set('_serialize', ['drivers']);

Your help would be highly appreciated.
---EDIT----
The statement I want to achieve is :
SELECT * FROM drivers, cars
         WHERE drivers.id = cars.driver_id
         AND cars.transmission = 'Automatic'

A: You should write your contain like this:
'contain' => [
    'Cars' => function($query){
        return $query->where(['transmission' => 'Automatic']);
    }
]

For more options, please refer to CakePHP cookbook: Passing Conditions to Contain
EDIT:
To select only Drivers that have Cars with "Automatic" transmission, and to select list of those cars for each driver, you need to join these two tables together. Result code should look like this:
$query = $this->Drivers->find()
            ->matching("Cars", function($q){
                return $q->where(["Cars.transmission" => "Automatic"]);
            })
            ->contain([
                "Cars" => function ($q) {
                    return $q->where(["transmission" => "Automatic"]);
                }
            ]);

$result = $this->paginate($query);

matching() used here will join tables drivers and cars, and set condition accordingly. contain() part of query is still the same.
For more options, please visit these docs:
Pagination
Retrieving Data & Results Sets

A: Additional associations can be loaded to the paginated table by using the contain parameter:
$this->paginate['contain'] = [
    'Cars' => function (\Cake\ORM\Query $query) {
        return $query->where(['Cars.transmission' => 'Automatic']);
    }
];

$drivers = $this->paginate($this->Drivers);

$this->set(compact('drivers'));
$this->set('_serialize', ['drivers']);

See also

*

*Joining Additional Associations


text:
Q: Example of 'a subroutine may have several entry and exit points' I'm reading the paper of Non structured programming, and found it says:

Unlike a procedure, a subroutine may have several entry and exit points, and a direct jump into or out of subroutine is (theoretically) allowed

I can't understand it, could anyone give me an code sample of:

*

*a subroutine may have several entry and exit points

*a direct jump into or out of subroutine

Thanks

A: 10 A = 1
20 GOSUB 100
30 A = 2
40 GOSUB 110
50 A = 3
60 GOTO 130
70 END

100 PRINT A
110 PRINT "HELLO"
120 IF A = 1 THEN RETURN
130 PRINT "THERE"
140 IF A = 3 THEN GOTO 70
150 RETURN

The subroutine has three entry points (lines 100, 110, and 130) and three exit points (lines 120, 140, and 150). There is a direct jump into line 130 (from line 60) and a direct jump out (at line 140).


text:
Q: Xubuntu 13.04 CCC requires reboot? CCC requires a reboot every time i enable or disable a screen. since i do it at least 8 times a day, this isn't acceptable for me. How do i get around this issue?!
I'm running the official AMD Catalyst™ 13.4 driver and I'm using sudo amdcccle to start CCC. The system is amd64.


text:
Q: Считывание данных из файла и занесение их в структуру Задание: Считать данные из файла, занести их в структуру и вывести в консоль.
Структура данных в файле: ABLEC&C,Missha,350.00,100,10.02.2017,South Korea;
Не удается считать данные и занести их в динамический массив структур.
Подскажите, пожалуйста, как можно исправить?
Код:
#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include <fstream>
#include <cstring>

using namespace std;

struct Goods {
    char company[40];
    char name[40];
    char country[50];
    double price;
    int amount;
    struct {
        int day;
        int month;
        int year;
    } date;
};

int main() {
    fstream file("goods.txt", ios::in);
    if (file.is_open()) {
        // находим количество записей о товарах в файле
        int records = 0;
        char stop;
        for (file >> stop; !file.eof(); file >> stop)
            if (stop == ';') records++;

        // считываем структуру в файле и выводим в консоль
        Goods* goods = new Goods[records];
        char* token;
        char line[256];
        for (int i = 0; i < records; i++) {
            cout << "Product " << i + 1 << endl;
            file.getline(line, 256, ';');
            token = strtok(line, ",");
            strcpy(goods[i].company, token);
            cout << "Company: " << goods[i].company << endl;
        }
    }
    else cerr << "Error with opening file." << endl;
    file.close();
}

A: После считывания количества данных, нужно закрыть и открыть файл заново. И снова считать данные или просто вернуться в начало с помощью seek.


text:
Q: CakePHP 2.0 inner join and create view I'm new in Cakephp 2.0, but I want to make a view of two tables with Inner Join.
I have the following tables tables:
hpsas with records: id, ciname, location, status
ldaps with records: id, ciname, status
The query I would do in MySQL is:
SELECT * FROM hpsas INNER JOIN ldaps ON hpsas.ciname = ldaps.ciname;

Which syntax do I have to use in whether the models, the controller or the view.

A: $options['joins'] = array(
    array('table' => 'ldaps',
        'type' => 'inner',
        'conditions' => array(
            'hpsas.ciname = ldaps.ciname',
        )
    )
);

$this->Hpsa->find('all', $options);

See Cake book section on associations for more details: http://book.cakephp.org/2.0/en/models/associations-linking-models-together.html#joining-tables

A: follow the activeRecord model i think you should define a relationship in the model to avoid running complex queries everytime you need records from this models. you will need to stick to cake's conventions tho and that means you will have 3 models(most possibly)
class cinema extends AppModel{

    hasMany = array(hpsas,idaps);
}
class hpsas extends AppModel{

     belongsTo = array(cinema)
}
class idap extends AppModel{
 belongsTo = array(cinema)
}

with recursive set at above 2 or three one simple query to any one of the models will give you all the data you want(cake magic).


text:
Q: Blender + SceneKit (how-to) A few questions to game developers. I am very beginner in this. I want to create a game level for example a green plane with trees. I have played a little in Blender and SceneKit. I know that I can export .dae from Blender and import it to Xcode. My questions:

*

*Should I delete camera and light node before export? Why?

*Should I design all level in one .dea file or make it separately? For example one .dea for plane and four different trees in for .dea's How to merge them in Xcode?

*Can I use many times one .dea to generate for example a forest? How?

*If creating design in separately is better way how to keep proportions between them to protect yourself from creation man bigger than tree?

I will be very great full if somebody someone dedicates to these questions. It will cut my time to learn basic. Thanks in advance. :)

A: I'll tell you how I do it:
1) .dea files use only for models(trees, charecters, building, etc...)
2) Game scene: floor, models, light, camera, obstacles build using Xcode scene builder or by code or mixed (based on the scene).
3) Based on size of world/level it can be split into several scenes(visible/invisible by player). Then you can create one blank scene and load/unload these scenes during runtime.
4) For a model you create a reference and after that build forest using reference of tree. If in the future you need to change the color of tree, all trees in all scenes will be updated.
5) For each model(SCNNode) (loaded from .dea file) you can set scale attribute (from code or by Xcode scene builder)
Also, 3D Apple Games by Tutorials is very good for starting.


text:
Q: Template Literals are not adding value together I think I am running into a Template Literal issue. I am trying to get some values, add them together to make a new value and then apply it to the target element. But when I add them together, no value is returned.
const el = document.querySelector('.row[data-target="row-offset"]');
const distanceFromLeft = el.offsetLeft;
const paddingLeft = window.getComputedStyle(el, null).getPropertyValue('padding-left');
const target = document.querySelector('#hero-carousel .flickity-page-dots');

target.style.left = `${distanceFromLeft + paddingLeft}px`;

I have alerted out the querySelector elements and thus know I am targeting them correctly. Console logging both distanceFromLeft and paddingLeft results in values being outputted.
Therefore I am left thinking there is something wrong with my Template Literal. No errors are being reported.
I have mocked up the issues here
The expected result is for target to have the same value as el.

A: That's because the window.getComputedStyle(el, null).getPropertyValue("padding-left") will output the value with px for example 16px, so you need to get the value as a number with parseFloat() method.
const paddingLeft = parseFloat(window
  .getComputedStyle(el, null)
  .getPropertyValue("padding-left"));

const el = document.querySelector('.row[data-target="row-offset"]');
const distanceFromLeft = el.offsetLeft;
const paddingLeft = parseFloat(window
  .getComputedStyle(el, null)
  .getPropertyValue("padding-left"));
const target = document.querySelector("#hero-carousel .flickity-page-dots");

target.style.left = `${distanceFromLeft + paddingLeft}px`;

// if (target) {
//   alert("Element exists");
// } else {
//   alert("Element does not exist");
// }
console.log(distanceFromLeft);
console.log(paddingLeft);
body {
  font-family: sans-serif;
  position: relative;
}

.row {
  display: block;
  background-color: pink;
  width: 90%;
  height: 100px;
  margin: 0 auto;
}

.flickity-page-dots {
  display: block;
  background-color: blue;
  width: 20%;
  position: absolute;
  left: 0;
  height: 100px;
}
<!DOCTYPE html>

    <title>Parcel Sandbox</title>
    <meta charset="UTF-8" />
    <link rel="stylesheet" href="src/styles.css" type="text/css" />


text:
Q: Basic Python While loop compound conditional evaluation In Python IDLE Shell it seems I cannot use a compound conditional expression and a while loop. I tried it within brackets too. Take these two examples:
k=0
m=0
while k<10 & m<10:
    print k
    k +=1
    m+=1

This doesn't evaluate the second condition. But if I write
 while k<10:
    print k
    k+=1

This does work. Is there a way I could achieve the first block of code with the "and" operator. I have done it in Java. Do I just need to put together "if" statements to achieve the same functionality in Python?

A: & should be and. & is the bitwise AND operator.


text:
Q: Map :w (save) and a call for a .sh file to F2 in VIM I'd like to map F2 in VIM so that it first saves the file with :w and then calls a script /home/user/proj/script.sh that will upload the changed files to the server.
I already tried
:map F2 :w<cr>|:! /home/user/proj/script.sh

but that doesn't work.
Please tell my why this isn't working and help me to get this working.

A: Try :noremap <F2> :<c-u>update <bar> !/home/user/proj/script.sh<cr>.
noremap vs. map
This creates a non-recursive mapping. See Wikia - Mappings keys in Vim
I just assumed this, because it's what people want most of the time. :-)
update vs. write
Only save the file if there were actual changes. See: :help :update.
<bar> vs. |
:help map_bar
<c-u>?
You used a generic mapping, instead of one for a certain mode, like nmap for normal mode mappings. Thus the mapping could also be triggered in visual mode. If you select something in visual mode and hit :, you'll see the commandline is prefixed with a range. But you don't want that in your case and <c-u> clears the commandline.
<cr> at the end?
Your mapping drops into the commandline mode and inserts 2 things separated by <bar>. Afterwards it has to execute what it has written, thus you need to append a <cr>.


text:
Q: Kendo UI , AutoComplete Max capacity is 1000. I want to increase this Hello Kendo UI users,
I came across a strange problem, where the CAPACITY of AUTOCOMPLETE is only upto 1000.
How do I increase it? because I need it for over 3000 values.
I checked for autocomplete function in kendo.all.min.js, with no success.
Any Help ?
Here is my code
var DS = new kendo.data.DataSource({
             type: "odata",
                    transport: {
                    read: {
                        url: "http://domain/news/_vti_bin/listdata.svc/translatorList/",
                        dataType: "json"
                        }
                   }
            });
 $("#translator").kendoAutoComplete({
                dataTextField: "Deutsch",
                dataSource: DS,
                  change: function(e) {
                    var value = this.value();
                    $.getJSON("http://Domain/news/_vti_bin/listdata.svc/WZlist?$filter=startswith(Deutsch,'" + value + "')",function(d){
                        $('#res').val(d.d.results[0].Englisch);
                    });
                  }
              });

A: You should use Server Filtering, as defined here:
http://demos.kendoui.com/web/autocomplete/serverfiltering.html
This will allow you to do any filtering you need server side and return a minimal number of rows to the client.
Even the limit of 1,000 for client-side filtering is a bit much, in my opinion!

A: Try to set pageSize:
$(document).ready(function(){
 $("#autoComplete").kendoAutoComplete({
  minLength: 3,
  dataTextField: "Name", // JSON property name to use
  dataSource: new kendo.data.DataSource({
   type: "odata", // specifies data protocol
   pageSize: 3000, // limits result set
   transport: {
    read: "http://odata.netflix.com/Catalog/Titles"
   }
  })
 })
});


text:
Q: Get points which are within a given distance in two different matrices I have two matrices A and B, in which the number of rows can vary. A and B do not necessarily have the same number of rows.
For example:
A = [ 110    90
      130   140
      230    50
      370   210 ];
B = [ 321    95
      102    35
      303   200 ];

Now matrix A and B have 'corresponding points'. Corresponding points are rows where the values in the 2nd column of both matrices are within +/-20.
For example:

*

*A(1,2) = 90 and B(1,2) = 95, the difference is within +/-20 so A(1,:) and B(1,:) are corresponding points.

*A(2,2) = 140 and B(2,2) = 35, the difference is not within +/-20 so A(2,:) and B(2,:) are not corresponding points.

*A(3,2) = 50 and B(2,2) = 35, the difference is within +/-20 so A(3,:) and B(2,:) are corresponding points.

Using this I want to store the corresponding points of A and B in C and D respectively. For the above example, the final matrices should look like this:
C = [ 110    90
      230    50
      370   210 ]
D = [ 321    95
      102    35
      303   200 ]

A: You can get all of the distances using pdist2
dists = pdist2( A(:,2), B(:,2) )
>> dists = [  5    55   110
             45   105    60
             45    15   150
            115   175    10 ]

Then get the indices of all 'corresponding points', as defined by a threshold of 20.
% Get combinations within tolerance
idx = dists < 20;
% Get indices
[iA, iB] = find(idx);

Then you can create the final matrices
C = A(iA, :);
D = B(iB, :);

Edit: One way to ensure each pairing is unique (i.e. A(1,:) cannot be paired with multiple rows from B) would be to get the minimum dists for each row/column. Note: this would still give you duplicate matches if the distances are exactly the same, you haven't defined how this should be handled.
dists = pdist2( A(:,2), B(:,2) );
% Set values which are greater than the row/column minima to be infinity.
% This means they will never be within the tolerance of 20 (or whatever else)
dists ( bsxfun(@gt, dists, min(dists,[],1)) | bsxfun(@gt, dists, min(dists,[],2)) ) = Inf;
% In MATLAB versions > 2016b, you can use implicit expansion to replace bsxfun
% That would be: dists( dists > min(dists,[],1) | dists > min(dists,[],2) )

% Now continue as before
[iA, iB] = find( dists < 20 );
C = A(iA, :);
D = B(iB, :);


text:
Q: How to retrieve the minimum date having 3 columns (day), (month) and (year) with RSQLite? I am working with SQL in R. I want to get the minimum date by choosing the minimum value of the column 'day;, the minimum value of the column 'month' and the minimum value of the column 'year'.
I have tried this by the following code:
dbGetQuery(db, "SELECT day, month, year
                FROM surveys
                WHERE year = (SELECT MIN(year) FROM surveys);")

But my output is not one value, how can I get one value in my output and not a list of values?

A: Using the test data shown we order it by year, month and day and select the first row of the sorted table.
library(sqldf)
surveys <- data.frame(year = 2001:2005, month = 5:1, day = 1:5)

sqldf("select day, month, year from surveys order by year, month, day limit 1")
##   day month year
## 1   1     5 2001

A: Right now your query returns rows on the minimum year, not minimum date. Consider generating a date column by concatenating the date parts to identify minimum:
sql = "WITH sub AS (
          SELECT day, month, year
                , DATE(year || '-' ||
                       CASE
                          WHEN length(month)=1
                          THEN '0' || month
                          ELSE month
                       END  || '-' ||
                       CASE
                          WHEN length(day)=1
                          THEN '0' || day
                          ELSE day
                       END) AS [date]
          FROM surveys
      )

      SELECT DISTINCT day, month, year, [date]
      FROM sub
      WHERE [date] = (SELECT MIN([date]) FROM sub)"

dbGetQuery(db, sql)

Online Demo


text:
Q: Losing numeric table precision during shapefile export in ArcGIS Pro I'm trying to export a GDB file version 10.5 in ArcGIS Pro 2.0.0 to a shapefile, but every time I do, I lose precision with the unique feature IDs. For example the IDs will go from 554423216 --> 554423210.000
This taints the data b/c now each feature does not have a unique ID, plus I can't accurately join attribute tables.
Why does this happen?