R fitting Poisson distribution with weighting

Question: I am wanting to fit a Poisson distribution but I am wanting to weight some of the values as more important. Is there a way to do this in R with fitdistr() or some equivalent function? Here is what I have at the moment:
randoms <- rpois(15,10)
weighting <- seq(1, 100, by=1)
fit <- fitdistr(randoms, "poisson")

I would like to use the 'weighting' data as a way to emphasize the observation at the end of the data set.
Comment: Other replies you received on Stack Overflow were merged with the ones here. Please, [don't cross-post](http://meta.stackexchange.com/q/64068/150510) in the future.
Comment: Could you then please help me decide where to post this question? It is programming in R but it is also related to statistics which is what this website deals with. I know that cross-posting is frowned upon but I got 2 different answers which are both very valuable. I love these websites but I'm not always sure where to post questions. Is there a decision tree that can be referenced? Thanks for the help.
Comment: Ah, I followed the link on cross-posting in your comment and cleared it up for me. Thanks for the help!
Comment: No problem. One solution about those two valuable answers (you accepted both) is to mention that you like them in a comment (beneath each answer) or to give an equal amount of your reputation *via* bounties.
Answer: Note that 'fitdistr does nothing but maximum likelihood estimation. That is to say, you can do it by yourself by writing down the likelihood. Below is an example for the poisson distribution in R. It can be adapted to upweight/downweight the contribution to the likelihood of each data.

density (as in R) $$f(x; \lambda) = \lambda^x \frac{\exp(-\lambda)}{x!}, \qquad \lambda > 0$$
likelihood $$L(\lambda; \mathbf{x}) = \prod_{i=1}^n \left\{ \lambda^{x_i} \frac{\exp(-\lambda)}{x_i!} \right\} $$
log-likelihood
$$\ell(\lambda; \mathbf{x}) = \sum_{i=1}^n \left\{ x_i \log(\lambda) - \lambda - \log(x_i!) \right\}$$
2nd derivatie of $\ell$:
$$ \frac{d^2 \ell}{d\lambda^2}(\lambda; \mathbf{x}) = \sum_{i=1}^n - \frac{x_i}{\lambda^2} = -\frac{1}{\lambda^2} n\bar{x}$$

#------data------
set.seed(730)
sample <- rpois(1000, 10)
#----------------

 ################################################################################
 # Using 'fitdistr'                                                             #
 ################################################################################

 library(MASS)
 fitdistr(x=sample, densfun="Poisson")
 lambda
   10.1240000
   ( 0.1006181)

 ################################################################################
 # writing down the log-likelihood explicitly                                   #
 ################################################################################

 #------minus log-likelihood------
 mloglik <- function(lambda2, sample) #lambda2 = log(lambda) in (-\infty, \infty)
 {
  - sum(sample * lambda2 - exp(lambda2) - log(factorial(sample)))
 }
 #--------------------------------

 #------optimisation------
 res <- nlm(f=mloglik, p=1, sample=sample)
 #------------------------

 #------recover lambda------
 lambda <- exp(res$estimate)
 round(lambda, 7)
 [1] 10.12399
 #--------------------------

 #------standard error------
 #square root of negative inverse second derivative of the log-likelihood
 se <- lambda / sqrt(length(sample) * mean(sample))
 round(se, 7)
 [1] 0.100618
 #--------------------------

Answer: If you're looking to do this just for the poisson distribution (where you're just estimating the point estimate of the one parameter lambda), you could use the glm function:
fit2 <- glm(randoms ~ 1, family = poisson(link = "log"),
  weights = weighting[1:15])

As a check,
fit1 <- glm(randoms ~ 1, family = poisson(link = "log"))
all.equal(unname(exp(coef(fit1))), unname(fit$estimate))
# [1] TRUE

And another check:
randoms2 <- rep(randoms, weighting[1:15])
fit3 <- glm(randoms2 ~ 1, family = poisson(link = "log"))

all.equal(exp(coef(fit3)), exp(coef(fit2)))
# [1] TRUE

Answer: If you look at the likelihood, the only bit of it that depends on both lambda and the x's is product lambda^x_i, which is lambda^{sum x_i}. Thus the sum of the x's, or equivalently the sample mean, is a sufficient statistic for lambda.
What that means is that you "fit a Poisson" by estimating the mean, using the sample mean. (And then you look at how well the Poisson with that mean fits your data.)
To go back to the OP's problem of weighting, all that means is that you calculate a weighted mean, and use that to estimate lambda with.


signup & signin using phone Number | flutter

Question: I want,
If the user is new to the app, I want to create an account for the user with a name, profile picture, and bio.
How do I know is the user is registered or not? (Look at the screenshot) -

**I do below steps understand to user already have an account or not
**

First, I say user to verify their phone number with OTP,
when it success, App will find their phone number in the firestore database,
(below is coding part for the above action)

<code>//phoneNumber: entered by user
if (phoneNumber ==
                  FirebaseFirestore.instance
                      .collection('users')
                      .doc('phoneNumber')) {
                print("user have!!!! Show main screen");
              } else {
                print('no, register! get data.. textfiledssss........');
              }
</code>
But the problem is, this is not working.
always output no, register! get data.. textfiledssss........
There is screenshot of my firebase firestore database,
,
My steps are not good? (what I do for understanding to the user is alredy have an account or not)
If there has another way to do this. please explain it.
If my steps are ok, why did this happen?
Answer: You can query the user's phone number to check if the phone number is available in the firestore or not.
<code>    FirebaseFirestore.instance
        .collection('users')
        .where('phoneNumber', isEqualTo: phoneNumber)
        .get()
        .then((value) {
      if (value.docs.isEmpty) {
        print('no, register! get data.. textfiledssss........');
      } else {
        print("user have!!!! Show main screen");
      }
    });

</code>


Groups - Prove that G is generated by A and B

Question: I'm revising for an Algebra exam and I am stuck on this question:
Let $G$ be a group of order $pq$ where $p$ and $q$ are primes and not necessarily distinct. Suppose that $A \ne B$ are subgroups of $G$ with $1<|A|$ and $1<|B|$. Prove that $G$ is generated by $A$ and $B$.
I am familiar with Lagrange's Theorem but I am unsure how to apply it here.
Thanks!
Comment: Since $A \neq B$ is the only condition, what happens when $|A| = |B|$? For example, in $G=S_3$, we have $A = \{e, (12)\}, B = \{e, (1,3)\}$. $A, B$ together generate $G$ but it is not straightforward conclusion.
Comment: Take a non abelian group $G$ of order 39. This will have 12 subgroups of order 3. No two of these can generate $G$. Hence we need the assumption that $|A| = p, |B|=q$. In this case $|AB| = \frac{|A||B|}{|A \cap B|} = pq$ since $|A\cap B| = 1$ and hence $AB = G$
Answer: Hint:  Use Lagrange's Theorem and the fact that if a group has prime order, then it is cyclic.
Answer: Since $A$ and $B$ are subgroups of $G$, then by Lagrange theorem, the cardinality of $A$ and $B$ each divides $pq$. If either one group has cardinality $pq$, then the statement holds trivially.
Therefore we may assume that $|A| = p$ and $|B|=q$. And from the hint by Jose, we may let $A$ and $B$ be generated by elements say $a$ and $b$ since they are cyclic.
Can you take it from here?
Comment: I think I must have gaps in my knowledge. I assume you can infer something since A and B can be generated by a single element respectively?


Data migration into CiviCRM - keep legacy IDs

Question: I develop custom migration code using CiviCRM's PHP API calls like:
<?php
$result = civicrm_api3('Contact', 'create', array(
  'sequential' => 1,
  'contact_type' => "Household",
  'nick_name' => "boo",
  'first_name' => "moo",
));

There's a need to keep original IDs, but specifying 'id' or 'contact_id' above does not work. It either does not create the contact or updates an existing one.
The ID is auto-incremented, for sure, but MySQL supports to insert arbitrary, unique values in that case.
How would you proceed? Hack CiviCRM to somehow pass the id to MySQL at the INSERT statement? Somehow dump the SQL after the import and manipulate the IDs in-place at the .sql textfile (hard to maintain integrity)?  Any suggestions for that?
I have ~300.000 entries at least to deal with, so a fully automated and robust solution is a must. Any SQL magic potentially to do that?
For those who are not familiar with CiviCRM, the table structure is the following:
mysql> desc civicrm_contact;
+--------------------------------+------------------+------+-----+-------------------+-----------------------------+
| Field                          | Type             | Null | Key | Default           | Extra                       |
+--------------------------------+------------------+------+-----+-------------------+-----------------------------+
| id                             | int(10) unsigned | NO   | PRI | NULL              | auto_increment              |
| contact_type                   | varchar(64)      | YES  | MUL | NULL              |                             |
| contact_sub_type               | varchar(255)     | YES  | MUL | NULL              |                             |
| do_not_email                   | tinyint(4)       | YES  |     | 0                 |                             |
| do_not_phone                   | tinyint(4)       | YES  |     | 0                 |                             |
| do_not_mail                    | tinyint(4)       | YES  |     | 0                 |                             |
| do_not_sms                     | tinyint(4)       | YES  |     | 0                 |                             |
| do_not_trade                   | tinyint(4)       | YES  |     | 0                 |                             |
| is_opt_out                     | tinyint(4)       | NO   |     | 0                 |                             |
| legal_identifier               | varchar(32)      | YES  |     | NULL              |                             |
| external_identifier            | varchar(64)      | YES  | UNI | NULL              |                             |

and we talk about the first field.
Comment: Please note for future question that CiviCRM have it's own stackexchange sub-site - http://civicrm.stackexchange.com/
Answer: You should use the external_identifier field which is exactly done for what you want.
This field is not used by CiviCRM itself so there is no risk to mess with core functionality. It's done to link with an external system (legacy for example).
CiviCRM consider the external_identifier to be unique so it will throw an error (using API - I think) or update (using CiviCRM contact import screen) if you try to insert a contact with the same external_identifier.
Comment: Thanks for that, it's definitely a good direction, my only issue is that i'd need to apply it to the Contributions too, which does not have this field. Of course it's an option to provide a patch to CiviCRM to have the external ID to all (many?) entities.
Comment: In that case, i suggest you create a custom field on contribution that store this external identifier.


Cause: unable to find valid certification path to requested target

Question: I am getting this error -

ERROR: Cause: unable to find valid certification path to requested target

Whenever I am doing Gradle sync.
It also says that there is an SSL exception and also resource not found exception for org.jetbrains.kotlin:kotlin-stdlib-jdk8:1.3.41.
However, I don't understand why am I getting issues about kotlin when I am writing the code in Java and not kotlin.
I am using Android Studio 3.5
Things I have tried till now :
-Changing jcenter() from https to http
-Tried to run on company as well as home network but got the same issue
-Downloaded the certificate and added it
-Uninstalled and Installed android studio
Also please note that the issuer of the certificate that is in my server certificate shows my company proxy and not CA no matter if its getting installed at home or on company network. I read it somewhere that the certificate issuer should be CA.
Error Log: Kotlin Part
        Caused by: org.gradle.internal.resolve.ModuleVersionResolveException: Could not resolve org.jetbrains.kotlin:kotlin-stdlib-jdk8:1.3.41.
        Required by:
            project : > com.android.tools.build:gradle:3.5.0
            project : > com.android.tools.build:gradle:3.5.0 > com.android.tools.build:builder:3.5.0
            project : > com.android.tools.build:gradle:3.5.0 > com.android.tools.lint:lint-gradle-api:26.5.0
            project : > com.android.tools.build:gradle:3.5.0 > com.android.tools.build:gradle-api:3.5.0
            project : > com.android.tools.build:gradle:3.5.0 > androidx.databinding:databinding-compiler-common:3.5.0
            project : > com.android.tools.build:gradle:3.5.0 > com.android.tools.build:builder:3.5.0 > com.android.tools:sdk-common:26.5.0
            project : > com.android.tools.build:gradle:3.5.0 > com.android.tools.build:builder:3.5.0 > com.android.tools:common:26.5.0
            project : > com.android.tools.build:gradle:3.5.0 > com.android.tools.build:builder:3.5.0 > com.android.tools.build:manifest-merger:26.5.0
            project : > com.android.tools.build:gradle:3.5.0 > com.android.tools.build:builder:3.5.0 > com.android.tools.analytics-library:tracker:26.5.0
            project : > com.android.tools.build:gradle:3.5.0 > com.android.tools.build:builder:3.5.0 > com.android.tools:sdklib:26.5.0 > com.android.tools:repository:26.5.0
            project : > com.android.tools.build:gradle:3.5.0 > com.android.tools.build:builder:3.5.0 > com.android.tools:sdk-common:26.5.0 > com.android.tools.analytics-library:shared:26.5.0
        Caused by: org.gradle.internal.resolve.ModuleVersionResolveException: Could not resolve org.jetbrains.kotlin:kotlin-stdlib-jdk8:1.3.41.
        Caused by: org.gradle.api.resources.ResourceException: Could not get resource 'http://jcenter.bintray.com/org/jetbrains/kotlin/kotlin-stdlib-jdk8/1.3.41/kotlin-stdlib-jdk8-1.3.41.pom'.
            at org.gradle.internal.resource.ResourceExceptions.failure(ResourceExceptions.java:74)
            at org.gradle.internal.resource.ResourceExceptions.getFailed(ResourceExceptions.java:57)
            at org.gradle.api.internal.artifacts.repositories.resolver.DefaultExternalResourceArtifactResolver.downloadByCoords(DefaultExternalResourceArtifactResolver.java:140)
            at org.gradle.api.internal.artifacts.repositories.resolver.DefaultExternalResourceArtifactResolver.downloadStaticResource(DefaultExternalResourceArtifactResolver.java:99)
            at org.gradle.api.internal.artifacts.repositories.resolver.DefaultExternalResourceArtifactResolver.resolveArtifact(DefaultExternalResourceArtifactResolver.java:65)
            at org.gradle.api.internal.artifacts.repositories.metadata.AbstractRepositoryMetadataSource.parseMetaDataFromArtifact(AbstractRepositoryMetadataSource.java:70)
            at org.gradle.api.internal.artifacts.repositories.metadata.AbstractRepositoryMetadataSource.create(AbstractRepositoryMetadataSource.java:60)
            at org.gradle.api.internal.artifacts.repositories.metadata.DefaultMavenPomMetadataSource.create(DefaultMavenPomMetadataSource.java:38)
            at org.gradle.api.internal.artifacts.repositories.metadata.RedirectingGradleMetadataModuleMetadataSource.create(RedirectingGradleMetadataModuleMetadataSource.java:51)
            at org.gradle.api.internal.artifacts.repositories.resolver.ExternalResourceResolver.resolveStaticDependency(ExternalResourceResolver.java:247)
            at org.gradle.api.internal.artifacts.repositories.resolver.MavenResolver.doResolveComponentMetaData(MavenResolver.java:127)
            at org.gradle.api.internal.artifacts.repositories.resolver.ExternalResourceResolver$RemoteRepositoryAccess.resolveComponentMetaData(ExternalResourceResolver.java:451)
            at org.gradle.api.internal.artifacts.ivyservice.ivyresolve.CachingModuleComponentRepository$ResolveAndCacheRepositoryAccess.resolveComponentMetaData(CachingModuleComponentRepository.java:375)
            at org.gradle.api.internal.artifacts.ivyservice.ivyresolve.ErrorHandlingModuleComponentRepository$ErrorHandlingModuleComponentRepositoryAccess.lambda$resolveComponentMetaData$5(ErrorHandlingModuleComponentRepository.java:153)
            at org.gradle.api.internal.artifacts.ivyservice.ivyresolve.ErrorHandlingModuleComponentRepository$ErrorHandlingModuleComponentRepositoryAccess.lambda$tryResolveAndMaybeBlacklist$18(ErrorHandlingModuleComponentRepository.java:222)
            at org.gradle.api.internal.artifacts.ivyservice.ivyresolve.ErrorHandlingModuleComponentRepository$ErrorHandlingModuleComponentRepositoryAccess.tryResolveAndMaybeBlacklist(ErrorHandlingModuleComponentRepository.java:236)
            at org.gradle.api.internal.artifacts.ivyservice.ivyresolve.ErrorHandlingModuleComponentRepository$ErrorHandlingModuleComponentRepositoryAccess.tryResolveAndMaybeBlacklist(ErrorHandlingModuleComponentRepository.java:221)
            at org.gradle.api.internal.artifacts.ivyservice.ivyresolve.ErrorHandlingModuleComponentRepository$ErrorHandlingModuleComponentRepositoryAccess.performOperationWithRetries(ErrorHandlingModuleComponentRepository.java:214)
            at org.gradle.api.internal.artifacts.ivyservice.ivyresolve.ErrorHandlingModuleComponentRepository$ErrorHandlingModuleComponentRepositoryAccess.resolveComponentMetaData(ErrorHandlingModuleComponentRepository.java:152)
            at org.gradle.api.internal.artifacts.ivyservice.ivyresolve.ComponentMetaDataResolveState.process(ComponentMetaDataResolveState.java:69)
            at org.gradle.api.internal.artifacts.ivyservice.ivyresolve.ComponentMetaDataResolveState.resolve(ComponentMetaDataResolveState.java:61)
            at org.gradle.api.internal.artifacts.ivyservice.ivyresolve.RepositoryChainComponentMetaDataResolver.findBestMatch(RepositoryChainComponentMetaDataResolver.java:139)
            at org.gradle.api.internal.artifacts.ivyservice.ivyresolve.RepositoryChainComponentMetaDataResolver.findBestMatch(RepositoryChainComponentMetaDataResolver.java:120)
            at org.gradle.api.internal.artifacts.ivyservice.ivyresolve.RepositoryChainComponentMetaDataResolver.resolveModule(RepositoryChainComponentMetaDataResolver.java:93)
            at org.gradle.api.internal.artifacts.ivyservice.ivyresolve.RepositoryChainComponentMetaDataResolver.resolve(RepositoryChainComponentMetaDataResolver.java:64)
            at org.gradle.api.internal.artifacts.ivyservice.resolveengine.ComponentResolversChain$ComponentMetaDataResolverChain.resolve(ComponentResolversChain.java:95)
            at org.gradle.api.internal.artifacts.ivyservice.clientmodule.ClientModuleResolver.resolve(ClientModuleResolver.java:64)
            at org.gradle.api.internal.artifacts.ivyservice.resolveengine.graph.builder.ComponentState.resolve(ComponentState.java:196)
            at org.gradle.api.internal.artifacts.ivyservice.resolveengine.graph.builder.ComponentState.getMetadata(ComponentState.java:146)
            at org.gradle.api.internal.artifacts.ivyservice.resolveengine.graph.builder.DownloadMetadataOperation.run(DownloadMetadataOperation.java:31)
            at org.gradle.internal.operations.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:402)
            at org.gradle.internal.operations.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:394)
            at org.gradle.internal.operations.DefaultBuildOperationExecutor$1.execute(DefaultBuildOperationExecutor.java:165)
            at org.gradle.internal.operations.DefaultBuildOperationExecutor.execute(DefaultBuildOperationExecutor.java:250)
            at org.gradle.internal.operations.DefaultBuildOperationExecutor.execute(DefaultBuildOperationExecutor.java:158)
            at org.gradle.internal.operations.DefaultBuildOperationExecutor.access$1500(DefaultBuildOperationExecutor.java:49)
            at org.gradle.internal.operations.DefaultBuildOperationExecutor$ParentPreservingQueueWorker.execute(DefaultBuildOperationExecutor.java:444)
            at org.gradle.internal.operations.DefaultBuildOperationQueue$WorkerRunnable.runOperation(DefaultBuildOperationQueue.java:231)
            at org.gradle.internal.operations.DefaultBuildOperationQueue$WorkerRunnable.access$600(DefaultBuildOperationQueue.java:173)
            at org.gradle.internal.operations.DefaultBuildOperationQueue$WorkerRunnable$1.create(DefaultBuildOperationQueue.java:210)
            at org.gradle.internal.operations.DefaultBuildOperationQueue$WorkerRunnable$1.create(DefaultBuildOperationQueue.java:204)
            at org.gradle.internal.work.DefaultWorkerLeaseService.withLocks(DefaultWorkerLeaseService.java:189)
            at org.gradle.internal.operations.DefaultBuildOperationQueue$WorkerRunnable.runBatch(DefaultBuildOperationQueue.java:204)
            at org.gradle.internal.operations.DefaultBuildOperationQueue$WorkerRunnable.run(DefaultBuildOperationQueue.java:178)
            at org.gradle.internal.concurrent.ExecutorPolicy$CatchAndRecordFailures.onExecute(ExecutorPolicy.java:64)
            at org.gradle.internal.concurrent.ManagedExecutorImpl$1.run(ManagedExecutorImpl.java:48)
            at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
            at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
            at org.gradle.internal.concurrent.ThreadFactoryImpl$ManagedThreadRunnable.run(ThreadFactoryImpl.java:56)
            at java.lang.Thread.run(Thread.java:748)
        Caused by: org.gradle.internal.resource.transport.http.HttpRequestException: Could not HEAD 'https://jcenter.bintray.com/org/jetbrains/kotlin/kotlin-stdlib-jdk8/1.3.41/kotlin-stdlib-jdk8-1.3.41.pom'.
            at org.gradle.internal.resource.transport.http.HttpClientHelper.performRequest(HttpClientHelper.java:91)
            at org.gradle.internal.resource.transport.http.HttpClientHelper.performRawHead(HttpClientHelper.java:68)
            at org.gradle.internal.resource.transport.http.HttpClientHelper.performHead(HttpClientHelper.java:72)
            at org.gradle.internal.resource.transport.http.HttpResourceAccessor.getMetaData(HttpResourceAccessor.java:66)
            at org.gradle.internal.resource.transfer.DefaultExternalResourceConnector.getMetaData(DefaultExternalResourceConnector.java:63)
            at org.gradle.internal.resource.transfer.AccessorBackedExternalResource.getMetaData(AccessorBackedExternalResource.java:201)
            at org.gradle.internal.resource.BuildOperationFiringExternalResourceDecorator$1.call(BuildOperationFiringExternalResourceDecorator.java:61)
            at org.gradle.internal.resource.BuildOperationFiringExternalResourceDecorator$1.call(BuildOperationFiringExternalResourceDecorator.java:58)
            at org.gradle.internal.operations.DefaultBuildOperationExecutor$CallableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:416)
            at org.gradle.internal.operations.DefaultBuildOperationExecutor$CallableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:406)
            at org.gradle.internal.operations.DefaultBuildOperationExecutor$1.execute(DefaultBuildOperationExecutor.java:165)
            at org.gradle.internal.operations.DefaultBuildOperationExecutor.execute(DefaultBuildOperationExecutor.java:250)
            at org.gradle.internal.operations.DefaultBuildOperationExecutor.execute(DefaultBuildOperationExecutor.java:158)
            at org.gradle.internal.operations.DefaultBuildOperationExecutor.call(DefaultBuildOperationExecutor.java:102)
            at org.gradle.internal.operations.DelegatingBuildOperationExecutor.call(DelegatingBuildOperationExecutor.java:36)
            at org.gradle.internal.resource.BuildOperationFiringExternalResourceDecorator.getMetaData(BuildOperationFiringExternalResourceDecorator.java:58)
            at org.gradle.internal.resource.transfer.DefaultCacheAwareExternalResourceAccessor$1.get(DefaultCacheAwareExternalResourceAccessor.java:102)
            at org.gradle.internal.resource.transfer.DefaultCacheAwareExternalResourceAccessor$1.get(DefaultCacheAwareExternalResourceAccessor.java:82)
            at org.gradle.cache.internal.ProducerGuard$AdaptiveProducerGuard.guardByKey(ProducerGuard.java:97)
            at org.gradle.internal.resource.transfer.DefaultCacheAwareExternalResourceAccessor.getResource(DefaultCacheAwareExternalResourceAccessor.java:82)
            at org.gradle.api.internal.artifacts.repositories.resolver.DefaultExternalResourceArtifactResolver.downloadByCoords(DefaultExternalResourceArtifactResolver.java:135)
            ... 47 more

Error Log: SSL Exception Part
 Caused by: javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
        at sun.security.ssl.Alerts.getSSLException(Alerts.java:192)
        at sun.security.ssl.SSLSocketImpl.fatal(SSLSocketImpl.java:1946)
        at sun.security.ssl.Handshaker.fatalSE(Handshaker.java:316)
        at sun.security.ssl.Handshaker.fatalSE(Handshaker.java:310)
        at sun.security.ssl.ClientHandshaker.serverCertificate(ClientHandshaker.java:1639)
        at sun.security.ssl.ClientHandshaker.processMessage(ClientHandshaker.java:223)
        at sun.security.ssl.Handshaker.processLoop(Handshaker.java:1037)
        at sun.security.ssl.Handshaker.process_record(Handshaker.java:965)
        at sun.security.ssl.SSLSocketImpl.readRecord(SSLSocketImpl.java:1064)
        at sun.security.ssl.SSLSocketImpl.performInitialHandshake(SSLSocketImpl.java:1367)
        at sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1395)
        at sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1379)
        at org.apache.http.conn.ssl.SSLConnectionSocketFactory.createLayeredSocket(SSLConnectionSocketFactory.java:396)
        at org.apache.http.conn.ssl.SSLConnectionSocketFactory.connectSocket(SSLConnectionSocketFactory.java:355)
        at org.apache.http.impl.conn.DefaultHttpClientConnectionOperator.connect(DefaultHttpClientConnectionOperator.java:142)
        at org.apache.http.impl.conn.PoolingHttpClientConnectionManager.connect(PoolingHttpClientConnectionManager.java:373)
        at org.apache.http.impl.execchain.MainClientExec.establishRoute(MainClientExec.java:394)
        at org.apache.http.impl.execchain.MainClientExec.execute(MainClientExec.java:237)
        at org.apache.http.impl.execchain.ProtocolExec.execute(ProtocolExec.java:185)
        at org.apache.http.impl.execchain.RetryExec.execute(RetryExec.java:89)
        at org.apache.http.impl.execchain.RedirectExec.execute(RedirectExec.java:110)
        at org.apache.http.impl.client.InternalHttpClient.doExecute(InternalHttpClient.java:185)
        at org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:83)
        at org.gradle.internal.resource.transport.http.HttpClientHelper.performHttpRequest(HttpClientHelper.java:132)
        at org.gradle.internal.resource.transport.http.HttpClientHelper.performHttpRequest(HttpClientHelper.java:109)
        at org.gradle.internal.resource.transport.http.HttpClientHelper.executeGetOrHead(HttpClientHelper.java:98)
        at org.gradle.internal.resource.transport.http.HttpClientHelper.performRequest(HttpClientHelper.java:89)
        ... 67 more
    Caused by: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
        at sun.security.validator.PKIXValidator.doBuild(PKIXValidator.java:397)
        at sun.security.validator.PKIXValidator.engineValidate(PKIXValidator.java:302)
        at sun.security.validator.Validator.validate(Validator.java:262)
        at sun.security.ssl.X509TrustManagerImpl.validate(X509TrustManagerImpl.java:324)
        at sun.security.ssl.X509TrustManagerImpl.checkTrusted(X509TrustManagerImpl.java:229)
        at sun.security.ssl.X509TrustManagerImpl.checkServerTrusted(X509TrustManagerImpl.java:124)
        at sun.security.ssl.ClientHandshaker.serverCertificate(ClientHandshaker.java:1621)
        ... 89 more
    Caused by: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
        at sun.security.provider.certpath.SunCertPathBuilder.build(SunCertPathBuilder.java:141)
        at sun.security.provider.certpath.SunCertPathBuilder.engineBuild(SunCertPathBuilder.java:126)
        at java.security.cert.CertPathBuilder.build(CertPathBuilder.java:280)
        at sun.security.validator.PKIXValidator.doBuild(PKIXValidator.java:392)
        ... 95 more

Comment: What version of Java were you running ? I mean which exact version, like 1.8.0_241-b07
Answer: If you are behind a proxy you should have the following in your gradle.properties file.
 systemProp.http.proxyHost=proxy_url
 systemProp.http.proxyPort=proxy_port
 systemProp.http.proxyUser=USER
 systemProp.http.proxyPassword=PWD
 systemProp.https.proxyHost=proxy_url
 systemProp.https.proxyPort=proxy_port
 systemProp.https.proxyUser=USER
 systemProp.https.proxyPassword=PWD

If you always have the same problem, you should add the jcenter certicate to your JVM's cacerts.

If your jcenter certificate is inside any other certificate you should add all certificates to the JVM's cacerts using this command
sudo keytool -import -alias jcenter -keystore  PathToYourCacertFile(in my case :/Library/Java/JavaVirtualMachines/adoptopenjdk-8.jdk/Contents/Home/jre/lib/security/cacerts) -file path to your cer file (in my case /Users/****/Desktop/jcenter.cer

Comment: No i am not behind any proxy and i had downloaded the jcenter certificate and added it directly inside Android Studio but that also did not work.
Is it always compulsory that the issuer name in the certificate should always be CA because in my case whether i am on a proxy or not , be it office network or home network ..... the issuer name is always coming as proxy.mycompanyname.com
Comment: Check your Network setting if the issuer name is always the same you may have your company's network proxy setted.
Importing the jcenter certificate into Android Studio doesn't work for me also.
You Should import it to your JVM instalation folder /Contents/Home/jre/lib/security/cacerts and it will work fine.
Comment: I tried importing the certificate through keytool but still facing the same issue. ERROR: Cause: unable to find valid certification path to requested target.

Also I checked that when Android Studio itself adds a certificate the issuer name is my company name however if i download the certificate from the site itself then the issuer name is different.


CKEditor toolbar using wrong icon file (via Rails "rich" gem)

Question: I'm using CKEditor via the 'rich' gem for Ruby on Rails.
It has historically worked fine, but at some point my editor icons started looking like this:

I'm not sure what caused was, whether I upgraded something or what.
(I do know that it's not a browser-cache issue.)
How I can fix these icons?
The code:
This is the HTML for the Bold button's span element (whitespace added for readability):

And the styles as interpreted by Chromium:

In that last line, url(icons.png) actually resolves to http://localhost:5000/assets/ckeditor/skins/moono/icons.png
What I can see but don't know how to resolve:
There are two different icons.png files at play here:

<gem_path>/vendor/assets/images/ckeditor/plugins/icons.png
(works correctly with background-position offset -24px)
<gem_path>/vendor/assets/images/ckeditor/skins/moono/icons.png
(is calibrated for a different offset value)

In the code snippets, you can see that the CSS specifies offset -24px, thus the first image is the correct one.  The inline-element style specifies the first image, but is overridden by an !important-ified url(icons.png) which loads the second image (which is wrong).
Why the heck is it doing that?
Can I somehow fix this without forking the gem?  (I can fork the gem, but I'd rather not maintain a separate fork if possible.)
Comment: There's no SO tag for the `rich` gem as far as I can tell.  If I'm mistaken, please add it or let me know.
Comment: I ended up forking the gem and fixing the image, which fixed my immediate problem.  Blech.  If anyone has an actually *good* solution, please let me know.
Comment: Did you finally find a proper solution for that? It started to happened also to me recently and I have no idea what is the reason.
Answer: Add below CSS in the application.html.erb file
.cke_ltr .cke_button_icon {
    background-image: url('/assets/ckeditor/plugins/icons.png?t=H5SC') !important;
}


Target probabilities in Platt's scaling with sigmoid regression

Question: For model calibration, Platt suggested to use these target labels instead of $[0, 1]$:
$$
y_+=\frac{N_++1}{N_++2};\quad\quad y_-=\frac{1}{N_-+2}
$$
These new values to not sum up to $1$, so would cross-entropy still applicable for fitting this model?
Answer: $y_+$ and $y_-$ are not meant to sum to 1, and cross-entropy is applicable.
The first is the probability you try to fit for a positive true class; the corresponding negative-class probability is 1/(N+ + 2). Those sum to 1.
Similarly, if the true class is negative, you use $y_-$. This and its complement (for a positive predicted class) sum to 1.
These are meant to be posterior probabilities, e.g. $p(\text{predict-positive} \mid \text{actually-positive})$.


Revit API Can not create new sweep in generic model adaptive family document

Question: I have just started working with Revit API for a short time and been scratching my head with this problem. I want to create a family containing a solid form using "generic model adaptive" family template. However, it seems like I can not create a sweep in the family document using
Autodesk.Revit.Creation.FamilyItemFactory.NewSweep()

as I keep receiving the following exception:
Autodesk.Revit.Exceptions.InvalidOperationException
The attempted operation is not permitted in this type of family.

What are the reasons for this error? Why is the operation not permitted even though I have been working on the newly created family document?
Here is my code:
// sweepPath is a CurveByPoints instance.
if (null != sweepPath)
            {
                acTrans.Start("Cable");
                // create a circle as bottom shape for the cable
                IList<XYZ> points = sweepPath.GeometryCurve.Tessellate();
                XYZ center = points[0];
                Plane workingPlane = Plane.CreateByNormalAndOrigin(XYZ.BasisZ, center);
                Arc bottomShape = Arc.Create(workingPlane, _radius, 0, 2 * Math.PI);

                // create profile
                CurveArray curveArray = new CurveArray();
                curveArray.Append(bottomShape);
                CurveArrArray arrArray = new CurveArrArray();
                arrArray.Append(curveArray);
                SweepProfile profile = _rvApp.Create.NewCurveLoopsProfile(arrArray) as SweepProfile;

                // create path
                XYZ sweepPathDirection = points[1] - points[0];
                double angle = sweepPathDirection.AngleTo(XYZ.BasisZ);
                XYZ direction = sweepPathDirection.CrossProduct(XYZ.BasisZ);
                Line axis = Line.CreateUnbound(center, direction);
                ElementTransformUtils.RotateElement(familydoc, sweepPath.Id, axis, angle);
                CurveArray path = new CurveArray();
                path.Append(sweepPath.GeometryCurve);

                // create sketch plane
                Plane plane = Plane.CreateByNormalAndOrigin(new XYZ(10, 0, 0), refPointArray.get_Item(0).Position);
                SketchPlane pathPlane = SketchPlane.Create(familydoc, plane);

                // create the cable
                // Sweep sweep = familydoc.FamilyCreate.NewSweep(true, curveArray, pathPlane, profile, 0, ProfilePlaneLocation.Start);
                ReferenceArray refArray = new ReferenceArray();
                refArray.Append(sweepPath.GeometryCurve.Reference);
                Sweep sweep = familydoc.FamilyCreate.NewSweep(true, refArray, profile, 0, ProfilePlaneLocation.Start);
                acTrans.Commit();
            }

Edit 1: I first thought that the family document is not activated, thus I tried
Application.OpenDocumentFile(file_path_for_my_family_document);

but it didn't work out. The same error keeps happening even when I tried the sample code for creating a sweep in family document from the SDK.
Answer: This turned out to be a bad idea because revit api does not support create sweep in particular and solid in general in an adaptive family document. I don't know the reason behind this but it is un-achievable even though I can do the same thing in a normal generic family document. I have to load an existing adaptive family instead.
I wonder what causes the difference?
If you use the family intensively or the family is complicated, loading one will make good performance and much more simple code to write.
If you only use a simple family in a very limited situation, create one from api is a good solution. It could be a tedious work in case you need many family of the same type but with difference in number of adaptive point.


Yet another probability question.

Question:
A nuclear reactor is equipped with 2 safety systems. The first safety
  system will work in 90% of the cases. If it doesn't work, the second safety system will start to work, but it only works in 80% of the cases. What is the probability that no safety
  system will alarm the employers of the nuclear reactor?

My attempt:
Let $S$ denote that an alarm works and $F$ that no alarm works. Write $(F,S)$ for the outcome "The first alarm doesn't work, the second does" and analoguous for the others.
Then, $\mathbb{P}(\{F,F\}) = \mathbb{P}(\{(F,F),(S,F)\} \cap\{(F,F),(F,S)\}) $
$= \mathbb{P}(\{(F,F),(S,F)\} \mid\{(F,F),(F,S)\})\mathbb{P}(\{(F,F),(F,S)\}) = (0.2)(0.1) = 1/50$
Is this correct?
It seems tedious to write this always out this way. Can I avoid this?
Comment: "Assuming the events are independent, the probability that both alarms fail is $.2\cdot .1 = 1/50.$"
Comment: P(system 1 off and system 2 off) = P(2 off | 1 off) P(1 off), this means .2*.1 = .02. They give you the conditional probability: " the second safety system will start to work, but it only works in 80% of the cases."
Answer: Yes, you can avoid it.
Let $F_1$ denote the event that the first alarmsystem will fail and let $F_2$ denote the event that the second alarmsystem will fail.
Then: $$\mathsf P(F_1\cap F_2)=P(F_1)P(F_2\mid F_1)=P(F_1)P(F_2)=0.1\cdot0.2=0.02$$here the second equality is based on independence.
Note that this can apparantly be solved without any bothering what the underlying probability space looks like.
Here you find a nice question about that subject.
It is important that you know about underlying probability spaces but there comes a time (if you persevere in probability theory) that you will hardly ever bother about them anymore.

Yet another probability question.


How do I correctly inform the system about my module's new config?

Question: I'm working on a module that already comes with a config file in mymodule/config/install/mymodule.settings.yml, and I'm working on a new feature that requires its own set of configuration in mymodule/config/install/mymodule.newfeature.yml.
I assume I need to put the following code in an update hook.
<code>function mymodule_update_8003() {
  \Drupal::service('config.installer')->installDefaultConfig('module', 'mymodule');
}
</code>
But if I do this, will sites that have overridden my existing configuration (from mymodule.settings.yml) get hosed, or is there another way to tell Drupal about my new configuration?
Comment: Just FYI, you should create a schema file for each configuration group.
Comment: @kiamlaluno ... Thanks for editing, but I think this question as you worded it is not what I was asking. Please leave the title alone
Comment: Please don't add tags to the title; we have tags for a reason. We don't need "Drupal" in the title, since this site is only about Drupal.
Comment: Sorry to butt in, guys - @kiamlaluno totally agree with removing Drupal from the title but I think it ended up slightly ambiguous (just my opinion). I've changed it slightly, hopefully that satisfies all angles. bleen, if you feel that's changed the meaning please feel free to change to something else. The editing might seem a bit "silly" but we're just touching up the question slightly so it conforms to the usual format, there's nothing wrong the content at all :)
Comment: Also did you see http://drupal.stackexchange.com/questions/164713/how-do-i-update-the-configuration-of-a-module?rq=1? It's a somewhat similar question, maybe it has some insights that will help you
Comment: @Clive .. hadn't seen that question, thanks. It's definitely helpful, but it seems more geared towards a site owner, as opposed to a contrib module dev. You did leave one comment in there that seems to imply that the only solution is to use [config update](https://www.drupal.org/project/config_update).  It doesn't address whether my example update is valid though.  Thoughts?
Comment: Sorry, I wish I knew - I'm very interested to find out myself. There are a few regular users who I'm fairly sure will know the answer, hopefully one of them will see this soon
Comment: If the config file exists in the install directory then it will be installed when the module is installed.
Comment: @Eyal, that's definitely true, but if what if I'm adding a config to a module that is already installed; as part of an update?
Comment: I think that the easiest solution would be to create and save it in a hook update function.
Comment: @Eyal yes... but what function or method (please be specific) can I call in my update hook in order to tell Drupal that I have a new configuration?
Answer: I think I found a strategy that is only slightly hackish to let Drupal know that your module has created a new config. This solution assumes that your new config is in a separate yml file in yourmodule/config/install but it should be adaptable to a situation where you are adding a new config to an existing file....
<code>/**
 * Install new config.
 */
function your_module_update_8003() {
  // Get all current configs for Your Module.
  $existing_settings_config = \Drupal::configFactory()->getEditable('your_module.settings');
  $existing_foo_config = \Drupal::configFactory()->getEditable('your_module.foo');
  $existing_bar_config = \Drupal::configFactory()->getEditable('your_module.bar');

  // Install the new configuration
  // (a new file was added a your_module/config/install/your_module.baz.yml)
  \Drupal::service('config.installer')
    ->installDefaultConfig('module', 'your_module');

  // Reset the existing configs in case they were changed when installing the
  // new configuration.
  $existing_settings_config->save();
  $existing_foo_config->save();
  $existing_bar_config->save();
}
</code>
It's not ideal, but it seems to work.
Answer: "will sites that have overridden my existing configuration (from mymodule.settings.yml) get hosed" Have you tried this?
A) I would suggest, to do separate configuration files (as granular as your updates need to be) and address them and update them separately, not using the "installDefaultConfig" method.
B) Have only one file, however in the updatehook don't call the config installer, but write the updateHook with "entityDefinitionUpdateManager" or any other service, custom php code you need.
On the other hand I totally agree: module default/update configuration system is really foggy.
Comment: I have tried and it appears that using "installDefaultConfig" does reset any overrides that a site might have made .. not a huge surprise there. That said, I don't see a good alternative. In my particular case I have added a separate config file but I still dont see how to "update them separately".


How should I practice the piano piece Fantaisie-Impromptu?

Question: It has always been a childhood dream of mine
to play well the piano piece Fantaisie-Impromptu.
Unfortunately, I was not able to learn the piece with my piano teacher
while I was learning the piano.
Recently, as an adult who is almost 20 years removed from piano lessons,
I decided to try to learn the piece,
and I noticed that the piece is fairly difficult.
As explained by Wikipedia:

[Fantaisie-Impromptu] uses many cross-rhythms (the right hand plays sixteenth notes against the left hand playing triplets).

It's fairly easy for me to play
the right hand part and the left hand part separately,
but I find it very difficult to keep the correct rhythm
when I try to play both hands together.
In addition, most performers seem to play the piece very fast!
How should I practice this difficult piano piece?
Note: I do think that this is a piece that I should be able to learn
with a reasonable amount of practice,
as it was very easy for me to pick up easier pieces such as
The Piano Sonata No. 16 in C major, K. 545, by Wolfgang Amadeus Mozart
and Rondo Alla Turca.
Comment: One thing to note is that when you put your hands together, slow *way* down. Even if you have the rhythm between the hands down, this song especially needs to go slow when putting hands together. When I learned it, I played at less than half the speed with hands together compared to hands separate
Comment: Alternatively, speed *way* up *before* you combine the hands. Before you can perform the polyrhythm correctly, you have to shift one of the rhythms (preferably the left hand)  from conscious control entirely to muscle memory (and that is much easier at high speed than at low speed). Then you can reserve your entire conscious focus for playing the right-hand melody.
Answer: You could start by practising the cross-rhythms just as five-finger exercises, for example

Use a metronome to keep the main beats even. Don't try to space out all the notes "mathematically", just make sure the notes on the beats line up, and the ones in between are even. And don't try to practice this too slow - start at about MM 80 or 100. Going slower makes it harder, not easier.
When you can do that without too much effort, try playing scales and arpeggios using the same idea.
You might like to try the first few exercises here as well: http://imslp.org/wiki/51_Exercises,_WoO_6_(Brahms,_Johannes)
Then go back to the Chopin!
Answer: Fantasie Impromptu contains polyrythms. A "Polyrythm"is the use of two different rythms playing together, and the Fantasie Impromptu also has a Polyrythm. The right hand plays semiquavers, while the left hand plays triplets. This piece is quite similar to both his Etude Op.25 No.1 and No.3.
You can take one part of these two pieces and practice it. So first you have to be comfortable with the rhythm, practice, practice, practice. From slow to fast. You can mark highlight notes from the treble and bass clef that are on the same beat. So every time you come across those notes, you can stomp your feet to indicate an accent. That goes to the rest of the piece.
Fantasie Impromptu is a fairly hard piece to learn just after learning a few Mozart pieces? Well that's a huge jump, I wish you all the best!
Answer: I am just now wrapping up this piece, and have my recital in a month.  I am not a professional musician by any means, and I have a day job, so I can only get a few hours of practice per week.  I've always loved Chopin's Fantaisie Impromptu, but honestly thought I would never be able to play it.  However, after asking my teacher about 18 months ago, he said it could be done.
So, 18 months later, I can tell you, it CAN be done, but it takes a LOT of practice.  The polyrhythm you refer to in your question took me several weeks to get right.  It is not easy, and I've played several Chopin preludes, nocturnes and waltzes before.  The other answers have already covered the things you need.  Basically, practice the rhythms with metronome again and again.  Focus on hitting the first of the semiquaver groups and first of the triplets exactly on the beat.
Also, this Youtube video from "BachScholar" is really good, and it explains precisely how to practice this:

Once you "get" this polyrhythm, though, you have the foundation for the rest of the piece, since 80% of it is based on that.  However, that doesn't mean the rest is easy. There are a lot of "blind" jumps on the left hand, uncomfortable (at first) right hand stretches, as well as non-stop music, so you have to build up your endurance.  The B section is really good for resting your fingers, but it too has some quirks so you have to pay attention. The last page/section is also pretty hard, and then you have to pay attention to dynamics, accents, etc.
In the end, it's totally worth it.  It's probably the piece I've spent the most time on in my entire life, but I'm ecstatic I'm now able to play it.  That being said, I don't think I would have been able to do this without having a piano teacher, so I'd highly recommend paying for some classes if you're able to.
Comment: Learn from this video that 'rushing' will be your main enemy!   Hear how even this skilled player is often having to pull himself back, just a little,  to avoid getting in front of the click.
Answer: I am doing this piece, and have "finished" the piece within 5 months (1h/day) and am right now polishing it. This is how I attempt most pieces. Note that this post is not a "for dummies" guide.
(Note 1 : Keep in mind that what makes this piece sound beautiful is that throughout the chaos of all the notes, there is an accented melody throughout the piece. )

Go slow! Correctness is more important than speed. However, do not go ridiculously slow, otherwise the piece ironically gets harder.
Practice the polyrhythm a lot. While playing, you can tell yourself "together, right, left, right, left, right, (cont...) "
As you get to the section where there there are high notes and notes an octave lower, know that the accents will be easier to play when the piece is faster.
At this point, hopefully, you are somewhat proficient in the first section (the song is in an A-B-A format). Aim to speed up the first section until you can hear the accent/melody. Add whatever dynamics in :)
Work on the part B; that is, the coordination easiest part of the song. This song requires a significant amount of endurance so your fingers don't die. Use this section as a rest period (but remember, there are occasional trills).
Again, the second section is just like the first, but this time, the polyrhythm is gone at the end.

Remember to add the following when you feel that you are ready:

dynamics (gradual volume changes and the pp and ff)
slurs
bring out the accent/melody
tempo changes
Answer: I had a teacher tell me to use "this is very easy". I would say that as I slowly played the section with the 4 against 3 rhythm. As you learn the notes and get used to the pattern eventually it should flow. I found a YouTube link with the rhythm. If you say this is very easy to it that should give you the idea.

I went about as slow as that video too when I started. It's great using those words too since you repeat over and over how easy it is.
To find the video I looked up polyrhythm and this is very easy I think. Don't think I even added the 4 against 3.
Oh right I also practices the rhythm away from the piano or while sitting at the piano but by hitting the keyboard or my lap. I probably did it at random throughout the day too.
That's great playing again. I keep thinking about it too. I've gone more than a decade now with hardly playing.
Answer: As addition to the other answers, this is how I learned to play those polyrythms on the piano:
Nr.1a
You focus on the triplets in the left hand and start with only two 16th in the right hand:

Nr.2a
 Then add the third 16th to the right hand:

Nr.3
and finally with the whole set of four 16th:

Another approach is starting with all 16th and build up the triplets like this:
Nr.1b

Nr.2b

Then Nr.3
It also is a good exercise to reduce it to the rhythm and tap it only with left and right hand on your knees. Like this you can practice the rhythm without sitting on the piano.
Answer: The first thing you should do is practice each hand separately and begin trying to feel the "pulse" of the half notes.
Then I would try to split up the tempo. Notice that the time signature is written in cut time. Try to play it in 4/4 time (with a triplet per beat). Start at quarter note = 80 and make your way up to quarter note = 160 (your goal) so that you have an easier time exploring the rhythm. And when this rhythm is played slowly, it's astonishingly beautiful.
There is a caveat with this as well. You will have a tendency to emphasize the third note of the triplet instead of emphasizing the entire group of six notes in the left hand like I did when I first played the piece when you play in 4/4 time (in reference to playing to 4/4 time, your emphasis should not be on beats 2 and 4 but on beats 1 and 3).
Once you have mastered 4/4 time, try going back to cut time. This will help you with the caveat I mentioned earlier. Your goal is to reach half note = 80, but if needed you can play slowly at first.
Lastly, when you have the technique and the notes are mastered and memorized, your final goal is to add your personality and rubato. At this point, I would take a short break from this piece if you have been practicing every day nonstop. You need time to contemplate the piece (and also at this point you would be sick and tired of the piece and it would be essentially impossible to play expressively).
Enjoy!
Answer: For playing the fast notes (so basically all of the notes), hit the key at the upper end of the key so this way you don't have to reach fingers to the accidentals. You'll also want to hit the notes using as little effort as possible so your hands won't get cramped.
NOTE: Make sure to use a real piano. Weighted keyboards will work but it's preferred to use an actual piano, so this way you don't develop a habit of always having unweighted keys.
Answer: I'm 13 and I can play this piece with an exaggerated left hand,(which is really annoying), the whole song sounds loud and can sometimes be a mess. Make sure once you perfect the piece that the song sounds fluent and clear but loose. The process of learning the song takes time and also can tire out your right hand once you get to the octaves part. It gets pretty difficult to play the song slowly because your brain is trying to rush the piece and play the song fast. Whatever you do, DON'T play fast when you first start off. It will be a pain to repeat parts that you messed up because your fingers are used to playing fast. The song is complex and has extremely fast bits, try to play slowly and gradually speed up. Also concentrate on the tempo, otherwise it'll sound like a jet engine going full speed by the end of the piece. The formula that my teacher came up with is LRLRLRBR, meaning the left hand note is first, then the right hand note, then left again, and right, left and right, then both notes, and finally right hand before repeating this cycle. The whole piece goes for around five minutes so you have to have strong and powerful fingers to play the song.
Answer: Im' no professional either and started the piece a few months ago. With a day job , a baby and so , i find 1 hour in the evening and practice it, and it starts to resemble a bit to something.
What i would say is start with very very very slow practice.
You can start with some Polyrythm exercices you find, but i started with the main theme of the piece where the left hand starts on the bass and the right hand starts off the beat because of a rest.
[![Section to train][1]][1]
What i would advise you is to always search first the notes that are played together.
[![Notes that are played together ][2]][2]
you will quickly start to realize that the notes that are being played together are the ones you play with your pinky and your thumb of your left hand. (except the rest on the first note you see sometimes) .
how do you go from there?
Fairly easy the polyrythm ask a form of alternation of notes you play .
Left Hand :  X - X - X - T - X - X - X - T
Right Hand:  R X - X - X T X - X - X - X T
X means you play the note, - means not playing a note, T means you play both notes together, and R is for rest.
As the right hand plays 16th notes, if you play both hands together, you always alternate first with your right hand again: if you would play a note with your right hand at the rest it would still be true.
To make it simple : Both hands together, RH, LH, RH, LH, RH, Both hands togther again etc.
And this is valid on almost the whole piece. If you get it in your hands by practicing slowly, you apply this to the whole piece almost.
Example for the middle part of the first section
[![enter image description here][3]][3]
I added numbers for the order in which notes are supposed to be played.
Focus first on notes 1 and 6 these are being played together.
After 1 your alternate first with RH then LF etc until you play 6 together again, and you repeat.
Hope it's clear.
[1]: https://i.stack.imgur.com/O5OMZ.png
[2]: https://i.stack.imgur.com/LyDhZ.png
[3]: https://i.stack.imgur.com/Eg0XI.png


Spring Boot - Erro ao redirecionar para pagina de listagem após exclusão de registro

Question: Estou iniciando com Spring Boot, minha dificuldade está em definir os redirecionamentos (caminhos). O erro atual ocorre no redirecionamento após a exclusão de um registro. Na pagina que lista todos os imóveis tenho as clássicas opções de Editar e Excluir, editar eu consegui redirecionar, mas após clicar no botão para excluir e tentar retornar para pagina que lista os imóveis, recebo o seguinte erro:
A URI fica com http://localhost:8080/imoveis/delete/imoveis/lista-imoveis, no retorno do método controller estou retornando "return "redirect:imoveis/lista-imoveis";". Tentei retornar somente return "lista-imoveis", não gera erro, mas aparece a tela de listagem sem registros e a URL "http://localhost:8080/imoveis/delete/121"
Whitelabel Error Page
This application has no explicit mapping for /error, so you are seeing this as a fallback.

Mon Jun 15 23:40:31 BRT 2020
There was an unexpected error (type=Not Found, status=404).
No message available

Minha @controller
@Controller
@RequestMapping("imoveis")
public class ImovelController {

@Autowired
private ImovelRepository imovelRepository;

@Autowired
private ImovelService imovelService;

@GetMapping
public List<Imovel> listar() {
    List<Imovel> imoveis = imovelService.listAll();
    return imoveis;
}

@RequestMapping ("/edit/{codigo}")
private String edit(@PathVariable String codigo, Model model){
    model.addAttribute("imovel", imovelService.obtemImovel(codigo));
    return "edit-imovel";
}

@RequestMapping ("/delete/{codigo}")
private String delete(@PathVariable String codigo){
    imovelService.delete(codigo);

    return "redirect:imoveis/lista-imoveis";
}

@GetMapping("/lista-imoveis")
public String lista_imoveis(Model model) {
    List<Imovel> imoveis = imovelService.listAll();
    model.addAttribute("imoveis", imoveis);
    return "lista-imoveis";
}

@GetMapping("/importacao")
public String importacao(Model model) {
    List<Imovel> imoveis = imovelService.importaImoveis();
    model.addAttribute("modulo", "IMOVEL");
    model.addAttribute("totalRegistrosImportados", imoveis.size());
    return "resultadoImportacao";
}

@GetMapping("/{idImovel}")
public Imovel buscar(@PathVariable Long idImovel) {
    try {
        return imovelService.findById(idImovel);
    } catch (RecursoNaoEncontradoException e) {
        throw new ResponseStatusException(HttpStatus.NOT_FOUND, "Imovel não cadastrado", e);
    }
}

@PostMapping("/save")
public String save(Imovel imovel, Model model) {
    imovelRepository.save(imovel);
    return "redirect:lista-imoveis";
}

@DeleteMapping("/{idImovel}")
public Optional<Imovel> excluir(@PathVariable Long idImovel) {

    Optional<Imovel> imovel = imovelRepository.findById(idImovel);
    imovelRepository.delete(imovel.get());

    return imovel;
}

@PutMapping
public Imovel editar(@RequestBody Imovel imovel) {
    Imovel imovelSAlvo = imovelRepository.save(imovel);
    return imovelSAlvo;
}

}

Tela lista-imovel.html
<?xml version='1.0' encoding='UTF-8' ?>
<!DOCTYPE html>

        <title>Lista Imóveis</title>

                            Código
                            Endereço
                            Locador
                            Ações

                        Editar
                        Excluir

Onde estou errando? Já fiz consultas no Google e na pagina do Spring, mas não consegui encontrar um tutorial que pudesse me fazer entender esse conceito. Alguém me indicaria algum site ou tutorial?
Answer: Então, consegui a solução. Utilizei o redirect, porém precisei colocar o caminho completo para listagem. Meu erro foi não incluir a primeira barra. Segue o método alterado:
@RequestMapping ("/delete/{codigo}")
private String  delete(@PathVariable String codigo){
    imovelService.delete(codigo);

return "redirect:/imoveis/lista-imoveis";

}


Rectangle exclusion by monominoes

Question: Here is the question: Given an $m\times n$ chessboard, what is the least number of monominoes can be placed on it so that the rectangle of shape $a\times b$ (or $b\times a$) can no longer be fitted onto the board? Here $a,b,m,n$ are positive integers and we assume that $a\leq m,b\leq n$.
Since the question seems quite classical, I wonder if it has already been (at least partially) solved somewhere, but unfortunately I can't find any reference.
Up to now, the following cases are known to me:

Either $a$ or $b$ is equal to $1$;
$a=b$.

It is likely that things would be easier if both $m$ and $n$ are multiples of $ab$, but I'm not sure to which extent does this assumption simplify the problem.
Any advice or hint is appreciated.
Comment: Presumably you do not allow the rectangle to be rotated? I.e., it is either oriented vertically or horizontally?
Comment: @JosephO'Rourke Rotation is allowed.
Comment: I've edited the question so that there should be no ambiguity.
Answer: A key search term is "blocking set." Here is one paper whose references and citations might lead you to useful literature.

Cano, J., García, A., Hurtado, F., Sakai, T., Tejel, J., & Urrutia, J. (2015). Blocking the $k$-holes of point sets in the plane. Graphs and combinatorics, 31(5), 1271-1287.

Rectangle exclusion by monominoes


For how long do I need to store the logs?

Question: I will soon be running an internet-based public service which will physically be hosted in the UK on a virtual server. The virtual server is provided by the ISP. I was wondering if there is/are any legal requirement(s) to keep access logs, and if yes - for how long?
There is a Wikipedia article that touches this subject but I'm afraid my brain just can't grasp the legislative gibberish.
I believe there's EU law and there's UK law; and I do need to comply to both, right?
Can somebody explain this in pure layman's terms?
Comment: You're asking an internet forum for legal advice? Of a non-hypothetical nature?
Comment: @jldugger: People make decisions: business, technical, legal. They seek advices, and (surprisingly!) they do it in this forum, too. There are chances that somebody gets misguided in a technical question/answer, and this will cost money to the business. And same applies to this legal question. I would understand your point if this was some unique situation, but this is pretty standard stuff, affecting literally tens (if not hundreds) of thousands of websites hosted in UK. Is it so hard just not to respond if you don't know the answer?
Comment: It's hard to decide whether to close this as off-topic or too localised. I can only suggest you seek appropriate legal advice.
Comment: On the Internet, there are many armchair lawyers. However, the advice you get from any or all of them would not be worthy of the trust you're looking for. The problem is that with any given situation, there's probably a loophole or a rarely-applied provision of some law, and inevitably it will apply to your situation. This is why we pay lawyers big money: to catch all of these twists and apply the correct one to our situation.
Answer: UK law and Statutory Instruments implement EU law (although the Government can be taken to court if it implements a law which contravenes EU law).
The most relevant pieces of legislation are the Regulation of Investigatory Powers Act 2000, the Data Protection Act 1998, and The Data Retention (EU Directive) Regulations. The Statute Law database is a good place to start.
RIPA specifies when you need to retain information, the DPA specifies when you need to get rid of it (unless you have a good reason not to). For most intents and purposes, the RIPA and DRR trumps the DPA: that is, the RIPA and DRR specifies the "good reasons not to" in the preceding sentence. Note, however, that if you're just operating a website, then you're not operating a Public Electronic Communications Network (PECN) or a Public Electronic Communications Service (PECS). You're definitely not a network, and a PECS is defined in the Communications Act 2003 as:

In this Act "electronic communications service" means a service consisting in, or having as its principal feature, the conveyance by means of an electronic communications network of signals, except in so far as it is a content service.

Thus, an ordinary website is a "a content service" and so not a PECS.
(Additionally, most of the regulations don't apply to you unless the Secretary of State has written to you to tell you to apply them).


Randomly Rotate text from a txt file in php

Question: I want to rotate text from a txt file
here is my below code but its not working, I don't know where I am getting thing wrong
 <?php
$text= file_get_contents("text.txt");

$arr = explode("\n", $text);

$max = count($arr);

$i = 0;
while($i < 3)
{
     $i++;
     echo $aText[rand(0, $arr)];
?>

In my text.txt file i have some text like
are
can
how
now
put
see

I want to out put it line by line but Its not working. Please help me out.
Comment: 1) where did you define `$aText` 2) `rand()` function take `min` and `max` parameters, you provide an array as the max value 3) your while loop doesn't have a closing curly bracket `}`
Comment: would `shuffle` not be a logical choice for this?
Comment: @catcon even after replacing `$aText` with `$text` and putting the `}` it is just out puting `aaa` thats all i see
Answer:      <?php

    $arr =   explode("\n", file_get_contents('text.txt'));

     foreach($arr as $key =>$value)
      {
        echo $value;//Prints the file content
      }

    ?>

Comment: your code output all the text in text.txt in one line
Comment: echo $value.'\n';


What test should I use see if there is a correlation between different populations and percentages of boats found in those locations?

Question: I am trying to see if there is a correlation between different location populations (in certain states in India and Bangladesh) and the percentage of boat counts found in each location. For a research project I had to count/locate boats on the Ganges River using GIS and now I need to see if there is any relation between how many boats were found in each location and the population of that location. I'm not very skilled with 'R' and thought it might be best to ask which test would be the best to find out this information.
The table that I have loaded into 'R' is the following data:
Answer: For the percentage of boat counts Poisson distribution would fit. It basically expresses given number of events occuring in a fixed time. In your case it could be number of boats located in a specific place (Ganges River) and time (depending on your interval).
Here you can find details about the distribution and here you can find simple tutorial how to apply it on R.
For the correlation part it also depends on what you would like to look at. In your case, it seems location population and the percentage of boat and simple linear regression can fit. Here you can find the theoretical background of it and here you can find how to apply it on R.


Register a broadcast receiver in a Service

Question: I have an Activity, this Activity will call a Service and that Service will call a broadcast to listen for SMS coming. I register a broadcast in the Service dynamically.
But it's not working. My code is below. Please help me resolve.
This is the onCreate method in the Service.
@Override
public void onCreate() {
    super.onCreate();
    final IntentFilter filter = new IntentFilter();
    filter.addAction("android.provider.Telephony.SMS_RECEIVED");

    this.registerReceiver(new BroadcastReceiver() {

        @Override
        public void onReceive(Context context, Intent intent) {
            showSuccessfulBroadcast();

        }
    }, filter);
}

Comment: check link : http://stackoverflow.com/questions/4462037/register-receiver-in-a-service
Comment: Post the code for `onStartCommand()` in your Service. Is your Service an `IntentService`?
Comment: Define "not working". Maybe you mean that your receiver method didn't get called when an SMS arrived?
Answer: The code is correct. Don't forget to declare used permission in AndroidManifest.xml, and to unregister receiver in onDestroy(). Both points are important.
<uses-permission android:name="android.permission.RECEIVE_SMS"></uses-permission>

Inside your Service
private BroadcastReceiver mSmsBroadcastReceiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        showSuccessfulBroadcast();
    }
};

@Override
public void onCreate() {
    super.onCreate();
    final IntentFilter filter = new IntentFilter();
    filter.addAction("android.provider.Telephony.SMS_RECEIVED");

    this.registerReceiver(mSmsBroadcastReceiver, filter);
}

@Override
public void onDestroy() {
    this.unregisterReceiver(mSmsBroadcastReceiver);
}

Comment: Not needed for dynamically registered broadcast receivers.


Applications of Mordell-Weil's theorem

Question: I've recently started to study elliptic curves and soon enough I came across the Mordell-Weil theorem.
It says, in particular, that if $E: y^2=f(x)$ is an elliptic curve with coefficients in $\mathbb{Q}$, then the set $E(\mathbb{Q})$ of rational points in $E$ is a finitely generated abelian group.
I agree it's an impressive result, but I still can't see any real use for it.
By "real use" I don't mean real-world applications, I'm actually interested in pure, conceptual math: what kind of concept or object does it help me to understand? What problems does it help me to solve? What kind of claim does it help me to prove? Or is it more helpful to disprove things?
I have some background in algebraic number theory, commutative algebra and basic algebraic geometry, so I might be able to understand examples
from those areas.
Any insights or references will be helpful, thanks!
Answer: The Mordell-Weil Theorem has many applications in modern number theory, and also to applied number theory, i.e., to cryptographic systems, see for example this article.
For the theory of elliptic curves over $\mathbb{Q}$, Mordell-Weil is essential to define the rank. This rank is very mysterious and there is a famous conjecture attached to it - the Birch-Swinnerton-Dyer conjecture.
More generally, we may also ask for rational points on algebraic curves in general, not just elliptic curves.
Here Mordell made also a conjecture that a curve of genus greater than $1$ over the field $\mathbb{Q}$ of rational numbers has only finitely many rational points. In $1983$ it was proved by Gerd Faltings.
Moreover, Mordell's conjecture/Falting's Theorem is a consequence of the abc-conjecture.
Comment: Finiteness of rational points on higher-genus curves is not Mordell--Weil; that is Faltings' solution to Mordell's conjecture.
Comment: @Nefertiti My god, of course the Mordell conjecture, I am sorry.
Comment: I think God will forgive you. :)
Answer: I wouldn't really see Mordell-Weil theorem as a tool for proving or disproving something. In every branch of math there are some fundamental and usually very broad questions that motivate the whole research in the field. In number theory (or arithmetic geometry), one of these fundamental questions is: take an algebraic variety over $\mathbb Q$; is it possible to find all of its rational points? Of course we are very far from answering this question in full generality, but Mordell-Weil gives you a good piece of an answer in the very specific case of elliptic curves. As mentioned in the answer above, elliptic curves are the most interesting case among smooth curves, since those of genus $>1$ have only finitely many rational points while those of genus  $0$ are either $\mathbb P^1$ or have no rational points. MW theorem is a structure theorem for the remaining case, and I think this already makes it deeply interesting.

Applications of Mordell-Weil's theorem


Views slideshow overlapping right hand sidebar block

Question: I'm using the default bartik theme and have created a views slideshow.  I have a url for this and have marked this as the front page under the admin section.  All great so far, in that when the (unauthenticated) user first visits the site they see the slideshow.  Once they log in, I have a block that appears in the right hand side sidebar.  However, the width of my slideshow is too wide in that it appears overlapped with this block on the right.  What is the best way to address this?  I could fix the width of the slideshow, but then that means I loose the flexibility to easily change the theme.
Also, can anyone point me to documentation that would help me understand why this happens?
Thanks in advance,
Comment: Sorry, this is Drupal 7.
Comment: Might be worth studying the CSS positioning attributes and seeing what can be adjusted there, there may be a rule that allows for this overlap that you don't want, and so it may be possible to switch it off.
Comment: What is the block that appears on the right?
Comment: It's a block containing a view of the last 5 items of a custom node.
Comment: I think I may know what the issue is, but I would be making assumptions. Can you provide a link/screenshot to the site?
Answer: I found two ways of resolving this.

Permissioning the splash screen so that only non authenticated users can see it.  That way, whenever anyone logs in they do not see the slideshow.
Use the corporate clean them - much better than anything I can develop!


Strict warning: Creating default object

Question: I am getting this error on my website.

Strict warning: Creating default object from empty value in theme541_preprocess_html()

I found a patch https://www.drupal.org/node/1242362 by Damien McKenna but I don't know how to apply the patch that fixes the error.
Comment: Hope this link will help you http://drupal.stackexchange.com/questions/23347/how-do-i-apply-a-patch-file
Answer: Applying patches is not actually a drupal specific issue and would be better on stack exchange, however there is a drupal documentation page so...
Check out the applying patches documentation.
However having said that, if you read that issue then you can see that patch was committed to that module 3 years ago and if you are using the latest release of the boron module (7.x-1.4) then that patch is already in there.
If you are applying the patch to something that isn't the boron theme then it will likely not work.

Strict warning: Creating default object


AEM 6.3 - How to read design properties within component helper for a dynamic editable template

Question: I have a dynamic editable template with design dialog at page component. The design properties are persisted under /conf/myapp/settings/wcm/policies/myapp like this:

My requirement is to read these page level design properties and use them inside an Image component. I have design dialog at component level as well. So when I do ${currentStyle.property}, it renders the component level design property.
Next I wrote a helper class like this:
<code>      Designer designer = currentPage.getContentResource().getResourceResolver().adaptTo(Designer.class);
      Design pageDesign = designer.getDesign(currentPage);
      Style pageStyle = pageDesign.getStyle(pageDesign.getPath());
      return pageStyle.get(PROPERTY_ANALYTICSPAGETYPE, String.class);
</code>
This code is trying to read page level design properties under /etc/designs/myapp authored under cq:designPath and NOT reading under /conf policies.
Now how I read the /conf policy nodes and access those properties?
How to access page level design properties within a component?
Answer: This should give you the desired result :
<code>ResourceResolver resourceResolver = this.request.getResourceResolver();
  ContentPolicyManager policyManager = (ContentPolicyManager)resourceResolver.adaptTo(ContentPolicyManager.class);
  if (policyManager != null)
  {
    ContentPolicy contentPolicy = policyManager.getPolicy(this.resource);
    if (contentPolicy != null) {
      this.myProperty = ((Boolean)contentPolicy.getProperties().get("myProperty", Boolean.valueOf(false))).booleanValue();
    }
</code>
Comment: Thanks for sharing. This worked except instead of getPolicy(this.resource), I had todo getPolicy(currentPage.getContentResource) since I wanted Page Level design policy.


Views filter criteria

Question:
I added a field to content type. The field type is select list.
I created a view. I added a filter criteria using the above field:
Operator > Is one of
Options > Select All is selected.
When I go to front end, I see -Any- selected by default but I dont the content/result. When I click Apply, i get the result. I am not sure why I have to click Apply to get the result. It should give me result as soon I go to views page.
Please help.
Comment: thats weird, you shouldn't need to hit the apply button. Try creating a new view and see what happens.
Answer: I just tested this and got the same problem as you.
I found the solution you need to check mark limit to selected items.
If you don't have the Limit list option, check marking the expose operator also fixes it. You would then have to use css to hide the expose operator if you don't want it.
Comment: I have created new view, created new content type and field. I still have the same problem. I just saw your answer and it solved it. I just had to place the check mark to the selected items. I have created this kind of view before, I don't think I had this kind of issue before. Thanks a lot.
Comment: @Drupol yeah seems the issue is with content type filtering. When using fields as a filter, it doesn't happen.

Views filter criteria


How to prove $0\le \lim\limits_{n\to\infty}\sum\limits_{i=1}^{n}\frac{1}{i+\frac{1}{i}}-\ln{\frac{n}{\sqrt{2}}}$?

Question:
Let $$x_{n}=\dfrac{1}{1+1}+\dfrac{1}{2+\frac{1}{2}}+\cdots+\dfrac{1}{n+\frac{1}{n}}
-\ln{\dfrac{n}{\sqrt{2}}},n=1,2,\cdots$$
  Show that
  $a=\displaystyle\lim_{n\to\infty}x_{n}$ exist and $0\le a\le\dfrac{1}{2}$

I know
since
$$\dfrac{1}{i+\dfrac{1}{i}}<\dfrac{1}{i}$$
so
$$x_{n}<1+\dfrac{1}{2}+\cdots+\dfrac{1}{n}-\ln{n}+\dfrac{1}{2}$$
and use Euler identity
$$1+\dfrac{1}{2}+\cdots+\dfrac{1}{n}-\ln{n}=C,n\to\infty$$
and
$$x_{n}>\dfrac{1}{2}+\dfrac{1}{3}+\cdots+\dfrac{1}{n+1}-\ln{n}+\dfrac{1}{2}$$
and then I can't
Answer: Define
$$f(x)=\frac{x}{1+x^2}$$
for $x\geq 1$. It is easy to cheack that it is decreasing. Note also that a primitive of $f$ is
$$F(x)=\frac12\log(1+x^2)$$
Define also, for $n\geq 1$,
$$a_n=\int_n^{n+1} [f(x)-f(n+1)]dx$$
Now,
$$\begin{align}
0&\leq a_n=F(n+1)-F(n)-f(n+1)\\
&\leq f(n)-f(n+1)
\end{align}$$
Now it is clear that $\sum_{n=1}^\infty a_n$ converges, and its sum is bounded by
$$\sum_{n=1}^\infty[f(n)-f(n+1)]=f(1)=\frac12$$
but
$$\sum_{k=1}^na_k=F(n+1)-F(1)-\sum_{k=1}^nf(k+1)$$
Thus,
$$\lim_{n\to\infty}\left[F(n)-\sum_{k=1}^nf(k)\right]=\lim_{n\to\infty}\left[\log\sqrt{1+n^2}-\sum_{k=1}^n\frac1{1+\frac1k}\right]=F(1)+\sum_{n=1}^\infty a_n$$
Answer: \begin{align}x_n&=\frac{1}{1+1/1}+\frac{1}{2+1/2}+...+\frac{1}{n+1/n}-\ln(\frac{n}{\sqrt{2}})\\&=\frac{1}{1^2+1}+\frac{2}{2^2+1}+...+\frac{n}{n^2+1}-\ln(n)+\frac{\ln2}{2}\\
&=\frac{1}{1}(1-\frac{1}{1^2+1})+\frac{1}{2}(1-\frac{1}{2^2+1})+...+\frac{1}{n}(1-\frac{1}{n^2+1})-\ln(n)+\frac{\ln2}{2}\\
&=(1+\frac{1}{2}+...+\frac{1}{n}-\ln(n))-(\frac{1}{1(1^2+1)}+\frac{1}{2(2^2+1)}+...+\frac{1}{n(n^2+1)})+\frac{\ln2}{2}\\&
\leq (1+\frac{1}{2}+...+\frac{1}{n}-\ln(n))-(\frac{1}{1(1^2+1^2)}+\frac{1}{2(2^2+2^2)}+...+\frac{1}{n(n^2+n^2)})+\frac{\ln2}{2}\\&
=(1+\frac{1}{2}+...+\frac{1}{n}-\ln(n))-\frac{1}{2}(1+\frac{1}{2^3}+...+\frac{1}{n^3})+\frac{\ln2}{2}=y_n
\end{align}
So we have $x_n\leq y_n$ for all $n$. On the other hand we have
\begin{align}
x_n&=(1+\frac{1}{2}+...+\frac{1}{n}-\ln(n))-(\frac{1}{1(1^2+1)}+\frac{1}{2(2^2+1)}+...+\frac{1}{n(n^2+1)})+\frac{\ln2}{2}\\
&\geq(1+\frac{1}{2}+...+\frac{1}{n}-\ln(n))-(1+\frac{1}{2^3}+...+\frac{1}{n^3})+\frac{\ln2}{2}=z_n
\end{align}
Hence $z_n\leq x_n\leq y_n$ for all $n$.
Now $$\lim_{n\to\infty}z_n\leq\lim_{n\to\infty}x_n\leq\lim_{n\to\infty}y_n$$
But $$\lim_{n\to\infty}z_n=\gamma-\zeta(3)+\frac{\ln2}{2}>-0.28$$
and
$$\lim_{n\to\infty}y_n=\gamma-\frac{\zeta(3)}{2}+\frac{\ln2}{2}<0.33<\frac{1}{2}$$
So
$$-0.28<\lim_{n\to\infty}x_n<\frac{1}{2}$$


SQL IF exist date by day do increment update else insert data

Question: How can I express the below statement as a SQL query ?
IF EXISTS (SELECT * FROM expense_history
           WHERE user_id = 40
             AND DATE_FORMAT(expense_history.created_date , '%Y-%m-%d') = '2018-06-02'
             AND camp_id='80')
    UPDATE expense_history
    SET clicks = clicks + 1,
        amount = amount + 1
    WHERE user_id = 40
      AND DATE_FORMAT(expense_history.created_date, '%Y-%m-%d') = '2018-06-02'
      AND camp_id = '80'
ELSE
   INSERT INTO expense_history (camp_id, created_date, amount, user_id)
   VALUES ('80', '2018-06-02 12:12:12', '1', '40')
END IF;

I just want to do increment clicks and amount if is set by day, else I want to add new row.
Comment: There is no `IF` in SQL - Which DBMS product are you using?
Comment: Possible duplicate of [Solutions for INSERT OR UPDATE on SQL Server](https://stackoverflow.com/questions/108403/solutions-for-insert-or-update-on-sql-server)
Comment: search for UPSERT
Comment: Is this on MySQL?
Comment: What version of MySQL?
Answer: I presumed your database is mysql, because of DATE_FORMAT() function(and edited your question as to be).
So, by using such a mechanism below, you can do what you want,
provided that a COMPOSITE PRIMARY KEY for camp_id, amount, user_id columns :
SET @camp_id = 80,
    @amount  =  1,
    @user_id = 40,
    @created_date = sysdate();

INSERT INTO expense_history(camp_id,created_date,amount,user_id,clicks)
VALUES(@camp_id,@created_date,@amount,@user_id,ifnull(clicks,1))
ON DUPLICATE KEY UPDATE
    amount = @amount + 1,
    clicks = ifnull(clicks,0)+1;

SQL Fiddle Demo
Answer: This is very tricky in MySQL.  You are storing a datetime but you want the date part to be unique.
Starting in MySQL 5.7.?, you can use computed columns for the unique constraint.  Here is an example:
create table expense_history (
  user_id int,
  camp_id int,
  amount int default 0,
  clicks int default 1,
  . . .
  created_datetime datetime,  -- note I changed the name
  created_date date generated always as (date(created_datetime)),
  unique (user_id, camp_id, created_datetime)
);

You can then do the work as:
INSERT INTO expense_history (camp_id, created_datetime, amount, user_id)
    VALUES (80, '2018-06-02 12:12:12', 1, 40)
    ON DUPLICATE KEY UPDATE
        amount = COALESCE(amount + 1, 1),
        clicks = COALESCE(clicks + 1, 1);

Earlier versions of MySQL don't support generated columns.  Nor do they support functions on unique.  But you can use a trick on a prefix index on a varchar to do what you want:
create table expense_history (
  user_id int,
  camp_id int,
  amount int default 0,
  clicks int default 1,
  . . .
  created_datetime varchar(19),
  unique (created_datetime(10))
);

This has the same effect.
Another alternative is to store the date and the time in separate columns.


Modifying a module's function from another module

Question: A particular module has a theme function (theme_nice_menus_build()) that I'd like to give a slightly different output; I'd rather not modify the .module file to be able to continue updating the module when new versions are available.
Is it possible to modify that function from another custom module or from template.php?
Answer: All theme functions can be overwritten in template.php by replacing theme with phptemplate.
so your function in template.php should be like
phptemplate_nice_menu_build


Numerical Solution for ODE with a squared term inhibiting use of Euler's Method

Question: I have this ODE:
$$A(x)\ddot{x}+B(x)\dot{x}^2+C(x) = 0$$
$A,B,C$ are functions of $x(t)$. Usually I'd solve this numerically using Euler's method but in this case the $\dot{x}^2$ is giving me problems since I cannot solve the equation for $x(t+\delta)$ because I have both $x(t+\delta)$ and $x(t+\delta)^2$.
What does one do in this case? I am open to using other numerical methods as well...
Answer: You should not use any Euler method to solve anything serious.
If you want to apply any Runge-Kutta or one-step method, you need to transform the ODE into a first order system
\begin{align}
\dot x &= v\\
\dot v &= -\frac{B(x)v^2+C(x)}{A(x)}
\end{align}
To this first order system you can now apply any Runge-Kutta method, not only the highly inefficient Euler method.
Comment: Thanks. Just to clarify, one thing. What I should do next is first solve for the velocity and then using the velocity, solve for the position, right?
Comment: No, you solve simultaneously as a vector valued system $\dot y=F(t,y)$ with $y=\begin{bmatrix}x\\v\end{bmatrix}$. Using $y_{k+1}=y_k+h·F(t_k,y_k)$ for the Euler method.


Hourly SQL Server 2005 Slowness (Possibly caused by SYSTEM)

Question: We're trying to diagnose the cause of slowness on our Database server.
We're running the latest rev SQL Server 2005 on Windows 2008x64.
The behavior that we're seeing is this: We see the SYSTEM process spike one of the CPUs for about 2 minutes, during this time SQL server slows down by a factor of 10. The slowness lasts until SYSTEM is done, then in an hour everything starts again.
During these slowdowns disk writes don't spike, paging doesn't spike, the only noticeable precursor we see is that SYSTEM maxes out one of the sixteen (HT)CPUs.
Note that this doesn't happen at the top of the hour, it just happens once an hour, and it shifts a bit depending on the length of the incident.
At the moment this is causing intermittent slowdowns, but when the server is really busy it can cause Worker Thread starvation.
The server is a Dual Quad Dell R710 with 96GB of RAM and RAID10 data/log disks.
Has anyone experienced this kind of problem? Does anyone know where we should look?
Edit: SQL Server Version is 9.0.4035
Comment: Please post your build number for SQL 2008. Anything else installed on the server?
Answer: We did quite a bit of experimentation on this:

We tried stopping Hyperic.
We tried freeing up one CPU for the OS to have.
We locked SQL server in memory and made sure to reserve 10GB for the OS.
We added and rebuilt lots of indexes.

Finally: We eliminated the periodic slowness by stopping the four DSM tasks associated with Dell OpenManage Server Administrator (OMSA).
Doing this immediately ended the periodic slowness issues and resulted in more consistent performance throughout the hour.
Comment: I've also seen a bad printer driver and the print spooler service on a SQL Server do this. If you are running a Print Spooler service on a SQL Server and don't need it running, then stop it and set it to Manual.


Qual o erro nesse INNER JOIN?

Question: Estou tentando fazer um update pegando a contagem de uma coluna de outra tabela com o mesmo cnpj + 1. Fiz todos os testes com os códigos inseridos dentro do contexto e todos funcionaram perfeitamente, mas quando vou fazer o update ele aparece o erro:

#1064 - Você tem um erro de sintaxe no seu SQL próximo a 'INNER JOIN (SELECT COUNT(n.numero) AS qtd_notas, n.prestador_cpfcnpj AS cnpjP...' na linha 3.

Não sei mais o que fazer, já tentei INNER, LEFT e é sempre o mesmo erro.
UPDATE cadastro c
SET c.ultimanota = (grup.qtd_notas + 1)
INNER JOIN (SELECT COUNT(n.numero) AS qtd_notas, n.prestador_cpfcnpj AS cnpjPrest
     FROM notas AS n
     WHERE n.prestador_cpfcnpj
     IN ( SELECT c.cnpj FROM cadastro AS c)
     GROUP BY n.prestador_cpfcnpj) AS grup
ON c.cnpj = grup.cnpjPrest;

Answer: Seu JOIN está na posição errada, ele deve vir antes do SET pois faz parte da especificação das tabelas:
UPDATE cadastro c
INNER JOIN (SELECT COUNT(n.numero) AS qtd_notas, n.prestador_cpfcnpj AS cnpjPrest
     FROM notas AS n
     WHERE n.prestador_cpfcnpj
     IN ( SELECT c.cnpj FROM cadastro AS c)
     GROUP BY n.prestador_cpfcnpj) AS grup
ON c.cnpj = grup.cnpjPrest
SET c.ultimanota = (grup.qtd_notas + 1);

Comment: Ahh, muito obrigado! Deu certinho <3

Qual o erro nesse INNER JOIN?


Collatz function iterates as a Markov chains

Question: In the Collatz Conjecture, the question is wether the sequence of iterates will always reach $1$ for all $n>0$ where $n\in\mathbb{Z^+}$. The formal Collatz function consists of the operations: $n/2$ for all even-parities of $n$, or $3n+1$ for all odd-parities.
There are three well known forms of the Collatz function; the formal, the shortcut and the reduced form. A conclusive proof of one form is analogous to the outcome of another form. I.e. the proof that one form is true implies that the other form is true and vice versa.
Starting with $n=12$, the following sequence is produced: $\{12,6,3,10,5,16,8,4,2,1\}$, and has stopping time $=9$.
Thats roughly a definition of the Collatz conjecture.

My question pivots around the idea of using a Markov model, preferably the markov chain to emulate Collatz sequences.

"..a Markov model is a stochastic model used to model randomly changing
systems. It is assumed that future states depend only on the current state, not on the events that occurred before it (that is, it assumes the Markov property).
"..the term Markov property refers to the memoryless property of a
stochastic process." -Wikipedia

Mathworld also mentions that the problem is connected to ergodic theory and markov chains.
Let $n_{i+1}$ be the future state, $n_{i}$ be the current state, and $n_{i-1}$ be the previous state.
$n_{i-1} \rightarrow n_{i} \rightarrow n_{i+1}$.
It is easy to show that it is impossible to know the previous state, by starting with two previous states $n_{i-1}=7$ and $n_{i-1}=44$.
For $n_{i-1}=7$, we get $n_{i} = 3n_{i-1}+1 = 3\cdot7+1 = 22$.
For $n_{i-1}=44$, we get $n_{i} = n_{i-1}/2 = 44/2 = 22$.
$7 \rightarrow 22 \rightarrow n_{i+1}$.
$44 \rightarrow 22 \rightarrow n_{i+1}$.
So when $n_{i}=22$, we do not know wether $n_{i-1} = 7$ or $n_{i-1} = 44$, refering to the memoryless property in the definition. So, for randomly chosen $n_{i}$ it is impossible to know what $n_{i-1}$ were.
If it is a hidden markov model, in that, "the state is not directly visible, but the output (in the form of data or "token" in the following), dependent on the state, is visible." what can be said about the model?

"A Markov chain is a stochastic model describing a sequence of
possible events in which the probability of each event depends only on
the state attained in the previous event"

I want to contract the process into the events where $n_{i} \rightarrow n_{i+1}$ or $n_{i-1} \rightarrow n_{i}$, using the binary expansion of $n$.
What kinds of things can be proven using a Markov model, in this case a markov chain on the bit-states of $n_{i}$ and $n_{i+1}$ in the Collatz conjecture ?
If we look at simple discrete dynamical systems in general, where the systems are based on binary states what kinds of things can be proven about it, with markov models?
Comment: It is unclear what the question is here.
Answer: Markov chains in the main apply to processes wherein at any given state $x_n$, the successor state $x_{n+1}$ takes a range of values, each with probability less than $1$.  In the case of the Collatz conjecture, any given state $x_n$ has a single fixed successor $x_{n+1}$ with probability $1$.  Therefore there is no probability involved.
In order to introduce probability and the idea of a Markov chain, one has to abstract away the actual numbers in question as Terrence Tao does in his 2011 blog post which I believe we have discussed before, in which he shows that on average one would expect any sequence to fall.
He does this by recognising that, in the absence of any knowledge of the specific sequence in question, one can deduce that $x_n$ will be odd half of the time and even the other half.  Then multiplying each odd number by $\approx3/2$ and dividing each even by $2$ we get that on average the sequence will fall.  This is the example of what can be done with the idea of a Markov chain.
Unfortunately, this says little about what any individual sequence will do - since (as he alludes to in that post) $\Bbb Z_2$ comes with its own Haar measure and $\Bbb Z$ is a measure zero subset of $\Bbb Z_2$ - and therefore any subset of $\Bbb Z$ could diverge irrespective of that the overall probabilistic statement might be.
Another way of understanding how abstracting away the specific numbers in question renders us unable to draw comprehensive conclusions, is that by abstracting them away, one must first introduce the assumption that the behaviour of $x_{n+1}$ is independent of $x_{n}$.  In actual fact, if we know $x_{n}$ then the behaviour of $x_{n+1}$ is NOT a random variable and $x_{n+1}$ isn't a random number even or odd with probability half.  Rather it is a determined number which is either even or odd with probability one.
It is also important (and I think you are in danger of not doing this) to recognise that $x_n$ being independent of $x_{n+1}$ is different to $x_{n+1}$ being independent of $x_n$.
Comment: Well put! (+1) for this
Comment: @NaturalNumberGuy maybe you're not in danger of failing to make that distinction. I thought I'd mention it just in case because it's a useful thing to be mindful of.
Comment: "It is also important (and I think you are in danger of not doing this) to recognise that $x_n$ being independent of $x_{n+1}$ is different to $x_{n+1}$ being independent of $x_n$." Did you read my initial post?
Comment: "It is also important (and I think you are in danger of not doing this) to recognise that xn being independent of xn+1 is different to xn+1 being independent of xn."  What?! See here: https://en.wikipedia.org/wiki/Independence_(probability_theory)#Two_events
Comment: @rukhin While $5$ has only one immediate successor $16$, the number $16$ has two possible predecessors - $32$ or $5$, so you don't have two events $A$ and $B$, you have one $B$ and two $A$'s. Moreover, in the form $3x+2^{\nu_2(x)}/\langle2\rangle$ more usually used for probabilistic analysis, you have infinitely many possible predecessors so $1$ following $1$ is different to $\{1,5,21,85,341\ldots\}$ being the predecessor of $1$. The probability of $1$ being the predecessor of $1$ is zero if you take the latter whereas the probability of $1$ following $1$ is $1$.
Comment: @rukhin did you understand my response about there being infinitely many $x_n$ for any given $x_{n+1}$ whereas there is only one $x_{n+1}$ for any given $x_n$ (since $f(x)=3x+2^{\nu_2(x)}/\langle2\rangle$ doesn't inject)?


Does Drupal 7 Entity Translation Translate?

Question: I've gone through the process of setting up Entity Translation and get the option for Translation, (for example a basic page). When editing the node, I get the translate tab, but see nothing there that actually translates. It appears that the functionality is the ability for the user or admin to supply the translation, and Entity Translation provides the link to the proper content depending on the translation option(s) specified by the user or browser, or other language selecting trigger.
I was hoping for an actual translation of content. Does that happen, or can it happen?
Modules installed and/or enabled on 7 include:

Entity Translation
Title
Entity
i18n
Variable
Localization Update
Answer: You need to edit your fields and make them translatable.
EDIT:
Ah, misunderstanding. Entity translations provides a user interface that allows you to translate entities. It doesn't translate itself.
What you are looking for in that case is Translation Management Tools*. It integrates with content translation, entity translation and more and allows to send text to a translator and save the translation in the correct place. There is a large list of supported translators, including a simple export/import, translation agencies, a local translator and Microsoft Translator, which is a machine translator and probably what you are looking for.
It's goal is to facilitate the management of a multilingual site with overviews, bulk operations, configurable review processes and a flexible, extendable architecture. It is, however, a new and large project, currently only available as an alpha and not every subsystem is finished. Notably, Microsoft Translator is currently broken because they changed their API, see http://drupal.org/node/1574516.
*Disclaimer: I am the maintainer of that project.
Comment: So... I'm taking that as a yes, translations *should* programatially happen? What do you mean by editing them to make them translatable? I think I've done that. In the case of "basic page", I've gone to administer>structure>content type>basic page>manage fields>body, and I check the "user may translate this field...
That suggests the USER translates it, not software.
Comment: Ah, misunderstanding. See my updated answer.