Unique id for a file in C#

Question: I need to generate a unique id for file sizes of upto 200-300MB. The condition is that the algo should be quick, it should not take much time. I am selecting the files from a desktop and calculation a hash value as such:
HMACSHA256 myhmacsha256 = new HMACSHA256(key);
byte[] hashValue = myhmacsha256.ComputeHash(fileStream);

filestream is a handle to the file to read content from it. This method is going to take a lot of time for obvious reasons.
Does windows generate a key for a file for its own book keeping that I could directly use ?
Is there any other way to identify if the file is same, instead of matching file name which is not very foolproof.
Comment: why reinvent the wheel? why not just use [md5](http://msdn.microsoft.com/en-us/library/system.security.cryptography.md5.aspx)?
Comment: @MichaelKjörling - It's very unlikely you'll get collisions unless manufactured by a malicious user; and since OP isn't using MD5 for security I don't see it as an issue.
Comment: @mtijn, maybe because [MD5 is broken](http://en.wikipedia.org/wiki/MD5#Security) and should not be used for new implementations?
Comment: Maybe you should hash not stream but just file size?
Comment: I don't see anything in the question to indicate whether collision-resistance is a requirement or not, only that this is about identifying whether "the file is [the] same".
Comment: You can't get unique ids from a hash.
Comment: is [this](http://stackoverflow.com/questions/1866454/unique-file-identifier-in-windows) what you are looking for?
Answer: MD5.Create().ComputeHash(fileStream);

Alternatively, I'd suggest looking at this rather similar question.
Comment: the OP says "the condition is that the algo should be quick", he did not say anything about secure, nor about using this for security reasons. it's just a checksum.
Comment: MD5 is broken such that it should not be used as a mechanic in a security context, as a way of hashing general data for summary comparison its fine & has the advantage of being very fast.
Comment: As I said in a previous comment, [MD5 is broken](http://en.wikipedia.org/wiki/MD5#Security) and **should not be used**. SHA256, which the OP already uses, at least insofar as I know, have no known significant vulnerabilities.
Answer: How about generating a hash from the info that's readily available from the file itself? i.e. concatenate :

File Name
File Size
Created Date
Last Modified Date

and create your own?
Comment: If it's used for security purposes, of course. If used only to identify files (which I thought was the intention), why not?
Comment: Rolling your own cryptography is a **very very bad idea**. People spend years on these things and get them wrong - what are the odds that the OP would do better? Additionally, the information you list (with the exception of file size) can very easily change while the file content remains exactly the same.
Answer: When you compute hashes and compare them, it would require both files to completely go through. My suggestion is to first check the file sizes, if they are identical and then go through the files byte by byte.
Comment: +1 to offset -1; including the size is a good idea for optimizing the check.
Answer: If you want a "quick and dirty" check, I would suggest looking at CRC-32. It is extremely fast (the algorithm simply involves doing XOR with table lookups), and if you aren't too concerned about collision resistance, a combination of the file size and the CRC-32 checksum over the file data should be adequate. 28.5 bits are required to represent the file size (that gets you to 379M bytes), which means you get a checksum value of effectively just over 60 bits. I would use a 64-bit quantity to store the file size, for future proofing, but 32 bits would work too in your scenario.
If collision resistance is a consideration, then you pretty much have to use one of the tried-and-true-yet-unbroken cryptographic hash algorithms. I would still concur with what Devils child wrote and also include the file size as a separate (readily accessible) part of the hash, however; if the sizes don't match, there is no chance that the file content can be the same, so in that case the computationally intensive hash calculation can be skipped.

Unique id for a file in C#


Drush is unable to update my site

Question: I'm trying to update my drupal core though drush. But how hard i trie, it won't work. I''m using drush pm-update but it fails. Below the output of the drush debug.
Tnx in advance
<code>Drush bootstrap phase : _drush_bootstrap_drupal_root() [0.05 sec, 4.34 MB]                                                                                [bootstrap]
Initialized Drupal 7.28 root directory at /var/www/my-site.nl-dev/web [0.06 sec, 5.95 MB]                                                                [notice]
Drush bootstrap phase : _drush_bootstrap_drupal_site() [0.07 sec, 5.96 MB]                                                                                [bootstrap]
Initialized Drupal site default at sites/default [0.12 sec, 6.47 MB]                                                                                [notice]
Drush bootstrap phase : _drush_bootstrap_drupal_configuration() [0.13 sec, 6.7 MB]                                                                           [bootstrap]
Drush bootstrap phase : _drush_bootstrap_drupal_database() [0.15 sec, 6.72 MB]                                                                               [bootstrap]
Successfully connected to the Drupal database. [0.15 sec, 6.72 MB]                                                                                [bootstrap]
Drush bootstrap phase : _drush_bootstrap_drupal_full() [0.16 sec, 7.55 MB]                                                                                [bootstrap]
Drush bootstrap phase : _drush_bootstrap_drupal_login() [1.12 sec, 41.71 MB]                                                                                [bootstrap]
Found command: pm-update (commandfile=pm) [1.21 sec, 42.14 MB]                                                                                [bootstrap]
Including /usr/share/drush/commands/pm/updatecode.pm.inc [1.21 sec, 42.17 MB]                                                                                [bootstrap]
Refreshing update status information ...
Done.
Update information last refreshed: ma, 07/28/2014 - 21:53

Update status information on all installed and enabled Drupal projects:
 Naam                       Geïnstalleerde versie  Proposed version  Status
 Alchemy                    7.x-1.0-beta1          7.x-1.0-beta1     Actueel
 Drupal core                7.28                   7.30              SECURITY UPDATE available
 Content Analysis           7.x-1.0-beta6          7.x-1.0-beta6     Actueel
 Context                    7.x-3.2                7.x-3.2           Actueel
 Chaos tool suite (ctools)  7.x-1.4                7.x-1.4           Actueel
 Keyword Research           7.x-1.0-alpha4         7.x-1.0-alpha4    Actueel
 Localization update        7.x-1.0                7.x-1.0           Actueel
 Metatag                    7.x-1.0-beta9          7.x-1.0-rc1       Nieuwe versie beschikbaar
 Nice Menus                 7.x-2.5                7.x-2.5           Actueel
 Piwik Web Analytics        7.x-2.5                7.x-2.5           Actueel
 Site map                   7.x-1.2                7.x-1.2           Actueel
 Site verification          7.x-1.1                7.x-1.1           Actueel
 Superfish                  7.x-1.9                7.x-1.9           Actueel
 Token                      7.x-1.5                7.x-1.5           Actueel
 Webform                    7.x-3.20               7.x-3.20          Actueel
 Wysiwyg                    7.x-2.2                7.x-2.2           Actueel
 XML sitemap                7.x-2.0                7.x-2.0           Actueel
 Busy                       7.x-1.5                7.x-1.5           Actueel

NOTE: A code update for the Drupal core is available.
Drupal core will be updated after all of the non-core modules are updated.

Code updates will be made to the following projects:
WD php: Notice: Undefined variable: print in pm_update_packages() (line 237 of /usr/share/drush/commands/pm/updatecode.pm.inc). [1.27 sec, 43.04 MB]            [notice]
Metatag [metatag-7.x-1.0-rc1]

Note: Updated projects can potentially break your site. It is NOT recommended to update production sites without prior testing.
Note: A backup of your package will be stored to backups directory if it is not managed by a supported version control system.
Note: If you have made any modifications to any file that belongs to one of these projects, you will have to migrate those modifications after updating.
Do you really want to continue? (y/n): y
Starting to update Metatag code at sites/all/modules/metatag... [13.69 sec, 43.02 MB]                                                                           [notice]
Executing: svn info '/var/www/my-site.nl-dev/web/sites/all/modules/metatag' [13.69 sec, 43.03 MB]                                                        [notice]
  svn: '/var/www/my-site.nl-dev/web/sites/all/modules/metatag' is not a working copy
Calling mkdir(/var/www/my-site.nl-dev/web/backup, 511)
Calling mkdir(/var/www/my-site.nl-dev/web/backup/modules, 511)
Calling mkdir(/var/www/my-site.nl-dev/web/backup/modules/20140729205514, 511)
Calling rename(/var/www/my-site.nl-dev/web/sites/all/modules/metatag, /var/www/my-site.nl-dev/web/backup/modules/20140729205514/metatag)
Downloading project metatag ... [13.92 sec, 43.05 MB]                                                                                [notice]
Executing: wget -P . http://ftp.drupal.org/files/projects/metatag-7.x-1.0-rc1.tar.gz [13.92 sec, 43.06 MB]                                                      [notice]
  --2014-07-29 20:55:28--  http://ftp.drupal.org/files/projects/metatag-7.x-1.0-rc1.tar.gz
  Resolving ftp.drupal.org... 188.8.131.52
  Connecting to ftp.drupal.org|220.127.116.11|:80... connected.
  HTTP request sent, awaiting response... 200 OK
  Length: 87802 (86K) [application/x-gzip]
  Saving to: "./metatag-7.x-1.0-rc1.tar.gz"

       0K .......... .......... .......... .......... .......... 58%  104K 0s
      50K .......... .......... .......... .....                100%  221K=0.6s

  2014-07-29 20:55:29 (133 KB/s) - "./metatag-7.x-1.0-rc1.tar.gz" saved [87802/87802]

Downloading metatag-7.x-1.0-rc1.tar.gz was successful. [14.92 sec, 43.06 MB]                                                                                [notice]
Md5 checksum of metatag-7.x-1.0-rc1.tar.gz verified. [14.92 sec, 43.06 MB]                                                                                [notice]
Executing: gzip -d metatag-7.x-1.0-rc1.tar.gz [14.92 sec, 43.06 MB]                                                                                [notice]
Executing: tar -xf metatag-7.x-1.0-rc1.tar [14.95 sec, 43.06 MB]                                                                                [notice]
Calling unlink(metatag-7.x-1.0-rc1.tar)
Project metatag was updated successfully. Installed version is now 7.x-1.0-rc1.
Backups were saved into the directory /var/www/my-site.nl-dev/web/backup/modules/20140729205514/metatag. [15.02 sec, 43.06 MB]                        [ok]
Including /usr/share/drush/commands/core/clear.cache.inc [15.02 sec, 43.06 MB]                                                                               [bootstrap]
Including /usr/share/drush/commands/core/clear.cache.inc [15.02 sec, 43.08 MB]                                                                               [bootstrap]
Including /usr/share/drush/commands/core/clear.cache.inc [15.02 sec, 43.09 MB]                                                                               [bootstrap]
Including /usr/share/drush/commands/core/clear.cache.inc [15.02 sec, 43.09 MB]                                                                               [bootstrap]
Including /usr/share/drush/commands/core/clear.cache.inc [15.02 sec, 43.09 MB]                                                                               [bootstrap]
Including /usr/share/drush/commands/core/clear.cache.inc [15.02 sec, 43.09 MB]                                                                               [bootstrap]
Including /usr/share/drush/commands/core/clear.cache.inc [15.02 sec, 43.09 MB]                                                                               [bootstrap]
Calling call_user_func(drupal_flush_all_caches)
'all' cache was cleared [16.99 sec, 49.06 MB]                                                                                [success]
Undefined variable: print in pm_update_packages() (regel 237 van /usr/share/drush/commands/pm/updatecode.pm.inc). [16.99 sec, 49.06 MB]                         [notice]
Including /usr/share/drush/commands/pm/updatecode.pm.inc [17 sec, 48.88 MB]                                                                                [bootstrap]
Refreshing update status information ...
Done.
Update information last refreshed: ma, 07/28/2014 - 21:53

Update status information on all installed and enabled Drupal projects:
 Naam                       Geïnstalleerde versie  Proposed version  Status
 Alchemy                    7.x-1.0-beta1          7.x-1.0-beta1     Actueel
 Drupal core                7.28                   7.30              SECURITY UPDATE available
 Content Analysis           7.x-1.0-beta6          7.x-1.0-beta6     Actueel
 Context                    7.x-3.2                7.x-3.2           Actueel
 Chaos tool suite (ctools)  7.x-1.4                7.x-1.4           Actueel
 Keyword Research           7.x-1.0-alpha4         7.x-1.0-alpha4    Actueel
 Localization update        7.x-1.0                7.x-1.0           Actueel
 Metatag                    7.x-1.0-beta9          7.x-1.0-rc1       Nieuwe versie beschikbaar
 Nice Menus                 7.x-2.5                7.x-2.5           Actueel
 Piwik Web Analytics        7.x-2.5                7.x-2.5           Actueel
 Site map                   7.x-1.2                7.x-1.2           Actueel
 Site verification          7.x-1.1                7.x-1.1           Actueel
 Superfish                  7.x-1.9                7.x-1.9           Actueel
 Token                      7.x-1.5                7.x-1.5           Actueel
 Webform                    7.x-3.20               7.x-3.20          Actueel
 Wysiwyg                    7.x-2.2                7.x-2.2           Actueel
 XML sitemap                7.x-2.0                7.x-2.0           Actueel
 Busy                       7.x-1.5                7.x-1.5           Actueel

Code updates will be made to drupal core.
WARNING:  Updating core will discard any modifications made to Drupal core files, most noteworthy among these are .htaccess and robots.txt.  If you have made any modifications to these files, please back them up before updating so that you can re-create your modifications in the updated version of the file.
Note: Updating core can potentially break your site. It is NOT recommended to update production sites without prior testing.
Do you really want to continue? (y/n): y
Executing: svn info '/var/www/my-site.nl-dev/web/drupal-7.30' [30.11 sec, 49.21 MB]                                                                      [notice]
  svn: '/var/www/my-site.nl-dev/web/drupal-7.30' is not a working copy
Calling mkdir(/var/www/my-site.nl-dev/web/backup, 511)
Drush command could not be completed. [30.16 sec, 49.25 MB]
</code>
Answer: You didn't show the command line that you're running, but it looks like you're using the various --svn* options to pm-update.  I don't think these are working well right now; try to do the update without them, and do your version control operations by hand after the update completes.
Comment: Just for more clarity... Drush 7 and later are not compatible with directories that are controlled by SVN.

Drush is unable to update my site


Are these two 2D datasets the same and can they be separated with the XOR NN?

Question: I'm a very beginner in the neural network topic. So I ran into a problem.
I see on the online lectures:
Famous example of a simple non-linearly separable data set, the XOR problem (Minsky 1969) in the right figure. but what about the left ones? is it same?
Can we used XOR NN for separate both of them? (is it same or not 2D datasets)?
I means with general neuron like as McCulloch is it possible via 3 nodes excepts input?
Comment: It has already been answered... what is the problem ?
Comment: The second data set seems rotated by 45°... they should be equivalent.
Answer: If you have a simple neural network which separates some data $\{x_i\}$, and it has a fully connected first layer with weight matrix $W$, and then you apply some invertible linear transform $x' = Ax$ to the data, then $Wx = WA^{-1}x'$, which is to say that if you use the weights $WA^{-1}$ on the transformed data, you'll get the same outputs.
Answer: If, as lcrmorin says in his/her comment, one set is essentially equivalent to the other, only rotated by 45°, then I agree with shimao's answer.
It is, however, not that clear from the figures whether this equivalence is given. It boils down to the question whether you can enclose one class in a convex area, so than no points from the other class are enclosed.
Concretely, for your datasets, this is equivalent to asking whether you can, in your left figure, draw two straight lines (blue (A) and orange (B)), so that all and only black triangles are between them:
If yes, then the two sets (figure left and figure right) are equivalent and you can use the same network to classify both sets. In the right figure, it is obvious that all and only the red crosses are between the two lines. The area between the two lines is convex (for any two points from the area, all points on the straight line connecting them are also in the area). From the classification point of view, the two sets are equivalent, the one is basically a 45 degrees rotated version of the other.
However, if you cannot draw such two lines (notice how both lines touch both the triangles and the circles), then the left dataset is somewhat more complicated: Each class is non-convex, has to be split into multiple convex subclasses, which then need to be combined. The network will need one more layer to achieve this.
Why is it so? First, recall that each neuron implies a linear boundary: $\textbf{w} \cdot \textbf{x} + b_0$ is a linear function of the neuron inputs $\textbf{x}$, the weights $\textbf{w}$ and the bias $b_0$. The set of all ${\textbf{x}}$ where this function is zero is, in 2D-case, a straight line. In a neuron, we typically pass the result of $\textbf{w} \cdot \textbf{x} + b_0$ through a non-linear activation function $f(\cdot)$. In case of classification, this is commonly some sigmoid function, but, for the discussion here, we can equally well assume it to be the step function: $f(x) = 0$ for $x < 0$ and $1$ otherwise.
Second, recall that you can construct boolean operators with such neurons. In the image below, the point (1, 1) is on one ("positive") side of the blue line (A), while all other points, (0, 0), (0, 1) and (1, 0) are on the other. If your neuron outputs 1 for the input (1, 1) and zero otherwise, you can consider it performing the logical "AND". Similarly, a neuron outputting zero for (0, 0) and one otherwise performs the logical "OR". And, a boolean "NOT" of some input $x$ is simply $1-x$.

Now, the classification rule for your right dataset (below) is pretty simple: The class is "red crosses" if it is between the blue and the orange line, and "green circles" otherwise:
You need only three neurons to implement it:

one to output 1 if the input is below (on the '+' side of) the blue line (A)
one to output 1 if the input is above (on the '+' side of) the orange line (B), and
one to perform the logical "AND" of (1) and (2).

That would be your "3 node NN".
However, for the left dataset, it is more complex: The class is "black triangles" IFF the input is (above the blue AND above the orange line) OR (below the blue AND below the orange line). You need five neurons to implement this:

one to output 1 if the input is above (on the '+' side of) the blue line (A),
one to output 1 if the input is above (on the '+' side of) the orange line (B),
one to perform the logical "AND" of (1) and (2),
one to perform the logical "AND" of (NOT 1) and (NOT 2), and
one to perform the logical "OR" of (3) and (4).

This would be your "2*2*1", "5 node NN".
In general, a three-layer perceptron, with each layer being sufficiently large, can perfectly represent any classification of the points:

it the first, linear boundaries between subsets of the data are defined;
in the second, these boundaries are combined by "AND" operators to form convex areas; and
in the third, these convex areas are combined by "OR" operators to achieve arbitrarily-shaped classes.
Comment: @MaryamPanahi I followed your link and read Martin Jansche's answer on Quora, posted today, but I don't know how do you want me to update my answer. Martin's answer is congruent with mine.
Comment: This answer is also congruent with mine at: https://datascience.stackexchange.com/questions/86000/one-challenging-neural-network-question-and-matlab-simulation/86069#86069


Calculate the closure and the interior of this set

Question:
Consider the set $A=\{m+n\pi:m,n\in\mathbb{N}\}$ in $(\mathbb{R},d_u)$

Where $d_u$ is the usual distance. The exercise asks to calculate the closure, interior and boundary of that set.
Now, intuitively, it seems to me that the set is closed, and hence its closure is $A$, and also that its interior is empty, hence the boundary being $A$ as well.
The problem is that I don't know how to formalize this properly. i.e. I've tried considering a point $p\notin A$ and showing that there exists an open ball centered at $p$ that doesn't intersect $A$, but I can't find which radius to use.
I've also tried to show that its not possible to create a sequence of points from $A$ that converges to a point that is not in $A$, but again, I'm failing at the time of formalizing this.
Any help will be appreciated.
Answer: Show that $ n\pi -[n\pi]$ is dense in $[0,1]$ where $[n \pi]$ denotes the floor function - that's a classic exercise. This shows that the closure of your set $A$  is the whole of $\mathbb{R}$ because you can use the $m$ term to be $(k - [n\pi])$ for any integer $k$. $A$ is countable hence has empty interior which answers the other questions, so in fact the only trick is to observe the density thing
Edit:
right, sorry, I assumed $n$ and $m$ were just integers, not necessary positive, my bad. anyway in case of natural numbers the question isn't so nice. you can easily see that for any interval $[0, T]$ with $T < \infty$ there are only finitely many elements of $A$ that can be in that interval (because you can just bound $m \leq T$ and $n \leq T/\pi$ which gives you finitely many possibilities. Therefore no point from $[0,T]$ (or $[0, T-1]$ if we want to be super cautious) that isn't in $A$ can be a limit point of $A$ so $A$ is closed. as we've noticed before it's countable hence has empty interior. Nevertheless - I advise you strongly to check out the modified problem with integer $m,n$ and try to justify my previous solution - it's a really nice exercise
Comment: right, my bad, I've edited the answer, but still - check out the problem I originally had in mind, you won't regret, I promise!
Comment: Wait a sec, wouldn't that be the case if we were considering integer numbers in general? How can negative numbers be in the closure if all terms here are possitive? Remember $m,n\in\mathbb{N}$. Is that reasoning still correct? If so I'm probably missing something big here!
Comment: Oh I see, bounding the set solves it. And thanks for the modified version, it certainly does seem more interesting ;)


Delphi: load large files with SynEdit

Question: "I would recommend switching to another edit control like SynEdit(it can load 80 mb of text file in few miliseconds)." - more memory for TMemo / TRichEdit
Is it possible?
To load 1,5 Mb takes me 8 sec...
My previous post: Delphi: Form becomes Frozen while assigning strings in thread
I have Delphi 2010 and UniSynEdit for Delphi 2009.
Thanks!
Comment: Maybe you need a faster edit control. Notepad++ loads large files like that much faster. It's based on Scintilla. I believe there are Delphi bindings for Scintilla.
Comment: what happened here, is this a new question or did something go wrong?
Answer: The backend of SynEdit is a TStrings descendant which loads EVERYTHING IN ONE GO if you just use
<code>ASynEdit.Lines.LoadFromFile
</code>
You could use on demand loading (i.e. just load visible lines, perhaps with 10 lines before and after) but you have to handle it yourself.
Comment: Are you loading it from USB or something? Thats horrendously slow
Comment: From HD. Did you try? Try in regular Notepad.
Comment: hmm... maybe I'm not clear enough. I mean, DON'T use `ASynEdit.Lines.LoadFromFile` as it will load the whole file, you have to use on demand loading technique which should only load the visible parts of the file

Delphi: load large files with SynEdit


Select Drop-down list item in Word document with Powershell

Question: I'm working on a powershell script that opens Word documents as COM objects and edits them using content controls. Each content control is identified by the titles assigned to it in the Word document. I'm able to edit text boxes and check boxes, but I can't figure out how to change which item is selected in a dropdown list in the Word document.
Here's an example of the code I've tried that successfully changes the text box and check box, but isn't working for the dropdown list. All the documentation I've seen seems to be for VBA, so I don't know how to interact with the dropdown list using powershell. This was my best guess after poking around in the com object to see what properties the content controls have.
<code>$filename = "C:\Path\File.docx"
$wordPg1 = New-Object -comobject Word.Application
$wordPg1.Visible = $False
$Page1Doc = $wordPg1.documents.open($filename)
$Page1Fields = $Page1Doc.ContentControls

           foreach($field in $Page1Fields)
           {
               switch ( $field.Title )
               {
                   # These two work
                   "Text Box"      { $field.Range.Text = "1234" }
                   "Check Box"     { $field.Checked = $TRUE }
                   # This one doesn't work
                   "Dropdown"      { $field.DropdownListEntries.Index = 2 }
               }
           }

$SaveAsFileName = "C:\Path\FileEdited.docx"
$Page1Doc.SaveAs([ref]$SaveAsFileName)

$Page1Doc.Close()
$wordPg1.Quit()
$null = [System.Runtime.InteropServices.Marshal]::ReleaseComObject($wordPg1)
</code>
This gives the error
Exception setting "Index": "The property 'Index' cannot be found on this object. Verify that the property exists and can be set."
Answer: I found the correct phraseology that I was looking for. This now works properly and selects the second item in the dropdown list.
<code>$filename = "C:\Path\File.docx"
$wordPg1 = New-Object -comobject Word.Application
$wordPg1.Visible = $False
$Page1Doc = $wordPg1.documents.open($filename)
$Page1Fields = $Page1Doc.ContentControls

           foreach($field in $Page1Fields)
           {
               switch ( $field.Title )
               {
                   # These two work
                   "Text Box"      { $field.Range.Text = "1234" }
                   "Check Box"     { $field.Checked = $TRUE }
                   # This will now select the second item in the dropdown list
                   "Dropdown"      { $field.DropdownListEntries.Item(2).Select() }
               }
           }

$SaveAsFileName = "C:\Path\FileEdited.docx"
$Page1Doc.SaveAs([ref]$SaveAsFileName)

$Page1Doc.Close()
$wordPg1.Quit()
$null = [System.Runtime.InteropServices.Marshal]::ReleaseComObject($wordPg1)
</code>


What error currently exists in the ssl.cnf file or code that is leading to the following output in zsh?

Question: Recently I was working on a project that utilized the Alexa AVS Sample App (the one written in java, and currently in maintenance mode: https://github.com/alexa/alexa-avs-sample-app/wiki/Mac#4---generating-self-signed-certificates) and when I was attempting to follow the given instruction:

Edit the ssl.cnf configuration file with your favorite text editor. Replace any placeholder values that start with YOUR_.
  Note: countryName must be two characters (e.g. US). If it is not two characters, certificate creation will fail. Additionally, if you will be accessing your device from any IP or DNS entry besides localhost (127.0.0.1 or 10.0.2.2), you must add the additional IP or or DNS entries to [alt_names]. One situation where you will need to add entries to [alt_names] is if you are going to authenticate using an Android or iOS companion app from a device instead of from the Android or iOS emulators on the same machine as the Node.js server and sample app.

I edited the file as said, and not sure if I did do it correctly, but her goes:
<code>[req]
distinguished_name      = req_distinguished_name
prompt                  = no

[v3_req]
subjectAltName          = @alt_names

[alt_names]
DNS.1                   = localhost
IP.1                    = 127.0.0.1
IP.2                    = 10.0.2.2

[req_distinguished_name]
commonName              = $ENV::COMMON_NAME                 # CN= Random
countryName             = YOUR_COUNTRY_NAME                 # C= US
stateOrProvinceName     = YOUR_STATE_OR_PROVINCE            # ST= CA
localityName            = YOUR_CITY                         # L= San Francisco
organizationName        = YOUR_ORGANIZATION                 # O= VEor
organizationalUnitName  = YOUR_ORGANIZATIONAL_UNIT          # OU= VE
</code>
I also did previously replace the YOUR_ORGANIZATION and etc. with the country codes and etc. themselves, like the following:
<code>[req]
distinguished_name      = req_distinguished_name
prompt                  = no

[v3_req]
subjectAltName          = @alt_names

[alt_names]
DNS.1                   = localhost
IP.1                    = 127.0.0.1
IP.2                    = 10.0.2.2

[req_distinguished_name]
commonName              = $ENV::COMMON_NAME                 # CN= Random
countryName             = US                 # C=
stateOrProvinceName     = CA            # ST=
localityName            = San Francisco                         # L=
organizationName        = VEor                 # O=
organizationalUnitName  = VE
</code>
Yet, I still get this output:
<code>❯ ./generate.sh
Generating RSA private key, 4096 bit long modulus
...........................++
.........................................................................................................................................................................................................................................++
e is 65537 (0x10001)
error on line 14 of ssl.cnf
140736175395720:error:0E065068:configuration file routines:STR_COPY:variable has no value:/BuildRoot/Library/Caches/com.apple.xbs/Sources/libressl/libressl-22/libressl/crypto/conf/conf_def.c:573:line 14
Generating RSA private key, 2048 bit long modulus
...........+++
........+++
e is 65537 (0x10001)
error on line 14 of ssl.cnf
140736175395720:error:0E065068:configuration file routines:STR_COPY:variable has no value:/BuildRoot/Library/Caches/com.apple.xbs/Sources/libressl/libressl-22/libressl/crypto/conf/conf_def.c:573:line 14
certs/client/client.csr: No such file or directory
Error opening input file certs/client/client.crt
certs/client/client.crt: No such file or directory
Generating RSA private key, 2048 bit long modulus
......................................................................................................................................+++
....+++
e is 65537 (0x10001)
error on line 14 of ssl.cnf
140736175395720:error:0E065068:configuration file routines:STR_COPY:variable has no value:/BuildRoot/Library/Caches/com.apple.xbs/Sources/libressl/libressl-22/libressl/crypto/conf/conf_def.c:573:line 14
certs/server/node.csr: No such file or directory
Generating RSA private key, 2048 bit long modulus
....+++
...................................+++
e is 65537 (0x10001)
error on line 14 of ssl.cnf
140736175395720:error:0E065068:configuration file routines:STR_COPY:variable has no value:/BuildRoot/Library/Caches/com.apple.xbs/Sources/libressl/libressl-22/libressl/crypto/conf/conf_def.c:573:line 14
error on line 14 of config file 'ssl.cnf'
Error opening input file certs/server/jetty.crt
certs/server/jetty.crt: No such file or directory
cp: certs/ca/ca.crt: No such file or directory
Error opening Certificate certs/ca/ca.crt
140736175395720:error:02001002:system library:fopen:No such file or directory:/BuildRoot/Library/Caches/com.apple.xbs/Sources/libressl/libressl-22/libressl/crypto/bio/bss_file.c:255:fopen('certs/ca/ca.crt', 'r')
140736175395720:error:20074002:BIO routines:FILE_CTRL:system lib:/BuildRoot/Library/Caches/com.apple.xbs/Sources/libressl/libressl-22/libressl/crypto/bio/bss_file.c:257:
unable to load certificate
cp: certs/ca/ca.der: No such file or directory
</code>
What should I do differently to ensure it works?
Answer: please modify ur openssl directory in generate.sh
->/usr/local/opt/openssl/bin/openssl
https://github.com/alexa/alexa-avs-sample-app/issues/1004


Z-transforming Pearson correlation vs. converting to mutual information: they seem to be related, but how?

Question: EDIT: By noodling around a bit, I found that they can actually both be re-arranged into even more similar forms:
$Z = -\frac{1}{2}(\ln(1-\rho) - \ln(1+\rho))$
$I =-\frac{1}{2}(\ln(1-\rho) + \ln(1+\rho))$
This seems too similar to be just a coincidence.
Original question:
Given a Pearson correlation coefficient ρ, it is common to transform it using Fisher's Z-transform:
$z = \frac{1}{2}\ln(\frac{1+\rho}{1-ρ})$
I noticed that this is extremely similar to the formula for the conversion of a Pearson correlation coefficient to the mutual information (assuming only linear relationships):
$I = -\frac{1}{2}\ln(1-ρ^2)$
They are clearly of a similar form, but it's not entirely clear how the relate to each-other. It seems like the FIsher's Z is doing something like turning into the correlation into a "quasi-MI."
Does anyone have an intuitive explanation for what is happening here? Or know of any literature I can consult to dig into more of this?
Comment: Since, up to a choice of units of measurement of two jointly Normal variables, the *only* parameter left is $\rho,$ literally any property of their joint relationship must be a function of $\rho.$  From this perspective there's nothing surprising going on here.
Answer: So the equation that you presented for mutual information is valid only in the case that both $X$ and $Y$ are normally distributed. Theorem 2.1 of Gelfand and Yaglom (1957) proves this relationship. As noted in this paper the relationship between the correlation coefficient and the mutual information makes sense because both quantities seek to describe the joint dependence structure of $X$ and $Y$. Indeed, the two metrics are complimentary, both revealing different properties of the linear mutual dependence structure of the two random variables. This is clear from the functional form,
$$I(X,Y)=-0.5 \ln(1-\rho^2)$$
This shows that the mutual information goes to infinity if $\rho=\pm 1$. Thus, when there is complete covariance of the two variables. Note that Pearson's un-standardized correlation coefficient is essentially trying to capture the covariance. This relationship and its relationship to mutual information are further discussed in this previous answer. Essentially, the correlation coefficient is trying to quantify the linear correlation-covariance of $X$ and $Y$. The mutual information is essentially measuring how "non-independent" $X$ and $Y$ are. Under the Gaussian assumption, this measure boils down to a function of the linear relationship (Gelfand and Yaglom, 1957).
Furthermore, since you mention the Fisher transformation I figure I should shed some light on why we do this procedure. This transformation is essentially a variance stabilizing transformation. The sample correlation coefficient is given by,
$$r = \frac{\sum_i (X_i-\bar X)(Y_i - \bar Y)}{[\sum_i (X_i-\bar X)^2(Y_i - \bar Y)^2]^{1/2}}$$
Using the delta method it is possible (assuming some existence conditions for higher-order moments) to show that,
$$\sqrt{n}(r-\rho)\overset{d}{\to}N(0,(1-\rho^2)^2)$$
Notice that that variance depends on $\rho$ here. This is a rather undesirable trait especially if we want to build confidence sets since we do not know $\rho$. So what we do instead is to find a transformation, $\phi$, of the parameter that stabilizes the asymptotic variance so that we may build confidence sets. We want to find $\phi$  such that the asymptotic variance is constant and so we can usually calculate it as,
$$\phi(\theta)=\int \frac{1}{\sigma(\theta)}d\theta$$
Thus, the variance stabilizing transformation can be computed as,
$$\phi(r)=\int\frac{1}{1-r^2}d\rho=\frac{1}{2}\ln\frac{1+r}{1-r}$$
This is actually the arctanh function and it is the Fisher transformation. Notice that just like the Gaussian mutual information this function will approach positive or negative infinity when $r=\pm 1$.
Comment: I think perhaps you misunderstood my answer. I was trying to make the case that these two measures are *complimentary* in that they are essentially measuring different aspects of the mutual dependence of the two random variables. As I pointed out in the answer, complete correlation, $\rho=\pm 1$ sends $I\to\infty$. Again, you should also [read this answer](https://stats.stackexchange.com/a/81682/321865) which explains some more of the intuition behind the two quantities.
Comment: Thanks for you comment - it's nice to see how these are derived. Are there any specific connections between them (maybe some kind of transformation that turns one into the other, or an intuitive relationship between them?)

They can be re-arranged as:

$Z = -\frac{1}{2}(\ln(1-\rho) - \ln(1+\rho))$

$I =-\frac{1}{2}(\ln(1-\rho) + \ln(1+\rho))$

This seems too similar to be just a coincidence.


Parametros via xml para ImageView customizado

Question: Tenho um ImageView customizado, que irá funcionar como um Switch.
Na tela, terei vários deste item, mas de cores diferentes.
Gostaria de saber se é possível passar um parametro de cor na declaração do xml.
Exemplo:
<com.example.utils.SwitchCustom
        android:layout_margin="15dp"
        android:layout_width="150dp"
        android:layout_height="50dp"
        cordefundo="azul"/>

Obrigado!
Comment: você tentou android:background="@android:color/black" ?
Answer: É possível criar atributos customizados.
Par isso é necessário declarar um Attribute Resource:
Na pasta res/value crie um arquivo chamado attrs.xml com o seguinte conteúdo:
<resources>
   <declare-styleable name="SwitchCustom">
       <attr name="cordefundo" format="color" />
   </declare-styleable>
</resources>

No código java do SwitchCustom poderá aceder ao valor desse atributo no construtor SwitchCustom(Context context, AttributeSet attrs):
private int cordefundo;

public SwitchCustom(Context context, AttributeSet attrs){
    super(context, attrs);

    TypedArray a = context.getTheme()
                          .obtainStyledAttributes(attrs, R.styleable.SwitchCustom, 0, 0);

    try {
        cordefundo = a.getInteger(R.styleable.SwitchCustom_cordefundo, 0);
    } finally {
        a.recycle();
    }
}

Ao inserir o SwitchCustom num layout, para ter acesso ao atributo, tem de indicar, no layout, o namespace a que ele pertence:
xmlns:custom="http://schemas.android.com/apk/res/com.example.utils"

Exemplo para um LinearLayout:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              xmlns:custom="http://schemas.android.com/apk/res/com.example.utils">

    <com.example.utils.SwitchCustom
        android:layout_margin="15dp"
        android:layout_width="150dp"
        android:layout_height="50dp"
        custom:cordefundo="@android:color/blue"/>

</LinearLayout>

Comment: Muito Obrigado!


I have an error of array_pop(): Argument #1 ($array) must be of type array, null given using PHP 8.2.7 and laravel 10.13.5

Question: I am learning laravel and php from laracasts tutorials. In episode 35 i have an error happen. It is an array error .
Error Message shown on the browser is given below:

TypeError array_pop(): Argument #1 ($array) must be of type array, null given

The error is caused by this line
{{ isset($currentCategory) ? ucwords($currentCategory -> name) : 'Categories' }}

The code is given below
My C:\Users\Admin\app-first\resources\views_posts-header.blade.php

            Latest Laravel From Scratch News

By Lary Laracore

            Another year. Another update. We're refreshing the popular Laravel series with new content.
            I'm going to keep you guys up to speed with what's going on!

                <x-dropdown>
                    <x-slot name ="trigger"  >
                        <button class="py-2 pl-3 pr-9 text-sm font-semibold w-full lg:w-32 text-left flex lg:inline-flex">
                            {{ isset($currentCategory) ? ucwords($currentCategory -> name) : 'Categories' }}
                            <svg class="transform -rotate-90 absolute pointer-events-none" style="right: 12px;" width="22" height="22" viewBox="0 0 22 22">
                                <g fill="none" fill-rule="evenodd">
                                    <path stroke="#000" stroke-opacity=".012" stroke-width=".5" d="M21 1v20.16H.84V1z">
                                    </path>
                                    <path fill="#222" d="M13.854 7.224l-3.847 3.856 3.847 3.856-1.184 1.184-5.04-5.04 5.04-5.04z"></path>
                                </g>
                            </svg>
                        </button>
                    </x-slot>

                                All

                                @foreach ($categories as $category )
                                     slug }}"
                                    class="
                                    block text-left px-3 text-sm leading-6
                                    hover:bg-blue-500 focus:bg-blue-500 hover:text-white focus:text-white
                                    {{ isset($currentCategory) && $currentCategory -> is( $category )  ? 'bg-blue-500 text-white' : '' }}
                                    " >
                                    {{ ucwords( $category -> name ) }}

                                @endforeach
                </x-dropdown>

                <select class="flex-1 appearance-none bg-transparent py-2 pl-3 pr-9 text-sm font-semibold">
                    <option value="category" disabled selected>Other Filters
                    </option>
                    <option value="foo">Foo
                    </option>
                    <option value="bar">Bar
                    </option>
                </select>

                <svg class="transform -rotate-90 absolute pointer-events-none" style="right: 12px;" width="22" height="22" viewBox="0 0 22 22">
                    <g fill="none" fill-rule="evenodd">
                        <path stroke="#000" stroke-opacity=".012" stroke-width=".5" d="M21 1v20.16H.84V1z">
                        </path>
                        <path fill="#222" d="M13.854 7.224l-3.847 3.856 3.847 3.856-1.184 1.184-5.04-5.04 5.04-5.04z"></path>
                    </g>
                </svg>

                <form method="GET" action="#">
                    <input type="text" name="search" placeholder="Find something" class="bg-transparent placeholder-black font-semibold text-sm">
                </form>

C:\Users\Admin\app-first\resources\views\components\dropdown.blade.php
@props(['trigger'])

{{-- Trigger --}}

{{ $trigger }}

{{-- Links --}}

{{ $slot }}

Routes\web.php
Route::get('categories/{category:slug}', function(Category $category){ return view('posts', [
'posts' => $category->posts,
'currentCategory' => $category,
'categories' => Category::all(),
]);

How I can fix this error?
Comment: Can you share what your blade component looks like, at least the part that will go into the `x-slot name="trigger" `
Comment: @props(['trigger'])

    {{-- Trigger --}}

             {{ $trigger }}

    {{-- Links --}}

         {{ $slot }}

Comment: You need to [edit] your question please when you have an update. Code in comments is hard to read. Thankyou
Comment: Route::get('categories/{category:slug}', function(Category $category){

    return  view('posts', [
        'posts' => $category->posts,
        'currentCategory' => $category,
        'categories' => Category::all(),

    ]);
Comment: You render `{{ $trigger }}`. Are you sure that's correct? That will escape all HTML markup
Comment: Again... **edit your question**. Do not add code to the comments! Everything should be in one place, in the main post
Comment: I have added the code to the question post now it is clear. Also, it is the laracasts episode 35.
Comment: @apokryfos
  code is added now you can see
Comment: @ADyson
 What is the solution to this error?
Comment: Where are you getting this syntax from? You use `` but normally it should be `` then you use `@props([ 'trigger' ])` to indicate `trigger` is actually a data attribute (i.e. not a slot) then you render `{{ $trigger }}` which would also escape the markup if it were to actually work. Try doing (a) remove `@props` from your component, (b) change the slot to `` and (c) use `{!! $trigger  !!}` in your component
Comment: @apokryfos Thank You So much For Your help. Trying Your Steps Finally worked for Me. I  have continued my laracasts episodes. I have less knowledge of laravel and PHP, and it is my first time learning. So Your steps and method are correct for me. Thank You So Much apokryfos
Answer: I also faced this error, you must remove spaces from name attribute
before:
<x-slot name ="trigger"  >

after:
<x-slot name="trigger">

Answer: array_pop accept array as parameter and you passed null so you received this error, to resolve this pass array instead null
    $a=array("1","2","3");
    array_pop($a);
    print_r($a);


vsftpd, virtual users and permissions. Avoid using chmod 777?

Question: I am running vsftpd with Virtual Users (managed through a MySQL db). Each users home/default directory is owned by vsftpd:vsftpd.
I need to give a user read/write permissions to some website files, owned by apache:apache so they can make some changes. I did a bind mount for the web directory to a directory in the ftp user's home/default directory. When logging in, the user is not able to write to the web folder, unless I set files to 777.
Is it possible to set this up with making the directory and it's files 777? The web directory needs to be apache:apache in order for apache to work with it.
Answer: It should be possible to work with chmod 777 if the files are static. If the files get created dynamically or you don't want to give everybody access you can use ACLs. For that you need to activate ACLs if not active yet (mount option). Then you could set permissions like this:
setfacl -R -m user:apache:rwx -m default:user:apache:rwx /path/to/website/dir
setfacl -R -m user:ftp:rwx -m default:user:ftp:rwx /path/to/website/dir

These commands set write permissions recursively for the users ftp and apache so that they are inherited for new files.


Starting a Windows Service programmatically

Question: I have a quartz.NET project set up which should schedule a windows service to run every so often. Currently, I am trying to start the service like this:
Process.Start("path/app.exe");

But I'm getting: "Cannot start a service from the command line or a debugger. A Windows Service must first be installed and then started with the ServerExplorer, Windows Services Admin tool, or the NET START command.
So I'm wondering, first of all, will this go away in release mode? Or am I going to have to find another way to go about this. Either way, I need to be able to schedule this job programmatically.
Answer: The message tells you a few ways how to start the service, but those are not the right way to do it from C#. There is a better way: Use the System.ServiceProcess.ServiceController class to start the service.


3-regular graph maximum matching

Question: I'm trying to prove that any 3-regular undirected simple graph has a matching that covers at least $(\frac{7}{8}) |V(G)|$ vertices.
I know Petersen's Theorem, and have understood its proof. I think, it should be possible to modify the proof by considering the number of possible bridges and using the Tutte–Berge formula, but unfortunately I was not able to find a concrete argument, so I am thankful for any help with this problem.
Answer: To apply Tutte-Berge, we want to find a small set $U \subseteq V$ such that $G[V-U]$ has many odd components. There are two limitations on the number of odd components:

In an $n$-vertex graph, there are at most $n-|U|$ vertices to be split up between the odd components.
There are at most $3|U|$ edges from $U$ to the odd components, and each component needs some number of those edges.

Based on the second constraint, we can consider two kinds of odd components. Odd components of $G[V-U]$ with $1$ or $3$ vertices must have at least $3$ edges to $U$ (just by counting the maximum number of edges within a component), and odd components with at least $5$ vertices still must have at least $1$ edge to $U$ (since you can't have an odd component by itself in a $3$-regular graph).
Let $u = |U|$, let $x$ be the number of small odd components, and let $y$ be the number of large odd components. Then the two constraints are $$x + 5y \le n-u \qquad \text{and} \qquad 3x + y \le 3u.$$
Combining these with weights $\frac18$ and $\frac38$, we get $\frac54x + y \le \frac18n + u$, so $x + y \le \frac18 n + u$ as well. By the Tutte-Berge formula, the number of vertices covered by a maximum matching is the minimum of $n+u-x-y$ over all sets $U$, and we've shown that this always satisfies
$$
   n + u - x - y \ge n + u - (\tfrac18 n + u) = \tfrac78 n
$$
So the matching covers at least $\frac78n$ vertices.

3-regular graph maximum matching


Prove the inequality $a^2 + b^2 +c^2 \ge ab +bc +ac$

Question: How do I prove the inequality
\begin{equation*}
a^2 + b^2 +c^2 \ge ab +bc +ac
\end{equation*}
where $ a,b,c\in\mathbb{R} $ and $a,b,c>0$?
I obtained only $(a+b+c)^2\ge 3(ab+bc+ac)$   and some other variations
Comment: I managed to obtain only $(a+b+c)^2=3(ab+bc+ac)$
Comment: and some other variations
Comment: @Alexandru In your comment, do you mean an inequality? Otherwise that's false.
Comment: that is correct $(a+b+c)^2\ge 3(ab+bc+ac)$ thanks
Comment: This seems to be a duplicate of: [How to prove $a^2 + b^2 + c^2 \ge ab + bc + ca$?](http://math.stackexchange.com/questions/64868/how-to-prove-a2-b2-c2-ge-ab-bc-ca) (Hence I am voting to close as a duplicate.)
Answer: Note that $$a^2+b^2+c^2-ab-bc-ca=\frac{1}{2}\left((a-b)^2+(b-c)^2+(c-a)^2\right).$$
Comment: thank you it is a simple and good answer
Answer: multiply by $2$ ,then you have :
$$2a^2+2b^2+2c^2 ≥ 2ab+2bc+2ac\\ 2a^2+2b^2+2c^2 -( 2ab+2bc+2ac) ≥0\\(a^2+b^2-2ab)+(b^2+c^2-2bc)+(a^2+c^2-2ac)≥ 0\\$$
Comment: yes that is ingenious, thank you
Answer: Hint   We  have  $x^2+y^2 \geq 2 x y .$
Write down the three inequialities for $a, b$ and  $a,c$ and $b,c$  and then add them.
Answer: Another proof is: Consider $f(a) = a^2 -(b+c)a + b^2+c^2 -bc$ as a function of variable $a$. Observe that this is a quadratic polynomial with leading coefficient $1 > 0$. So all that you need to show is the discriminant $\triangle < 0$. Indeed, $\triangle = B^2-4AC = (b+c)^2 - 4(b^2+c^2-bc) = b^2+2bc+c^2 - 4b^2-4c^2+4bc = -3b^2-3c^2+6bc = -3(b-c)^2 \leq  0$. Thus $f(a) \geq0, \forall a \in \mathbb{R}$, and this implies the result...


Prove that $\varlimsup_{n\to\infty}(\max\{x_n,y_n\})=\max\{\varlimsup_{n\to\infty}x_n,\,\varlimsup_{n\to\infty}y_n\}$

Question: Prove, that $\varlimsup_{n \to \infty}(\max\{x_n, y_n\}) = \max\{\varlimsup_{n \to \infty} x_n,\, \varlimsup_{n \to \infty} y_n\}$.
Let $(x_n)$ and $(y_n)$ be bounded number sequences. Does also the following equality always stand $\varlimsup_{n \to \infty} (\min\{x_n, y_n\}) = \min\{\varlimsup_{n \to \infty} x_n, \,\varlimsup_{n \to \infty}y_n\}$?
In the proof, should I use upper limit monotonicity and/or upper limit description with partial sequences? Any tips or advice? I'm a little stuck and don't know where to begin.
Answer: You can write the max-function as $\frac{x_{n}+y_{n}+|x_{n}-y_{n}|}{2}$ . Show continuity and then u can pull limes into the max-function.


Matrix series which exhibits finitely many non-zero terms

Question: If $A=C-\frac{1}{2}C^2+\frac{1}{3}C^3-\frac{1}{4}C^4+\cdots$ where
C=$\left(
\begin{array}{ccc}
 0 & c & c^2 \\
 0 & 0 & c \\
 0 & 0 & 0 \\
\end{array}
\right)$
(i) I want to show that A possesses finitely many terms apart from $0$.
(ii) How can I compute A?
(iii) How can I also illustrate that $A-\frac{1}{2!}A^2+\frac{1}{3!}A^3-\frac{1}{4!}A^4+\cdots$ exhibits finitely many non-zero terms.
(iv) How can I also show that $A-\frac{1}{2!}A^2+\frac{1}{3!}A^3-\frac{1}{4!}A^4+\cdots=C$?
Comment: Compute  $C^2$ and $C^3$ and you should see the trick.
Answer: Hint:
You may suppose $c\ne0$. Rewrite $C$ as $\;c\begin{pmatrix}0&1&c\\0&0&1\\0&0&0\end{pmatrix}$, and check $C^3=0$, so $A$ is indeed a finite sum.
Answer: A strictly upper triangular matrix like $C$ is always nilpotent, meaning that $C^k=0$ for some finite $k$. More generally, $M^n=0$ for any $n\times n$ strictly upper (or lower) triangular matrix, then $C^3=0$ and
$$
A= C - \frac{1}{2}C^2.
$$
This answers (i) and (ii). As $A$ is a polynomial of a nilpotent matrix, it is itself nilpotent, what answers (iii). Now realize that $A^3=0$ and $A^2=C^2$, then
$$
A-\frac{1}{2}A^2=C-C^2\neq C.
$$
Thus (iv) is not correct.


Get default min and max default values in views exposed filter form element

Question: I have a views display that lists out content that meets a criteria defined by an exposed form. One of the filters is 2 values which a content attribute must be between. In views, I can define this as a default min and max value.
I would like to get these default values out as data attributes on the form fields for some javascript validation, and therefore will need to be able to get these as twig variables in the form element template, or set these as attributes in the form element preprocess.
The inputs initially have the value of the default min and max, but as soon as these are changed there is no way I can see to access the defaults.
How can I do this?
Answer: <code>function MYTHEME_preprocess_input(&$variables) {
  if (isset($variables['element']['#default_value'])){
    $variables['attributes']['data-default-value'] = $variables['element']['#default_value'];
  }
}
</code>


Compactar imagem ao fazer upload com laravel

Question: Gostaria de saber se alguém tem alguma ideia de como proceder para compactar imagem ao fazer upload, pois a imagem está ficando muito grande.
A rotina que estou usando atualmente é a que está abaixo:
public function providerUpdateDocuments() {
    $inputs = Input::all();
    $walker_id = Session::get('walker_id');

    foreach ($inputs as $key => $input) {
        $walker_document = WalkerDocument::where('walker_id', $walker_id)->where('document_id', $key)->first();
        if (!$walker_document) {
            $walker_document = new WalkerDocument;
        }
        $walker_document->walker_id = $walker_id;
        $walker_document->document_id = $key;

        if ($input) {
            $file_name = time();
            $file_name .= rand();
            $file_name = sha1($file_name);

            $ext = $input->getClientOriginalExtension();
            $input->move(public_path() . "/uploads", $file_name . "." . $ext);

            $local_url = $file_name . "." . $ext;

            // Upload to S3
            if (Config::get('app.s3_bucket') != "") {
                $s3 = App::make('aws')->get('s3');
                $pic = $s3->putObject(array(
                    'Bucket' => Config::get('app.s3_bucket'),
                    'Key' => $file_name,
                    'SourceFile' => public_path() . "/uploads/" . $local_url,
                ));

                $s3->putObjectAcl(array(
                    'Bucket' => Config::get('app.s3_bucket'),
                    'Key' => $file_name,
                    'ACL' => 'public-read'
                ));

                $s3_url = $s3->getObjectUrl(Config::get('app.s3_bucket'), $file_name);
            } else {
                $s3_url = asset_url() . '/uploads/' . $local_url;
            }

            $get = Walker::where('id', '=', $walker_id)->first();
            $pattern = "Olá, " . $get->first_name . ", ID " . $walker_id . " Documento enviado, aguarde a aprovação.";
            $subject = "Waiting for an Approval";
            /* email_notification('', 'admin', $pattern, $subject); */

            if (isset($walker_document->url)) {
                if ($walker_document->url != "") {
                    $icon = $walker_document->url;
                    unlink_image($icon);
                }
            }

            $walker_document->url = $s3_url;
            $walker_document->save();

            /* if ($walker_document->save()) {
              echo 'asdasd';
              } */
        }
    }

    $message = "Seus documentos foram atualizados com sucesso.";
    $type = "success";
    return Redirect::to('/provider/documents')->with('message', $message)->with('type', $type);
}

Alguém tem alguma ideia do que pode ser feito para reduzir o tamanho dessa imagem antes de fazer o upload ou até mesmo após o upload.
Valeu.
Abraço.
Comment: Você pode converter para `webp`; Utilizar o [ImageMagick](http://php.net/manual/en/book.imagick.php) e reduzir um pouco da qualidade; ou poderá utilizar softwares como `jpegoptim`, `optipng` e `pngquant`.
Answer: Sugiro utilizar o pacote Intervention Image, que tem integração com Laravel
Um exemplo simples que no upload altera a imagem e salva em disco:
<?php
    ...
    class MyController extends Controller

    public function uploadImage(Request $request) {
        // resizing an uploaded file
        Image::make(Input::file('photo'))->resize(300, 200)->save('foo.jpg');
    }

Comment: como descrito no manual http://image.intervention.io/api/resize, os parâmetros são width e height, (larg e alt), isso são em pixels ... logicamente o tamanho final vai alterar também
Comment: essa função resize() modifica o arquivo em pixels ou em bytes?


What does each graph quadrant mean with LDAvis plot in R?

Question: I write about the graph explained in this video that shows a big probability mass. It's a web-based interactive visualization of topics estimated using
Latent Dirichlet Allocation that is built using a combination of R and D3; the default for scaling the set of
inter-topic distances defaults to Principal Components, but other algorithms are also enabled.
This is the way that it finally shows with some data I found online and used to understand Latent Dirichlet Allocation topic modeling. As far as I understand, this graph is ideal to give out final names to each topic according to the frequency or relevance of each term given the topic but I've got two questions:
1. What would you simply say about topic 8 position on the graph? Meaning that I can't tell what each square represents in this graph, I can't tell in plain words what's the difference between topic 1 and 10, or topic 8 and 3, given their position on this graph?
2. What can you say about the big gray line in comparison with the red filling when lambda is 0? I think I get that when lambda is 1, it's meaning about plain frequency of the term in the whole corpus vs the frequency of the terms in that topic, but I'm not sure I get it with putting more weight in the ratio from red to gray: what is the gray line saying about that term and how is red contrasting?
You can get this for a model named lda_model$plot() found here.
I am looking for the main idea at least. If there is info I need to add please tell me.
Answer: The LDA Vis algorithm uses a Principal Component Analysis (PCA) to reduce N-dimensional vectors to 2D vectors and get these (x,y) coordinates. In short PCA will breakdown N variables to n < N which will describe best your original data set. It's not inherent to the LDA model, it is just a way to plot the topics and the distance among them.


Using node.js's prompt for user input?

Question: I'm working on a JS project running with node.js and I can't figure out how to get the prompt to work correctly for user input. I installed it from npm, followed the steps and I can get the program to prompt for user input but I can't store the result in a variable.
What I want is to prompt the user for his next move (up,down,left or right) every turn and use the result. I tried making a global move variable and affecting it in the prompt section, but it doesn't seem to work.
  var Moving = function(maxMoves){

    for(var n=maxMoves; n>0;){
        var move;
        var l;
        //This would prompt for a direction (up,down,left,right)
        move = prompt();
        //And this would prompt for the number of tiles to advance;
        l = prompt();
        Direction(move,l);
        n-=l;
    }
};

Comment: We cannot help you with code we cannot see. Reduce your problem to a [mcve], and put that in the question.
Comment: Duplicate of [*How can I take console input from a user in node.js?*](http://stackoverflow.com/questions/26683734/how-can-i-take-console-input-from-a-user-in-node-js) Please [search before posting.](/search?q=How+to+store+a+user+input+in+a+variable+in+node.js) More on searching [here](/help/searching).
Comment: Basically, independantly from my code, my question is simply: How to store a user input in a variable in node.js?
Answer: Using require('prompt') or require('readline') are both good, easy ways to do this, but I wanted to find THE EASIEST WAY, and I didn't care about whether it is synchronous or asynchronous. Finding it took me longer than it should have, so maybe I can save people some time if they read this before digging any further.
Here you go:
# npm install readline-sync

var readline = require('readline-sync');

var name = readline.question("What is your name?");

console.log("Hi " + name + ", nice to meet you.");

Disclaimer: I am just spreading the word, here are my sources:
https://teamtreehouse.com/community/how-to-get-input-in-the-console-in-nodejs
How to take in text input from a keyboard and store it into a variable?
Answer: When  you say "installed it from npm" I'm assuming you're referring to the prompt module from flatiron.
From their docs, as with most Node things, it looks like it exposes an asynchronous function, so you'll handle input inside the prompt callback:
var prompt = require('prompt');

  //
  // Start the prompt
  //
  prompt.start();

  //
  // Get two properties from the user: username and email
  //
  prompt.get(['username', 'email'], function (err, result) {
    //
    // Log the results.
    //
    console.log('Command-line input received:');
    console.log('  username: ' + result.username);
    console.log('  email: ' + result.email);
  });

Storing it in a variable would be no different than accessing it from the result object above, but realize that since it's async it'll only be reliable available inside that callback.
Comment: I'm still a bit confused. Considering it's async, I'm not sure how to store it in a variable I can use immediately. I tried using that template and adding _move = result;_, but then when I tried to _console.log(move)_, I got an _undefined_.
Comment: As I said, the variables will only be reliably available inside the prompt callback.  Again, this is an area where if you post your code we could more easily help you with specific advice.
Comment: yes, and you're not following my answer at all.  Once again. *this is asynchronous.  The only place the prompt results will be is inside the callback. *
Answer: you can use two packages readline and prompt
Here's a simple example with readline package https://nodejs.org/en/knowledge/command-line/how-to-prompt-for-command-line-input/
const readline = require('readline');
const rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout
});

rl.question('What is your name ? ', function (name) {
  rl.question('Where do you live ? ', function (country) {
    console.log(`${name}, is a citizen of ${country}`);
    rl.close();
  });
});

rl.on('close', function () {
  console.log('\nBYE BYE !!!');
  process.exit(0);
});

Here is an another example with prompt package. https://www.npmjs.com/package/prompt
const prompt = require('prompt');
prompt.start();
prompt.get(['username','email'], function (err, result) {
    console.log('Command-line input received:');
    console.log('  username: ' + result.username);
    console.log('  email: ' + result.email);
});

Answer: inquirer module has a prompt function.
Use
const { prompt } = require('inquirer');

prompt([array] | object | string ')

Using node.js's prompt for user input?


Zero-one linear programming with substitutable constraints

Question: Suppose $x_1, x_2, \ldots, x_n$ each take values zero or one and we want to solve the following linear programming problem:
$$
\min_{x_1,x_2,\ldots, x_n} f(x_1,x_2,\ldots,x_n)
$$
subject to a bunch of constraints. Suppose $f$ is linear.
Can I have one of those constraints be $x_1+x_2 \ne 1$ (or alternatively $x_1+x_2=0$ OR $x_1+x_2=2$)?
It's still a well-defined problem with a constraint like that, but can we use standard algorithms to solve it? In some sense, it seems conceptually pretty easy. My hope is that this is a pretty standard problem and one that can be easily worked with in Gurobi or CPLEX, but I've never had to work with a constraint like this before.
Comment: Solve the two problems: with $x_1+x_2=0$ and with  $x_1+x_2=2$. Then choose the better solution.
Comment: @user64494 That's true. In principle I could do that. In practice, though, if I have a lot of constraints like that, the number of problems to solve goes up exponentially.
Comment: "The feasible set would no longer be convex" but it never was. The feasible set was already ${0,1}^n$ to begin with.
Comment: @MichaelGrant. You're right. That's more misleading than helpful. I had in my mind that if the $x$'s were real then $x_1+x_2\ne1$ would make the feasible set convex, but that's not really applicable here.
Comment: True but most logical constraints can be represented using linear equations and inequalities. I am not sure of a binary constraint that cannot be.
Comment: Thanks -- that's useful to keep in mind.
Answer: The constraint is equivalent to saying $x_1=x_2$ so you can recast it into the problem:
$$\min_{x_2,\ldots,x_n} g(x_2,\ldots,x_n)$$
where
$$g(x_2,\ldots,x_n)=f(x_2,x_2,\ldots,x_n).$$
Comment: That's a useful way of thinking about it. And obvious -- not sure how it didn't occur to me! I would have a slight preference for keeping the constraint explicit in the problem (as in some cases it might be worth relaxing it), but this is a pretty good solution, which I'll accept unless a better one comes along shortly. Thanks!


How does Drupal handle autoloading of classes?

Question: How does Drupal handle autoloading of classes through modules? For instance, if I have an Events module, and I declare a class called Event, and then in the .info file I include the class file, how is this registered?
The problem is that I'm trying to dynamically get an array containing all loaded class names. get_declared_classes() does not return the names of all my classes declared in this manner, so I'm assuming that they're autoloaded somehow. Following the suggestions from another stack overflow question, I tried getting all of them with spl_autoload_functions(), but that was also unsuccessful.
Any ideas?
Answer: All files listed in .info files are parsed when modules are rebuild (Only changed/new files in that list are, for performance reasons).
That information is then stored in the {registry} and {registry_files} tables. So if you want to get all classes or those according to a given naming pattern, you can query those tables.
Answer: Drupal maintains a code registry and uses it for its classes autoloader. To populate this registry with your module's classes, you should add their files to the files[] entry in it's .info file:
files[] = includes/Foo.inc
files[] = includes/Bar.inc

PHP's class autoloading will make sure that the parent class file is also loaded.
Credit to user pier-buyle for this answer, see his original answer here for the same question.
Hope that helps
Answer: spl_autoload_functions() returns the list of the autoload functions that have been registered with spl_autoload_register(). Drupal registers two autoload functions: one for the classes (drupal_autoload_class()), and one for the interfaces (drupal_autoload_interface()).
Both the functions use _registry_check_code(); using its code, you can write a function that lists all the classes implemented by Drupal 7 modules.
Answer: If you have added an entry to the files[] array of the .info file, you will have to go to your modules administration section and click on "save configuration". This will get drupal to refresh the .info information, and the new entries will be registered.
Answer: I have found that declaring my include files in the info file does not get them recognized when I start running the module.  If I have a class Event in the file event.inc.  but crate an object in the module, it is not recognized.  I add the line
include_once ('CMatArticleHandler.inc');

prior to the $variable = new event(); line.  Im' new at this so there may be more to it then this, but it has worked so far.
Comment: Really unfortunate that people just downvote this instead of explaining what to do to avoid needing to do this. I am in the same situation: Drupal's autoloader is not consistently recognizing the need to load a file to get a class.
Comment: One needs to clear the registry when adding new classes. An easy way to do othis via drush is with this command:  https://www.drupal.org/project/registry_rebuild


Can I reference C++ code from KMM iosMain?

Question: I'm considering implementing KMM in my project.
I was able to reference C++ code via JNI in androidMain.
However, I was unable to use external fun in iosMain because it uses Kotlin/Native.
In existing iOS projects, it was possible to call Objective-C++ from Swift and reference C++ code from Objective-C++.
Is there a way to reference C++ code from iosMain?
Comment: Did you find a solution? I'm approaching the same problem. Currently I made it work on androidMain, but I not have any clue on iosMain
Comment: @Capps99 Sorry for the delay in answering. I have described the solution I found.
Answer: I made an effort to resolve the problem.
The first prerequisite is how the XCFramework is created.
C++ cannot be referenced directly in Swift.
Therefore, to create the XCFramework, it is necessary to wrap C++ in Objective-C++.
Next, create a def file.
Suppose we have a Bridge.XCFramework that wraps C++ with Objective-C++.
We name this def file framework.def.
language = Objective-C
modules = Bridge
package = Bridge

Modify Build.gradle.kts.
Make sure to load the corresponding framework for each architecture.
listOf(
    iosX64(),
    iosArm64(),
    iosSimulatorArm64()
).forEach {
    it.binaries.framework {
        baseName = "shared"
        xcf.add(this)
    }

    val myFrameworkCompilerLinkerOptssim = listOf(
        "-framework",
        "Bridge",
        "-F/{Path}/Bridge.xcframework/ios-arm64_x86_64-simulator"
    )
    val myFrameworkCompilerLinkerOpts = listOf(
        "-framework",
        "Bridge",
        "-F/{Path}/Bridge.xcframework/ios-arm64"
    )

    it.compilations.getByName("main") {
        val ZipArchive by cinterops.creating {
            defFile("src/nativeInterop/cinterop/framework.def")

            when (it) {
                iosArm64() -> compilerOpts(myFrameworkCompilerLinkerOpts)
                iosSimulatorArm64() -> compilerOpts(myFrameworkCompilerLinkerOptssim)
                else -> compilerOpts(myFrameworkCompilerLinkerOptssim)
            }
        }

        it.binaries.all {
            when (it) {
                iosArm64() -> linkerOpts(myFrameworkCompilerLinkerOpts)
                iosSimulatorArm64() -> linkerOpts(myFrameworkCompilerLinkerOptssim)
                else -> linkerOpts(myFrameworkCompilerLinkerOptssim)
            }
        }
    }
}

Synchronize Build.gradle.kts when done.
import is the name of the framework.
import Bridge.*

Now you can call C++ wrapped in Objective-C++ from iOSMain.


How do I change the uploading image file name

Question: How do I change the image name while uploading through a file uploading field? In drupal 8 whenever I add an image to a file field, it automatically uploads the image file to my S3 bucket. I need to change the image name before uploading because I need to list my image names with a specific pattern. I searched the internet but couldn't find a hook for that auto image uploading.
Answer: If you're uploading a file I'm assuming it's within a form, right? You could add a submit handler function using form_alter() (or override the submitForm() method) and change the file's name using the $form_state object's setValue() and getValue() methods I'm sure.
Comment: Unfortunately I can't do that because that file upload field is in a content type and as soon as I added the file to the file uploading field it gets uploaded to the S3 bucket. So practically I can't get it from submitForm().
Comment: Does it immediately send the file to S3 as soon as the user uploads?
Comment: Yes that is how the Drupal 8 file uploader works.
Comment: I'm not sure I understand. Did you build your D8 site from a pre-built setup on S3 or do you develop on a local machine and then deploy? I ask because I can't understand how it would immediately upload the file to S3 before you get the chance to modify it. Do you have an AWS/S3 module installed that does that for you?
Comment: It doesn't matter whether you use S3 or local file storage it always upload the files automatically to the server when selecting. You can create a content type and add a file field. You will see yourself.
Comment: Ah ok, just to clarify that your site's also on S3? Sorry, I was under the impression you were using S3 bucket purely for media storage and uploading the files to there from another server. If your whole site and file system is on S3, you should definitely be able to use hooks to modify the file name.
Comment: And also just to clarify you're using your browser's default file uploader rather than a JS driven one?
Comment: Only the uploading files are going to the S3. I searched but couldn't find any hook for this? Do you have any idea? I am using the default file uploader.
Comment: Surely there must be a contrib module that's doing this no? By default D8 just uploads the file to your local server's file system.
Comment: @iambatman are you using [Flysystem S3](https://www.drupal.org/project/flysystem_s3) OR [S3 File System](https://www.drupal.org/project/s3fs) contrib module?
Comment: I am using S3 File System @NoSssweat
Comment: It would be best to look at the File System module's code to see at what point it uploads to S3. It may be that it supplies its own hook you could use beforehand. If you don't find anything there, you could look at using hook_file_insert and arranging your module and the S3 module's weight in the system table. Module's with a greater weight are executed after those with a lower weight.


show hide accordion tabs depending on php variable session

Question: I am trying to show amount of accordion tabs depending on php variable present in session
I have a simple accordion (see bellow).
And I have a switch statement of variables (see bottom), I am trying to work out a easy way to display some of sections depending on the variable active withing the switch statement.
for example
if var1 present hide section2 and section3.
if var2 present hide section2.
One Idea I had (First Idea)
I could pop different accordions into different PHTML pages and include depending on the statement, but this is repeating code many times, I feel like there should be a more efficient method where I hide and show accordion tabs depending on the variable.
A different Idea I had (Second Idea)
give each section a class, then using the case statement hide the class
 <?php
        switch ($_SESSION['buy_test_session']) {
            case "var1":
             //--//
                break;
            case "var2":
                ?>

        <?php
                break;
            case "var3":
                //--/
                break;

If All else fails my Second Idea will work and ill go with that
My Current Code
accordion

Section 1

   text

Section 2

    text

Section 3

   text

Section 4

   text

Switch Statement
 <?php
            switch ($_SESSION['buy_test_session']) {
                case "var1":
                  //hide section 2 and 3//
                    break;
                case "var2":
                    //hide section 2//
                    break;
                case "var3":
                  //--//
                    break;
                case "var4":
                         //--//
                    break;

                default:
                    echo "Normal";
            }
            ?>

Comment: Try looking at this: http://stackoverflow.com/questions/1899307/jquery-ui-accordion-activate
Comment: Thanks @Dean.DePue ill investigate into the solution
Answer: simple fix, just populate each tab with a class and depending on the session hide.
<?php
    switch ($_SESSION['buy_test_session']) {
        case "var1":
         //--//
            break;
        case "var2":
            ?>

    <?php
            break;
        case "var3":
            //--/
            break;


Showing the scheme is smooth near generic point

Question: The question comes from Liu's book :
2.9. Let $X$, $Y$ be locally Noetherian integral schemes. Let $f : X \to Y$ be a dominant morphism of finite type. We say that $f$ is generically separable (resp. generically étale) if $k(X)/k(Y)$ is a separable (resp.finite separable) extension.
(a) Show that if $f$ is generically separable (resp. generically étale), then there exists a non-empty open subset $U$ of $X$ such that $f|_{U} : U \to  Y$ is smooth (resp. étale).

First we say that a finitely generated extension $K$ of $k$ (i.e. $K = k(f_{1}, ..., f_{n})$ for some $f_{i} \in K$) is separable if K is finite separable over a purely transcendental extension of k. This is equivalent of saying that Then $\Omega_{K/k}^{1}$ is a K-vector space of dimension $\operatorname{trdeg}_{k}K$.
Now what I've done .
Let $\xi, \xi'$ the respective generic points of de $X, Y$. Let $n := \operatorname{trdeg}_{K(Y)}K(X)$. We can suppose $X = Spec(A)$ and $Y = Spec(B)$. Being generically separable (respectively generically étale) is equivalent to $\dim_{K(X)}\Omega^{1}_{K(X)/K(Y)} = n$ (respectively $\dim_{K(X)}\Omega^{1}_{K(X)/K(Y)} = 0$ ). If I show $f$ is smooth at $\xi$ (respectively étale at $\xi$) it would be ok since the set of points where $f$ is smooth (respectively étale) is open. But we have, $\Omega^{1}_{K(X)/K(Y)} = \Omega^{1}_{\mathcal{O}_{X, \xi}/\mathcal{O}_{Y, \xi'}}$. So,being generically separable (respectively generically étale) implies $\Omega^{1}_{X/Y}$ is a locally free in a neighborhood of $\xi$ of rank $n$ (respectively is a locally zero in a neighborhood $\xi$). This comes from exercise $1.12.$ $(a)$ page $173$  of the book and from the coherence of $\Omega_{X/Y}^{1}$ (since $f$ is of finite  type).
Hence for all $x \in X_{\xi'}$, $\Omega^{1}_{\mathcal{O}_{X, x}/\mathcal{O}_{Y, \xi'}} \simeq \Omega^{1}_{X_{\xi'}/k(\xi'), x} \otimes k(x)$ by the exercice $2.5.$ $(b)$ page $226$. Now I don't know what to do?
Comment: What is your definition of smoothness?
Comment: I'm not sure how you can show such a statement without some sort of openness property (eg "the set of points at which $f$ is étale is open", or maybe replace "étale" with "flat"). Anyway, I think the smooth case follows from the étale case, because after shrinking $X,Y$, you can assume that $f$ comes from a generically étale $X \rightarrow \mathbb{A}^n_Y$.
Comment: Let $X, Y$ be two locally noetherian schemes. We say $f : X \mapsto Y$ is smooth at $x$ if the fiber $X_{f(x)}$ (which is a $k(f(x))$ scheme)  is smooth near $x$ over $k(f(x))$.
Comment: I want to show $f$ is smooth at $\xi$ (respectively étale at $\xi$).
Comment: It's enough to show $\Omega^{1}_{X_{\xi'}/k(\xi'), \xi}$ is free of rank $dim_{\xi}X_{\xi'}$ (respectively $\Omega^{1}_{X/Y, \xi } = 0$ since smooth implies flat and since $\Omega^{1}_{X/Y, \xi } = 0$ will implie unramified at $\xi$ hence étale at $\xi$).
Comment: The étale case is then easy and it's just the smoothness I still searching for.
Comment: Note that $\Omega^{1}_{\mathcal{O}_{X, \xi}/\mathcal{O}_{Y, \xi'}} \simeq \Omega^{1}_{X_{\xi'}/k(\xi'), \xi} \otimes k(\xi)$ is a $k(\xi)$ vector space of dimension $trdeg_{K(Y)}K(X)$. If the fiber $X_{\xi'}$ were integral, I could show this implies $\Omega^{1}_{X_{\xi'}/k(\xi'), \xi}$ is free of rank $trdeg_{K(Y)}K(X) = dim(X_{\xi'}) = dim_{\xi}X_{\xi'}$.
Comment: Your definition of smoothness does not look sufficient. You need to assume that $f$ is flat of finite type near (or at – this is equivalent [not obviously so, though]) $x$!
Comment: Right I forget of finite type and flat!
Comment: thank you very much.
Answer: Both statements follow from standard openness properties and an alternate characterization of smoothness in terms of the rank of $\Omega_{X/Y}$.
Theorem. (Openness of the flat locus, Stacks 0938). Suppose $f:X\to S$ is a morphism of schemes which is locally of finite presentation. Let $\mathcal{F}$ be a quasi-coherent $\mathcal{O}_X$-module which is locally of finite presentation. Then the set $$U=\{x\in X \mid \mathcal{F} \text{ is flat over } S \text{ at } x\}$$ is open in $X$.
This theorem is a bit of a bear to prove yourself; hopefully Liu has spent some time on this breaking it up or proving it himself.
Lemma. The rank of a coherent sheaf on a noetherian scheme is upper semi-continuous, and if such a sheaf has a free stalk at a point, it is locally free in a neighborhood. (Refer to here on MSE and here on MSE for instance.)
Lemma. (Stacks 01V9) A map of schemes $f:X\to S$ is smooth at $x\in X$ iff the map $\mathcal{O}_{S,f(x)}\to\mathcal{O}_{X,x}$ is flat and $\Omega_{X/S,x}$ can be generated by at most $\dim_x X_{f(x)}$ elements.
Now we can look at the situation for the maps of generic points, apply the results above, and win.
Let $\eta$ be the generic point of $X$ and $\theta$ be the generic point of $Y$. Then the map $\mathcal{O}_{Y,\theta}\to\mathcal{O}_{X,\eta}$ is just $k(Y)\to k(X)$, which is a field extension and therefore flat. The stalk of $\Omega_{X/Y}$ at $\eta$ is the module of differentials associated to the field extension $k(Y)\subset k(X)$, and so by generic separability, it is a $k(X)$-vector space of dimension $\operatorname{trdeg} k(X) -\operatorname{trdeg} k(Y)$ and hence $\Omega_{X/Y}$ is free of rank $\operatorname{trdeg} k(X) -\operatorname{trdeg} k(Y)$ near $\eta$. Now $f$ is flat in a neighborhood of $\eta$ by the theorem, $\Omega_{X/Y}$ is locally free of rank $\operatorname{trdeg} k(X) -\operatorname{trdeg} k(Y)$ in a neighborhood of $\eta$ by the first lemma, and so on the common open neighborhood $U$ of $\eta$ where both these conditions hold we may conclude that $f$ is smooth and we're done. When $k(Y)\to k(X)$ is finite, $\Omega_{X/Y}$ is zero in a neighborhood of $\eta$, and we may conclude that $f$ is in fact smooth of relative dimension zero, or etale.
Comment: It works, thank you very much for your answer KReiser.


Código em C simplesmente fecha

Question: #include <stdio.h>
#include <stdlib.h>

void recebeNumCartas(int *nAlice, int *nBeatriz){

    scanf("%d %d", nAlice, nBeatriz);

}

int achaMenor(int nAlice, int nBeatriz, int menor){

    menor = nAlice;

    if (nBeatriz < nAlice){
        menor = nBeatriz;
    }

    return menor;
}

int realizaTroca(int nAlice, int nBeatriz, int menor){

    int cartasAlice[nAlice];
    int cartasBeatriz[nBeatriz];
    int troca[menor * 2];

    for (int i = 0; i < nAlice; ++i){
        scanf("%d", cartasAlice[i]);
    }

    for (int j = 0; j < nBeatriz; ++j){
        scanf("%d", cartasBeatriz[j]);
    }
}

int main(void){

    int nAlice = 0;
    int nBeatriz = 0;
    int menor = 0;

    recebeNumCartas(&nAlice, &nBeatriz);
    menor = achaMenor(nAlice, nBeatriz, menor);

    realizaTroca(nAlice, nBeatriz, menor);

    getchar();
    getchar();
    return 0;
}

Estou fazendo um exercício com o código acima, mas depois que o primeiro for loop da função realizaTroca é executado o programa encerra sem nenhuma mensagem de erro. Preciso de ajuda para entender oque está acontecendo.
Answer: Seu código está retornando um segmentation fault na leitura do vetor.
Segue a documentação da função:
int scanf ( const char * format, ... );

Reads data from stdin and stores them according to the parameter format into the locations pointed by the additional arguments.
The additional arguments should point to already allocated objects of the type specified by their corresponding format specifier within the format string.

Isto diz que os argumentos adicionais da função devem ser ponteiros (ou um endereço de memória) para objetos já alocados do mesmo tipo da função.
Sendo assim o seu problema pode ser resolvido simplesmente colocando o operador & no scanf dessa forma:
scanf("%d", &cartasAlice[i]);
scanf("%d", &cartasBeatriz[j]);

No início do código você já estava usando seu código sem o & e funcionou, na seguinte instrução:
scanf("%d %d", nAlice, nBeatriz);

Isso ocorre pois as variáveis nAlice e nBeatriz já conterem endereços de memória. Veja a declaração da função:
void recebeNumCartas(int *nAlice, int *nBeatriz)

Estes * indicam que esta variável deve conter um endereço de memória para uma variável do tipo inteiro. Este endereço está sendo passado na chamada, com o & nesta linha:
recebeNumCartas(&nAlice, &nBeatriz);

Sendo assim o scanf está recebendo exatamente o que ele espera.
Comment: Em qual linha isso ocorre? Estou meio perdido
Comment: ainda estou editando a pergunta, vou explicar tudo que está ocorrendo
Comment: entendeu o que está acontecendo agora?
Comment: Entendi, vou prestar mais atenção nestes detalhes, obrigado!

Código em C simplesmente fecha


python program to print sequence of 7 numbers startting with user entered number

Question: I need to write a program that asks the user to enter a number, n, which is -6

The numbers needed to be printed using a field width of 2 and need to be right justified. Fields must be seperated by a single space, with no space after the final field.
so far this is what i have got to this:
n = int(input("Enter the start number: "))
if n>-6 and n<93:
   for i in range(n, n+7):
      print("{:>2}".format(i), end="  ")

But I still seem to be getting spacing issues, any help would be much appreciated!
Comment: Hello, it looks like a homework question, so you need to figure out the complete answer by yourself.
I can hint you to create a list of numbers and use `str.join`
https://docs.python.org/3.7/library/stdtypes.html?str.join#str.join
Answer: n = int(input("Enter the start number: "))
if n>-6 and n<93:
   for i in range(n, n+7):
       if i < n + 6:
           print("{:>2}".format(i), end="  ")
       else:
           print("{:>2}".format(i))

Comment: Please don't post only code as answer, but also provide an explanation what your code does and how it solves the problem of the question. Answers with an explanation are usually more helpful and of better quality, and are more likely to attract upvotes.
Answer: Solution
n = int(input("Enter the start number: "))
width = int(input('Enter width : '))
if n>-6 and n<93:
   for i,val in enumerate(range(n,n+width)):
       if i==(width-1):
           print("{}".format(val))
       else:
            print("{}".format(val),
            end="  ")

Output
Enter the start number: 5
Enter width : 5
5  6  7  8  9


Why are comments not a node content type?

Question: So Drupal has a 'special' commenting system.

Comments are second-class citizens in Drupal compared to nodes...

But why did the core team not just create a default Content Type, Block and View for comments, and allow the site administrator add in a comment block as necessary? Just like the 'Article' and 'Basic Page' content types, which we can create blocks and views for. Why are comments so different?
Comment: You seem to be essentially asking "why are comments not nodes?" The answer is simply "because they're not supposed to do the same thing". Just like you wouldn't use a tractor to race in Grand Prix; it could theoretically be done, but it would be crazy to do so. Read [this](http://drupal.stackexchange.com/questions/22586/when-is-it-appropriate-to-create-an-entity-versus-just-adding-a-new-content-type/22587#22587) for some more general background on entity types v content types
Comment: @dayuloli comment or integral part of question, whatever you wish, just avoid parts that look so separate, if possible :)
Comment: That IS essentially what I am asking. Thanks for the link, it is relevant. I would have asked a better question if I knew the terminology. Thank you for your understanding.
Comment: No problem, I wasn't trying to insinuate your question wasn't a good one - far from it in fact, if you're new to Drupal these sorts of things can be very confusing. I just wanted to get straight to the point though, in the case of comments v nodes it's as straightforward as "different requirements, different entity types"
Comment: @dayuloli now you know the terminology, so you can edit and **make** it a better question! :)
Comment: @Clive & Molot I'll read the link as well as more of the docs. And then I will edit the question. Thanks for taking the extra step to make sure I feel welcomed! Much appreciated! (I might come back with more questions later!)
Comment: Please avoid "Update" and alike in questions. Try to make them read as a natural whole. It shouldn't be hard to do it with this one. You have my upvote, but it does not mean I'll stop nagging you to make it a perfect question ;)
Comment: This question has technically been [asked before](http://drupal.stackexchange.com/q/22586/18794), but for anyone new to Drupal (like I am), they might not have the correct terminology to ask the right question. And so I am leaving this question as is.
Comment: @Mołot moved my 'update' into the comments, where it belongs? (:
Comment: The main reason for not making comments more like nodes is because they don't have to have a URL. You could try disabling the module "comments" and create your own comments content type with the assistance of other modules such as entity relationships, but when you do that you will later find yourself struggling and using some configuration tricks to hide their URL from search engines and users. A comment by itself is irrelevant, they have to be"attached" to something in order to make sense. Imagine a user finding a page of your website that says "I love it".
Answer: To answer this, I first had to understand one thing: Entities are not nodes.
Entity Types are special groupings of fields.
Node is an entity type, which requires some fields, such as 'Title', 'Author' and 'Publish Date'.
Content Types are instances of Node which further define more fields. So a 'blog post' content type can have 'Hook', 'Introduction', 'Summary' and 'Related posts' fields, in addition to 'Title', 'Author' and 'Publish Date'.
Node is an entity type specialized for content. A comment is not designed to be a node because it is too different from a typical content. It's not necessary to have a 'Title', 'Author' or 'Publish Date' field in a comment. Because it is so different, it is created as another Entity type instead.
For more details, see this article on Drupal.
Comment: No need to dig very deeply to find something explicit: https://www.drupal.org/node/1261744
Comment: _Technically_ all entity types have a bundle @AyeshK. If one isn't provided core uses an implicit one
Comment: Thanks @clive - I actually meant some entity types have different bundles and some don't. Flag, Node are entity types with multiple bundle support. User, taxonomy term, etc have only one bundle. Thanks again for the clarification.
Comment: Nodes, comments, taxonomy terms, users, etc are all entity types. Some have bundles, some don't. A node type is technically a "bundle" from entity point of view.
Answer: In Drupal 8 nodes and comments (and custom blocks and user added menu links and users and taxonomy terms and...) are entities both. While in D7 an entity was indeed just for a bundle of fields -- I still remember when they were simply <code>$object</code> and there was no API at all. In Drupal 8 entities have a proper CRUD API; they are classed objects with save, load etc. And comment settings are now a field so everything fieldable is commentable. The mind boggles at the possibilities (commented comments? Commentception! even that is possible AFAIK).
Answer: Just as a sidenote, sometimes perhaps you really do not need the power of the core Comments entity, but just a simple list of comments or notes (without replies) associated to the Content Type or Entity.
In these cases, you may lighten your system load disabling the Comments for that Content Type, and using just a field for storing the comments or notes.
At least 2 contrib modules provide this kind of field:

Field Comments: https://www.drupal.org/project/field_comments
Comment Field: https://www.drupal.org/project/commentfield