Cut off long tail of distribution (no matter how long is the tail)

Question: One of the algorithms that we are working on is designed to report the time it takes for people to finish the onboarding process in an app.
We need an algorithm to eliminate the long tail of a distribution in a way in which it doesn't matter how long the tail is. Basically we want to identify the main body of the distribution on how much time it takes for users to finish the onboarding process.
We want to report "p% of users onboard within X time" where p should be determined by cutting the long tail of the distribution. The tail has variable length.

The characteristic curve could be a log-normal distribution if we consider data from the maximum value, or a power law distribution.
Considering this, how would you suggest finding the cut-off point of the long tail ? We are excluding Pareto principle, or other predetermined percentage (75%, 90%, etc).
In the uploaded photo, you can see the blue bar. Let's suppose that is the point that we are to find. The problem with the current algorithm is that when we select another period of analysis for the same client for the same report, that blue point shifts significantly to the right or left according to the length of tail.
One solution that we have is to determine the power law trendline of the raw data (pink line) and to calculate the tangent slope in each point of it and to set a threshold - the value where the slope is significantly flat -  after which we can consider the start of the long tail.
Running numerous tests, the upper method seem to resolve the shifting problem. Would you consider this a valid approach? Do you see any potential problems with it?
Comment: Neither model you mention, power law or lognormal, implies that a cut-off makes sense at all. I don't find here a clear discussion of why you want or need this at all.
Comment: @PeterFlom-ReinstateMonica, that's correct. To solve this, we need to decide what is the threshold of the slope where we can consider it "flat enough"
Comment: @NickCox we are interested in analyzing the head of the distribution separately from the tail and we need to automate the process of identifying the data of the head. The further back we look in the data, the longer the tail (more outliers that take much longer to finish the process). The length of the tail should not impact how the head is selected. How would you recommend we address this?
Comment: Sure, but if the head can't be distinguished systematically from the tail, the question can't be answered. I would look systematically at the survivor (survival, reverse or complementary distribution) function on double logarithmic scale. if you don't see systematic, identifiable breaks in that you're searching for something that doesn't exist.
Comment: @NickCox, thank you! It is a useful start for research.
Comment: I agree with @NickCox that this question has no real answer in a lot of cases.  In the method you outline, you just push the problem back to figuring out what "significantly flat" means.
Answer:
We want to report "p% of users onboard within X time" where p should be determined by cutting the long tail of the distribution. The tail has variable length.
[...]
Considering this, how would you suggest finding the cut-off point of the long tail ? We are excluding Pareto principle, or other predetermined percentage (75%, 90%, etc).

Approach a)
You may report a fixed value of $p$ so that you can compare data over time. To me, a value of $90\%$ or $95\%$ seems adequate.
Note that what, in this case, you are reporting a quantile of the time. More specifically, if you choose $p=90\%$, you will be reporting the $90\%$ percentile of the time.
Approach b)
Alternatively, you may choose a "reasonable" time, like a "round" number, and find the percentage of individuals that are "on board" in a time as large as that.
Approach c)
Nevertheless, if you really want to determine a cut-off in an "automatic" way, you may be interested in looking at kernel density estimation. A possible cut-off could be determined by the time $X$ such that the derivative of the probability density is lower than a small value for all times larger than $X$. However, you still have a problem in choosing that small value: will it be fixed or a fraction of the maximum density?
Examples of made up sentences:
Approach a) $95\%$ of users onboard within $9.74$ minutes.
Approach b) $94.7\%$ of users onboard within $10$ minutes.
Approach c) $94.8\%$ of users onboard within $9.84$ minutes.
In my opinion, the first two approaches will give you values that are easier to understand by the general public (and I prefer slightly the second approach).


6-Core Xeon VS Opteron for virtualization

Question: Which processor gives better price/performance for virtualization environment?
Comment: **We need more details to give a good answer**. What hypervisor are you using? What kind of workload? If you have a pricing deal with one reseller or manufacturer that will effect the price...
Answer: I would recommend dual Nehalem Xeons (w/ 8MB L3 cache, list) as the optimum price/performance chips for VMWare ESXi virtualization right now - they're old enough to be cheap but still powerful enough to run lots of big VMs. Generally you won't run into performance problems with CPUs though, you'd be better off spending the cash you save on 32+ GBs of RAM.
(caveat: this is obviously subjective and dependant on application)
Comment: I'm upvoting this one for the part that says you'd be better off worrying about more RAM.
Comment: +1 for comment on more RAM
Answer: This can't be answered as prices are relative based on who's buying.
It also depends on whether your hypervisor of choice can deal with hyperthreading well.
Comment: Also depends on the workload of the VMs. Some programs run faster on each of the given processors.


Unique field value for all nodes and content types

Question: I have list integer field in 3 content types and each have same possible values (from 1 to 6) and I need to disable user to choose the same number for two nodes, so each node with this field filled in need to be unique.
I found Unique field module but it is not working for me, because I have field in each content type and I need to look at all nodes from all content types and this module is on content type base.
Basic example of what I need:
Field field_1 from content type type_1 have value 5, so field_2 from content type type_2 and field_3 from content type type_3 can't have value 5.
Any idea how to achieve this?
Comment: If you have 6 possible values shared between 3 content types that's a total of 6 nodes total.. Could you explain why you are doing this because it doesn't make much sense to me. If you wanted to go down your route you can hook into the validation/node creation (sorry cant remember off top) events and query the DB for all nodes on your content types and loop through them and check if it already exists. if exists then throw error, if doesn't proceed with node creation.
Comment: Are field_1 field_2 and field_3 the same fields used in 3 content types? You could try to use EntityFieldQuery each time a node is updated in a custom validation handler and check if there are other nodes with the same field value. If there are many nodes to compare consider caching.
Answer: Check out this example
<code>function custom_node_validate($node, $form) {
  if ($node->type == 'page') {
    //retrieve the value for your field using Entity API
    $wrapper = entity_metadata_wrapper('node', $node);
    $value = $wrapper->field_collection->field_unique->value();

    //Execute a count query to see if there's other similar values.
    $query = new EntityFieldQuery;
    $query->entityCondition('entity_type', 'field_collection_item')
      ->fieldCondition('field_unique', 'value', $value)
      ->count();
    $count = $query->execute();
    if ($count > 1) {
      form_set_error('field_unique', 'Unique field value is already used.');
    }
  }
}
</code>


Coefficients of a polynomial

Question: Consider the polynomial $$ P_n(t)=(-1)^n (2t-1) \frac{(2t-1)^{n-1}-t^{2n-2}}{(t-1)^2},$$
that is up to a factor $(-t^2)^{n-1}$ the Tutte polynomial $\frac{x^n-x}{x-1}$ of the cyclic graph evaluated in $\frac{2t-1}{t^2}$.
I claim that the coefficients of the polynomial $P_n(t)$ are
$$
p_k = \begin{cases}
(-1)^k \sum_{i=0}^k \binom{n-2-i}{k-i}(i+1)2^{k-i} & k\leq n-2\\
2n-1-k & n-1\leq k \leq 2n-3
\end{cases}
$$
In other words I need to prove the following equality
$$P_n(t)= \sum_{k=0}^{2n-3} \left((-1)^k \sum_{i=0}^k \binom{n-2-i}{k-i}(i+1)2^{k-i} \right) t^k ,$$
where the binomial coefficient $\binom{-a}{b}$ is $(-1)^b \binom{a+b+1}{b}$ for all positive integers $a,b$.
Answer: A partial answer. By writing
$$\begin{eqnarray*} P_n(t)&=&(-1)^{n+1}(2t-1)\frac{(t^2)^{n-1}-(2t-1)^{n-1}}{(t-1)^2}\\&=&(-1)^{n+1}\sum_{h=0}^{n-2}(2t-1)^{n-1-h} t^{2h}\tag{1} \end{eqnarray*}$$
we have
$$ [t^k]P_n(t) = (-1)^{n+1}\sum_{h=0}^{n-2}[t^{k-2h}](2t-1)^{n-1-k}=\sum_{h=0}^{n-2}\binom{n-1-k}{k-2h}2^{k-2h} \tag{2}$$
where the RHS of $(2)$ is pretty close to the expression we want to get. In the opposite direction, for a fixed value of $k\leq n-1$
$$ \sum_{i=0}^{k}\binom{n-2-k+(k-i)}{k-i}2^{k-i}(i+1)=[u^k]\left(\sum_{b\geq 0}(b+1)u^b\right)\cdot\left(\sum_{a\geq 0}\binom{n-2-k+a}{a}2^a u^a\right) $$
hence the LHS is the coefficient of $u^k$ in $\frac{1}{(1-u)^2(1-2u)^{n-k-1}}$ and
$$ \sum_{k=0}^{n-1}u^k\sum_{i=0}^{k}\binom{n-2-i}{k-i}2^{k-i}(i+1) = \frac{1-(1-2u)^n}{2u(1-u)^2(1-2u)^{n-1}}\tag{3}$$
where the RHS of $(3)$ matches $P_n(u)$ up to the monomial $u^{n-1}$.
Now it should be enough to extend this approach to $k\geq n$ to prove the wanted identity.

Coefficients of a polynomial


Qt C++ MySQL to QTableView Multiple Connections Tables Empty

Question: I'm trying to view data from MySQL database to two TableViews in qt C++ application and now I'm always getting an empty tables but with the correct header names in database and the row counts, but inside the tables there's no data, it's just empty.
I don't know if I'm fetching the data right or not?
<code>#include "mainwindow.h"
#include "ui_mainwindow.h"

MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);

{
    QSqlDatabase db = QSqlDatabase::addDatabase("QMYSQL", "test_db");

    db.setHostName("localhost");
    db.setUserName("root");
    db.setPassword("abc123");
    db.setDatabaseName("test_db");

    if(db.open())
    {
        qDebug("Connected!");

        QSqlQuery query(db);

        if(!query.exec("SELECT * FROM employees"))
        {
            qDebug(query.lastError().text().toLatin1());
        }
        else
        {
            QSqlQueryModel* model = new QSqlQueryModel();

            model->setQuery(query);

            ui->tableView->setModel(model);

            ui->tableView->show();
        }
    }
    else
    {
        qDebug("Connection Failed!");
    }

    db.close();
}

{
    QSqlDatabase db = QSqlDatabase::database("test_db");

    db.setHostName("localhost");
    db.setUserName("root");
    db.setPassword("abc123");
    db.setDatabaseName("test_db");

    if(db.open())
    {
        qDebug("Connected!");

        QSqlQuery query(db);

        if(!query.exec("SELECT * FROM clients"))
        {
            qDebug(query.lastError().text().toLatin1());
        }
        else
        {
            QSqlQueryModel* model = new QSqlQueryModel();

            model->setQuery(query);

            ui->tableView_2->setModel(model);

            ui->tableView_2->show();
        }
    }
    else
    {
        qDebug("Connection Failed!");
    }

    db.close();

    db = QSqlDatabase();

    db.removeDatabase("test_db");
    }
}

MainWindow::~MainWindow()
{
    delete ui;
}
</code>
Comment: I'd suggest working through the [examples](http://doc.qt.io/qt-5/examples-sql.html). Probably start with the [book](http://doc.qt.io/qt-5/qtsql-books-example.html) one
Comment: You don't have to add the database twice. From the [docs](http://doc.qt.io/qt-5/qsqldatabase.html#addDatabase): *If there already exists a database connection called connectionName, that connection is removed.*
Replace the second call to `addDatabase` with [`database`](http://doc.qt.io/qt-5/qsqldatabase.html#database)
Comment: Thanks for Relpying, I did what you said but the result is aslo empty tableviews.
Comment: When i erase the second connection the data in tableview 1 appear!
Comment: Please read [Under what circumstances may I add "urgent" or other similar phrases to my question, in order to obtain faster answers?](//meta.stackoverflow.com/q/326569) - the summary is that this is not an ideal way to address volunteers, and is probably counterproductive to obtaining answers. Please refrain from adding this to your questions.
Answer: <code>if (db.open())
{
    QSqlQuery query;
    query.prepare("SELECT * FROM librarian");
    if(query.exec()){
        QSqlQueryModel* model = new QSqlQueryModel();
        model -> setQuery(query);
        ui -> tableView -> setModel(model);
    }

}
else {
    qDebug() << "Not Loaded";

}
</code>


Splitting of treatment sum of squares in ANOVA

Question: An apparently classic mantra appearing in about a dozen of ANOVA textbooxs i consulted reads roughly as: given any choice of $T-1$ orthogonal contrasts $C_1, \cdots, C_{T-1}$ in a (not necessarily balanced) $T$-groups (one-way) ANOVA design, the treatment (or "between-groups") sum of squares $SS_{Treat}$ can be decomposed as the sum $\sum_{j=1}^{T-1}SS_{C_j}$ of contrasts $C_j$ sums of squares.
I think it would be helpful to have a proof of this fact or a reference to one, as most textbooks seem to lack.
I do not know if of any help, but here are some of the definitions of the statistics involved: let $\overline{Y}_i$ be the mean of the $n_i$ observations in the $i$-th group and $\overline{Y}$ the mean of all the observations; then
--a contrast is a linear combination $\sum_{i=1}^{T} \lambda_i\overline{Y}_i$ such that $\lambda_i\in \mathbb{R}$ and $\sum_i\lambda_i=0$;
--if two contrasts have coefficients $\lambda_i$ and $\nu_i$ such that $\sum_i\lambda_i\nu_i/n_i=0$, they are said to be orthogonal;
--sum of squares are defined as: $SS_{Treat}=\sum_{k=1}^Tn_k(\overline{Y}_k-\overline{Y})^2$ and $SS_C=\dfrac{C^2}{\sum_{i=1}^T\frac{\lambda_i^2}{n_i}}$
thanks a lot.
Answer: We let $C$ denote a contrast such as $C=\sum_{i=1}^T\lambda_i\bar{Y}_i$ and the vector $C=(\lambda_1,\cdots,\lambda_t)$.  Define $C_0=\sum_{i=1}^Tn_i\bar{Y}_i$. Therefore, $C=\{C_0,C_1,\cdots,C_{T-1}\}$ forms an orthogonal basis for $\mathrm{R}^T$, with respect to the inner product
$$\langle C_a,C_b\rangle=\sum_{i=1}^T\frac{\lambda_i^a\lambda_i^b}{n_i}.$$
Then, by the Parseval's identity, for any vector $M\in\mathrm{R}^T$,
$$\|M\|^2 = \sum_{i=0}^{T-1}\frac{\langle C_i,M\rangle^2}{\langle C_i,C_i\rangle}.$$
Define $M=(\sqrt{n_1}\bar{Y}_1,\cdots,\sqrt{n_T}\bar{Y}_T)$, and check that for this specific $M$ we have,
$$SS_{C_i}=\frac{\langle C_i,M\rangle^2}{\langle C_i,C_i\rangle}\;\;\;\text{for }i =0,\cdots,T.$$
Therefore, since $\|M\|^2=\sum_{i=1}^Tn_i\bar{Y}_i^2$,
$$\sum n_i\bar{Y}_i^2=N\bar{Y}^2+\sum_{i=1}^{T-1}SS_{C_i},$$
where $N=n_1+\cdots+n_T$ and we let $SS_{C_0}=N\bar{Y}^2$.Therefore,
$$\sum_{i=1}^{T-1}SS_{C_i}=\sum_{i=1}^Tn_i\bar{Y}^2_i-N\bar{Y}^2=\sum_{i=1}^Tn_i(\bar{Y}-\bar{Y}_i)^2=SS_{treat}.$$
QED

Just 3 comments:

The fact that $C$ forms a basis follows from the fact that
coordinates of $C_1,\cdots,C_{T-1}$ add up to zero. So every linear
combination of them has this property. But $C_0$ does not have this
property. Therefore $C_0$ is orthogonal to $C_1,\cdots,C_{T-1}$. On
the other hand, every $T$ orthogonal vectors form a basis for
$\mathrm{R}^T$.
The Parseval's identity states that for orthonormal basis $\{v_i\}$,
we have $$\|M\|^2=\sum\langle v_i,M\rangle.$$ To apply this to the
orthogonal basis $C$, you can first divide the vector to their
length to get the orthonormal basis $\{\frac{C_0}{\sqrt{\langle
   C_0,C_0\rangle}},\cdots,\frac{C_{T-1}}{\sqrt{\langle
   C_{T-1},C_{T-1}\rangle}}\}$
note that $\|M\|^2$ is not the Euclidean length. It is the length
defined by the inner product.
Answer: @pmjn6's answer is not based on standard notation so it can be a bit confusing. Based on his answer though, the Parseval's identity is the key to decomposing the sums of squares. Constructively, take the contrasts
$$c_l = \frac{1}{\sqrt{l(l+1)}}(\underbrace{1, 1, \ldots, 1}_{l\text{ times}}, -l, 0, \ldots, 0)^\prime,\quad l=1,\ldots,a-1.$$ Now, take $c_0 = 1_a/\sqrt{a}$ where $1_a$ is a vector of ones. $\{c_0,c_1,\ldots,c_a\}$ forms an orthonormal basis for $\mathbb{R}^a$. By Parseval's identity, for any vector $v \in \mathbb{R}^a$,
$$\|v\|^2 = \sum_{i=0}^a (c_i^\prime v)^2.$$ Therefore, take $v = \sqrt{n}(\bar{Y}_{1\cdot},\ldots,\bar{Y}_{a\cdot})^\prime$. We have
$$\mathrm{SS}_{c_i} = (c_i^\prime v)^2,\qquad i=0,\ldots,a$$, thus, $\|v\|^2 = \sum_{i=1}^a n\bar{Y}_{i\cdot}^2$, and
$$\sum n\bar{Y}_{i\cdot}^2 = na\bar{Y}_{\cdot \cdot}^2 + \sum_{i=1}^a \mathrm{SS}_{c_i},$$ where $\mathrm{SS}_{c_0} = na\bar{Y}_{\cdot \cdot}^2$. Thus,
$$\sum_{i=1}^a \mathrm{SS}_{c_i} = \sum_{i=1}^a n\bar{Y}_{i\cdot}^2 - na\bar{Y}_{\cdot\cdot}^2 = \sum_{i=1}^a n(\bar{Y}_{\cdot\cdot}-\bar{Y}_{i\cdot})^2.$$
The sums of squares due to the contrasts decompose the treatment sum of squares, or $\mathrm{SSR}_c$.


Is it appropriate to create multiple ViewModels in one View?

Question: This is more of a code architecture question.
I have a Game View with a deck of 52 cards. The model is:
struct Card {
    let suit: String
    let value: String
}

The simplified ViewModel is:
class GameViewModel: ObservableObject {
    let numberOfCards: Int
    @Published var cards: [Card] = []

    init(numberOfCards: Int) {
        self.numberOfCards = numberOfCards
        for _ in 0..<numberOfCards {
            cards.append(Card(suit: "", value: ""))
        }
    }
//Other logic methods
}

And the View:
struct GameView: View {
    @StateObject var gameVM = GameViewModel(numberOfCards: 52)
...
}

I've kept all game logic in GameViewModel, even manipulated cards via its self.cards[i], but now I've realized that I will need more control over each Card and thus probably a ViewModel for each Card.
Question: is creating 52 more ViewModels a good MVVM design pattern? Or one View = one ViewModel?
And where should I create Cards ViewModels? In the View? Or GameViewModel should create them like:
class GameViewModel: ObservableObject {
    let numberOfCards: Int
    @Published var cards: [CardViewModel] = []

    init(numberOfCards: Int) {
        self.numberOfCards = numberOfCards
        for _ in 0..<numberOfCards {
            cards.append(CardViewModel(suit: "", value: ""))
        }
    }
}

P.S. I feel like this question can be expanded to any example where we have One-Many relations like CategoryVM->Items, or GroupVM->Individuals, or FamilyVM->People.
Comment: Put the game logic in a Game model. Make ViewModels that format just the bits of the model that each View needs
Comment: I'm afraid this is opinion-based question. In my opinion 52 instance is not an issue, as long as this is what you really need and you keep roles & responsibilities separation clean.
Comment: https://stackoverflow.com/questions/4807101/viewmodel-to-viewmodel-communication
Answer: You can add funcs to the Card, e.g.
struct Card {
    let suit: String
    let value: String
    var somethingYouWantToChange

    mutating func someMethod() {

    }
}

In swiftUI we usually use the names "Model" or "Store" for the single object that stores the model structs, e.g.
class GameModel: ObservableObject {
    @Published var cards: [Card] = []

When you want to pass the card along and require write access, we use @Binding which converts the View struct into a View model struct, e.g.
struct CardView: View {
    @Binding var card: Card

    var body: some View {
        Text(card.value, format: .number) // Text automatically reformats the UILabel when region settings change.
        Button("Some action") {
            card.someMutatingFunc()
        }
    }

It's passed in like:
CardView(card: $card)

ForEach is usually the view model that creates and manages the bindings, e.g.
ForEach($gameModel.cards) $card in {

To make this word you have to make Card conform to Identifiable and give it an id var, usually let id = UUID() but in your case it might be var id: String { suit + value }.
Comment: MVVM objects aren't really compatible with SwiftUI it would slow it down and cause bugs. I recommend learning structs and property wrappers state and binding which are designed to completely replace view controllers.
Comment: Thank you! 1. Doesn't adding methods to a Model break the idea of MVVM? That data and code layers should be separated? 2. I wish to use Combine and it will be hard to use it in a struct as I can't make structs variables @Published.


Calculate Points in Right Angle to Line

Question: Given two points(blue) A(1,1) and B(3,3) I need to calculate the coordinates of two new points(orange) which are in an right angle to line AB and a certain distance from point A.
So far, I've calculated the angel to X-axis (45°) with Arctan(1/1).
I calculated the coordinates of the new points as follows:
X = (sin(45° + 90°) * Distance) + X
Y = (sin(45° + 270°) * Distance) + Y
However, this is wrong. How would I calculate the coordinates of the points shown in organge?
Answer: Hints (fill in details):
Slope of $\;AB\;$ is $\;\cfrac{3-1}{3-1}=1\;$ , so orange points are on the line with slope $\;-1\;$ which pases through $\;A(1,1)\;$
Thus, you need two points on the line $\;y-1=-(x-1)\implies y=-x+2\;$, and thus their general form is $\;(a, -a+2)\;$, and to a certain distan $\;d\;$ from $\;A(1,1)\;$, thus solve the equation
$$(a-1)^2+(-a+1)^2=d^2\iff2(a-1)^2=d^2\implies\ldots$$
Answer: Refer to the graph:
$\hspace{2cm}$
$$\begin{cases}x_1=1-d\cos{45^\circ}=1-\frac{d}{\sqrt{2}} \\ y_1=1+d\sin{45^\circ}=1+\frac{d}{\sqrt{2}}\end{cases}$$
Similarly, can you find the coordinates of the second orange point?
Comment: Thanks, I found the second point by switching 1- with 1+ and vice versa.
Comment: Good job. It conforms with your attempted method, just needed to adjust the terms.

Calculate Points in Right Angle to Line


Ordered associative containers of pointers

Question: Is it okay practice to define ordered associative containers of pointers (either built-in or class-type ones) despite the fact that, as far as I can tell from the standard, relational operators on (non-array objects et al.) pointers are undefined?
From 5.9 of the c++11 standard:

If two pointers p and q of the same type point to different objects that are not members of the same object or elements of the same array or to different functions, or if only one of them is null, the results of p<q, p>q, p<=q, and  p>=q are unspecified.

Since ordered containers (map, set, multimap and multiset) use the < operator by default to provide a total order it compiles fine to create a set of pointers. Then again if the relational operators for pointers are truly unspecified it could be that p<q and p>q both test false or true meaning this may not be a good idea for the ordering of a set. I would've probably accepted that it is a bad idea if it wasn't for the fact that an example in my book (C++ Primer 5th ed chapter 13.4) defines a set of pointers for a class type Folder*, i.e. set<Folder*> seemingly with no comment on my concern.
Answer: The ordered associative containers do not use operator< directly, they use std::less, which is well defined and establishes a total ordering for pointer types, even when operator< isn't.
So, it is fine to instantiate std::set or std::map with pointer types as keys.
Answer: "Yes, because it uses std::less, which is required to result in a total order even if < doesn't. (< would be allowed to treat different pointers from distinct sequences as equal, which would result in an odd behaviour of map etc if you insert pointers from different sequences)." -etarion
Source of quote: Are pointers allowed as keys in ordered STL containers?
Also, this question is a duplicate of that question.


UIbutton frame and addtarget is different

Question: I make custom view and there create button add on view.
In View Controller
MyCustomView *customView = [[MyCustomView alloc] init];
[customView.button addTarget:self action:@selector(goodTry) forControlEvents:UIControlEventTouchUpInside];

But if I touch my button in frame only down mean line is touchable, upper of mean line addTarget does not working.
 ----
|\   |
|*\  |
|**\ |
|***\|
 ----

-- It is my button frame. Where *** - it is working. Where empty place doesn't work.
Thanks for your help.
Comment: The drawing is the customView or the button? Is it the same size?
Comment: @Rajneesh071 it is a `UIControlEvent` that he has to add here not a `UIControlState` that will just throw an error or at the very least a warning. `UIControlEventTouchUpInside` should work if everything else is done correctly. How do you create the buttons on the customView?
Comment: Avi, drawing is for button. Size of CustomView  and my button is different
Answer: Check that your button frame lies inside the parent's frame. Area of button outside Parent's frame freezes and doesn't respond to touch events. Set clipToBounds = YES; on button to test it.
Answer: Add background color for button and check how and where the button positioned.If it positioned outside of your custom view you can't perform action with that outside portion.


ENOTFOUND Error on UDP socket with node.js 0.10

Question: I tried to run some js with node 0.10 using UDP and I get errors. The API changes talks about the new all asynchronous dgram system but I can't run the example.
When I try :
var s = dgram.createSocket('udp4');

s.bind(1234, function() {
    s.addMembership('220.127.116.11');
});

I get this :
events.js:72
    throw er; // Unhandled 'error' event

Error: getaddrinfo ENOTFOUND
    at errnoException (dns.js:37:11)
    at Object.onanswer [as oncomplete] (dns.js:124:16)

I don't have any problems with node 0.8 .
I'm on windows 8 x64.
Answer: Can you try like this :
s.bind(1234,'0.0.0.0', function() {
  s.addMembership('188.8.131.52');
});

Does it give some error
Comment: Thanks ! No error now. I will try to run my full program but I think you perfectly resolve my problem :)


Accessing a parent UIViewController from its children UIViewControllers

Question: I have a UIViewController called Container, that houses two other child UIViewControllers: Master and Detail.
My problem is trying to access the Container from one of its child controllers.
App Delegate Code:
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
    var window: UIWindow?
    var container: Container?

    func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
        window = UIWindow(frame: UIScreen.mainScreen().bounds)
        container = Container(nibName: "Container", bundle: nil)
        window?.rootViewController = Container()
        window?.makeKeyAndVisible()
        return true
    }

    func appShowDetailView(vc:UIViewController){
        container!.showDetailView(vc)
    }
}

Container Code:
import UIKit

class Container: UIViewController {

    var masterView:UIViewController?
    var detailView:UIViewController?
    var masterViewFrame = CGRectMake(0, 0, 0, 0)
    var detailViewFrame = CGRectMake(0, 0, 0, 0)
    var detailOnScreenFrame = CGRectMake(0, 0, 0, 0)
    var detailOffScreenFrame = CGRectMake(0, 0, 0, 0)
    var masterViewHeight:CGFloat = 50

    override func viewDidLoad() {
        super.viewDidLoad()
        masterView = MenuViewController(nibName: "MenuViewController", bundle: nil)
        detailView = RootViewController(nibName: "RootViewController", bundle: nil)
        masterViewFrame = CGRectMake(0, 0, self.view.frame.width, masterViewHeight)
        detailViewFrame = CGRectMake(0, masterViewHeight, self.view.frame.width, self.view.frame.height - masterViewHeight)
        detailOffScreenFrame = CGRectMake(detailViewFrame.origin.x, detailViewFrame.origin.y + detailViewFrame.height, detailViewFrame.width, detailViewFrame.height)
        detailOnScreenFrame = detailViewFrame
        self.addChildViewController(masterView!)
        self.addChildViewController(detailView!)
        masterView!.view.frame = masterViewFrame
        detailView!.view.frame = detailViewFrame
        self.view.addSubview(masterView!.view)
        self.view.addSubview(detailView!.view)
    }

    func cycleDetailView(from:UIViewController, toView to:UIViewController){
        from.willMoveToParentViewController(nil)
        self.addChildViewController(to)
        to.view.frame = self.detailOffScreenFrame
        self.detailView = to
        self.transitionFromViewController(from, toViewController: to, duration: 0.25, options: UIViewAnimationOptions.allZeros,
            animations: {() -> Void in

                // send the new view controller in, and the old one out
                to.view.frame = self.detailOnScreenFrame
                from.view.frame = self.detailOffScreenFrame
            }, completion: {success -> Void in

                // tells the view controllers cycling has ended
                from.removeFromParentViewController()
                to.didMoveToParentViewController(self)
            }
        )
    }

    func showDetailView(vc: UIViewController){
        if let oldView = detailView {
            cycleDetailView(oldView, toView: vc)
        }else{
            detailView = self.childViewControllers[1] as? UIViewController
            if let oldView = detailView {
                cycleDetailView(oldView, toView: vc)
            }else{

            }
        }
    }
}

The problem lies in showDetailView(). When this is called by a piece of code like this:
    let appDelegate = UIApplication.sharedApplication().delegate as? AppDelegate
    if let delegateUnwrapped = appDelegate {
        delegateUnwrapped.appShowDetailView(aViewController)
    }

...the Container function showDetailView() can only get nil values for detailView and self.childViewControllers is an empty array.
This make me think I am accessing the child view controller in the wrong way.
Can anyone tell me where I am going wrong?
TIA.
Answer: I think your problem is this line in the app delegate,
 window?.rootViewController = Container()

This creates a new instance of Container, not the one that you assigned to the container property. Change that line to,
window?.rootViewController = container


Using SQL Keywords in C# MySqlCommand.CommandText

Question: I'm moving my stored procedures to C# code.
In the stored procedures I have something like
Begin
SET @Id = null;
IF ?Status = 0 THEN SET ? ?DateToday = UTC_TIMESTAMP(); END IF;
SELECT * FROM TABLE
END

In the C# Code I just copy pasted everything inside Begin and END. Like so,
MySqlCommand command = new MySqlCommand();
command.CommandText = @"SET @Id = null;
IF ?Status = 0 THEN SET ? ?DateToday = UTC_TIMESTAMP(); END IF;
SELECT * FROM TABLE"

I have an error in the If statement saying incorrect syntax. The stored procedure is working but not when I place it in C# code.
Comment: Why not use only command.CommandText = "SELECT * FROM TABLE"
Comment: Does your stored procedure have parameters?
Comment: @Damith its just an example, the Set and If statement are causing errors.
Comment: @BlackFrog yes it does. i've set it in the code too.
Answer: That's not the logic of Stored Procedures. As its name implies stored procedures are functions that are stored in the database itself. And you can invoke them by calling their names.
Hence you cannot just put the stored procedure function code in your C# code, I mean you shouldn't.
Update:
If you only want to use T-SQL statements (if-else blocks and so) check out this link.
Comment: I understand, but what is the counterpart of Set and the If statement in C# CommandText?btw thanks for you reply :)
Answer: If you have created a stored procedure then you can call it using a stored procedure syntax like this;
using (SqlConnection con = new SqlConnection(someconnectionstring)) {
    using (SqlCommand cmd = new SqlCommand("myStoredProc", con)) {
      cmd.CommandType = CommandType.StoredProcedure;
      //If you have parameters in your SP, add like this else ignore below line
      cmd.Parameters.Add("@myparam", SqlDbType.VarChar).Value = somevalue;

      con.Open();
      cmd.ExecuteNonQuery();
    }
  }

Comment: @Cosytyle;- Any specific reason to do that. As it is not a good coding practice?


Limit of probability question 2

Question:
Assume for all finite $r>r_0$ that
  $$\lim_{n\to\infty}\mathbb{P}(\mathcal{A}_{r,n})=0,$$
  where $\mathcal{A}_{r,n}$ is an event on some random variables, and $n$ and $r$ are deterministic variables. How to prove the following?
  $$\lim_{n\to\infty}\mathbb{P}(\lim_{r\to\infty} \mathcal{A}_{r,n})=0.$$

This is a part of a bigger problem. I need to prove the second equation but I have proved the first one. Is the second equation always true? If yes, how can I prove that?
Comment: @Did Note that this is not duplicate,  they are two different questions. Please read the problem statements and think more before you mark something as a duplicate.
Comment: @Did this is your second mistake about me when marking duplicate.
Comment: Sure. When you will take the time to make a pause of about, say, 5 minutes in the stream of small variations of questions you are posting to the site, none of them being actually the one you mean to ask, let me suggest that you use these 5 minutes to take a honest and hard look at your past questions and wonder how they help to establish the site as a repository of knowledge (never heard the phrase? why am I not surprised?). Thanks in advance.
Answer: Again, this isn't necessarily true. Consider the case that
$$
\mathbb P(\mathcal A_{r,n}) = \begin{cases}
1 & \text{, if } r > n \\
0 & \text{, otherwise}.
\end{cases}
$$
Comment: Thank you again, and you are right. Can you tell me under what conditions we can conclude the second equation from the first? Can I share the real problem with you?
Comment: @Su20200 Well, there are such properties but it's impossible to tell which one might help you with the given information. If you want to post the problem, I'd suggest posting it as a separate question.
Comment: Comments are not for extended discussion; this conversation has been [moved to chat](http://chat.stackexchange.com/rooms/72922/discussion-on-answer-by-stefan-mesken-limit-of-probability-question-2).

Limit of probability question 2


Valores nulos de ajax para controller

Question: Estou recebendo valores null no objeto por parametro no controller do asp.net core via ajax
Segue o  javascript com o ajax
 var ClienteFornecedor = {
        Id: "0",
        Tipo: $('#selTipoAdicionar').val(),
        NomeRazaoSocial: $('#txtNomeRazaoSocialAdicionar').val(),
        NomeFantasia: $('#txtNomeFantasiaAdicionar').val(),
        CpfCnpj: $('#txtCpfCnpjAdicionar').val(),
        Endereco: $('#txtEnderecoAdicionar').val(),
        Bairro: $('#txtBairroAdicionar').val(),
        Cidade: $('#txtCidadeAdicionar').val(),
        Estado: $('#txtEstadoAdicionar').val(),
        Cep: $('#txtCEPAdicionar').val(),
        Telefone: $('#txtTelefoneAdicionar').val(),
        Celular: $('#txtCelularAdicionar').val(),
        Ie: $('#txtInscEstadualAdicionar').val(),
        Observacao: $('#txtObservacaoAdicionar').val()
    };

   var dto = JSON.stringify(ClienteFornecedor);

    $.ajax({
        url: 'ClienteFornecedor/Adicionar',
        type: 'POST',
        dataType: 'json',
        contentType: 'application/json; charset=utf-8',
        data:  dto,
        success: function (result) {

            }

        }
    });

Verifiquei no debug e vi que está convertendo corretamento em json, porém o problema é que no controller da aplicação, o objeto está chegado com as propriedades null
Segue o meu controller:
    public JsonResult Adicionar(ClienteFornecedorDto dto)
    {
        int res = _appCliFor.Adicionar(dto);

        var settings = new JsonSerializerSettings();
        return Json(res, settings);
    }

O objeto dto está vindo com as propriedades null
Comment: public JsonResult Adicionar([FromBody]ClienteFornecedorDto dto) e ver se funciona!
Comment: Confirma se os nomes das propriedades do objeto ClienteFornecedor estão iguais aos do ClienteFornecedorDto.
Comment: Sim são iguais, a unica diferença é o Id que é `int`, mas acredito que não interfere. E é uma classe que tem herança e um método. não sei se interfere.
Comment: Tenta assim: var dto = $.toJSON(ClienteFornecedor);
Comment: Esse método é exclusivo de uma bilbioteca que eu não tenho.. o stringify está convertendo.. eu testei
Comment: Não.. agora o objeto vem completamente `null`
Comment: além do from body, adicione o [HttpPost] antes da declaração da controller e poste a sua DTO para vermos se ela bate com o objeto que está postando... E quando você diz que tudo vem null, o que vinha preenchido antes?
Comment: Adiciona também o Json que está sendo postado, você consegue capturar pelo browser mesmo.
Comment: Tudo isso que vocês me falaram (HttpPost e FromBody) deram certo, porém precisei ajustar o ajax. `data: JSON.stringify(ClienteFornecedor);` Deu certo. Muito Obrigado a todos
Answer: Boa tarde, poderia tentar fazer a action da seguinte forma:
[HttpPost]
public JsonResult Adicionar([FromBody] ClienteFornecedorDto dto)

Valores nulos de ajax para controller


Using UPDLOCK without transaction

Question: The documentation states that Specifies that update locks are to be taken and held until the transaction completes. So if I'm not transactions is it pointless to add it to my query?
Answer: Everything in SQL Server is done inside a Transaction. Whether you explicitly open a transaction by using key words Begin Transaction or you don't, if you don't explicitly open a transaction (A.K.A Explicit Transaction), sql server wraps your t-sql statements inside a transaction automatically also known as Implicit Transactions.
Now during a transaction (explicit or implicit) sql server will obtain some locks on the resources (tables, indexes etc), depending on what type of action is being taken, sql server obtain different types of locks (Shared Locks , Exclusive locks etc)
If you use UPDLOCK (Update lock) in your statement, it is an exclusive lock and other users will not be able to access the object(s) for the duration of your transaction (explicit or implicit).
Hence whether you use transactions (explicit transaction) or not (Implicit transaction) if you use the hint (UPDLOCK) in your statement you query will obtain exclusive locks and will lockout the object to you exclusively for the duration of your transaction.
Comment: An UPD lock is not exclusive. It is compatible with shared locks, but not other UPD locks or X locks. https://technet.microsoft.com/en-us/library/ms172925(v=sql.110).aspx
Comment: thanks, the extra context on the implicit transactions was helpful.

Using UPDLOCK without transaction


GeometryReader behaves oddly with an extracted view

Question: In this example, the "hello" text is placed in the middle of the screen, as expected.
struct ContentView: View {
    var body: some View {
        GeometryReader { geo in
            Text("hello")
                .background(Color.green)
        }
        .background(Color.blue)
    }
}

But when I move Text to an extracted view, the "hello" text moves to the top left corner of the screen.
struct ContentView: View {
    var body: some View {
        GeometryReader { geo in
            ExtractedView()
        }
        .background(Color.blue)
    }
}

struct ExtractedView: View {
    var body: some View {
        Text("hello")
            .background(Color.green)
    }
}

Is this a bug, or an expected behavior I don't understand?
Comment: Yes, in both cases.
Comment: Can't reproduce with Xcode 11.5, iOS 13.5 (SwiftUI 1.0).
Comment: @pawello2222 I'm on Xcode 11.6. What do you see with Xcode 11.5?
Comment: In both cases the same: the text "hello" with a green background and a blue background for the rest of the view.
Comment: @pawello2222 in both cases the "hello" is centered?
Comment: @pawello2222 thank you
Answer: Confirm top-left location on Xcode 12 / iOS 14. I don't think it is a bug. Actually, GeometryReader is not a container and does not (should not) have own default alignment, its purpose custom alignment, so here we are.
Possible solutions (tested with Xcode 12b3 / iOS 14):

place by position

GeometryReader { geo in
    ExtractedView()
        .position(x: geo.size.width / 2, y: geo.size.height / 2)
}

wrap into full-size stack container (that has default alignment)

GeometryReader { geo in
    VStack {
        ExtractedView()
    }
    .frame(maxWidth: .infinity, maxHeight: .infinity)
}

Comment: Thank you for the confirmation. But if it's not a container, why does it behave like one in my first example? What's the difference between using something directly vs in an extracted view?


syntax error near unexpected token `newline' on GCP

Question: I am getting this error
install-logging-agent.sh: line 2: syntax error near unexpected token <code>newline' install-logging-agent.sh: line 2: </code>'
on this command
curl -sSO https://dl.google.com/cloudagents/install-logging-agent.sh
sudo bash install-logging-agent.sh
Comment: Have you seen these instructions for installing the logging agent?  https://cloud.google.com/logging/docs/agent/logging/installation
Comment: Execute the two commands **one at a time** and not as a single command.
Answer: I use the same installation script for a server I set up back in 2018 and ran into the same issue today. The installation method we are using appears to have been deprecated by Google because trying to load the URL https://dl.google.com/cloudagents/install-logging-agent.sh returns a 404 error. This was still working for me two weeks ago, so it was something recent.
The solution would be to update your installation method to follow the current documentation at https://cloud.google.com/logging/docs/agent/logging/installation (posted by @Kolban in a comment)


Scheme of characteristic zero is Q-scheme?

Question: Let $X$ be an arbitrary scheme.
I think one calls $X$ a characteristic zero scheme if all the residue fields of $X$ are of characteristic zero, for any point $x$ on $X$.
If $X$ is a scheme over $\mathbb Q$, then of course it is a scheme of characteristic zero.
My question is: does also the converse hold? And how does one make this rigorous?
Comment: Assuming that $X$ has characteristic zero, you have to construct a morphism $X\to\mathrm{Spec}\:\mathbb Q$. At the level of topolgical spaces, there are no choices to be made. Can you see what can be done at the level of structure sheaves?
Comment: It might be worth noting that $X$ may not actually have any $\mathbb{Q}$-points. This may not be confusing to other people, but confused me for awhile. If $E$ is a genus $1$ curve of characteristic zero that has a $\mathbb{Q}(\sqrt{2})$-point but no $\mathbb{Q}$-point, then people might say that $E$ is defined as an elliptic curve over $\mathbb{Q}(\sqrt{2})$ but is not defined over $\mathbb{Q}$. As the argument below shows, this does not mean that it is not a scheme over $\mathbb{Q}$. Ignore this if that was already obvious to you.
Answer: Yes, you only have to show that any non-zero integer $n$ is invertible in $O_X(X)$ (then the universal property of localization induces a homomorphism from $\mathbb Q \to O_X(X)$ hence to the sheaf $O_X$). For all $x\in X$, as $n$ is no zero in $k(x)$, it is invertible in $O_{X,x}$, hence invertible in an open neighborhood of $x$. The local inverses glue into a global inverse by the uniqueness of the inverse.


css div centering

Question: I am trying to center a div button and its not working
here is the css
    .game-actions{
margin-left:auto;
margin-right:auto;
}

.game-actions a.up {
    display: block;
    text-decoration: none;
    font-weight: bold;
    padding:12px 32px;
    float: left;
    border: 1px solid #c1d9f6;
    -moz-border-radius: 7px;
    -webkit-border-radius: 7px;
}

.game-actions a:hover {
    border-color: #80b0ea;
    background:#e1ecf3;
}

here is the html

Tweet it

Website is at - http://gibberize.com/
Answer: By default, div tags expand their width to the entire width of their parent container. Thus setting their margins to auto doesn't do anything since it just auto-sets both margins to 0. If you set a fixed width for the div then it will center.
Answer: By default div elements are the full width of the page and since you aren't specifying how wide it should be the auto margin will be 0 on both sides.
In this case I would use a text-align: center; on the div to center the link.
Answer: Here's one solution for you. To your first .game-actions CSS class add:
width:1px;

Also, change the caption Tweet it to:
Tweet it

(to avoid breaking the button over 2 lines)

css div centering


Linux (Centos) soft raid1 - motherboard died

Question: I use centos 6.3 and soft raid1 (via mdraid) + LVM. The problem is that MB died and I have several questions.

I have two hard drives. Is it important what drive how connect to MB. I mean slave/master and etc. Besides I don't remember how they were connected before.
Should I just replace MB and swith server on? I mean will OS auto determine MB change?
Should I do something else not to loose data?
Answer: Assuming your array isn't positively ancient (kernel 2.2 vintage), each volume has a MD header containing information about how the array is constructed.  Among other things, the header contains the UUID of the array the volume belongs to and the volume's position within that array.  Since this information is available, MD RAID doesn't care how the drives are connected.  You could probably reassemble the array even if you put one of the drives in a USB enclosure and served the other up over the network as an nbd device -- though I wouldn't recommend such a crazy setup.
Note, however, that if your array is using version 0.90 metadata rather than version 1.0 or newer, some parts of the header are CPU-specific.  It's difficult to move such an array from, for example, x86 to PowerPC, and moving from x86 to x86-64 may also have problems.
Answer: you should make sure you note which is the ide master and slave
If its the same motherboard you'll be ok to just swap it out. It happens every now and then when a server motherboard will die and a vendor will just swap it out and everything comes up just fine.
Comment: Thank you for your time. Unfortunatety it's impossible now to determine what was master and what was slave. Can I do something with it? And motherboard is now different.
Comment: plug in the server with a single drive and the system should find a degrated raid.. then shutdown and format the other in rescue mode then reboot with it and it should repair


Custom template for view with block display in a page

Question: I created a template views_block__applications_block_1.twig for a block used on one of my pages. The block is based on a block view (unformatted list). Under blocks, the machine-readable name is views_block__applications_block_1. After searching around, I found that views_block__applications_block_1.twig should be the right template name. But no matter what I try, it doesn't seem to be working, all changes to the file are invisible. Can anybody point me in the right direction?
File content:
{#
/**
 * @file
 * Theme override to display a view of unformatted rows.
 *
 * Available variables:
 * - title: The title of this group of rows. May be empty.
 * - rows: A list of the view's row items.
 *   - attributes: The row's HTML attributes.
 *   - content: The row's content.
 * - view: The view object.
 * - default_row_class: A flag indicating whether default classes should be
 *   used on rows.
 *
 * @see template_preprocess_views_view_unformatted()
 */
#}

TEST

{% if title %}

{{ title }} - TEST

{% endif %}
{% for row in rows %}
  {%
    set row_classes = [
      default_row_class ? 'views-row',
    ]
  %}

    {{ row.content }}

{% endfor %}

Answer: The correct naming is:
views-view--applications--block-1.html.twig
Also, the custom template should be based on the views-view.html.twig template, rather than on the views-view-unformatted.html.twig template.
The following are the possible template names sorted by precedence:
[base template name]--[view machine name]--[view display id].html.twig

[base template name]--[view machine name]--[view display type].html.twig

[base template name]--[view display type].html.twig

[base template name]--[view machine name].html.twig

[base template name].html.twig

(Source: http://redcrackle.com/blog/drupal-8/theme-views-templates)


Add SQL 2014 support to activerecord-sqlserver-adapter

Question: We've be using the activerecord-sqlserver-adapter gem with sqlserver 2008 and everything works great. We just tried to deploy our Rails 3 app against a new sqlserver 2014 db and I get an error that says:
Currently, only 2005, 2008, 2010, 2011, and 2012 are supported. We got back Microsoft SQL Server 2014 - 12.0.2000.8 (X64)

A quick look at github shows that a small update was recently made to the sqlserver_adapter.rd to resolve this issue. I tried to update the gem and it turned into a bit of dependency hell and eventually looked as though I'd have to upgrade to rails 4 (which I don't particularly want to do right now) in order to get this fix.
So I thought I make my first attempt at a monkey patch and created an .rd in my initializers folder that incorporates the the changes to add sqlserver 2014 support:
module ConnectionAdapters

    class SqlServerAdapter < AbstractAdapter
      SUPPORTED_VERSIONS = [2005,2008,2010,2011,2012,2014]

      # === SQLServer Specific (DB Reflection) ======================== #

       def sqlserver_2014?
        @database_year == 2014
      end

    end
   end

My intention was to simply override the several lines of code in sqlserver_adapter.rd with change in the fix on github. However when I try to deploy, I now get an UnitializedConstant Error referring to AbstractAdapter.
How can make this patch work? Or this there a better way to accomplish this task?
Answer: I found a much better solution than a monkey patch. Turns out the guys over at activerecord-sqlserver-adapter updated the various releases so I just had to specify the version 3.2 branch with the SQLServer 2014 support fix. The following line in my gem file resolved the entire issue and we are now connecting to SqlServer '14
gem 'activerecord-sqlserver-adapter', :git => "git://github.com/rails-sqlserver/activerecord-sqlserver-adapter.git", :branch => "3-2-stable"

Answer: I have also addressed this problem with the Ruby 1.8.6 setup that I inherited.
The solution is not really as high-tech as proposed here.
The adapter interface is located at C:\ruby\lib\ruby\gems\1.8\gems\activerecord-sqlserver-adapter-2.3.4\lib\active_record\connection_adapters and is called sqlserver_adapter.rb.
I modified the following code to appear as such:
    class SQLServerAdapter < AbstractAdapter

  ADAPTER_NAME                = 'SQLServer'.freeze
  VERSION                     = '2.3.4'.freeze
  DATABASE_VERSION_REGEXP     = /Microsoft SQL Server\s+(\d{4})/
  SUPPORTED_VERSIONS          = [2000,2005,2008,2012,2016].freeze
  LIMITABLE_TYPES             = ['string','integer','float','char','nchar','varchar','nvarchar'].freeze
  LOST_CONNECTION_EXCEPTIONS  = {
    :odbc => ['ODBC::Error'],
    :ado  => []
  }
  LOST_CONNECTION_MESSAGES    = {
    :odbc => [/link failure/, /server failed/, /connection was already closed/, /invalid handle/i],
    :ado  => []
  }

The only thing I did to modify the adapter code was change [2000,2005,2008] to [2000,2005,2008,2012,2016].
I then used the ODBC Datasource Administrator (32-bit) to configure to use the "SQL Server Native Client 11.0" for the Sql Server 2016 instance.
This last step is the really important one in the ODBC adapter setup.
The "SQL Server" adapter may default to a 64-bit connection which gives the following error when trying to connect to the database:
#<ODBC::Error: S1090 (0) [Microsoft][ODBC Driver Manager] Invalid string or buffer length>.

I am retrofitting an obsolete 2008R2 server set of legacy Ruby programs running on Apache to a new Windows Server 2016 setup, and don't have the luxury of debugging the legacy Ruby code to make it work with a newer version of Ruby and Ruby on Rails.
This low-tech solution fully meets our operational needs, budget and time constraints.
Answer: I did the following with v 4.1.8:
module ActiveRecord
  module ConnectionAdapters
    class SQLServerAdapter < AbstractAdapter
      SUPPORTED_VERSIONS << 2014
      # === SQLServer Specific (DB Reflection) ======================== #

      def sqlserver_2014?
        @database_year = 2014
      end
    end
  end
end

Comment: @donfnielson, where did create the above module, can you give me the path and file name?


Drupal 7.14 on IIS 7.5, MS SQL Server 10.5

Question: I have been tasked with seeing if Drupal can be made to run on IIS (specifically, IIS 7.5 running on Windows Server 2008 R2) and MS SQL Server (2008 R2). I'm aware of Microsoft's WebPI Drupal package, but since we have an existing site which we wish to migrate to this new environment I'd prefer to add the pieces that are needed so that they can go into the source control environment with the others rather than use a black box package. I am doing the experimentation with Drupal 7.14, which is the latest release at this time.
I have got basic PHP scripts to run (Hello World, phpinfo, etc), and installed the sqlsrv driver 7.x-1.2 (recommended at the present time) into Drupal. The Drupal installation process gets as far as to the database settings screen without any complaints. However, if I select MS SQL Server as backend:

if I enter invalid database credentials I get an error back, as expected.
if I enter valid database credentials, after clicking proceed I get a HTTP 500.0 error from IIS saying about php-cgi.exe The FastCGI process exited unexpectedly.

I have enabled request tracing in IIS and found the error code GENERAL_READ_ENTITY_END Reached the end of the file. (0x80070026) in the resulting log file. Googling for the hexadecimal error code produced very little in terms of helpful information.
drupal.org reports 4772 sites reporting using the sqlsrv module, so the module obviously works. Any hints on how to get it to work, preferably other than "use the WebPI packages"?
By setting Instance MaxRequests to 1, keeping Standard Error Mode at ReturnStdErrIn500, disabling friendly errors in IIS and ditto MSIE (thanks for the link @DigitalFire which pointed me in the right direction for this), I was able to get at what I suspect is the actual command output, or at least as close to it as I can easily get in the web browser. What is shown in MSIE's "View Source" is a plain, almost-empty, boilerplate HTML document with an empty body. Before I turned off MSIE's friendly HTTP error messages (who came up with the idea of having that turned on as standard on Server, anyway?) it showed HTTP 500, so this is probably pretty close to the truth.
Using SQL Server's Profiler, I traced the database calls made and toward the end was the following, ignoring pure SELECT statements:
-- repeated a number of times
INSERT INTO system ([filename], [name], [type], [owner], [info]) VALUES (@P1, @P2, @P3, @P4, @P5)

UPDATE system SET [status]=@P1
WHERE  ([type] = @P2) AND ([name] = @P3) AND( ([status] <> @P4) OR ([status] IS NULL ) )

UPDATE system SET [bootstrap]=@P1
WHERE ( ([bootstrap] <> @P2) OR ([bootstrap] IS NULL ) )

INSERT INTO registry ([name], [type], [filename], [module], [weight]) VALUES (@P1, @P2, @P3, @P4, @P5)

The final INSERT occurs only once, with EventClass SQL:StmtRecompile. I'm not sure this helps much...
Comment: Glad I could at least point you in the right direction :]
Comment: Based on your error description, I think the problem happens during installation of the very first module, `system`.
I would fire up a debugger, start with breakpoints in `install_settings_form_submit($form, &$form_state)` and `install_system_module(&$install_state)`. One of these two should land you near whatever actually goes wrong.
Comment: @Letharion, Unfortunately the only debugging environment I have set up is on a different VM, and runs on Apache no less, so I have nothing ready to use for such a purpose. If no one else has posted anything more concrete by tomorrow I probably will look into it, but a way to troubleshoot this that doesn't include installing a development environment would be nice. Failing that, you wouldn't happen to have any good links relating to debugging PHP on IIS?
Answer: Try commenting out extension=php_gd.dll in your php.ini file and try again. I found this article in which the OP had a similar problem.
Comment: The only seemingly relevant extension is `php_gd2.dll`, and commenting that one out causes Drupal to complain about the `gd` library not being installed.
Answer: After a lot more digging both by myself and a colleague, we finally ran across what appears to be the answer. In a TechNet Forum post in the thread MSVCR90 fault with Sql Server driver, Pierre Couzy mentioned the issue Error when executing empty queries in PHP 5.3.8 on drupal.org. Attached to that incident report is a suggested patch for the sqlsrv module which changes the substitution for RELEASE SAVEPOINT to a non-empty SQL statement in the file sqlsrv/database.inc.
What's interesting is that it looks like this fix is included in mainline 7.x-1.2, whereas both I and my colleague (downloading and installing the module independently over the last few days) apparently were running against version 7.x-1.1 of the sqlsrv module. It sincerely beats me how that happened (I was sure I'd downloaded 7.x-1.2), but manually applying the patch to the version that we had downloaded seems to have resolved the issue, and actually running 7.x-1.2 shows the same result.
Hopefully this keeps somebody from beating their head against this same problem.
Answer: The first thing I was going to ask was what version of PHP and PHP to SQL driver you were using. We were receiving errors like this when using PHP 2.7 and PHP to SQL 2.x. I recommend getting the PHP drivers from Microsoft through the Web Platform installer and getting the latest version of Drupal and the MS SQL driver from drupal.org. Also if you change the MS SQL driver you must run update.php so the changes can be picked up. I highly recommend using Wincache as it will help your performance and can possibly be used as an alternative query backend. Drupal is kind of a database hog so if you are not using an alternative query backend and Entity Cache then you will most likely have performance issues.


application crashed when open camera

Question: I'm using https://github.com/ivpusic/react-native-image-crop-picker in my app, when camera opened I can take the picture but when I want to choose it the app crashes and sometimes it's crashed once the camera is opened, but it works when I use debugging mode instead on android works very well in the all cases.
when I run the project from xcode works fine but not with react-native run-ios --device "myDeviceName"
also with higher version ios like 13 it works well

react-native-image-crop-picker ^0.23.1
react-native v0.59.0
Ios 9.3.6

Component when I call open camera:
ImagePicker.openCamera({
          cropping: true,
          width: 500,
          height: 500,
          includeExif: true,
          includeBase64: true,
          mediaType:"photo"
        })
          .then(image => {
            this.setState({
              cameraOpened: false
            });
            this.props.navigation.navigate("Preview", {
              picture: image,
              type: this.type,
              state: this.props.navigation.state,
              userId: this.userId
            });
          })
          .catch(e => {
            console.log(e);
            this.setState({
              cameraOpened: false
            });
            this.props.navigation.goBack();
          });
      }

Preview.js:
ImageEditor.cropImage(
          this.picture.path,
          {
            offset: { x: 0, y: 0 },
            size: { width: 500, height: 500 },
            displaySize: { width: 500, height: 500 }
          },
          res => {
            // Change it to res
            this._uploadPicture(this.picture.path, response => {
              if (response.status == 200) {
                this.props.savePicture(this.picture);
                this.setState(
                  {
                    loading: false
                  },
                  () => {
                    this.navigation.goBack(key);
                  }
                );
              } else {
                alert(response);
              }
            });
          },
          err => {
            this.setState({
              loading: false
            });
            alert(err);
          }
        );

Any idea ? Thank you
Answer: A little bit later, but for futures searchers:
I had the same issue and even after added in Info.plist the
NSPhotoLibraryAddUsageDescription, NSPhotoLibraryUsageDescription, NSMicrophoneUsageDescription, NSCameraUsageDescription, I got an email from Apple Store connect saying about "Missing Purpose String in Info.plist".
This time I  missed the "NSAppleMusicUsageDescription". Im not sure why I need this property since I've no music in my app but its what worked for me.
Comment: Did not help to me :(

application crashed when open camera


Erro ao Salvar alterações EF

Question: Boa noite,
Ao tentar inserir os dados na tabela me da o erro "An error occurred while updating the entries. See the inner exception for details.".
var db = new Repositorio();
            var perfilPessoaDB = Objeto.ConverterParaEntidade<PerfilPessoaFisica, tbPerfilPessoaFisica>(perfilPessoa);
            perfilPessoaDB.tbPerfilPessoaFisicaObjetivo = Objeto.ConverterParaEntidade<PerfilPessoaFisicaObjetivo, tbPerfilPessoaFisicaObjetivo>(perfilPessoa.Objetivo);
            perfilPessoaDB.tbPerfilPessoaFisicaObjetivoS = Objeto.ConverterParaEntidade<PerfilPessoaFisicaObjetivo, tbPerfilPessoaFisicaObjetivo>(perfilPessoa.ObjetivoSecundario);
            perfilPessoaDB.TbUsuario = Objeto.ConverterParaEntidade<Usuario, TbUsuario>(perfilPessoa.Alterador);
            db.tbPerfilPessoaFisica.Add(perfilPessoaDB);
            db.SaveChanges();

Comment: possível duplicata de [Como corrigir o EntityValidationErrors](http://pt.stackoverflow.com/questions/17644/como-corrigir-o-entityvalidationerrors)
Comment: Não sei se é duplicata de fato.
Answer: Provavelmente o erro esta ocorrendo por que alguma propriedade não deve está preenchida.
Utiliza try catch para debugar e encontrar o erro:
try
            {
                db.SaveChanges();
            }
            catch (DbEntityValidationException dbEx)
            {
                foreach (var validationErrors in dbEx.EntityValidationErrors)
                {
                    foreach (var validationError in validationErrors.ValidationErrors)
                    {
                        Debug.WriteLine("Property: {0} Error: {1}", validationError.PropertyName, validationError.ErrorMessage);
                    }
                }
            }

Answer: Quando a exceção estourar no Visual Studio, clique em View Detail.... Uma janela irá abrir na qual você pode expandir o nó Inner Exception.

Erro ao Salvar alterações EF


Why isn't there a person class at ILSVRC'12 classification task?

Question: Recently I played a bit around with the Caffe Classification Demo and recognized bad classification results with images of people. I guessed the model is trained with the ILSVRC'12 classification dataset. When looking at it in more detail I realized there isn't a human/person class. The most related classes are just "scuba diver", "groom" and "ballplayer, baseball player".
So why there are added many classes for fine-grained classification, but there isn't a simple person class? I couldn't find a direct explanation at the ImageNet paper. Isn't it impractical for many applications?
Comment: Unless the researchers involved in the project happen to stop by, we can only speculate. You should email the authors.
Answer: I think there are two likely reasons (but I'd be delighted if you email the researchers!):
Firstly, categories in underlying ImageNet dataset are derived from WordNet, an older NLP dataset of basically synonyms (synsets). WordNet consists of about 150,000 words arranged in an essentially hierarchical order (you can browse WordNet here).  Part of the goal of the creation of the ImageNet was not just to build a very large image dataset but also to have the images arranged in a dense semantic hierarchy with around 500-1000 images per leaf node in the hierarchy. ImageNet was originally based on the vehicle and mammal subtrees.  If you browse through WordNet, I think it becomes clear that not all the trees are related to objects with distinct visual properties. If you look at the synset "firemen", you'll see it's part of the follow pretty abstract hierarchy:

fireman -> defender -> preserver

There is an hierarchy for person in ImageNet, but I think it suffers from the same problem of being quite abstract, whereas the hierarchy for dogs is a little more concrete.  You can find more information in the paper by Deng et al. 2009 "ImageNet: A Large-Scale Hierarchical Image Database" on the ImageNet dataset (you are citing the paper about ILSVRC which is different). That's my guess though about why persons was not included in ILSVRC.
Secondly, working with images and video of people is almost it's own subdiscipline in computer vision. There are specialised models and subtasks in like face detection, activity recognition, pedestrian detection, and eye tracking. If the researchers were interested more generally in object recognition problem, they might not want deal with all the complications of dealing with people.
Comment: I got an answer. The person class isn't included to keep the categories (mostly) mutually exclusive.
Comment: I'm aware about the difference between ImageNet and ILSVRC. So I wondered why they didn't simply take the "person" class from ImageNet into the competition. Your explanation sounds logical to me. I will try my luck and contact the researchers.
Comment: Oh that's good to know, thank you! It's a shame the question has been put on hold otherwise you should post that as  the answer to your question.


Why the do while loop is not working properly here?

Question: #include<stdio.h>
#include<string.h>

int main()
{
        char letter;
        char answer[10];
        char affirmation[10] = "yes";

        do
        {
                printf("Enter a character: \n");
                scanf("%c",&letter);

                if(letter>=65 && letter<=90)
                {
                        printf("UPPERCASE! \n");
                }
                else if(letter>=97 && letter<=122)
                {
                        printf("LOWERCASE \n");
                }
                else
                {
                        printf("Not an Alphabet \n");
                }

                printf("Wanna try for another Character ? [yes/no] \n");
                scanf("%s",&answer);

        }
        while(strcmp(affirmation,answer) == 0);

        return 0;
}

I was trying to make a program which would tell if the character entered is uppercase or lowercase and then ask if the user wants to try again for another character. But it is not reiterating in the desired way.Sometimes it says "terminated with signal 11".
Here it is.And sometimes it acts completely different.
See here.What should be done in order to get desired results?
Comment: `if(letter>='A' && letter<='Z')` is much much more readable.
Comment: this will help fix your second problem https://stackoverflow.com/questions/29775323/scanf-function-seems-to-be-skipped-in-c
Comment: change `scanf("%s",&answer);` --> `scanf("%s",answer);` https://www.geeksforgeeks.org/not-used-strings-scanf-function/
Comment: After those changes, unable to reproduce the segfault (and don't see how that could've happened to begin with unless you're fuzzing the input).
Answer: You should include a space before %c in scanf(" %c",&letter);. The space before %c is needed to skip the white space in buffer memory. Take a look at this post for more information. https://www.codesdope.com/discussion/why-are-you-using-a-space-before-c-in-scanf-c-ch/.
Then you should also change scanf("%s",&answer); to scanf("%s",answer); because an array is already a pointer to its first element. Take a look at Reading a string with scanf.
#include<stdio.h>
#include<string.h>

int main()
{
        char letter;
        char answer[10];
        char affirmation[10] = "yes";

        do
        {
                printf("Enter a character: \n");
                scanf(" %c",&letter);

                if(letter>=65 && letter<=90)
                {
                        printf("UPPERCASE! \n");
                }
                else if(letter>=97 && letter<=122)
                {
                        printf("LOWERCASE \n");
                }
                else
                {
                        printf("Not an Alphabet \n");
                }

                printf("Wanna try for another Character ? [yes/no] \n");
                scanf("%s",answer);

        }
        while(strcmp(affirmation,answer) == 0);

        return 0;
}

Comment: Bonus points: `scanf("%9s",answer);` to ensure you do not overwrite your array bounds. When reading into an array with `"%s"` unless a *field-width* modifier is used, `scanf()` is no safer than `gets()` -- see [Why gets() is so dangerous it should never be used!](https://stackoverflow.com/q/1694036/3422102) A citation to why answer is already a pointer is [C11 Standard - 184.108.40.206 Other Operands - Lvalues, arrays, and function designators(p3)](http://port70.net/~nsz/c/c11/n1570.html#184.108.40.206p3)


Show multiple select dropdown with checkboxes value in the text

Question: I have a problem to show multiple select dropdown with checkboxes value in the text.
Below is sample code:

<select id="mySelect" multiple class="form-control"  onchange="myFunction()">
 <option value="" selected>Sila Pilih</option>
<option value="Kakitangan MPK">Kakitangan MPK</option>
<option value="Ahli Majlis">Ahli Majlis</option>
                                </select>

Now the output like below the picture:

Actually, I want the output like below the picture:

Hope someone can guide me to solve this problem. Thanks.
Answer: If you have all the required libraries in place then you can use onChange like the following way:

$('select[multiple]').multiselect({
  columns: 2,
  placeholder: 'Select options',
  onChange: function(element, checked) {
    var options = $('#mySelect option:selected');
    var selected = [];
    $(options).each(function(index, brand){
        selected.push($(this).val());
    });
    $('#demo').text("You selected: " + selected.join(','));
  }
});

$('#demo').text("You selected: "+$('#mySelect').val());// to show the selected on page load
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-multiselect/0.9.13/css/bootstrap-multiselect.css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

<select id="mySelect" multiple class="form-control">
  <option value="Sila Pilih" selected>Sila Pilih</option>
  <option value="Kakitangan MPK">Kakitangan MPK</option>
  <option value="Ahli Majlis">Ahli Majlis</option>
</select>


Prove that the sum of the infima is smaller than the infimum of the sum

Question: I'm trying to prove the following inequality:

Let $f$ and $g$ be bounded real-valued functions with the same domain. Prove the following:
$$\inf(f) + \inf(g) \leqslant \inf(f+g).$$

I thought I had proved it, but I made the erroneous assumption that $\inf(f+g)$ can always be expressed in the form $(f+g)(x_1)$ for some $x_1$, which is not necessarily true.
Answer: Let $h=f+g$ and $y\gt\inf h$, then there exists $x$ such that $y\geqslant h(x)=f(x)+g(x)$. But $f(x)\geqslant\inf f$ and $g(x)\geqslant\inf g$ hence $y\geqslant\inf f+\inf g$.
Every $y\gt\inf h$ is such that $y\geqslant\inf f+\inf g$. Hence $\varepsilon+\inf h\geqslant\inf f+\inf g$, for every $\varepsilon\gt0$. In particular, $\inf\{\varepsilon+\inf h\mid\varepsilon\gt0\}\geqslant\inf f+\inf g$. The infimum of the set on the LHS is $\inf h$ hence all this proves that $\inf h\geqslant\inf f+\inf g$.
Likewise, $\sup h\leqslant\sup f+\sup g$.
Answer: It seems that we can argue in the following simple way and no need to introduce $\varepsilon$: Denote
$a=\inf(f)$ and $b=\inf(g)$. Note that for each $x$ in the domain,
$a\leq f(x)$ and $b\leq g(x)$. Therefore, $a+b\leq f(x)+g(x).$
This shows that $a+b$ is a lower bound of $\{(f+g)(y)\mid y\in\mbox{Domain}\}$
and hence $a+b\leq\inf(f+g)$.
Answer: Another attempt:
Let $a:=\inf (g)$, then $a \le g$, and
$f+a \le f +g$.
Hence
$\inf (f +a) \le \inf (f+g).$
Since $a$ is fixed,
$\inf (f+a)= \inf (f) + a =$
$\inf (f)+ \inf(g) \le \inf (f+g)$.
Answer: The other answers already proved that $\inf(f + g) \ge \inf(f) + \inf(g)$, but for those who are curious to see an actual example of how $\inf(f + g) \gt \inf(f) + \inf(g)$ within some interval, I thought about the following one:
Let's consider the interval $[0,1]$. Let $f(x) = x + 1$ and $g(x)=\begin{cases}1 & x = 0\\ 0 & x \neq 0 \\ \end{cases}$.
Then in this interval we see that $\inf(f) = 1$, $\inf(g) = 0$ and therefore $\inf(f) + \inf(g) = 1$. Nevertheless, $f(x) + g(x) = 2$ when $x = 0$ and $f(x) + g(x) > 1$ otherwise (for instance, if $x = 0.001$, then $f(x) + g(x) = 1.001)$, and therefore $\inf(f + g) \gt \inf(f) + \inf(g)$ for all $x \in [0, 1]$.


RenderTransform without affecting children possibly Inverse

Question: I'm resizing a canvas with touch events as follows:
<code>e.Handled = true;
var transformation = MyCanvas.RenderTransform as MatrixTransform;
var matrix = transformation == null ? Matrix.Identity :transformation.Matrix;

matrix.ScaleAt(e.DeltaManipulation.Scale.X,
               e.DeltaManipulation.Scale.Y,
               e.ManipulationOrigin.X,
               e.ManipulationOrigin.Y);

MyCanvas.RenderTransform = new MatrixTransform(matrix);
</code>
The canvas has several child canvasses. I don't want to resize them and in fact need them to go smaller. So looked at RenderTransform.Inverse but am not having any joy.
Comment: What do you want to happen to the child canvasses when you resize the parent one? Do you want them to move to keep their relative positions or just keep the same absolute positions?
Comment: They need to move to keep relative but not resize.
Answer: EDIT after reading the comment below
In that case of a chart you might want to redraw the chart with different axis ranges. A RenderTransform might be not accurate enough and indeed you will have to scale back everything else (axis, labels, gridlines,...)
previous answer, still valid
You will have to iterate through the child canvases and scale them individually. As far as I know there is no build in support for what you want.
You will have to apply both the inverse scale transformation to negate the parent's resize and a scale transformation that will make them smaller.
Post the code you are using to get more detailed help and or feedback.
Comment: Thanks Erno, I'll give that a go. I've create a sort of scatter chart and on zooming want to increase the gap between them for legibility.
Comment: Ah, in that case you might want to redraw the chart with different axis ranges. A RenderTransform might be not accurate enough and indeed you will have to scale back everything else (axis, labels, gridlines,...)
Comment: Yeah it's a very rough chart on a Pixelsense device so only has a single Y axis which is basically 0 (above positive/below negative)
Comment: Went with this solution although I have no doubt that Danny Varod's solution below will also work.
Answer: You can create a custom canvas by inheriting from Panel with

A new dependency property: NonInheritableScale
A binding between bind the transform's scale to the NonInhertiableScale property
overrides of the MeasureOverride() and ArrangeOverride() methods,
so that the take 1.0/NonInhertiableScale.X and 1.0/NonInhertiableScale.Y into account during the layout.

Here is an article on creating custom WPF panels that might help you (a search result, haven't read it).


Simplifying $ \;x({y^{3}}/{x^{4}})^{1/4}$

Question: I'm a little unsure how to simplify the following expression:
$$
x\left(\frac{y^{3}}{x^{4}}\right)^{1/4}
$$
According to the answer, this should get you $\;\; x y^{3/4} x^{-1} = y^{3/4} $.
My intuition tells me that when we bring up $ \,x^{4} \,$ from the denominator, we get $ \,x^{-4}\, $ (with a negative power). In general, I'm unsure how $ x $ on the outside should multiply with what is inside the brackets. (Following BEDMAS, brackets should go first, right?)
Comment: Please use LaTeX formatting next time.
Comment: I would also suggest using \frac instead of /.
Answer: $$
\begin{align}
x\left(\frac{y^3}{x^4}\right)^{1/4}  \\ \\
& = x(y^3x^{-4})^{1/4} \\ \\
& = xy^{3(1/4)}x^{-4(1/4)} \\ \\
& = xy^{3/4}x^{-1} \\ \\
& = xx^{-1}y^{3/4} \\ \\
& = \frac xx (y^{3/4}) \\ \\
& = y^{3/4} \\ \\
\end{align}
$$
Comment: so the y^3 multiplies with ^-4 to give you 3/4? What about the remaining X on the outside or the ^1\4 power ?
Comment: No, the $y^3$ becomes $y^{3(1/4)} = y^{3/4}$ and $x^{-4}$ becomes $x^{-4(1/4)} = x^{-1}$ I edited to make this clearer to you.
Comment: Does that make sense now? You distribute the exponent $1/4$ over $y^3x^{-4}$
Comment: can anyone explain why you can gather powers like in step 2? Is it because of commutivity ? (sorry laggy internet on this one)
Comment: Do you mean placing x next to $x^{−1}$? Yes, multiplication is commutative, so you can rearrange/commute factors. ...Perhaps you mean why $(y^3x^{-4})^{1/4} = y^{3/4}x^{-4/4} = y^{3/4}x^{-1}\,$? Because one of the laws of exponents is $(ab)^c = a^cb^c$. So $(a^db^e)^c = a^{c \cdot d}b^{c\cdot e}$
Comment: I meant the latter -  why is c not applicable to all terms? a^{d*c}*b^{c*e}?
Comment: It is applicable to all terms: as I wrote: $$(a^db^e)^c = a^{cd}b^{ce} = a^{dc}b^{ce}$$
Comment: So $$(y^3x^{-4})^{1/4} = y^{3(1/4)}x^{-4(1/4)} = y^{3/4}x^{-1}$$ The scope of the exponent $1/4$ is all and only the factors in parentheses. So we multiply $y^{3/4}x^{-1}\;$ by $x:\quad$ $x(y^{3/4}x^{-1}) = xy^{3/4}x^{-1} = x x^{-1}y^{3/4} = \dfrac xx y^{3/4} = y^{3/4}$
Comment: makes sense thank you :)
Answer: You have
$$ x\Bigl(\frac{y^3}{x^4}\Bigr)^{\frac{1}{4}}$$
You can leave out the braces, if you apply the exponent $\frac14$ to each, nominator and denominator. Thus
$$ x\Bigl(\frac{y^3}{x^4}\Bigr)^{\frac{1}{4}}=x\frac{y^\frac{3}{4}}{x^1}$$
Now as $\frac{1}{x} = x^{-1}$ you get
$$ x\Bigl(\frac{y^3}{x^4}\Bigr)^{\frac{1}{4}}=x{y^\frac{3}{4}}{x^{-1}}=x^{1-1} y^\frac34= y^\frac34$$
Comment: I wouldn't say, that my solution is better than the one of @amWhy. Note, that he is more detailed and really takes his time with his comments.
Comment: x^1/4*X^4 should be x(^1)? if I'm reading that right ? if so this solution is more elegant.
Comment: No $x^\frac14 \cdot x^4 = x^{\frac14+4}=x^\frac{17}{4}$. But $\bigl(x^\frac14 \bigr)^{4} = x^{\frac14\cdot 4} = x^1 = x$.
Comment: good solution anyway. thanks, this is much more straightforward.


How to display a button with "markup"?

Question: I created a custom module and in the code below the button is not rendered, there is only the text :
$form = ['#markup' => '<button type="button" class="btn btn-success" disabled="disabled">Product unavailable</button>'];

How to display the button?
<?php

/**
 * @file
 * Hook implementations of commerce_add_to_cart_access module.
 */

use Drupal\commerce_product\Entity\ProductType;
use Drupal\commerce_product\Entity\ProductVariationType;
use Drupal\Core\Entity\Display\EntityViewDisplayInterface;
use Drupal\Core\Entity\EntityInterface;
use Drupal\Core\Url;

function commerce_add_to_cart_access_form_commerce_order_item_add_to_cart_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {
  // Your original code to get store owner.
  $current_store = \Drupal::service('commerce_store.current_store');
  $owner = $current_store->getStore()->getOwner();
  if (!$owner->hasRole('marchand_premium')) {
    // Overwrite the whole form markup!
    $form = ['#markup' => '<button type="button" class="btn btn-success" disabled="disabled">Product unavailable</button>'];
  }
}

Comment: if you change it to `'#markup' => 'Hello World'` do you see the text?
Comment: @NoSssweat  Yes it works, but I try to display the text in a button
Comment: If you remove/disable all CSS styles using [web developer](https://chrome.google.com/webstore/detail/web-developer/bfbameneiokkgbdmiekhjnmfkcnldhhm), or using some other tool, do you see the `Product unavailable` text?
Answer: You can use the inline_template to solve the problem:
// Delete the other button.
unset($form);
$form['submit'] = [
  '#type' => 'inline_template',
  '#template' => '<button type="button" class="btn btn-success" disabled="disabled">Product unavailable</button>',
];

Comment: Comments are not for extended discussion; this conversation has been [moved to chat](https://chat.stackexchange.com/rooms/85155/discussion-on-answer-by-adrian-cid-almaguer-how-to-display-a-button-with-markup).
Answer: I don't know much about commerce, but I think you need to output a render array rather than actual HTML.
So replace $form = ['#markup' ... with something like the following:
// Add the new button to the form
$form['button'] = [
  '#type' => 'button',
  '#value' => t('Product unavailable'),
  '#attributes' => [
    'class' => ['btn', 'btn-success'],
    'disabled' => 'disabled'
  ],
];

See this link for what you can render with Drupal https://api.drupal.org/api/drupal/namespace/Drupal%21Core%21Render%21Element/8.5.x
Comment: Thanks, with your code, the button is displayed but the module is broken. This answer does not work anymore if I apply your code https://drupal.stackexchange.com/questions/271623/how-to-enable-or-disable-the-add-to-cart-button-for-products-based-on-the-role it shows the button "Add to cart" + the button ''Product unavailable"
Comment: Sorry not sure why the module would break with the above code, but to get rid of the duplicate button you can unset it - `unset(form['existing_add_to_cart_button'])`

How to display a button with “markup”?


I have a situation with OSPF and EIGRP which requires a specific trace route. How can I get this to work?

Question: Objective: Traffic should follow from R1->R3->R4->R6->R7->R8->R9->R10
In traceroute/extended ping :
188.8.131.52,) (
220.127.116.11,
184.108.40.206,
18.104.22.168,
126.96.36.199,
18.104.22.168,
220.127.116.11.
What I did is filter R8,9,10 with route-map and distribute-lists, so that traffic goes from R6 to R7 but it doesn't. It just goes from R6 to 220.127.116.11 and 220.127.116.11. Can anyone help this out?
Image:
Comment: Is this really a business scenario? It looks more like a course homework.
Comment: The world doesn't need people with degrees who don't know anything. If you want a certificate, work hard to have one. Do your homework yourself. This is the only way to learn something.
Answer: What you are asking is contrary to the nature of routing protocols like OSPF or EIGRP.
Routing protocols are not intended for creating specific fixed routes but for determining routes dynamically from the current network situation. If you need a specific route you already know, configure it as a static route.
Comment: Thanks but I'm sure we can alter the routing paths between them. I just can't work it out in that order.
Comment: Sure, you could go and tweak the metrics until you get the results you want, but you'd be putting the cart before the horse. I cannot imagine a business scenario where that approach would make any sense.
Answer: You can adjust the routing metric (cost) to make your desired route preferred.
Comment: I tried changing AD, cost but the packet from 184.108.40.206 is moving to 126.96.36.199 and then to 18.104.22.168. Here we want it to move from 188.8.131.52-22.214.171.124-22.214.171.124 and then to 220.127.116.11. Can you help with it ?
Comment: AD is not the metric.  It only determines which routing protocol is preferred.  You want to change the OSPF cost.  Make it lower on preferred links.
Comment: Thank you for that. Will try and get back to you.
Comment: Hello there, I tried changing metrics on the routers but still, I could only get it to work up to 220.127.116.11 in the order i.e, 184.108.40.206 - 18.104.22.168 - 184.108.40.206. After that, it just comes through 22.214.171.124 to 18.104.22.168 again. Any idea of what to do?


The Normal Vector of two 3D vector's Cross Product

Question: I am wondering why the cross product of two vectors in $\mathbb{R}^3$ would get the Normal Vector of the plane generated by them? I know it is the definition, but I am still wondering why we can get it just by calculating their cross product.
Is there any proof?

This is cross product of two vectors in $\mathbb{R}^3$ :
$$(a,b,c) \times (d,e,f) = (bf-ce, cd-af, ae-bd)$$
Comment: You can calculate *dot product* of $(a,b,c)\times(e,f,g)$ in each of the initial vectors and see that it must be zero. The cross product is the unique vector with this property up to a scalar coefficient.
Answer: When you believe that the scalar product of two non-zero vectors is 0 exactly when they are perpendicular, then its easy. You just have to evaluate:
$\mathbf{a}\cdot(\mathbf{b} \times \mathbf{c})$
for either
$\mathbf{a} = \mathbf{b}$ or  $\mathbf{a} = \mathbf{c}$. You can do this using the coordinate expansions you mentioned above or using algebraic properties such as the triplet product expansion of the cross product/scalar product together with the anti-commutativity of the cross product $\mathbf{a} \times \mathbf{b} = - \mathbf{b} \times \mathbf{a}$ (and here setting $\mathbf{a} = \mathbf{b}$, this must then be the $\mathbf{0}$ vector).


Preciso abrir uma conexão com o MySQL para cada consulta em PHP?

Question: Preciso pegar diversas variáveis baseadas no meu banco para montar um dashboard completo. Por exemplo, preciso do número de linhas, do valor médio de um determinado campo e desse mesmo valor médio só que por UF.
A estratégia que tem funcionado comigo é a de pedir o acesso por meio da função msqli_connect() e logo depois da solicitação atendida eu fecho com msqli_close(). Com isso estou conseguindo só uma ação, ou seja, só a média, ou só a lista de todos os usuários, ou só a soma. Não consegui, por exemplo, conseguir a média e a soma dentro de uma mesma solicitação. É assim mesmo? como posso pedir mais dados em uma mesma solicitação?
O código que venho usando é:
// Para conseguir a média
    $conn = mysqli_connect($servername, $username, $password, $dbname);
    if (!$conn) {
        die("Connection failed: " . mysqli_connect_error());
    }

    $sql = "SELECT AVG(q1) AS avg FROM nome_da_tabela";
    $result = mysqli_query($conn, $sql);

    if (mysqli_num_rows($result) > 0) {
        // output data of each row
        while($row = mysqli_fetch_assoc($result)) {
            echo $row["avg"];
        }
    } else {
        echo "0 results";
    }

    mysqli_close($conn);

    // agora para conseguir a soma:

    $conn = mysqli_connect($servername, $username, $password, $dbname);
    if (!$conn) {
        die("Connection failed: " . mysqli_connect_error());
    }

    $sql = "SELECT SUM(q1) AS soma FROM nome_da_tabela";
    $result = mysqli_query($conn, $sql);

    if (mysqli_num_rows($result) > 0) {
        // output data of each row
        while($row = mysqli_fetch_assoc($result)) {
            echo $row["soma"];
        }
    } else {
        echo "0 results";
    }

    mysqli_close($conn);

Comment: Alguma das respostas resolveu sua dúvida? Acha que pode aceitar uma delas? Veja o [tour] como fazer isso, se ainda não o fez. Você ajudaria a comunidade identificando qual foi a melhor solução para você. Pode aceitar apenas uma delas. Mas pode votar em qualquer pergunta ou resposta que achar útil no site todo
Answer: Não, de preferência não deve fazer isto, em PHP fica até fácil controlar isso porque em quase 100% do casos está só rodando um script efêmero, então o limite é basicamente a duração dele, pode ter alguma exceção, mas quase sempre isto é o adequado.
Não é o fim do mundo fazer diferente, se fizer certo, o que complica mais, mas não tem vantagem, inclusive se isso fosse bom nem precisaria exigir abrir e fechar, toda consulta abriria e fecharia a conexão por conta própria. O caso mostrado na pergunta claramente é errado, mesmo que funcione.
Por outro lado a pergunta tem uma outra questão importante que é o abuso de consultas quando só uma resolve. Esta sim causa bastante problema porque entra em contato com o servidor duas vezes e tem processamento quase repetido para fazer a mesma coisa. Este é um caso que não só deveria ter apenas uma conexão como uma só consulta. Ela pede duas coisas na mesma tabela sob as mesmas condições, então faz tudo de uma vez:
SELECT AVG(q1) AS avg, SUM(q1) AS soma FROM nome_da_tabela

Coloquei no GitHub para referência futura.
Aí pega os dois campos retornados no mesmo processamento. Este código todo pode ser reduzindo para pouco mais de meia dúzia de linhas, o que fica bem mais simples.
Answer: Oi, Pedro, tudo bem?
Você pode criar um arquivo para conter a conexão com o MySQL e incorporar ele dentro deste. Desta forma, a conexão com o banco de dados já vai estar aberta e você poderá fazer suas consultas. Finalize com o mysqli_close($conn) apenas quando já tiver concluído todas as consultas.
Ex:
Arquivo: connection.php
.
$servername = "";
$username= "";
$password = "";
$dbname= "";

$conn = mysqli_connect($servername, $username, $password, $dbname);
if (!$conn) {
    die("Connection failed: " . mysqli_connect_error());
}

Com isso, você pode fazer um include desse arquivo em qualquer página e fazer as consultas, com uma única conexão. ;)
Espero ter ajudado.
Comment: Pessoalmente acho errado abrir conexões sem necessidade, colocar um header com msqli_connect para abrir conexões deliberadamente é o mesmo que consumir algo até quando não precisa, nem toda página vai ter queries para serem executadas, logo manter uma conexão aberta seria consumir mais do servidor de banco. Inclusive tive um problema semelhante, sempre ultrapassava de 150 conexões no banco, o que fazia ou o banco ficar lento ou cair, quando mudei a abordagem, só conectar se for executar uma query ou mais, caiu o numero de conexões para entre 1 e 15 por minuto, e o banco nunca mais caiu.
Comment: @GuilhermeNascimento, realmente parece uma forma mais aplicada de se utilizar. Obrigado pela explicação e por me ensinar algo novo. rs
Comment: @GuilhermeNascimento, entendi seu ponto de vista. Mas a ideia não é chamar a conexão em todas as páginas e sim em todas as quais farão de fato as requisições. Basicamente estou apenas separando o arquivo de conexão e chamando quando necessário. Já desenvolvi e acompanhei diversos projetos que usam dessa forma e nunca vi problemas com conexões em excesso, até porque ela sempre é encerrada logo após a consulta. Talvez essa não seja realmente a melhor forma de usar, mas comigo sempre deu certo. rs
Comment: @ClebertFigueiredo sem entrar na discussão se está certo, mas pegando no ponto "eu já participei de projetos que fazem assim" é um fato recorrente na nossa indústria. Quase ninguém sabe fazer direito, quase todo mundo "aprende" reproduzindo o que outra pessoa faz, que aprendeu do mesmo jeito e em geral pegam sempre alguém que não sabia o que estava fazendo, portanto todo mundo aprende errado e acha que está fazendo certo, e chegamos no estado lastimável atual onde quase tudo é inseguro, lento e cheio de outras falhas, e as pessoas nem percebem o quanto estão fazendo algo ruim, porque é vicioso
Comment: Ainda sim isto ai não tem controle, teria mais sentido colocar a conexão em static numa hipotética função chamada `function query($query) { static $conn; if (!$conn) { $conn = mysqli_connect(HOST, ....); } return mysqli_query($query);  }`, pq ai sim teria maior garantia de conectar só quando realmente uma query for usada. Eu já debati muito este assunto aqui no site e no chat do site, porque a maioria das pessoas não entendem os gargalos que podem sofrer com banco de dados e geralmente não sabem o que estão fazendo.
Comment: @Maniero, isso é verdade. Acaba que as pessoas utilizam algo que deu certo e simplesmente por isso param ali e levam pro resto da vida.
Comment: Dá pra fazer de variaveis, maneiras, essa ai é só um exemplo ;)
Comment: A minha dúvida também ia um pouco nessa linha. Eu tentei fazer várias demandas com uma conexão só, colocando, por exemplo $sql, depois $sql2, $result, depois $result2, e só depois fechando a conexão. Mas por algum motivo isso não funciona. Só quando eu fecho a conexão e abro uma nova.  Posso fazer várias solicitações dentro de uma mesma conexão?


(php)import .sql and add columns if table exists or create new table

Question: I don't know if its possible.
I released a script version 1.0
and now I am about to release 1.2 version and I made some upgrade in database tables like change name field size or default value also added few new columns  and table then export full db to .sql file(new db).
Is it possible from PHP to import new .sql file and add new tables and also change columns structure without deleting any data from table and add new columns in existing tables?
I tried to import it but it shows this error:

ALTER TABLE table1 ADD PRIMARY KEY (id);: Multiple primary key defined

Example:
Old Database v1.0
Table 1

ID (primary key , AI)
First Name(size-50 ,default - none)
Last Name(size-50 ,default - none)
Email(size-50 ,default - none)
Password(size-50 ,default - none)

New Database v1.2
Table 1

ID (primary key , AI)
First Name(size-100 ,default - none)
Last Name(size-100 ,default - none)
Email(size-255 ,default - none)
Password(size-50 ,default - none)
Gender (size 10 , default - none)

Added Table 2

ID (primary key , AI)
coloum1 (size-100 ,default - none)
coloum2 (size-255 ,default - none)

Is it possible to import new .sql over old database without loosing any data from PHP and also add data from new database?
I done my best to explain and hope you understand.
EDIT: I use this code to import new .sql file and its not working: How do I import a .sql file in mysql database using PHP?
Comment: Yes, absolutely possible.  When you create your ALTER TABLE statements though, you should only include the changes - leave anything that already exists and doesn't need updating alone.
Answer: you get that message because column id already exist and has KEY, if its PRIMARY KEY and AUTOINCREMENTED then it can not be duplicated, try this:
ALTER TABLE Table1 ADD COLUMN Gender varchar(10) NOT NULL DEFAULT 'none';
ALTER TABLE Table2 ADD COLUMN coloum1 varchar(100) NOT NULL DEFAULT 'none';
ALTER TABLE Table2 ADD COLUMN coloum2 varchar(255) NOT NULL DEFAULT 'none';

or just import the new columns