environment variable used with gradle intellij - spring boot

Question: I am building a Spring Boot Java application using the lattest version of IntelliJ built with gradle on Windows 7.
I am trying to leverage environment variables in my application.properties, one way I was able to get this functionality to work was to take the followimg steps.
If I change over from gradle to maven I am able to simply leverage the Environment Variable under the menus Run -> Edit Configurations.
Please let me know why this process does not work for gradle and if the below process is recommended.
from application.properties
MyApplication.log_level = ${LOG_LEVEL}

from build.gradle
setEnvVarRunConfiguration 'MyApplication', 'LOG_LEVEL', 'INFO'

def setEnvVarRunConfiguration( final String configuration, final String envName, final String envValue ) {
  final javaExecRunConfiguration = { task -> task instanceof JavaExec && task.name == "run $configuration" }
  tasks.matching(javaExecRunConfiguration).all { environment envName, envValue }
}

Comment: https://youtrack.jetbrains.com/v2/issue/IDEA-180652 may be the case.
Answer: File -> Setttings -> Build,Execution,Deployment > Build Tools > Gradle Runner
Ensure the checkbox "Delegate IDE build/run action to gradle" is unchecked
Comment: Might want to flesh this out, but I don't know why it got downvotes. It fixed this issue for me.
Comment: What is the updated version of this option ?


How to install apd in debian php5

Question: I have a debian etch server running php+apache. I am using php5-cli, php5-common, php5-mysql and php5-sybase. I want to use APD to profile my php code, but a php5-apd package is not available in debian. Even pear package is missing (only php4-pear is available). I do not want to downgrade to php4 for fear of breaking some thing. What would be the safe way to install apd for php5 in Debian Etch?
with regards,
raj
Answer: Debian don't always put the version number in the packages. Php Pear is just in as php-pear for version 5, the default version. See here
Once that is installed, the pecl tool will become available.
pecl install apd

Will install the latest version of apd for you. If you do anything to your php.ini or include paths, these may need to be modified to pick up the install.
Answer: APD is part of PECL. You can use the PECL installer to install the package:
pecl install apd

It will download, compile and install the package automatically. You may then need to enable it in php.ini.

How to install apd in debian php5


Call Stored Proc where Input is User Defined Data Type - Using Python

Question: This is Oracle PLSQL Code :
create or replace TYPE EMP_TYP IS OBJECT (
  EMP_ID VARCHAR2(36), EMP_NAM  VARCHAR2(50)
)
--
create or replace TYPE EMP_TAB IS TABLE OF EMP_TYP
--
create or replace PACKAGE BODY EMP_NEW_PKG
IS PROCEDURE EMP_INSERT_PROC (new_record     EMP_TAB) IS
BEGIN
INSERT INTO EMPLOYEE_MAIN_TABLE ( EMP_ID, EMP_NAM )
SELECT EMP_ID, EMP_NAM FROM TABLE ( new_record ) ;
COMMIT;
END;

How can I call this Stored Proc using Python ?
I tried Python Code,
args = [ '12345' , 'Rajan']
cursor.callproc('EMP_NEW_PKG.EMP_INSERT_PROC', args)

Getting Error as :
PLS-00306 : wrong number or types of argument in call EMP_NEW_PKG.EMP_INSERT_PROC.

Please help with code snippet / relevent reference.
Answer: You have to create a database object and pass that through to the stored procedure. Something like this (untested):
emp_type_obj = connection.gettype("EMP_TYP")
emp_obj = emp_type_obj.newobject()
emp_obj.EMP_ID = "12345"
emp_obj.EMP_NAM = "Rajan"

emp_tab_type_obj = connection.gettype("EMP_TAB")
emp_tab_obj = emp_tab_type_obj.newobject()
emp_tab_obj.append(emp_obj)

cursor.callproc("EMP_NEW_PKG.EMP_INSERT_PROC", [emp_tab_obj])

Comment: Tried the same getting same error
PLS-00306 : wrong number or types of argument in call EMP_NEW_PKG.EMP_INSERT_PROC
Comment: Ah, it looks like you have a table of these records. I have adjusted the code to address that.


How valuable is winning the coin toss in test cricket?

Question: Often in international test cricket the captain that wins the toss chooses to bat first. This is largely because the pitches tend to deteriorate meaning batting becomes more difficult and going first is an advantage. I wonder though, how much of an advantage is it to win the toss?
What percentage of test matches end with the team that won the the toss winning the the match? (How does this compare to the percent won teams losing the toss, and matches drawn?)
What's the average run score for teams who win the toss and teams that loose the toss?
*I'm after figures for the team winning the toss, not the team batting first - occasionally the toss winning captain will choose to bat second! However, it would be interesting to compare the figures for times toss winners bat first and second too!
Answer: There's more than one question here. Normally I'd point you to Cricinfo, where you could work this out, but here goes:
What percentage of test matches end with the team that won the the toss winning the the match?
Win toss, win match - 34.8043% - source: totals from Cricinfo Statsguru query
Lose toss,win match - 31.2556% - source: totals from Cricinfo Statsguru query
Win toss, draw match - 33.7579% - source: totals from Cricinfo Statsguru query
Lose toss,draw match - 33.7579% - source: totals from Cricinfo Statsguru query
From the same queries above, the average score for sides winning the toss is 31.71, which for sides losing the toss it's 31.9.
Answer: Just out of a practical point of view it matters a significant amount in Test cricket. Traditionally in five day cricket you really don want to bat in the 4th innings.
The pitch no matter how well prepared will have experienced wear and tear. By the fifth day it will show and your teams spinners will be having a field day. You can also experience variable bound for your seamers that generally make batting a nightmare.
Although this is true in most condition it is taken to the extreme in the Sub-Continent. There I must say the wickets are often very unsporting and by the fifth day the wickets are such a nightmare that batting becomes virtually impossible.
In those condition the team bating 1st and 3rd is at a great advantage.
Answer: To refine TrueDub's answer somewhat, we can completely ignore drawn and tied matches - obviously that's going to result in one win and one loss, and given that it's extremely unlikely for there to be any significant bias towards the "better" or "worse" team winning a coin toss, those results can be safely ignored for the purposes of seeing if winning the toss gives an advantage.
Out of the 1452 matches that ended in a (non-tie) result that Cricinfo gives data for, the team that won the toss won 765 (52.686%) of them, losing 687 (47.314%). From this it's reasonable to assume that winning the coin toss probably gives a slight advantage under at least some conditions, although not enough to be too much more significant than statistical noise.
Unfortunately, I do not believe it's possible to easily get the average runs scored for each team - TrueDub posted the average runs per wicket, but that can be heavily misleading as it is common for a Test match to end without 40 wickets being taken. It seems like Cricinfo does not have the numbers you are looking for, though.
TL;DR: The team that wins the toss wins about 1 in 40 more matches than they'd expect to.


Get active trails's siblings in menus

Question: I'm developing a custom theme using sub-theme just for learning purpose. In custom theme, I have added a custom block in which I need to display main menus' sub items if in_active_trail. I have already tried many times and wasted a lot time but unsuccessful.

Block should display when Level 1 is in_active_trails and it has child(s).
Block should not display when Level 1 in_active_trails but it has no child.
If any Level 2 is current page, display Level 2 and 3 menu items expect level 1.
Same as point 3, if Level 3 is current page then display level 3 and 2 items.

See attached image below for more understanding what I want to do.
Main Menu hierarchy
Answer: Here is the solution Menu Block. Install and configure it.
It works for me.

Get active trails's siblings in menus


Faz diferença ordenar os ifs/else ifs pelo mais provável de acontecer?

Question: Se eu fizer
if (muito provável)
    //faz algo
else if (alguma probabilidade)
    //faz algo
else if (bem pouco provável)
    //faz algo

é melhor que colocar em qualquer outra ordem?
Sem olhar a legibilidade, o que o domínio pede para fazer de forma mais intuitiva, só pensando na performance, é melhor fazer assim se precisar de otimização extrema? Ou dá na mesma colocar em qualquer ordem?
Considere que reordenar não muda o resultado.
Comment: Em que contexto isto se aplicaria ?! Em uma analogia imperfeita o peso de um piloto de F1 é um fator importante o de um motorista de carreta de 100 T irrelevante, na maioria dos sistemas a clareza do código é mais importante creio.
Comment: De extrema necessidade de otimização, conforme está na pergunta.
Comment: Ok , aí sim , e é para isto que este site foi feito.
Answer: Vou começar dizendo que isso sempre vai depender da implementação do compilador, qual é a arquitetura alvo que vai gerar e até de certas condições.
Os processadores modernos têm um mecanismo chamado branch prediction onde ele tenta "adivinhar" o que vai acontecer e começa processar antecipadamente o caminho que pode acontecer. Se ele fizer certo o ganho pode ser bem grande já que hoje em dia os processadores ganham performance executando várias linhas de processamento ao mesmo tempo (não estou falando de thread, é só o pipeline). Se ele errar é um problema porque tem que fazer algo de novo que já foi gasto tempo. Ele precisa acertar mais que errar para compensar.
Então se você colocar em certa ordem e isso prejudicar o algoritmo do processador e causar misprediction, pode ser uma péssima ideia.
E isso pode mudar em cada geração de processador, não é só a marca dele.
E claro, pode mudar o que o compilador faz também.
E o compilador pode não ajudar tanto porque ele pode até otimizar para um tipo de processador, x86 ou ARM, por exemplo, mas não pode otimizar para um modelo específico (teoricamente poderia, mas não compensa).
Lembrando que compiladores modernos permitem você dizer quais são mais prováveis (C e C++, especificado na linguagem).
Para execuções pontuais pode haver ganho, para muitas repetições provavelmente o ganho será inicial, depois o processador "aprende" o que provavelmente vai acontecer e já não tem ganho mais.
De forma geral pode haver algum ganho sim em colocar o mais provável antes, mas nunca confie nisso para todos os casos.
De qualquer forma não espere ganhos muito grandes na maioria dos casos.
Note que um switch pode ser diferente, ele é outra construção bem diferente, especialmente os muito longos, pode até inibir ou habilitar certas otimizações que ele pode fazer.
E até qual é a condição pode fazer uma diferença enorme. Se a condição demora muito para dar seu resultado a ordem dos ifs fará quase nenhuma diferença em qualquer caso, a não ser que o branch prediction se torne impossível, aí pode fazer uma enorme diferença. E o bloco que deve executar também pode fazer o todo ser irrelevante, o grosso do tempo gasto no código não depende do branch.
Conclusão
Se é tão importante tem que testar nas condições reais que serão executadas. Pode ser que consiga uma informação confiável. Aqui serve para dar uma base para pensar.
Coloquei no GitHub para referência futura.
Answer: Para fazer diferença, você teria de algum truque específico de compilador, indicando que o primeiro branch é o mais provável.
Por exemplo, o GCC possui a pseudo-função __builtin_expect(), que dentro do kernel do Linux é usada para compor as macros likely() e unlikely().
Alguns consideram que o branch prediction das CPUs modernas é tão bom que usar esse tipo de anotação explícita é otimização prematura e desnecessária.
Answer: O bom de organizar dessa maneira é que exigiria menos do seu processador, já que ele não precisaria validar diversos ifs falsos até encontrar o verdadeiro e dar continuidade ao código.
Comment: Sua resposta pode ser melhorada adicionando informações fundamentais. Basta [edit] para adicionar mais detalhes, como citações ou documentação para que outras pessoas possam confirmar que sua resposta está correta. Você pode encontrar mais informações sobre como escrever boas respostas [na Central de Ajuda](/help/how-to-answer).


Don't remove infoWindow on elsewhere click

Question: I use the mapFragment to display a map.
Since I wanted to disable the centering of the marker, when the marker is clicked, I implemented the following click listener:
@Override
public void onMapReady(GoogleMap map) {
    map.getUiSettings().setScrollGesturesEnabled(false);
    map.getUiSettings().setMapToolbarEnabled(true);
    map.setOnMarkerClickListener(new GoogleMap.OnMarkerClickListener() {
        public boolean onMarkerClick(Marker marker) {
            marker.showInfoWindow();
            return true;
        }
    });
    if (!event.getLatlgn().equals("")) {
        LatLng eventLocation = event.getLatlgn());
        Marker location = map.addMarker(new MarkerOptions().position(eventLocation).title(event.getLocation()));
        location.showInfoWindow();
        LatLng camera = Events.modify4Camera(event.getLatlgn());
        map.moveCamera(CameraUpdateFactory.newLatLngZoom(camera, 15));
    }
}

But when the user clicks anywhere else in the map, the info windows dissapears. How an I fix this? I want the info window to be always open.
Also since I implemented my own onMarkerClickListener, the toolbar in the bottom right corner is not displayed anymore... How can I display it on map load?
Answer: If you want to show the infoWindow when clicking anywhere in the map, you can programmatically show an info window by calling showInfoWindow(). Info windows are designed to respond to user touch events. Also, info window can be hiddden by calling hideInfoWindow().
Here's an example how to use showInfoWindow() method:
static final LatLng MELBOURNE = new LatLng(-37.81319, 144.96298);
Marker melbourne = mMap.addMarker(new MarkerOptions()
.position(MELBOURNE)
.title("Melbourne"));
melbourne.showInfoWindow();

For more details, you may try this demo app. This demo app includes showInfoWindow() method: https://github.com/googlemaps/android-samples/blob/master/ApiDemos/app/src/main/java/com/example/mapdemo/MarkerDemoActivity.java


App stop syncing after adding Mobile Ads SDK

Question: My app is working fine, but after adding Mobile Ads SDK, it stops syncing.
apply plugin: 'com.android.application'

android {
    compileSdkVersion 28
    defaultConfig {
        applicationId "abc
        minSdkVersion 16
        targetSdkVersion 28
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
        vectorDrawables.useSupportLibrary = true
    }
    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }

    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }

    sourceSets {
        main {
            assets.srcDirs = ['src/main/assets', 'src/main/assets/images', 'src/main/assets/databases']
            res.srcDirs =['src/main/res', 'src/main/res/menu', 'src/main/res/anim', 'src/main/res/values-ja']
        }
    }
}

dependencies {
    implementation fileTree(include: ['*.jar'], dir: 'libs')
    implementation 'com.android.support:appcompat-v7:28.0.0-rc02'
    implementation 'com.android.support.constraint:constraint-layout:1.1.3'
    implementation 'com.android.support:support-v4:28.0.0'
    implementation 'com.android.support:support-vector-drawable:28.0.0'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:1.0.2'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
    implementation 'com.sothree.slidinguppanel:library:3.4.0'
    implementation 'com.squareup.picasso:picasso:2.71828'
    implementation 'com.readystatesoftware.sqliteasset:sqliteassethelper:+'
    implementation 'com.google.android.gms:play-services-ads:17.1.1'
}

This is the error.

Manifest merger failed : Attribute
  meta-data#android.support.VERSION@value value=(26.0.2) from
  [com.android.support:recyclerview-v7:26.0.2]
  AndroidManifest.xml:25:13-35
        is also present at [com.android.support:customtabs:26.1.0] AndroidManifest.xml:25:13-35 value=(26.1.0).
        Suggestion: add 'tools:replace="android:value"' to  element at AndroidManifest.xml:23:9-25:38 to override.

I don't know what the error means, have anyone encountered the same problem?
Comment: Possible duplicate of [Android: Getting "Manifest merger failed" error after updating to a new version of gradle](https://stackoverflow.com/questions/43280871/android-getting-manifest-merger-failed-error-after-updating-to-a-new-version)
Answer: Problem:
Problem is support library version is getting conflicted.
Solution:
First step you need to try is using a common version of support library, you can declare a common variable:
supportLibraryVersion=28.0.0
And refer the same for all the dependencies of the same package:
implementation "com.android.support:appcompat-v7:$supportLibraryVersion"
implementation "com.android.support:support-v4:$supportLibraryVersion"

Second step:
You need to debug the dependencies list, use the ./gradlew dependencies command which will list dependencies tree. Analyse the dependencies tree, you will get to see which library is internally referring which version of the support library:
For example, this older version of the library:
com.android.support:recyclerview-v7:26.0.2
Answer: The mobile Ads SDK might have a support library version which is different that is being used in your application. The error clearly says that there is a different version in your AndroidManifest.xml file. The error also suggests -
add 'tools:replace="android:value"' to element at AndroidManifest.xml:23:9-25:38 to override
It also shows the lines where you need to add this. I think that should solve the problem.
Answer: Open Your AndroidManifest.xml .you will see Merged Manifest below it . Now from your error log.

[com.android.support:recyclerview-v7:26.0.2]
  AndroidManifest.xml:25:13-35 is also present at
  [com.android.support:customtabs:26.1.0] AndroidManifest.xml:25:13-35
  value=(26.1.0).

Your manifest is having conflict with two version for same library.So  click on  Merged Manifest and your will get

add 'tools:replace="android:value"' to element at
  AndroidManifest.xml:23:9-25:38 to override

Click on it . and issue will be solved.


Kernel density estimation on bounded support?

Question: I was looking for some way to deal with boundary bias of kde in case of a unit interval. One example is an usage of Chen estimators (or Beta estimators; an example might be seen here: http://stats-www.open.ac.uk/TechnicalReports/mcjdah.pdf -p.4) - instead of typical kernel density estimator $$ \hat{f}(x) =\frac{1}{n} \sum_{i=1}^{n}K(x,X_{i};h) $$ we obtain:
$$
\hat{f_{C1}}(x)=\frac{1}{nB(\frac{x}{h^2}+1,\frac{1-x}{h^2}+1)}\sum_{i=1}^{n}X_{i}^{x / h^2}(1-X_{i})^{(1-x) / h^2},
$$
where B() is beta function
The difficulty which I encountered is underflow problems in calculating beta function in case of large values of parameters. For example in R:
data <- runif(10000)

Chen_kde <- function(x,input,h=1/length(input)^(0.9)){

   p = x / h + 1
   q = (1-x) / h + 1

   output = mean(trans_data^(p-1)*(1-trans_data)^(q-1)/beta(p,q))
   return(output)
}

Chen_kde(0.1,data)

Warning message:
In beta(p, q) : underflow occurred in 'beta'

I found that one way to tackle this problem is to approximate a beta distribution with a normal density with equal mean and std deviation. However, each element of above mentioned sum is only "similar" to the beta distribution since x lies in exponent, not in base. My question is if in this example I can also approximate somehow each element to get rid of underflow problems or there can be some other successful methods to correct boundary bias of kde for unit interval.
Answer: Several methods to deal with density estimation on bounded support (including the estimation method proposed by Chen) are implemented in the bde package available from the CRAN repository. You may be interested in using it.


Python Logging - How to log as JSON str?

Question: I have a Python Django app where we need to log using below code snippet to allow ELK to index the log record as JSON
logger.info(json.dumps({'level':'INFO','data':'some random data'})

I have to use json.dumps() everytime . Is there a way in logging module to get rid of json.dumps() in every log message but still achieve the same functionality
Comment: Does this answer your question? [Python logging into file as a dictionary or JSON](https://stackoverflow.com/questions/50144628/python-logging-into-file-as-a-dictionary-or-json)
Answer: python-json-logger
do the job.
this article seems explain the approach to the solution.
You can customize the formatter, as suggested by @NicoCaldo
or in general use any other format like a 'pipe separated format' to communicate to ELK  like inthis example


A Qual Problem:Convergence of sum of Poisson random variable over sum of their mean

Question: Assume that $X_i$'s are independent  Poisson$(\lambda_i)$, and $\sum_i^\infty\lambda_i=\infty$. Show that $\frac{\sum_i^n X_i}{\sum_i^n\lambda_i}\rightarrow1$ almost surely.
I also tried to show weaker version: convergence in probability, yet I could not succeed. We know that $\sum_i^\infty\lambda_i=\infty$ implies $\sum_i^\infty X_i=\infty$ almost surely but i could not connect their rate of convergence to solve the problem.
For any help/hint/solution, thanks in advance.
Comment: Possible duplicate of [Sums of independent Poisson random variables](https://math.stackexchange.com/questions/2426186/sums-of-independent-poisson-random-variables)
Answer: What a coincidence... This problem was on my probability qual just a few days ago.
I think it's pretty straightforward when you use the version of Strong Law of Large Numbers that uses Kronecker's Lemma.
Or just embedding the sum in a Poisson process...


How to set custom user view mode for comments

Question: How do I control which view mode of a user account appears on different pages?
I have a Compact user view mode with two fields I want to appear in forum posts and comments. I then have a more complete user view mode I would like to have appear on the users home page and eventually i would like a different view mode for article bylines.
I cannot, for the life of me though, figure out how to actually have any of these display.
I want to modify the layout of user.html.twig for the user home pages to have additional headings and information. But then it gets used wherever the user entity appears. Am I suppose to create specific twig templates for every user appearance or is there some more sensible way to control the fields that appear?
I tried accessing specific user entity fields and styling them in templates such as node--forum.html.twig but I can only seem to access the complete user entity with {{ author_picture }} - why is it named that if it is the entire entity? or the user name with {{ author_name }}
How do I do this?
Answer: The variables {{ author_picture }} and {{ author_name }} are prepared in preprocess in the hook template_preprocess_node(). You can modify these variables or add your own in a custom preprocess hook.
Or you can make the field uid configurable in UI by modifying the field definition in the node entity:
mymodule.module
function mymodule_entity_base_field_info_alter(&$fields, $entity_type) {
  if ($entity_type->id() == 'node') {
    if (isset($fields['uid'])) {
      $fields['uid']->setDisplayConfigurable('view', TRUE);
    }
  }
}

and you'll find the Authored by field in the Manage Display page, where you can configure how the referenced user entity is formatted (which view mode is used).
A third and IMHO perferable option is to use the module Display Suite.


Prove by induction that $2^n\le (n+1)!$ for all $n\in\Bbb N$.

Question:
Prove by induction that $2^n\le (n+1)!$ for all $n\in\Bbb N$.

What I've done so far is prove for $n=1$:
$$2^1 \le (1+1)!,$$
$$2 \le 2,$$
which is correct
Then I tried to prove for $n+1$, in other words, I want to get here:
$$2^{n+1}\le(n+2)!.$$
So, I multiplied everything with $2$:
$$2\cdot 2^n \le2\cdot (n+1)!,$$
$$2^{n+1} \le2(n+1)n!.$$
So I already have what I wanted in the left part of the inequality, but I'm stuck for the right part.
Can someone help me?
Thanks!
Comment: So, your induction hypothesis is obviously that $2^k \leq (k+1)!$. You want to show that this implies $2^{k+1} \leq (k+2)!$. Well, $2^{k+1} = 2^k \cdot 2$, so using your induction hypothesis you can easily reason that $2^k \cdot 2 \leq (k+1)! \cdot 2$. Of course, $(k+2)! = (k+2)(k+1)!$. Is there any further you can say about the relationship between $k + 2$ and $2$? Well, $k \in \mathbb{N}$, so clearly $k+2 > 2$. That should complete the proof.
Comment: @lhf Yes, induction is needed. The proof by induction is *exactly* what you abbreviate with the dots.
Comment: Does one really need induction when it is clear that $(n+1)!= 1 \cdot 2 \cdot 3 \cdots n \cdot (n+1) \ge  1 \cdot 2 \cdot 2 \cdots 2 \cdot 2 = 2^n$?
Comment: This is a good point, lhf. Many of my professors have argued as much. In fact, one of them said that if I'm tempted to use ellipses, I should erase what I wrote and start writing a proof by induction. But I think your point is completely valid.
Comment: And another one https://math.stackexchange.com/questions/76946/prove-the-inequality-n-geq-2n-by-induction
Answer: Hint:
$$2\,(n+1)!<(n+2)\,(n+1)!=(n+2)!$$
Comment: It should be $\le$, not $<$.
Comment: @egreg: I supposed $n\ge 1$, as often students follow the convention that $\mathbf N$ starts at $1$.
Answer: hint
if n is a positive integer then
$(n+2)!\geq (n+1)!$so that
$(n+2)(n+1)!\geq2(n+1)!$
Btw that 2 comes from an easy proof by developping the parenthesis. Now use
($a<b<c\implies a<c$)
In your second inequality
Comment: agreed but...
i don't know how to get to (n+2)!
Comment: See the edit man
Comment: ok man, got it.
Comment: You're welcome please accept my answer
Answer: Since a hint has already been provided, I am supplying a combinatorial approach.  There are $(n+1)!$ permutations on the set $\{0,1,2,\ldots,n\}$.  Amongst these, consider permutations $\sigma$ such that, for any $k=0,1,2,\ldots,n$, there exists $j_k\in\{0,1,2,\ldots,n-k\}$ such that $\sigma$ maps $\{0,1,2,\ldots,k\}$ to $\left\{j_k,j_k+1,\ldots,j_k+k\right\}$.  Show that there are $2^n$ such permutations.
An Example:  Take $n=2$, and represent permutations as juxtapositions of labels $0$, $1$, and $2$.  Then, amongst all six permutations $012$, $021$, $102$, $120$, $201$, and $210$, only four of them ($012$, $102$, $201$, and $210$) are the special permutations we consider.


Native Android app with Drupal backend and Login

Question: I need to create a native Android app, this app will use Drupal as a back end.
The app must be native. All the back end functionality, will be taken care of in Drupal, even the login credentials. I will use JSON to get the data from Drupal
I have a few questions on what is possible.
Login credentials are stored in Drupal DB. How can i login to Android with these credentials? Can i use JSON and what about the password? The password need to be encrypted.
Is there something like a password protected JSON url? I don't want anyone not authorized to see the JSON url.
If you have any advice or suggestion please let me know.
I am new to Android and not an experienced programmer.
Thanks in advance
Comment: Your password protection is encryption (i.e. HTTPS). As for the rest of question, the answer will vary based on your Drupal version & what you're using for REST service (e.g. RestWS, Services, etc.).
Answer: You didn't mention your version of Drupal, and I cannot speak for D8. But D7 has the Services module, and this provides all the functionality you will need. We use the Oauth2 module (that ties in with Services) to provide the authentication mechanism for the apps we build. With this, the user will first log in with their credentials, from which they will receive an authentication token. This token is then used for all further communication between the app and the server.
The Services module is highly customizable, and can be used to code your own resoures that can be called through the API from the app. You can choose the output format, of which JSON is one option.
Shawn answered your questions regarding protection of the user's credentials. This is the same as with a browser - use HTTPS (SSL certificate) and the credentials will be protected. If you don't use HTTPS, the credentials will be there for anyone who looks.


Importing nodes from custom XML feed: how do I convert some XML fields into entity references?

Question: Here's the problem:
I'm migrating a Wordpress website to Drupal. It's a gaming portal with a highly customized Wordpress with custom fields, so we decided to generate some XML dumps from Wordpress, then use Feeds module to import that. There are two different "content types", games and articles about those games (strategy guides, tricks, so on). We have two content types, so we generate two XML files. All good so far.
The problem is that those two content types are related. To be precise, the "article" content type is always referred to a game. In Drupal terms, "article" contains an entity reference fields that points to a node of type "game".
Where's the problem?
Example: we have an article entitled: "8 tricks for Clash of Clans". This article refers to game "Clash of Clans". The problem is: in our XML we have "Clash of Clans", written in words. I want Feeds module to those words to Node IDs, then save those Node IDs as node references.
I want to do the same with some Taxonomy Terms.
Makes sense?
Comment: Probably you would have found some solution, can you please share because I have to implement the similar stuff for my work.
Answer: Maybe a bit late...
Do you know the feeds_tamper module?
But - I think you won't get around writing your own feeds_tamper plugin.
You have to parse your input field and search for node IDs, then replace it with the ID, as you wrote. This can not be done with feeds_tamper standard plugins, because even with REGEX-replace you don't have access the node IDs.


Angularjs Directive Error: ng:areq Bad Argument

Question: Why am I getting this error Error: ng:areq Bad Argument with below directive??
(function () {
    'use strict';

    angular.module('app.home')
        .directive ('centerTabs', {
            restrict: 'E',
            templateUrl: 'app/home/directives/html/center-tabs.template.html',
            controller: centerTabsController,
            controllerAs: 'centerTab',
            scope: {
                accountList: '=',
                emailsOpened: '=',
                contractsOpened: '='
            }
        });

    function centerTabsController() {...

And this is withinn HTML Template Below:

Comment: can you share the html for this directive
Comment: I have edited it with the html.. please see above.
Answer: Can you please restructure the directive like so, maybe its a syntax error.
The change is the properties are wrapped in an object and returned inside the directive!

var app = angular.module('myApp', []);

app.controller('MyController', function MyController($scope) {

});

app.directive('centerTabs', function() {
  return {
    restrict: 'E',
    // templateUrl: 'app/home/directives/html/center-tabs.template.html',
    template: '
hello!
',
    controller: function(){},
    controllerAs: 'centerTab',
    scope: {
      accountList: '=',
      emailsOpened: '=',
      contractsOpened: '='
    }
  };
});


Java Script regular expression for detecting non-ascii characters

Question: How can we use java script to restrict the use of non-ascii characters in a specific text field..? thanks in advance...
Comment: Dup: http://stackoverflow.com/questions/3465874/javascript-regex-to-reject-non-ascii-us-characters (I'm out of votes)
Comment: Do you want them removed or replaced?
Comment: @jnpcl Just an alert to the user will do...... removing them is also a good option
Comment: There are some jQuery Plugins that will do this. Some are [simple](http://plugins.jquery.com/project/aphanumeric), others are [robust](http://plugins.jquery.com/project/validate).
Comment: can you give me some "javascript" code..? i don't know how to use regular expressions in java script
Comment: @sasidhar - `can you give me some "javascript" code..? ` Why dosen't your company hire programmers?
Comment: @sln i am sorry, but i am student trying to learn... you could be more helpful than that i guess.
Comment: **str.replace(/[^\x20-\x7E]/g, '');** (Reference: https://www.w3resource.com/javascript-exercises/javascript-string-exercise-32.php)
Answer: Ascii is defined as the characters in the range of 000-177 (octal), therefore

function containsAllAscii(str) {
    return  /^[\000-\177]*$/.test(str) ;
}

console.log ( containsAllAscii('Hello123-1`11'));
console.log ( containsAllAscii('ábcdé'));

You probably don't want to accept non-printing characters \000-\037, maybe your regex should be /\040-\176/
Answer: I came accross this page trying to look for a function to sanitize a string to be used as friendly URL in a CMS system. The CMS is multilingual but I wanted to prevent non-ascii characters to appear in the URL. So instead of using ranges, I simply used (based on the solution above):
function verify_url(txt){
    var str=txt.replace(/^\s*|\s*$/g,""); // remove spaces
    if (str == '') {
        alert("Please enter a URL for this page.");
        document.Form1.url.focus();
        return false;
    }
    found=/^[a-zA-Z0-9._\-]*$/.test(str); // we check for specific characters. If any character does not match these allowed characters, the expression evaluates to false
    if(!found) {
        alert("The can only contain letters a thru z, A thru Z, 0 to 9, the dot, the dash and the underscore. No spaces, German specific characters or Chinese characters are allowed. Please remove all punctuation (except for the dot, if you use it), and convert all non complying characters. In German, you may convert umlaut 'o' to 'oe', or in Chinese, you may use the 'pinyin' version of the Chinese characters.");
        document.Form1.url.focus();
    }
    return found;
}


masstransit semver error on rake build

Question: I keep getting the following error when trying to build the masstransit source from github:
Building for .NET 3.5
rake aborted!
no such file to load -- semver

(See full trace by running task with --trace)

with the --trace switch I get:
Building for .NET 3.5
rake aborted!
no such file to load -- semver
C:/Ruby192/lib/ruby/site_ruby/1.9.1/rubygems/custom_require.rb:36:in `require'
C:/Ruby192/lib/ruby/site_ruby/1.9.1/rubygems/custom_require.rb:36:in `require'
C:/Users/****/Dev/Scratch/MassTransit/build_support/versioning.rb:1:in `<top (required)>'
C:/Ruby192/lib/ruby/site_ruby/1.9.1/rubygems/custom_require.rb:36:in `require'
C:/Ruby192/lib/ruby/site_ruby/1.9.1/rubygems/custom_require.rb:36:in `require'
C:/Users/****/Dev/Scratch/MassTransit/rakefile.rb:10:in `<top (required)>'
C:/Ruby192/lib/ruby/gems/1.9.1/gems/rake-0.9.2/lib/rake/rake_module.rb:25:in `load'
C:/Ruby192/lib/ruby/gems/1.9.1/gems/rake-0.9.2/lib/rake/rake_module.rb:25:in `load_rakefile'
C:/Ruby192/lib/ruby/gems/1.9.1/gems/rake-0.9.2/lib/rake/application.rb:495:in `raw_load_rakefile'
C:/Ruby192/lib/ruby/gems/1.9.1/gems/rake-0.9.2/lib/rake/application.rb:78:in `block in load_rakefile'
C:/Ruby192/lib/ruby/gems/1.9.1/gems/rake-0.9.2/lib/rake/application.rb:129:in `standard_exception_handling'
C:/Ruby192/lib/ruby/gems/1.9.1/gems/rake-0.9.2/lib/rake/application.rb:77:in `load_rakefile'
C:/Ruby192/lib/ruby/gems/1.9.1/gems/rake-0.9.2/lib/rake/application.rb:61:in `block in run'
C:/Ruby192/lib/ruby/gems/1.9.1/gems/rake-0.9.2/lib/rake/application.rb:129:in `standard_exception_handling'
C:/Ruby192/lib/ruby/gems/1.9.1/gems/rake-0.9.2/lib/rake/application.rb:59:in `run'
C:/Ruby192/lib/ruby/gems/1.9.1/gems/rake-0.9.2/bin/rake:32:in `<top (required)>'
C:/Ruby192/bin/rake:19:in `load'
C:/Ruby192/bin/rake:19:in `'

Is this supposed to be able to build out of the box or am i missing something?
Answer: DOH!!
gem install albacore
gem install semver2

https://github.com/phatboyg/MassTransit
:)
Comment: fixed - nowadays Chris has added a fake SolutionVersion.cs file as well, so this shouldn't be needed anymore if you aren't looking to create nugets

masstransit semver error on rake build


Multisite- different localizations and domains but same codebase and user base

Question: I have an established site which caters to Australian market and now I want to launch a similar site for US market.

New site will have a different domain
New site will have different content

However, I want both sites to share code and users so that someone who has an account on Australian site should be able to log in to US site plus any changes in code should reflect on both sites.
Sorry I am bit a knoob and will appreciate some guidance.
Comment: I have a dedicated server - Linux.
Answer: You're going to have lots of fun with this one if you're a "knoob".
The module you want to look at is Domain Access. This will do pretty much exactly what you want to do. It's a slightly heavy configuration so if you are new, then you might struggle but you can probably get some assistance on #drupal-support on freenode.


how to count a repeating string in a line using perl

Question: I have the below file
file1:
abc def host 123 host 869 host
I wrote below script to count the occurrence of a "host" keyword in each line.
I tried all the ways(refer the ones which are commented) still it does not seem to work. sed command worked in command line but not inside the perl script
#!/usr/bin/perl
open(SOURCE,"</home/amp/surevy01/file1");
open(DESTINATION,"</home/amp/surevy01/file2");
while(my $line = <SOURCE>)
    {
  while(my $line1 = <DESTINATION>)
     {
        #chomp($line);
        #chomp($line1);
            if ($line =~ "host")
            {
            #my $count = grep {host} $line;
            #my $count = `sed -i {s/host/host\n/g} $line1 | grep -c {host}`;
            #my $count = `perl -pi -e 's/host/host\n/g' $line1 | grep -c host`;
            #my $count grep ("host" ,$line);
            print "$count";
            print "match found \n";
            next;
            }
           else
            {
               print "match not found \n";
               exit;
            }
      }
    }

I'm a beginner to perl. Looking for your valuable suggestions
Comment: This is an off topic comment but: you should use 3-argument `open` with lexical file handles and check for success (as in `open( my $fh_in, '<', $filename) or die "cannot open $filename: $!\n"`) _and_ you shouldn't name a read-only filehandle `DESTINATION`. This will only confuse you (and others) later. And please always `use strict; use warnings;`.
Comment: Possible duplicate of [Counting number of occurrences of a string inside another (Perl)](https://stackoverflow.com/questions/9538542/counting-number-of-occurrences-of-a-string-inside-another-perl)
Answer: Your own solution will match instances like hostages and Shostakovich
grep is the canonical way to count elements of a list, and split will turn your line into a list of words, giving
my $count = grep { $_ eq 'host' } split ' ', $line

Answer: This produces the number of instances of host in $line:
my $count = () = $line =~ /host/g;

But that also matches hosting. To avoid that, the following will probably do the trick:
my $count = () = $line =~ /\bhost\b/g;

=()= this is called Perl secret Goatse operator. More info
Answer: I don't know why you're looping through two files in your example, but you can use the /g (global) flag:
my $line = "abc def host 123 host 869 host";

my $x = 0;
while ($line =~ /host/g){
    $x++;
}
print "$x\n"; # 3

When you run a regex with /g in scalar context (as is the conditional in the while statement), it will keep track of the location of the last match and restart from there. Therefore, /host/g in a loop as above will find each occurence of host. You can also use the /g in list contexts:
my $line = "abc def host 123 host 869 host";
my @matches = $contents =~ /host/g;
print scalar @matches; # 3 again

In this case, @matches will contain all matches of the regexp against the string, which will be ('host', 'host', 'host') since the query is a simple string. Then, scalar(@matches) will yield the length of the list.
Comment: You probably want `/\bhost\b/` to avoid, for example, matching `hosting`


make space in a list with string

Question: Hi is there any function that takes a list
['-x','+2x','-3x']
and makes a space after the operators like this
['- x','+ 2x','- 3x']
Thanks in advance!
Comment: please make an attempt before asking.
Comment: There's most likely no such function - you'll have to write one yourself
Comment: Is the operator always present, always one character, and always the first character? If so this is trivial using basic string slicing.
Answer: string = ['-x','+2x','-3x']
newString = [ n1.replace('-','- ').replace('+','+ ') for n1 in string ]
print(newString)
['- x', '+ 2x', '- 3x']

Comment: Welcome to Stack Overflow. Code dumps without any explanation are rarely helpful. Stack Overflow is about learning, not providing snippets to blindly copy and paste. Please [edit] your question and explain how it works better than what the OP provided. See [answer].
Answer: You could inert a space at the second position for each string in the list using a list comprehension:
terms = ['-x','+2x','-3x']
terms = [t[:1]+' '+t[1:] for t in terms]

['- x', '+ 2x', '- 3x']

make space in a list with string


How to show $(A \cap B^c \cap C^c) \cup (A \cap B \cap C^c) \cup (A \cap B^c \cap C) = A\backslash(B \cap C)$?

Question: I should show the following equation with the rules for sets:
$(A \cap B^c \cap C^c) \cup (A \cap B \cap C^c) \cup (A \cap B^c \cap C) = A\backslash(B \cap C)$
I drew the diagramms for the sets and so it is logical that the equality must hold. But i don't know how to who that with the rules for the sets.
Anyone here who could help me with that?
Comment: Drawing the diagrams is already an excellent start. Do you know the rules how to 'multiply out' unions, ie $(X \cap Y) \cup Z=(X \cup Z)\cap (Y \cup Z)$?
Comment: I know them with just one set out of the brackets but i have never done that with such a long expression like the left side of my equation.
Answer: Note that
$$(A\cap B^{c}\cap C^{c})\cup(A\cap B\cap C^{c})\cup(A\cap B^{c}\cap C)$$
$$=((A\cap B^{c}\cap C^{c})\cup(A\cap B\cap C^{c}))\cup((A\cap B^{c}\cap C^{c})\cup(A\cap B^{c}\cap C))$$
$$=(A\cap C^{c})\cup(A\cap B^{c})=(A\setminus C)\cup(A\setminus B)=A\setminus(B\cap C)$$
where in the second equation we use the fact that
$(U\cap V)\cup(U\cap V^{c})=U$.


Find equivalence classes of x ~ y : <=> x-y ∈ Z

Question: The equivalence relation is:
$$X=\mathbb{R}$$
$$x∼y:⇔x−y∈\mathbb{Z}$$
I proved the relation properties but how can I find the equivalence classes?
Also I was wondering whether the equivalence relation above is the same as the following?
$$n∈\mathbb{N}$$
$$x∼y:⇔n|x−y$$
Does this help?
Is it related to congruence?
Also, I think x and y must have the same decimal expansion, does this help?
EDIT: Thank you all for your help.
Comment: You pretty much said the answer yourself: $x,y\in \mathbb{R}$ is in the same equivalence class if their 'decimal part' is the same: for instance, $0.5\sim 1.5 \sim 2.5 \sim 3.5 \sim 4.5 \sim \cdots$ etc
Comment: Just find a set $X$ which contains every decimal part just once; the equivalence classes are then uniquely given as $[x]=x+\mathbb Z$ for $x\in X$.
Comment: Can I somehow write that down in a formal way for all x in R?
Comment: A complete set of representatives is made up of the points in $[0,1)$.
Answer: I think someone posted an answer before but it seems it is deleted now. Anyway consider $[x]$ the equivalence class for some $x\in \mathbb{R}$.
If $y\in [x]$ then $x\sim y$ so $y-x\in \mathbb{Z}$. Then $y\in x+\mathbb{Z}$.
Conversely if $y\in x+\mathbb{Z}$ then $y-x\in \mathbb{Z}$ so $y\sim x$ and $y\in [x]$
So $[x]\subseteq x+\mathbb{Z} \subseteq [x] \implies [x]=x+\mathbb{Z}$.
Comment: This makes sense to me, thanks! With [x]=x+Z the decimal part must always be the same.


Ionic4: PDF upload to server

Question: I need to upload PDF file to server using form-group how i do it or any possible way to do it same. I'll try file chooser plugin but that was not supported in ios
Comment: have a look on [file-transfer](https://ionicframework.com/docs/native/file-transfer/) plugin of ionic
Comment: but to pick file first because file chooser plugin not work in ios
Answer: you can use file chooser plugin conditionally
check platform using : https://ionicframework.com/docs/angular/platform
<code>if(this.platform.is('ios')){
    // run ios code
}
else{
    // run android code
}
</code>
For ios :  https://ionicframework.com/docs/native/file-picker
For android :  https://ionicframework.com/docs/native/file-chooser
Then use file transfer plugin to upload : https://ionicframework.com/docs/native/file-transfer

Ionic4: PDF upload to server


Iterating on group of columns in a dataframe from custom list - pandas

Question: I have a dataframe df like this
TxnId     TxnDate           TxnCount
  100     2023-02-01      2
  500     2023-02-01      1
  400     2023-02-01      4
  100     2023-02-02      3
  500     2023-02-02      5
  100     2023-02-03      3
  500     2023-02-03      5
  400     2023-02-03      2

I have the following custom lists
datelist = [datetime.date(2023,02,03), datetime.date(2023,02,02)]
txnlist = [400,500]

I want to iterate the df as per below logic:
for every txn in txnlist:
     sum = 0
     for every date in datelist:
           sum += df[txn][date].TxnCount

I would also be interested to understand how to find average of TxnCount for filtered TxnIds.
After Sum step based on above input and filters:
 TxnId         TxnCount
  400          2
  500          10

Average corresponding to TxnId 400 = (2+0)/2 = 1
Average corresponding to TxnId 500 = (5+5)/2 = 5
If average > 3 , add row from dataframe to breachList
breachList =[[500,10]]

Please help me how to do this in pandas
Comment: How looks expected ouput?
Comment: Added my expectation in the question @jezrael
Answer: Filter DataFrame by both lists first by boolean indexing with Series.isin:
df1 = df[df['TxnId'].isin(txnlist) & pd.to_datetime(df['TxnDate']).dt.date.isin(datelist)]
print (df1)
   TxnId     TxnDate  TxnCount
4    500  2023-02-02         5
6    500  2023-02-03         5
7    400  2023-02-03         2

And then for sum of column TxnCount per groups:
out = df1.groupby('TxnId', as_index=False)['TxnCount'].sum()
print (out)
   TxnId  TxnCount
0    400         2
1    500        10

EDIT: If need filter TxnId by average, here greater like 4 use:
df1 = df[df['TxnId'].isin(txnlist) & pd.to_datetime(df['TxnDate']).dt.date.isin(datelist)]
print (df1)
   TxnId     TxnDate  TxnCount
4    500  2023-02-02         5
6    500  2023-02-03         5
7    400  2023-02-03         2

#create averages per TxnId
out = df1.groupby('TxnId')['TxnCount'].mean()
print (out)
TxnId
400    2
500    5
Name: TxnCount, dtype: int64

#get TxnId greater like 4
TxnId = out[out > 4].index
print (TxnId)
Int64Index([500], dtype='int64', name='TxnId')

Filter rows in df or df1:
df2 = df[df['TxnId'].isin(TxnId)]
print(df2)
   TxnId     TxnDate  TxnCount
1    500  2023-02-01         1
4    500  2023-02-02         5
6    500  2023-02-03         5

df3 = df1[df1['TxnId'].isin(TxnId)]
print(df3)
   TxnId     TxnDate  TxnCount
4    500  2023-02-02         5
6    500  2023-02-03         5

EDIT1:  For expected ouput use:
First filter by lists (for avoid processig all rows):
df1 = df[df['TxnId'].isin(txnlist) & pd.to_datetime(df['TxnDate']).dt.date.isin(datelist)]
print (df1)
   TxnId     TxnDate  TxnCount
4    500  2023-02-02         5
6    500  2023-02-03         5
7    400  2023-02-03         2

Pivoting for all combinations TxnDate/TxnId :
out = df1.pivot_table(index='TxnId',
                      columns='TxnDate',
                      values='TxnCount',
                      aggfunc='sum',
                      fill_value=0)
print (out)
TxnDate  2023-02-02  2023-02-03
TxnId
400               0           2
500               5           5

Last filtered summed values by means per rows and convert to lists:
breachList = out.sum(axis=1)[out.mean(axis=1).gt(3)].reset_index().to_numpy().tolist()
print (breachList)
[[500, 10]]

Comment: Thanks a lot. This is very elegant. @jezrael
 Instead modifying the TxnCount column inplace, If i need to find the average of TxnCount for every TxnId in df1 and populate those rows matching to a condition lets say avg > 4 into a separate list/dataframe. How do we do that?
Comment: @KurinchiMalar - Do you think `df1.groupby('TxnId', as_index=False)['TxnCount'].mean()` ?
Comment: @KurinchiMalar - Yes, but problem is if mising some combinations, then it count only from `4` instead `0,4`. So need pivoting for `0` and then processing like in `EDIT1`
Answer: The fact that your are using a nested loop is reminiscent of a 2D pivot_table (or crosstab):
df['TxnDate'] = pd.to_datetime(df['TxnDate'])

out = (df.pivot_table(index='TxnId', columns='TxnDate',
                      values='TxnCount', aggfunc='sum'
                      fill_value=0)
         .reindex(txnlist, datelist)
       )

Output:
TxnDate  2023-02-03  2023-02-02
TxnId
400               2           0
500               5           5

And if you want to further aggregate on Ids (or Date):
out.sum(axis=1)

TxnId
400     2
500    10
dtype: int64


A question about Histogram-to-distribution transformation

Question: I have done a simulation with 1 million runs on Matlab. I have got a histogram for this. Using Matlab command hist(X), (where X is the 1 million samples as results of my simulation), I get the distribution all right.
Now I have to show these results in my paper, I understand that the y-axis for the distribution is a probability, but what should I name this probability, Probability of what?
(Note that on the x-axis for the histogram and of the density diagram, I have data-rate in bits/second)
Comment: Many scientists are taught (from secondary school) to show units of measurement explicitly on graph axes. That good practice would lead us to explain one histogram axis as (e.g.) "density (probability per metre)" or "frequency in 10 m bins": clearly densities are relative to units of the other axis and frequencies are dependent on bin width. I see that done only rarely and I suppose it's partly because almost everyone is copying almost everyone else. Nevertheless I've often seen squawks that a density plot must be wrong as some or all densities exceed 1, which imply not thinking about units.
Answer: Elementary textbooks often show 'frequency' $f$ or 'relative frequency' $r =f/n$ on the vertical axis of a histogram, where $f_i$ is the frequency of the $i$th interval and $n$ is the number of observations in the sample represented.
However, the basic principle of the histogram is area. The area of each bar (bin width times height) represents that bar's percentage of the $n$ observations shown in a histogram. So if you're trying to match a histogram with the density function of a continuous distribution, then you should put 'density' on the vertical axis.
Density histogram. Here is a histogram of a random sample of size $n = 1000$ from the population
$\mathsf{Norm}(\mu = 100,\, \sigma = 15)$ along with the density function of that distribution. The histogram is made using R statistical software, in which
the argument prob=T of the function hist is used to put "Density" on the
vertical axis.
set.seed(1886);  x = rnorm(1000, 100, 15)
summary(x);  sd(x)
   Min. 1st Qu.  Median    Mean 3rd Qu.    Max.
  46.61   89.59   99.20   99.43  109.74  151.70
[1] 15.16357

hist(x, prob=T, br=15, col="skyblue2",
    main="Sample of 1000 from NORM(100, 15) with Density")
  curve(dnorm(x, 100, 15), add=T, col="red", lwd=2)

The height of the fifth bar (80-90) is 0.0158 and the bin width is 10
so the area of this bar is 0.158. The area under the normal
curve between 80 and 90 is 0.1613. (The total area of all the bars is $1.)$
diff(pnorm(c(80,90), 100, 15))
[1] 0.1612813

Frequency histogram. By contrast, here is a frequency histogram of the first 100 observations in
this same sample. The argument label=T causes frequencies to be plotted atop
each bar; additional statements add horizontal reference lines and put tick marks to show the location of each of the 100 observations (some too close together to count individually at the resolution of this figure).
 hist(x[1:100], col="skyblue2", ylim=c(0,35), label=T,
     main="Frequency Histogram of 100 Normal Observations")
 abline(h=seq(0, 35, by=5), col="green2");  rug(x[1:100])

Comment: (+1) Nicely crafted mix of mathematics, code and graphics.
Answer: It depends on what you're plotting. Here are some possibilities. The relative heights of the histogram bars will be the same in all of these cases; only the units are different.

If the histogram shows the number of data points in each bin, then the y axis should be labeled "count" or "frequency".
If the histogram shows the fraction of points in each bin, then the y axis should be labeled "relative frequency".
If the histogram is treated as a continuous probability density estimate (i.e. the 'x' variable is continuous, and the histogram has been normalized such that it integrates to one), then the y axis should be labeled "density" or "probability density".
In some cases, the y axis can be omitted entirely to reduce visual clutter. This should only be done when the absolute units don't matter, and the title/caption makes it clear what's being plotted.

Often, the y axis label doesn't need to specify the variable, as it will already be clear from the x axis label and the title/caption. There may be cases where the alternative makes sense, depending on taste and context. For example, suppose you were studying the data rate of widgets. You might label the x axis "Data rate (bits/s)" and the y axis "Number of widgets" or "Fraction of widgets" (depending on what you're plotting). If you have a continuous density estimate, then only "density", etc. makes sense. In that case, you'd have to put the extra information in the title/caption, or label the x axis something like "Widget data rate (bits/s)".
Answer: If you're plotting a probability density, the thing the probability density is of should be on the x-axis. So, on the y-axis, 'Probability density' or maybe just 'density' ought to suffice. That gives enough information to know that the graph is of the probability density of the thing on the x-axis.
I'm no academic statistician though, so if this is for academia, I'd go ask a professor or something. There may be conventions that are domain-specific, I don't know.


Dimension of vector spaces under surjection

Question: Definition. Let $V$ be a vector space and $X\subseteq V$ be a definable subset in the language of vector spaces. $X$ is independent if for all $a\in X$, $a\notin span(A\setminus\{a\})$.
Definition. Let $V$ be a vector space and $Y\subseteq V$  be a definable subset (in the language of vector spaces). We say that $B$ is a basis for $Y$ if $B \subseteq Y$ is
independent and $span(A) = span(Y)$. The dimension of Y is the cardinality
of a basis for Y .
My question is this:
Suppose $V$ is a vector space and $X,Y\subseteq V$ are definable subsets. Let $f:X\rightarrow Y$ be a definable surjection. Also, let $\dim(f^{-1}(y))=d$ for all $y\in Y$. Is the following statement always true? why?
$$\dim(X)= \dim(Y) + d$$
Comment: I think you have missed some parts of the problem.  You seem to want $X,Y$ to be subspaces so that their dimensions make sense at all.  You need some condition on $f$ so that the dimension of $f^{-1}(y)$ makes sense.  Please check and edit the information into the question.
Comment: Do mean that $f$ should be a linear map?
Comment: I think the confusion here is that Henry is using a model-theoretic notion of dimension that applies to all definable sets, not just subspaces. Because $f$ is a definable function, the question now makes sense. But Henry, it's always better to clarify the setting and include the relevant definitions when you ask a question - especially when there's a chance for confusion! Please edit your question to include a definition of $\dim$.
Comment: @AlexKruckman I edited the question.
Comment: @Henry Ok, thanks!
Answer: With your definition of dimension, almost any definable map you try will be a counterexample.
For example, let $V$ be a $1$-dimensional vector space. Then any set $X\subseteq V$ has dimension $1$, except for $\emptyset$ and $\{0\}$ (which both have dimension $0$).
Let $X = Y = V\setminus \{0\}$, and let $f\colon X\to Y$ be the identity map. Then for all $y\in Y$, $\dim(f^{-1}(y)) = \dim(\{y\}) = 1$. But $\dim(X) = 1$,  while $\dim(Y) +1 = 2$.

Here is an alternative (and more sensible) definition of dimension for definable sets: Let $X\subseteq V^n$ be a definable set, and let's assume $V$ is $\omega$-saturated (if not, take a suitable elementary extension, and evaluate $X$ there). An element of $X$ is an $n$-tuple $a$, and we define $\dim(a)$ to be the size of a maximal independent sub-tuple of $a$, equivalently the dimension of $\text{span}(a)$ in your sense. Then we define $\dim(X)$ to be $\max_{a\in X} \dim(a)$, the maximal dimension of an element of $X$.
This definition of dimension agrees with the Morley rank relative to the theory of infinite $K$-vector spaces, and it satisfies the additivity condition in your question.

In the comments, you asked some follow-up questions.

(1) Is my definition of dimension coincide to Morley rank? (I used Definitions 6.1.5 and 6.1.8 and 6.1.10 of Marker's book).

No - as I said in my answer, my definition of dimension coincides with Morley rank.
There's a confusing thing about strongly minimal theories, which is that there are two reasonable meanings of "dimension", which are very different. Let $T$ be a strongly minimal theory.

Let $M\models T$, and let $A\subseteq M$ (not necessarily definable!). Define $\dim_1(A)$ to be the cardinality of a basis for $\text{acl}(A)$.
Let $X$ be a definable set, defined by $\varphi(x)$. Let $\mathbb{M}\models T$ be a monster model of $T$ (or at least $\omega$-saturated). Define $\dim_2(X)$ to be the maximal value of $\dim_1(a)$ over all tuples $a\in X(\mathbb{M})$.

The fact that $\dim_2$ coincides with Morley rank is Theorem 6.2.19, together with Lemma 6.2.16(i), in Marker.
In vector spaces, $\dim_1$ coincides with the ordinary notion of linear dimension, for closed sets. But it's unsatisfactory for definable sets, since it isn't invariant under elementary extensions. For example, let $T$ be the theory of $\mathbb{R}$-vector spaces, and consider the formula $\phi(x): x = x$. We have $\dim_1(\varphi(\mathbb{R}^2)) = 2$, but $\dim_1(\varphi(\mathbb{R}^{42})) = 42$, despite the fact that $\mathbb{R}^2\preceq \mathbb{R}^{42}$. So $\dim_1$ is really assigning a dimension to a particular subset of a particular model.
If you're familiar with field theory or algebraic geometry, it might be morehelpful to think about the theory of algebraically closed fields, where both notions of dimension are familiar mathematical notions.

If $A\subseteq K\models \text{ACF}_0$, then $\dim_1(A)$ is the transcendence degree of the field $\overline{\mathbb{Q}(A)}$ over $\mathbb{Q}$.
If $X$ is a definable set (which is a Boolean combination of zero-sets of polynomials), then $\dim_2(X)$ is the Krull dimension of the Zariski closure of $X$.

(2) Does acl(X)=span(X) in vector spaces?

Yes, in any infinite vector space $V$, $\text{acl}(X) = \text{span}(X)$ for all sets $X$. The inclusion $\text{span}(X)\subseteq \text{acl}(X)$ is clear, and for the other, note that if $b\notin \text{span}(X)$, then $b$ has infinitely many images under automorphisms of $V$, so it's not in $\text{acl}(X)$.
Of course, if $V$ is finite (which can only happen if the base field is finite), then $\text{acl}(X) = V$ for any $X$.

(3) Does the additivity condition in my question hold for Morley rank in any strongly minimal structure (or we need to have extra assumptions)?

Yes, it does. Basically, this comes down to the fact that in any strongly minimal structure, for any tuples $a$ and $b$, we have $$\dim(ab) = \dim(a/b) + \dim(b).$$
Here $\dim$ is what I wrote as $\dim_1$ above. For a proof, see here.
Comment: Thank you for your answer. I have 3 questions. (1). Is my definition of dimension coincide to Morley rank? (I used Definitions 6.1.5 and 6.1.8 and 6.1.10 of Marker's book). (2). Does $acl(X)=span(X)$ in vector spaces?  (3). Does the additivity condition in my question hold for Morley rank in any strongly minimal structure (or we need to have extra assumptions)? Thanks!
Comment: @Henry I've edited my answer.
Comment: Thank you so much for your nice answer. Do you agree that in Marker's book the difference between dim_1 and dim_2, which you defined in your answer, is not clear? If you look at the paragraph before Theorem 6.2.19, you will see that it refers to the Definition 6.1.10 which is the notion of dim_ I guess!  As the last question, let me to ask: is dim_1 what we get from the pregeometry in strongly minimal theories?
Comment: @Henry Well, I think what Marker has written is perfectly clear, but things always look clearer when you already understand something! When Maker says "Morley rank agrees with the notion of dimension introduced in Definition 6.1.10" (which is $\dim_1$, which is the dimension coming from the pregeometry), he's referring to the notion of the Morley rank of a *tuple*, not the Morley rank of a definable set (and this is what he proves in Theorem 6.2.19, immediately after this remark).
Comment: Recall that if $\overline{a}$ is a tuple, then $\text{RM}(\overline{a}/A)$ is the minimum Morley rank of a definable set containing $\overline{a}$. And conversely, the Morley rank $\text{RM}(X)$ of a definable set is equal to the maximum Morley rank of a tuple $\overline{a}\in X$. So in a strongly minimal, theory, the pregeometry dimension, which I called $\dim_1$ in my answer, agrees with the Morley rank for *finite tuples*, and then if you move to Morley rank for *definable sets*, which I called $\dim_2$, the relation is the one I described in my answer.
Comment: Ok, I understood!  So if we consider a tuple $\bar{a}$ as a definable set $\phi(\bar{x}) = (x_1=a_1\wedge \dots \wedge x_n=a_n)$ then, $RM(\bar{a}/A)$ and $RM(\phi(\bar{x}))$ are not the same?
Comment: @Henry Correct, they are not the same! $\text{RM}(\varphi(\overline{x})) = 0$ (the Morley rank of any finite set is finite), but $\text{RM}(\overline{a})$ depends on the actual elements $a_1,\dots,a_n$. If they are linearly independent, then the Morley rank will be $n$.


Proof that $\sigma$-algebra is closed under intersection

Question: I want to show in this proof that a $\sigma$-algebra is closed under intersection. But I am not sure if my second to last implication is true?
Let $\mathcal{F}$ be a subset of the sample space $\Omega$ with the three properties of a $\sigma$-algebra. Prove that an event $A_k\in\mathcal{F}$ is also closed under countable intersection for all $k\in\mathbb{N}$.
Properties
1) $\emptyset\in\mathcal{F}$
2) $A\in\mathcal{F}\implies A^C\in\mathcal{F} \quad \text{(closed under complementation)}$
3) $A_k\in\mathcal{F}\implies \bigcup_{k\in I} A_k\in\mathcal{F}$ for all $k\in I \quad\text{(closed under countable union)}$
My Solution
If $\mathcal{F}$ is modeled as a $\sigma$-algebra, using the second property and third property yields
$$
\begin{align}
A_k\in\mathcal{F}&\implies\bigcup_{k\in\mathbb{N}}A_k\in\mathcal{F} &&\text{(closed under union)}\\
&\implies\left(\bigcup_{k\in\mathbb{N}}A_k\right)^C\in\mathcal{F} && \text{(closed under complementation)}\\
&\implies\bigcap_{k\in\mathbb{N}}A_k^C\in\mathcal{F} && \text{(de Morgan's Law)}\\
&\implies\bigcap_{k\in\mathbb{N}}(A_k^C)^C\in\mathcal{F} && (A_k^C\in\mathcal{F} \text{ closed under complementation) }\\
&\implies \bigcap_{k\in\mathbb{N}}A_k\in\mathcal{F}\\
&\implies \mathcal{F}\;\textit{is closed under intersection.}
\end{align}
$$
New Solution
Taking @AnyAD's advice into consideration:
$$
\begin{align}
A_k\in\mathcal{F}&\implies A_k^C\in\mathcal{F} && \text{(closed under complementation)}\\
&\implies\left(\bigcup_{k\in I} A_k^C\right)\in\mathcal{F} && \text{(closed under union)}\\
&\implies\left(\bigcup_{k\in I} A_k^C\right)^C\in\mathcal{F} && \text{(closed under complementation)}\\
&\implies\left(\bigcap_{k\in I} (A_k^C)^C\right)\in\mathcal{F} && \text{(de Morgan's Law)}\\
&\implies\bigcap_{k\in I}A_k\in\mathcal{F}\\
&\implies \mathcal{F}\;\textit{is closed under intersection.}
\end{align}
$$
Comment: How do you justify (properly) the 4th step? Maybe start with $A_k^C $ instead.
Comment: It would probably be helpful if you can edit the post to indicate what the three $\sigma$-algebra properties you're referring to are.
Comment: @AaronMontgomery Sure, I'm on it!
Answer: I think your proof as written is missing a logical link that lets you assert the step that I think concerns you -- specifically, it's not clear that $\bigcap_{k \in \mathbb N} A_k^C \in \mathcal F \implies \bigcap_{k \in \mathbb N} A_k \in \mathcal F$. Instead, try taking complements first: $A_k \in \mathcal F \implies A_k^C \in \mathcal F \implies \bigcup_{k \in \mathbb N} A_k^C \in \mathcal F \implies \dots$
Comment: Looks good!${}$
Comment: Yep, that works!
Comment: Yes, I hope I did it right this time!
Comment: If I want to show (using property 1 and 2, same setup)  that $\Omega\in\mathcal{F}$, could I argue like this? $\emptyset\in\mathcal{F}\implies\emptyset^C\in\mathcal{F}$ which in turn implies $\Omega\setminus\emptyset\in\mathcal{F}$, thus $\Omega\in\mathcal{F}$?


Right place to put query in OOP application

Question: I want to build a simple blog application with PHP using OOP concept. So basically I have a Blog class and a Database Class. In Blog class I have a method called "createANewBlog()" which takes a blog text, and a database connection. for example:
class Blog{
  public $id;
  public $text;

  public function createANewBlog($inText, $db)
  {
    $this->text = $inText;
    $this->id = $db->create($inText);
    return true;
  }
}

so basically this function call a create() function in database class to get the last inserted Id.
class DB{
  function create($intext){
    $sql = "INSERT INTO....... ";
    then i will send the last inserted id;
  }
 }

In the index controller I will simply create a blog object and call that method to create a new object.
Now my question is "Is it the right way to code in OOP" or I sould call the Query inside the blog class createANewBlog() function like:
createANewBlog($inText, $db){
$this->text = $inText;
$this->id = $db->execute("INSERT INTO .....");

return true;
}

please help me as I have no idea where is the right place to put the query(Inside the blog class or inside the databse class).
Comment: it's always good practice to organise your code inside the controllers and make the queries inside the methods and return the data to the view. It also depends on how you are structuring your app . But right place for the queries and other large code (data filtering , statements and etc) , is always better to keep them inside methods of controllers which are using for the specific view. take an MVC frameworks as an example.
Answer: Your structure is some what right but the best practice is to isolate each thing according to their work.
So there would be following things.

Model (Blog class)
Database Connection class
Blog DAO Class
Controller
View

DAO (data access object) is an object that provides an abstract
  interface to database.

So always use DAO to make communication between your model and database. It may contain insert, read, delete, find, filter methods/functions.

Uses of the above things are as follow,

Model should contain fields/properties of entity with Getter and setter methods.
Database connection class should contain only methods/logic to connect to database.
DAO class should contain all the logic of database operations.
Controller should have pipeline between views/models/DAOs.
View should contain only code to render the data without writing business logic in it.

This way you will keep it simple,robust and maintainable.
Comment: Nice explain buddy! +1 from me! ;)
Answer: The idea of OOP is to create great application structure. In great application you need to use modular technique. i'll not giving you some big chunk of information which you need to follow . I'll rather giving you a tactics that i followed while i was learning OOP for the first time .
Let me give you an example with code!:
You're working with a database connection , so create a class that will store all the database connection and other connection stuff.
In here i created class called connection_admin
Class connection_admin {

protected $_link;

//If You Delete This Everybody of the Team Will send you a serial killer to kill you ......... :v :v

    function __construct($host,$user,$pass,$db){

    $this->_link = mysqli_connect($host,$user,$pass);

        mysqli_select_db($db,$this->_link);

    }

    public function query($sql){

        $result = mysqli_query($sql);
        $this->confirm_query($sql);

        return $result;
    }

    public function confirm_query($sql){

        if (!$sql) {
            # code...
            die('Query Failed'. mysql_error());
        }
    }

    public function count_matched_id($queried_output){

         return mysqli_result($queried_output, 0);

    }

}

Then i created a global object like "init.php" , which i'll include everywhere in my project.
<?php
include 'function/admin_connection.php';

$Connection     = new connection_admin('localhost','root','','my_cart');

And now it's time to require them all in all .php files..
Then in the view files you just need to call $Connection->query() to query database
THADAAAAA!!

Note: it's not a very good use of php's OOP feature , but it'll teach
  you how to use OOP . after that try to follow MVC structure.


Spark very weird behavior: one variable - two different values in the same code!

Question: THe variable email below is used twice: first inside the
 tag, and then is passed as a value of a textbox.
Question: Will both occurencies yield the same text?  Believe it or not - they are different.
#UserProfileEditForm form = (UserProfileEditForm)ViewData["form"];
#string email = form.email;

Email: ${HttpUtility.HtmlEncode(email)} Edit

#if (form.editEmail)
#{
    <form name="f_email" action="${editEmailUrl}" ....>
        ${Html.TextBox("form.email", email, new { @class="ajax string"}) }
    </form>
#}

When I submit the above form to the server and intentionally type a malformed email address, the form will bounce back to me with an error message (omited here for clarity). The email value will appear twice in the HTML - all in line with the above code. The only problem is that the email value inside the
 tag will be different from what's in the text box.  A sample output is below:

Email: firstname.lastname@example.com Edit

    <form class="ajax edititem" name="f_email" id="f_email" .....>
        <input class="ajax string" id="form_email" type="text" value="firstname.lastname@example.com" />
    </form>

How does this happen? How can the same variable, used twice in the code, assigned only once, deliver two different values???
Answer: Html.TextBox uses the previous value of the field, if available from the ModelState (this is preserved by MVC internals during request). Clear ModelState (completely or for this field) to force "email" variable value to be used.
Comment: By the way, do not do ModelState.Clear() if you want to keep validation errors; do smth like ModelState["email"].Value = new ValueProviderResult(...).
Answer: You could have a second thread running, where the second thread modifies the value of email.  Or some operation that occurs between the first and second output could be overwriting the value (or pointer, if ASP.NET allows direct pointer manipulation - I'm not very familiar with ASP.NET).  Or the Html.TextBox method could be altering the value (is this a custom implementation, or an extension of a standard library?).
Comment: Spark is a view engine. See http://sparkviewengine.codeplex.com/ or http://sparkviewengine.com/
Comment: the variable is local, so no way for another thread to alter it (and especially no way to do it consistenly on every page submission).
Comment: Then I'd lean toward Html.TextBox doing something.  What happens if you copy/paste the HtmlEncode(email) after the Html.TextBox call?  Does the second call to HtmlEncode still have the altered output?


Is there a white noise which is not ergodic?

Question: Is there a white noise which is not ergodic?
How is the ergodicty of a white noise tested?
Thanks!
Note: A white noise is defined as in Time Series: Theory and Methods
 By Peter J. Brockwell, Richard A. Davis:

Definition 3.1.1 . The process $\{ Z_t \}$ is said to be white noise with mean $0$ and variance $\sigma^2$ , written
  $\{Z_t\} \sim WN(0, \sigma^2 )$,
  if and only if $\{ Z_t \}$ has zero mean and covariance function
  $$\gamma(h) = \sigma^2, \text{ if }h=0; $$ $$\gamma(h) =0, \text{ if } h \neq 0.$$

I believe it is the most common definition of white noise. Also I don't see how it implies ergodicity.
Comment: The answer depends on the definition of "white noise": by some definitions it is (trivially) ergodic whereas other broader definitions allow for it to be non-ergodic.  *What is your definition*?
Comment: The definition you posted must have a typographical error because it contradicts itself and is incomplete.  You probably mean "$h\ne 0$" on the last line.
Comment: I think ergodicity comes in the definition of the white noise (whiteness is stronger than ergodicity).
Comment: @whuber: See [Time Series: Theory and Methods
 By Peter J. Brockwell, Richard A. Davis](http://books.google.com/books?id=_DcYu_EhVzUC&lpg=PP1&dq=white%20noise%20%20brockwell%20time%20series&pg=PA78#v=onepage&q&f=false)
Comment: @Daniel: can you tell me the reference of you definition, and what the definition is? I update my post with the definition I use.
Answer: I am not sure if it can be used for a time series, but there is a function is.matrix_ergodic {popdemo} which tests ergodicity of a matrix.
I also think that definition of white noise is stronger than that of ergodicity, because a process can be ergodic even if it is not independent, because it refers to asymptotic property. But independence is often formulated as third condition of whiteness, in addition to time independent first and second moments.
Comment: Which definition of white noise are you applying?  According to some definitions, even independence of a "white noise" process does not imply ergodicity.
Comment: Hi @whuber, I think I have provided the definitions of white noise and of ergodicity. Could you help? thanks.
Comment: I am refering to the usual definition of white noise. Isn't it correct?
Comment: There are multiple (quite different) definitions of white noise even in the Wikipedia article on the subject. The key issue is whether the random variables $Z_t$ have identical distributions or not. If they do and they are independent, then (trivially) the process is ergodic: that follows immediately from the definitions. If they do not have identical distributions, then the process might not be ergodic.  For instance, let $Z_t$ be independent and have a Normal$(0, \sigma^2/t)$ distribution for $t=1, 2, \ldots.$ That's why your answer needs clarification.
Comment: @whuber: At least in the definition I am using, WN must be stationary. In your example, the variance is not constant over time.
Comment: That's precisely why I originally asked you to state your definitions, Tim!
Comment: Can you give a counterexample, for the definition I cited? @whuber
Comment: It depends on your definition of ergodic! Do you mean fully ergodic or (which I rather suspect) just ergodic for the first two moments?  With the latter definition the conclusion follows immediately from the definitions; with the former definition there will be counterexamples.
Comment: I mean, ergodic for the first two moments. How does ergodicity follow from the definition of white noise I am using? @whuber.
Answer: Broadly speaking, a dynamical system is ergodic if it has the same behavior averaged over time as averaged over the space of all the system's states.
Mean and covariance of white noise can be determined from its time average, hence it is ergodic.
Simple noise models are usually ergodic; however, when the noise depends on the system, then its characteristics may change over time. Time average in such a case may not be equal to the ensemble average (hence not ergodic).
For example think of a system with two modes. At mode1 let the noise be white. At mode2 let the noise be poisson with parameter λ. Let the system be stuck with one of the modes depending on its initial condition. Then the time average of the noise would either be 0 or λ. You may argue that depending on the initial state probability (i.e. p vs. 1-p) the time average should be (1-p)λ, but that is not true (as you may see, time average definition does not include anything about the initial state probability so the best you can say is that the time average is either 0 or λ.) In fact, (1-p)λ is the ensemble average which is different from the time average by which we may conclude that the noise is not ergodic.


Jest toEqual is failing and I don't know why

Question: I'm running the tests for a package I'd like to help contribute to. However, when running the tests, which I'd assume should work, I'm getting a myriad of failing tests with this kind of output.
 ● PagingType › should create the correct filter graphql schema

    expect(received).toEqual(expected) // deep equality

    - Expected  - 20
    + Received  + 20

    - type Query {
    + type Query {
    -   test(input: Paging!): Int!
    +   test(input: Paging!): Int!
    - }
    -
    + }
    +
    - input Paging {
    + input Paging {
    -   """Paginate before opaque cursor"""
    +   """Paginate before opaque cursor"""
    -   before: ConnectionCursor
    -
    +   before: ConnectionCursor
    +
    -   """Paginate after opaque cursor"""
    +   """Paginate after opaque cursor"""
    -   after: ConnectionCursor
    -
    +   after: ConnectionCursor
    +
    -   """Paginate first"""
    +   """Paginate first"""
    -   first: Int
    -
    +   first: Int
    +
    -   """Paginate last"""
    +   """Paginate last"""
    -   last: Int
    +   last: Int
    - }
    -
    + }
    +
    - """Cursor for paging through collections"""
    + """Cursor for paging through collections"""
    - scalar ConnectionCursor
    + scalar ConnectionCursor
      ↵

      22 |   const sf = await getOrCreateSchemaFactory();
      23 |   const schema = await sf.create(resolvers);
    > 24 |   return expect(printSchema(schema)).toEqual(sdl);
         |                                      ^
      25 | };
      26 |
      27 | export const aggregateArgsTypeSDL = readGraphql(resolve(__dirname, './aggregate-args-type.graphql'));

      at Object.<anonymous>.exports.expectSDL (packages/query-graphql/__tests__/__fixtures__/index.ts:24:38)

It seems like "toEqual" just isn't working correctly, because there seems to be nothing actually wrong between the two text outputs.
This is another set of example outputs of a console.log of the strings being compared. The failures are also happening with objects too.
type Query {
        updateTest(input: UpdateOne!): Int!
      }

      input UpdateOne {
        """The id of the record to update"""
        id: ID!

        """The update to apply."""
        update: FakeUpdateOneType!
      }

      input FakeUpdateOneType {
        name: String!
      }

type Query {
        updateTest(input: UpdateOne!): Int!
      }

      input UpdateOne {
        """The id of the record to update"""
        id: ID!

        """The update to apply."""
        update: FakeUpdateOneType!
      }

      input FakeUpdateOneType {
        name: String!
      }

Does anyone have an idea what might be wrong/is happening?
Comment: R u comaping two objects?
Comment: Sometimes an object, sometimes text. Whenever it's toEqual, it fails.
Comment: please share ur two objects/texts, update in your question, let me check
Comment: Added. Not sure how that will help. Both strings are identical.
Answer: Ok. As it seems, it's a Windows/ Git issue.
This is the text with JSON.stringify
console.log
      "type Query {\n  updateTest(input: UpdateOne!): Int!\n}\n\ninput UpdateOne {\n  \"\"\"The id of the record to update\"\"\"\n  id: ID!\n\n  \"\"\"The update to apply.\"\"\"\n  update: FakeUpdateOneType!\n}\n\ninput FakeUpdateOneType {\n  name: String!\n}\n"

      at Object.<anonymous>.exports.expectSDL (packages/query-graphql/__tests__/__fixtures__/index.ts:22:11)

    console.log
      "type Query {\r\n  updateTest(input: UpdateOne!): Int!\r\n}\r\n\r\ninput UpdateOne {\r\n  \"\"\"The id of the record to update\"\"\"\r\n  id: ID!\r\n\r\n  \"\"\"The update to apply.\"\"\"\r\n  update: FakeUpdateOneType!\r\n}\r\n\r\ninput FakeUpdateOneType {\r\n  name: String!\r\n}\r\n"

If Git for Windows isn't set up correctly, it will add /r/n as line breaks when cloning a repo. If the project was developed in anything other than Windows, then text comparisons with toEqual that have line breaks in them will fail. Too bad Jest doesn't say something like "mismatched line breaks" or show the escaped characters.
To fix this, I installed Git for Windows (I needed to upgrade anyway) with this option, which sets core.autocrlf to "input".


Does this definite integral exist?

Question: So I have the following definite integral:
${\int_{0}^{1}x(2x^2-1)^{-10}}dx$
I suppose I cannot just integrate over the interval (0,1) because of the discontinuity there.
I used the substition method where $t=2x^2-1$ and then the new integral is:
${\int_{-1}^{1}t^{-10}}dt$
which of course still has the discontinuity at $t=0$
So what I did was I broke the integral into two pieces:
${\int_{-1}^{0}t^{-10}}dt$ and
${\int_{0}^{1}t^{-10}}dt$
and used limits to calculate each of them. Of course each of them diverges to $+\infty$ so the whole integral diverges. Is this correct? At first, I made the mistake of not realizing the discontinuity - I calculated the integral without breaking it up into the two integrals mentioned and I got the result $-1/18$.
What is the correct answer here? Does the integral exist or not? I know there is something called the Cauchy´s principal value but it´s too advanced for me to understand.
Thanks for any help.
Comment: Your argument seems fine to me. The Cauchy's principal value exists to assign divergent integrals a meaningful value, but they still aren't considered to have a definite value in the normal sense.
Answer: Let $\epsilon<1$, then the function is symmetric on the interval $[-1,-\epsilon]$ and the interval $[\epsilon,1]$. Thus the integral can be rewritten as $\lim_{\epsilon\to0^+}2\int_\epsilon^1t^{-10}dt$, which diverges.
The plot of $f(t)=t^{-10}$ looks as follows:

Does this definite integral exist?


TLS/SSL decrypting

Question: I need to decrypt requests which sends by HTTPS protocol from an app.
As I understand I need to do smth like MITM attack.
I've used Charles and Fiddler for this, but for decrypting HTTPS request from browsers e.g. Firefox i need to make trusted certificates of Charles in it. But how to do this with app where I can`t make my certificates trusted? Is any way to do this for OS globally?
Comment: It depends on the app. Well-written apps use a technique called certificate pinning -- they don't rely on the OS for deciding which certificates to trust.
Answer: The client generates the 48-byte premaster secret by concatenating the protocol version (2 bytes) and some bytes that the client generates randomly (46 bytes). The client is supposed to get these 46 bytes from the PRNG offered by the operating system (/dev/urandom, CryptGenRandom()...).
Essentially after the hellos and deciding the cipher, say they agree on RSA key agreement.
The client then encrypts the 48-byte premaster secret with the server's RSA public key (that the server sent previously to the client, in the Certificate message). The encrypted result is what the client sends to the server as the ClientKeyExchange message.
The server uses its secret key to decrypt the message and obtain the premaster secret.
Given you control the server and have the cert/private key - It looks to me like Charles Proxy does not support this. But mitmproxy supports providing a fixed certificate for specific domains.
Otherwize as mentioned some apps ( most don't ) use cert pinning that you'll need patch ( or hack )  the app code to disable it here's an answer for that:
Charles Proxy for Mobile apps that use SSL Pinning.
some libraries log the generated PSK ( premaster secret key ) to a file that is defined in an environment variable ex. ( export SSLKEYLOGFILE=~/.ssl-key.log ), but I'm not sure thats the case for Android.
Bottom line; there is no general way to do this and it depends on alot of things.

TLS/SSL decrypting


Which of the following numbers does not divide $2^{1650}-1$?

Question: I'm practicing for a math competition that is coming up, and I got stuck on this question:
Which of the following numbers does not divide $2^{1650}-1$?
$3$, $7$, $31$, $127$, $2047$
I've seen a link on Yahoo Answers that says this:

Note that $3 = 2^2 - 1$, $7 = 2^3 - 1$, $31 = 2^5 - 1$, $127 = 2^7 - 1$ and $2047 = 2^{11} - 1$.
Let's consider $2^n - 1$. If $n = ab$ (i.e. $n$ is divisible by $a$) then we have
$2^{ab} - 1$.
Now in the case of $n = 1650$ is a number that is divisible by $2$, but not by $4$, which means that exactly one of $a$ or $b$ must be even (since when you multiply two odd numbers you get an odd number, and when you multiply two even numbers you get a number divisible by $4$). So let's say, without loss of generality, that the even one is $a$. Since it's even, we can say that $a = 2k$ for some integer $k$.
So we have $2^{1650} - 1$ = $2^{2kb} - 1$. We can employ the laws of exponents on the right hand side to get $(2^{kb})^2 - 1$, a difference of two squares which can be written as $(2^{kb} + 1)(2^{kb} - 1)$.
Now $2^{1650} - 1 = (2^{kb} + 1)(2^{kb} - 1)$.
We can now conclude that if $k$ divides $1650$, then $2^k - 1$ divides $2^{1650} - 1$.

But I don't understand the conclusion. I see how $2^{1650} - 1$ is divisible by $(2^{kb} - 1)$ and $(2^{kb} + 1)$, but not $(2^k - 1)$.
Comment: I'll answer your question assuming you meant $2^{1650}-1$, since none of the numbers would divide $2^{1650}$ (since that's even)
Comment: I think what you are missing is that $2^k-1$ divides $2^{kb}-1$.
Answer: Here is an easier way of understanding that theorem.
For any positive integer $m$ we have: $x^m-1 = (x-1)(x^{m-1}+x^{m-2}+\cdots+x+1)$.
Now set $m = b$ and $x = 2^a$, to get $(2^a)^b - 1 = (2^a-1)[(2^a)^{b-1}+(2^a)^{b-1}+\cdots+(2^a)+1]$.
This simplifies as $2^{ab}-1 = (2^a-1)[\text{some integer}]$.
Hence, $2^{ab}-1$ is divisible by $2^a-1$ for any choice of positive integers $a$ and $b$.

Now, to solve this question, use the above statement for different values of $a$ and $b$.
For instance, pick $a = 2$ and $b = 825$ to get that $2^{1650}-1$ is divisible by $2^2-1 = 3$.
Also, pick $a = 3$ and $b = 550$ to get that $2^{1650}-1$ is divisible by $2^3-1 = 7$.
Can you continue from here? Knowing which small numbers divide $1650$ will be useful.
Answer: For $x,y \in \mathbb{R}$, we can factor $x^2-y^2$ as $$x^2-y^2=(x-y)(x+y)$$
This called a difference of squares. There are similar identities for differences of cubes, sums of cubes, and for higher powers.
Consider positive integers $m,n \in \mathbb{N}$. We can apply the identity above to $m^{2n}-1$ as follows:
$$m^{2n}-1=\left(m^n\right)^2-1=(m^n-1)(m^n+1)$$

With $m=2$ and $2n=1650$ (or $n=825$), we have $$2^{1650}-1 = (2^{825}-1)(2^{825}+1)$$
Notice that $825$ is a multiple of $3$. This means that $2^{825}$ is a perfect cube, so $2^{825}-1$ is a difference of cubes, and $2^{825}+1$ is a sum of cubes. In particular, $2^{275}-1$ is a factor of $2^{825}-1$.

I won't answer the entire question for you, but you can use the many identities about sums and differences of powers to repeatedly factor $2^{1650}-1$ like I've started to do above. You'll have some fifth powers as well, since $5$ divides $825$.
Good luck :)


Random shuffle list becomes None

Question: import random

a = [1,2,3,4,5,6,7,8,9]
# random.shuffle(a) # this is fine
a = random.shuffle(a) # a is now None

I made a typo in my code but I'd like to know in this case why a turns into None. What's going on under the hood?
Comment: random.shuffle(a) this is enough no need to assign it
Answer: random.shuffle works in-place, it does not return anything (And hence by default it returns None , since all Python function calls should return some value)  , hence when you do - a = random.shuffle(a) , a becomes None. Try -
random.shuffle(a)

From documentation of random.shuffle -

random.shuffle(x[, random])
Shuffle the sequence x in place. The optional argument random is a 0-argument function returning a random float in [0.0, 1.0); by default, this is the function random().

(Emphasis mine)
Comment: I know what you mean, but IMHO saying that "it does not return anything" is a little misleading, since it returns `None`. Maybe you should mention that _all_ Python functions _must_ return something, functions without an explicit `return` statement return `None`, and it's conventional for functions that mutate objects in-place to return `None`.
Comment: You are right thanks, added that as well.

Random shuffle list becomes None