Need to move all MOSS DBs to named instance

Question: I've been asked to move all of our SP related DBs to a new named instance on the same SQL 2005 server. I've done a content DB move before by disconnecting the content db then reconentcing to it with the new location, but I'm a bit lost on what process to follow for the SSPs, mysites, and config. From what I can tell, the general consesus is that I should create a brand new config DB and SSP and migrate the content DB over. Is this the only clean option? My biggest concern is that it took me a while to get profile imports working due to a multitude of reasons, I'd hate to go through that again.
We have 2 WFEs, 1 search/index server, and a shared clustered SQL 2005 DB on the backend.
Answer: Agent,
Generally speaking, pointing a new database instance (or instances) is a "deal breaker" when it comes to the farm.  My "fallback safe opinion" tracks with the general consensus: construct a new farm (i.e., a new configuration database), build out your SSP, and then perform content database migrations into the new farm.
Here's a tip on avoiding this (painful) process in the future: implement SQL connection aliases.  An article describing how to do this can be found here: http://decipherinfosys.wordpress.com/2007/11/26/using-a-server-alias-to-connect-to-sql-server-instances/.  Aliases are also particularly helpful from a disaster recovery perspective, as they introduce a layer of abstraction between your farm and the supporting data layer.
I haven't tried this next item, so I mention it strictly as an investigative point ... but you might be able to implement aliases in your MOSS environment now before you do a rebuild and potentially avoid it altogether.  Let's say your SQL Server is named "SQLSERVER" and you'll be going to a named instance on that server called "MOSS".  For each MOSS server:

Install SQL Client Tools
Establish an alias named "SQLSERVER" that points to the server "SQLSERVER"
Build out your named instance (SQLSERVER\MOSS) and copy over all databases for the farm to the new named instance
Switch the "SQLSERVER" alias on each MOSS server to point to "SQLSERVER\MOSS" instead of "SQLSERVER" and see what happens.

At worst, this will fail and you'll have to build out a new farm as you're expecting to do now.  At best ... you'll continue to run without a farm rebuild.
I hope this helps!
Comment: First off ... WOOT!  That's great news, Agent; I'm glad that the aliases look to be (generally) working for you.  You asked about SQL Server, aliases, and DNS.  Your comparison to the HOSTS file is on-the-mark -- The SQL client will check for a local alias match before concluding that a connection string refers to a server/host name on the network.  This behavior is specific to SQL server connection strings and database access  Non-SQL access, on the other hand, will continue to use HOSTS and DNS for the resolution of endpoints.  Aliases only affect SQL client connections.  Does that help?
Comment: You also asked about SharePoint being built to check aliases.  To be clear: this isn't a SharePoint behavior -- it's a SQL Server Client library behavior.  *Any* SQL Server connection string can use the alias you established -- not just SharePoint.  As I may have mentioned, this is commonly done for abstraction purposes to provide a certain level of location transparency to SQL operations for things like mirroring failover, DR, etc.  Aliases are also commonly leveraged to map client access to SQL Servers running/listening on non-standard (i.e., non TCP:1433) ports.
Comment: Good question.  I typically use the SQL Server Client Tools to manage aliases, so I wasn't sure about cliconfg.exe (since they aren't the same thing - but serve the same purpose).  With a little checking, it would appear that cliconfg.exe is part of MDAC's (Microsoft's Data Access Components) distribution; I based that on Dan Guzman's response in the following chain: http://www.sqlnewsgroups.net/sqlserver/t1394-server-name-problem.aspx.  Given that an MDAC distribution of *some* sort is on nearly every system these days, you're more likely than not to find it on a system regardless of MOSS.
Comment: Sorry that I didn't have a better answer for you.  The issue is specifically with SharePoint configuration databases; they maintain references to server/host names and the database server instance names.  WSS and MOSS are sensitive to environment changes for this reason.  I don't think you're completely up the river yet, though.  See if you can skirt the issue with SQL aliases (steps #1 through #4) in your current environment.  I have some hope that it'll work for you.  I would definitely like to hear how things work out.  Good luck!
Comment: I would expect a new alias to take effect immediately, but that's an educated guess.  To avoid serious problems, you'll want to ensure that farm members aren't trying to connect while aliases are being established.  The easiest way to do this would be temporarily take your SQL servers offline; alternatively, you'd need to shut down all SharePoint-related services (OSS, W3SVC, timer service, etc.) on all members.  If you have VMs, I'd recommend testing a process there first to avoid prod problems.  Your final point about aliases is accurate -- you'd be using SQLSERVER going forward.  Good luck!
Comment: Interestingly enough, I'll be in a position to test this soon myself.  I'm building a new database server for one of my farms in the next week or so, and aliases aren't in use (due to an incompatibility between their use and DPM 2007's operation).  As part of the move, I'll give this a shot (using aliases) and report my results, as well!
Comment: Sean, I made the change yesterday and looks like it worked *almost* perfectly. I'm not exactly sure what caused the connections to the DBs to fail but signs point to the DBA team not allowing one of the SP user accounts access to the config DB once I made the alias change. Once they granted access, Sharepoint access came back online!

The only thing I'm curious about is that I sort of got into it with a DBA who said that the SP server will use DNS to find the remote server and that my cliconfg settings were not right. Continuing in next comment...blasted limit
Comment: The reason he thought this was because my alias name was set to the "old" DB server name. I told him that this was the point of the alias, so that SP does not have to be changed, the server handles redirecting the connections from old server to the new.

I guess my question is, is SP built to check aliases/cliconfig first and then DNS, similar to how Windows checks the HOSTS file before hitting DNS?

Thanks again!
Comment: I guess what I meant to say was, is cliconfg a standard utility with Windows or was it installed during the MOSS install? I have a dozen or so other apps I manage but have never had a vendor or DBA suggest using this utility to manage connections. It would've made a LOT of things a hell of a lot easier for 15-20 various DB migrations we've done in the past couple of months.
Comment: Great, that answers all my questions...for now! Thanks!
Comment: Well that absolutely blows. I just don't understand why MS didn't make it as modular when it comes to the DB. I never got the chance to work with SPS 2003 but from what I understand, it was a bit more forgiving about DB moves like these. It's problematic and time consuming enough when I'm talking about my fairly small environment, but I can't imagine the hassle of something like this in much bigger environments with custom solutions, huge/multiple DBs, thousands of sites, uptime requirements, etc.

Thanks Sean, I'll also look into the aliases option, just have to talk to the DBAs about it.
Comment: Thanks for your help Sean, just a couple of other question. I understand the general concept, but how would this work while Sharepoint is running? If I add the alias to a production WFE then change the mapping to the new server, will it start connecting through the alias as soon as I press Ok or should I restart any services before/after for this switch to prevent any corruption of the content/config DBs? Also, it seems with this I won't be able to change the name of the alias for accuracy, it will have to stay SQLSERVER instead of SQLSERVER\MOSS. Not that it's a big deal for now I guess.
Comment: Thanks, I most likely will try this after business hours today. I'm sure I'll encounter some issues as I always seem to with SP, but even if it doesn't work as expected in this case, it's very nice to know about SQL aliases for future reference. I'll update this post after the switch.
Answer: I have detailed steps in a blog post on how to go about moving databases to a new database server using SQL connection aliases and I would imagine it would be of use in this scenario. Feel free to check it out at http://mossblogger.blogspot.com/2009/10/migrating-to-new-sql-server-in-moss.html and let me know if it is of any use to you.
Cheers, Benjamin Athawes.


How do I seamlessly compress the data I post to a form using C# and IIS?

Question: I have to interface with a slightly archaic system that doesn't use webservices. In order to send data to this system, I need to post an XML document into a form on the other system's website. This XML document can get very large so I would like to compress it.
The other system sits on IIS and I use C# my end. I could of course implement something that compresses the data before posting it, but that requires the other system to change so it can decompress the data. I would like to avoid changing the other system as I don't own it.
I have heard vague things about enabling compression / http 1.1 in IIS and the browser but I have no idea how to translate that to my program. Basically, is there some property I can set in my program that will make my program automatically compress the data that it is sending to IIS and for IIS to seamlessly decompress it so the receiving app doesn't even know the difference?
Here is some sample code to show roughly what I am doing;
private static void demo()
    {

        Stream myRequestStream = null;
        Stream myResponseStream = null;

        HttpWebRequest myWebRequest = (HttpWebRequest)System.Net
                              .WebRequest.Create("http://example.com");
        byte[] bytMessage = null;
        bytMessage = Encoding.ASCII.GetBytes("data=xyz");
        myWebRequest.ContentLength = bytMessage.Length;
        myWebRequest.Method = "POST";

        // Set the content type as form so that the data
        // will be posted as form
        myWebRequest.ContentType = "application/x-www-form-urlencoded";

        //Get Stream object
        myRequestStream = myWebRequest.GetRequestStream();

        //Writes a sequence of bytes to the current stream
        myRequestStream.Write(bytMessage, 0, bytMessage.Length);

        //Close stream
        myRequestStream.Close();

        WebResponse myWebResponse = myWebRequest.GetResponse();
        myResponseStream = myWebResponse.GetResponseStream();
}

"data=xyz" will actually be "data=[a several MB XML document]".
I am aware that this question may ultimately fall under the non-programming banner if this is achievable through non-programmatic means so apologies in advance.
Answer: I see no way to compress the data on one side and receiving them uncompressed on the other side without actively uncompressing the data..
Answer: No idea if this will work since all of the examples I could find were for download, but you could try using gzip to compress the data, then set the Content-Encoding header on the outgoing message to gzip.  I believe that the Length should be the length of the zipped message, although you may want to play with making it the length of the unencoded message if that doesn't work.
Good luck.
EDIT  I think the issue is whether the ISAPI filter that supports compression is ever/always/configurably invoked on upload.  I couldn't find an answer to that so I suspect that the answer is never, but you won't know until you try (or find the answer that eluded me).


How not to log URLs with recovery token using Matomo

Question: We are integrating Matomo (formerly Piwik) to monitor our application visits.
We have a page for users to recover their password, the URL looks like :
<code>https://example.com/pwdRecovery?token=ABCDEFGHIJKLMNOPQRST
</code>
Could you confirm that it is unsecure to log the URL containing the recovery token with Piwik ?
It is interesting to gets statistics on this page, that is why I do not want to remove my Matomo Tracking code here, how can I remove the confidential part of the URL in my Matomo's stats ?
Answer: Matomo (formerly Piwik) handles this for you, you just need to configure the parameters' name you want to exclude.

Login as the Super User, go to Administration > Manage Websites > Global list of Query URL parameters to exclude field.

Documented on their FAQ :

How do I exclude URL query parameters from the URLs tracked, and from Pages reports?


time derivative of discrete data in simulink

Question: I'm implementing a program in Java that was delivered in Simulink. My expertise is limited, and I'm stuck on converting a derivative block.
The simulink code applies a du/dt block to the input data. I'm doing the following in my code:
du_dt = (signal[i] - signal[i-1])/time[i];

where signal is an array of data samples, and time is an array of elapsed time (in seconds) between sample i and sample i-1.
my java program is generating much larger derivative values than my simulink program. doing some digging, i see that the simulink man8al talks about the derivative definition as
$$
y(k)=\frac{1}{\Delta t}(u(k)-u(k-1))
$$
and taking the z-transform
$$
\frac{Y(z)}{u(z)}=\frac{1-z^{-1}}{\Delta t}=\frac{z-1}{\Delta t\cdot z}
$$
my undergrad in mathematics stops short of being able to understand what the z-transform is and how to translate it into code. any help?
EDIT
Here's a link to the simulink manual page describing this:
http://www.mathworks.com/help/toolbox/simulink/slref/derivative.html
EDIT 2
As requested, here's the data of the Simulink output and mine:
0.0, 0.0
1211.4359554191567, 692.2491173823755
573.0790390610672, 859.6185585916019
346.12455869118764, 461.4994115882501
807.6239702794378, 634.5616909338439
230.74970579412505, 692.2491173823755
286.53951953053365, 401.1553273427467
519.1868380367816, 634.5616909338443
-288.43713224265656, 403.8119851397189
-57.307903906106624, 343.8474234366401
-173.06227934559388, 57.68742644853153

0   0
1.01133071339275    1.01133071339275
-1.38227619434410   -1.38227619434408
-1.43825420168704   -1.43825420168706
-0.640385232441365  -0.640385232441365
-0.157483736804270  -0.157483736804270
-1.01133071339275   -1.01133071339275
-2.92203612549265   -1.96668341944271
-3.77588310208105   1.68679338272849
-2.98846441805972   1.44870448691124
-2.96756384761120   -0.629934947217123

The first section is mine, the second is the simulink. The indices are aligned, the data is two-dimensional but the derivative is of each individual dimension (so it's like two separate data sets)
Comment: What does `i`, `signal[i]`, and `time[i]` represent? Are they scalar? Of  what type (integer, rational, complex, etc)? And are they discrete or continuous?
Comment: i is an integer index into the signal and time arrays; signal is an array of discrete signal samples, rational real numbers; time is an array of time elapsed between sample[i] and sample [i-1], in seconds.
Comment: Relevant: [wiki/Digital_Signal_Processing/Discrete_Operations#Derivatives](http://en.wikibooks.org/wiki/Digital_Signal_Processing/Discrete_Operations#Derivatives)
Comment: yes, i saw that before i came here. theoretically relevant, but definitely not what the simulink documentation is talking about
Comment: Your arrays are in time domain. You do not need the discrete Laplace transform. The [simulink page](http://www.mathworks.com/help/toolbox/simulink/slref/derivative.html) describes the discrete *time* derivative as `(signal[i] - signal[i-1])/time[i]`. Also, it describes the derivative in $z$-domain as `(singal[z] - signal[z]/z)/time[z]`. Your arrays are in time domain.
Comment: crap. then i don't know why my derivative values are about an order of magnitude larger than the simulink ones.
Comment: Can you post some of the numbers? May be there is a pattern or the difference is a certain factor/multiple.
Comment: Posted data and comments
Comment: Even more disturbing than the magnitude variance is that the signs of the two derivatives are different.
Answer: Regarding your question about implementing the z transform in code:  The z transform is a one time frame advance in the sample series.  The 1/z transform is a one time frame delay in the sample series.  So you can see directly that your java code implements ${1 - z^{-1}\over \Delta t} = {z-1\over z \Delta t}$.  The ${1\over z}$ transform is easy to implement in computer code.  Just retain the signal value from the prior time frame.  The only problem is in deciding how to initialize the prior frame value for the first call.  On the first frame, it is normally best to initialize first-frame prior values as though the signal has been steady.  That avoids initial transients that may take a long time to die out.  So your Java code would start with signal[0] = signal[1]; More complicated Tustin transformations that use z would require solving for the correct signal prior values that the first frame should use for a steady state initialization.
Answer: The simple command

du_dt = (signal[i] - signal[i-1])/time[i];

is a correct translation of time derivative. One should be aware, though, that this approach greatly amplifies noise. Several noise-robust differentiators are described by Pavel Holoborodko.
Looking at the output of Java, I conclude that the input was not the same in both columns. Yet, the simulink output is the same in both columns most of the time. This suggests that two programs do not really do the same thing. There is not enough information to find exactly what the second one is doing.
But there is something notable in rows 5-6 of java output:
807.6239702794378, 634.5616909338439
230.74970579412505, 692.2491173823755

Namely,
807.6239702794378 - 230.74970579412505 = 576.87426448531275
634.5616909338439 - 692.2491173823755 = -57.6874264485316

There may be some sign and order-of-magnitude issues here.


how to dump mysql database if it cannot create a tcp ip socket (or how to fix it)

Question: while trying to run mysql/mysqldump i get an error
"Can't create TCP/IP socket(10106) when trying to connect"
is it possible to fix it? or is it possible to make a backup of mysql dbs in this situation somehow? what if i copy paste whole mysql install on another computer? (i know it's a wrong way but if it's the only way..)
why i need it is because my win xp installation got broken and i want to reinstall it - i cannot start apache(alloc_listener:failed to get a socket for 127.0.0.1) and connect to internet anymore (wireless connection constantly says it cannot renew ip)
Answer: shutdown mysql and just take backup of mysql database files - to be on the safe side take all.
if you use innodb DO TAKE innodb log files as well : ib_logfileX and innodb data file: ibdataX
preferably try on another machine if data is readable and then peacefully reinstall the whole thing.
Comment: Make sure MySQL is shut down before doing this.  Otherwise, you can get a corrupt backup (especially with InnoDB).  Alternatively, look for one of the "hot copy" solutions out there.
Comment: @Matt Solnit you are absolutly right. i've corrected my answer.


Variance of bivariate values

Question: If I have two lines of regression ($y$ on $x$ and $x$ on $y$) and I know $\sigma(x)$, why isn't the variance of $y$ equal to $m^2 \sigma(x)^2$ where $m$ is the slope?
Comment: Those two regression lines would have different slopes so you would have two different models, with two different slopes - could you clarify your question?
Comment: I can't tell, that's all I've got. I assume I just pick one of the lines, but is my equation for the variance of $y$ correct?
Comment: Is it a homework? If so, it should be tagged as `[self-study]`, see http://stats.stackexchange.com/tags/self-study/info
Answer: In a linear model
$$y = \beta_0 + \beta_1 \cdot x + \epsilon,$$
the following is true about the variance of the dependent variable $y$:
$$\mathrm{var}(y) = \beta_1^2 \cdot \mathrm{var}(x) + \mathrm{var}(\epsilon).$$

Your assumption is limited to cases where $\mathrm{var}(\epsilon) = 0$.
Comment: I'm not sure what $\epsilon$ is. If I have two regression lines and nothing else, is my $\epsilon = 0$?
Comment: @user51819 $\epsilon$ respresents the residuals. These are the deviations of the individuals points from the regression line.
Comment: I don't have individual points, just the two lines of regression and $\sigma(x)$
Comment: @user51819 In this case, you can't calculate $\mathrm{var}(y)$ based on the slope and $\mathrm{var}(x)$.

Variance of bivariate values


General solution to differential problem with $dy/dx$

Question: I am given $\frac{dy}{dx} + 6y=e^x$ and I am trying to find the general solution but I am struggling. Can someone solve it out? Thanks
Comment: Hello, welcome to MSE. It is best to include any ideas you may have, or to provide some context for the problem.
Comment: Looks like a linear first order differential equation to me
Answer: If
$$
y'+6y=e^x
$$
then we can multiply both sides by the integrating factor $e^{6x}$
$$y'e^{6x}+6ye^{6x}=e^{7x}
$$
Now observe that
$$
(ye^{6x})'=y'e^{6x}+6ye^{6x}
$$
Can you take it from here?
Comment: So I realized that (ye^(6x))' = e^7x so took the integral of both sides and got ye^(6x)=e^(7x)/7 so I put the y on one side and got the answer y=(1/7)e^x is this correct? Again, I'm struggling with the solution.
Comment: Close, there's an integration constant you need to take into account
Comment: I added the constant at the end so that y(x) = (1/7)e^x + C. Is this right? If not please correct me.


Estimating variance of an unobserved component

Question: Consider $N$ time-series $x_{i,t}$ coming from the following data-generating process:
$$x_{i,t}=\beta_i y_t + \xi_{i,t} + \varepsilon_{i,t},$$
where $y_t$ is a common component among all the series, it is i.i.d. in time with mean 0 and variance $\sigma^2$; $\varepsilon_{i,t}$ is i.i.d. in time and across series with mean 0 and variance $\sigma_i^2$. For every $t$, $\xi_{i,t}$ satisfies the following property
$$\sum_{i=1}^N \xi_{i,t} = 0$$
At the same time $\xi_{i,t}$ is identically distributed in time and across series with mean 0 and variance $\sigma_{\xi}$.
None of the parameters ($\beta_i, \sigma, \sigma_i, \sigma_{\xi}$) are known; $y_t$, $\xi_{i,t}$ and $\varepsilon_{i,t}$ are unobservable. One observes a sample of length $T$ of $x_{i,t}$, $\{x_{i,t}\}_{i=1,t=1}^{i=N,t=T}$, only.
Questions:

What are possible ways to estimate $\sigma_{\xi}$ and $\sigma_i$? What are more robust/statistically efficient ways to estimate them?
Is there any way to infer the value of $\sum_{i=1}^N |\xi_{i,t}|$ for every $t$?

Any thoughts are welcome. For practical considerations assume $\sigma_i$, $\sigma$, $\sigma_{\xi}$ are of similar order of magnitude and $\beta_i \in (0,2)$.
Comment: I suspect the model is not identified, i.e. there exist different combinations of parameters who all yield the same likelihood. You would need to fix some of the parameters (i.e. normalize) to be able to estimate the remaining ones uniquely.
Answer: If you rewrite your model in state space form:
$$
\mathbf{x}_{t}= \mathbf{B} y_t + \left[\begin{array}{c} \xi_{1,t} \\ \xi_{2,t} \\ \xi_{3,t} \\ -\sum_{i=1}^{n-1} \xi_{i,t} \end{array}\right] + \varepsilon_{t}.
$$
$$
\left[\begin{array}{c}
\xi_{1,t} \\
\xi_{2,t}\\
\xi_{3,t}\\
\end{array}\right] =
\left[\begin{array}{ccc}
.9 & 0 & 0 \\
0 & .9 & 0\\
0 & 0 & .9\\
\end{array}\right]
\left[\begin{array}{c}
\xi_{1,t-1} \\
\xi_{2,t-1}\\
\xi_{3,t-1}\\
\end{array}\right] +
\left[\begin{array}{c}
\epsilon_{1,t-1} \\
\epsilon_{2,t-1}\\
\epsilon_{3,t-1}\\
\end{array}\right]
$$
then

you can estimate all unknown parameters with the EM algorithm or ML techniques with general purpose optimizers, and
you can do (2) with a Kalman Smoother, using the parameters you estimated from (1).

NB: This is one particular model that satisfies your requirements. There are other options available,and in particular, there are other dynamics you can choose for the states that satisfy your requirements. However, if you choose a state transition kernel that is nonlinear, then (1) and (2) will not be true, and you will require techniques that are more complicated.
For starters, and this would still allow you to use (1) and (2), it might be worthwhile to replace the $.9$s with different parameters, or assume they are unknown as well.
Also I am assuming you have a typo and mean to say that you observe $\{x_{i,t}\}$ and $\{y_{i,t}\}$.
Answer: Here is a wrong solution strategy.

Construct series $\hat{y_t} = \sum_{i=1}^N x_{i,t}$. For large $N$ this is a good proxy for $y$ up to a proportionality coefficient.
Run OLS regressions: $x_{i,t} = \hat{\alpha_i} +\hat{\beta_i} \hat{y_t}+
\hat{\zeta}_{i,t}$
Sample variance $V[\hat{\zeta}_{i,t}]$ will be a consistent estimate for $\sigma_i^2+\sigma_{\xi}^2$
Notice that
$$\sum_i V[x_{i,t}]-V\left[\sum_i x_{i,t}\right]= V[y_t]\left(\sum_i \beta_i^2-\left(\sum_i \beta_i\right)^2\right)+\sum_i V[\xi_{i,t}]$$
Take the sample counterpart of the above expression by substituting sample variances for $V[x_{i,t}]$, $V\left[\sum_i x_{i,t}\right]$, $V[\hat{y_t}]$, and estimates of $\beta_i$ obtained at step 2 to calculate an estimate for $\sum_i V[\xi_{i,t}]$. Divide it by $N$ to get an estimate $\hat{\sigma}^2_{\xi}$.
Subtract $\hat{\sigma}_{\xi}^2$ from the sample variance $V[\hat{\zeta}_{i,t}]$ to obtain $\hat{\sigma}^2_i$.
Comment: This answer is actually wrong. Estimated $\beta_i$ contain noise. So the sample counterpart of $\sum V[\xi_{i,t}]$ obtained at step 5 actually  equals sum of sample variances of the residuals $\hat{\zeta}_{i,t}$.


How to validate token from Localstorage and return currentUser from Apollo Server to React front-end?

Question: I already have a jwt middleware which verifies token and returns currentUser to React front-end:
app.use(async (req, res, next) => {
    const token = req.headers['authorization'];
    if(token !== "null") {
        try{
            const currentUser = await jwt.verify(token, process.env.SECRET)
        } catch {
        console.error(err);
    }
}
next();
});

Now, I want to integrate the logic into the following Apollo server:
const app = express();
const server = new ApolloServer({
  typeDefs: gql(typeDefs),
  resolvers,
  context: async () =>({
  db,
  secret: process.env.SECRET,
  }),
});

app.use(cors(corsOptions));
server.applyMiddleware({ app });

At the end, the value of currentUser should be available to be used at react front-end.
How can I achieve this?
Answer: You can add the currentUser to the request object inside the middleware. Next, you pass it copy it from the request to the GraphQL context. Then you can add a currentUser resolver and simply return the user from the context.
Your middlware
app.use(async (req, res, next) => {
    const token = req.headers['authorization'];
    if(token !== "null") {
        try{
            req.currentUser = await jwt.verify(token, process.env.SECRET)
        } catch {
        console.error(err);
    }
}
next();
});

Your server
const app = express();
const server = new ApolloServer({
  typeDefs: gql(typeDefs),
  resolvers,
  context: ({ req }) =>({
    currentUser: req.currentUser,
    db,
    secret: process.env.SECRET,
  }),
});

app.use(cors(corsOptions));
server.applyMiddleware({ app });

and the resolvers
const resolvers = {
  Query: {
    currentUser: (parent, args, context) => context.currentUser,
    ...
  }
}

Add the corresponding type definition and you should be able to query the current user from your client.
If you need more information here is a detailed tutorial which might be of help.


How to add element in the end of array Angular JS?

Question: I have one array in Angular JS: $scope.messages = [];
In template I do ng-repeat:

When I try to do add a new element to the end of array like as:
angular.forEach($scope.messages, function (value, key) {
      $scope._lastMsg = key; // Get key of last element of array
});

$scope.messages[++$scope._lastMsg] = obj; // Do increment of next key and add new element obj

This way adds element not at end of array, always differently.
Comment: Why not the `push()` function ?
Comment: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/push
Answer: Try to push it at the end with Array.push()
$scope.messages.push(obj)

Comment: @Hamed I doubt it. Post your complete controller code in the question.
Comment: I get error: `TypeError: $scope.messages.push is not a function`
Comment: It seems that `$scope.messages` was not initialized as an array before.

Try first: `$scope.messages = []`
Comment: Was initialized in top of controller `$scope.messages = []`


Como detectar auto se o aparelho esta na horizontal em java

Question: Quero fazer um script em Java pra detectar se o aparelho esta na horizontal ou na vertical, com if else, quero pra se estiver na horizontal esconde automaticamente a barra de navegação do aparelho em setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_FULL_SENSOR);
e se na vertical exibir a barra de navegação, alguém sábio para me instruir?
Comment: É uma velha pergunta aqui do site, mas tive dificuldade de localizar e agora não estou com tempo para fazê-lo. Tentei procurando por Android horizontal rotation e coisas assim. Talvez nas tags tenha alguma coisa. Se alguém encontrar por favor marque como duplicada.
Comment: Mas pensando melhor acho que isso se resolve com XMLs separados para os layouts vertical e horizontal, seria uma coisa a ser pesquisada.
Answer: Você pode detectar a orientação do aparelho sobrescrevendo método onConfigurationChanged  , como abaixo:

 @Override
   public void onConfigurationChanged(Configuration newConfig) {
      super.onConfigurationChanged(newConfig);
      if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
         //horizontal
      } else if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT) {
         //vertical
      }
   }

Exemplo na documentação
Comment: Obrigado isso mesmo resolveu


Bean binding not working in ajax call

Question: I have a flow defining a helper that submits correctly the data
<var name="contactForm" class="my.package.bean.ContactFormHelper"/>

To get some data based on user input I use in the view an ajax call on the binded attribute String id in this way:
<h:panelGroup >

        <f:ajax
            event="change"
            listener="#{contactController.identifyCustomer(contactForm)}"
            render="anotherPanel"
        />

</h:panelGroup>

But when identifyCustomer is executed only the field where ajax is placed (String id) is updated. The rest of fields are filled with default values.
LOG TRACE

[21/11/16 17:10:12:508 CET] 0000007a SystemOut     O DEBUG [WebContainer : 0 : 8610ff45-f4c5-4faf-a370-efa36701bc01] - ContactForm[name=, surnames= , nif=46713535Y]

Some idea of why is this happening?
Comment: Read this http://stackoverflow.com/questions/25339056/understanding-primefaces-process-update-and-jsf-fajax-execute-render-attributes  answers your question I think
Comment: There is only one field in the example... [mcve] please (and did you try a `p:ajax`?)
Answer: I've found a solution with process using @this and fields separated by commas:

Hope it help to others.

Bean binding not working in ajax call


Pandas: merging rows with condition

Question: I have a pandas DataFrame with the next columns - "A", "B", "C", "D". I want to merge the rows of the DataFrame that has the following condition -
if my DataFrame is called df:
(df.at[i,"A"] == df.at[j, "B"]) and (df.at[j,"A"] == df.at[i,"B"])

For example -
df = pd.DataFrame([[1,2,10,0.55],[3,4,5,0.3],[2,1,2,0.7]], columns=["A","B","C","D"])

Which gives -
In [93]: df
Out[93]:
   A  B   C     D
0  1  2  10  0.55
1  3  4   5  0.30
2  2  1   2  0.70

In the example above rows 0 and 2 has the condition. I know for sure that there can be at most 2 rows that correspond to this condition. For the rows that has this condition I would like to sum the "C" values, Average the "D" and remove the redundant row. In the example above I would like to get -
In [95]: result
Out[95]:
   A  B   C      D
0  1  2  12  0.625
1  3  4   5  0.300

Or
In [95]: result
Out[95]:
   A  B   C      D
0  2  1  12  0.625
1  3  4   5  0.300

I tried the following code that was very slow:
def remove_dups(path_to_df: str):
    df = pd.read_csv(path_to_df)
    for i in range(len(df)):
        a = df.at[i, "A"]
        b = df.at[i, "B"]
        same_row = df[(df["A"] == b) & (df["B"] == a)]
        if same_row.empty:
            continue
        c = df.at[i, "C"]
        d = df.at[i, "D"]
        df.drop(i, inplace=True)
        new_ind = same_row.index[0]
        df.at[new_ind, "C"] += c
        df.at[new_ind, "D"] = (df.at[new_ind, "D"] + distance) / 2
    return df

Is there a way to accomplish this using only built-in Pandas functions?
Comment: Hi. Please take the time to read this post on [how to provide a great pandas example](http://stackoverflow.com/questions/20109391/how-to-make-good-reproducible-pandas-examples) as well as how to provide a [minimal, complete, and verifiable example](http://stackoverflow.com/help/mcve) and revise your question accordingly. These tips on [how to ask a good question](http://stackoverflow.com/help/how-to-ask) may also be useful.
Comment: Hello, thanks for the comment. I've edited the question and added an example that can be copy-pasted to an interpreter. Is the question clearer now? If not, please tell me
Answer: Use numpy.sort first and then GroupBy.agg:
df[['A','B']] = np.sort(df[['A','B']], axis=1)

df = df.groupby(['A','B'], as_index=False).agg({'C':'sum', 'D':'mean'})
print (df)
   A  B   C      D
0  1  2  12  0.625
1  3  4   5  0.300

If original values cannot be changed:
arr = np.sort(df[['A','B']], axis=1)

df = (df.groupby([arr[:, 0],arr[:, 1]])
       .agg({'C':'sum', 'D':'mean'})
       .rename_axis(('A','B'))
       .reset_index())
print (df)
   A  B   C      D
0  1  2  12  0.625
1  3  4   5  0.300

Pandas: merging rows with condition


The dimension of a linear space is a multiple of 3 if it has an endomorphism of a certain feature

Question: I am trying to solve the following problem:

Let $K$ be a field of characteristic zero and $V$ be a finite-dimensional $K$-vector space. Assume that there exists a linear endomorphism $T$ over $V$ such that $T^3=\mathrm{id}$ and $\mathrm{Tr}\ T = 0$. Prove that the dimension of $V$ is a multiple of 3.

If $K=\mathbb C$, things are much simplified, because the eigenvalues of $T$ are among 1, $\omega$ and $\omega^2$, where $\omega$ is the primitive cubic root of 1.
But for general $V$ that is not necessarily algebraically closed, I do not how to use the condition for the trace.
I would be very grateful  if you could give a clue. (If possible, I prefer an elementary solution that does not use field theory.)
Comment: Hint: The conditions do not change if you extend the scalars to an algebraic closure.
Comment: @TobiasKildetoft Thank you.  Since I am not familiar with field theory,  I would appreciate if you could elaborate on that.
Comment: For simplicity, let us assume the field $K$ is contained in $\mathbb{C}$. Now, the eigenvalues of $T$ are the same (they just might not be elements of $K$), and they must still sum to $0$, so the same argument applies.
Answer: For the case $K=\Bbb C$ you would use the fact that the only $\Bbb Q$-linear dependency between the cubic roots of unity $1,\omega,\omega^2$ is (up to a scalar) $1+\omega+\omega^2=0$, so that $m_1.1+m_2\omega+m_3\omega^2=0$ with $m_1,m_2,m_3\in\Bbb N$ implies $m_1=m_2=m_3$ and hence $m_1+m_2+m_3\equiv0\pmod3$.
The same argument works whenever $\omega\in K$, so assume that this is not the case, in other words that $X^3-1=(X-1)(X^2+X+1)$ is a decomposition into irreducible factors over$~K$.
The condition $T^3=\operatorname{id}$ means that the minimal polynomial$~\mu$ of$~T$ divides $X^3-1$; it is a product of a subset of those factors. Without using field extensions, every irreducible factor of the characteristic polynomial$~\chi$ of$~T$ is also a factor of$~\mu$, so $\chi=(X-1)^{m_1}(X^2+X+1)^{m_2}$ for some $m_1,m_2\in\Bbb N$. Then simple computation shows that
$$\chi= X^n+(m_2-m_1)X^{n-1}+\text{lower order terms} \qquad\text{where $n=m_1+2m_2$,}$$
and the subdominant coefficient $m_2-m_1$ equals $-\operatorname{Tr} T=0$, so $m_1=m_2$ and $n=3m_1$.
Of course the latter is just a watered-down version of the argument used when $\omega\in K$, in other words one can avoid case distinctions be reasoning in an extension field where $X^3-1$ does split into linear factors. But I think you asked for a proof that does not use (the existence of) such extensions, and as you can see this can be done.
Added. I'll add a bit about the "whenever $\omega\in K$" above. First of all this should really say "whenever $K$ contains a root of $X^2+X+1$, which we may call$~\omega$". So supposing that, why should $1+\omega+\omega^2=0$ be up to a scalar the only $\Bbb Q$-linear dependency between $1,\omega,\omega^2$? Basically because $X^2+X+1$ is irreducible over$~\Bbb Q$. One has in general (apply it for $F=\Bbb Q$):
Lemma. Let $K$ be a field containing a subfield$~F$ and a root$~\alpha$ of an irreducible monic polynomial$~P=p_0+p_1X+\cdots+p_{n-1}X^{n-1}+X^n$ in $F[X]$. Then the elements $1,\alpha,\alpha^2,\ldots,\alpha^{n-1}$ of$~K$ are $F$-linearly independent, and the unique $F$-linear dependency between $1,\alpha,\alpha^2,\ldots,\alpha^n$ involving $\alpha^n$ with coefficient$~1$ is $p_0+\cdots+p_{n-1}\alpha^{n-1}+\alpha^n=0$.
The fact that $\alpha$ is root of$~P$ means that the final relation holds. We can take $d$ minimal such that $1,\alpha,\alpha^2,\ldots,\alpha^d$ are linearly dependent over$~F$. The linear dependency involved must involve $\alpha^d$, and by scaling can be made to do so with coefficient$~1$, which gives a degree$~d$ monic polynomial$~Q$ with $\alpha$ as root. By minimality every polynomial in $F[X]$ with $\alpha$ as root, in particular$~P$, must be divisible by$~Q$ (as a nonzero quotient in the Euclidean division would have too small degree to have $\alpha$ as root). But $P$ is irreducible, so $Q=P$ and $d=n$. In particular $1,\alpha,\alpha^2,\ldots,\alpha^{n-1}$ are $F$-linearly independent, and $\alpha^n$ can be expressed uniquely as $F$-linear combination $\alpha^n=-p_0-p_1\alpha-\cdots-p_{n-1}\alpha^{n-1}$.
Comment: @Pteromys: I did.
Comment: +1 Nice. You gave precisely the kind of proof OP asked for.
Comment: Thank you. I am embarrassed to say I am totally unfamiliar with field theory, and do not know how to prove that 1, $\omega$ and $\omega^2$ are $\mathbb Q$-linearly independent, especially when $K\neq\mathbb C$ (what is $\omega$ in this case?)  I would be very happy  if you could elaborate on these points.


ActiveX component can't create object: 'MSXML2.ServerXMLHTTP.4.0'

Question: I'm getting an error:

ActiveX component can't create object: 'MSXML2.ServerXMLHTTP.4.0'

With this line of code:
<code>Set objHTTP = CreateObject("MSXML2.ServerXMLHTTP.6.0")
</code>
I'm very naive when it comes to IIS. Is this an IIS configuration issue or something up with the code?
How can I solve this.
Answer: Try Server.CreateObject instead of CreateObject
CreateObject (without the Server. bit) is for client side vbscript
Comment: I'll give you the win. I got there with Set objHTTP = Server.CreateObject("Microsoft.XMLHTTP")
Comment: Microsoft.XMLHTTP is an older version of Microsoft's xml processor, but it should do the job just as well


Moving Drupal site to new server

Question: I'm tasked with moving a Drupal 6 site from a shared hosting account to a new virtual server.
Once I transfer the files to the new server, can I have the new server access the same database on the old shared server? So both sites (shared account and virtual server) would access the same db until DNS finishes propagation? Then I could put the new site into maintenance mode, and move the db to the new server.
I'm hoping that this will work so the old db doesn't get changed while DNS propagates...
Answer: You could theoretically do this, but I'd highly advise against it. Nasty things could happen when you have two sites trying to write to the same database.
Honestly, nearly every website takes things offline from time to time for maintenance. Just put the current site in maintenance mode, sync your files and database over to the new server, take the new copy out of maintenance mode, and switch DNS. Sure, there may be a bit of time where your users will see the maintenance mode page, but if you put an honest and explanatory message on that page, people won't really mind for the most part.

Moving Drupal site to new server


How do I play a crossed note before a hammer-on?

Question: The tab below is from Stop this Train - John Mayer
How am I suppose to play the part circled in red?
Also what is the correct name for this notation?
Comment: The redirection of your question explains that these notes are grace notes that have no rhythmic value (because of the slashes they have). However part of your question is not answered by the answers of the other question, which is how to play them. In both cases you want to strike the open E string then immediately hammer the 2nd fret. The first one is as part of a D chord and the second is hammering the note on the high E string while playing the low E 2nd fret at the same time.
Comment: @JohnBelzaguy - good point. The 'dupe' asks **what** the signs mean, with nothing in the answers explaining how to execute on guitar. Vote to re-open? Then your comment could be an answer.
Answer: This is accacciatura, see:

Difference between appoggiatura, acciaccatura and grace note
https://en.wikipedia.org/wiki/Ornament_(music)#Acciaccatura

The way to perform it is basically explained in the tabulature. You play the crossed note together with the other notes of the chord, and then, rather quickly, hammer on the following, not crossed note.


Fluent NHibernate - Mapeamento chave composta um para muitos

Question: Estou com um problema para mapear uma entidade pelo Fluent NHibernate.
Tenho uma relação 1-N com as duas tabelas no banco tendo chaves compostas.
Quando tento listar minha entidade Usuario volta um erro, mas isso acontece apenas quando crio a relação com a entidade AcessoDepartamento
UsuarioMap
public class UsuarioMap : ClassMap<Usuario>
{
    public UsuarioMap()
    {
        CompositeId()
            .KeyProperty(x => x.Email, "Usuario")
            .KeyReference(x => x.Empresa, "CodEmp")
            .KeyProperty(x => x.CodigoFilial, "Filial");

        Map(x => x.Nome, "Nome");
        Map(x => x.AcessoTodosDepartamentos, "AllDeptos");
        Map(x => x.AcessoTodosPedidos, "allPed");
        Map(x => x.Email, "email");
        Map(x => x.NivelUsuario, "UsrTipo")
            .CustomType<NivelUser>();
        Table("Usuario");

        References<Empresa>(x => x.Empresa, "CodEmp");
        References<CentroCusto>(x => x.CentroCusto, "CCusto");
        References<Departamento>(x => x.Departamento)
            .Column("CodDep");

        HasMany<AcessoDepartamento>(x => x.AcessoDepartamentos)
            .KeyColumn("AcessoDep");
    }
}

AcessoDepartamentoMap
public class AcessoDepartamentoMap : ClassMap<AcessoDepartamento>
{
    public AcessoDepartamentoMap()
    {
        CompositeId()
            .KeyProperty(x => x.AcessoDep, "AcessoDep")
            .KeyReference(x => x.Departamento, "CodDep");

        Map(x => x.CodigoFilial, "Filial");
        Table("AcessoDep");

        References<Departamento>(x => x.Departamento)
            .Column("CodDep");
        References<Empresa>(x => x.Empresa)
            .Column("CodEmp");
    }
}

Já tentei de tudo que já vi pelas pesquisas que fiz e nada até agora, continua voltando esse erro:

Foreign key (FK44A92FD8F30CB372:AcessoDep [AcessoDep])) must have same
  number of columns as the referenced primary key (Usuario [Usuario,
  CodEmp, Filial])

Como posso resolver?
Comment: Seu `AcessoDepartamento` também tem uma coluna chamada `Filial`? O detalhe é que o NHibernate está tentando adicionar um FOREIGN KEY ao `Usuario`, mas precisa referenciar as três colunas que compõe o usuario.
Comment: Eu tentei referenciar as três colunas como o erro dizia, nesse caso o erro parou de aparecer, mas não puxou a referencia do `AcessoDepartamento`. Dessas três colunas o `AcessoDepartamento` só não tem o `Usuario`, as outras duas (`Filial` e `CodEmp`) ele tem.
Answer: Achei essa resposta no Stack Overflow em Inglês, mas na minha experiência uma coisa assim ajuda e resolve mesmo:
HasMany<AcessoDepartamento>(x => x.AcessoDepartamentos)
  .KeyColumns.Add("AcessoDep", "CodDep").Cascade.All();


Drupal Commerce cart page to enter items

Question: I have a website I am working on, and I want to have a shopping cart page that is basically like a purchase order entry form, where a customer can enter the products he wants and then save it or post it, etc. In other words, so you don't have to go through the whole site selecting the products you want like a shopping cart, but rather just enter the item codes like you were writing out a purchase order. The website is for a producer basically and the customers are distributors.
I need to be able to enter products by item code or UPC (need both), and it would be a bonus if each user account could have a list attached to it where the customer could enter their own item codes for our products.
I hope this makes sense, can someone point me in the right direction?
Answer: Check out the module Commerce Add to Cart Extras. This got me started. Also, the module Views Field View I used to show the quantity that was ordered last time.


Number of infinite trees on certain cardinal

Question: Let $\kappa$ be some infinite cardinal. I usually use the notation $\langle T,<_T\rangle$ to refer to a tree. My question is: what is the number of non-isomorphic trees with $|T|=\kappa$?
There is an easy upper bound: $<_T\subseteq T\times T$, then, $<_T\in\mathcal{P}(T\times T)$, therefore, there are no more than $2^\kappa$-many non-isomorphic trees with cadinality $\kappa$. But, is this an optimal bound? Is it possible to define a tree for each element of $\mathcal{P}(T\times T)$? This question seems very basic and simple to me, however, I have not been able to find the answer anywhere. I suspect it may be independent of $\mathsf{ZFC}$, but I have no idea.
Thanks in advance!!
Answer: Given a set $S\subseteq\kappa$, consider the tree $T_S$ that has a maximal branch of length $\alpha$ iff $\alpha\in\kappa$. Concretely we can set $$T_S=\{f\in\kappa^{<\kappa}: f(0)\in S, length(f)<f(0), i>0\rightarrow f(i)=0\}.$$ Then clearly $T_S\cong T_{S'}$ iff $S=S'$.
(Fine, I technically need to restrict to $S\subseteq\kappa\setminus\{0\}$ and require $\vert S\vert=\kappa$, but there are again $2^\kappa$-many such subsets of $\kappa$ so that's benign.)
Comment: @HanulJeon Actually I might have overshot if GCH fails; I've added a clause to keep the size of $T_S$ small.
Comment: Thank you, but I have a question: how do we see that $|T_S|=\kappa$?
Comment: @Yester If $|S|=\kappa$, then the least node of $T_S$ has $\kappa$ many immediate successors so $|T_S|=\kappa$.


simple probability question - Independent experiments

Question: p=0.43
(1-p)=q=0.57
n=3
Its known that the first experiment failed.
what is the probability that the next experiments will succeed.
I'm thinking
P(X='Fail then success then success')=0.57*0.43*0.43
P(Y='Fail at the first time')=0.57
P(X/Y)=0.43^2
Is that correct?
Thanks.
Answer: Your answer is correct but your working is more complicated than necessary.  Since experiments are independent, the fact that there has been one failure has no effect on future probabilities.  So all you want is
$$P(\hbox{$2$ successes from $2$ experiments})=(0.43)^2\ .$$


how to connect android app to drupal database?

Question: I have a Drupal Site with content. I now want to make an Android App. Obviously, I would like Android App to access my Drupal site database - has anyone tried this?
From what I have read (from Google), it seems that I could use something like the phonegap module, or the Services module.
Am I on the right path? Are there other modules/tools/features I should be researching?
Comment: Yes the services module is what you need, but this is a very broad question which can't be reasonably answered in its current form. Your best bet would be to install the services module, read all the available documentation, then come back to ask specific questions about things you can't get to work :)
Comment: you may need this SDK, this SDK can connect Drupal & Android with both session and oauth1.0a which are the most popular approach right now. https://github.com/drucloud/drupalForAndroidSDK
Comment: You can read about this: .
Comment: This Drupal 8 Android SDK might be of help - [http://drupalsdk.com/](http://drupalsdk.com/)
Answer: Here is a module that will help in this venture, for Drupal 6.x and 7.x sites:
DrupalGap
It leverages PhoneGap (Cordova), Drupal + Services + Views Datasource (Views JSON). It provides a starting point for creating multi platform (Android, iOS, etc) mobile applications for Drupal websites.
Comment: Thank you for all the suggestions, I am just starting off in this project. I will try the options, report back on what/how it works for me.0
Comment: @tyler.frankenstein What if I convert the drupal site into a PWA using the pwa module? What's next? Can I use drupalgap to create a mobile of my pwa drupal site?
Answer: One possible approach would be to make a view and output data as JSON (If you only need to get data from the drupal website) . For that , this module might be handy.
<code>https://www.drupal.org/project/views_datasource
</code>
There can be other methods as well, but if you only need to read data, then above module is a life saver!
Answer: Yes You are on the right path what you can do with Phonegap  and DrupalGap module is
1) Drupal Authenticaiton
2) Add Content (By Default Article Content Type)
3) View Articles
This are the basic functionality so far Provided By PhoneGap and DrupalGap modules
To work with this you will require following
1) JDK(6)
2) Eclipse
3) ADT(For Developing Android apps)
4) Set your Enviornment variable from  the following links http://docs.phonegap.com/en/2.2.0/guide_getting-started_android_index.md.html#Getting%20Started%20with%20Android
Open Eclipse and create new android project and paste the code provided from this link into asset directory http://code.google.com/p/drupal-phonegap/downloads/list so the final path will be assets/www/ and run as android project i better advice you to dnt use emulator instead copy apk file from your project/bin directory and run on your own android Enjoy !!!


React Native erro "Cannot read property 'navigate' of undefined onPress

Question: Eu estou com um problema no código eu estou tentando acessar uma tela pressionando um botão, até ai tudo bem mas o problema é que eu estou tentando passar uma props para o onPress, mas está acontecendo esse erro:

TypeError: Cannot read property 'navigate' of undefined onPress C:/Users/21/projetoTeste/screens/home.js:57 54 | 55 | return( 56 |
57 | <TouchableOpacity style={this.styles.bntStyle} onPress={()=> this.props.navigation.navigate(this.props.screen)}> | ^ 58 | {this.props.titulo} 59 | {this.props.subTitulo} 60 | <Image style={this.styles.img} source={require('./imagens/cadeado.png')}/>

Basicamente eu criei um classe chamada Bnt que é um botão que recebe várias props e uma delas é a props screen que recebe justamente para qual tela irá passando para o onPress lá na classe Bnt do código acima.
Abaixo é a classe sendo usada:
<Btn titulo='Módulo 1:' subTitulo='Fundamentos' left ='50' screen = 'modulo1'/>

<Btn titulo='Módulo 2:' subTitulo='Hardware' screen = 'modulo2'/>

<Btn titulo='Módulo 3:' subTitulo='Software' screen = 'modulo3'/>

<Btn titulo='Módulo 4:' subTitulo='Internet' screen = 'modulo4'/>

Alguém pode me ajudar com isso?
Answer: O que ocorre é que a props "navigation" vai existir apenas para as telas que você informou na hora de criar as suas rotas. Se você por exemplo tiver uma tela "home" no seu arquivo de rotas, e ela tiver um componente para fazer os botões, os componentes de botões não herdam o navigation.
Para que elas possam usar o "navigation", uma das soluções é passar ela como props para o seu componente.
<Btn titulo='Módulo 1:' subTitulo='Fundamentos' left ='50' screen = 'modulo1' navigation = {this.props.navigation}/>

Fazendo isso, o seu componente Btn vai conseguir fazer a navegação para a tela que você informou na props "screen".
 <TouchableOpacity style={this.styles.bntStyle} onPress={()=> this.props.navigation.navigate(this.props.screen)}>
 <Image style={this.styles.img} source={require('./imagens/cadeado.png')}/>
 </TouchableOpacity>

Comment: Obrigado Irmão funcionou aqui, você é 10.


PIL Writing Text on Image Using Escape Sequence

Question: <code>`from PIL import Image, ImageDraw, ImageFont

image = Image.new('RGB', (950, 250), color=(255, 255, 255))
TEXT = 'You are a wondeful \033[32mperson.'
font_size = 50
font_type = "SourceCodePro-Bold.ttf"
draw = ImageDraw.Draw(im=image)
font = ImageFont.truetype(font_type, font_size)
draw.multiline_text((int(950 / 2), int(250 / 2)), text=TEXT, font=font,fill=(0, 0, 0), anchor='mm')
image.show()`
</code>
I tried to print text on an image using some escape sequence "\033[32m" using PIL (Pillow).
I was expecting the below output image
What I want

What I'm getting

So anybody have any idea that how to get the desired result then it'll be very helpful.
Thanks.
Comment: I think this procedure will not work yet. It's possible by changing the text position . if you want i can give a static solution. for this text
Comment: please share your solution.
Comment: please check on answer.. I have given the solution.. you can modify your code in this logic. thanks
Comment: The sequence you are using is an *"ANSI Escape Sequence"* https://en.wikipedia.org/wiki/ANSI_escape_code and they are only really used for controlling text colour and cursor position on ***terminals*** rather than in image processing.
Comment: Then Mark do you have any better solution for this ?
Comment: The nearest I know of is **Pango** which you can certainly do with **ImageMagick** just in the shell, see https://stackoverflow.com/a/51963371/2836621 I have not tried it with `wand` the ctypes binding of ImageMagick to Python https://pypi.org/project/Wand/
Comment: If it is in `wand` I guess you'd need to open a pseudo-image prefixed `pango:` as per examples here https://docs.wand-py.org/en/0.6.10/guide/read.html#open-a-pseudo-image
Comment: Thank you very much Mark for your time & effort. Let me try those.
Answer: You can try this one and change the position of text. i think this logic will help you. thanks
<code>from PIL import Image, ImageDraw, ImageFont
image = Image.new('RGB', (950, 250), "white")
text1 = "You are a wondeful"
text2="Person"
font_size = 100
font_type = "SourceCodePro-Bold.ttf"
draw = ImageDraw.Draw(im=image)
font = ImageFont.load_default()
draw.multiline_text((int(950 / 2), int(250 / 2)), text=text1, font=font,fill ="black",anchor='mm')
draw.multiline_text((int(1180 / 2), int(250 / 2)), text=text2, font=font,fill = "green",anchor='mm')
image.show()
</code>
Comment: Thanks for your reply, but in your case you are hard coding the  x position of text2. but suppose if the length of text1 changes then i have to change the x position of text2. my goal is to automate the whole process.


Find the asymptotic distribution of $T_n = \frac{X_{1n} X_{2n}}{X_{3n}X_{4n}}$ under multinomial distribution

Question: Let $(X_{1n}, X_{2n},X_{3n},X_{4n}) \sim \operatorname{Multnomial}(n; \pi_1,  \pi_2, \pi_3, \pi_4)$. Find the asymptotic distribution of $T_n = \frac{X_{1n} X_{2n}}{X_{3n}X_{4n}}$ as $n \to \infty$.
I don't know how to do the above question. I guess I need to use delta method. How to solve the above?
Comment: Do you know any theorems that allow you to conclude that $\tfrac{1}{n}X_{kn} \to \pi_k$ almost surely for each $k$?
Answer: Let us define the function $g(x,y,z,t) = (xy)/(zt)$ then
$$ g\left(\frac{X_{1n}}{n},\frac{X_{2n}}{n},\frac{X_{3n}}{n},\frac{X_{4n}}{n}\right) = T_n = \frac{\frac{X_{1n}}{n}\cdot \frac{X_{2n}}{n}}{\frac{X_{3n}}{n} \cdot \frac{X_{4n}}{n}}$$
According to the defintion 5.8.3 of the multnomial distribution and the central limit theorem, we have
$$\sqrt{n}\left(\pmatrix{X_{1n}/n \\X_{2n}/n \\X_{3n}/n \\X_{4n}/n } -\pmatrix{\pi_1 \\\pi_2\\\pi_3\\\pi_4}  \right)\xrightarrow[n\to+\infty]{\mathcal{D}} \mathcal{N}_4 \left(\pmatrix{0 \\0\\0\\0} ,\Sigma \right)$$
where $\Sigma \in \mathbb{R}^{4\times 4}$ such that
$$\Sigma_{i,j} = \cases{\pi_i (1-\pi_i)&if $i=j$\\
                        \pi_i\pi_j &if $i\ne j$ }$$
By the same technique multivariate Delta method used in this answer, we  have:
$$\sqrt{n}\left(g\left(\frac{X_{1n}}{n},\frac{X_{2n}}{n},\frac{X_{3n}}{n},\frac{X_{4n}}{n}\right) -\frac{\pi_1\pi_2}{\pi_3\pi_4}  \right)\xrightarrow[n\to+\infty]{\mathcal{D}} \mathcal{N} \left(0 ,\Gamma'\cdot\Sigma\cdot\Gamma  \right)$$
where $\Gamma\in\mathbb{R}^{4}$ is the gradient of $g$ at the point $(\pi_1,\pi_2,\pi_3,\pi_4)$ (I let you compute $\Gamma$):
$$\Gamma =\nabla g(\pi_1,\pi_2,\pi_3,\pi_4)$$
We can conclude that
$$\color{red}{T_n \xrightarrow[n\to+\infty]{\mathcal{D}} \mathcal{N} \left( \frac{\pi_1\pi_2}{\pi_3\pi_4}  , \frac{1}{n}\cdot \Gamma'\cdot\Sigma\cdot\Gamma  \right)}$$
Comment: This seems like it proves too much. Suppose we want to apply the same technique to $\frac{X}{n-X}$ where $X \sim \text{Binomial}(n,p)$. Then would you claim that this is asymptotically normally distributed around $\frac{p}{1-p}$? But in fact, $\Pr[\frac{X}{n-X} \le a] = \Pr[X \le \frac{a}{1+a}n]$, which tends to $1$ if $\frac{a}{1+a} > p$ and $0$ if $\frac{a}{1+a} < p$; the asymptotic distribution is a point distribution. What distinguishes the problem here from this simpler example?
Comment: @MishaLavrov  Exactly, that's what I meant, the estimator you suggested is asymptotically normally distributed for $n \to +\infty$ ($n$ large, but **not** $n = +\infty$!). And this normal distribution have a variance with a multiplicator factor of  $1/n$, so, it will converge almost surely to $p/(1-p)$  (that is the point distribution you mentionned) which occurs only when $n = +\infty$!
Besides, your example is not too diffrent from $\frac{X}{n}$ where $X \sim \text{Binomial}(n,p)$, do you agree with me that, asymptotically, this $\frac{X}{n}$  follows a normal distribution(and not a point)?
Comment: No, $\frac{X}{n}$ does *not* asymptotically follow a normal distribution, except in the trivial sense! The variance of $\frac{X}{n}$ tends to $0$. We can say that $\frac{X - np}{\sqrt n}$ asymptotically follows a normal distribution.
Comment: @MishaLavrov I think the discussion here is just because of my notation (which seems to be too abused :) )? Perhaps you prefer a more traditional notation such as this one ?
$$\sqrt{n}\left(T_n - \frac{\pi_1\pi_2}{\pi_3\pi_4} \right) \xrightarrow[n\to+\infty]{\mathcal{D}} \mathcal{N} \left( 0 ,  \Gamma'\cdot\Sigma\cdot\Gamma  \right)$$
Comment: I would agree with that - but then it seems that you're claiming that as $n \to \infty$, the distribution of $T_n$ *itself* is a point mass at $\frac{\pi_1 \pi_2}{\pi_3 \pi_4}$. The distribution of $\sqrt{n}\left(T_n - \frac{\pi_1\pi_2}{\pi_3\pi_4} \right) $ is a more precise estimate of the behavior of $T_n$ for large $n$, which is valuable, as long as there is no confusion. (I was initially confused because I did not spot the $\frac1n$ in the variance of your answer, which I think you'll agree is a bit of an abuse-of-notation flag :))
Comment: @MishaLavrov Yes, that's what I meant (and so did you in your first comment, didn't you?), according to the  law of large numbers (for example [here](https://stats.stackexchange.com/a/205294/130516)), $T_n$ converges  to a point mass(at least in probability, I believe even it converges almost surely).
PS: Finally, it seems there is no confusion (as you spotted now the factor $1/n$). For information, I prefere the notation that I used in the answer, but I still agree with you that it's a bit abuse of notation) :)


If I register a domain name as a name server what do I set it's name server to?

Question:
Possible Duplicate:
What is a glue record?

Do I add my ISP's name servers for the domain or itself as the name server?
e.g. say I have the domain www.shoes.com and a server setup for DNS ns1.shoes.com
will the name server for shoes.com be ns1.shoes.com or my ISPs name servers?
EDIT:
Just to clarify my DNS server is configured with the ISPs name servers but from domain registrar what do I put as the name server for the domain.
Example:
Say I have 3 domain names:
www.shoes.com
www.hats.com
www.shirts.com
I have a web server web.shoes.com and a name server ns1.shoes.com
www.hats.com will have the name server ns1.shoes.com
www.shirts.com will have the name server ns1.shoes.com
www.shoes.com I am unsure about. Can it be it's own name server?
Comment: Do you add what for? I have strong impression you don't know what you want or at least don't know how to say what you need.
Comment: I already have a DNS server up and running with bind9 however I do not have a domain name associated with it. I now have a domain name and need to enter the name servers for that domain with the domain registrar. I have also registered the name server ns1.shoes.com with the domain registrar and now I am unsure weather I enter ns1.shoes.com as it's name server or the ones my domain registrar provides.
Comment: Say I have another domain www.hats.com I know I will use ns1.shoes.com as the name server however for the name servers domain itself do I use itself as it's name server? does that make sense? I don't know how to be any clearer
Comment: See http://serverfault.com/questions/309622/what-is-a-glue-record
Comment: @Shane yes that is what I mean! though I still don't get an answer it seems as if I do enter ns1.shoes.com as the name server for shoe.com but doing so means i need to setup a glue record is that right?
Comment: @Craig Exactly right.
Answer: The simplest setup is to use your domain registrar's name servers.  This will work well for a simple domain.  Is also means you you don't have to learn how to secure a public bind server.  These days you need to secure the server against use in amplification attacks in addition to the standard infrastructure security.
Also you need at least two name servers preferably in different geographic locations.  There are services which will provide secondary servers for you.
If you use your own name servers (ns1, ns2...), you need to register both their domain and IP address with your registrar.  They will provide the IP addresses as additional information records for name server requests.
EDIT: For subdomains like www.example.com you don't need to provide additional name servers.  Just register the subdomain in your domain's DNS data.  The name servers for a domain will serve all subdomains not delegated to other name servers.   Only sub-domains delegated to other domain administrators require name servers be specified.
Comment: Maybe a simpler way to ask what I want is:
Testra have 2 name servers ns0.telstra.net and ns1.telstra.net
what is there name server set to for the domain **www.telstra.net**
Comment: @Craig The name servers for telstra.net will resolve www.telstra.net.  Normally no name serves will be specified for subdomains like www, smpt, mail, etc. See my last paragraph.
Answer: The glue records for the domain name point to the appropriate name servers. It's a field you have to fill in when you register for the domain.
If you do a dig on www.shoes.com, here are the listed name servers:
<code>shoes.com.      172744  IN  NS  ns5.savvis.net.
shoes.com.      172744  IN  NS  ns1.savvis.net.
shoes.com.      172744  IN  NS  ns2.savvis.net.
shoes.com.      172744  IN  NS  ns3.savvis.net.
shoes.com.      172744  IN  NS  ns4.savvis.net.
</code>
So those are the authoritative name servers for your domain and those servers are where all DNS queries on that domain will be resolved.
When you sign up for a domain, the registrar will ask for your name server address and domain name. If it's a brand new domain, you setup your own name server and call it ns1.yourdomain.com, even though you don't have the domain yet, and give them the IP address for that server.
They'll then configure the glue record for your domain to point to that address. Any DNS queries on your domain will hit the registrar first for the glue records and proceed from there.
Since you mentioned you have a DNS server, you would give the registrar the address of that server and call that server whatever you like but, again, standard practice is to use something like ns1.yourdomain.com
On your DNS server, you need to configure it to be authoritative for yourdomain.com and add the NS entry for ns1.yourdomain.com as well as any other entries you need.
Now, you said you have your ISPs DNS servers configured on your DNS server, and that's probably where the confusion is.
Basically, any queries for yourdomain.com are served by your DNS server itself and that's why you use the address of your DNS server. The reason your ISPs domain servers are configured on your DNS is because it passes requests from your internal hosts over to your ISP for any domains it is not authoritative for.
Comment: Ok sorry I meant my ISPs name servers are set as forwarders https://help.ubuntu.com/community/BIND9ServerHowto
So yes I have told my domain registrar that I have a name server ns1.shoes.com that is all good I can use this for my other domains that I register however with the domain **shoes.com** what do I tell the domain registrar to put for the name servers?
Comment: You tell them to use your DNS server. You're actually registering shoes.com since that's the top level domain. www.shoes.com is a sub-domain under shoes.com.

Is shoes.com your actual domain?


Increasing capacity of RAID5 array

Question: Assume that I built an 2TB RAID5 array and its running and some data is stored on it.
Now I need to increase its size to 5TB.
Can I increase capacity (By adding extra drives)? How?
If Yes is it possible to do this while RAID array is working?
I'm going to use Linux as OS.
I don't mind any special controller; I just want to know is it possible or not;
Comment: This depends completely on what's handing the array. Is it a hardware RAID controller?  If yes, what model?  If no, what OS is the software RAID running on?
Comment: @Shane Madden. I don't mind any special controller; I just want to know is it possible or not; and if yes what features controller must have? and about OS, I want to use LINUX (Maybe Ubuntu)
Answer: Linux MD software RAID can add disks to a hot RAID-5 array (mdadm --grow), reshaping the data on the fly.  Don't proceed until the reshape finishes (cat /proc/mdstat).
You'd then need to expand your filesystem to fill the array.  For an ext2/3/4 filesystem, for instance, you'd then run resize2fs to expand your filesystem to use the newly available space on the device.
Comment: «likely need a full, offline fsck» — BS.
Comment: @poige Right you are.  Edited.
Answer: Answer depends on what exactly RAID-5 implementation you'd use. Linux Soft RAID (LSR) allows for both on-line adding drives into RAID-5 (re-shape) and replacing drives with bigger ones then increasing overall size. I think some RAID-5 controllers should have supported this too, but don't expect them to be cheap. Lots of Linux filesystems allows for online size grow, but not shrink usually.
In case you go with either RAID it makes sense using LVM-2 too. You can merge several RAID-5 arrays into single logical volume with it, for e. g..
P. S. RAID-5 may be not optimal solution — just think: either disk you lose and your array is performing sub-optimal × not having redundancy.

Increasing capacity of RAID5 array


If you change the sign of a two tailed test does the p value remain the same?

Question: If the results of a t test are reversed are the p values the same?
I am running an experiment:
Treatment: sample size - 5k and metric value - 0.57 Control: sample size - 5k and metric value - 0.62
The lift from the control to the treatment is -0.05 with a p value of 0.013. So it's significant.
What if I flipped the treatment and control so now I have:
Treatment: sample size - 5k and metric value - 0.62 Control: sample size - 5k and metric value - 0.57
The lift from control to treatment is 0.05 but does the p value stay the same?
Comment: It depends on your hypotheses. What hypotheses are you using?
Comment: What would you consider your null and alternative hypotheses? Depending on the answer, I could see the p-value changing or remaining the same.
Comment: It is a two tailed test so I assume it would stay the same. If its one tailed it would be 1-p value. Am I correct in that assumption?
Comment: If I weigh 5 Kg more than you, do you weigh 5 Kg less than me?
Answer: Yes, if it's a two tailed test the p-value would stay the same.
You can think of it like this: When you do a t-test you look at the difference in mean between two samples, and then you balance that by how well that mean is estimated (the standard error of the mean). The standard error of the mean will depend on how many observations you have and how much your observations vary (standard deviation). $$standard\:error=\frac{standard\:deviation}{\sqrt{nr\:of\:observations}}$$
When you take $\frac{difference\:in\:means}{standard\:error}$ you get your t-score. So if you take $\bar{x}_1-\bar{x}_2$ instead of $\bar{x}_2-\bar{x}_1$ this will indeed flip the sign on the t-score, but not the magnitude. However, the p-value basically represents not-yet-covered-percentiles on the distribution of t-scores.
T-scores are assumed to become more normally distributed when the number of observations increases so just like you can get a percentile rank of someone's height you can get a percentile on the t-distribution i.e. how much of the area under the normally distributed curve you've covered. When we do a one-tailed test we count how much of the distribution we've covered from the bottom of the distribution (like with percentiles for height). When we do a two-tailed test we instead let the area we're covering expand from the mean. Since your t-score only flips sign, not magnitude, you would get the same p-value.
Comment: `T-scores are assumed to be normally distributed` Then what has a t-distribution?
Comment: Sorry, I guess it was a bit of a simplification. The t-distribution approaches the normal distribution as n goes towards infinity.


Pause Flutter app in debugger and wait for tap in IntelliJ

Question: I'm trying to debug a Flutter app in the Android emulator by pausing it, tapping on a button and expecting the debugger to take me to the buttons onPressed event handler, where I want to step through the code.
When I tap the button, nothing happens and the debugger doesn't change from paused to running. However, if I resume the app after tapping the button, the onPressed event handler is immediately invoked, so obviously the tap is being picked up by the emulator while the app was paused.
How can I debug my app in this manner, instead of manually finding the correct .dart file and the correct button and inserting a breakpoint?
Answer: Unfortunately you cannot do exactly that. Pausing the app prevents the event loop from executing and your button handler is not called. Making it pause in any of your code requires a new feature in which IntelliJ can differentiate between your code and framework code, and stop at any invocation of your code (even then, it should ignore your build() functions). The closest thing to that I could find in IntelliJ is Java method breakpoints, which would not work with Dart.
However, here is one thing you can do: You can set up a breakpoint in the caller of onPressed, which would pause your app on any button press. Here's where you can place that breakpoint:
// This is Line 504 of flutter/lib/src/material/ink_well.dart
// Ctrl+click on button to go into the framework code
// and find this file in project explorer
  void _handleTap(BuildContext context) {
    _currentSplash?.confirm();
    _currentSplash = null;
    updateHighlight(false);
    if (widget.onTap != null) {
      if (widget.enableFeedback)
        Feedback.forTap(context);
      widget.onTap(); // <---PLACE BREAKPOINT HERE
    }
  }

Once you hit this breakpoint, click step into (F7) a couple of times and you should get to your onPressed.


Possible lossy conversion from int to byte error in byte methods

Question: I have a byte variable
byte A;

and the setters-getters methods
    public void setA(byte A) throws NumberBelowEqualZeroException{
        if(A > 0)
            this.hoursPerWeek = hoursPerWeek;
        throw new NumberBelowEqualZeroException();
    }

    public byte getWorkingHoursPerWeek(){
        return hoursPerWeek;
    }

when I try to set the variable in main
AClass.setA(0);

NetBeans complains with the message incompatible types. Possibly lossy conversion from int to byte. None of the above are int. I cannot understand what is going on. Should I convert byte type like byte A = new Byte(A)? Thank you for your help.
Answer: Now try
AClass.setA((byte)0)

It complains because constant 0 is an int


js - marking bracket pair in input text box depending on cursor position

Question: I'm working on a math project. Therefore I want to modify the 'input text'-Box. It should mark the bracket pair of the cursor i. e. the bracket positioned left and the one right from the cursor.
I already know, how to get the cursor position:
document.getElementById('inutField').addEventListener('keyup', e => {
  console.log('pos: + e.target.selectionStart)
})

Now I thought about formatting a string
str = '3*(4+5)*6

formatting the span tag (maybe bold) and put it into the Text field with
document.getElementById('inputField').value = str;

Unfortunately the value variable doesn't take formatted strings, so it won't work.
Mayby someone has an idea or there is a library that already solves the problem?
Thanx for your help...
Philipp
Comment: Take a look at: https://github.com/handsontable/formula-parser
Comment: Thank you, for your answer! I think, this is not what I'm searching for... I'm looking for a possibility to format only some of the characters in an input field.
Answer: It seems like an overkill but you could use one of the WYSIWYG editor libs. The most popular are:

https://quilljs.com/
https://ckeditor.com/
Comment: As it's currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer).


Problems with playing high notes (17-20th fret on e-string)

Question: I have a problem that when I play a note on the e string (the tiniest one) on the 17th to 20th fret, I noticed that the same notes were repeated and starting in the 21st fret, the notes were fine again. I tried messing up with my electric guitar's action and intonation and something went wrong and I cannot bring it back when it was before. How do I fix this?
Comment: The header is misleading.
Answer: The top string is a little too low, so as you get to the dusty end, it's catching on the fretwire of fret 20. If that's the only problem, raising the saddle on the the string should be enough to get it sounding past fret 17.
There's a faint possibility that the fretwire itself is just too high - check using a ruler - not to measure, but as a straight edge. If it's not in line, a little tap should put it back in its place.


Gulp.js + Ember + Common.js: Cannot set property 'exports' of undefined

Question: I recently tried to use the gulp Gist posted here:
Everything builds fine, but in the browser I get an error in the generated templates.js file:
global.Handlebars = require("handlebars");
module.exports = Ember.TEMPLATES["index"] = Ember.Handlebars.template(function anonymous(Handlebars,depth0,helpers,partials,data) {

The error claiming, basically, that 'module' is undefined...
I'm getting a strong feeling that I'm missing something extremely trivial here.
Thanks in advance
Comment: I think setting `module.exports` is Node specific, and not in the original CJS.
Comment: Are you sure that before you call module.exports you have already loaded your module loader?
Answer: Because this causes the file to be wrap in some shim javascript:
'templates': {
    path: 'public/js/templates.js',
    exports: 'Ember.TEMPLATES'
},

Remove it and you'll be fine.
And requiring Ember in the prebundle is useless if you are also requiring it from your code.


col-md-6 não está funcionando em MVC

Question: Criei um form usando bootstrap.css no site w3schools.com/bootstrap/tryit.asp com o seguinte codigo:

        <form role="form">
                    <fieldset>

                                    Código
                                    <input type="text" name="email" id="email" value="" class="form-control" />

                                    CNPJ
                                    <input type="text" name="email" id="email" value="" class="form-control" />

                                    Nome Comercial
                                    <input type="text" name="phone" id="phone" value="" class="form-control" />

                                    Razão Social
                                    <input type="text" name="email" id="email" value="" class="form-control" />

                                    Endereço
                                    <input type="text" name="email" id="email" value="" class="form-control" />

                                    Numero
                                    <input type="text" name="email" id="email" value="" class="form-control" />

                    </fieldset>
     </form>

Lá funciona corretamente e o form fica como imaginei.

Mas dai eu copiei esse código exatamente como está(ainda não cheguei a parte de mesclar com os códigos @Html do RAZOR) e ele não renderiza legal, mas a linha RAZAO SOCIAL, que deveria ocupar toda a largura do FORM, não acontece independente se eu coloco 6, 7, 8... ou 12.
O form fica assim:

O que esta impedindo que ela fique na largura correta?
Obrigado
Answer: O projeto ASP.NET MVC clássico configura algumas coisas indevidas, tipo esta.
Abra o arquivo Content/Site.css e comente ou retire o seguinte:
/* Set width on the form input elements since they're 100% wide by default */
input,
select,
textarea {
    max-width: 280px;
}

Ou ainda, apague o arquivo. Apenas não esqueça de removê-lo do BundleConfig.cs.
Answer: Simples, o grid do boostrap possui classes para desktops e mixed displays porém o recurso utilizado para identificar a midia é o width, sua exibição está fora dos tamanhos padrões de um desktop dessa forma os seletores do grid não funcionam.
Consultando a documentação do boostrap em: https://getbootstrap.com/examples/grid/ você poderá ler mais sobre este tipo de problema mas para resolver este bug basta substituir o col-md-#numero# pelo col-xs-#numero# vide meu exemplo:

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet" />

        Razão Social
        <input type="text" name="email" id="email" value="" class="form-control" />

        Endereço
        <input type="text" name="email" id="email" value="" class="form-control" />

        Numero
        <input type="text" name="email" id="email" value="" class="form-control" />

Comment: Felipe alterei todos os md para xs, mas não funcionou. Apresentou o mesmo problema, com a diferença de que o form agora não ficou renderezida no meio da tela e sim a esquerda.
Comment: Estranho cara usando exatamente o seu html vide exemplo acima funcionou perfeitamente, teste removendo todos os arquivos.css e deixando apenas o bootstrap

col-md-6 não está funcionando em MVC


How to delete a node with optimisticUpdater in Relay?

Question: I am trying to delete a node, and then update the UI using optimisticUpdater inside the mutation, but I cannot to update the store and update the connection. The mutation itself works, but I want the UI to be updated without reloading the page. If I just delete the node from the store, then the error "TypeError: edge.node is null" occurs. I am also trying to access the connection using ConnectionHandler to remove the node from the connection, but I cannot figure out how to access the connection inside the mutation. I looked at the Relay documentation on mutations and store, but everything is very compressed there, and there are few examples on the network. The documentation says that the Relay Store is the one source of truth for the entire application, but I don't understand how to access the right data from any component. Please tell me what I need to do inside optimisticUpdater, or somewhere else, to update the UI after deleting the record.
After removal, the mutation returns the id of the removed node. Here is the mutation code:
import { commitMutation, graphql } from 'react-relay';
import environment from '../Environment';
import { ConnectionHandler } from 'relay-runtime';

const mutation = graphql`
  mutation RemoveHeroMutation($input: RemoveHeroInput!) {
    removeHero(input: $input) {
      deletedId
      deleted
    }
  }
`;

export default (id) => new Promise((resolve, reject) => {
  commitMutation(
    environment,
    {
      mutation,
      variables: {
        input: {
          id
        }
      },
      optimisticUpdater: (store) => {
        //this doesn't work
        const heroProxy = store.get(id);
        const conn = ConnectionHandler.getConnection(
          heroProxy,
          'HeroesList_Heroes'
        );
      },
      onCompleted: (res, err) => {
        if (err) return reject(err);
        return resolve("Removed");
      },
      onError: err => console.error(err)
    },
  );
});

The root component in which the request occurs. The Fragment container is used here:
import React, { Component, Fragment } from 'react';
import { Link } from 'react-router-dom';
import { Button } from 'antd';
import { PlusOutlined } from '@ant-design/icons';
import Line from '../components/Line';

import { QueryRenderer, graphql } from 'react-relay';
import environment from '../Environment';
import HeroesList from '../components/HeroesList';

const HeroesQuery = graphql`
  query HeroesQuery {
    viewer {
      ...HeroesList_viewer
    }
  }
`;

class Heroes extends Component {
  render() {
    return (
      <Fragment>

Heroes page

        <Line />
        <Button type="primary">
          <PlusOutlined /> <Link to="/addhero">Add Hero</Link>
        </Button>
        <QueryRenderer
          environment={environment}
          query={HeroesQuery}
          render={({ error, props }) => {
            if (error) {
              return
{error.message}
;
            } else if (props) {
              return <HeroesList viewer={props.viewer} />;
            }
            return
Loadind...

          }}
        />
      </Fragment>
    );
  }
}

export default Heroes;

The HeroesList component:
import React, { Component } from 'react';
import HeroTpl from './HeroTpl';

import { createFragmentContainer, graphql } from 'react-relay';

class HeroesList extends Component {
  constructor(props) {
    super(props);
  }
  render() {
    return (

        {this.props.viewer.Heroes.edges.map(edge => (
          <HeroTpl hero={edge.node} key={edge.node.id} />
        ))}

    );
  }
}
export default createFragmentContainer(
  HeroesList,
  {
    viewer: graphql`
      fragment HeroesList_viewer on Viewer {
        Heroes
          @connection(key: "HeroesList_Heroes") {
          edges {
            node {
              id
              ...HeroTpl_hero
            }
          }
        }
      }
    `,
  }
);

The 'HeroTpl' component:
import React, { Component, Fragment } from 'react';
import { Link } from 'react-router-dom';
import { Row, Col } from 'antd';
import { createFragmentContainer, graphql } from 'react-relay';
import { DeleteOutlined } from '@ant-design/icons';

import RemoveHeroMutation from '../mutations/RemoveHeroMutation';

class HeroTpl extends Component {
  render() {
    return (
      <Fragment>
        <Row className="line">
          <Col span={12}>
            <Link to={`/heroes/${this.props.hero.id}`}>

{this.props.hero.name}

            </Link>
          </Col>
          <Col span={6}>{this.props.hero.date}</Col>
          <Col span={6}>
            <DeleteOutlined
              className="delete"
              onClick={() => { RemoveHeroMutation(this.props.hero.id); }}
            />
          </Col>
        </Row>
      </Fragment>
    );
  }
}

export default createFragmentContainer(
  HeroTpl, {
    hero: graphql`
      fragment HeroTpl_hero on Hero {
        id
        name
        date
      }
    `
  }
);

I would be grateful for your help. I'd love to figure it out.
Answer: Maybe this could help
NODE_DELETE
relay will get a hint that a node is deleted and will update the require state in the store and hence re-render all the components using that state.
We can give Relay instructions in the form of a configs array on how to use the response from each mutation to update the client-side store


Inequality leading to Holder's: $t^\theta \leq \theta t + 1 - \theta$ with $0<\theta<1$ and $t\geq 0$

Question: In the process of proving Holder's Inequality for $l^p$ spaces, as per my instructions it begins by first asking us to prove the following inequality as a first step:

If $0<\theta<1$ and $t\geq 0$ then $$t^\theta \leq \theta t + (1-\theta)$$ and equality only holds if $t=1$.

The inequality is trivially true when $t=0$ and when $t=1$ but for other values of $t$ it is unclear to me how to approach this.  Note also: $\theta t + (1-\theta) = 1 + (\theta-1)t$
My thought process:

Attempt to bring the exponent down via logarithms, then $\theta \ln t \leq^? \ln(\theta t + (1-\theta))$, but attempting to expand the RHS with powerseries for $\ln$ seems unwieldy and equally difficult.
Attempt to expand the LHS as $t^\theta = (1+(t-1))^\theta = \sum_k \binom{\theta}{k}1^{\theta-k}(t-1)^k$ where the coefficients $\binom{\theta}{k}$ are the generalized binomial coefficients $\binom{\theta}{k}:=\frac{\theta(\theta-1)(\theta-2)\cdots(\theta-k+1)}{k!}$.  This also seems rather unwieldy and difficult to work with.
Since we know it works for $t=0$ and for $t=1$, try to find a range such that $f(t,\theta) = \theta t + (1-\theta) - t^\theta>0$ for $t=0$ and for fixed theta that $\frac{\partial f}{\partial t} \geq 0$.  We have $\frac{\partial f}{\partial t} = \theta -\theta t^{\theta-1}$ which for $t\geq 1$ since $-1<\theta-1<0$ will be $\theta - \theta\cdot \frac{1}{c}\geq 0$ where $c=t^{1-\theta}\geq t^0=1$ (with strict inequality for $t>1$)

This third approach seems to work for the case where $t\geq 1$ showing that difference between the RHS and the LHS is increasing and nonnegative for every value of $\theta$, but when $0<t<1$, you have $t^\theta>t$ so it appears that the derivative is in fact decreasing on the interval so it seems to require a different approach.
Where should I go from here to prove the case with $0\leq t\leq 1$?

aside: The form of Holder's Inequality that I am approaching is:  if $x\in l^p$ and $y\in l^{p'}$ where $1\leq p\leq \infty$ and $\frac{1}{p}+\frac{1}{p'}=1$ then for $xy=(x_ky_k)$ you have $\|xy\|_1\leq \|x\|_p\|y\|_{p'}$.  Where $1<p<\infty$ this is equivalent to writing: $\sum_k|x_ky_k|\leq\left(\sum_k|x_k|^p\right)^{\frac{1}{p}}\left(\sum_k|y_k|^{p'}\right)^{\frac{1}{p'}}$
Answer: For $t > 0$, write
$$t^\theta = t^\theta\cdot 1^{1-\theta}.$$
Taking the logarithm of both sides, what you need to show becomes
$$\theta\log t + (1-\theta) \log 1 \leqslant \log (\theta\cdot t + (1-\theta)\cdot 1),$$
which follows from the concavity of $\log$.
Answer: Note that this is a special case of the general theorem of means.
If $a, b$ are non-negative and $0 < x, y < 1$ with $x + y = 1$ then $a^{x}b^{y} \leq ax + by$. Equality occurs if $a = b$.
Here in the current question $a = t, b = 1, x = \theta, y = 1 - \theta$. An easy proof of the general theorem mentioned above is based on Mean Value Theorem.
Clearly if $a = b$ then there is equality. So let's suppose $a < b$ (since the inequality does not change by interchanging $a$ and $b$ there is no need to consider $b > a$). Consider the function $f(t) = t^{1 - x}$ so that $f'(t) = (1 - x)t^{-x}$. By mean value theorem we get $$b^{1 - x} - a^{1 - x} = f(b) - f(a) = (b - a)f'(c) = (b - a)(1 - x)c^{-x}$$ where $a < c < b$. And since $-x < 0$ we have $c^{-x} < a^{-x}$. It follows that we have $$b^{1 - x} - a^{1 - x} < (b - a)(1 - x)a^{-x}$$ Multiplying by $a^{x} > 0$ and noting that $1 - x = y$ we get $$a^{x}b^{y} - a < (b - a)y$$ or $$a^{x}b^{y} < a(1 - y) + by = ax + by$$ This can be further generalized to the following theorem:
If $a_{1}, a_{2}, \ldots, a_{n}$ are non-negative and $x_{1}, x_{2}, \ldots, x_{n}$ are positive with $\sum\limits_{i = 1}^{n} x_{i} = 1$ then we have $$\prod_{i = 1}^{n}a_{i}^{x_{i}}\leq \sum_{i = 1}^{n}a_{i}x_{i}$$ and equality occurs only when all the $a_{i}$ are equal.
Answer: If we take $g:\theta\to t^{\theta}$ we are just stating that the graphics of $g$ on the interval $(0,1)$ lies below the line through $(0,1)$ and $(1,g(1))$. However, that is trivial, since $g(\theta)$ is a convex function due to:
$$ g''(\theta) = t^{\theta}\log^2 t \geq 0.$$


Why is the start/finish line halfway down the grid?

Question: In F1, it would be simple enough to have the Start/Finish line (the line where the lap is counted) be the line in front of pole position, but for a weird reason the line is down the grid, somewhere between 10th and 15th.
So what is the reasonning why the line is deep in the grid instead of being where the lights are in front?
Comment: In some cases the finish line can be at the same position of the starting line, and on rare occasions even **ahead** of the starting line, as I mentioned here: https://sports.stackexchange.com/a/24250/16880
Answer: Ultimately it comes down to practical reasons.  The finish line must be adjacent to the tower where they wave certain of the flags, and also needs to be in clear view of the scorer.  The location of the grid, however, needs to be on a clear straightaway with room for dozens of cars - and sometimes that doesn't line up with the necessary location for the finish line.
See this article for some more detail:

The most common reason is practicality. There quite often is only a limited space on pit straight between corners. It is necessary, for example, that the finish will be by the tower where the start/finish flag marshal will await with the chequered flag, but also other such flags - like the black flag, the black/white 'bad sportsmanship' flag, and 'the meatball' - black with orange circle - flags which can only be shown at the start finish line.
A full grid of double-spaced Grand Prix cars can take up quite a bit of room - and at most Grand Prix circuits the various support categories have larger grids. To fit all the cars onto the grid it is sometimes necessary to move the start line forward of the finish line. Silverstone is a double exception in that the start line is behind the finish line. A reason for this is in the hope that the field will be slightly more spread out when the field arrived at Copse corner the first time, which is sharper now on entry than it used to be.
Comment: It's worth pointing out that while the logical side of things in that article snippet are probably still true, the information regarding Silverstone is quite out of date. If memory serves, the start line was moved infront of the finish line in '97 or '98, and then the whole start/finish/pits complex was moved to its current location in 2010 - in which the start line is still infront of the finish line
Comment: Thinking about it, not every circuit got this setup, its just that Austria was fresh on my mind. My local circuit (Montreal,Canada) the Start/Finish and the grid are aligned just the way its logical for it to be. Should mention that the Circuit Gilles-Villeneuve is only used for F1 and the supporting races.
Comment: Oh so if I understand right that line is the first thing that is placed (because that box being physically there you cant really change it every time theres a new series at the circuit) and then F1 places the grid to be able to fit everybody on the Start/Finish Straight? I thought it was the other way around but thinking it this way makes much more sense.
Comment: That sounds correct to me. Finish line is where it is, start line could change potentially if grid size changes I suppose.


Query calculando datas com INNER JOIN

Question: Salve pessoal,
Aqui tem um exemplo que um cara aqui da comunidade postou
e estou tentando adaptar as minhas necessidades porém surge um error:
#1248 - Every derived table must have its own alias

Minha query
SELECT
 date_format(TABLE_2.data, '%d/%m/%Y %H:%i:%s') as DATA_2,
 date_format(TABLE_1.data, '%d/%m/%Y %H:%i:%s') as DATA_1,
 Anos,
 Mes,
 Dias,
 Horas,
 Minutos
FROM TABLE_1
INNER JOIN
(
 SELECT
 data,
 TIMESTAMPDIFF(YEAR, data, TABLE_1.data) as Anos,
 TIMESTAMPDIFF(MONTH, data + INTERVAL TIMESTAMPDIFF(YEAR,  data, TABLE_1.data) YEAR , TABLE_1.data) AS Mes,
 TIMESTAMPDIFF(DAY, data + INTERVAL TIMESTAMPDIFF(MONTH,  data, TABLE_1.data) MONTH , TABLE_1.data) AS Dias,
 TIMESTAMPDIFF(HOUR, data + INTERVAL TIMESTAMPDIFF(DAY,  data, TABLE_1.data) DAY , TABLE_1.data) AS Horas,
 TIMESTAMPDIFF(MINUTE, data + INTERVAL TIMESTAMPDIFF(HOUR,  data, TABLE_1.data) HOUR , TABLE_1.data) AS Minutos
 FROM TABLE_2
)
ON TABLE_2.id = TABLE_1.id

Preciso fazer o mesmo que o exemplo só que usando 2 tabelas e com soma de horas e minutos.
Agradeço desde já pela atenção
Comment: Já pesquisou sobre o erro `Every derived table must have its own alias`? Tente colocar um `alias` depois dos parênteses no `INNER JOIN`. Ex.: `tbl2`. E depois no `ON`, faça referência ao `alias` criado. `tbl2.id = TABLE_1.id`.
Answer: Você precisa de um alias no select interno. De qualquer forma, sua query está errada. TABLE_1.data não faz sentido dentro do select interno. Tente algo como
SELECT
 date_format(TABLE_2.data, '%d/%m/%Y %H:%i:%s') as DATA_2,
 date_format(TABLE_1.data, '%d/%m/%Y %H:%i:%s') as DATA_1,
 TIMESTAMPDIFF(YEAR, data, TABLE_1.data) as Anos,
 TIMESTAMPDIFF(MONTH, data + INTERVAL TIMESTAMPDIFF(YEAR,  data, TABLE_1.data) YEAR , TABLE_1.data) AS Mes,
 TIMESTAMPDIFF(DAY, data + INTERVAL TIMESTAMPDIFF(MONTH,  data, TABLE_1.data) MONTH , TABLE_1.data) AS Dias,
 TIMESTAMPDIFF(HOUR, data + INTERVAL TIMESTAMPDIFF(DAY,  data, TABLE_1.data) DAY , TABLE_1.data) AS Horas,
 TIMESTAMPDIFF(MINUTE, data + INTERVAL TIMESTAMPDIFF(HOUR,  data, TABLE_1.data) HOUR , TABLE_1.data) AS Minutos
FROM TABLE_1
INNER JOIN TABLE_2
ON TABLE_2.id = TABLE_1.id;

Comment: obrigado pela ajuda irmão. agora surge o erro `#1054 - Unknown column 'TABLE_1.data' in 'field list'`
Comment: TABLE_1 tem a coluna data?
Comment: Sim tem........
Comment: @Hugo o problema é que TABLE_1.data não faz sentido no select interno. não tinha percebido isso.
Comment: E como posso resolver isso @BrunoCalza :(
Comment: @Hugo editei a resposta. forneca mais informações sobre sua estrutura para podermos te ajudar
Comment: agora foi! vlw Brunão
Comment: com essas informações acima daria para pegar o tempo médio geral?

Query calculando datas com INNER JOIN


Set what Console.ReadKey gets with Console.SetIn?

Question: I know you can do Console.SetIn(new StringReader("new input")); and then Console.ReadLine(); will return "new input" but is there a way to do this for Console.ReadKey()?
Comment: I really doubt you can do that, because TextReader is an abstract class.
Comment: @Andrey - Fixed question to be StringReader.
Answer: No, Console.ReadKey() uses the native console API, ReadConsoleInput() to read input.  You can't redirect that.
Other than by the obvious way, write a public static method that calls ReadKey() unless you want to return something else.
Answer: I believe you would rather want Console.Read() as ReadKey waits for a keystroke while Read just reads the next character.
Comment: yea, I actually want to wait for the next keystroke (I think)... I want to do something like "Press any key to continue" in my console app.


Working of Montgomery Ladder

Question: Can anybody explain the working of Montgomery Ladder and its efficiency in non cryptic language?
I have searched it but the notations are too cryptic for me.
Comment: What does it do?
Comment: speed up scalar multiplication...used for calculating exponents in logarithmic time....
Comment: Thanks. Sorry, not my area.
Comment: Please improve your question. provide citation of Montgomery Ladder.
Answer: The purpose of Mongomery Ladder is in some way to be less than optimally efficient. It does so by permorming one multiplication and one squaring per bit of the exponent, no matter if that bit is a one or a zero.
This is slightly wasteful as one could save one operation for each zero bit.
So why waste time? Because an attacker who measures the time needed to calculate the exponentiation could infer how many operations are performed and hence could make a guess at the number of zero bits in the exponent. By even closer inspection, it might be possible to even determine more detailed information from things like power consumption or electromagnetic radiation patterns (I once had an old computer next to an old radio and one could really hear the difference between a long memcopy operation, a complicated mathematical calculation, and a keyboard wait loop) that differ between a normal multiplication and a squaring operation; in that case the attacker could in fact "hear" the exponent's exact bit pattern.

Working of Montgomery Ladder