Distinct derivations of polynomial over finite field

Question: I am a student studying algebra and cryptography.
I wonder below question is possible.
Can I make some polynomials $f(x)$ over finite field that all derivations $f^{(k)}(x)$ are distinct when x is fixed but picked randomly?
i.e. $\forall x \in F, \forall k \in \{ 0,...,n \}, \ where \ n \ is \ degree \ and \ F \ is \ finite \ field, \\ \exists f \ s.t. \ \forall f^{(k)}(x) \ are \ distinct \ when \ random \ x \ is \ fixed \ ?$
I think it will be impossible, but also wonder that is possible when the finite field or polynomial has some specific conditions...
If there exists some related works, please tell me..!!
Comment: Note that if $F$ is a field of characteristic $p$, $f^{(p)}= 0$ for all polynomials.  So you'll certainly want $p > n$.
Answer: The choice of $x$ doesn't matter, because if $g(X) = f(X-x)$, $g$ is a polynomial of the same degree as $f$ and $g^{(k)}(x) = f^{(k)}(0)$.
So let's choose $x = 0$ for convenience.  Take any prime $p > n$. Then you can choose the coefficients $a_0, \ldots, a_n$ of $f(X) = a_0 + \ldots + a_n X^n$ so that $f^{(k)}(0) = k!\; a_k$ are congruent mod $p$ to any chosen $n+1$ values in $\{0,1,\ldots,p-1\}$.
Comment: Thanks for answer! Then I can choose a0, a1, ..., k! * ak, ..., n! * an are distinct, then g(X) is the what I want. Is it right?


How to change MIUI force dark mode on expo?

Question: MIUI devices are set force dark mode settings. I want to change this but expo android settings are not changing. How to change below settings on expo?
<item name="android:forceDarkAllowed">false</item>
Comment: Is there any update? I found this https://github.com/expo/react-native-appearance/issues/60 but no pull request... the setting should be "userInterfaceStyle": "light" but it does not work for me.
Comment: Any updates on this issue?
Comment: Same issue, looking for an answer :)
Answer: As documented in Expo documentation clearly now, you set this property in app.json
{
  "expo": {
    "userInterfaceStyle": "automatic"
  }
}

And you MUST also install expo-system-ui dependency as well, via npm install expo-system-ui


Refresh html page sections *only* upon database table change (row addition)

Question: I have a website where users make bets.
Every time a user makes a bet, a new row is inserted into a mysql table.
I would like to find a way to refresh html page sections (not whole page) only when users make bets (upon row insertions).
For example if user A adds a bet, every other user that has the page open in their browsers (user B, user C, ... user N) will get their page sections refreshed.
Having an ajax call to run every second adds excesive overhead to the server and it eventually hungs it (we have tried it).
Is there a technique in Ajax I am missing? We are using PHP, MySQL, jQuery.
What about frameworks such as angularJS, nodeJS, are there any better at accomplisging what I am trying to do?
Thank you in advance for your constructive positive inputs.
Comment: You're going to want to look up [WebSockets](https://developer.mozilla.org/en-US/docs/Web/API/WebSockets_API)
Answer: Yes, you can use nodejs and socket.io to meet your goal...
Create a socket connection and trigger an event to the client when a new bet inserts into your database, here is an example I have created for you https://github.com/atikassam/mysql-express-socket-example
Comment: For example if user A adds a bet, every other user that has the page open in their browsers (user B, user C, ... user N) will get their page sections refreshed. Will it work like this?
Comment: Yes, you have to create a socket connection for each of your users and then after when a new bet adds, emit an event to all the sockets to notify that your bets are updated and now on client-side, update your data table when the same event is triggered ...
Answer: <code><input type="button" value="Refresh Page" onClick="window.location.reload()">
</code>
You can try this.
Comment: The OP wants sections of the page refreshed, not the whole page.


remover colchetes dos valores armazenados em um dicionário

Question: Ao tentar utilizar uma planilha excel como fonte de dados para meu DOCX-TEMPLATE, o dicionário que estou gerando está armazenando os valores com colchetes, e estes e colchetes estão aparecendo no texto final que é gerado em DOCX pelo Docx-Template.
Para simplificar, utilizei uma tabela excel que contém os seguintes dados:
name    birth      gender
 Felipe   07/04/1988   male

O meu código está da seguinte forma:
import pandas as pd
from docxtpl import DocxTemplate

file_path = 'teste.xlsx'
df = pd.read_excel(file_path, encoding='utf-8')
data = df.to_dict(orient= 'list')

doc = DocxTemplate("modelo.docx")
context = data
doc.render(context)
doc.save("generated_doc.docx")

Para simplificar, meu "modelo.docx" contém o seguinte texto:
My name is {{ name }}, i am {{ gender }} and i  was born in {{ birth }}.
O Resultado gerado no "generated_doc.docx" é:
My name is ['felipe], i am ['male'] and i  was born in [Timestamp('1988-04-07 00:00:00')].
Se eu der um print(data)  para verificar o meu dicionário, o resultado é {'name': ['felipe'], 'birth': [Timestamp('1988-04-07 00:00:00')], 'gender': ['male']} .
Se eu executar o comando data['name'] = 'felipe' , meu dicionário ficará : {'name': 'felipe', 'birth': [Timestamp('1988-04-07 00:00:00')], 'gender': ['male']}  e funcionará. Portanto, preciso descobrir uma maneira de alterar todos os valores armazenados, de modo a remover os colchetes deles. Ou senão, existiria alguma maneira de já armazena-los sem os colchetes? Eu li a documentação do read_excel() e do to_dict(), porém não consegui resolver o problema.
Answer: O fato de que seu dicionário está assim: {'name': ['felipe'], 'birth': [Timestamp('1988-04-07 00:00:00')], 'gender': ['male']} indica que cada valor no dicionário é uma lista, com um único elemento.
Então o "remover colchetes" na verdade é criar um outro dicionário (ou atualizar o mesmo), de forma que todas as listas de um único elemento deixem de ser listas e passem a ser elementos.
Uma das formas de se criar um novo dicionário é usar uma "dict comprehension" - uma expressão com um for na mesma linha - o dict-comprehension economiza umas 2 ou 3 lihas de programa - então para ficar mais fácil entender, vou fazer "por extenso" primeiro - depois na forma de dict comprehension:
novo = {}
for chave, valor in data.items():
    if isinstance(valor, list):
        novo[chave] = valor[0]  # (pega o primeiro elemento da lista)
    else:
        novo[chave] = valor

data = novo

Com  o uso de "dict comprehension" esse mesmo trecho pode ser escrito como:

data = {chave: valor[0] if isinstance(valor, list) else valor for chave, valor in data.items()}

Comment: Obrigado jsbueno. Isso ocorreu pelo fato de eu ter usado a função `to_dict(orient= 'list')` no meu DataFrame, correto? Ela foi a única que me pareceu formatar o conteúdo da melhor forma para o Docx ler. De qualquer forma, solucionou meu problema !


Is there a way to generate thumbnails within Drupal?

Question: I see that Drupal 7 natively includes the GD toolkit. Looking at the documentation, there are Several Functions available to me that would seem to make it possible to, from an existing image, generate temporary thumbnails. The issue, however, is that any of the resizing methods seem to be destructive, and there is no simple way to copy images. PHP, of course, offers facilities that are low-level enough to handle this...and I'll use those if I have to...but is there a simple, Drupal way to programmatically create a thumbnail to a specified size?
Answer: First, create an image style from the Drupal UI, or by implementing hook_image_default_styles in a custom module. An image style contains the resizing and cropping rules for your thumbnail. After that, you can use theme_image_style to create the html output for an image using the thumbnail style. Do not call theme_ functions directly though; call it like this: theme('image_style', ... ). The thumbnail will automatically be created in a non-destructive way when it is first requested.


String Buzz and Dead Notes on Squier Strat

Question: I am new to guitar and bought a new Squier Strat as my first guitar.
I changed the strings myself to 008's a couple months in, and I think that may have caused some of the problems that followed shortly after.
I noticed I had multiple frets on the high E string which all played the same pitch, and string buzz all over the fretboard. Bends are typically inaudible (they sound like dead notes).
Additionally, I noticed my strings were not aligned well with the neck (the high E string often is too close to the edge of the neck to comfortably play). When I loosened the bolts on the back of the neck to move the neck back into place to realign the strings, they would shift back out of alignment within a couple of days.
I researched how to fix this problem, and I adjusted the action and also the truss rod, to no success.
While I understand that uneven frets may be responsible for my problem, I suspect it may also have something to do with the string replacement I did a while ago.
Can anybody point out what my problem with my guitar might be? Any help is greatly appreciated!
Comment: If I may ask, Bob: what made you go to 8s? Did you have a specific issue you were attempting to address? Or we you attempting to follow the setups of your heroes? For new players, I suggest _mediums_ (10s for electric) because going heavier gives finger pain through string tension and going lighter makes inadvertent bending out of tune much to easy. If you can express a reason to go lighter —  you don't need to defend yourself to _me_ — do so, but it helps to know your needs and preferences first.
Answer: It may be string replacement.  If it didn't buzz before then it is not likely uneven frets.  Do you happen to know what gauge was on it when you bought it?  When you change gauge you change the tension that neck feels and because of this the truss rod in the neck should be adjusted to balance that change in tension.
Since you are a complete beginner I'd take the guitar to the store where you got it and see if they can tweak it.  A complete set up can cost 50$ to 80$ in the US, not sure about elsewhere.  Or, you could just ask what gauge was on it and replace the strings and hopefully it will "readjust" but I'm not sure that will work, the process may not be completely reversible.
Answer: "Can anybody point out what my problem with my guitar might be?"
Yes, it might be that the lighter gauge strings are sitting too deep in the nut slots. If the guitar was set up for heavier gauge strings, the slots will be wider than optimal for the new, lighter set, thus the strings will sit deeper and be too close to the frets. This can cause the buzzing, incorrect pitch and dead notes you are encountering. Reverting to heavier gauge strings might get you back on track, but you'll likely have to readjust saddles and truss rod, as well.
In addition to the nut slot depth, the lower tension of lighter gauge strings will also reduce the relief, the slight concave bend, of the neck. This can also cause buzzing, incorrect pitch and dead notes. Since you tried adjusting relief with the truss rod to no better effect, I suspect the nut is a bigger impediment to a proper set up than the relief. Best solution at this point is to take it to a guitar tech, maybe the shop you bought from, and have it set up for the string gauges you prefer.
As for the neck shifting and settling into bad alignment, it's hard to make any judgements without seeing it. If it truly is misaligned, then that is a structural problem and may warrant replacement under warranty. However a lot of new guitar players have problems with pushing the e string off the fret board, so it could just be part of the learning curve for you.
Bottom line, I'd take it to a tech and get it sorted out by an expert. However if you're still inclined to work it out yourself, Fender provides guidance for set ups here:
How do I set up my Stratocaster guitar properly?
Comment: is right here. We're at a golden age for beginner guitars, with CNC routers making good bodies and necks so much easier to make. I think 8s not having enough tension for a guitar set up for 10s is a very likely cause for your problems, much more than a dead-dog Squier getting past QC. That _could_ be the case, though.


App works on iPhone but crash on iPad simulator stuck with launch image on ipad

Question: I am very new to this and hope I am at the right tread asking the right question.
My app has been in the AppStore for a couple of weeks now and always only worked on iPhone. it was rejected because the App does not run on an iPad. The exact reason it was rejected was:

Reasons for Rejection: 2.10: iPhone apps must also run on iPad without
  modification, at iPhone resolution, and at 2X iPhone 3GS resolution

When run on iPad 5 simulator, the following error occurs:
Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '* -[__NSArrayM insertObject:atIndex:]: object cannot be nil'
* First throw call stack:
(0x1ba5022 0xf60cd6 0x1b9233e 0x1b931f0 0x18bc04 0x19724f 0x3c3c 0x18a99b 0x418e 0xfd9d4 0xfdbe0 0x4155 0x15159 0x1433f 0x3b18 0x2b0d 0xc1386 0xc2274 0xd1183 0xd1c38 0xc5634 0x14d0ef5 0x1b79195 0x1addff2 0x1adc8da 0x1adbd84 0x1adbc9b 0xc1c65 0xc3626 0x2a60 0x29c5)
terminate called throwing an exception
What do I need to do in Xcode 4.5.1 to make my app run on an iPad?
Comment: please post the rest of the stack trace.
Comment: It looks like you are trying to insert a null object into a NSMutableArray. Have you tried debugging into your code? If you are not sure where to start, you could trying setting breakpoints at all you inserts and adds to NSMutableArrays and then stepping through each of them.
Comment: thank you, Sirs, I have added stack trace, your help is greatly appreciated.
I am hopeless on why it runs OK on iphone but not iPad simulator?
Answer: Do not insert a nil into an array. If you want to express that there is an "empty" object, use the singleton NSNull: [myArray insertObject: [NSNull null] atIndex: myIndex];.
* EDIT *
In case you did not use such code by intention, you should seek for automatic platform-dependent code. Hot candidates are missing or misconnected outlets or actions, platform-specific bundles, or missing or wrong (i.e. with incorrect IDs) elements in NIB/storyboard. However, without seeing your code, everything is guessing. Try to detect the fault by identifying the last place in the code trace, that belongs to your code (not library/framework code).
Comment: Hi, Matthias, could you please guide me thru the reasons that it is OK on iphone but not on iPad simulator? I did specify that it is for iphone in plist and in device family. A lot of thanks!
Comment: thanks again Matthias, actually there is only one line in my main(), and seems like the error came from it,

int main(int argc, char *argv[])
{
@autoreleasepool{
return UIApplicationMain(argc, argv, nil, NSSstringFromClass([AppDelegate class]));
}
}

I have tried whole day and still don't know what to do.
Comment: @user1703590: Did you check your NIBs/storyboard? Maybe your configuration assumes a storyboard for iPad, but none exists and you get a nil.
Comment: Matthias, the whole thing was created by interface builder 4.4, storyboard was configured for iphone, I checked the plist only main storyboard file base name says mainstoryboard, there is NO main storyboard file base name(iPad) exists.
Answer: For Cordova developers, you will get this error if you supply anything in the "Main Interface" dropdown in the General Project Settings. Always leave this blank if you want to target all platforms with a Cordova app.
You can also click all four orientations if you like. Also make sure "Universal" is selected in the devices dropdown.
Comment: The debugger will show an exception here: int main(int argc, char *argv[]) { @autoreleasepool{ return UIApplicationMain(argc, argv, nil, NSSstringFromClass([AppDelegate class])); } }


Simple Custom Block

Question: So I am trying to create a block to list the cities of the scrapyards in the system and i've followed some tutorial and i'm not even getting the block to show up in the list.
I have dir created at: /sites/all/modules/list_city and inside that I have the necessary .info and .module files.
The info file contains this:
name = List City Module
description = List the scrapyard cities
core = 7.x

And the module file contains this:
<?php
/**
 * Declare what blocks are provided by this module.
 * Implements hook_block_info().
 */
function list_city_block_info(){
  $blocks = array();
    $blocks['list_city'] = array(
      'info' => t('My Custom Block'),
  );
  return $blocks;
}

/**
 * Define what our block is going to look like.
 * Implements hook_block_view().
 */
function list_city_block_view($block_key){
  $block = array();
    if($block_key == 'list_city'){
      $block['subject'] = t('Marty McFly Countdown');
      $block['content'] = t('Marty will arrive in ').(strtotime("2015-10-21")-time()).t(' seconds.');
    }
  return $block;
}
?>

I'm not sure what I am doing wrong. The tutorial says it should show up in the lost of blocks but i'm not seeing it.
Also how could I go on to just list field_city of the scrapyard node.
Linking me to some page won't help much because at the minute i've looked at 10+ websites with tutorials on how to create blocks and i'm having no luck at all
EDIT: I've looked at a simpler tutorial and i'm now trying to use this updated code
Comment: Maybe a silly question but did you enable the module?
Comment: Try to clear cache.
Comment: Btw for examples check:https://www.drupal.org/project/examples
Comment: You have info and configure, but where is [hook_block_view](https://api.drupal.org/api/drupal/modules!block!block.api.php/function/hook_block_view/7)?!
Comment: Or as an alternative, have you considered making a simple Views block?
Answer: The following worked for me:
listcity.info
name = List City Module
description = List the scrapyard cities
core = 7.x

listcity.module
/**
* Implements hook_block_info().
*/
function listcity_block_info() {
  $blocks['listcity'] = array(
    'info' => t('List City'),
  );
return $blocks;
}

Make sure that you enable the module. (I've forgotten to do this before)
In your code sample there is a closing php tag ?> This shouldn't be in the module file.
Comment: If I could comment on your question I would.  Really, I am just trying to help.

Simple Custom Block


Print translated links in custom page--front.tpl.php

Question: I have a custom template for my front page, where I have to manually set URLs. Some of them are Views paths (such as news), some - aliased node URLs (projects/project-1). How to get their path translation URL in raw PHP code?
If I say something like:
<a href="<?php print url('news', array('language'=> $langcode, 'alias' => TRUE)) ?>" ...>
the rendered link is invalid langauge-crossed, such as mysite.com/es/news.
I tried also with the l() function but I'm getting untranslated link pointing to the root mysite.com/news.
Answer: This might be an obvious answer to experts, but hopefully this will help some newbie someday. I painstakingly investigated the url stuff in Drupal and my findings surprised me - especially when I referred them to the docs.
In the tpl I placed the following nasty debug lines:
<?php dpm(drupal_get_normal_path('alias-en')) ?>
<?php dpm(drupal_get_normal_path('alias-en', 'es')) ?>
<?php dpm(drupal_get_normal_path('alias-en', 'en')) ?>
<?php dpm(drupal_get_normal_path('en/alias-en')) ?>
<?php dpm(drupal_get_normal_path('/en/alias-en')) ?>
<?php dpm(drupal_get_normal_path('es/alias-es')) ?>
<?php dpm(drupal_get_normal_path('/es/alias-es')) ?>

And the results were:
alias-en
alias-en
node/298
en/alias-en
/en/alias-en
es/alias-es
/es/alias-es

Only the third result (node/298) was returned as desired, good for passing to i18n_get_path_translations. Even though the drupal_get_normal_path() function docs say the language parameter is optional, and subsequently called drupal_lookup_path() is said to put current language if NULL is passed, it does not seem to work this way.
drupal_get_normal_path() seems to require that you pass two parameters: alias and the language the alias is set for. Only then you'll get the result that will work reliably with i18n_get_path_translations.
I'm close to thinking it is a bug in Drupal or docs, and if no one sheds light on me, I'm going to file an issue.
Answer: You should use l function with language options to protect links against language prefix, like this one mysite/en/node/etc/1 for example:
<?php print l(t('title'), $path, array('language' => 'en')); ?>

Comment: Unfortunately, this produces untranslated href, only the link text is translated.
Comment: I just found this http://drupal.org/project/multilink and will give it a try.
Comment: good luck and good night ) its too late


Restore specific indexes in Elasticsearch

Question: i have 2 Elasticsearch (1 for PROD and 1 for DEV Environment)
and i already set a NFS partition (repository) for backup ALL indexes from PROD through bash script.
and we have the same indexes on the DEV Elasticsearch but with different data within. and today developer said that he wants a full copy of 2 indexes from PROD to DEV. i've already have full index backup!
I Know how to restore all indexes, but how can i choose the only 2 indexes? not the full restore of indexes?
for example i have snapshot which contains this guys
<code>{
   "snapshot":"elasticsearch_all_indicies_25_06_2018",
   "uuid":"aGzmhyOkmlkfmflnslndfs",
   "version_id":5060699,
   "version":"5.6.6",
   "indices":[
      "banners",
      "products",
      "catalogs",
      "darbiz",
      ".kibana",
      "invoices",
      "bundles",
      "groups",
      "searchitems",
      "params",
      "orders"
   ],
   "state":"SUCCESS",
   "start_time":"2018-06-24T23:30:01.978Z",
   "start_time_in_millis":1529883001978,
   "end_time":"2018-06-24T23:30:06.765Z",
   "end_time_in_millis":1529883006765,
   "duration_in_millis":4787,
   "failures":[

   ],
   "shards":{
      "total":75,
      "failed":0,
      "successful":75
   }
}
</code>
and for example i need to restore to DEV only orders and params indexes, not the whole set, how can i do that? thank you
Comment: Stack Overflow is a site for programming and development questions. This question appears to be off-topic because it is not about programming or development. See [What topics can I ask about here](http://stackoverflow.com/help/on-topic) in the Help Center. Perhaps [Super User](http://superuser.com/) or [Unix & Linux Stack Exchange](http://unix.stackexchange.com/) would be a better place to ask.
Answer: You can specify the indices to restore in the body of the JSON content sent to the REST API.  For example:
<code>POST /_snapshot/my_backup/snapshot_1/_restore
{
  "indices": "order,params",
  "ignore_unavailable": true,
  "include_global_state": true
}
</code>
Reference
https://www.elastic.co/guide/en/elasticsearch/reference/current/modules-snapshots.html#_restore


PHP XML parsing + daily authentication request

Question: I have a news provider who sends me non-RSS XML feeds through HTTP requests that then need to be parsed to be used on my site. However, my first request to the external server always has to be an authentication request which expires after 24 hrs. The authentication ID gets sent back to me as an XML tag attribute in the source code of an otherwise empty document. I then have to include this ID with every news request I send back to the news server.
Is there any way to automate this entire process through a series of Drupal 6 modules, or is it just best to write the code directly in the template files and schedule a daily task to request the authentication ID?
Answer: You could write a module where you implement hook_cron() to get the authentication ID and then store in the drupal DB (e.g. as variable via variable_set()). After that you can use it inside your templates without any worry. But you have to trigger your cron.php once a day via a sytem cron-job or the poormanscron module. For PHP xml-parsing take a look at SimpleXML.
EDIT: Module creation:
For this job it would be a simple module. Take a look at the module-dev-guide. First you create a YOURMODULE.info file. After that you put your code inside a YOURMODULE.module file. Than implement that hook_cron() like that:
function YOURMODULE_cron() {
     update_news_service_id();
}

function update_news_service_id() {
    // add your code here
}

One more comment: If you try to solve it this way you must consider calling update_news_service_id() from the template (or ..._preprocess()) if you run into an expired service id-error.
Comment: OK thanks... is it difficult writing my own hook_cron module? I really don't have any experience writing modules as I'm much more of a themer than a developer. Thank you for your help!


Ratio of Boys and Girls

Question: In a country where everyone wants a boy, each family continues having babies till they have a boy. After some time, what is the proportion of boys to girls in the country? (Assuming probability of having a boy or a girl is the same)
Comment: There is an _extremely_ thorough discussion of this question on MO: http://mathoverflow.net/questions/17960/google-question-in-a-country-in-which-people-only-want-boys
Comment: Hint: For every child born, what is the probability that it is a boy? So if $n$ babies are born in total, how many do you expect them to be boys? (Does it matter *which* family is having a baby?)
Comment: Earlier at https://math.stackexchange.com/questions/20426/famous-puzzle-girl-boy-proportion-problem-sum-of-infinite-series
Answer: It stays 50%. As long as the chance for each child is 50%, it won't change. You will have 1/2 of the families with just one child, a boy, 1/4 with one girl and one boy, 1/8 with two girls and one boy, etc. the average will be one girl and one boy per family.
Comment: As Douglas Zare points out in his answer to the MO question above, the question is ambiguous; there is no definite proportion of girls to boys, only 1) an expected number of girls, 2) an expected number of boys, 3) an expected proportion of girls, and if you interpret the question as asking for 3) then you can't divide 1) by 1) + 2) to compute it.
Answer: Both $B/G$ and $G/B$ are random variables.  If the "some time" in the question is long enough so that each family has had its one boy, then $B$ is the number $n$ of families, while $G$ is a random variable whose expectation is also $n$.  So if one interprets the question as being about the ratio of the expectations of $B$ and $G$, then the answer is $1$.  If, on the other hand, one interprets the question as being about the expectation of the ratio (which is not the same as the ratio of expectations!) then things get more interesting.  The expectation of $B/G$ is infinite, simply because $\infty$ is one of the possible values of $B/G$, since there is a non-zero probability that every family has a boy on the first try and so $G=0$.  As for $G/B$ and related non-obvious matters, see the answers at the MathOverflow question cited in Qiaochu Yuan's comment.  An amusing calculation is that, when there is just a single family (so $n=1$), the expectation of $B/(B+G)$, which could be regarded as the proportion of boys among the children of the unique family, is $\ln(2)$.  Specifically, $B/(B+G)$ has the possible values $1/k$ for all positive integers $k$, and the probability of the value $1/k$ is $2^{-k}$; the expectation is thus given by an infinite series, whose sum turns out to be $\ln(2)$.
Comment: Andreas:  I do not think one can reasonably interpret this question as asking for a ratio of expectations; it asks about the proportion of boys to girls, not of expected boys to expected girls.  So it's asking for B/G, or perhaps one of the related ratios G/B or G/G+B, etc.  Each of these is a random variable, and ordinarily one of the most interesting properties of a random variable is its expectation.   So I don't think the value of E(B)/E(G) is responsive to the question, but if someone else does, then, unlike Monty, I won't object to someone computing something other than I would have.
Comment: @WillO: It's debatable. The wording in the question here is "After some time, what is the proportion of boys to girls in the country"? If $N$ is the number of families in the country, and $B_i$ and $G_i$ are the number of boys and girls in the $i$th family (obviously $B_i=1$, for instance) and $\mathcal{B}=\sum_{i=1}^{N} B_i$ and $\mathcal{G}=\sum_{i=1}^N G_i$, then I'd say the question is asking for "the proportion of" $\mathcal{B}$ to $\mathcal{G}$. You could interpret this as the random variable $\mathcal{B}/\mathcal{G}$ I guess, but note that $E[\mathcal{B}/\mathcal{G}] \neq E[B_i/G_i]$.
Comment: Shreevatsa:  Yes, it seems clear to me that the problem is asking for the properties of the random variable ${\cal B}/{\cal G}$, which of course is not the same as $B_i/G_i$, unless $n=1$.  (Slight correction to your comment, though:  The expectations *are* equal, both being infinite.)  Again, I accept that what seems clear to me might not seem clear to others, and one can calculate anything at all as long as one indicates what one's calculating.  Monty's problem, of course, is that he keeps saying ridiculous things like $G/B=1$ (without taking expectations), which anyone can see is wrong.
Answer: Obviously the ratio of boys to girls could be any rational number, or infinite.   If you either fix the number of families or, more generally, specify a probability distribution over the number of families, then B/G is a random variable with infinite expected value (because there's always some non-zero chance that G=0).
Comment: WillO: The ratio of B/G = 1 = G/B. Both with the statistical errors (which in case that only boys are born extends to infinity).
Comment: monty:  I'm sorry that I have no idea what it means for two things to be "equal with statistical errors"; could you please provide the definition?
Comment: This sequence 01|01|001|1|001|0001|1|01|1|01|01|1|1| does not supply G/O = 1. That means , there is a deviation. Another sequence would show another deviation. Infinitely many sequences woulkd show 1 - also infinitely many trials of a single family! Not 31% G/(G+B).
Comment: Monty:  Perhaps my question wasn't clear.  Can you please define the phrase "equal with statistical errors"?
Answer: The expected number of boys per family is clearly 1. The probability that a family will have exactly $k$ girls is $(1/2)^k \cdot (1/2) = (1/2)^{k+1}$, as the first $k$ "draws" need to be a girl, while the $(k+1)$'th draw needs to be a boy (if not for the latter, the family would have more than $k$ girls).
Hence, the expected number of girls in a family is
$$(1/2) \cdot 0 + (1/4) \cdot 1 + (1/8) \cdot 2 + (1/16) \cdot 3 +\dots = \sum_{k=0}^{\infty}(1/2)^{k+1} k$$
Due to a well known property of geometric distributions, this expection is equal to 1. The ratio of boys to girls will thus be 1.
Comment: The ratio of two expected values is not usually the expected value of their ratios; see Douglas Zare's answer to the MO question above.
Comment: Monty:  Actually the question concerns the ratio of boys to girls, not girls to boys.  Do you also believe the ratio of boys to girls is "1/1 in every case"?
Answer: If every family continues having children until they have one boy, then every family will have one boy; except those who haven't stopped having children yet, or those that are not able to continue due to various circumstances.   Let's ignore these, as we don't have enough information to consider such.   (Likewise how many births are twin boys?)
The expected number of girls in families which have a boy is $1$, by reason that this count a geometrically distributed random variable (of failures before success), and for $\;G\sim\mathcal{Geo_0}(p)\;$, then $\;\mathsf E(G) = (1-p)/p\;$.
This leads to a theoretical expected ratio of $1:1$ boys to girls in the country.
Of course, we will actually expect the ratio to be somewhat higher, because there are families which have no boys (yet).   But we can't say what proportion of families these may be.

Ratio of Boys and Girls


Show me a badge in the navbar under certain VueJS pages

Question: I am building a SPA with Vue 3 and now I have the case that I would like to show a badge in the navbar of certain pages.
My structure:
// App.vue
<template>
  <NavBar />
  <RouterView />
</template>

My paths:

"/"
"/faq"
"counter/x" => here i need the badge in the navbar
"counter/y" => here i need the badge in the navbar

I also use a simple store solution. Here I have a function
export const store = reactive({
  isCounterPage: false,

  checkIsCounterPage() {
   this.isCounterPage = window.location.pathname.includes("/counter/");
  }
}

In the router/index.js File, I call the checkIsCounterPage() method.
// router/index.js
router.beforeEach(async (to, from, next) => {
  store.checkIsCounterPage()
}

And in my navbar, I use a condition where i check the variable:
// someView.vue
<template>

BADGE

</template>

Unfortunately, it doesn't work the way I want it to. Only after a hard refresh of the page (for example F5 / refresh Page) it recognises where it is. So the problem is that the store method is only called once on initialisation and not on route change as I assume.
Question:
What am I doing wrong and is this the right way at all?
Comment: Why are you not using a computed + vue-router path combo? It will be reactive that way.
Comment: @kissu Thank you! Can you paraphrase a little more how you mean it. i.e. roughly draw the structure.
Answer: You can add meta field to your counter routes:
routes: [
  { path: '/counter/x', component: x, meta: { isCounterPage: true } },
  ...
],

and check meta:
router.beforeEach(async (to, from, next) => {
  if (to.meta.isCounterPage) store.checkIsCounterPage(true)
  next()
}

and in store:
export const store = reactive({
  isCounterPage: false,

  checkIsCounterPage(val = false) {
    this.isCounterPage = val
  }
}

Comment: Thank you! I had already thought of it in a similar way. But why I hadn't done that was because I didn't want to add the meta in all the routes. Which is onsolte with the default value of the function. so this is a good solution. Thanks to you.
Comment: @Max Pattern you are welcome mate :) btw If you have many conter routes, and small number of no-counter ones, you can reveret and put meta on them, ofc adjust functions then, cheers :)


Pandas groupby two columns and create a new column based on difference in days from third column

Question: I have a dataframe with creation_timestamps and personal_id's. Each personal_id has one or more application_id's. An application_id can have a bunch of rows, but they all have the same creation_timestamp.
I want to create a column that indicates the days between two application_id's for a given personal_id. All the offer rows within the application_id should show the same days between the two application_id's.
Here's the code I've tried to modify in a bunch of ways:
# Calculate days between consecutive applications for each personal_id
df['days_between_applications'] = (
    df.groupby(['personal_id'])['creation_timestamp']
    .diff()
    .dt.days
)

Here's a preview of the current result:

personal_id
application_id
creation_timestamp
days_between_applications

1007
c1de3552cfb0
e18e5d77199f
2019-05-16 06:53:57.817842
NaN

1008
c1de3552cfb0
e18e5d77199f
2019-05-16 06:53:57.817842
0.0

1010
c1de3552cfb0
e18e5d77199f
2019-05-16 06:53:57.817842
0.0

1006
c1de3552cfb0
e18e5d77199f
2019-05-16 06:53:57.817842
0.0

7094153
c1de3552cfb0
 1f64dd61aee2
2023-08-07 11:01:45.588173
1533.0

7094147
c1de3552cfb0
 1f64dd61aee2
 2023-08-07 11:01:45.588173
 0.0

This is what I'm trying to achieve:

personal_id
application_id
creation_timestamp
days_between_applications

1007
c1de3552cfb0
e18e5d77199f
2019-05-16 06:53:57.817842
NaN

1008
c1de3552cfb0
e18e5d77199f
2019-05-16 06:53:57.817842
NaN

1010
c1de3552cfb0
e18e5d77199f
2019-05-16 06:53:57.817842
NaN

1006
c1de3552cfb0
e18e5d77199f
2019-05-16 06:53:57.817842
NaN

7094153
c1de3552cfb0
 1f64dd61aee2
2023-08-07 11:01:45.588173
1533.0

7094147
c1de3552cfb0
 1f64dd61aee2
 2023-08-07 11:01:45.588173
 1533.0

I've tried to forward fill, sort and then forward fill, groupby personal_id and application_id etc, but nothing has worked.
Comment: In my solution below, I'm assuming the application_id are unique (i.e. two different personal_id cannot have the same application_id). If this is not the case, please let me know.
Answer: You could drop_duplicates then compute the diff between successive applications per personal_id with groupby.diff. Finally, map this to the original DataFrame:
df['creation_timestamp'] = pd.to_datetime(df['creation_timestamp'])

diff = (df
   .drop_duplicates(['personal_id', 'application_id'])
   .sort_values(by='creation_timestamp')
   .set_index('application_id').groupby('personal_id')
   ['creation_timestamp'].diff().dt.days
)

df['days_between_applications'] = df['application_id'].map(diff)

Output:
          personal_id application_id         creation_timestamp  days_between_applications
1007     c1de3552cfb0   e18e5d77199f 2019-05-16 06:53:57.817842                        NaN
1008     c1de3552cfb0   e18e5d77199f 2019-05-16 06:53:57.817842                        NaN
1010     c1de3552cfb0   e18e5d77199f 2019-05-16 06:53:57.817842                        NaN
1006     c1de3552cfb0   e18e5d77199f 2019-05-16 06:53:57.817842                        NaN
7094153  c1de3552cfb0   1f64dd61aee2 2023-08-07 11:01:45.588173                     1544.0
7094147  c1de3552cfb0   1f64dd61aee2 2023-08-07 11:01:45.588173                     1544.0

Intermediate diff:
application_id
e18e5d77199f       NaN
1f64dd61aee2    1544.0
Name: creation_timestamp, dtype: float64

Variant if the application_id are not necessarily unique to one personal_id:
df['creation_timestamp'] = pd.to_datetime(df['creation_timestamp'])

diff = (df
   .drop_duplicates(['personal_id', 'application_id'])
   .sort_values(by='creation_timestamp')
   .set_index(['application_id', 'personal_id']).groupby('personal_id')
   ['creation_timestamp'].diff().dt.days
)

df['days_between_applications'] = diff.reindex(df.set_index(['application_id', 'personal_id']).index).values


Monotouch license

Question: I'm trying to transfer my monotouch license to a new machine, so that I can code on that one instead. How can I go about doing that?
I cloned everything from my old mac to my new mac, now when I build in monodevelop I get the error:
Error 99: mtouch failed with the following message:
Invalid license.  Please reactivate MonoTouch
 (99)
I have a redownloaded monotouch and monodevelop, I'm not sure where to go from here.
Comment: This can also happen after upgrading Windows (eg: Win7->Win8). In that case it seems to help to delete You'll need to remove the license file from:
%PROGRAMDATA%\MonoTouch\License\  and going back to VS, Tools -> Xamarin Store Account and reactivate.
Comment: I'm voting to close this question as off-topic because it is about software licensing.
Answer: This worked in previous versions where the activation was separate from the Install, but now it is together with the installer, so if the above app is still there, run it, but that might be an older version.
To register now you'll have to remove the license file and re-run the setup. The license file is in ~/Library/MonoTouch and will have the name "License" or "License.v2" depending on the version of MonoTouch you have installed.
Answer: The current (2012) error is "mtouch exited with code 99".
In addition to deleting the license file in ~/Library/MonoTouch, as noted by @Kenny, you may also need to delete the contents of /Developer/MonoTouch. If you don't do this, the MonoTouch installer may not do anything at all.
Answer: In case someone has trouble with this:

Log in at xamarin.
Download your license file (think about creating a new on if you moved to another machine)
Open the Mac terminal
chflags nohidden ~/Library/
Open your user-home-directory in Finder.
NOW you can see the freakin' Library-folder.
After you placed the license-file there go back to terminal and use chflags hidden ~/Library/

For those of you who don't know where "~" comes from on Mac: Alt + N + Space!
Answer: see this answer for a current solution:
How do I reactivate Monotouch?
this original answer is obsolete

Use the Activation application
/Developer/MonoTouch/Applications/MonoTouch Activation

Monotouch license


Trabalhar com dois cursores na mesma conexão

Question: preciso fazer a leitura de duas tabelas no banco de dados de forma a compara-las posteriormente, o código que fiz esta dando erro, pois estou passando duas consultas na mesma conexão como poderia estar corrigindo isso? Obrigado.
<code>import pyodbc
conn = pyodbc.connect("DRIVER={SQL Server};Server=localhost;database=teste;uid=;pwd=")

cursor1 = conn.cursor()

cursor1.execute("select top 10 * from tab1")

cursor2 = conn.cursor()

cursor2.execute("select top 10 * from tab2")

for row in cursor1:
   print(row)

for row in cursor2:
    print(row)
</code>
Answer: Você pode corrigir isso sem infinitivo + gerúndio. Basta atribuir cada consulta a  uma variavel usando fetchAll() e posteriormente comparar as variaveis.


Why is sklearn PCA implementation in Python sensitive to the order of columns in source data?

Question: The rotation matrix outputted by the PCA algorithm should be independent of something trivial like the column ordering of the source data. Can anyone explain why my output diverges from my expectation for consistency?
I made a test input file 30x569 from a pre-made dataset
from sklearn.datasets import load_breast_cancer
cancer = load_breast_cancer()
cancer.keys()

df = pd.DataFrame(cancer['data'],columns=cancer['feature_names'])
df.to_csv(r'input file',index=False)

Then generated a 30x30 output with all the covariance-based PCA components
import pandas as pd
import numpy as np

daily_series = pd.read_csv (r'input path')

sd = daily_series[daily_series.columns[0:daily_series.shape[1]]]
scaled_data = sd #unscaled
from sklearn.decomposition import PCA
pca = PCA(n_components=daily_series.shape[1])
pca_model = pca.fit(scaled_data)
components = ['PC1','PC2','PC3','PC4','PC5','PC6','PC7','PC8','PC9','PC10','PC11','PC12','PC13','PC14','PC15','PC16','PC17','PC18','PC19','PC20','PC21','PC22','PC23','PC24','PC25','PC26','PC27','PC28','PC29','PC30']
variables = daily_series.columns[0:daily_series.shape[1]]
Matrix = pd.DataFrame(pca_model.components_, columns=components, index=variables)

Matrix.to_csv(r'output path', index=True)

When I reorder the columns (let's say alphabetically) of the test input file. And run the above my output from the original test is different not just in the signs but also magnitude. I don't understand how that's possible.
Output (left is original output/right is output after alphabetizing columns in source data):
Comment: The main thing to observe is that the SVD of $A$ is given by

$$
A = U\Sigma V^\top
$$

then for a column permutation via matrix $P$ we have

$$
AP = U\Sigma V^\top P
$$ because permutation matrices are orthogonal and products of orthogonal matrices are orthogonal. Your components are given by $V^\top P$.

The rest is just showing the relationship between PCA and SVD. This is covered thoroughly in https://stats.stackexchange.com/questions/134282/relationship-between-svd-and-pca-how-to-use-svd-to-perform-pca
Comment: @SycoraxsaysReinstateMonica  I looked at the output files again and I see you were right. PC1, PC2, PC3 became PC12, PC15, PC11 respectively when I alphabetized columns in my example. Ok this means the relationship between variables after you reduce dimensions is sensitive to the ordering of the columns in the beginning. How do you pick the "best" order of columns in the beginning if your goal is to understand how the variables are interrelated?
Comment: Hey Quesop. I talked to @Sycorax in the comments to their answer, and we figured out that your confusion was because your PCs are in *rows* of your Excel table, and your variable are in *columns*. You somehow have these tables transposed. PC1 cannot become PC12 after changing the column order, this just does not make any sense. PC1 stays PC1, but its elements are reordeded.
Comment: @SycoraxsaysReinstateMonica The transformed variables (principal components) should correspond to the original variables. So why don't they as I highlighted in red? So I'm trying to understand why the python PCA implementation doesn't work as it should. I shouldn't have to write my own implementation right?
Comment: The transformed variables *do* correspond to the original variables. The reason the two outputs don't match is that one is a permutation of the other. This is what I wrote in my first comment. The python implementation works correctly because this is a property of SVD and orthogonal matrices.
Comment: @SycoraxsaysReinstateMonica I know what a permutation is and I know what column is but I don't understand what you mean by "column permutation." Permutation means the order matters. Manifestly the order of the columns matters but why? Column order is trivial so it should not matter. How are the left and the right screenshots equivalent representations?
Comment: They're not *equivalent,* they're *permutations.* You can rearrange the columns in the two screenshots, and after rearranging, they'll be the same. The order that you use for rearranging is given by $P$. In the permuted case, `pca_model.components_` has computed $V^\top P$. Because permutation matrices have the property that $P^{-1}=P^\top$, you can retrieve the original $V$ by observing $V^\top P P^\top= V$.
Comment: This seems like a fundamentally different question, distinct from the one in your post. If you've found my answer addresses your original post, please consider upvoting and/or accepting. If you have additional questions, you can click Ask Question (if you feel you need this question for context, you can link to it).
Answer: We have thoroughly developed the relationship between SVD and PCA in
Relationship between SVD and PCA. How to use SVD to perform PCA?
which is worth reviewing if you're uncertain about the connection.

The sklearn PCA implementation is working correctly.
The main thing to observe is that the SVD of $A$ is given by
$$
A=U S V^\top
$$
so for a permutation of columns via matrix $P$ we have
$$
AP=U S V^\top P.
$$
Another way to state this is that if you compute the SVD of $AP$, you'll end up with $AP = U S \tilde{V}^\top$, where $\tilde{V}^\top = V^\top P$.
We know that $\tilde{V}^\top=V^\top P$ is orthogonal because permutation matrices are orthogonal and products of orthogonal matrices are orthogonal.
Your screenshots show different things because you're comparing $V^\top$ and $V^\top P$, which are not equal in general. In fact, $V^\top$ and $V^\top P$ are only guaranteed to be equal if $P=I$. Column order matters just for $V$; $U$ and $S$ are the same.

We can even show that a permutation yields the same orthogonal rotation.
$$
\begin{aligned}
AV &= USV^\top V \\
AV &= US
\end{aligned}
$$
And we can show the same result for $AP$ because a permutation matrix $P$ is orthogonal.
$$
\begin{aligned}
AP P^\top V &= USV^\top P P^\top V \\
AV &= US
\end{aligned}
$$
In other words, the column order doesn't matter for creating a linearly independent basis for $A$, because you obtain the same result for $AP$ and $A$.

We can demonstrate this all in Python.
import numpy as np
from numpy.linalg import svd
from numpy.random import shuffle
from sklearn.datasets import load_breast_cancer

if __name__ == "__main__":
  X, y = load_breast_cancer(True)
  U, S, V = svd(X, full_matrices=False)

  P = np.eye(X.shape[1])
  shuffle(P)

  print("X and X @ P are not the same.")
  print(X @ P - X)

  # This will work correctly because both X and the SVD of X are permuted.
  assert np.allclose(U @ np.diag(S) @ V @ P - X @ P, 0.0)

  try:
    # This will fail because X is permuted but the SVD is ~not~.
    assert np.allclose(U @ np.diag(S) @ V - X @ P, 0.0)
  except AssertionError:
    print("V @ P != V")
    print(V @ P - V)

You can replace P with any permutation matrix you desire, even one which alphabetizes the column names.
Comment: @amoeba I see what you're saying, but I've found that reliance on terminology can confuse the issue, especially because most software documentation is garbage. Instead, I prefer to think through the factorization. So in your example, if I want the product $AV$ to have rank $k$, I just think through the algebra: what shapes of $U,S,V$ do I need for the (truncated) SVD to make sense and produce the desired result? Maybe it's just a personal quirk, but this is the only way I can remember how PCA and SVD work. What's a "score," "loading," or "PC"? I honestly can never remember, but I know the math
Comment: Actually I am still confused by this Q. Shouldn't `PCA` from `sklearn` order components by explained variance? If so, permuting the features in X should not affect the returned V, because its columns are supposed to be sorted. What am I missing?
Comment: They *are* ordered by explained variance. The $U$ and $S$ in my answer are the same for both $AP$ and $A$. The difference is that the $P$ re-arranges which directions maximize variance, kind of like how re-labeling "North" on a compass doesn't change where the North Pole is. Another way to think about it is that the covariance of $AP$ is given by $\frac{1}{n-1} P^\top A^\top AP = P^\top V\frac{S^2}{n-1} V^\top P$, which is a full permutation of $A$'s covariance $V \frac{S^2}{n-1} V^\top$ . Clearly the factors $S, V$ are just re-arranged by $P$, but its values aren't changed.
Comment: Another way to answer your question is to point out that it's just convention to sort an SVD factorization according to the values of $S$. However, the definition of a singular value and singular vector (and likewise eigenvalue and eigenvector) is still satisfied as long as you match singular values in $S$ to their singular vectors in $U,V$. So for whatever ordering of $S$ you choose, all of the equalities in my answer will still hold, as long as you order $U,V$ to match the ordering in $S$.
Comment: Sorry but this does not clarify :-( Maybe I am misunderstanding what happens in the question? The breast cancer dataset has 30 features and 500+ samples. OP does PCA on 30x30 cov matrix using sklearn and gets 30 eigenvectors. They should be sorted by the eigenvalues. Now the OP permutes the 30 features and re-runs PCA. The eigenvectors are not the same even accounting for the re-ordering: e.g. the element for "area error" in the 1st eigenvector is 0.08 vs. 0.05. In the comments OP says that PC1 became PC12. This does not make sense to me.
Comment: Suppose $A$ has rank 2 and 2 columns and you swap the  two columns. Do you expect $V$ to be the same or to be permuted? Why or why not? Can you relate your intuition to the definitions of eigenvalues and eigenvectors? Drawing a picture should make this more clear but I'm on a train now so I can't.
Comment: So for concreteness, if A has measurements of some objects and its columns are Width and Height, and I do PCA and get PC1 which has let's say [0.6, 0.8] weights (so that's the eigenvector with the largest eigenvalue), then if I swap the columns to [Height, Width], then I expect the resulting PC1 to have [0.8, 0.6] weights. The same weights as before but permuted of course, such that the PC1 weight for Height remains the same as it was (0.8). Surely you cannot argue with that??? But this is NOT what I see in the tables that OP posted! [exploding head emoji]
Comment: @amoebasaysReinstateMonica In a comment, OP says "PC1, PC2, PC3 became PC12, PC15, PC11 respectively when I alphabetized columns in my example." But the tables only have the first 3 PCs. So the reason the table doesn't show the same PCs in a different order is because the table is only showing the first 3 PCs, which does not extend to PC 11, 12, ... 15.
Comment: I think we are talking past each other :) What I tried to show in my concrete example in the comment above with Height/Width, is that if PCs are ordered by variance then PC1 should remain the same (up to reordering of its entries). So [0.6, 0.8] will become [0.8, 0.6]. Do you agree with that? If you do agree, then "PC1 becoming PC12" in OPs comment does not make sense.
Comment: $V^\top P$ is a permutation of the columns of $V^\top$, so what happens in your example is that PC1 is swapped with PC2, not that the elements of PC1 are swapped. (The only non-$I$ permutation matrix for $2\times 2$ covariance matrix is $P=[e_2 ~~ e_1]$).
Comment: But this does not make any physical sense! Just imagine a diagonally elongated 2D scatter plot with the first eigenvector pointing in the [0.8, 0.6] direction. Now swap X and Y. The scatter plot is still diagonally elongated, with the first eigenvector pointing in the [0.6, 0.8] direction. It is *NOT* pointing in the direction orthogonal to [0.8,0.6]. In terms of algebra and using your notation, PC1 is the first row of $V^\top$. Your $P$ permutes columns of $V^\top$ so it permutes elements of PC1, and not the PC1 with PC2.
Comment: You should probably ask a question about this. I feel like we're talking in circles. Maybe the screenshots are transposed? Maybe the terminology is confused? I'm confident that the algebra works out. I'm less interested in an argument about what a row is.
Comment: Well I'm saying that your statement (from the comment above) "what happens in your example is that PC1 is swapped with PC2, not that the elements of PC1 are swapped" is wrong. And I explained why. Not sure what your response to that is; do you agree with me? If you don't agree, what specifically in the last sentence of my previous comment do you think is wrong?
Comment: I think all you're saying is that OP's table should be transposed? Or that what I'm calling a PC is a misuse of terminology? Like I said, the terminology discussion is not interesting to me... Just work out the algebra, and you can show that it works, and you don't end up tripping over what someone decided to label a column or a row.
Comment: Re "I think all you're saying is that OP's table should be transposed? " -- to be honest I didn't think of that, but now that you say it, it does seem like a likely explanation of what happened there :)
Comment: I am sorry, but I cannot agree that it does not matter what the word "PC" refers to here. If you ask sklearn PCA to give you only PC1 with `n_components=1`, you really expect matrix V that you get out to have one column. So that is PC1. Not a row.
Comment: That said, we do seem to be in full agreement as long as the math goes :)
Comment: +1 to this, I think this is a great way to think about it. And I agree that some traditional terminology here (score/loading/etc) is confusing. Nevertheless, let me suggest that we reserve the word "PC1" to whatever comes out of rank-1 approximation! This should be easy for you to remember because it clearly follows the mental picture suggested in your last comment. As we figured out, the confusion that OP had was because his PCs are actually in rows of his Excel tables and his variables are in the columns; I doubt that your answer resolved their confusion (but who knows, maybe it did).


problem on determining limit of sequence

Question:
 In the solution , I think there is a mistake the value of l should be π and   1-π it should not be π+1. Then what would be the limit of this sequence?
Comment: No if you see the recurring formula the limit point at n step (say ), will always be greater than π . although in our calculation it comes out to be π and 1-π.
Comment: Why do you think $l =1-\pi $?
Answer: If $x_n-\pi> 1$ then $$x_{n+1}-\pi =\sqrt {x_n-\pi}> \sqrt 1=1.$$ Since $x_1-\pi>1, $ we have $x_n-\pi>1$ for all $n$ by induction on $n.$
You have correctly shown that if the limit exists it is $\pi$ or $\pi +1.$ But since $x_n>\pi +1$ for all $n,$ the limit cannot be $\pi.$ The problem allows you to assume the limit exists  (The allowable answers give you no other option.) So it must be  $\pi+1.$
BTW since $y>1\implies y>\sqrt y>1,$ we have $x_n-\pi>1\implies x_n-\pi>x_{n+1}-\pi>1.$ So if $x_1>\pi +1$ then the sequence $(x_n-\pi)_n$ is decreasing and has a lower bound (namely, $1$) so it must have a limit.
Comment: How did u assume at the beginning that n term minus π is greater than 1 . This is a convergent sequence and hence its possible that the n^th term may be smaller than π.
Comment: I said IF $x_n-\pi>1$ THEN $x_{n+1}-\pi >1.$ I didn't assume anything.


Laravel - Salvar dados no banco apenas se não existir e.......

Question: Estou com um sistema de cadastro de pessoa e nele há uma área com diversos campos de checkbox que representam os grupo sociais que a atual pessoa representa:
TABELAS
pessoa
id | nome
1  | João
2  | Maria
3  | Ana

grupo
id | grupo
1  | Lorem1
2  | Lorem2
3  | Lorem3

grupo_pessoa
id | id_grupo | id_pessoa
1  |     1    |      1
2  |     1    |      2
3  |     2    |      1

E estou com o seguinte código no meu controller para salvar as alterações:
PessoaController
    $grupo = $request->grupo; //retornando valores dos campos checkbox

    for($x = 0; $x < count($grupo); $x++){
        array_push($query_grupo, array('id_grupo' => $grupo[$x], 'id_pessoa' => $id));
    }
    DB::table('grupo_pessoa')->insert($query_grupo);

Eu preciso remover da tabela os grupos que eu desmarco e salvar os selecionados apenas se não existirem ainda.
Eu tentei usar o "save" pq dizem que ele já faz essa verificação mas não funcionou da forma que tentei:
$grupo_pessoa = new GrupoPessoa;

        for($x = 0; $x < count($grupo); $x++){
            $grupo_pessoa->id_grupo = $grupo[$x];
            $grupo_pessoa->id_pessoa = $id;
            $grupo_pessoa->save();

            array_push($query_grupo, array('id_grupo' => $grupo[$x], 'id_pessoa' => $id));

        }

Comment: vc conhece o sync ou o attach e dettach? Veja aqui que encontrará... https://laravel.com/docs/5.2/eloquent-relationships#inserting-many-to-many-relationships se não conseguir faço um modelo hoje mais tarde. Abs
Comment: Nunca usei e é bem complexo kkkk vou ver se entendo.
Comment: é tranquilo na verdade. sua tabela de ligação nem precisa de id, pode ter somente as duas chaves da tabela pessoa e grupo ambas como sendo chave primária e ficará inclusive mais rápida a pesquisa. Faça um teste simples primeiro e verá que é bem simples. Tenho algo pronto, mas não consegui achar aqui. Te mandarei um exemplo pronto depois. Abs
Comment: Legal a resposta do João é bem isso. Não consegui terminar... mas farei em breve pra ficar como referência, segue: https://github.com/code-sample/laravel-many-to-many Devo terminar hj a noite ou amanhã. Tenho de fazer as views... se quiser ajudar. Abs
Answer: No relacionamento muitos para muitos, é identificado pela chave primária de outras duas tabelas, formando o conjunto que identifica a chave primária da tabela intermediária, ou seja, aquele que recebe as duas chaves.
Em seu caso eu observei que colocou um chave primária que identifica cada registro de sua tabela, e dois campos que são os que relacionam as chaves primárias. Será que é preciso (redundante) ???
Em Laravel, o Eloquent ORM faz o trabalho pesado, então se for configurado como especificado logo abaixo é um simples comando. Exemplificando:
Tabela Pessoa (class pessoa)
<?php namespace App;

use Illuminate\Database\Eloquent\Model;

class Pessoa extends Model
{
    protected $table      = 'pessoa';
    protected $primaryKey = 'id';
    protected $fillable   = ['nome'];
    public  $timestamps   = false;

    public function grupo()
    {
        return $this->belongsToMany('App\Grupo','grupo_pessoa','id_pessoa', 'id_grupo');
    }
}

Tabela Grupo (class grupo)
    <?php namespace App;

    use Illuminate\Database\Eloquent\Model;

    class Grupo extends Model
    {
        protected $table      = 'grupo';
        protected $primaryKey = 'id';
        protected $fillable   = ['grupo'];
        public  $timestamps   = false;

        public function pessoa()
        {
            return $this->belongsToMany('App\Pessoa','grupo_pessoa','id_grupo','id_pessoa');
        }
    }

A sua tabela grupo_pessoa nesse caso exemplo tem que ficar com dois campos somente: (Layout)
grupo_pessoa
id_grupo | id_pessoa

A relação Many To Many é nesse formato, eu tive que colocar os campos na configuração, porque o padrão seria o nome da tabela, undescore e id da tabela, no seu caso o id vem na frente, mas, na configuração colocada funciona da mesma forma reescrevendo a maneira do Eloquent saber o nome do campo que relaciona.
A pergunta se resume agora nesse comando simples e fácil o sync, aonde ele verifica ao enviar o array de informações quais informações tem na tabela ai ele não faz nada, quais não tem ele insere como novo registro e as que foram retiradas ele remove. Na verdade esse comando em um detach e um attach do Eloquent em sequencia.
$pessoa = App\Pessoa::findOrFail(1);
$pessoa->grupo()->sync([1,2,3];

Essa seria a forma correta, e ideal, seguindo a nomenclatura do próprio Framework de persistência o Eloquent no relacionamento simples de Many to Many
Leia:
Eloquent ManyToMany - Relacionamentos Muitos para Muitos
github - code-sample/laravel-many-to-many
Comment: Legal João bem isso mesmo. Vou fazer um modelo para futura referência. Vejo que isso é uma questão recorrente com o Laravel. Estou começando aqui: https://github.com/code-sample/laravel-many-to-many
Comment: Boa @Evert legal ... demais ... parabéns, vou colocar o seu link na resposta!


Python generator objects: __sizeof__()

Question: This may be a stupid question but I will ask it anyway. I have a generator object:
>>> def gen():
...     for i in range(10):
...         yield i
...
>>> obj=gen()

I can measure it's size:
>>> obj.__sizeof__()
24

It is said that generators get consumed:
>>> for i in obj:
...     print i
...
0
1
2
3
4
5
6
7
8
9
>>> obj.__sizeof__()
24

...but obj.__sizeof__() remains the same.
With strings it works as I expected:
>>> 'longstring'.__sizeof__()
34
>>> 'str'.__sizeof__()
27

I would be thankful if someone could enlighten me.
Comment: You might also be interested in [`sys.getsizeof()`](http://docs.python.org/library/sys.html#sys.getsizeof). It also considers gc overhead (if that matters to you), and it is a little less hackish.
Comment: @mhawke: actually, the OP wasn't even interested in `__sizeof__`! :)
Comment: @NedBatchelder: yes, you're right!
Answer: __sizeof__() does not do what you think it does. The method returns the internal size in bytes for the given object, not the number of items a generator is going to return.
Python cannot beforehand know the size of a generator. Take for example the following endless generator (example, there are better ways to create a counter):
def count():
    count = 0
    while True:
        yield count
        count += 1

That generator is endless; there is no size assignable to it. Yet the generator object itself takes memory:
>>> count.__sizeof__()
88

You don't normally call __sizeof__() you leave that to the sys.getsizeof() function, which also adds garbage collector overhead.
If you know a generator is going to be finite and you have to know how many items it returns, use:
sum(1 for item in generator)

but note that that exhausts the generator.
Comment: Indeed it's possible to have infinite generators or non-deterministic generators
Answer: As said in other answers, __sizeof__ returns a different thing.
Only some iterators have methods that return the number of not returned elements. For example listiterator has a corresponding __length_hint__ method:
>>> L = [1,2,3,4,5]
>>> it = iter(L)
>>> it
<listiterator object at 0x00E65350>
>>> it.__length_hint__()
5
>>> help(it.__length_hint__)
Help on built-in function __length_hint__:

__length_hint__(...)
    Private method returning an estimate of len(list(it)).

>>> it.next()
1
>>> it.__length_hint__()
4

Comment: thanks for the __length_hint__. also len(list(it)) consumes an iterator but __length_hint__ does not.
Comment: @root Yes, `list` consumes it, converts to list (which takes some memory) and only then calculates the length of the created list. While `length_hint` is a specially implemented method just for list iterator object.
Answer: __sizeof__ returns the memory size of an object in bytes, not the length of a generator, which is impossible to determine up front as generators can grow indefinitely.
Answer: If you are certain that the generator you've created is "finite" (has a countable number of elements) and you don't mind waiting a while you can use the following to get what you want:
len(list(gen()))

As the other posters said __sizeof__() is a measure of how much memory something takes up (a much lower level concept that you probably will rarely need), not its length (which is not a feature of generators since there's no guarantee they have a countable length).

Python generator objects: __sizeof__()


Erro: 'boolean java.lang.String.equals(java.lang.Object)'

Question: Este é um programa, que por traz da calculadora, guarda arquivos que julgue importantes. O campo de mensagem do erro creio que não seja dele e sim do Super SU ou do sistema Android, pois toda vez, em qualquer programa que tenha que ter um acesso mais profundo ele abre o mesmo estilo de campo dizendo que concedeu permissão. Porém desta vez um erro ocorreu. Alguém poderia me auxiliar a resolver este problema?
Comment: mas está a desenvolver essa aplicação? Ou é um erro de alguma aplicação que já exista?
Comment: Coloque o seu código cara, desse jeito sua pergunta ira receber downvotes e será fechada. Outra coisa você está comparando um boolean com um Object?
Comment: @WellingtonAvelino nesse caso boolean é o tipo de retorno do método equals.
Comment: @WellingtonAvelino o `boolean` é da função `equals`
Comment: O seu problema se chama `java.lang.NullPointerException`. Veja mais aqui: http://pt.stackoverflow.com/a/63736/132
Comment: Não entendi direito então, achei que fosse outra coisa não o retorno dele. hahaha
Answer: O erro informado por você indica que em alguma parte do seu código você esta fazendo str1.equals(str2); sendo que str1 é um objeto nulo, ou seja, você esta fazendo referencia a um objecto nulo.
verifique em seu código os lugares em que você está usando o método equals para encontrar onde está seu erro.
Exemplo que dará o erro:
String str1 = null;
String str2 = "teste";
boolean ret = str1.equals(str2);


Address bits within uint8_t as members of struct

Question: I am currently writing code for a PIC micro-controller and I would like to structure some of my code using a uint8_t as a "state counter" for a part of my code. This involves a lot of bitwise operations. What I'd like to do is create a struct for this uint8_t in a similar vein to the SFR bits structs that are within the header flies, I have included an example of one from the header file that I'm using below.
The header file allows access to the bits within the SFR using a notation similar to accessing elements within a struct, eg U1STAbits.UTXBF and as a uint16_t this is what I'd like to implement in my code as it will allow me to use a switch statement as the main structure of my code.
#define U1STA U1STA
extern volatile unsigned int  U1STA __attribute__((__sfr__));
__extension__ typedef struct tagU1STABITS {
  union {
    struct {
      unsigned URXDA:1;
      unsigned OERR:1;
      unsigned FERR:1;
      unsigned PERR:1;
      unsigned RIDLE:1;
      unsigned ADDEN:1;
      unsigned URXISEL:2;
      unsigned TRMT:1;
      unsigned UTXBF:1;
      unsigned UTXEN:1;
      unsigned UTXBRK:1;
      unsigned :1;
      unsigned UTXISEL0:1;
      unsigned UTXINV:1;
      unsigned UTXISEL1:1;
    };
    struct {
      unsigned :6;
      unsigned URXISEL0:1;
      unsigned URXISEL1:1;
    };
  };
} U1STABITS;
extern volatile U1STABITS U1STAbits __attribute__((__sfr__));

Update:
I have made a potential solution based from this:
typedef struct  {
    union {
        struct{
            unsigned breakDetected  :1;
            unsigned overrunError   :1;
            unsigned framingError   :1;
            unsigned startDetected  :1;
            unsigned dmxMode        :1;
            unsigned rdmMode        :1;
        };
        uint8_t UartFlags;
    };
} UartFlagsBits;

UartFlagsBits uartFlags;

Comment: The smallest addressable unit on just about all modern CPUs is the byte. Bit fields like the one you show is handled by the compiler generating the code needed to get or set the individual bits.
Comment: @RobbG At minimum you should at least use same type for bits as a flag variable (`uint8_t` instead of `unsigned`). But even then C standard allows compiler to put padding in bitfields and change type or order. In general bit fields are a mess for what you are trying to do. I would use plain `uint8_t` and use bit mask operators `~&|^` to modify bits to have 100% control.
Comment: This is called bit field. And what is your question?
Comment: So if I was to declare my bitfield in a similar way would I be able to access it as a uint8_t as well then?
Comment: If you use the solution with unions then yes.
Comment: Define a union, with uint8_t member and bitfield struct. You can read/write both the whole value through uint8_t and its bits through bitfield structure. Standard way in hardware programming.
Comment: Relevant: http://stackoverflow.com/a/19376742/694733
Answer: By defining a union between a bitfield struct and a uint8_t I am able to access the bitfield as a number to perform actions on the whole bitfield as suggested by Alex.
typedef struct  {
    union {
        struct{
            uint8_t breakDetected  :1;
            uint8_t overrunError   :1;
            uint8_t framingError   :1;
            uint8_t startDetected  :1;
            uint8_t dmxMode        :1;
            uint8_t rdmMode        :1;
        };
        uint8_t UartFlags;
    };
} UartFlagsBits;

UartFlagsBits uartFlags;


The first $4$ primes $p$ for which $15347$ has a square root mod $p$ are $2, 17, 23,$ and $29$

Question: I am reading about Quadratic Sieve article in wiki and I don't understand the sieve part.
The article says:

The first $4$ primes $p$ for which $15347$ has a square root mod $p$ are
  $2, 17, 23,$ and $29$

How $2,17,23,$ and $29$ been calculated? If you can, please explain me the idea and the exact calculation.
Comment: Use [quadratic reciprocity](https://en.wikipedia.org/wiki/Quadratic_reciprocity).
Comment: Note that $ 15347=103\cdot 149$ and use the above.
Comment: The real answer to your question is, I wrote a C program that looked for large numbers that could be factored with few primes over a small sieve, and picked one that looked the best.  Finding a 5 digit number that could be factored with 4 primes and a sieve of only 100 entries was the best I found.  Usually, it would take much larger sieves and many more primes (quadratic residues).
Answer: You could use quadratic reciprocity, as suggested in the comments, but those primes are so small that a brute-force approach is also reasonable. To find out whether a large $n$ has a square root modulo a small prime $p$, first compute $x = n \bmod p$, and then check whether $y^2 \equiv x \bmod p$ for some $y \in \{0,1,\ldots,(p-1)/2\}$.
Comment: It worked for $y \in \{0,1,\ldots,p\}$ Tnx


A subtlety in calling the index of the added element to an infinite sequence

Question: $\newcommand{\N}{\mathbb{N}}$
Consider a bounded increasing infinite real sequence $(a_i)_{i \in \N}$. If I add an element $x$ larger than the supremum of $(a_i)$ to create another increasing sequence $(b_i)$, it contains the largest element $x$. Meanwhile, the index of every element is finite. Then, what can we say about the index of $x$? Is it also finite? I am confused because if it is finite, it will mean $(b_i)$ is finite. Please let me know what I am missing here. (I suspect I just can't make a new sequence in such a way.)
Comment: "Add it" where? To get an increasing sequence, you would need $k\geq i$ for all $i\in\mathbb{N}$. That's not a sequence any more, because a sequence is a function with domain $\mathbb{N}$, so every index has to be a natural number. So what you can say is "You can't add it to begin with."
Comment: @AdamRubinson I thought Magidin has already explained why it is incoherent, didn't he?
Comment: @ArturoMagidin You just excellently answered my question. Thank you. If you give an answer, I will accept it.
Comment: Relevant is [Brian M. Scott's answer to: *On defining sequences*](https://math.stackexchange.com/a/484644/13130).
Comment: "If I add an element $x$ larger than an upper bound of $(a_i)$ to have another increasing sequence $(b_i)$, $b_i$ has the largest element $x$." This sentence is incoherent. Please clarify.
Comment: The sentence makes no English sense. I don't know how Arturo parsed it. But if what he said answers your question then ignore me.
Comment: Would you correct me based on how he interpreted my question? $b_i$ has $x$ as its largest element or something?
Answer: Recall that a real sequence is "really" a function $a\colon\mathbb{N}\to\mathbb{R}$; it's just that instead of writing $a(1)$, $a(2)$, etc. we write $a_1$, $a_2$, and so on; and because we can list the inputs, we can describe the whole function with a list, $(a_1,a_2,a_3,\ldots)$.
You start with an increasing bounded sequence, $(a_1,a_2,\ldots,a_n,\ldots)$, with $a_i\leq a_j$ whenever $i\leq j$, and with $a_k\leq M$ for all $k$. You say, "if I add an element $x$ greater than $M$" to the sequence, while keeping it an increasing sequence... but that is not really doable.
If you were to put this number $x$ in the sequence, it would have to be the image of some natural number $k$; and if the resulting sequence is still increasing, then because $a_m\leq x$ for all natural numbers $m$, you would need $m\leq k$ for all natural numbers $m$. There is no such natural number. So there is no way to "add" this term to the sequence: there is no place where you can place it (while keeping every term before its location where it is, and "shifting" every term after where you locate it one position over). The operation of adding a single term somewhere is doable. You just cannot do it and still keep an increasing sequence, if you are adding a term that is larger than all terms you already have.


UIPopoverController setting frame size

Question: I am creating a popover in this way:
<code>popoverController = [[UIPopoverController alloc]initWithContentViewController:browser];
[popoverController presentPopoverFromRect:CGRectMake(44, 400, 600, 800) inView:self.view permittedArrowDirections:0 animated:YES];
</code>
for some strange reason whatever CGRectMake size I put, the result is the same, the popover takes all the hight of my view and half of the width. Why is this?
Answer: You may have to set contentSizeForViewInPopover property for your content view controller before presenting the popover.
Comment: ok, this works popoverController.popoverContentSize = CGSizeMake(400.0, 500.0);
Comment: but still, it seems that if I put any size I still have that problem. what shall I put instead of CGRectMake?
Comment: The CGRect which is passed to the `presentPopoverFromRect:inView:permittedArrowDirections:animated:` does not affect the size of the popover at all. It is needed to determine the position of the popover and the arrow direction. Apple's documentation states the following about this parameter: "The rectangle in view at which to anchor the popover window." So to set the size of the popover you have to use either the `popoverContentSize` of `UIPopoverController` or `contentSizeForViewInPopover` of your content `UIViewController`.

UIPopoverController setting frame size


Number of samples required to have visited all classes of a uniformly distributed distribution?

Question: So let's say I have a set of binary vectors $x \in \{0,1\}^n$. Hence, $|\{x\}| = 2^n$  . For all $x$, there is a class $c_i$. We do not know what is this class a priori, but we can compute it once we sample $x$.
There are polynomially many such classes and the number of such classes is bounded above by $n^{k}$ for some $k$ (known to us).
I also know that $|\{x_i: x_i \in c_i\}| \approx |\{x_j: x_j \in c_j\}| $ i.e there are equally many $x$'s in each class.
Now, my question, what is the fastest way to draw at-least one sample from each class. Is there anything better than uniform sampling ? And How can I device a good stopping criterion ? I only know the bound on the number of classes not the exact number of classes, can there be a $(\delta,\epsilon)$ guarantee on visiting all the classes ?
Comment: Within this question appear a strange mix of assumptions.  The question as formulated appears to be answerable for any given (but arbitrary) $n$ without any of the information it provides: what is the point of providing asymptotic information?  Also, by "fastest way to draw" what do you really mean? Objectively, one starts with a list of members of the classes and takes one member from each class: done. Are you supposing the sampling must be blind to class membership? If so, what possible alternatives to uniform sampling could there be? Can you clarify your problem?
Comment: One way to ask this question is: Suppose we have samples $x_1,\ldots x_n$ from a uniform distribution of $c$ classes, and have observed $m$ classes so far. What is the maximum likelihood estimate of $c$? And if we use a stopping criterion of $$P[x_1,\ldots x_n|c=m+1]< \epsilon P[x_1,\ldots x_n|c=m]$$ how can we calculate the probabilities easily, and what is the distribution of stopping times under various assumptions for $c$ and $\epsilon$?
Comment: E.g. if our first dozen observations include three A's, three B's, three C's, two D's and an E, then $c$ is most likely 5. But if our first dozen observations include eight A's, and one each of B, C, D, E, then maybe it's more likely that $c$ is larger.
Comment: I am sorry, I see my question was poorly explained. We do not know the number of classes, and getting a sample from each class is precisely the goal. Also, It is much harder to the reverse process of generating a sample given the class. I hope it is clearer now.
Comment: Thank you: I think the nature of your question is clear enough.  I wonder, though, what you might mean by "fastest way."  Isn't it necessary to sample uniformly and sequentially; and the only issue concerns when to stop sampling?  You just don't have any information you could possibly to exploit to improve over that.  And since you're not in an asymptotic situation--you have a set of vectors, pure and simple--of what use are any asymptotic bounds on the number of classes?
Comment: @MattF. I use an intuitive version of this to stop sampling so far. I stop when I stop seeing new samples. I agree with your formulation.
Comment: @wuber since $k$ is known, when you have a very large $n$ then the stopping criterion is relatively simple. For example if $k=2$ , then for n =25 , you will not really need many samples(w.r.t 2^(25)) before you would have visited all the classes. The problem is in my case $k$ is quite large $\approx 100$. Well, I would be interested if something can be said even theoretically for a case when n^k << 2^n, like what number of samples gaurentee with a certain confidence having visited all classes
Comment: That's a slightly different question.  I don't think you need maximum likelihood here, and it might even get in the way of developing an efficient solution, because after you have done some sampling you will obtain a fairly accurate estimate of the average class size and from that you can accurately estimate the chance of not having sampled one or more classes.
Answer: Suppose we have $n$ observations, with $m$ classes so far, and we want to determine the total number $c$ of classes. With a maximum likelihood approach, the most likely scenario is that all the classes have been observed if
$$n> 1+(m+\frac12)\log(m)$$
The probability of observing exactly $m$ classes after the first $n$ observations is $$p(c)=\binom{c}{m}m^n/c^n$$
We maximize this probability by finding the $c$ for which $$\frac{p(c)}{p(c+1)} =\frac{c+1-m}{c+1}\cdot\frac{(c+1)^n}{c^n}=1$$
i.e.
$$\log\left(1-\frac{m}{c+1}\right)+n\log\left(1+\frac{1}{c}\right)=0$$
This occurs with $c=m$ iff
$$n = \frac{\log(m+1)}{\log(m+1)-\log(m)}$$
and approximating that gives the first inequality here.
To find the most likely $c$, we can solve the equation with logs numerically. It's hard to find a nice formula that's close to the root for a wide range of $m$ and $n$.
We can also use the formula for $p(c)/p(c+1)$ to test whether any other $c$ will be less likely by a factor of $\epsilon$.
Comment: @SagarM, I now think it's even worse than that, and needs an inclusion-exclusion principle: $\sum (-1)^{m-k} \binom{c}{k} k^n / c^n$, summing over $1 \le k \le m$.
Comment: thanks for the detailed reply and sorry for late response, can you please explain me how you evaluate the probability of observing exactly $m$ classes? In my understanding this seems to be an over estimate
Comment: For example, Let us have 4 classes A, B,C,D. Now, in three trials the probability of picking exactly three classes is 4*(1/4)^3, but in your case it would be 4*(3/4)^3.
Comment: I guess the right expression should be  ${c \choose m}(m/c)^n - {c \choose (m-1)}((m-1)/c)^n $


Does CGContextRotateCTM rotate on different rotational speeds on simulator and device?

Question: I have a project where it rotates 2 spindles 360 degrees both at different speeds over time. I have noticed that it runs well on simulator but when I test it on a device it is significantly slower. The timing taken to make the first 3 full rotations on the simulator and the device are:
On Simulator: 7.0, 7.2, 7.2
On Device: 19.3, 19.5, 19.7
Essentially the project works but I'd like to find out why there is such a big difference between device and simulator and I thought CGContextRotateCTM might be the source.
Answer: Sounds right.
Don't forget, when you run the simulator, you are actually compiling native code to run on your native x86 hardware. Assuming your Mac runs faster than the 800MHz ARM chip in the iPhone - no surprise it will run faster in the simulator.
If you need deterministic timing in your application, your going to need more work to achieve that. This is where people use things like the UIView animation timing, NSTimer calls, or cocos2d inter-frame timers to give deterministic time to their animation calls.
If you don't - when the next gen device comes out with a faster CPU - your app will again be messed up.
Remember when they used to have "Turbo" buttons on PCs to deal with this?! :-O
Comment: Thanks Brad, that has confirmed what I thought might be the problem as well. Do you have any particular examples that shows deterministic timing? I do remember my IBM 386 having the Turbo button hah!
Comment: You could implement this functionality like in cocos2d by calling "setNeedsDisplay" of your UIView at the end of the "drawRect" - while *keeping track* of the absolute time of the *last* drawRect - thus you would be able to see how fast you are updating - just like in Cocos2d. This would make it so the event loop would keep sending you redraw events - which you could act on - while taking the difference between the *current* and *last* drawRect times to determine how far your "animation" should "move".


Show: $\int f \, d\nu = \int f \, d\mu$ for continuous $f$ implies $\nu=\mu$

Question: Consider two $\sigma$-finite measures $\mu$ and $\nu$, both defined on $(\mathbb{R}^{k},\mathscr{B}(\mathbb{R}^{k}))$. Prove that if $\int{f}d\mu=\int{f}d \nu$ for all continuous functions $f:\mathbb{R}^{k}\rightarrow \mathbb{R}$, then $\mu=\nu$. Can someone give me hints?
Comment: For each open box $A$ consider a sequence of continuous functions $f_n$ that are equal to $1$ on a box $B_n\subset A$ and zero outside the box $A$, with $B_n$ growing to $A$ as $n$ growths. Use the equality of their integrals and take the limit.This gives you that the measures of $A$ are the same. *I changed the way the boxes change from my previous comment to be able to use monotone convergence, since dominated convergence is not guaranteed to be applicable*.
Comment: Once you know they are equal on open boxes, they are equal on open sets, since open sets are the union of all the open boxes they contain.This is again using dominated convergence theorem.
Comment: @ ABC: I might be wrong, but once you know that $\mu$ and $\nu$ are equal on open boxes, then you are done. This is because the collection of open boxes is a $\pi$-system which generates $\mathcal{B}(\mathbb{R}^n)$. Unless maybe I'm missing something?
Answer: Hints:

For a closed set $F \subseteq \mathbb{R}^k$, define $$f_n (x) := \max\{1-n d(x,F),0\}.$$ Show that $f_n \downarrow 1_F$ and that $f_n$ is continuous and bounded.
Conclude from the assumption and the monotone convergence theorem that $$\mu(F) = \nu(F) \qquad \text{for all closed sets $F$.}$$
Deduce that $\mu(A) = \nu(A)$ for any Borel set $A \in \mathcal{B}(\mathbb{R}^k)$.

Remark: Note that it suffices to assume $$\int f \, d\mu = \int f \, d\nu$$ for all bounded  continuous functions $f$.
Comment: @Ben Use that $\mu$ and $\nu$ are $\sigma$-finite. (Sorry, couldn't answer your comment earlier.)
Comment: I have difficulty to get step 3. Can you provide more details?
Comment: @Ben 1. Recall that the Borel-sigma-algebra is generated by the closed sets. 2. Do you know any uniqueness theorem for measures?
Comment: For 2. Do you mean if the measures are same for $\pi$ system, then they are same for the sigma-algebra generated by that $\pi$ system?
Comment: @Ben Yes, exactly.
Comment: I am not sure I am right or not: for $\mathscr{B}(\mathbb{R}^{k})$, what should I do? Just take $F\subseteq \mathbb{R}^{k}$? And do it again?
Comment: @Ben Use $\mathcal{B}(\mathbb{R}^k) = \sigma(F; F \subseteq \mathbb{R}^k \, \text{closed}\}$.
Comment: Do I need to use induction here?
Comment: @Ben Induction? No. Step 1+2 show that for $\mathcal{D} := \{F; F \subseteq \mathbb{R}^k \, \text{closed}\}$ we have $$\nu(F) = \mu(F)$$ for all $F \in \mathcal{D}$. Since $\mathcal{D}$ is a $\pi$-system which generates $\mathcal{B}(\mathbb{R}^k)$, the claim follows directly from the already-mentioned result on uniqueness of measures.
Comment: But in step 1, you choose $F\subseteq\mathbb{R}$ not $\mathbb{R}^{k}$?
Comment: @Ben Typo, sorry.
Comment: The theorem about equivalence of two measures needs $\mu$ and $\nu$ are sigma finite on $\mathscr{D}$. But we only have they are sigma finite on $(\mathbb{R}^{k},\mathscr{B}(\mathbb{R}^{k}))$.
Comment: @Ben So what? $\mu$ and $\nu$ *are* measures on $(\mathbb{R}^k,\mathcal{B}(\mathbb{R}^k))$.
Comment: In the proof of equivalence of two measures, we need "there exists $B_{i}\in\mathscr{D}$ with $\nu(B_i)=\mu(B_i)<\infty$ and $\mathbb{R}^{k}=\cup_{i=1}^{\infty}B_i$". You can see it #13.http://www.randomservices.org/random/prob/Existence.html


Unable to install/run SQL Server driver in WildFly 10

Question: I am running my application on a WildFly 10 server. I do not wish to place my connection details on my application src codes thus am trying to place it inside WildFly 10 server itself.
However I am facing issues.
Under [WILDFLY_HOME]\modules\system\layers\base\com\microsoft,
I created the following directory sqlserver\main and I place my JAR file and my XML file inside the main folder.
The JAR that I am using is sqljdbc.jar.
module.xml:
<?xml version="1.0" encoding="UTF-8"?>

<module xmlns="urn:jboss:module:1.3" name="com.microsoft.sqlserver">
  <resources>
    <resource-root path="sqljdbc.jar"/>
  </resources>
  <dependencies>
    <module name="javax.api"/>
    <module name="javax.transaction.api"/>
  </dependencies>
</module>

Next under [WILDFLY_HOME]\standalone\configuration, I modified the standalone.xml. Under the subsystem datasource section, I add the details for SQL Server.
standalone.xml:
<subsystem xmlns="urn:jboss:domain:datasources:4.0">
    <datasources>
        <datasource jndi-name="java:jboss/datasources/ExampleDS" pool-name="ExampleDS" enabled="true" use-java-context="true">
            <connection-url>jdbc:h2:mem:test;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE</connection-url>
            <driver>h2</driver>
            <security>
                <user-name>sa</user-name>
                <password>sa</password>
            </security>
        </datasource>
        <datasource jndi-name="java:/TestDS" pool-name="TestDS" enabled="true" use-java-context="true">
            <connection-url>jdbc:sqlserver://localhost\test:1433;databaseName=test</connection-url>
            <driver>mssql</driver>
            <security>
                <user-name>sa</user-name>
                <password>Password123!</password>
            </security>
            <pool>
                <min-pool-size>5</min-pool-size>
                <max-pool-size>50</max-pool-size>
                <prefill>false</prefill>
                <use-strict-min>false</use-strict-min>
                <flush-strategy>FailingConnectionOnly</flush-strategy>
            </pool>
            <validation>
                <valid-connection-checker class-name="org.jboss.jca.adapters.jdbc.extensions.mssql.MSSQLValidConnectionChecker"></valid-connection-checker>
            </validation>
        </datasource>
        <drivers>
            <driver name="h2" module="com.h2database.h2">
                <xa-datasource-class>org.h2.jdbcx.JdbcDataSource</xa-datasource-class>
            </driver>
            <driver name="mssql" module="com.microsoft.sqlserver">
                <xa-datasource-class>com.microsoft.sqlserver.jdbc.SQLServerDriver</xa-datasource-class>
            </driver>
        </drivers>
    </datasources>
</subsystem>

The error that I am facing now is as per below when I start running my WildFly:
15:19:51,098 ERROR [org.jboss.as.controller.management-operation] (Controller Boot Thread) WFLYCTL0013: Operation ("add") failed - address: ([
    ("subsystem" => "datasources"),
    ("data-source" => "TestDS")
]) - failure description: {
    "WFLYCTL0412: Required services that are not installed:" => [
        "jboss.jdbc-driver.mssql",
        "jboss.jdbc-driver.mssql"
    ],
    "WFLYCTL0180: Services with missing/unavailable dependencies" => [
        "org.wildfly.data-source.TestDS is missing [jboss.jdbc-driver.mssql]",
        "jboss.driver-demander.java:/TestDS is missing [jboss.jdbc-driver.mssql]",
        "org.wildfly.data-source.TestDS is missing [jboss.jdbc-driver.mssql]"
    ]
}
15:19:51,120 INFO  [org.jboss.as.controller] (Controller Boot Thread) WFLYCTL0183: Service status report
WFLYCTL0184:    New missing/unsatisfied dependencies:
      service jboss.jdbc-driver.mssql (missing) dependents: [service org.wildfly.data-source.TestDS, service jboss.driver-demander.java:/TestDS]

Comment: Do you have "Unable to find driver class name in ... jar " in log?
Comment: Apart from any other problem, the class name for XA seems to be different according to this source: https://learn.microsoft.com/en-us/sql/connect/jdbc/understanding-xa-transactions?view=sql-server-ver15
Answer: I managed to resolve the issue with this.
Since I place the file under this directory: [WILDFLY_HOME]\modules\system\layers\base\com\microsoft
Then the correct module location should be as per follow for normal datasource:
<driver name="mssql" module="system.layers.base.com.microsoft.sqlserver">
    <driver-class>com.microsoft.sqlserver.jdbc.SQLServerDriver</driver-class>
</driver>

or
if you are using xa datasource:
<driver name="mssql" module="com.microsoft.sqlserver">
    <xa-datasource-class>com.microsoft.sqlserver.jdbc.SQLServerXADataSource</xa-datasource-class>
</driver>

credits to @jklee
Answer: The driver is wrong, use
 <driver name="mssql" module="com.microsoft.sqlserver">
    <xa-datasource-class>com.microsoft.sqlserver.jdbc.SQLServerXADataSource</xa-datasource-class>
 </driver>

or
<driver name="mssql" module="com.microsoft.sqlserver">
    <driver-class>com.microsoft.sqlserver.jdbc.SQLServerDriver</driver-class>
</driver>

Answer: You can add sqlserver as global module as shown below
 <subsystem xmlns="urn:jboss:domain:ee:4.0">
            <global-modules>
                <module name="com.microsoft.sqlserver" slot="main"/>
                <module name="com.sql.mysql" slot="main"/>
            </global-modules>
.
.
</subsystem>


Can I Be Alerted On-Screen Each Time Someone Remote Desktop's Onto My Windows 2003 Server

Question: I work all day on a Windows Server 2003 machine and have noticed people "borrowing" my machine by using Remote Desktop to log in. This is pretty much "normal behaviour" at the company I work at, but I'd like to know when this is happening.
Is there any way I can be alerted each time someone remote desktop's onto my server? A simple "Bob has logged in" would be great - and I imagine there is a facility somewhere to enable this.
Answer: There are some good suggestions here - but I've taken the hard work out of it all by writing a remote access monitor tool. I've open sourced it in case anyone wants to use it / add to it.
https://github.com/Steve-Fenton/RemoteAccessMonitor
It examines the process list and alerts when a process is started by "another user" - so it works for all remote access types.

Ported from the code I originally shared on Codeplex (http://remoteaccessmonitor.codeplex.com/). Updated .NET version, but otherwise just what I wrote a long time ago!
Comment: @JoelDavis I've rescued the code and added a link to GitHub. Amazingly, it works.
Comment: I know this is 13 years old, but FYI, URL is currently broken
Answer: You can list the sessions on any terminal server using the built-in tool qwinsta and the correct credentials.
Script this to poll the status regularly and have it alert you with a popup or send you an IM or whatever you fancy and can script ^^
Add a login script to that machine either manually or by group policy that alerts you whenever someone logs on. It could be made to check if it's a remote session or not if that distinction is really needed.
Or use any tool available, I'd use whatever monitoring suite is in place, to monitor the event log which would also contain these logins - and have the suite alert you.
If it was a Windows 2008+ machine the event log itself could take action, if configured to, I think.
Answer: Why not create a logon script for that server to send you an alert using whatever method you like, such as email, net send, etc.?
Answer: Terminal Services Manager (located in Administrative Tools) lists the connections made to a terminal server (includes computers with remote desktop for administration enabled, which is your situation).
It's an mmc snap in, so you wouldn't normally have it running but it will show you the connections (who and when, etc). I suppose if you have a very large desktop you could have it running in an unused part of the screen.
Answer: On the server, add a .bat file into the All Users -> Start Menu -> Startup folder.
In it add the line:
NET SEND yourpcname %username% logged into the server
You'll need to enable messenger on both machines. Assuming you have XP because I'm not sure you can receive messenger messages in Vista or 7.


How can I do a custom form redirect on the user registration form?

Question: I added a custom submit function to the user registration form. I want to be able to redirect to the user profile edit. How can I get the uid of the record that is about to be created? global $user doesn't work:
function my_user_register_submit ($form, &$form_state) {
  global $user;
  $form_state['redirect'] = 'user/' . $user->uid . '/edit?registration=1&destination=blahblah';
}

Edit:
My use case is this: after registration I want to redirect the user to the "edit profile" page to complete the remaining profile fields. When they "skip" that or complete the form they go to their profile page.
However, when a ?destination parameter is passed into the register form I want to carry that value to the "edit profile" page and then direct the user to that destination page when they are done.
Comment: Just for reference you first gain access to the new users UID at hook_user_insert() (Stored in DB) and even earlier at hook_user_presave() (Just before storage in DB.)  See: http://api.drupal.org/api/drupal/modules--user--user.api.php/function/hook_user_insert/7  and note `$account->uid`;
Answer: Login Toboggan has an option for this whereby you can use %uid as an argument for the redirect URL.
Literally a text box where you'd type /user/!uid/edit
It's also got a whole host of awesome features that are worth checking out :)
Comment: thanks. In this case I would like to do it in code. Login Toboggan is a lot of module to solve one small problem ;-)
Comment: hmm...you won't be able to get the UID of the user that is about to eb created in the form_alter hook, as that user has not yet been created.

If you want it to happen every time a use logs in, you should just be able to utilise hook_user_login() with a drupal_goto()?
Comment: thanks. I want it to happen after they submit the register form.
Comment: At that point the user has not been created, so there would be no FOOLPROOF way to redirect them.  I guess the only way would be to run a query to pull out the most recent UID, and then add one to it.  That's really messy though and not really reliable =\

Is there a specific reason why it has to occur at this point?
Comment: I updated my question above.
Answer: Have a look at how login toboggan implements user_register_submit(): logintoboggan_user_register_submit(). It first save the $user in order to retrieve uid later.
function my_user_register_submit($form, &$form_state) {
  //Save $user
  $account = $form['#user'];
  $edit = array_intersect_key((array) $account, $form_state['values']);
  $account = user_save($account, $edit);
  $form_state['user'] = $account;
  $form_state['values']['uid'] = $account->uid;

  //Make the redirection
  $form_state['redirect'] = 'user/' . $account->uid . '/edit?registration=1&destination=blahblah';
}

Don't forget to check all the other pieces in the login toboggan's function to not forget any important part.
Answer: I think the better option you have is using the Rules module, rather than altering the form.
Comment: rules is great for that, except you have to "force" the redirect which means you'll use the ?destination value
Comment: > I think the better option you have is using the Rules module, rather
> than altering the form. And why ? This can be done in 5 lines of php, I can't see no reason why rules module should be a better solution than php to solve such a simple problem. Also do not forget than php can be versionned, reverted etc.. with svn and git and that this is easy to deploy. You'll have to use features or hook to export configuration with rules. Same thing for logintobiggan, that require probably strongarm.