Guitar nails and touch typing

Question: I've played so much guitar that I'm now not completely worthless at it. I understand that nails are important for good tone and I spend a lot of time manicuring them.
I  also touch-type a lot and the combination of nails and typing is frustrating. The reason is because when I type, my nails hit the keys at a 70-90 degree angle (the correct way to touch-type) causing my precious nails to bend. Almost the same shape as eagle beaks which causes the strings to get hooked underneath the nails.
Is there a solution to this dilemma? I can trim my nails very short but then I feel that I'm losing a lot of  the sound.
Comment: I had a similar dilemma that lead to me having to cut my guitar nails. Of course, my problem was that they were interfering with my other miscellaneous instruments which I have more experience with, but it was disappointing all the same. I hope you figure something out!
Comment: @GeneralNuisance yes I often have these problems too. Nails are great, but only for playing the guitar (and scratching of things ;). I struggle to play electric bass with nails, and even electric guitar.
Answer: A similar problem arises when combining guitar and piano. The only "solution" I've found is a sort of compromise: cut the nails a little shorter than your ideal for guitar.
This isn't necessarily a "compromise" from a somewhat broader perspective. Having a little less nail should make apoyando easier and more effective. In older (pre-Segovia) methods this is the norm. Very little if any nail is advised in Sor's method, for example.
I've also discovered that a shorter nail makes tremolo easier and more effective, too. Sensing the string with the fingertips by touch gives you that much more control of how you send it into vibration and stop it again.
This can change your tone as well, but probably for the better (IMO). More fingertip should give a sweeter, warmer tone, albeit with less brilliance and sting that the nail can give.
Answer: As someone who studied classical guitar for 2 years in university before changing majors to computer science, all I can say is you will get used to it. It will slow you down a bit overall, but not much once you get used to it.
Comment: Also, as luser droog points out, maybe try shorter nails. I was always a fan on very little nail (with the exception of the thumb). Maybe that's why I never had much issue adjusting.
Answer: I'm not a trained touch typist, but I type from a much closer angle; 45 degrees or even less (maybe because I've been playing guitar with nails almost as long as I've been typing!) It may not be correct by the book, but I average around 100wpm so it hasn't been an obstacle to typing fast and accurately. Unless there are RSI risks that I don't know about or something, you might want to think about simply changing your typing style.

Guitar nails and touch typing


Como pegar o estado do toggleButton Android?

Question: Como pegar o estado do ToggleButton se esta ligado ou desligado, olhei a documentação do Android só tem o método de mudar o estado, precisava pegar o estado do botão pra fazer a comparação.
Answer: o método é o isChecked(). Ele é herdado da classe CompoundButton.
Ex:
if(myToggleButton.isChecked())
  // Faça algo se estiver checado
else
  // Faça algo se não estiver checado


Android SAF, cannot copy file, FLAG_SUPPORTS_COPY not set

Question: I'm trying to copy a document with the SAF framework in Android by using DocumentsContract.copyDocument(ContentResolver, Uri, Uri) however this doesn't work, android returns error "Failed to copy document".
By narrowing the issue down, the FLAG_SUPPORTS_COPY is off on that document (according to DocumentsContract.Document#COLUMN_FLAGS)
(COLUMN_FLAGS value is 326 in decimal). So this explains the error.
However moving the document is allowed (flag FLAG_SUPPORTS_MOVE is on) and file is really moved when calling DocumentsContract.moveDocument(ContentResolver, Uri, Uri, Uri)
Access to the document tree (both the root of the drive, and DCIM folder) have been granted through Intent.ACTION_OPEN_DOCUMENT_TREE
Why is the FLAG_SUPPORTS_COPY set to false for the Document ? Am I missing something ?
Note: I believe I fullfill the requirements from this post https://stackoverflow.com/a/58147682/15401262
Thank you
Code (java)
// docFilesToProcess if of type "DocumentFile[]" and contains "regular files, like images" (not directories).
// Create destination dir
Uri destUri = DocumentsContract.createDocument(this.getContentResolver(), docFilesToProcess[i].getParentFile().getUri(), DocumentsContract.Document.MIME_TYPE_DIR, "destDir");
Log.i("M", "destUri: "+ destUri.toString());
// Create document
Uri docToMove = DocumentsContract.createDocument(this.getContentResolver(), docFilesToProcess[i].getParentFile().getUri(), "text/plain", "text");
Log.i("M", "docToMove: "+ docToMove.toString());
// copy document
DocumentsContract.copyDocument(this.getContentResolver(), docToMove, destUri);

Output
I/M: destUri: content://com.android.externalstorage.documents/tree/primary%3ADCIM/document/primary%3ADCIM%2FdestDir
I/M: docToMove: content://com.android.externalstorage.documents/tree/primary%3ADCIM/document/primary%3ADCIM%2Ftext.txt
W/DocumentsContract: Failed to copy document
    java.lang.UnsupportedOperationException: Copy not supported
        at android.database.DatabaseUtils.readExceptionFromParcel(DatabaseUtils.java:172)
        at android.database.DatabaseUtils.readExceptionFromParcel(DatabaseUtils.java:140)
        at android.content.ContentProviderProxy.call(ContentProviderNative.java:658)
        at android.content.ContentResolver.call(ContentResolver.java:2042)
        at android.provider.DocumentsContract.copyDocument(DocumentsContract.java:1442)
        at com.example.exifthumbnailadder.MainActivity.addThumbs(MainActivity.java:1036)
        at java.lang.reflect.Method.invoke(Native Method)

Persistant permission request
    Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT_TREE);
    intent.addFlags(
        Intent.FLAG_GRANT_READ_URI_PERMISSION
            | Intent.FLAG_GRANT_WRITE_URI_PERMISSION
            | Intent.FLAG_GRANT_PERSISTABLE_URI_PERMISSION
            | Intent.FLAG_GRANT_PREFIX_URI_PERMISSION);

Comment: `java.lang.UnsupportedOperationException: Copy not supported` I never saw something different from this. Its not implemente yet i think..
Comment: `Persistant permission request` No, no. Remove those flags there. They make no sense at all. You cannot grand anything there. You should be glad that in onActivityResult you are granted access to the obtained ur. In onActivity result you should take persistable uri permissions.
Comment: Thanks for looking at this. I'm not sure what you mean but I don't do these permission requests at the time I call `copyDocument`. I did in the onActivityResult (with the call to takePersistableUriPermission and others) at the time I picked the dir in the UI.

For now a `getPersistedUriPermissions()` before the copyDocuments block above return `UriPermission {uri=content://com.android.externalstorage.documents/tree/primary%3ADCIM, modeFlags=3,...`. So I guess this is ok.
Comment: You should have persisted permission for both directory and file at the time of copy. And...remove those flags..
Comment: Ok, I removed the flags (had no noticable adverse effect). Then, just before the copyDocument, I added, for both URIs (destUri & docToMove), the `grantUriPermission(getPackageName(), theURI, Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION | Intent.FLAG_GRANT_PREFIX_URI_PERMISSION | Intent.FLAG_GRANT_PERSISTABLE_URI_PERMISSION);` & `getContentResolver().takePersistableUriPermission(destUri, Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION );`. They are in the persistPerms. I still have the same error and FLAG_SUPPORTS_COPY is off ...
Comment: `Then, just before the copyDocument, I added, for both URIs` Both actions make no sense. For the first: you cannot grand anything and i said that before. For the second: what shall i say. Useless. Persistable uri permissions you should take in onActivityResult as that is the place where permissions are offered to you.
Comment: I'm sorry but I don't understand what you mean. You say I should have persistent permission, so to be sure I have them I do the call again (I already have a grantUri... & takePersistable... in the onActivityResult). I checked with getPersistedUriPermissions() if both directory & file are in the list of persistedUriPerm before I call copyDocument, and they are. Isn't this what you meant ? BTW is that permission problem the cause of the copy not working (while moveDocument works perfectly). Thanks again.
Comment: `java.lang.UnsupportedOperationException: Copy not supported` That is all.
Comment: so it means android doesn't support copying on local storage with SAF ? :/
Comment: No. It means that that function cannot be used. Of course you can copy files with SAF. Or with DocumentFile or with DocumentsContract.
Comment: Ok. I don't see a copy method in DocumentFile, How do you suggest to do it ?
Comment: You have to obtain an uri for the destination file using for instance  DocumentsContract.createFile. Further you have an uri for the source file. Using content resolver  open an InputStream an OutputStream and read/write all bytes. Using DocumentFile about the same.
Comment: Ok I will try that. But I guess document attributes (creationTime, modificationTime) will be lost. Why the flag `FLAG_SUPPORTS_COPY` is set to false is a mistery. Do you have any explanation for this ? BTW, if we transpose the case to a media file, is there an equivalent to copyDocument for the mediastore that would work ? or is it also necessary to do it with InputStream and OutputStream.
Comment: For the MediaStore i use .insert() to obtain an uri where to write the new file to. About the same then. For the rest i know nothing..
Comment: It works fine with InputStream and OutputStream. Thank you.
Comment: @usilo, I was also fighting with this problem and yet do not able to apply DocumentsContract.copyDocument. As I wrote before, moving, creating, deleting are working fine, but somehow there is an exception for copying. As far as I understood from your messaging here, you are also giving up the idea of using of DocumentsContract.copyDocument.
The interesting thing is that unlike of me (I'm kind a beginner in Android) I noticed that even skilled guys here encounter troubles with "copyDocument - copy not supported" issue.
Comment: There is a ticket: https://issuetracker.google.com/issues/182942755
Answer: In general, you cannot ever rely on any SAF provider to implement any optional feature. You should check whether the feature is supported, and you should have a viable fallback plan for when it is not.
ContentResolver cr = getContentResolver();
if((flags & FLAG_SUPPORTS_MOVE) == FLAG_SUPPORTS_MOVE)
    Uri newDoc = DocumentsContract.copyDocument(cr, docToCopy, destDir);
else {
    Uri newDoc = DocumentsContract.createDocument(cr, destDir, mimeType, name);
    manuallyCopyBytes(docToCopy, newDoc);
}

It's important to give the provider a chance to do it, because something like Google Drive may be able to perform the copy separately on the device and on the server, instead of copying it on the device and then having to upload the whole thing to the server again.


Uploading large files to Google Storage GCE from a Kubernetes pod

Question: We get this error when uploading a large file (more than 10Mb but less than 100Mb):
403 POST https://www.googleapis.com/upload/storage/v1/b/dm-scrapes/o?uploadType=resumable: ('Response headers must contain header', 'location')

Or this error when the file is more than 5Mb
403 POST https://www.googleapis.com/upload/storage/v1/b/dm-scrapes/o?uploadType=multipart: ('Request failed with status code', 403, 'Expected one of', <HTTPStatus.OK: 200>)

It seems that this API is looking at the file size and trying to upload it via multi part or resumable method. I can't imagine that is something that as a caller of this API I should be concerned with. Is the problem somehow related to permissions? Does the bucket need special permission do it can accept multipart or resumable upload.
from google.cloud import storage

try:
    client = storage.Client()
    bucket = client.get_bucket('my-bucket')
    blob = bucket.blob('blob-name')
    blob.upload_from_filename(zip_path, content_type='application/gzip')

except Exception as e:
    print(f'Error in uploading {zip_path}')
    print(e)

We run this inside a Kubernetes pod so the permissions get picked up by storage.Client() call automatically.
We already tried these:

Can't upload with gsutil because the container is Python 3 and gsutil does not run in python 3.
Tried this example:  but runs into the same error:  ('Response headers must contain header', 'location')
There is also this library. But it is basically alpha quality with little activity and no commits for a year.
Upgraded to google-cloud-storage==1.13.0

Thanks in advance
Comment: Can you upload large files from outside the pod?
Comment: yes. it turns out that credentials picked up automatically from the kubernetes service account was problematic. Will have to look at what that account was and how was it that it was working at some point and then stopped working. creating a new service account and loading the credentials explicitly solved the problem.
Answer: The problem was indeed the credentials. Somehow the error message was very miss-leading. When we loaded the credentials explicitly the problem went away.
 # Explicitly use service account credentials by specifying the private key file.
 storage_client = storage.Client.from_service_account_json(
        'service_account.json')

Answer: I found my node pools had been spec'd with
    oauthScopes:
    - https://www.googleapis.com/auth/devstorage.read_only

and changing it to
    oauthScopes:
    - https://www.googleapis.com/auth/devstorage.full_control

fixed the error. As described in this issue the problem is an uninformative error message.


how to create dictionary in with multiple values?

Question: I want to create a dictionary in C# with one key and multiple keys associated with the key.I also want to retrieve the values based on the key.I found on internet people suggested to use a tuple but couldn't find a proper example. How to use it and retrieve the data?
Goal:  I want to parse a JSON response and store response in key pair form.
Comment: JSON.Net will take care of parsing JSON. Unless it is homework please don't invent square wheel.
Comment: [Google results for "Tuple example"](https://www.google.co.uk/search?q=tuple+example&oq=tuple+example&aqs=chrome..69i57j0l5.2073j0j7&sourceid=chrome&es_sm=93&ie=UTF-8) - are you really after a dictionary dictionary?
Comment: No actually I want to parse a json response and store response in key pair form.I dont know what data stucture will be good for it.
Comment: I've removed thank you notes from you post and inlined your JSON comment. Feel free to update your post if my edit changed meaning (I hope it did not).
Comment: Thanks for that,actually i know how to parse the json response but ya I am not clear on how to store in key with multiple values form.
Answer: When I have needed to do something like this, I usually just create a custom class that can be used as the value. For example, if I wanted to store a dictionary with a digit as the key and a name, address, and phone number as the value, I'd create a Person class to contain the name, address, and phone number.
Dictionary<int, Person> = new Dictionary<int, Person>();

Alternately you can just make the value an array or List.
Answer: What your asking for would look something like this
Dictionary<int, Tuple<int, string>>

But what you should do is create an class to replace that Tuple
public class Person
{
  public int PersonId {get;set;}
  public string FirstName {get;set;}
}

Then you can define your Dictionary like this
Dictionary<int, Person> bar = new Dictionary<int, Person>();

Then you could retrieve values like this
var firstName = bar[1].FirstName  //1 is the key of the dictionary item

Comment: checkout [dotnetfiddle](http://dotnetfiddle.net/45af0g) which follows this approach.
Comment: can you tell me how to retrieve the data?
Comment: updated to show retrieving a value from the dictionary
Answer: I dont know if this is what you want:
Dictionary<int, KeyValuePair<int, string>> = new Dictionary<int, KeyValuePair<int, string>>();

But I think it fit your need.


Class design - create a object from String data?

Question: I am working on simple application of Universal Turing Machine. I have a data to create machine from, my questions is not about UTM I would like to illustrate it only on this app. I need to create an object from String data, e.g. this method create one transition function of my UTM:
public static Transition createFromData(String data) {

    Transition trans = new Transition();
    String[] dataSplitted = data.split("1");
    trans.setInputState(new State(dataSplitted[0]));
    trans.setInputSymbol(dataSplitted[1]);
    trans.setNewState(new State(dataSplitted[2]));
    trans.setNewSymbol(dataSplitted[3]);
    trans.setMovement(Movement.getByCode(dataSplitted[4]));

    return trans;

}

Is it good idea (from class design perspective) to have such methods in Transition class or should I separate them to another / tool classes? What is bets practice for this issue?
Comment: This is a perfectly valid design pattern, called the "static factory pattern". I would recommend using some sort of "parser" interface and injecting an implementation dependant on the type of data - it's not good to couple the class to it's representation in the data. Having said all that this question is not suitable for this forum - it is a) opinion based and b) asking for code review.
Answer: Using tools/utils classes always remind me of structured programming ;) but would help if you just had a constructor on the Transition class the would receive the raw data and create a new transition object with that. Since you will be creating a new transition each time you find some raw data the best fit is in the constructor (or maybe in a factory method, but that is another discussion)
Comment: *(or maybe in a factory method, but that is another discussion)*: it's not another discussion. The OP specifically asked if it would be a good idea to have this method in the Transition class itself, making it a factory method.
Comment: I prefer the OPs static factory pattern to your suggestion of sticking it all in a constructor. As @JBNizet points out that _is_ the discussion here.
Answer: what about having this method in a another class for eg: RawData, which will have static factory methods for creating different objects from data.
In your case you can have one method will will return Transition object and then you can have multiple methods and each return a different object depending upon how data is organized / represented in that object.


Monitor Apache Error Logs for Specific Strings

Question: Whats the recommended solution to comb apache's previous day's /var/log/httpd/error_log looking for lines that contain a certain string and email when such strings are detected?
It could be run hourly via cron and the strings in my case would be "sigkill" or "reached maxclients".
Nagios, Cacti, etc would be an overkill. I need something simple.
Thanks
Answer: For running periodicaly via cron, you could Us a cache to store last position in logfile than grep on newest lines:
<code>#!/bin/bash

logfile=/var/log/apache2/error.log
searchstr='sigkill\|reached maxclients'
cachefile='/var/cache/lastpos-apache2-scan4maxclntOrSigKill'

[ -f $cachefile ] && lastpos=$(<$cachefile)
[ "$lastpos" ] || lastpos=0

newpos=$(stat -c %s $logfile)

[ $lastpos -gt $newpos ] && lastpos=0

tail -c +$lastpos $logfile | grep "$searchstr"

echo $newpos >$cachefile
</code>
Comment: This way I can run it even hourly and it will only send me the new entries, right?
Comment: (added a line for "touch /var/cache/lastpos-apache2-scan4maxclntOrSigKill" to avoid errors on the first run)
Comment: it stores $lastpos in the cachefile but it outputs nothing (even with the correct value in logfile). manually doing tail -c +40667 /var/log/httpd/error_log | grep "sigkill|reached maxclients" also brings nothing.
Comment: maybe did you need case independant: `grep -i "...` ?
Comment: sorry, I forget the ``\``  before `|` in the grep command
Comment: At all, you could try the perl version, lighter than bash.
Comment: thanks. but what's the proper grep syntax?
Answer: But if really you prefer perl, it's a little lighter than bash, but...
<code>#!/usr/bin/perl -w

use strict;

my $cachefile="/var/cache/lastpos-apache2-scan4maxclntOrSigKill";
my $logfile="/var/log/apache2/error.log";
my $searchstr="sigkill|reached maxclients";

my $lastpos=0;
if (-f $cachefile) {
    open FH,"<".$cachefile;
    $lastpos=<FH>;
    close FH;
};

my $newpos=(stat $logfile)[7];

open FH,"<".$logfile;
seek FH,$lastpos,0;
while (<FH>) {
    print if /$searchstr/i;
};
close FH;

open FH,">".$cachefile;
print FH $newpos;
close FH;
</code>
Comment: still, no output.
Comment: with `i` modifier for case independant?
Comment: don't forget to clean cache: `rm /var/cache/lastpos-apache2-scan4maxclntOrSigKill`
Comment: yes, i delete the cache every time before i run it.
Comment: Did you add the `i` modifier after `if /$searchstr/i;`, did you need case independant, what's the look of your searched lines exactly?
Comment: i do need case independant, i dont want to bother entering proper casing in the strings. thanks
Answer: There's always Perl, e.g.:
<code>perl -ne 'print if m/sigkill|reached maxclients/i' /var/log/apache2/error_log
</code>
Comment: how do I make that case insensitive? mi/ ?
Comment: @Gaia `m//i`, see updated answer.
Comment: ahhh perl is like magic... one more thing. each line begins with the date in format "[Wed Oct 24 05:15:52 2012]". how do i pick only the prior day's (i will set to run it past midnight) or the last 24 hours, whichever is simpler? Logs are rotated weekly.
Comment: See the answers to [this question](http://stackoverflow.com/q/3506475/1630171).
Comment: Thanks, but I think i am better off with caching $lastpos, as suggested below. Unless awk or sed has a one-liner that can do the above and only get the last X hrs...
Answer: Monit is a very lightweight system monitoring tool and will watch log files and send alerts when certain strings appear.  See the documentation at http://mmonit.com/monit/documentation/monit.html#file_content_testing for usage.
Comment: thanks, but a 15 line script and a cron job did it.


Maximum of dependent binomial random variables.

Question: Suppose that I have 1 million balls ( $10^6$ ) and 1000 buckets. For each ball, I choose a bucket for it with equal probability. The task is to estimate the probability that some bucket contains more than 1250 balls, from the top.
If I define random variable $X_i$ as the number of balls in bucket $i$, then I have no idea how to estimate the maximal value of $X_i$ for $i$ from 1 to 1000 (or at least these which have more than 1250 balls in it), given just some information on just one of them.
Any hints on directions, or how to pick adequate random variables?
Comment: https://math.stackexchange.com/questions/3406603/probability-of-more-than-k-balls-in-any-m-buckets-given-n-total-balls?rq=1
Comment: @d.k.o. this is certainly on topic, albeit not functional, as this is a problem to be solved on paper, and with 1000 buckets and 1000000 balls the inclusion-exclusion principle is cumbersome.
Comment: Then use an approximation (I gave one below).
Comment: Yes, this is helpful, but I need to read the paper you linked in detail. Thanks.
Answer: The required probability,
$$
p\equiv\mathsf{P}\!\left(\max_{1\le i\le 1000}X_i>1250\right),
$$
is hard to compute directly. A possible approximation is given in this paper. Specifically,
$$
\frac{\max_{1\le i\le 1000}X_i-1111}{\sqrt{500/(3\ln(10))}}+0.5\ln(4\pi)\overset{d}{\approx}\text{Gumbel}(0,0).
$$
Therefore, $p\approx e^{-e^{-17.6}}\approx 2.26\cdot10^{-8}$.


Finding windows of high-correlation across coordinates in R

Question: I've got a dataset that looks like this:
id      start   end     score1  score2
[...]
LmjF.31 280000  290000  .       .
LmjF.31 290000  300000  .       2686
LmjF.31 300000  310000  .       .
LmjF.31 310000  320000  .       74
LmjF.31 320000  330000  .       1897
LmjF.31 330000  340000  .       4116
LmjF.31 340000  350000  705     3156
LmjF.31 350000  360000  663     4145
LmjF.31 360000  370000  170     4864
[...]
LmjF.34 1140000 1150000 2284    2751
LmjF.34 1150000 1160000 .       .
LmjF.34 1160000 1170000 .       .
LmjF.34 1170000 1180000 572     .
[...]

(dot=. means score is 0)
I would like to rank the regions for each id where the correlation between score1 and score2 is highest . The second and third columns are start and end positions for sliding windows that at their minimum can be of size 1, but with smaller windows, fewer of them have non-zero on both scores, so I am already using bigger windows. Since these windows in different chromosomes for two different species, correlations in score1 and score2 that don't overlap but that are close to each other would still be relevant, but if they partially or fully overlap, then even better. That's why the sliding window size is relative, since I would like to use a method that takes into account cases like the ones for LmjF.31 start=340000 to end=370000, where there is three consecutive rows with a score bigger than 0. Any suggestions?
Comment: To get a good answer, please provide specific descriptions of what you mean by "window" and by "correlation."  You should also specify the sense in which "takes into account" is some modification of the usual definitions of correlation ([Pearson](http://en.wikipedia.org/wiki/Pearson_product-moment_correlation_coefficient) and [Spearman](http://en.wikipedia.org/wiki/Spearman%27s_rank_correlation_coefficient), among others).
Comment: Given your comment to Gong-Yi Liao that the combination of id, start and end is the "window", the question does not make sense as written. Do you perhaps mean you want to rank the data according to how *close* score1 and score2 are in each row?  If so it is a pretty straightforward problem - just create a new variable that measures "closeness" (however you want to - proportional, absolute, or squared difference being the obvious choices) and rank on that basis.  But I suspect you want something else - you will probably need to edit the question rather thoroughly I'm afraid.
Comment: I edited my question, maybe now it's a bit clearer that this comes from already applying a sliding window on the raw data.
Comment: sorry, still don't understand - now you've introduced a new word "regions", what does that mean?  And I still don't understand what the correlation you are looking at is, nor what is meant by "taking into account" the situation near the end of your question.  Maybe have another go, giving an example of one subset of the data where column of score1 is correlated with an equal length column of score2.
Answer: If "id" is your window id, than you may do :
rhos = NULL
for w in unique(id)
    rhos = c(rhos, cor(data[data$id==w,c("score1", "score2")])[1,2])

rank = unique(id)[order(data)]

wish my assumption fits your data.
Comment: Thus, each window has only one observation of score1 and score2. Therefore , a problem arises: how can one compute sample correlation with only one observation ?
Comment: The window id is the combination of the first three columns: `id`, `start` and `end`.


Proof in ZF set theory involving surjection and cardinality

Question: Let $f$ $:A\rightarrow B$ be a surjection.
Show that $|B|$ < $2^{|A|}$.
Please can anyone lend a hand here?
Answer: It is easy to see without choice that if there is a surjection from $A$ onto $B$, then there is an injection from ${\mathcal P}(B)$ into ${\mathcal P}(A)$, and the result follows from Cantor's theorem that $B<{\mathcal P}(B)$.
To define the injection, suppose $g:A\to B$ is onto. Define $f:{\mathcal P}(B)\to{\mathcal P}(A)$ by $$f(C)=\{a\in A\mid g(a)\in C\}$$ for $C\subseteq B$. It is easy to check that $f$ is injective, using that $g$ is onto: If $D\ne C$ are subsets of $B$ and $b\in D\setminus C$, then any $a\in A$ such that $g(a)=b$ is in $f(D)\setminus f(C)$.
Comment: So $f(C) = g^{-1}[C]$, essentially.
Comment: Precisely. ${}$
Answer: Remember that "$\vert X\vert\le\vert Y\vert$" means "there is an injection from $X$ to $Y$." There are two pieces to this question:

Showing that $B$ injects into $2^{A}$.
Showing that $2^A$ does not inject into $B$.

For the first point, note that if $A$ surjects onto $B$, then we can "reverse" that to get an injection from $B$ to $A$ . . . using the axiom of choice. In ZF alone, that's not possible. And the problem is that a surjection $s: A\rightarrow B$ might be very non-injective, so it might not have a left inverse. So the problem is that $s$ might associate lots of elements of $A$ to a single element of $B$; do you seen, based on that, a way to associate a set of elements of $A$ to a single element of $B$? Do you see why that map is injective?
For the second point, if $2^A$ injects into $B$, then $B$ surjects onto $2^A$ (do you see why? this is provable in ZF, it's the converse that needs choice). Now, do you see why this is a problem? HINT: by assumption, $A$ surjects onto $B$ . . .


The shape of elements of schemes

Question: In the book Geometry of Schemes, written by David Eisenbud & Joe Harris, at the start of chapter one in the section Schemes as Sets, the authors introduce elements of $R$ as functions. I can't understand their meanings there! If anyone knows how these functions are defined, please describe what functions that correspond to elements of $R$ are.
Answer: If $R$ is a commutative ring one associates to it a set, the spectrum $Spec(R)$ of that ring.
The elements of that spectrum are the prime ideals $\mathfrak p\subset R$.
Now, given an element $r\in R$ one associates to it a function $\hat r $  defined on $Spec(R)$ (the Gel'fand transform of $r$), whose value at $\mathfrak p\subset R$ is the residue class $\hat r(\mathfrak p)=\text {class} (r)\in R/\mathfrak p\subset \kappa (\mathfrak p) =Frac(R/\mathfrak p)$.
This is an amazing  construction.
 Many  rings are naturally given as   functions  on some structured set: think of continuous functions on a topological space or smooth functions on a manifold or holomorphic finctions on a holomorphic variety or...
The fantastic idea, due to Gel'fand for Banach algebras and to Grothendieck for general rings, is that you can essentially force every ring to be  a ring of functions on some set, namely $Spec(R)$, extracted from $R$ itself.
Of course there are technical problems: the association  $r\mapsto \hat r$ is not always injective , so that the ring $R$ is not always exactly a ring of functions,  but  this idea of trying   to consider any ring as a ring of functions is really extraordinary and extremely useful.
Comment: Also, $\hat{r}$ may not be a function since the fields of fractions $\operatorname{Frac}(R/\mathfrak{p})$ need not be the same at different points $\mathfrak{p}\in\operatorname{Spec}(R)$.
Comment: Dear @Javier, $\hat r$ is *always* a function. But its codomain is admittedly  a bit weird: it is the union $\cup \mathfrak p \text {Frac} (R/\mathfrak p)$ of all the residual fields of the primes making up $Spec(R)$.
Comment: yes indeed, any one-image assignment to each point is a function by considering the union of the possible codomains. I should have said something like "traditional function", as I was thinking in the motivation where $R$ is the coordinate ring of an algebraic variety over a field $k$, so $r$ takes values in $k$ at any closed point. You are right that the striking contribution is considering such "general functions" beyond those taking value in something like a number field, so that $\hat r$ contains much more information, i.e. all its restrictions to any subscheme.
Comment: I understand what you say in your last paragraph as: the "general function" $\hat r$ is not necesssarily determined by the values of it at every point (closed or generic). A silly example: for $k$ a field, then $R=k[x]/(x^2)$ has $\operatorname{Spec}(R)=(x)=:\mathfrak{p}_x$, thus $x\in R$ and although $x\neq 0$, it has $\hat x (\mathfrak{p}_x)=0$; in general there can be cases where $\hat r$ does not determine $r$ by its values at every point, so calling $r$ a function because of $\hat r$ must be done with care. (That is why in Eisenbud-Harris' book they emphasize quotation marks "function").
Answer: In the book Geometry of Schemes, written by David Eisenbud and Joe Harris, at the start of chapter one in the section Schemes as Sets, the authors introduce elements of R  as functions. we will describe what functions that correspond to elements of R  are.
Let us recall some Theorems from fundamental Algebras
Theorem: Assume $R$ is a commutative ring with an identity element, then "$P$ is a prime ideal of $R$ $\Longleftrightarrow$ $\frac{R}{P}$ be an integral domain".("Algebra" written by Dr. Mohammadi Hasan Abadi)
having identity element was needed for $\frac{R}{P}$ will be an integral domain, because we defined a ring $R$ is an integral domain if it will be commutative with identity element and has no non-zero zero divisor. But if you look at the proof of this theorem it is not needed to implies from $P$ is a prime ideal of $R$ that $\frac{R}{P}$ has no non-zero zero divisor and its convert.
Theorem: Assume $R$ is a commutative ring with at least two elements and has no non-zero zero divisors. Then the relation $\thicksim$ on $\{(a,b)\in R\times R\:|\:b\neq 0\}$ with definition "$(a,b)\thicksim(c,d)\Longleftrightarrow ad=bc$" is an equivalence relation on the set of quotients of $R$.("Algebra" written by Dr. Mohammadi Hasan Abadi, page 299)
Theorem: The set of equivalence classes introduced in previous theorem with operations $+$ and $\cdot$ that are defined below is a field.("Algebra" written by Dr. Mohammadi Hasan Abadi, page 301)
$\{        +:F\times F\longrightarrow F \\
        (a,b)+(c,d)=(ad+bc,bd)$
$ \{\begin{array}{c}
        \cdot:F\times F\longrightarrow F \\
        (a,b)\cdot(c,d)=(ac,bd)
      \end{array}$
Theorem: Assume $R$ is a commutative ring with at least two elements and has no non-zero zero divisor and let $F$ be its quotients field. Then R is embeddable in $F$.("Algebra" written by Dr. Mohammadi Hasan Abadi, page 302)
Note that the identity of quotient field is equivalence class contains $(a,a)$ that $a\in R-\{0\}$ is arbitrary. And note that, embedding function that is mentioned is
$\{\begin{array}{c}
         f:R\longrightarrow F \\
         f(a)=[(ab,b)]_{\thicksim}\quad ;b\in R-\{0\}
       \end{array}$
Be care that by definition of $\thicksim$, $[(ab,b)]_{\thicksim}$ is independent from $b$ and only depends on $a$.
Now if $R$ be commutative ring for every prime ideal of $R$ like $P$ we have $\frac{R}{P}$ is commutative ring with no non-zero zero divisors, so by mentioned theorems, $F_{P}$ the set of equivalence classes of relation $\thicksim$ on $\{(a+P,b+P)\in \frac{R}{P}\times \frac{R}{P}\:|\:b+P\neq P\}$ with mentioned operators $+$ and $\cdot$ will be a field that $\frac{R}{P}$ will be embedded in it with following function.
$\{\begin{array}{c}
         f_{P}:\frac{R}{P}\longrightarrow F_{P} \\
         f_{P}(r+P)=\frac{(r+P)(s+P)}{s+P}\quad ;s+P\in \frac{R}{P}-\{P\}
       \end{array}$
Now the main concept of those authors will be shined as below:
For every $r\in R$ define;
$\{\begin{array}{c}
         f_{r}:Spec(R)\longrightarrow \bigcup_{P\in Spec(R)}F_{P} \\
         f_{r}(P)=\big(f_{P}o\pi_{P}\big)(r)=\frac{(r+P)(s+P)}{s+P}\quad ; s\in P
       \end{array}$
$\{\begin{array}{c}
         \pi_{P}:R\longrightarrow \frac{R}{P} \\
         \pi_{P}(r)=r+P
       \end{array}$
For every one of elements of $R$ like $r$, $f_{r}$ is a function because if $P_{1},P_{2}\in Spec(R)$ and $P_{1}=P_{2}$ then it is like you are denoting a prime ideal of $R$ with two nomads, so $\frac{R}{P_{1}}=\frac{R}{P_{2}}$ and $F_{P_{1}}=F_{P_{2}}$ and for every $s\notin P_{1}$ we have $s\notin P_{2}$ and conversely and at the end $\frac{(r+P_{1})(s+P_{1})}{s+P_{1}}=\frac{(r+P_{2})(s+P_{2})}{s+P_{2}}$ that means $f_{r}(P_{1})=f_{r}(P_{2})$.
Comment: Some notations are meaningless here for others so, it is better to avoid them. +1 :)

The shape of elements of schemes


Quando usar variáveis de instância vs parâmetros?

Question: Assumindo que uma classe A utilize uma classe B (diretamente ou através de uma interface C para desacoplar A de C).
Deixando claro que A e B são partes independentes, i.e., a relação entre as duas classes não é de composição ou uma agregação óbvia, porém existe uma associação "fraca" em que A usa B (nesse caso, através do contrato estabelecido por C).
Considere os dois exemplos (em Java):
Exemplo 1 - C como Variável de instância:
public class A {
    private C c;

    // Não estou discutindo injeção através de construtores vs. getters and setters
    // Apenas assuma que `c` foi inicializado de alguma maneira
    public A(C c) {
        this.c = c;
    }

    public metodo1() {
       // faz algo com c
    }

    public metodo2() {
       // faz algo com c
    }

    public metodo3() {
      // não faz nada com c
    }
}

Exemplo 2 - C como parâmetro:
public class A {

    public metodo1(C c) {
       // faz algo com c
    }

    public metodo2(C c) {
       // faz algo com c
    }

    public metodo3() {
       // não faz nada com c
    }
}

A minha pergunta é em que situação devo fazer com que A possua uma variável de instância do tipo C vs. quando devo passar uma instância do tipo C como parâmetro para os métodos de A?
Em outras palavras: Em que situações a API exposta no Exemplo 1 seria "melhor" do que a API exposta no Exemplo 2 e vice-versa? Quais seriam as justificativas para apoiar essa decisão?
Após muitos anos como desenvolvedor eu ainda tomo essa decisão na base do feeling. Também reparei que com o passar do tempo a construção do exemplo 2 (que era rara, e prontamente refatorada para 1 no meu código) começou a se tornar mais aceitável e até preferível em boa parte das situações. Porém, até hoje tenho dificuldade em formalizar os motivos que me levam a escolher uma construção ou outra.
Comment: Olá @mgibsonbr, sugestões para melhor a pergunta são bem vindas. Porém eu infelizmente não estou trabalhando em cima de um exemplo "concreto de código". O problema é que, ao meu ver, existe uma diferença tênue em certas situações. Uma lacuna conceitual e espaço para opinião na hora de decidir entre associações vs passagem de parâmetros repetidamente na API. Para mim uma associação é mais forte e "continua", enquanto a passagem de parâmetros é mais fraca e "discreta" (não sei se fez sentido).
Comment: Bom, minha principal sugestão é tornar mais claro sobre o que a pergunta **não é**. Por exemplo, quando escreve "Assumindo que uma classe `A` utilize uma classe `B`" fica ambíguo se existe ou não relação entre ambas [fora do contexto do método]. Se para fins dessa pergunta assume-se que **não**, que `A` e `B` não se relacionam conceitualmente, seria interessante ter isso explícito na pergunta. Da mesma forma, sua principal motivação pelo que entendi é a criação de uma boa API, e não a modelagem de entidades em classes. Visto por esse foco, pode-se dar respostas mais direcionadas.
Comment: Parte do programa mais perguntas para o Beta
Comment: Pessoalmente, considero essa pergunta meio "ampla demais" meio "não está claro o que está perguntando". Antes de ler sua própria resposta, achava que era uma pergunta conceitual (e formulei a primeira parte da resposta); depois de lê-la, vi que se tratava mais de aspectos práticos (i.e. a "relação natural entre `A` e `B` está clara, mas implementá-la dessa forma traz consequencia negativas") - e formulei a segunda. Sugiro que, se possível, edite a pergunta para torná-la mais específica.
Comment: Bem melhor agora! +1, e vou editar minha resposta para torná-la mais concisa.
Answer: De fato, nenhuma das opções é a ideal. Vou discorrer brevemente sobre cada uma delas e depois propor uma alternativa.
Opção 1: guardar estado em A
Essa solução, embora deselegante, pode ser viável ao menos em casos onde não há paralelismo (i.e. somente um algoritmo executando em um único thread terá acesso a A). Nesse caso, o uso de uma variável representando o "C corrente" simplifica bastante o seu uso.
Entretanto, em se tratando de uma API para terceiros, fica difícil prever como a mesma será usada. Tomando como exemplo uma pergunta que respondi recentemente, o fato da biblioteca matplotlib usar uma "imagem corrente" e um "subplot corrente" para direcionar todas as suas operações torna complexo trabalhar com múltiplas imagens e subplots ao mesmo tempo (mesmo na ausência de paralelismo).
Opção 2: passar C como parâmetro sempre
A maior vantagem aqui é a flexibilidade, a maior desvantagem a verbosidade do código (sempre ter que ficar repetindo a passagem de c como parâmetro). Na maior parte do tempo isso é apenas um inconveniente, de modo que essa solução é válida sem reservas. Não é a ideal, mas é válida.
Opção 3: "currying" de objetos
O conceito de currying, quando suportado por uma linguagem de programação, normalmente se aplica a uma única função. Por exemplo, dado A.metodo1(C, D, E):F poderia ser fixado o C na forma de curry(a.metodo1, c) -> fn(D, E):F. Entretanto, isso é de pouca ajuda ao código cliente, já que ele precisará combinar dois ou mais métodos de A para realizar sua função.
Entretanto, se extrapolarmos esse conceito para toda a classe A, podemos criar uma classe auxiliar X que "fixa" a instância de C [além do próprio A] e expõe somente os métodos de A que envolvem a classe C. Por exemplo:
class X {
    private A a;
    private C c;

    public X(A a, C c) {
        this.a = a;
        this.c = c;
    }

    public metodo1() {
        // faz algo com a e c
    }

    public metodo2() {
        // faz algo com a e c
    }

    // Sem "metodo3"; somente os métodos em que A e C interagem
}

Se conveniente, A pode servir como uma fábrica para X:
class A {
    public X curry(C c) {
        return new X(this, c);
    }
}

Dessa forma você simplifica a interface (i.e. cria uma fachada) sem ter que "poluir" a classe A com a introdução de uma propriedade que não corresponde à relação conceitual [estática] entre as entidades A e C.
Comment: *Currying* me dá uma saudade brava de Scala e Haskell :). A ideia de criar uma classe auxiliar para amarrar `A` e `C` sem introduzir uma variável de instância é muito útil. Você consegue expor uma API em que uma instância de `A` esteja "vinculada" a uma instância de `C` sem impor esse modelo para `A`. Muito obrigado!
Answer: Algumas referências interessantes sobre o assunto:
SOE - Parameter vs. Member variables
Principais Pontos:

Variáveis da classe são considerados estado do objeto
Usar uma variável de instância implica em manter estado entre duas chamadas de método. Se o valor armazenado em C não precisar viver entre duas chamadas então a variável de instância não deve existir
Quanto menor o escopo léxico e tempo de vida de uma variável, menor a possibilidade de uso errôneo e melhor para a eliminação de recursos.

SOE: Instance variables vs parameter passing? Is there an argument?
Principais pontos:

Do lado positivo, uso de variáveis de instância evitam a proliferação de parâmetros em métodos. A legibilidade de métodos com muitos argumentos é prejudicada. O livro Clean Code argumenta que métodos não devem ter mais do que três parâmetros.
Do lado negativo, uso de variáveis de instância apenas para evitar passá-las como parâmetro não é uma boa idéia e incha a classe.

Programmers: Ruby - when to use instance variables vs parameters between methods?
Principais pontos:

A decisão entre um estilo e outro depende do papel de C perante toda a classe A. Se a informação transportada em C é relevante para a maior parte da classe, então faz sentido ter uma variável de instância. Exemplo: Um objeto representando uma conta do banco que necessita do titular para quase todas as ações.
Por outro lado, se os dados são específicos para determinado método (e métodos auxiliares) eles devem "viajar" como parâmetros ou objetos intermediários.


how to get the value of slider in another page with a button click in xamarin crossplatform

Question: I am new in Xamarin and I want to go to another screen from one screen. Here i have Two sliders, 2 labels and a button. I want to open another screen after clicking on that button and I should display the values of two sliders in another xaml page.. like slider1 = 2.5 slider2=4. How can i do this?
my cs code:
public partial class MainPage : ContentPage

{

    public MainPage()

    {

        InitializeComponent();

    }

  private void MainSlider1_OnValueChanged(object o, ValueChangedEventArgs e)

    {

        Double slider1 = MainSlider1.Value + 1;

        MainLabel1.Text = Convert.ToString(slider1);

    }

 private void MainSlider2_OnValueChanged(object o, ValueChangedEventArgs e)

    {

        Double slider2 = MainSlider2.Value + 1;

        MainLabel2.Text = Convert.ToString(slider2);

    }

    private async void NavigateButton_OnClicked(object o, EventArgs e)

    {

        await Navigation.PushAsync(new Page1());

}

Answer: You can pass the parameters by having a class as below:
private async void NavigateButton_OnClicked(object o, EventArgs e)
{
    var yourClass = new YourClass {
      Slider1Text = MainLabel1.Text,
      Slider2Text = MainLabel2.Text
    };

    await Navigation.PushAsync (new Page1(yourClass));
}

For this we have to change in the Constructor method of Page1:
public Page1(YourClass yourClass)
{

}

And you can use the data from YourClass as required.
Comment: i want to do it in blankxamlApp(xamarin.forms.portable)


Are RSA keys needed for LAN only setups?

Question: I have an SSH installed on my Ubuntu server. I can log into it from my Ubuntu desktop, using a user and a password. I can only access SSH from my LAN, since the SSH port is not forwarded on my router. Do I need to set up an RSA key for a setup like this? From what I understand the SSH is secure since it cannot be accessed from the Internet.
On a side note, what other things should I double check for security? I have Apache, MySQL and ProFTPD running.
Answer: As a side note, it's very, very easy to setup passwordless logins with SSH, so you might want to try that:
$ ssh-keygen -t rsa # if you don't already have your key pair
$ ssh-copy-id -i ~/.ssh/id_rsa.pub myuser@myserver

And then you wont be asked for a password each time you login to your server :)
Comment: I use keys as well, but I always use them *with* passwords, and use keychain (on Linux) or pageant (on Windows) to cache the password for me.
Comment: Seconded.  Take the few minutes to setup SSH keys and you'll love live even more.  http://pkeck.myweb.uga.edu/ssh/
Answer: If your sure that only authorised users can get access to your LAN, then a username and password should suffice. Nothing is ever going to be completely secure, you need to ask yourself, is it good enough?
If your server is only accesible via your LAN, and your not worried about people gaining access to it, by WiFi hacks, or physical network access, then username/password authentication is probabley good enough.
Answer: Setup keys with passwords. Then use keychain, the only time you will ever have to enter passwords will be after a reboot. All the security of passwords, all the convenience of keys.
Answer: I don't mind entering a password for SSH.  For added security however, I'd recommend enabling the Ubuntu Firewall ufw, which is installed but disabled on Jaunty by default.  It's easy to enable and configure:
sudo ufw enable

EDIT: Don't do this first if you're connecting remotely or you'll lock yourself out!  It's safer to enable last once you're sure all your rules are in place. See Olaf's comment below.
Default block everything
sudo ufw default deny

Allow TCP on prt 22 for SSH:
sudo ufw allow 22/tcp

Delete this rule (if necessary down the road):
sudo ufw delete allow 22/tcp

In addition to port 22, you'll want to allow traffic to port 3306 for MySQL, 80 for Apache, and 20 & 21 by default for ProFTPD.
You can check your rules easily too:
sudo ufw status

Lastly, you can create more fine-grained rules to specific hosts or subnets:
ufw allow proto tcp from 192.168.0.0/24 to 192.168.0.1 port 22

After you configure, disable and re-enable ufw to apply.
Comment: wow - make that from a distance (e.g. over ssh) and you're locked out :) ... make the default settings and allow ssh (22/tcp) before you enable the firewall.

What I don't like with ufw is that the status is not visible (with ufw status) when the firewall is not enabled, so configuring this from a distance is always a bit risky. I usually setup a cron script to disable the firewall every 5 minutes while I change the settings or make sure to have an alternative way in without having to run...
Comment: Good point, I'll edit accordingly -- I usually run sudo ufw disable first and sudo ufw enable last for just this reason.  However, I also really like the idea of the cron script to fire every 5 minutes while you're tinkering just in case!
Answer: Do you need to use keys?  No.  But it sure becomes a lot more convenient to use them once you have more then one server, or if you ever have to script some kind task that will require ssh access.


React state value transfer to another state without repeating value?

Question: I am using the react-select library for multi-select. I am using it as a state selector but the problem is the react-select an array of objects. Like
{
        "label": "Andaman and Nicobar Islands",
        "value": "Andaman and Nicobar Islands"
    },
    {
        "label": "Andhra Pradesh",
        "value": "Andhra Pradesh"
    },

I want to extract the value part from it and I tried directly but It gave me an error I decided to use a different state array to extract but the problem is I only accept three state values and also want to remove duplicate values new state also have only values. I couldn't fix this problem help me to fix this.
const [job_preference, setJobPreference] =
        useState([]);
    const [multiSelect, setMultiSelect] = useState(
        []
    );

const handleMultiSelectChange = (val) => {
        setMultiSelect(val);
    };

const handleJobPreference = () => {
        multiSelect?.map((select) =>
            setJobPreference((prev) => [
                ...prev,
                select.value,
            ])
        );
    };

                                        Job Preference

                                    <Select
                                        value={multiSelect}
                                        isMulti
                                        components={
                                            animatedComponents
                                        }
                                        isSearchable
                                        placeholder='Choose any 3 states as job location'
                                        options={states}
                                        onChange={
                                            handleMultiSelectChange
                                        }
                                        isOptionDisabled={() =>
                                            multiSelect.length >= 3
                                        }
                                    />

Comment: Please show what `handleMultiSelectChange` is.
Comment: You want to remove duplicates, right? What else?
Comment: @kinduser I only want 3 values in multi-select want to remove  duplicate values as well if user changes the value of multi-select it should also change
Comment: you are storing the selected values to the state ? sorry not clear what you are trying to achieve here
Comment: @kinduser I am storing the string of array in the database I only want the value part of multi-select. I suggest not to change the handleMultiSelectChange but to change the handleJobPreference  function.
Comment: @kinduser I want to store the values inside the job_preference state which should be a string of an array that should only have 3 values doesn't matter if the user changes the values it also changes the values. End goal is 3 string values in the job_preference state
Answer: To get the values onChange of multiselect you can do as
  const handleMultiChange = (options) => {
    const values = options.map((opt) => opt.value);
    console.log(values);
  };

Comment: you can do w/e you want to with the values :)
Comment: this won't work react-select only accepts array of objects please what ever you want to do change the job_preference function
Answer: I think this will work for your needs to change slightly KcH answers.
const handleMultiSelectChange = (options) => {
        setMultiSelect(options);
        const values = options.map(
            (opt) => opt.value
        );
        setJobPreference([...values]);
    };


Where can I find an implementation of Hinton's original Boltzmann Machine?

Question: I've been trying to implement the Boltzmann machine 4-2-4 encoder that appeared in A Learning Algorithm for Boltzmann Machines. but I am unable to find clear pseudocode for doing it or more specific details. I have tried "Neural networks: algorithms, applications, and programming techniques" and Fausett books so far. Where can I find an implementation of the encoder or more specific details about it?
Answer: I finally implemented the Boltzmann machine for 4-2-4 encoder problem using several descriptions. You can find my implementation in this blog post.
Comment: Just a note: the $\LaTeX$ code on your page isn't rendering on my computer, it's just source code. Not sure if it's because I'm using an old browser on an old computer or what.
Comment: It is a problem of loading correctly the MathJax libraries on blogspot. It seems that I managed to solve the Latex rendering issue using the advice on this page [link](https://groups.google.com/forum/#!searchin/mathjax-users/blogspot/mathjax-users/Jh_4kWotsS8/Jq5fD0eci48J), hope it works for you.
Comment: Still no luck, but MathJax seems to have stopped working on other sites as well for me so I don't think you can fix it, unless you want to buy me a new laptop.
Answer: Salakhutdinov was a student of Hinton who has since moved to Microsoft.
http://www.cs.toronto.edu/~rsalakhu/DBM.html <-- here is working MatLab code for an RBM.
It's a bit of a mess, I'm a week into rewriting it. If I haven't updated this answer within a month, someone ping me and I will upload my rewrite to GitHub.


Indexing all pages of a website in Google

Question: I use Google CSE on my website, which contains upwards of 5000 stories. Naturally, I would like all of this content to be indexed in Google. Many of these stories will not be linked elsewhere on the site... can they still find their way into Google's search index?
Thanks!
Comment: If the issue's purely one of time (ie there's too much content to manually alter) then you can still try an automated approach, eg. a related items block that uses the node contents to 'guess' which nodes are related to one another. Even a simple chronological paged feed might be better than nothing. Just my 2 cents.
Comment: It will, it will! I was really just making an additional comment about improving your site's SEO.
Comment: Not an answer to your Q, but have you considered trying to increase/improve the internal links on your site? It's not normally a good thing from an SEO POV to have lots of content with no inbound links. Some taxonomy pages and maybe a _related content_ block could perhaps help.
Comment: Sure but the thing is, many of these stories are archives, I want people to be able to find them, but I can't link directly to each and every one of them.
Comment: So xml sitemap wouldn't help index unlinked nodes?
Answer: The XML sitemap module will generate a file which can be submitted to google, and other search engines to tell them about all of your content.
Comment: OK thanks - do you think that would be enough to index all of my nodes?
Comment: If you install and enable the proper sub-modules, you should be able to get all of your orphaned pages into the sitemap.


If $C(X)$ is finite dimensional then $X$ is finite.

Question: I've seen this link: When is the vector space of continuous functions on a compact Hausdorff space finite dimensional?
$X$ is metric and compact. But I don't want to use the Tietz theorem. So how can I prove that if $C(X)$ (the set of all continuous functions from $X\to \mathbb{C}$) is finite dimensional then $X$ is finite?
Comment: Metric implies the Hausdorff axiom.
Comment: Can you check whether or not the definition of compactness you are using includes separated (i.e. that the space satisfies "Hausdorff's axiom", a.k.a. Hausdorff space)? Some times people define compactness as Hausdorff's axiom + quasicompact (myself included). This implies compact and Hausdorff. (A space is "quasicompact" if it satisfies the "Borel-Lebesgue's axiom" that every open cover has a finite subcover.)
Comment: @Mina Is your space $X$ a metric space? If so, please update your question to indicate this.
Comment: @WilliamM. No in the question it just said that $X$ is metric compact set.
Comment: @WilliamM. If I don't know the Tietze theorem, you should I prove this?
Answer: Let $X$ be infinite with the trivial topology $\{\emptyset , X\}$. Then $X$ is compact, $C(X)$ consists of constant functions but $X$ is not finite
Comment: This question has been edited and now is asking a different thing. Originally it asked how to prove that a compact, not necessarily Hausdorff space with finite dimensional $C(X)$ must be finite, so my answer is a counterexample
Answer: Suppose $X$ is infinite and let $\{x_n:n\ge1\}\subset X$ be distinct points. By Urysohn's lemma we can find continuous functions $h_n:X\to[0,1]$ such that $h_n(x_{n+1})=1$ and $h_n(x_{i})=0$ for all $i=1,\dots,n$. Note that if $n<m$ then $n+1<m+1$, so
$$\|h_n-h_m\|_\infty\ge|(h_n-h_m)(x_{n+1})|=|h_n(x_{n+1})-h_m(x_{n+1})|=|1-0|=1\;\;\;\;\;(\star)$$
Also, $\{h_n\}_{n=1}^\infty$ is sequence in the closed unit ball of $C(X)$ since $\|h_n\|_\infty\le1$. But $(\star)$ shows us that $\{h_n\}_{n=1}^\infty$ does not contain any Cauchy subsequence. This proves that the closed unit ball of $C(X)$ is not compact, and therefore $C(X)$ is not finite dimensional.
Answer: This question already gives much of the answer: when $X$ is finite, certainly $C(X)$ is finite-dimensional, since $C(X)$ is just $\mathbb{R}^X$.
Let the metric on $X$ be $d$.
When $X$ is infinite, we can choose a sequence of finite increasing subsets $\{S_j\}_j$ where $S_j\subseteq X$ and $|S_j|=j$.  We have the natural projection $\pi_j\in C(X)\to C(S_j)$ given by "evaluation at $S_j$".  Also, for each $s\in S_j$, the function $x\mapsto d(s,x)$ is a function that is zero on precisely $\{s\}$.  Taking products, we can construct functions that are zero on precisely all-but-one-point of $S_j$, and then sum to get any function on $S_j$.  Thus $\pi_j$ is always surjective.  Moreover, define the function $g_j(x)=\prod_{s\in S_j}{d(s,x)}$; we have $\pi_j(g_j)=0$.
Suppose $C(X)$ has dimension $J$.  Then $C(S_J)$ also has dimension $J$, and so $\pi_J$ is injective.  Thus $g_J=0$.  But since $X$ is infinite, there exists $y\in X\setminus S_J$.  By the definition of a metric, we can prove each factor in $g$ is nonzero, though, and so $g(y)>0$.  $\rightarrow\leftarrow$.
Answer: Here is a paraphrasal of JustDroppedIn's argument: if $C(X)$ is finite-dimensional, then so is its dual $C(X)^\ast$; which space can be identified as the space of real measures on $X$. The map $\delta_\bullet:X\to C(X)^\ast$ that takes a point $x\in X$ and gives the Dirac measure concentrated at $x$ is a topological embedding. If $x_1,...,x_d\in X$ are distinct, then $\delta_{x_1},....,\delta_{x_d}\in C(X)^\ast$ are linearly independent by the Urysohn Lemma.


I got jquery-ui sortable working with meteor templates, but is it a bad hack?

Question: I'm trying to use jquery-ui sortable with nested templates in Meteor, as follows. Here are the two templates in question:
<template name="activityEditor">
  {{! the main activity editor view }}

    <input type="text" name="title" class="input-xxlarge" value="{{info.title}}" placeholder="Type a title here...">

      {{#each info.steps}}
        {{>activityStepEditor}}
      {{/each}}

</template>

<template name="activityStepEditor">
  {{! the container view for each step editor }}

{{order}}

    {{!....stuff...}}

</template>

and the template code (using coffeescript):
_.extend Template.activityEditor, {

  # ...stuff...

  rendered: ->
    $(".activity-steps").sortable {
      items: '.activity-step'
      handle: '.order'
      update: ->
        stepIds = ($(el).attr('data-id') for el in $('.activity-step'))

        $('.activity-steps').empty() #this must be done in order to steps to re-render properly
        Lab.Activity.reorderSteps stepIds

    }
    $(".activity-steps").disableSelection()

}

The only way I can get this code to work and properly rerender the order is by emptying the container of my sortable elements right after they update with $('.activity-steps').empty(). I've tried cancelling the update event and forcing a rerender by changing another variable watched in the context, but any change causes Exception from Meteor.flush(): undefined after which I can't rerender anything until page reload.
This seems to work, and everything rerenders great. So my question is: is there any reason why I shouldn't do this? Is there a better, standard practice way to handle the sortable that I'm not seeing?
Answer: In the near future there'll be a better way to do it, as Meteor team is developing its new rendering engine: http://youtube.com/watch?v=ISNEhPG0wnA
(in this video, Avital Oliver shows exactly a way to do it without redrawing the screen: the object in the list is actually moved on all clients)
See this Meteor's Github Wiki entry for more technical info:
http://github.com/meteor/meteor/wiki/New-Template-Engine-Preview
While that's not officially published, if you need it right now, you could try Nazar Leush's approach:
http://github.com/nleush/meteor-todos-sortable-animation
He also published a working example here: http://todos-dnd-animated.meteor.com


Firmware updates for HP DL360 G5 server

Question: DL360 G5 firmware update (BIOS, iLO, etc): From where it should be taken? Most existing links to the HP portal are broken.
Update: HP has moved to new portal (reason why links are broken). However, almost everything is accessible according to accepted answer.
Comment: no, but if HP does not support them anymore, we can't help much. I seen a customer with a really old server, a worst case than you.  When it died it put them down for 1 weeks, and that costed them a lot, as it was a emergency reinstall and upgrade with third part. If your customer think to upgrade the firmware, it's not because the server behave good too. It's kinda the talk, maybe some were direct, but we try to bring the discussion, but in the end, we can't offer what HP stopped offering
Comment: Yes, it's unprofessional to run unsupportable kit in production.
Comment: If cost is a issue I would think to use a profession workstation, like a HPz desktop system and to use an hypervisor on it to replace such old hardware. HP is one of the manufacturer that support for the longer server. They can provide part up to 10 years for a a server even if no warranty. The fact HP retired all the download related to that server model is worring to say the least.
Comment: Maybe you can finde someone who kept his downloaded ISO of **ProLiant SPP 2014.06.0** or check https://myenterpriselicense.hpe.com/cwp-ui/free-software/spp_2014.06.0 out.
Comment: Why on earth are you still dealing with G5 kit, that model was retired 11 years ago and went of of support 6 years ago - this site is for professionals sorry.
Comment: thank you, Mister Professional
Comment: Is there a correlation between "professionalism" and "end of support for hardware"
Comment: Sure, next time when small business owner brings me "unsupported" hardware, I will tell them go anykey themselves around the corner, because it is unprofessional.
Comment: @yagmoth555, cost is an issue, always. There are many other reasons not to replace old HW: COVID, economic slowdown, CO2 neutrality and most popular - "it still works"
Comment: @yagmoth555, Of course you can. Specialist like you can help in this case. This is why ServerFault exists - to share knowledge. And I appreciate your help. By the way, please check Questions tagged [hp].
Answer: Visit the HPE Support Center at https://support.hpe.com/hpesc/public/home
Enter DL360 G5 for your search
Filter by 'Software Downloads' and then sort by date.
Comment: @JohnDeer Is the question about their "Entitlement Required" policy, if so what specifically is the question? (Presumably beyond their explanation provided on the page)
Comment: This is a great answer. However, HP does not allow to download the most recent version (why?). Previous taken as the latest available.
Comment: See my comment above.
Comment: Your comment above is off topic and does not answer why HP restricts some downloads.
Comment: It's not off topic if the reason you can't download firmware is because the manufacturer hasn't supported the model for 6 years.
Comment: @HåkanLindqvist, well, this is a rhetorical question. I just simply took previous version, which is accessible.
Answer: If the links to download firmware are dead, your only hope is to get your hands on a ProLiant Support Pack that does support your server hardware.
I don't have my HPe login near, but check there for older version of it;
HP Service Pack for ProLiant
As stated in comments, please advise your customer.
Comment: You have to pay to access PSPs, and HPE won't take money for access to a system they've not supported for more than half a decade.

Firmware updates for HP DL360 G5 server


How do I play these notes from Ólafur Arnalds' Romance?

Question: I'm studying this Ólafur Arnalds piece called Romance.  I wonder how do I play the following notes.
First, on this measure, the two F's are supposed to be the same.

What should I do?  Raise the LH thumb and play the note with my RH thumb?  Play it with the LH thumb?  Do not play it at all?
Then, on the last measure, I have those notes too spaced.

Even though I have big hands, I can't reach those notes together with my LH.  What should I do?  Play the upper B with my RH?  Play them as a kind of arpeggio?
Answer: For the first one, yes.  Lift up your left thumb in time to play the 8th note with your right hand (you could use your left hand if you wanted to, but I would use my right as it seems more natural).  This sort of thing is fairly common; don't allow yourself to get too wound up in the apparent contradiction.
For the second one, by all means play the upper notes in the bass clef with your right hand.  There is nothing that says that you put left hand notes pointing down and right hand notes pointing up or anything like that.  It's whatever works best.
Comment: Agreed. In the first example, I'd give a touch of pedal slightly after hitting the quaver A to allow the F to keep ringing when the LH thumb is lifted.
Comment: Interesting.  I played over the passage and find myself using more pedal than that, personally.  The style is Grieg-like, and allowing the pentatonic notes to run together some creates a nice ethereal effect.  My first instinct was to pedal through the first two beats (assuming 4/4), and then clear the pedal once on the third and fourth beats.  It goes to show the amount of variety you find in performances with use of the pedal.
Comment: Yup, that's a perfectly viable way to do it. I tend to look at minimal pedal first when (as here) finger legato is easily attained, and then consider if the sound can stand to be wetter. That's probably because I'm primarily a composer (and a fairly contrapuntal one at that, usually), and I don't like to specify pedal unless I need it. My writing habits have some tendency to carry over to my analytic habits. Here, though, a break in the middle of the bar is called for, and being a bit sparing with the pedal can help.


keep diskpart command line open after command execution

Question: I'm working in a script that takes screenshots of the terminal after execution a list of commands, one of those commands is list disk in "diskpart command line" this is the what I've coded:
Set args = WScript.Arguments
Set objShell = CreateObject("WScript.Shell")

Dim comando
comando = "list disk"

objShell.CurrentDirectory = "C:"
objShell.Run ("diskpart command line" & comando)
WScript.Sleep(5000)

Everything is working, but after the command is executed, the terminal disappear and the screenshot cannot be taken. How can I pause the terminal execution?
I've also tried with this line:
objShell.Run ("cmd /k diskpart " & comando)

but /k is not making any difference.
Answer: The parameter /k keeps the CMD instance running. It does not affect the diskpart command. If you want to keep an interactive diskpart prompt after running a command just run diskpart a second time (use & for daisy-chaining the commands). Also, diskpart doesn't accept commands as parameters. You must either write them to a script and call that via diskpart /s SCRIPT or pipe the command into diskpart.
Set sh = CreateObject("WScript.Shell")
cmd = "list disk"
sh.Run "cmd /k ""echo " & cmd & " | diskpart & diskpart"""

Replace /k with /c if you want the CMD window to close automatically when you exit from diskpart.


Private browsing with UIWebView on the iPhone & iPad

Question: How do existing apps implement this feature???
Can I store cookie only for certain sites, and only inside my app? It's my understand that the web view stores cookies in shared mode...so that they are shared with Safari and other apps that use UIWebView.
Comment: Just to be sure, are you talking about private browsing or anonymous browsing?
Comment: private browsing actually. I want to be able to completely wipe out the cache of downloaded images and cookies.
Comment: Please consider changing the title from "Anonymous browsing" to "Private browsing" so that others that search for it won't be mislead. They are two totally different things.
Answer: According to the NSHTTPCookieStorage docs, cookies are not shared between applications:

iPhone OS Note: Cookies are not shared
  among applications in iPhone OS.

So it seems like they should be "private" by default.  You can also use the [NSHTTPCookieStorage sharedHTTPCookieStorage] object to set the cookie storage policy to not store cookies at all, or you could use the deleteCookie: method to clean up after yourself if you needed to.
As for other content that is loaded by your UIWebview, when you create the NSURLRequest that is loaded by your webview, you can set a cache policy that controls if the content will be cached.  For example:
NSURLRequest * request = [NSURLRequest requestWithURL: [NSURL URLWithString: url]
                                          cachePolicy: NSURLRequestReloadIgnoringLocalAndRemoteCacheData
                                       timeoutInterval: 60.0]
[webView loadRequest: request];

NSURLRequestReloadIgnoringLocalAndRemoteCacheData tells the request to ignore the cache and load the request from the network.  I'm not sure if it also prevents the response from the network from being cached, but to be sure, you could alway remove it from the cache yourself:
[NSURLCache sharedURLCache] removeCachedResponseForRequest:request];

Answer: If you're talking about Private Browsing, the UIWebView actually does not store history after the app is closed (only temporary for going back and forth). Instead you would have to implement storing history yourself, so it would be automatically Private Browsing.
Short answer: Don't do anything. Its already in Private Browsing mode.
EDIT: For handling cache check out this method:
- (NSCachedURLResponse *)connection:(NSURLConnection *)connection willCacheResponse:(NSCachedURLResponse *)cachedResponse

And make cashedResponse return nil.
Comment: mmm...ok about the history...but what about cached images, and cookies? I think at least cookies are preserved, and probably images too...no?
Comment: thanks thyrgle...that sounds like a good response but...where/how do I implement it in the UIWebView? Or should I imeplement in a subclass for NSURLCache as shown here: http://www.icab.de/blog/2009/08/18/url-filtering-with-uiwebview-on-the-iphone/

Is it any useful to implement this, is the UIWebView OS doesn't store a cache?


Flask-Login: Does not work on local machine but fine on hosting

Question: I have a flask app, and I use flask-login, following tutorials (nothing fancy here)

works fine on hosting
works fine on my local MAC computer (at home)
does not work on my local Linux computer (at office, which may be behind a firewall, but I am able to do port-forwarding and connect to the database)
does not work on Chrome or Firefox
does not work if I serve on localhost instead of 127.0.0.1.

from flask.ext.login import LoginManager

login_manager = LoginManager()
login_manager.session_protection = "strong"
login_manager.init_app(app)
login_manager.login_view = 'login'

def login():
    error = None
    form = LoginForm()

    if request.method == 'POST':
        user = db.users.find_one({"username": form.username.data})
        pass_hash = generate_password_hash(form.password.data)

        if user and User.validate_login( pass_hash,  user['password'] ):
            user_obj = User(user['username'])
            session['logged_in'] = True
            login_user(user_obj,remember=True)
            flash("Logged in successfully", category='success')
            print 'logged in: OK'

            #return redirect(request.args.get("next") or url_for("index"))
            return redirect( url_for("index"))
        error = 'Invalid credentials'
    return render_template('login.html', title='login', **locals())

well, when I enter my password wrong, it gives the "Invalid credentials" error. When I enter my password correctly, I do not see "Logged in successfully" flash, but on console I see "logged in OK". So there is no problem with DB connection. However I am not logged in. For example,
g.user.is_authenticated()

gives false in the template (this occurs only on my local Linux, on the other hand hosting and MAC successfully logs in the user).
Comment: Looks like you are using mongodb (but I might be wrong). Can you add  print statements to print user and pass_hash before this line  if user and User.validate_login( pass_hash,  user['password'] ):  or use python debugger to check if the database gives you back what you expect !
Comment: @skippy yes I get all of them correctly, I get user object correctly too.
Comment: Hmmm, so from looking at your code, if you could pass the check "if user and User.validate_login( pass_hash,  user['password'] ):" ,  you should be able to see "Logged in successfully" . So  if you are able to get your objects correctly as expected from your db ,  then you are failing on your "if clause" . To be precise you are failing on this check "User.validate_login( pass_hash,  user['password'] )". Can you step into this code and verify if it is returning a False ?
Comment: @skippy thanks but, I am not failing on if clause. As I mentioned in the question, on console I can see "logged in :OK", so if clause is fine. There has to be something else, that I do not know.
Comment: Oh , I missed it on your description. My bad !  Well , if the flash msg doesn't show up on the web page , you could probably view its html source and check if the msg actually made it there.  Im guessing you are using jinja as your templating engine on the client side and I haven't seen any anomalies with jinja on linux/mac so far.    But if the html source indeed doesn't expand the flash message , I'd be using a client side debugger like Firebug/chrome-debugger to check if there are any exceptions generated. I'd do the same thing on Firefox and Chrome and check if the behavior is consistent
Comment: It sounds like a problem with the session. That would affect both the login and the flash messages. You mentioned port forwarding. Are you forwarding to the same port, e.g., 5000 to 5000, or are you forwarding to a different port, e.g., 80 to 5000?
Comment: @dirn yes looks like something with the session. Yes it is forwarding the same port. Well if I forward to wrong port, it cannot read from the database. But currently it reads from database.
Comment: What's your `User` model? In particular, what is your implementation of `is_authenticated()`?
Answer: Where and how are you saving the session in the browser?
Consider a session stored in a browser cookie for the production domain example.com, which you have also configured locally (by adding an override to your /etc/hosts file).
If your office server is configured to use a different subdomain, for example office.example.com, and REMEMBER_COOKIE_DOMAIN is set to example.com, the office server will not be able to read the cookie. The fix is to use a cross-domain cookie: REMEMBER_COOKIE_DOMAIN=.example.com (note the preceding dot).
Ref: https://flask-login.readthedocs.org/en/latest/#cookie-settings
Answer: With sessions come session management...

Are you using a client-based session management?

possible issues with the cookies e.g. cookie size, too much data in cookie
possible issues with the server secret key e.g. generating a new secret key each time

Are you using server-based session management (e.g. flask-kvsession)?

possible issues trying to access the same backend as prod e.g. firewall preventing access to a redis server

It is possible that you are trying to store more session data when hitting your dev server (e.g. longer server urls, debug data, etc...), which can be a pain to deal with when session management is done on the client.


como acessar o jbutton que está na outra classe?

Question: tenho o jbutton na classe principal, dai coloquei ele como public para poder acessar de outra classe.
mas está sem fazer o correto
public class piscarbt{

 tela t = new tela();
public void piscar(){

    t.jButton1.setBackground(Color.white);

}

}

fiz esse código e a cor do jbutton não altera, lembrando que na classe principal ele estápublic javax.swing.JButton jButton1;
não sei o qeu fazer pois ele já está como publico
Comment: Não é muito fácil de fazer, mas não é impossivel de aprender. Veja http://stackoverflow.com/questions/7115672/change-jbutton-gradient-color-but-only-for-one-button-not-all?lq=1
Answer: Faz um get do botão na classe principal:
public JButton getBotao() {
return seuBotao;
}

Na outra classe instância a a principal:
ClassePrincipal controle = new ClassePrincipal():

E seu código irá ficar assim:
JButton botao = controle.getBotao();
t.botao.setBackground(Color.white);

Tenta ai e da um feedback
Comment: Só isso não vai resolver, dependendo do LAF que estiver sendo aplicado. Pois quem colore o button é o UIManager, e esse método por si só não altera o bakcground.
Comment: o que eu devo fazer diego
Comment: @DiogoCipriano eu postei um link com um exemplo, talvez se você adaptar, atenda.
Comment: consegui mudar a cor dele porém tem um  porém eu mando ele mudar duas vezes usando thread e ele só muda a ultima sempre
Answer: Você pode deixar o botão como estático:
Private Static JButton btnBotão;
E criar um método estatico pra chamar esse botão:
public static JButton getButton(){
     return btnBotao;
}
tudo isso na classe principal.
Na classe que vc for chamar esse botão pode chamar pelo método estatico:
Principal.getButton().addActionListener() .... enfim, implementa como desejar


Handle mousemove stop with RxJs

Question: Is there a way to identify when user stopped moving the mouse? I can't figure it out how to tell in RxJs if user stopped for let's say 2s.
When I use it like this:
fromEvent(document, 'mousemove').pipe(
    debounceTime(2000)
).subscribe(() => console.log("Stoped"));

It triggers even if I move cursor out of the screen.
Comment: Well, you can't handle events that aren't emitted by the browser so when you move mouse out of the screen browser is not emitting any events so there's nothing you can do about it
Answer: Depends on a situation, but timeout or timeoutWith may work for you.
This example will emit "stop" every time when there was no mousemove events for more than 1s:

const { of, defer, concat, fromEvent } = rxjs;
const { mapTo, timeoutWith, skipUntil } = rxjs.operators;

const move$ = fromEvent(document, 'mousemove').pipe(mapTo('move'));
const moveAndStop$ = move$.pipe(
  timeoutWith(
    1000,
    defer(() => concat(
      of('stop'),
      moveAndStop$.pipe(skipUntil(move$))
    ))
  )
);

moveAndStop$
  .subscribe(e => console.log(e));

Move your mouse over me

Comment: Ok, but how to tell, when to start the timeout? I'm struggling with that.
Comment: @Gabriel I've updated my answer with code example for you

Handle mousemove stop with RxJs


Como gravar dados no registro do Windows?

Question: Preciso gravar dados no registro do Windows em minha aplicação.
Como trabalhar com a manipulação de dados do registro do Windows usando C++?
Qual é a maneira correta de se gravar novos dados no registro sem erros?
Comment: Dando uma fuçada no SO gringo encontrei estes posts: http://stackoverflow.com/q/34065/4178863 e http://stackoverflow.com/q/15084380/4178863. Também tem esse: http://www.tenouk.com/ModuleO1.html Se você acha que te ser posso criar uma resposta em cima delas.
Comment: Você está usando C++/CLI? Ou C++ normal?
Answer: Escrevendo no registro do Windows
/* Namespaces */
using namespace System;
using namespace Microsoft::Win32;

    //Criando uma instância gravável da classe de RegistryKey
    RegistryKey^ rk;
    rk = Registry::LocalMachine->OpenSubKey("SOFTWARE\\", true);

    //Criando sua subchave
    RegistryKey^ nk = rk->CreateSubKey("DWORD");

    //Adicionando novo valor a sua subkey
    String^ newValue = "NewValue";
    try
    {
        nk->SetValue("NewKey", newValue);
        nk->SetValue("NewKey2", 44);
    }
    catch (Exception^)
    {
        Console::WriteLine("Failed to set new values in 'NewRegKey'");
        getchar();
        return -1;
    }

Se estiver usando Visual Studio lembre de fazer as seguintes alterações:
Configuration Properties -> General
Configuration Properties -> C/C++ -> General
Altere Common Language RunTime Support para "Common Language RunTime Support (/clr)"
Lembre também de fazer as validações no código.
Answer: Além das soluções já apresentadas, é possível utilizar algumas WinAPIs que fornecem a você o acesso ao Registro e a manipulação do mesmo.

RegOpenKeyEx: Abre a chave especificada para leitura ou gravação.
RegCreateKeyEx: Cria uma chave no Registro, caso já exista, a função abrirá tal chave. Vale lembrar que é possível criar quatro chaves de modo hierárquico, especificando uma sequência ao parâmetro lpSubKey, algo assim subkey1\subkey2\subkey3\subkey4.
RegDeleteKeyEx: Exclui uma chave do Registro e seus valores. A chave excluída não é removida até que o último identificador da operação seja fechado.
RegDeleteKeyValue: Exclui a subchave e valor especificados.
RegDeleteTree: Exclui as subchaves e valores da chave especificada de forma recursiva.
RegDeleteValue: Exclui um valor nomeado, especificando a chave.
RegSetKeyValue: Utilizado para alterar o nome de um valor ou chave, ou modificar os dados de um valor.
RegSetValueEx: Altera os dados e tipo(REG_SZ, REG_MULTI_SZ,..) de um valor especificado, indicando a chave.
RegQueryValueEx: Recupera os dados e o tipo de um valor especificado, associado a uma chave de registro aberta.
RegGetValue: Semelhante a função acima, porém, a diferença entre elas é que esta é mais apropriada para retornar valores de terminação nula(REG_SZ, REG_MULTI_SZ, e REG_EXPAND_SZ) enquanto a outra função pode não armazenar adequadamente os caracteres nulos.

Essas devem ser as funções que devem te interessar, a lista completa de funções que envolvem o Registro, pode ser vista aqui.

Veja um exemplo de uso da função RegSetValueEx.
HKEY regKey;
std::wstring foo = TEXT("O dado a ser gravado aqui");

Result = RegOpenKeyEx(HKEY_LOCAL_MACHINE, TEXT("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run"), 0, KEY_ALL_ACCESS | KEY_WOW64_64KEY, &regKey);
if (Result == ERROR_SUCCESS)
{
    Result = RegSetValueEx( regKey,
        TEXT("Nome do valor"),
        0,
        REG_SZ,
        (const BYTE*)foo.c_str(),
        ( foo.size() + 1 ) * sizeof( wchar_t ) );
    if (Result == ERROR_SUCCESS)
    {
        std::cout << "Done!";
    }
}

Answer: Como nunca usei, vou postar somente o que achei no site da MSDN.

O código a seguir usa a chave CurrentUser para criar uma instância de
  escrita da classe RegistryKey, correspondendo à chave do Software. O
  método CreateSubKey é usado para criar uma nova chave e adicionar os pares
  valor/chave.

// registry_read.cpp
// compile with: /clr
using namespace System;
using namespace Microsoft::Win32;

int main( )
{
   array<String^>^ key = Registry::CurrentUser->GetSubKeyNames( );

   Console::WriteLine("Subkeys within CurrentUser root key:");
   for (int i=0; i<key->Length; i++)
   {
      Console::WriteLine("   {0}", key[i]);
   }

   Console::WriteLine("Opening subkey 'Identities'...");
   RegistryKey^ rk = nullptr;
   rk = Registry::CurrentUser->OpenSubKey("Identities");
   if (rk==nullptr)
   {
      Console::WriteLine("Registry key not found - aborting");
      return -1;
   }

   Console::WriteLine("Key/value pairs within 'Identities' key:");
   array<String^>^ name = rk->GetValueNames( );
   for (int i=0; i<name->Length; i++)
   {
      String^ value = rk->GetValue(name[i])->ToString();
      Console::WriteLine("   {0} = {1}", name[i], value);
   }

   return 0;
}

Fonte: http://msdn.microsoft.com/en-us/library/bwt6b955.aspx


JDBC preparedStatement not working in JSP

Question:
PreparedStatement is working fine if query is static (no parameters), for example:
select * from RWEMP;

but if I use the code below with a search condition:
SELECT * FROM RWEMP WHERE ENAME= ?

It doesn't show anything, it is just showing the table headers.
<FORM METHOD="get">
        <INPUT TYPE="text" NAME="cond" SIZE=50>
</FORM>

    <% String value = request.getParameter("cond");
        if (value != null) { %>

 Search results for   <%= value %>

        <% }  %>

    <%@page import="java.sql.*" %>
         <%Class.forName("oracle.jdbc.driver.OracleDriver");

          String sql="SELECT * FROM RWEMP WHERE ENAME= ?";

         Connection con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:XE","hari","root");
         PreparedStatement stat=con.prepareStatement(sql);
         stat.setString(1,"value");
         ResultSet rs=stat.executeQuery();
         try {
             if(rs!=null) {
         %>

                 Emp ID
                 Emp Name
                 Emp Dept
                 Emp Area
                 Emp D.O.B
                 EMP Mobile
                 Emp Salary
                 EMP Wife

        <%
          while(rs.next()) {
        %>

            <%= rs.getString("EID")%>
            <%= rs.getString("ENAME") %>
            <%= rs.getString("EDEPT")%>
            <%= rs.getString("EAREA")%>
            <%= rs.getString("EDOB")%>
            <%= rs.getString("EMOBILE")%>
            <%= rs.getString("ESAL")%>
            <%= rs.getString("ESPOUSE")%>

         <%
          }
           }
     }
          catch(SQLException e) {
            e.printStackTrace();
             }
con.close();

%>

Comment: Unrelated, but: don't put SQL code like that inside a JSP - especially not obtaining a connection. Use a connection pool for that. The JSP should **only** contain presentation code, never Java code and absolutely never SQL code.
Answer: Change your PreparedStatement's query parameter binding code as
stat.setString(1, value); // no quotes

You need to search on what the value variable contains, not by its name "value" itself.


Matrix Addition and Pivot Points

Question: I'm rather new to more formal settings of linear algebra and am having a little bit of trouble acquiring a natural grasp on certain aspects of matrices. I understand that any matrix is congruent (is that the correct term in English?) to a single, unique reduced matrix (RREF). What I'm not too comfortable with is knowing how pivot points are specifically related to individual matrices—one thing I'm struggling with right now:
If I have two matrices with their own defined pivot points and I add the matrices, what effect will this have on the pivot points of the resulting matrix? Is there any relation?
Answer: Pivot points can tell you important things about your matrix, for example take a matrix $A_{mxn}$:

If there are $n$ pivot positions (a pivot in every row) in the RREF form, then we know that the columns of the matrix span $\mathbf{R}^{n}$.
If there are $m$ pivot positions (a pivot in every column) in the RREF form then the columns of the matrix are linearly independent.

You can only add two matrices of the same dimensions, say $A_{nxm}$ and $B_{nxm}$. Lets take an example:
$
A=
    \begin{matrix}
    a & b & c \\
    0 & 0 & f \\
    0 & 0 & 0 \\
    \end{matrix}
$
$
B=
    \begin{matrix}
    a & b & c \\
    0 & e & f \\
    0 & 0 & g \\
    \end{matrix}
$
You will get the result A+b =
$
    \begin{matrix}
    2a & 2b & 2c \\
    0 & e & 2f \\
    0 & 0 & g \\
    \end{matrix}
$
The pivot position of each row in the sum is going to be the same position as whichever matrix had a pivot position further left in the row before being added.
Comment: Okay, makes sense. So, for example, if I have two 2x2 matrices, one with 2 pivot points and the other with only 1, then the matrix resulting from the sum of the two matrices would have 2 pivot points. Right?

Matrix Addition and Pivot Points


Show that a sequence converges in distribution

Question: I recently go through this problem in a past exam and I wonder how to solve this problem. The statement goes as follows:
Let $X_n, n \in \mathbb{N}$ be a sequence of i.i.d random variables satisfying:
$$\mathbb{P}(X_1>x) = \mathbb{P}(X_1<-x) = \frac{1}{2x}$$
for all $x \geq 1$ and let $S_n = X_1 + ... + X_n$. Shows that as $n \rightarrow \infty$, the sequence $\frac{S_n}{n}$ converges in distribution and identify the limit.
Comment: Was this question isolated, or did it came after other questions?
Comment: @ChristopheLeuridan it is an isolated question
Answer: Call $\varphi$ the characteristic function of $X_1$. One checks that the characteristic function of $S_n/N$ is given by $\phi_{S_n/n}(t) = \phi_{S_n}(t/n) = \varphi^n(t/n)$.
Let us look at the behaviour of $\varphi$ at $0$. Since the distribution of $X_1$ is symmetric with regard to $0$, the function $\varphi$ is even. More precisely, for every real number $t$,
$$\varphi(t)
= \int_{\mathbb{R}} e^{itx} \mathbb{1}_{[|x| \ge 1]} \frac{dx}{2x^2}
= \int_1^\infty \cos(tx)\frac{dx}{x^2}.$$
For every $t>0$,
$$\frac{1-\varphi(t)}{t}
= \int_1^\infty \frac{1-\cos(tx)}{tx^2} dx
= \int_t^\infty \frac{1-\cos(y)}{y^2}dy.$$
Thus
$$\lim_{t \to 0+} \frac{1-\varphi(t)}{t} \to \int_0^\infty \frac{1-\cos(y)}{y^2}dy = \frac{\pi}{2}.$$
As a result, since $\varphi$ is even,
$$\varphi(t) = 1 - \frac{\pi}{2}|t| + o(t) \textrm{ as } t \to 0.$$
Thus for every real number $t$,
$$\varphi(t/n) = 1 - \frac{\pi|t|}{2n} + o(1/n) \textrm{ as } n \to +\infty.$$
so
$$\phi_{S_n/n}(t) = \varphi^n(t/n) \to \exp(-\pi|t|/2) \textrm{ as } n \to +\infty.$$
The distribution of $S_n/n$ converges to the Cauchy distribution $\mathcal{C}(0,\pi/2)$.


Should I separate my data into different batches and then perform tsne on each batch?

Question: I have a very huge dataset and required to reduce the embedding of 768 dimension to 128dimension with TSNE. Since I have more than 1million rows, it takes more than weeks to complete dimension reduction on whole dataset, so I thought maybe I can separate the dataset into different parts and then perform each part separately. I do not have GPU so only CPU.
<code>from sklearn.manifold import TSNE
tsne = TSNE(n_components=128, init='pca', random_state=1001, perplexity=30, method='exact', n_iter=250, verbose=1)
X_tsne = tsne.fit_transform(df_dataset[:1000000]) # this will either fail or take a while (most likely overnight)
I am wondering whether my way is considered OK?
</code>
The above is not using split yet, but just load all the datasets. I just want to confirm whether splitting to multiple batches and then fit_transform each batch is the right way or not.
Also, I check the below link about whitening sentence representation but not sure whether does it work with my above method by replacing tsne with whitening. https://deep-ch.medium.com/dimension-reduction-by-whitening-bert-roberta-5e103093f782
Comment: Not a *programming* question, hence off-topic here; please see the intro and NOTE in https://stackoverflow.com/tags/machine-learning/info
Comment: If you are aware about `split` which is avaible in `Unix` . Make use of that to split into batches of `100`. Make a embedded script `Unix + Python`  . Link : https://kb.iu.edu/d/afar
Comment: Yes, I know how to split it using python but I am wondering whether splitting it and then fit_transofrm each batch is the right way to do it.
Answer: It probably depends what you're trying to do, but I suspect the answer is that it is the wrong thing to do.
Between different batches it would difficult to guarantee that the reduced dimension representations would be comparable, since they would have been optimised independently, not using the same data. So you could end up with data looking similar in the low-D representation, when they aren't similar in the original representation.
It seems like PCA might be more suited to you, since it's very fast. Or UMAP, since it is also fast, but additionally has some ways to work with batched data etc.
Comment: Thank you. Yes, I tried UMAP too but then I faced another issue. I posted it here. https://stackoverflow.com/questions/73970140/kernel-dead-when-training-umap-with-large-dataset-with-high-dimension
Comment: It seems like you've deleted your other question, but given the info in the URL, my guess is that you hit a memory error. UMAP has a argument for specifying low-memory, maybe give that shot? Or try the method outlined in the [alignedUMAP](https://umap-learn.readthedocs.io/en/latest/aligned_umap_basic_usage.html) examples.
Comment: Thank you, actually I found the answer to it. It seems like I can use update as an alternative to make umap an incremental type
Comment: Hi, since I am facing the same problem, could you elaborate on what you finally did?


Trying to create rule based static blocks in Magento

Question: So one of my clients has a request to do rule based static blocks on their home page. The page will basically swap out several static blocks for others based on the perceived gender of the person viewing the site. It will get this data from the session that the user is currently in, or the data associated with the users account. Basically, if a user searches in a specific set of categories (Men's or Women's categories) it should swap the static blocks out on the home page, so when that user visits the site again they will have a more personalized experience. There will be a default set of blocks if the user is new to the site.
Something like this (and excuse my shabby php):
if($categories = $user->getViewedCategories()){
    foreach($categories as $category){
        switch($category){
            case 14: //insert womens category id here
                echo $staticBlockWomen
                break;
            case 16: //insert mens category id here
                echo $staticBlockMen
                break;
        }
    }
} else {
    echo $staticBlockDefault
}

I know Magento tracks a users path through a site, and I know that other elements in Magento can have rules based on this data (the dynamic banners and checkout rules), but I am really lost on where to get started.
If someone could point me in the right direction, any help would be appreciated!
Cheers,
Matthew
Answer: I'm assuming you know the basics of Magento (at least how to create new blocks and how to manage the layout using xml).
If you need more info about that,
You can accomplish what you need in a few steps:
1 - create the blocks you need (create a new module and block classes inside it within the corresponding .phtml files)
2 - from the admin panel, select the category for which you want to add a block and navigate to "Custom Design" tab, then add in the "Custom Layout Update" textarea  something like this:
<reference name="content" >
    <block type="mymodule/myblock" name="myblock" />
</reference>

This way, every time the selected category is viewed by the custmer, a block of type "mymodule/myblock" will be added in the content area.


Provide support for embedding feature

Question: I am wondering how can I provide support for embedding feature. Actually in my application when user creates article/content, I need to take option from user that if his content can be embedded via embed code to some other web sites. For that he selects yes, then, system should display embed code in the article page, by using which, other people can embed this article.
Please suggest is their any module in drupal that helps me to achieve this or some tutorial helping me to achieve this will also be useful.
Thanks for your time.
Comment: Embed What and which Drupal version ?
Answer: For D6 there is Embed widgets

Embed widgets allows content such as pages, blocks, views, and nodes
  from your Drupal site to be embedded in external sites (including
  non-Drupal ones).

If its D7 there is Embeddables

Embeddable provide a method for embed thingies in content.It is a
  pluggable system that currently allows the embedding of nodes and
  blocks.

Found 136 results containing the words: Embed on drupal.org
Comment: @NikhilM, I think OP is looking for embeddable codes (nodes) of the drupal site to put into other non-drupal sites. The Embeddables module is probably for embedding of nodes/blocks in the same site.

Provide support for embedding feature