Safety of write cache on SATA drives with barriers

Question: I've been reading lately about write caching, NCQ, firmware bugs, barriers, etc regarding SATA drives, and I'm not sure what's the best setting that would make my data safe in case of a power failure.
From what I understand, NCQ allows the drive to reorder the writes to optimize performance, while keeping the kernel informed on which requests have been physically written.
Write cache makes the drive serve a request much faster, because it doesn't wait for the data to be written to physical disk.
I'm not sure how NCQ and Write cache mix here...
Filesystems, specially journalled ones, need to be sure when a particular request has been written down. Also, user space process use fsync() to force the flush of a particular file. That call to fsync() shouldn't return until the filesystem is sure that the data is written to disk.
There's a feature (FUA, Force Unit Access), which I've seen only on SAS drives, which forces the drive to bypass cache and write directly to disk. For everything else, there's write barriers, which is a mechanism provided by the kernel that can trigger a cache flush on the drive. This forces all the cache to be written down, not just the critical data, thus slowing the whole system if abused, with fsync() for example.
An then there are drives with firmware bugs, or that deliberately lie about when data has been physically written.
Having said this.. there are several ways to setup the drives/filesystems:
A) NCQ and Write cache disabled
B) Just NCQ enabled
C) Just Write cache enabled
D) Both NCQ and write cache enabled
I'm asuming barriers are enabled.. BTW, how to check if they are actually enabled?
In case of power loss, while actively writing to the disk, my guess is that option B (NCQ, no cache) is safe, both for filesystem journal and data. There may be a performance penalty.
Option D (NCQ+cache), if using barriers or FUA, would be safe for the filesystem journal and applications that use fsync(). It would be bad for the data that was waiting in the cache, and it's up to the filesystem to detect it (checksuming), and at least the filesystem won't be (hopefully) in an unstable state. Performance-wise, it should be better.
My question, however, stands... Am I missing anything? Is there any other variable to take into account? Is there any tool that could confirm this, and that my drives behave as they should?
Comment: Be sure to get a UPS.
Comment: Use ZFS on Linux instead and couple with a purpose-built ZIL device. I use the [DDRDrive](http://www.ddrdrive.com/) for ZFS systems :)
Comment: What's the application in your situation? You're overlooking  the effect or influence of a RAID controller and its cache on the setup. What operating system are you focusing on as well? Which filesystem are you considering?
Comment: No specific application. I've been using software raid1 for years, but never dig into the problem that write caches represent. Also, having looked into btrfs, for which there is no reliable fsck yet, makes me question what can I do to prevent corruption, if I were to use it.
Comment: Are you using ZFS with FUSE?
Comment: No, I'm using it directly on CentOS 6.3 using RPMs compiled from [ZFSonLinux.org](http://zfsonlinux.org/). It works wonderfully! And I'm a [hardcore ZFS user](http://serverfault.com/search?tab=votes&q=user%3a13325%20zfs) from the Solaris/Nexenta camp.
Answer: For straight up Enterprise systems, there is an additional layer in the form of the storage adapter (almost always a RAID card) on which yet another layer of cache exists. There is a lot of abstraction in the storage stack these days, and I went into deep detail in this in a blog series I did on Know your I/O.
RAID cards can bypass on-disk cache, some of which even allow toggling this feature in RAID BIOS. This is one reason why Enterprise disks are Enterprise, thier firmware allows such things that consumer drives (especially 'green' drives) don't. This feature directly addresses the case you're concerned about: power failure with uncomitted writes. The RAID card cache, which should be either battery or flash-backed, will be preserved until power returns and those writes can be recomitted.
Certain enterprise SSDs include an onboard capacitor with enough oomph to commit the onboard cache before fully powering down.
If you're working with a system with disks directly connected to the motherboard there are fewer assurances. Unless the disks themselves have the ability to commit the write-cache, a powerfailure will indeed cause a loss. The xfs filesystem earned a reputation for unreliability due to it's inability to survive just this failure mode; it was designed to run on full up enterprise systems with engineered storage survivability.
However, time has moved on and XFS has been engineered to survive this. The other major Linux filesystems (as well as ntfs on Windows) already had engineering to survive this very failure mode. How it's supposed to work is that the lost writes will not show up in the FS journal and it'll know they didn't get comitted, so corruption will be safely detected and worked around.
You do point to the one problem here: disk firmware that lies. In this case the FS journal will have made a wrong assumption versus reality and corruption may not be detected for some time. Parity RAID and mirror RAID can work around this as there should be another comitted copy to pull from. But single disk setups won't have that cross-check, so will actually fault.
You get around the firmware risk by using Enterprise-grade drives that get much more validation (and are tested versus your presumed workload patterns), and designing your storage system so that it can survive such untruths.
Comment: I understand that under hardware RAID, it's up to the controller to do the caching (hopefully battery backed), and it's advisable to have the actual disks cache disabled.

In my case (didn't mention it) i'm using software raid. It seems that write cache is not recommended as it will cause data loss. Maybe not catastrofic (filesystem corruption), but data loss anyway.

I'll refrain, for the time being, from migrating my softraid1+ext4 to btrfs+raid1. :)
Comment: RAID does not help with this since the data can just as easily sit in both drives write caches as one drive.
Comment: @psusi It is not a 100% mitigation, but it does provide *added* protection. It's a timing problem. Individual RAID implementations differ.
Comment: It isn't a mitigation at all.  The secondary drive does not matter at all, since in the event of a crash, the primary will be copied back over the secondary to recover.  Hence, you are back to whether or not the write made it to the (first) drive or not.
Answer: The filesystem journal originally waited for the write to the journal to complete before issuing the write to the metadata, assuming that there was no drive write cache.  With drive write caching enabled, this assumption is broken and can cause to data loss.  Thus, barriers were created.  With barriers, the journal can make sure that the write to the journal completes before the write to the metadata, even if the disk is using write caching.  At the disk driver layer, the barrier forces a disk cache flush before subsequent IO is sent down, when the drive reports that it has a write cache and it is enabled.  Otherwise, this is not needed, so the barrier just prevents issuing of the subsequent IO to the drive until the previous IO has completed.  NCQ just means it might have to wait for more than one pending request to complete before issuing more.
Comment: I think barriers protect you from journal corruption (if the filesystem requests so), but I'm not sure about the actual data on the files... Issuing a cache flush after every write would make the write cache useless, wouldn't it?
Comment: @julianjm, of course... cached file data is always lost in the event of a crash, with or without NCQ or drive write caches.


Form #after_build is not working for PHP 7x

Question: I'm using #after_build in one of my custom module form like follows
  $form['profile_image'] = array (
    '#type' => 'managed_file',
     '#after_build' => array("change_pic"),
  );

and the function is
function change_pic($element, &$form_state, $form) {
  if($form_state['values']['profile_image']['fid'] != 0){
    // my code goes here..
    return $element;
  }
}

It's working fine in PHP 5x version. but throws the following error in PHP 7x version.

ArgumentCountError: Too few arguments to function change_pic(), 2 passed
  How can we handle this in PHP 7?

Any inputs would be helpful.
Answer: There are only 2 args to an after build method, the element and the form state.
Just remove the extra one and it'll work:
function change_pic($element, &$form_state)

Answer: Clive's answer to use only those 2 arguments is correct; but this is also wrong on your code:
 $form['profile_image'] = array (
    '#type' => 'managed_file',
     '#after_build' => array("change_pic"),
  );

this will wipe out any other after builds added by other modules. You should add like this:
 $form['profile_image']['#after_build'][] = 'change_pic';


Standardizing data values

Question: I see an example for standardizing data value here. For better illustration, the table is shown below

I did the same thing in excel and as you can see, the results are different.

For mean and variance, I used AVERAGE and VAR formulas, respectively in Excel. The standardized values are calculated as:
0  ->  (0-2.5)/3.5 = -0.714
...

What is wrong then?
Comment: Use the [standard deviation](https://stats.stackexchange.com/q/398116/930) (the $\sigma_x$ in the post you refer to) instead of the variance.
Answer: The value $3.5$ is calculated using the sample variance formula.
You need to use the population standard deviation formula:
\begin{equation}
\sqrt{\frac{\sum_{i=1}^{n}(x_i-\bar{x})^2}{n}}
\end{equation}
The population standard deviation is $\sqrt{2.916667}$. Standardizing using this value will yield the desired results.
\begin{equation}
\frac{0-2.5}{\sqrt{2.916667}} \approx -1.4638501
\end{equation}
Using R we can replicate the results from your example:
x = c(0,1,2,3,4,5)
s1 = sum((x-mean(x))^2)/6
xs = (x-mean(x))/sqrt(s1)
data.frame(x, xs= round(xs,2))

Output:
 x    xs
 0 -1.46
 1 -0.88
 2 -0.29
 3  0.29
 4  0.88
 5  1.46

Comment: Yes it does, the sample and population standard deviation use different denominator $n-1$ vs $n$, respectively. STDEVP is the function you want to use - this will use $n$
Comment: In Excel, I see STDEV, STDEV.P, STDEV.S and some other forms. Doe sit matter which one to use?

Standardizing data values


Using prefix and suffix form api layout

Question: I have created a form, though I'm having an issue with using the prefix and suffix to place items into rows rather than the list they appear as standard.
For example I have these 3 form elements, how would I go from having them appear as standard on a new line, to on the same line. Normally I would just chuck them into a table and place each one in a different column. I have read that I should possibly use floats?
I have tried  '#prefix' => '
',
'#suffix' => '

' , But this seems to affect the navigation on the left and shuffle it down.
$form['orange'] = array(
    '#type'=>'select',
    '#title' => t('Select Orange'),
    '#options' => $Orange,
    '#multiple' => false,
    '#prefix' => ,
    '#suffix' => ,
    '#attributes'=>array('size'=>0),
    '#required' => TRUE,
);
$form['apple'] = array(
    '#type'=>'select',
    '#title' => t('Select apple'),
    '#options' => $apple,
    '#multiple' => false,
    '#prefix' => ,
    '#suffix' => ,
    '#attributes'=>array('size'=>0),
    '#required' => TRUE,
);
$form['strawberry'] = array(
    '#type'=>'select',
    '#title' => t('Select strawberry'),
    '#options' => $strawberry,
    '#multiple' => false,
    '#prefix' => ,
    '#suffix' => ,
    '#attributes'=>array('size'=>0),
    '#required' => TRUE,

);

I cannot answer for 7 hours but here it is:
The solution was to close the DIV, I had forgotten, which meant the styling was effecting the whole page.
     '#prefix' => '
',
    '#suffix' => '

',
    [Useful link to aligning form elements horizontally][1]

Answer: I think you want to keep it in table. Lets try with putting it in one like this --
$form['orange'] = array(
    '#type'=>'select',
    '#title' => t('Select Orange'),
    '#options' => $Orange,
    '#multiple' => false,
    '#prefix' => '

',
    '#suffix' => '	',
    '#attributes'=>array('size'=>0),
    '#required' => TRUE,
);
$form['apple'] = array(
    '#type'=>'select',
    '#title' => t('Select apple'),
    '#options' => $apple,
    '#multiple' => false,
    '#prefix' => '',
    '#suffix' => '	',
    '#attributes'=>array('size'=>0),
    '#required' => TRUE,
);
$form['strawberry'] = array(
    '#type'=>'select',
    '#title' => t('Select strawberry'),
    '#options' => $strawberry,
    '#multiple' => false,
    '#prefix' => '',
    '#suffix' => '

',
    '#attributes'=>array('size'=>0),
    '#required' => TRUE,

);

I haven't tested this code, so please try this & let me know if it works :)
Answer: Yes. We can put the form and form elements into table with rows, columns structure. And of course we can use the prefix and suffix attribute to do that. Please follow this instruction from this Drupal 7: theming forms with tables

Using prefix and suffix form api layout


Update shape color using Ruby Google Slides API

Question: I'm trying to update an ellipsis shape using the google slides api in ruby. This is the code:
shape_properties = {
    shape_background_fill: {
        solid_fill: {
            color: {
                rgb_color: {
                    red: 1.0,
                    green: 0,
                    blue: 0
                }
            }
        }
    }
}

requests = [{
              update_shape_properties: {
                object_id: ellipse.object_id,
                fields: 'shapeBackgroundFill',
                shape_properties: shape_properties,
              },
            }]

# Execute the request.
req = Google::Apis::SlidesV1::BatchUpdatePresentationRequest.new(requests: requests)
response = @slides.batch_update_presentation(presentation_id,req)

Another code that I've tried with the same error is this one:
rgb_color = Google::Apis::SlidesV1::RgbColor.new(red: 1.0, green: 0, blue: 0)
color = Google::Apis::SlidesV1::OpaqueColor.new(rgb_color: rgb_color)
solid_fill = Google::Apis::SlidesV1::SolidFill.new(color: color)
shape_background_fill = Google::Apis::SlidesV1::ShapeBackgroundFill.new(solid_fill: solid_fill)
shape_properties = Google::Apis::SlidesV1::ShapeProperties.new(shape_background_fill: shape_background_fill)
requests = [{
                update_shape_properties: {
                  object_id: ellipse.object_id,
                  fields: 'shapeBackgroundFill',
                  shape_properties: shape_properties,
                },
            }]
req = Google::Apis::SlidesV1::BatchUpdatePresentationRequest.new(requests: requests)
response = @slides.batch_update_presentation(presentation_id, req)

I get this error:
`check_status': badRequest: Invalid requests[0].updateShapeProperties: The object () could not be found. (Google::Apis::ClientError)

Any idea why is it fails?
Comment: **The object () could not be found.** sounds like your not sending an object
Comment: @DaImTo I've updated the post with another try that I did to make sure I was sending an object, but I had the same error
Answer: try using object_id_prop instead of object_id in update_shape_properties.
shape_properties = {
    shape_background_fill: {
        solid_fill: {
            color: {
                rgb_color: {
                    red: 1.0,
                    green: 0,
                    blue: 0
                }
            }
        }
    }
}

requests = [{
          update_shape_properties: {
            object_id_prop: ellipse.object_id,
            fields: 'shapeBackgroundFill',
            shape_properties: shape_properties,
          },
        }]

# Execute the request.
req = Google::Apis::SlidesV1::BatchUpdatePresentationRequest.new(requests:
requests)
response = @slides.batch_update_presentation(pres`entation_id,req)

Because UpdateShapePropertiesRequest has object_id_prop accessor instead of object_id.
That's why object_id name is already used in Object.


Apache daily logrotate

Question: I want to create daily logs, but there's a small problem. Logs aren't being created for each day, rather they contain the previous log files. Here's my current setup, how can I change it so it only create a log file for each day?
I edit the following file : /etc/logrotate.d/httpd
I'm using a control panel called Zadmin so I included its log path as a second dir.
I'm using CentOS 6.5 64 bit.
/var/log/httpd/*log /var/sentora/logs/domains/zadmin/*.log {
    missingok
    rotate 4000000
    daily
    notifempty
    sharedscripts
    postrotate
    /sbin/service httpd reload > /dev/null 2>/dev/null || true
    endscript
}

Comment: What do you mean by
> they contain the previous log files
Comment: For instance, when I look at the access.log file, it includes all the logs that has been created so far. I don't want it, I want it to create logs daily and name it like the following : access.log-21-08-2015
Comment: There is also a rotate logs program that comes with Apache, [rotatelogs](http://httpd.apache.org/docs/2.4/programs/rotatelogs.html).
Comment: Is this happening only to Apache logs? If its happening to all logs the 'create' option might be missing from /etc/logrotate.conf (please add the content of that file to your post). Also the /var/lib/logrotate.status (I think Centos has that one, at least Arch has it) might be corrupted, you could try and move it out of harms way and try running logrotate -f /etc/logrotate.d/httpd manually as root. Also adding the -d switch for debugging purposes wont hurt.
Comment: Do you have cron task which runs logrotate? what happens when you run logrotate /etc/logrotate.conf manually?
Comment: WAG: There is an error in the apache configuration so the reload isn't working.  Try `apachectl configtest`
Answer: Apache lets you pipe log files to another program which can then handle rotation without having to reload/restart Apache. Apache even provides a program to do this.
ErrorLog "|bin/rotatelogs -l -f /var/log/apache2/errlogfile.%Y.%m.%d.log 86400" common
CustomLog "|bin/rotatelogs -l -f /var/log/apache2/logfile.%Y.%m.%d.log 86400" common

Comment: And you copied it incorrectly. ErrorLog doesn't have "common" in the examples!
Comment: ErrorLog has an issue in the format. ErrorLog takes one argument, The filename of the error log - no "common" is expected in the end of the line. Apache fails to start with such config.
Comment: Moreover, you need to specify the real path to rotatelogs. Normally it's not like above but can be /usr/local/apache/bin/rotatelogs
Comment: @Hardoman The examples are from the documentation: [rotatelogs - Piped logging program to rotate Apache logs](https://httpd.apache.org/docs/2.4/programs/rotatelogs.html#examples)
Answer: Try running logrotate manually to look for errors: logrotate -d /etc/logrotate.d/httpd. The manual says "-d Turns on debug mode and implies -v.  In debug mode, no changes will be made to the logs or to the logrotate state file."
This is what we're using successfully:
/var/log/httpd/*log {
  daily
  dateext
  dateformate -%d-%m-%Y
  missingok
  nocompress
  rotate 30
  postrotate
    /sbin/service httpd reload > /dev/null 2>/dev/null || true
  endscript
}

Answer: Following on to Brian's answer, I'm a big fan of cronolog, which does pretty much exactly what you're going for:
CustomLog "|/usr/sbin/cronolog /var/log/httpd/%Y/%m/%Y-%m-%d-access.log" combined
ErrorLog "|/usr/sbin/cronolog /var/log/httpd/%Y/%m/%Y-%m-%d-error.log"

yum install cronolog will get you cronolog on Cent6.
Comment: It does look nicer than the Apache program, would just add it is in the EPEL repository which is not enabled be default on CentOS (`yum install epel-release` to install/enable it).
Comment: Where I should put the text that starts with "CustomLog" and "ErrorLog", /etc/logrotate.d/httpd?
Comment: Additionally, should I remove everything in the /etc/logrotate.d/httpd and just put these?
Comment: They go in the Apache web server's configuration file.

Apache daily logrotate


7th chords with black key at the bottom fingering

Question: I want to ask why nobody plays for example, F# half diminished chord on piano with 2145 fingering on right hand. Everybody plays 1235 or 1245. I think better to use 2 at the bottom because you can reach lower notes on piano with right hand and high notes are also comfortable with 2. Am I wrong?
Comment: 1235 works fine for the chord itself. I sense you are not just playibg a simple chord but playing arpeggios. You have to give us some sheet music. We dont seem to understand you. I dont anyway
Comment: Did you mean 2345?
Comment: 2345 is also an option
Comment: Generally, there is suggested fingering for arpeggios (and songs), but if something else works for you, you can use that
Comment: So, would you play f# half diminished chord 1235 1235 long arpeggio? I probably would play 2123 4123. In short arpeggio I would probably use 2145 or 2345 because of better range ability of low notes
Comment: Pretty sure most teachers do not recommend having the right thumb playing a higher note than any other finger on the right hand, but not sure whether it's a problem, so this is a comment.
Comment: A pic of you doing exactly what you ask about is worth a thousand words!
Answer: As always,  talk to an experienced teacher.  In many cases, the choice of fingering depends on how you enter or leave that chord in the piece being played.  In other cases, there are fingerings which may seem awkward at first but cause much less strain on your fingers or wrists.  Avoiding biophysical damage is important!
Answer: The general answer has to be that most people can't reach! Personally, using index on F♯ and thumb on A (other notes C and E with whatever's remaining) is impossible as a block chord with R.H.
Arpeggiating may give that option of 2145, but that's not made clear in the question. There's always the 'rule' that says thumb is best on white keys, as it's generally shorter than the fingers.
The basic idea with any fingering is to do what is most comfortable, practical and logical, and because there are so mant variants of hand physiology, there will also be variants as to how exactly a player fingers certain notes/chords/passages.


Test User Approval Kernel Extension Loading on mac (TN2459)

Question: TN2459: https://developer.apple.com/library/content/technotes/tn2459/_index.html introduces that under macOS High Sierra user approval is required for loading new third-party kernel extensions.
The kext that I would like to test has been loaded before upgraded to High Sierra, so loading the same kext after upgrade does not trigger the user approval flow which I would like to test against.
The kernel extension user consent is enabled:
$ spctl kext-consent status
Kernel Extension User Consent: ENABLED

I deleted the entry that corresponds to the kext in the kext_policy table in /private/var/db/SystemPolicyConfiguration/KextPolicy under recovery mode and restart several times. But the user approval flow is still not triggered when I load the kext.
I wonder if the policy info is cached somewhere else and if I need to clear NVRAM for my machine or tell syspolicyd to clear its cache? Or there is other things that I need to do?
Comment: This is possibly duplicated to https://stackoverflow.com/questions/47810161/macos-high-sierra-kext-loading-are-there-any-ways-to-cancel-user-approval?rq=1
Answer: In short, you have to boot in recovery mode (Mac+R) and edit the sqlite table /private/var/db/SystemPolicyConfiguration/KextPolicy.
This table is accessible in read-only mode in normal boot:
sqlite3 /private/var/db/SystemPolicyConfiguration/KextPolicy
sqlite> SELECT * FROM kext_policy;
sqlite> SELECT * FROM kext_load_history_v3;

You have to remove your entries (recovery mode) and reboot, like this (Replace 'G43BCU2T37' with your team_id):
sqlite> DELETE FROM kext_policy WHERE team_id = 'G43BCU2T37';
sqlite> DELETE FROM kext_load_history_v3 WHERE team_id = 'G43BCU2T37';
sqlite> .exit

To avoid the reboot every time, you could alter the "System Integrity Protection" configuration (in recovery mode): csrutil enable --without fs --no-internal. Now kext_policy is changeable from normal boot.
The whole procedure is described here: https://forums.developer.apple.com/thread/79172#248518.
Comment: Now I see the answer is also here: https://stackoverflow.com/questions/47810161/macos-high-sierra-kext-loading-are-there-any-ways-to-cancel-user-approval
Answer: Was able to test it using a high sierra vm. The full step of installing the vm is: https://www.howtogeek.com/289594/how-to-install-macos-sierra-in-virtualbox-on-windows-10/


Validate my understanding on Express Routes

Question: Actually, before I get into the question, when I do anything like
const app = express()
app is an instance of the entire express module right? Meaning, when I do app.route, route is it an Express method right or a NodeJS method, since Node has .route as well? Anyways... I just wanted to double check this.
app.route('/games')
    .post(postGame)
    .get(getGames);

app.route('/games/:id');
    .get(getGame)
    .delete(deleteGame);

Is this the same as... and if not... why would one choose one over the other?
app.get('/games');
app.post('/games');
app.get('/games/:id');
app.delete('games/:id');

Sorry, it's just been a while since I have used Express, and couldn't find anything about this specific problem. Thanks!
Answer:
app is an instance of the entire express module right?

Yes, the app object is create by calling the top-level express() function exported by the Express module. That set the default http headers, render options.... and wrap the http node module:
app.listen = function listen() {
  var server = http.createServer(this);
  return server.listen.apply(server, arguments);
};

You can see more in the source code here (really readble)

route is it an Express method right or a NodeJS method

Route is an express object and nodeJs don't provide a routing system like express.
And for your example yes it's totally the same. They stores the handlers function in the same this._router.route
Comment: Thank you, I think I should start investing time into reading source code. I feel like I need to build an npm module so I can understand to read it better :)
Comment: @dsomel21 Can you valid the answer for close the question pls :)


Where does polynomials come from in Stone Weierstrass?

Question: It might be a silly question to ask but most versions of Stone Weierstrass theorem define polynomials inductively and shows that it converges to a particular function. To make the previous sentence meaningful, consider the following theorem

Define a sequence $(P_n)_{n=0}^\infty$ of polynomials recursively by the relations $P_0(t)=0$ and $P_{n+1}(t)=P_n(t)+1/2 [ t^2-P_n(t)^2]$. Then $P_n\to \mid t \mid $ uniformly on $[-1,1]$.

Now my question is where do these polynomials come from? Thanks for any help!
Comment: I gave an answer to your question, but now I am no longer sure what you are *really* asking. Is it why polynomials are used *at all* to approximate functions or why, precisely, the above $P_n$ are used to approximate $\lvert x \rvert$?
Comment: You might be interested in "Bernstein polynomials". https://en.wikipedia.org/wiki/Bernstein_polynomial
Comment: "most versions of Stone Weierstrass theorem define polynomials inductively"??? I don't know a version of the theorem that even _mentions_  polynomials. Weierstass' theorem on polynomial approximation is a special case of S-W, not a "version of" S-W.
Comment: @DavidC.Ullrich All versions of Stone Weierstrass Theorem rely on (function) subalgebra. Along the way you need to show that uniform closure is closed for $\wedge $ and $\vee$ operations. For this fact you need a theorem like the one I put in my question. So every version implicitly relies on polynomials defined inductively!!!!
Comment: If you mean the latter, I shall delete my answer.
Comment: @PaulFrost It is more like the latter. How can we get those polynomials rather than why polynomials if that makes sense. I think your answer is still useful for the why part.
Comment: Okay, I edited my answer.
Answer: In its most general version the Stone-Weierstrass theorem is a result about generating dense subalgebras of $C(X)$ = unitary algebra of continuous functions $f : X \to \mathbb{R}$ endowed with the compact-open topology (which is the topology of uniform convergence on all compact subsets of $X$). Note that if $X$ is compact, then $C(X)$ has the topology of uniform convergence.
Any subset $D \subset C(X)$ generates a smallest unitary subalgebra $A(D) \subset C(X)$. It is easy to see that $A(D)$ is the set of functions having the form $p(f_1,\dots,f_n)$, where $f_i \in D$ and $p$ ranges over all polynomials in $n \ge 1$ variables (all $n$ allowed).
This is the true origin of the polynomials in the Stone-Weierstrass theorem which says the following:
If $D$ separates points (which means that for any two distinct $x,x' \in X$ there exists $f \in D$ such that $f(x) \ne f(x')$), then $A(D)$ is dense in $C(X)$.
Now let $X = [-1,1]$. Then $D = \{ id \}$, $id(x) = x$, trivially separates points and $P(X) = A(D)$ is the set of all polynomials in the variable $x$. That $P(X)$ is dense in $C(X)$ is the "classical" Stone-Weierstrass theorem. One can certainly give a direct proof by constructing inductively a sequence of polynomials converging to a given $f \in C([-1,1])$, but in my opinion this is an unusual (though valid) approach.
Edited:
A key ingredient in the proof of the Stone-Weierstrass Theorem is the following result:
Let $A \subset C(X)$ be a unitary subalgebra. If $f \in A$, then $\lvert f \rvert \in \overline{A}$.
This is proved as follows (here we only consider compact $X$, but the argument can be generalized to arbitrary $X$).
For $f : X \to \mathbb{R}$ let $R = \sup_{x \in X} \lvert f(x) \rvert$. Then $f/R \in C(X)$ and $(f/R)(X) \subset [-1,1]$. If we can find a sequence of polynomials $p_n(t)$ such that $p_n(t) \to \lvert t \rvert$ uniformly on $[-1,1]$, then $p_n(f(x)/R) \to \lvert f(x)/R \rvert$ uniformly on $X$. Defining $f^*_n(x) = Rp_n(f(x)/R)$ we see that $f^*_n(x) \to  \lvert f(x) \rvert$ uniformly on $X$. But we have $f^*_n \in A$ because $f/R \in A$ and $p_n$ is a polynomial (recall that $A$ is a unitary algebra). Note that to conclude $p_n(f/R) \in A$ it is essential that $p_n$ is a polynomial.
So how to find these $p_n$? There are certainly many approaches. Not all of of them construct the $p_n$ recursively as in your question. An alternative is to construct polynomials $q_n(x)$ such that $q_n(x) \to \sqrt{x}$ uniformly on $[0,1]$. Then $p_n(x) = q_n(x^2)$ is a solution. But now it is known that
$$1 - \sqrt{1-y} = \sum_{i=1}^\infty \left\lvert \binom{\frac{1}{2}}{i} \right\rvert y^i$$
uniformly on $[0,1]$. Therefore $q_n(x) = 1 - \sum_{i=1}^n \left\lvert \binom{\frac{1}{2}}{i} \right\rvert (1-x)^i$ will do.
Conclusion:
Polynomials are essential to prove the Stone-Weierstrass theorem. The reason is that $A$ being a unitary subalgebra of $C(X)$ is equivalent to the following:
For all polynomials $p$ in $n \ge 1$ variables and all $f_1,\dots,f_n \in A$ one has $p(f_1,\dots,f_n) \in A$.
However, in the general formulation of the Stone-Weierstrass theorem this fact is not explicitly mentioned. But it is implicit in the assertion that $A(D)$ is dense in $C(X)$ because $A(D)$ is generated by polynomials.


Word Puzzle - How to fix it going out of path?

Question: I'm hoping someone can point me in the right direction with this issue.
For my project in school, we need to make a "Word Puzzle" solver. So there is a .txt file with a "grid" of letters, along with actual words under this grid that the puzzle needs to look for and see if they exist in the puzzle.
example:
4 4
s e l f
w t r g
a o o v
g x q e
frog
swag
self

The 4 4 represents the puzzle will be 4 letters wide, and 4 letters high.
The problem I am running into is that if, for example, we are searching for "frog". My program finds the 'f', then moves on to the next character in the word 'r'. It finds the 'r', then moves onto the 'o'. This is where my problem is. The way my program is designed uses a bunch of if else statements to check if the letter above, below, left, right, upright, downright, upleft, or downleft of the current location contains the next letter we are looking for.
So what happens is that it will pick the wrong 'o', and then try to find the 'g' after moving to 'o's location, but it can't because it took the wrong path.
My question is this: does anyone have an idea on how to fix this issue? I don't want a direct coding answer if possible, since this is an academic assignment and I don't want to cheat, but if someone could lead me in the right direction, I would be ecstatic!
Thank you.
EDIT : Here is the code: http://pastebin.com/SJ4EePk7
Comment: Code sharing will save you time to describe your problem and to get quick attention.
Comment: This really depends on your "path" algorithm. Don't you want to check in all directions from the initial character for a certain distance if that "substring" is contained within some master list of words?
Comment: *"does anyone have an idea on how to fix this issue?"* It looks like your code is checking each nearby field for the searched letter and stops looking if it found one, maybe with a `break`. In that case, you can't/shouldn't break that search, so the `break` statement should be removed. That might be the only necessary thing to fix, but it is hard to say without the code.
Comment: I posted the code here: http://pastebin.com/SJ4EePk7 Please take a look and let me know what you think
Comment: Your code belongs into the question, not to another page with a link in the comments ;P.
Comment: Please. Please help.
Comment: I am assuming you want to search string even in substring of puzzle. i.e. in `self`, `elf` is also a word.
Comment: It is only searching for the words given under the puzzle, so "elf" is irrelevant.
Comment: I did mean if `elf` is in list, is your code supposed to match it too, which is a subpart of string.
Comment: Is there any special algorithm that should be implemented?
Comment: KMPL to just search text in another text which makes searching faster @Pooya
Answer: their are 4 orientations in any your word could be found.

Horizontal (4 rows)
Vertical (4 rows)
Diagonal 1 - topleft to bottomright (7 rows)
Diagonal 2 - topright to bottomleft (7 rows)

Create program to get strings from all these orientations
s e l f
w t r g
a o o v
g x q e

Horizontal :
[self, wtrg, aoov, gxqe]
Vertical :
[swag, etox, lroq, fgve]
Diagonal 1 :
[s, ew, lta, frog, gox, vq, e]
Diagonal 2 :
[f, lg, erv, stoe, woq, ax, g]

Now to check if your strings are found in these strings you can use String.contains(...) function.
Comment: This doesn't guarantee when the word starts from bottom to top such as `xote` (if it was a real word).
Comment: then you will have to take two more orientation (1 extra for horizontal, and 1 for vertical)


I want to do correlation for many data frame

Question: i have almost 13 files and i want to conduct three types of correlations to it.
all the files have the same content except the values.
for example:
v1  v2  v3  v4  v5  v6  v7  v8  ........... v50
first correclation between v6 and v20
second correlation between v7 and v21
third correlation between  v8 and v22
my data have missing values.
doing it manually for each file will leads to a too long scrip, i want to do a loop function for all the files ( unfortunately im not expert in loop function and i tried so much)   I need help please
Answer: If 'd1', 'd2', ...'d13' are the datasets and the columns are the in the same order, we can place the dataset in a list and get the cor for the specified columns.  There are options in ?cor to compute the covariances in the presence of missing values.  Here, I used na.or.complete.  We can change it according to the need.
lapply(mget(paste0('d', 1:13)), function(x)
      diag(cor(x[,6:8], x[,20:22], use='na.or.complete')))

It may be better to read the files into a list directly than creating individual data.frame objects in the global environment.  Assuming that the files are all in the working directory.
files <- list.files(pattern='file\\d+.txt')#change the pattern as needed
lapply(files, function(x) {
                x1 <- read.table(x, header=TRUE)
                diag(cor(x1[,6:8], x1[,20:22], use = 'na.or.complete'))})

Comment: I just now create this code and results match perfect expect the output result is not in order   >>>>>                                                              directory <- "~/XXXX/XXXX /XXXX/DataXXX"
>    files <- list.files(directory, full.names=TRUE)
>
>    correlations <- c()
>
>    for (file in files) {
+       file_data <- read.csv(file, sep = ",");
+       complete_cases <- file_data[complete.cases(file_data),];
+
+       correlations <- c(correlations, cor(complete_cases$v6, complete_cases$v20))
Comment: @user1894845  Not sure why it is not in order.  I tried on an example dataset and it was in order.  It is better to provide some example dataset.  Your code is different than the one I used.
Comment: i named the files like this x1 ....... x13      and the output  showed  x1, x10, x11, x12, x13, x2, x3 , x4 , x5, x6, x7, x8, x9.
Comment: @user1894845 Are those file names? i.e. `x1.txt`, `x2. txt`. etc...  If these are file names.  `files <- paste0('x', 1:13, '.txt'); lapply(files, function(x) {x1 <- read.table(x, header=TRUE); diag(cor(x1[,6:8], x1[,20:22], use= 'na.or.complete'))})`
Comment: I appreciate your help. it worked wonderfully. my file names are in order as well as the results.
Answer: Here's a brute force version (with data generation included), it'll probably work for your purpose, a little more information about the structure of your data/task could help make this more efficient:
N <- 10
k <- 50

d <- data.frame(matrix(runif(N * k), ncol = k))

sapply(20:k, function(col) cor(d[,col - 14], d[,col]))

Edit: Question has been edited, I'm not sure if this is actually what you're after now.
Comment: thank you for supplying an answer for me.  its hard to explain my real task, but the example describes it.


Lucene as a high-volume cache?

Question: I work with a system where we do a lot of batch processing.  We have caches that are pre-loaded to help with data lookup performance.  There are scenarios however where I cannot cache the entire dataset into memory.  Up to this point, I've been reverting to running a query to lookup the data which kills performance.  In an attempt to resolve, I've added a hybrid cache where I use a HashMap up to a threshold and then I spill over to a Lucene index (local file system).  This is a definite improvement over running the query (anywhere from 6 to 10 times faster than the database query).  However, I was hoping for a little better and was wondering if there are better alternatives for this kind of thing.  I'm using a single String as my key and am caching Java objects.  I'd like to stick with a Java library to not complicate my deployment.  (I'd like to avoid a separate server process.)  I was wondering if anyone else was using Lucene for this purpose.  Are there better alternatives for this?
Answer: I think that if you are using a single string as key and don't need to run queries in the data stored, you could use Google's LevelDB. It has good performance and does low memory usage. Check this: http://code.google.com/p/leveldb/
Answer: There are several cache libraries available that should be able to handle your situation by writing cache entries to disk if a certain threshold is reached. A good strategy is to write the entries to disk that are leased accessed. There are also caches out there that distribute the cache entries over a cluster, keeping everything in memory.
A cache solution that I use often is Infinispan: http://www.jboss.org/infinispan
It is fast, easy to use, scalable and can certainly handle your problem.
Answer: EhCache! seems to be a good fit for what I need.  It performs much better than Lucene for this single key lookup.  It supports disk overflow and is simple to use.

Lucene as a high-volume cache?


Passing Viewbag value to javascript function

Question: I am new to MVC and trying from last 7 hours to pass value from viewBag to javascript function in MVC 5.
I have a string variable
ViewBag.c1 = "0.30"

and i passed it to view and stored it as a hidden element
@Html.Hidden("Superman", (string)ViewBag.c1)

and then i want to access the value of this hidden element in following js function
function getValue1() {
return parseFloat(document.getElementById("Superman"));
}

Comment: The hidden input is not necessary. You can just use `function getValue1() { return @Html.Raw(Json.Encode(ViewBag.c1)) }` and the controller code should be `ViewBag.c1 = 0.30F;` is you want a number
Answer:

@Html.Hidden("Superman", (string)ViewBag.c1)

function getValue1() {
  return parseFloat($("#Superman").val());
}

//or

function getValue1() {
  return parseFloat(document.getElementById("Superman").value);
}
Answer: var c1Value = "@Html.Raw(ViewBag.c1)";

function getValue1() {
  return parseFloat(document.getElementById(c1Value).value);
}

Answer: You could simply store view-bag value in JavaScript variable like below.


Calculate the address of the subnet

Question: Calculate the address of the subnet:
COMMAND:
If you represent the host address and netmask as lists of 4 numbers each, you may take the bitwise AND of the first number from one list and the first number from the other list, followed by the bitwise AND of the second number from the one list and the bitwise AND of the second number from the other list, and so on. Returns the address of the network as a list.
MY CODE:
def apply_network_mask(host_address, netmask):
    ips = host_address.split(".")
    net = netmask.split(".")

    ips_bin = [format(int(i), '08b') for i in ips]
    net_bin = [format(int(i), '08b') for i in net]

    print(f"{ips_bin & net_bin}")

My Code:

what I need:
apply_network_mask ([192,168,0,191], [255,255,255,0]) I should get back [192,168,0,0]
Comment: So if you're supposed to return the address of the network as a list, why aren't you returning anything?
Comment: Also `ips-Bin` is not `ips_bin`.
Comment: yea i have changed it but still need help
Comment: You've edited out the typo that caused the error in your screenshot. So what is your question?
Comment: What's your input? What's your actual vs. desired output? What's your question? Don't post images of code. Paste text into question.
Comment: i need to get the address of the subnet.
Comment: apply_network_mask ([192,168,0,191], [255,255,255,0]) I should get back [192,168,0,0]
Comment: Your code expects strings, not lists.
Comment: Welcome to Stack Overflow! Please read "How to create a [mcve]". Then use the [edit] link to improve your question (do not add more information via comments). Otherwise we are not able to answer your question and help you. Seriously: code is text, so show it as text, not as screen shot. And dont come in and rework crucial parts of your question later on like this, in a way that changes context completely.
Answer: You can do this in one go by reading the network property of an ipaddress.ip_interface
>>> import ipaddress
>>> ipaddress.ip_interface("192.168.0.161/255.255.255.0").network
IPv4Network('192.168.0.0/24')

You can go further and directly get your network address as a string from the IPv4Network's with_netmask property
>>> ipaddress.ip_interface("192.168.0.161/255.255.255.0").network.with_netmask.split('/')
['192.168.0.0', '255.255.255.0']

This will also work for IPv6 addresses
>>> ipaddress.ip_interface("2001:0db8:85a3:0000:0000:8a2e:0370:7334/64").network
IPv6Network('2001:db8:85a3::/64')

Answer: look at this example
from ipaddress import IPv4Address
import re

class MyIPv4(IPv4Address):
    def __and__(self, other: IPv4Address):
        if not isinstance(other, (int, IPv4Address)):
            raise NotImplementedError
        return self.__class__(int(self) & int(other))

    @property
    def binary_repr(self, sep=".") -> str:
        """Represent IPv4 in binary"""
        return sep.join(f"{i:08b}" for i in self.packed)

    @classmethod
    def from_binary_repr(cls, binary_repr: str):
        """Represent IPv4 ifrom binary to human readable view"""
        i = int(re.sub(r"[^01]", "", binary_repr), 2)
        return cls(i)

addr = MyIPv4("192.168.0.2")
mask = MyIPv4("255.255.255.0")

print(f'{addr} & {mask} is {addr & mask} network')
print(f'{addr.binary_repr} & {mask.binary_repr} is {(addr & mask).binary_repr} network')

source
Comment: Please give attribution when you copy code from another source.

Calculate the address of the subnet


Understanding coordinates with respect to orthonormal bases.

Question: If you have an orthonormal base $B$ of $\mathbb{R}^2$, you can calculate coordinates $\vec{x} \in \mathbb{R}^2$ with respect to $B$:
$$[\vec{x}]_B = (\vec{x}\cdot B_1 , \vec{x}\cdot B_2)$$

I know how to calculate that alright. But what I don't understand is...
... so what? What is the point of doing this? What is this useful for? What is (visually) happening to $\vec{x}$?
Additionally, if I have TWO bases $A,B$ of the same subspace, and $\vec{x}$ a vector of such subspace, is
$$[\vec{x}]_A = [\vec{x}]_B$$
True?

As you can see, although I know how to perform the calculation, I don't know why would I ever want to do this, or what does it imply.
For instance, I know how to calculate the orthogonal complement of a subspace, which I find pretty cool because, well, you have all the the vectors that are orthogonal to it. But converting a coordinate with respect to an orthonormal base? What for?
Comment: What use is it to know the coordinates of a vector in $R^3$ normally?
Comment: This is generally more useful in physics (at least from my experience) where you can greatly simplify problems by choosing the right orthonormal basis to transform the problem into.
Comment: I've recently answered a question where changing to another basis can make the problem easier. Hope it will be useful.
http://math.stackexchange.com/questions/838174/linear-transformation-with-the-matrix-a-mirroring-in-a-plane-show-that-aa/838189#838189
Answer: Let's say you have $\vec x$ in terms of a basis $C$.  That is, you have
$$\vec x = x_C^1 C_1 + x_C^2 C_2$$
Now, let's say that you have the basis vectors $B_1, B_2$ in terms of the basis vectors $C_1, C_2$.  That is, you have
$$B_1 = B_{1,C}^1 C_1 + B_{1,C}^2 C_2$$
and similarly for $B_2$.
Then, you can change basis to get the expressions for $x_B^1$ and $x_B^2$ merely by carrying out the dot product formula you've been given, rather than using a whole change-of-basis matrix as you might be taught using classical linear algebra.  This is entirely equivalent to that procedure--you change $B_1, B_2$ into the basis $C$, after all--but often times you express one set of basis vectors in terms of another basis anyway.
What happens to $\vec x$ here is a bit of a point of view thing.  A more pure-mathematics type answer might say be that vectors themselves are indistinguishable from collections of components, and as such, a basis transformation is an actual transformation of the vector.  A more physics type of answer would be that vectors don't necessarily change due to change of basis, that we merely have the freedom to use any basis we choose, and any change of basis changes the coordinates without changing the overall direction of the vector.  This is a little more in line with the expressions I used above.  The distinction here is pretty slight: both physicists and mathematicians need to be familiar with using active and passive transformations both.

About your question about the bases $B,C$ that each span a particular subspace:  the expression $[\vec x]_C$ literally means "the components of $\vec x$ in terms of the basis $C$".  Well, $B$ and $C$ are two different bases; even though they span the same subspace, one would not generally expect the coordinates with respect to two different bases to be the same.  It doesn't matter that they span the same subspace.
Answer: Nothing is happening to $\vec{x}$; rather $\vec{x}$ is being projected onto the elements of the basis. You are able to represent $\vec{x}$ in way such that the projection of $\vec{x}$ on a single basis element is relatively "independent" of the projection of $\vec{x}$ on other elements. Your basis elements are also of an appealing size, such that the projection takes less computations than usual and that one can fairly compare the size of the coordinate of $\vec{x}$ in one direction with the size of the coordinates of $\vec{x}$ in other directions.
From a very practical standpoint, representations in terms of orthonormal bases are preferred for scientific computing because they minimize computations and reduce numerical error.
Answer: Visually, in $\mathbb{R}^n$, it is a rotation (and possibly a reflection). The transformation takes a vector in one coordinate system, and lets you view it in another coordinate system.
This is an important aspect of geometry, because it is a transformation which preserves lengths and inner products. The fact that you can change basis at will is the reason why you can consider "space" independent of your choice of origin.
In the general language of linear transformations and vector+inner product spaces, this is very handy/sensible terminology when you want to find the Fourier series of a function. Suppose [roughly speaking] your vector space is the set of all functions $f(x)$ where $-\pi<x<\pi$. Your inner product is $\langle f,g\rangle=\int_{-\pi}^\pi f(x) g(x) dx$. The set of all functions $\cos(n x)/\pi$ for integer $n>0$, $\sin(n x)/\pi$ for integer $n>0$, and $1/(2\pi)$, form an orthonormal basis* for this space, and you can transform back and forth between the function $f(x)$ and the list of coefficients found by taking $\text{coefficient}=\langle f,\phi\rangle$, with $\phi(x)$ being any one of these orthonormal basis functions.
The concepts of change of basis transformations are used in anything involving regular Euclidean geometry (really, use of the word "orthonormal" referring to something like $x_1 y_1+x_2 y_2+\cdots=0$ means we're working in a Euclidean space). For example, change of basis concepts are used all the time in computer graphics programming.
They can also be used in special relativity, where "orthonormal" means something a bit different. Take for example my use of on this physics.se answer.
It's also used extensively in Quantum Mechanics, where you have a wavefunction $\psi(x)$. Because the whole concept of "change of basis" tells you that you can pick any basis you desire, physicists prefer to ditch the $\psi(x)$ notation, and instead work in the abstract, Dirac, or "bra-ket" notation. This vector denoted $|\psi\rangle$ is an element of the vector space of all functions from $\mathbb{R}^3\to \mathbb{C}$, but one doesn't have to assume that the thing is a function of position. It turns out (through some physics) that you can also write it as a function of momentum, merely through a change of basis.
So change of basis with an orthonormal basis of a vector space:

is directly geometrically meaningful
leads to insight, and
can help in solving problems.

*Technically they don't form a basis, they form a Hilbert basis, where you may only get the resulting vector by an infinite sum. I'm being very sloppy here - You might wonder what happens if the integral of $f(x) g(x)$ doesn't exist, or if they're pathological functions, etc. The theory of Hilbert spaces is what spells this all out, and it requires a lot of machinery mainly because "the set of all functions" includes some scary things.
Answer: Let $B=\{\vec{B}_1,\vec{B}_2\}$ orthonormal.
Coordinates of $\vec{x}$ in basis $B$ are the ortogonal projection of $\vec{x}$ over $B_1$ and $B_2$, i.e.
$\vec{x}=\mbox{proy}_{\vec{B}_1}^{\displaystyle\vec{x}}+\mbox{proy}_{\vec{B}_2}^{\displaystyle\vec{x}}=(\vec{x}\cdot\vec{B}_1)\vec{B}_1+(\vec{x}\cdot\vec{B}_2)\vec{B}_2\;$
Another way: The matrix $R^T=[\vec{B}_1\;\;\vec{B}_2]^T$ is orthonormal, i.e.,  $RR^T=I.$ Let  $\;\vec{x}=x_1\vec{i}+x_2\vec{j}\;$ and $\;\vec{x}=a_1\vec{B_1}+a_2\vec{B_2},\;$ i.e. $\;[\vec{x}]_{B}=(a_1,a_2)$, then
$\vec{x}=R^T\begin{bmatrix}a_1\\a_2\end{bmatrix}\Longrightarrow \;R\begin{bmatrix}x_1\\x_2\end{bmatrix}=\begin{bmatrix}a_1\\a_2\end{bmatrix} \Longrightarrow \begin{bmatrix}\vec{B}_1\\\vec{B}_2\end{bmatrix}\begin{bmatrix}x_1\\x_2\end{bmatrix}=\begin{bmatrix}a_1\\a_2\end{bmatrix}$
So, $a_1=\vec{x}\cdot\vec{B}_1$ and $a_2=\vec{x}\cdot\vec{B}_2$


source code syntax highlighting for trac?

Question: I've installed trac on my Ubuntu server but there is no php syntax highlighting.
I have installed Pygments using apt-get install but how do I configure trac so it uses highlighting in the svn source browser?
Answer: Trac should automatically detect pygments, assuming its installed in the same Python instance. You may want to have a look at the doc, particularly the bit about the mimeviewer section of trac.ini and make sure everything is ok.
The two most likely candidates I can think of are:
1) the PHP mime type is not properly registered or (even worse) your files were committed to svn with the svn property svn:mime-type set to text/plain (I had this happen on a large project, but resetting the mime-type property worked (Trac uses the file extension as a fallback if the mimetype isn't reported by the VCS).
2) Everything may be working, but the default style may not be working properly. Try adjusting the highlighting style either through the /prefs page on your Trac instance or through the pygments_default_style setting in trac.ini.


como passar parâmetro Url via get

Question: Estou tendo uma dúvida em relação a passar parâmetros de uma página para outra. Já tentei fazer de várias maneiras via get. Até consigo pegar o parâmetro, mas não são todos os parâmetros que consigo pegar. No exemplo abaixo, só consigo pegar o último id cadastrado na tabela...
Por exemplo:
Através de select, estou listando em forma de menu, no qual passo a variável id da tabela do banco de dados. Quando clico no link ele me redireciona para página que eu determinei, no entanto, só pega o último id cadastrado na tabela, mesmo apresentando uma url diferente, ele não pega os dados do id referente a este...
O código que eu estou usando é o seguinte:
prepare('SELECT id, categoria FROM teste ORDER BY categoria ASC');
$stmt->execute();
if($stmt->rowCount() > 0)
{
    while($row=$stmt->fetch(PDO::FETCH_ASSOC))
    {
        extract($row); $Link = "".$row['categoria'].""; ?>
".$Link.""?>

A outra página: "pagina"
prepare('SELECT * FROM teste WHERE id=" . $_GET["id"]');
if($stmt->rowCount() > 0)
    while($row=$stmt->fetch(PDO::FETCH_ASSOC)){ // Escreve dados da pessoa } ?>

está desse jeito.
Como disse no início, só consigo pegar e visualizar os dados do último id cadastrado na tabela. Onde está o erro?
Alguém pode me ajudar com exemplos práticos?
Obs.: Estou trabalhando o sistema com pdo. Desde, já agradeço a todos que de alguma maneira puder me ajudar a resolver essa questão. o htaccess está configurado assim:
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ $1.php

Já tentei outras configurações no htaccess, mas o problema persiste.
Answer: Sim. Resolvi fazer alterações.
Para chamar a outra página, coloquei assim também:
<a href="detalhe.php?id=<?php echo $id; ?><?php echo $id; ?>

Mas não resolveu o problema. Os dados são passados pela url, mas só pegar apenas um id, no caso o último cadastrado na tabela.
E na página que receberá os dados deixei assim:
<?php

    $stmt = $DB_con->prepare('SELECT * FROM produtos WHERE id:$_GET["id"]');

    if($stmt->rowCount() > 0)

    while($row=$stmt->fetch(PDO::FETCH_ASSOC)){

        // Escreve dados da pessoa

    }

?>

...
O erro continua.
Até agora não consegui resolver o problema.
Obs.: Posso passar os códigos das duas páginas se você quiser, para ver se consegue ver onde está o erro.
Comment: Ok, pode colocar. Tanto eu quanto os demais podemos dar uma olhada
Comment: Por favor mostre o código das páginas, parecem existir alguns erros de sintaxe.

como passar parâmetro Url via get


Is the wave equation a hyperbolic, parabolic, or elliptic PDE?

Question: I am a very beginner of PDEs. I want to study the wave equation in 1D and 2D for numerical methods. One basic question is which type the wave equation is. Elliptic, parabolic, or hyperbolic?
Comment: I think it is hyberbolic. Right?
Comment: Yes, it is hyperbolic. If you think of $\partial/\partial x=X$ and $\partial/\partial t=T$, the equation looks like $(X^2-T^2)u=0$, and this looks like the equation of a hyperbola. (The notion of the symbol of a differential operator makes this rigorous.)
Answer: Generally speaking, wave equations are hyperbolic. They have the similar form that
$$\frac{\partial^2u}{\partial t^2}=a^2\Delta u,$$ where $\Delta$ is the Laplacian and $u$ is the displacement of the wave.
Typical examples are acoustic wave, elastic wave, and electromagnetic.
In one dimensional, the equation is written as $$\frac{\partial^2u}{\partial t^2}=a^2\frac{\partial^2u}{\partial x^2}.$$
The general solution is
$$u(x,t)=u(x-at)$$ or $$u(x,t)=u(x+at).$$
Comment: * grumble * Schroedinger equation is not a wave equation, and it is not hyperbolic.
Comment: @WillieWong You mean to say that "Schroedinger equation is a wave equation", I guess.
Comment: @L.K. no, I meant exactly what I wrote. The post has been edited since my comment, which was directed at the original version of the answer. See the edit history.
Comment: This answer does not explain why it is hyperbolic


What is the ratio of the side length of a regular hepatgon to the side length of the internal heptagon?

Question: Given a regular heptagon with side length 1, create a star heptagon by connecting every vertice.

Note that removing the "points" of the star yields a similar heptagon. I want to know the side length of this internal heptagon (blue sides) in relation to the side length of the original heptagon.
The blue lines: $$ \rho = 2cos(\pi/7)
$$
The green lines: $$ \sigma=4cos^2(\pi/7) - 1
$$
[Golden Fields: A Case for the Heptagon, Peter Steinbach, Albuquerque Technical-Vocational Institute, Mathematics Magazine, Vol. 70, No. 1, February 1997]
No idea where to start :(
Answer: Refer to the following diagrams:-
Comment: Law of Cosines:

$$ c^2 = a^2 + b^2 - 2abcos(\theta) $$
Comment: Law of Sines:

$$ a / sin(A) = b/sin(B) = c / sin(C) $$
Comment: @LXE Sorry. Don't understand your comments.
Answer: Thank you Mick for the approach.
Given:
$\sigma = 4cos^2(\pi/7) - 1 $ ,  $\rho = 2cos(\pi/7)$
Law of Cosines
$$ c^2 = a^2 + b^2 - 2ab*cos(C)
$$
Law of Sines $$a /sin(A) = b / sin(B) = c/sin(C)$$
Since $ \sigma $ and $\rho$ are given, we can subsitute these in for a, b, and c to determine angle C (which I will call $\theta$ from here on)
 $$ \sigma^2 = \rho^2 + \rho^2 - 2(\rho)(\rho)cos(\theta) $$
$$\sigma^2 = 2\rho^2 - 2\rho^2cos(\theta) $$
$$ \sigma^2 / 2\rho^2 = 1 - cos(\theta)$$
$$ cos(\theta) = 1 - \sigma^2/2\rho^2$$
$$ \theta = arccos(1 - \sigma^2/2\rho^2)$$
$$ \theta = arccos(1 - ((4cos^2(\pi/7)-1)^2/2(2cos(\pi/7))^2))$$
$$ \theta \approx 1.3463968515384828164839900214055012360845011711607596$$
Now, with $\theta$, and the knowledge that the interior angle of a regular heptagon is $5\pi/7$, we can use the law of sines to determine the blue star's side length. The triangle, which is formed by the large heptagon's side length and the blue star's side lengths, is isosceles, and the base angles (i'll call them $\gamma$) are $(5\pi/7 - \theta)/2$. The vertex angle is equivalent to $\pi - (5\pi/7 - \theta)$, and i will call this $\beta$. We know that the red side length is 1. By the law of sines, the blue star side length (i'll call this $\delta$).
This gives:
$$\delta / sin(\gamma) = 1 / sin(\beta) $$
$$\delta = sin(\gamma)/sin(\beta) $$
$$\delta =  sin(1/2(5\pi/7-arccos(1-(4 cos^2(\pi/7)-1)^2 /(2(2cos(pi/7))^2))))/sin(2\pi/7+arccos(1-(4 cos^2(pi/7)-1)^2/(2 (2 cos(pi/7))^2))) $$
$$\delta \approx 0.5549581320873711914221948710064104810672888624709100 $$
Back to the law of cosines a final time to find the length we're primarily interested in. This time, $\theta$ is known, and the congruent side lengths $\delta$ are known. We'll call the final answer, the small heptagon side length $x$.
$$ x^2 = \delta^2 + \delta^2 - 2(\delta)(\delta)*cos(\theta)
$$
$$ x^2 = 2\delta^2 - 2\delta^2cos(\theta)
$$
$$ x = (2\delta^2(1-cos(\theta)))^.5
$$
$$ x = \delta(2-2cos(\theta)^.5
$$
Therefore, $x$ is exactly:
$$ (-1/4 (4 cos^2(\pi/7)-1)^2 sec^2(\pi/7))^.5(sin(1/2 (5\pi/7-arccos(1-(4 cos^2(\pi/7)-1)^2/(2 (2 cos(\pi/7))^2)))))/(sin(14\pi/49+arccos(1-(4 cos^2(\pi/7)-1)^2/(2 (2 cos(\pi/7))^2))))
$$
or for practical purposes:
$$ x \approx 0.692021471630095869627814897002069140197260599321894 $$


false implication (A => B) = 0

Question: this is a question about logical implication.
I need to prove that the implication $X \Rightarrow Y$ is verified. I use a proof by contrapositive, that is, I assume $Y = 0$ and I want to prove $X = 0$.
Now $Y$ itself is an implication, let say $Y := (A \Rightarrow B)$. My assumption is then translated into $ (A \Rightarrow B) = 0 $. My question now is the following.
Saying that $ (A \Rightarrow B) = 0 $ is equivalent to assume $(A=1) \Rightarrow (B=0)$?
Answer: Not quite. $(A\Rightarrow B)=0$ is equivalent to "$A=1$ and $B=0$", or, if you will, $A(1-B)=1$.

false implication (A => B) = 0


Sample size calculation for correlation study

Question: I am planning a study to assess the correlation of perceived stress in medical students and their academic performance. After a literature review, it appears that one previously done recent study has reported a correlation coefficient value of 0.47. But when I use this value to calculate my required sample size through some online calculators, my N value comes out to be only 45.
Not sure if I'm doing something wrong, can someone kindly point me out to a standard formula for sample size calculation in correlational studies?
Comment: What alpha and power did you specify? And you testing 0.47 against 0? Or some other value?
Answer: I would be wary of using the published value of r, 0.47, as the basis for your sample size calculations.
What if the true correlation is say 0.25? If that were the true population correlation, would you want your study to find a "significant" result? If so, compute the sample size for r = 0.25 (or even smaller). More generally, try to find the sample size that can detect (with reasonable power) the smallest effect (correlation coefficient for this example) you would care about.
Answer: To run the power analysis, you need to know three of the four to calculate the last one:

Number of observations
Effect size (correlation coefficient)
Significance level
Power

You have stated the effect size (correlation coefficient) in your question to be 0.47. Next, let's decide to use the conventional significance level $\alpha = 0.05$. A typical choice for the power is $p = 0.8$. Using the library pwr in R, we get
<code>> pwr.r.test(n=NULL, r=0.47, sig.level=0.05, power=0.80, alternative="two.sided")

     approximate correlation power calculation (arctangh transformation)

              n = 32.38727
              r = 0.47
      sig.level = 0.05
          power = 0.8
    alternative = two.sided
</code>
Alternatively, we could set the threshold upper:
<code>> pwr.r.test(n=NULL, r=0.47, sig.level=0.05, power=0.95, alternative="two.sided")

     approximate correlation power calculation (arctangh transformation)

              n = 52.12905
              r = 0.47
      sig.level = 0.05
          power = 0.95
    alternative = two.sided
</code>
You don't need very large sample size because $r=0.47$ is already quite strong relationship.
Answer: Here is another example using GPower expressed in graph, with sample size versus power:

A sample of 45 seems to be reasonable, with power > 0.9.


How to make sense of graphing relationships?

Question: Let x be an apple (x = apple).
Let y be an orange (y = orange).
let 3x = 2y be a proportional relationship. That is, having 3 apples is the equivalent as having 2 oranges.
Now lets graph our relationship:
Y
9           1
8
7
6       1
5
4
3   1
2
1
0 1 2 3 4 5 6 7 8 9 X

The question is, if I am saying that x + x + x = y + y, then why the graph is showing 2 apples in the apple dimension and 3 oranges in the orange dimension. It sounds like the opposite of what I am trying to say.
Instead, I was expecting 3 apples in the apple dimension and 2 oranges in the orange dimension:
Y
9
8
7
6                 1
5
4           1
3
2     1
1
0 1 2 3 4 5 6 7 8 9 X

Why this looks counter intuitive?
Comment: Here's your confusion: $x$ is "apple" or $x$ is the amount of apples?
Comment: @YGranja You're using $x$ and $y$ to label the axes, which means that you're using $x$ as "amount of apples" and $y$ as "amount of oranges"
Comment: You appear to be confusing "apples" as units with "number of apples".  Let's do inches and feet instead.  There are, of course, $12$ inches in a foot.  Thus $12$ inches = $1$ foot as units.  however it is not the case that $12$ times the number of inches equals the number of feet.  Indeed, phrased this way, you need $\frac 1{12}$ in place of $12$.
Comment: @jjagmath, the context is presented as x being a single unit of apple. Note that I am not assigning a value/price to a single unit of apple.
Comment: "having 3 apples is the equivalent as having 2 oranges" - this does not define a direct proportion. You should say that the ratio of apples to oranges (or vice versa) is constant.
Comment: @Vasili, When I say 3 dollars = 2 euros or 3 dollars is the equivalent as 2 euros, isn't that a direct proportion?
Comment: @YGranja: No, this is only one data point which does not define a relationship. But if you say "for every three dollars, a bank gives two euros", this defines many data points. This also means that for $x$ dollars you will get $\frac{2}{3}x$ euros as the ratio of euros to dollars is $2:3$.
Comment: Take a look at ["Ratio" and "proportion" confusions](https://math.stackexchange.com/a/4331538/21813) and [What does being proportional mean?](https://math.stackexchange.com/a/4393103/21813).
Answer: If

3 dollars = 2 euros

then the proportionality constant is
$$
\frac{3}{2}\frac{\text{dollars}}{\text{euro}}
$$
which is just another way to write the number $1$.
Then the relationship is
$$
\text{quantity of dollars} =
\frac{3}{2} \frac{\text{dollars}}{\text{euro}}
\times \text{quantity of euros}.
$$
If you draw the graph with quantity of euros on the $x$-axis and quantity of dollars on the $y$-axis the line will have slope $3/2$ and go through the point $(2,3)$.
Answer: Your equation 3x=2y is wrong, if x is the number of apples, put in x=3  and you know y=2 so you would have $3*3=2*2$ and you see it is wrong.
the relation of number of apples to number of oranges x/y=3/2 and so you have 2x=3y your second graph saying "let x be an apple" is misleading , say x is the number of apples  ans always try you equation with numbers you know.
Comment: When I say 3 dollars = 2 euros, am I misleading the ratio between dollars to euros?
Comment: If you say 3 dollars = 2 euros, it is not misleading, if you use it right, which is convenient, when traveling, since you know if you spend 200€ you have spend 300$ so you multiply each side with the same number, here 100. but if x is the number of $ and y the number of € and you write 3x=2y you will get wrong results  y=300 will give you x=400/3$=133$ and you think this is cheap and buy it!
so you need the exchange rate $/€=3/2 and will have x/y=3/2, 2x=3y
Answer: You are misinterpreting what $3x=2y$ means. If x=(number of apples) and y=(number of oranges), then $3x=2y$ does not means that 3 apples are equivalent to 2 oranges. This tells you that 3 times the number of apples is equal to 2 times the number of oranges. So, if you have 3 apples, you have $3\cdot3=9$ which is 2 times the number of oranges, so the oranges are $\frac{9}{2}$, so you have 4 and a half oranges.
In order to visualize it graphically, it is better to isolate the $y$ dividing both sides by its coefficient, so the equation becomes:
$$y=\frac{3}{2}x \ , $$
which means that for each apple (x) you have $\frac{3}{2}$ oranges, i.e. one orange and a half.
Comment: I don't see why that is the case, you seem to present a direct relationship very similar to other answers. I will cast a vote up sice I don't see anything wrong here.
Comment: So you are telling me that 3x = 2y does not means that 3 dollars are equivalent to 2 euros, assuming that x and y are acting as dollars and euros?
Comment: Exactly, 3x=2y mathematically means that 3 times the dollars is equal to 2 times the euros. You are confusing variables (x and y which can stay for quantitative of dollars and quantitative of euros) with unit measurements. If you write 3dollars=2€ it means what you are saying, because dollars and € are just unit measurements, in fact you can't change € and dollars like you change x and y which are variables.
Comment: Ps: I don't understand why I got two undervotes, did I say something wrong? Please correct me if it is the case.
Comment: @SilvioM More than one year later, but I can guess why this answer got downvotes. The OP's confusion appears to come mostly from confusing the two statements "x is the value of an apple" and "x is the number of apples" (which is a legitimate confusion, and this error creeps in the work of even experienced people occasionally; it's a bit like making a sign error or confusing left and right). In fact the OP's post begins with "Let x be an apple." And your post starts with "x=(number of apples)". So I can guess that the downvoters thought this answer was adding to the OP's confusion.


why do i get an SPF Softfail?

Question: I installed SPF on my LAMP server with postfix.  But for some reason, I get this error
Received-SPF: softfail (mta1070.mail.re4.yahoo.com: domain of transitioning firstname.lastname@example.com does not designate 188.8.131.52 as permitted sender)

I have two questions:
1) how do I trouble shoot this error
2) I've been looking through my configuration files in an attempt to change email@example.com to email@example.com because anotherurl.com has the correct SPF TXT records.  Where do i go to change this?  I tried editing myhostname under /etc/postfix/main.cf, but it didn't do anything.
Comment: The error is due to the wrong e-mail address showing up in the From: field, which it seems you have identified in #2. I don't know Postfix, but someone around here will.
Comment: Perfect!  I temporarily fixed the problem by changing the IP address A Record of websiteurl.com to the same as anotherurl.com.  So now email servers can find the SPF TXT records.  But I'll need a better solution, because websiteurl.com will be down until i remap the IP address back to original.
Comment: the www-data suggests that these are being sent via a script, if I'm correct what language?
Comment: @obsidian - correct.  I'm using PHP5 with Apache 2 on Ubuntu 8.04
Answer: Since you're sending via PHP you need to set the headers properly and use the last parameter of the mail function.
Something like the following will work
<?php
$email@example.com';
$to="email@example.com";
$subject="this is an email";
$headers = 'MIME-Version: 1.0' . "\r\n".'Content-type: text/html; charset=UTF-8'."\r\n".'From: '.$fromemail."\r\n" .
$headers .= "Reply-To: ".$fromemail."\r\n";
$headers .= "Return-Path: ".$fromemail."\r\n";
$extra='-r '.$fromemail;
mail($to,$subject,$message,$headers,$extra);

why do i get an SPF Softfail?


Criar/manipular arquivo dentro de um diretório diferente do que está o main.cpp

Question: Isto funciona, cria um arquivo e coloca o que eu quero dentro dele:
#include <fstream>
#include <vector>

using namespace std;
int main() {
    ofstream arquivo;
    arquivo.open("arquivo.txt");
    vector<string> v;
    v.push_back("linha1");
    v.push_back("linha2");
    v.push_back("linha3");
    if(arquivo.is_open()){
        for(auto n: v) { arquivo << n << endl; }
    }
}

Mas isto não funciona, se eu quero criar um novo arquivo dentro de uma pasta chamada "pasta", ele não dá erro, só não cria o arquivo. Faz absolutamente nada:
#include <fstream>
#include <vector>

using namespace std;
int main() {
    ofstream arquivo;
    arquivo.open("pasta/arquivo.txt");
    vector<string> v;
    v.push_back("linha1");
    v.push_back("linha2");
    v.push_back("linha3");
    if(arquivo.is_open()){
        for(auto n: v) { arquivo << n << endl; }
    }
}

Answer: O erro está na hora de abrir um arquivo inexistente para gravação. A chamada do método ofstream::open() cria um novo arquivo caso ele não exista, porém, não cria diretórios!
Você pode incluir um tratamento mais elaborado de erros usando a macro errno da biblioteca padrão cerrno em conjunto com a função std::strerror() da biblioteca padrão cstring.
Vejamos como entender o erro:
#include <fstream>
#include <vector>
#include <cstring>
#include <cerrno>
#include <iostream>

using namespace std;

int main( void ) {
    ofstream arquivo;
    vector<string> v;

    arquivo.open("diretorio/arquivo.txt");

    if(!arquivo.is_open()) {
        cerr << "Erro abrindo o arquivo para gravacao: " << std::strerror(errno) << endl;
        return 1;
    }

    v.push_back("linha1");
    v.push_back("linha2");
    v.push_back("linha3");

    for(auto n: v) { arquivo << n << endl; }

    return 0;
}

Compilando:
$ g++ -std=c++11 teste.cpp -o teste

Saída:
Erro abrindo o arquivo para gravacao: No such file or directory

Uma alternativa não padrão, porém elegante para resolver seu problema é usar a biblioteca boost::filesystem, que possui uma função chamada create_directories(), vejamos:
#include <fstream>
#include <vector>
#include <cstring>
#include <cerrno>
#include <iostream>
#include <boost/filesystem.hpp>

using namespace std;

int main( void ) {
    ofstream arquivo;
    vector<string> v;

    boost::filesystem::create_directories("diretorio" );

    arquivo.open("diretorio/arquivo.txt");

    if(!arquivo.is_open()) {
        cerr << "Erro abrindo o arquivo para gravacao: " << std::strerror(errno) << endl;
        return 1;
    }

    v.push_back("linha1");
    v.push_back("linha2");
    v.push_back("linha3");

    for(auto n: v) { arquivo << n << endl; }

    return 0;
}

Compilando:
$ g++ -lboost_system -lboost_filesystem -std=c++11 teste.cpp -o teste


Override core Js file

Question: Working on my theme
I need to override a core Js file ..\core\modules\contextual\js\contextual.js
My code from theme.info
libraries-override:
  contextual/drupal.contextual-links:
    js:
      js/contextual.js: js/override/contextual.js

The problem is that the loading order of this component js files did change after the override which cause script errors :

So how can override file js core and still same order file?
Answer: Thanks can be done with with the hook_js_alter function
    function hook_js_alter(&$javascript) {
    $javascript['js/contextual.js']['data'] = drupal_get_path('theme', 'THEMENAME') . 'js/override/contextual.js';
    }

Comment: Hey @Sam!!, thanks for the example, I actually searched a lot to override the library inside my custom module and NOT in the theme as asked by @John. Using the ```libraries-override``` approach I was not able to achieve the goal so does that mean it is available for the theme only does not work for the module ?
Answer: This is a solution I've applied to override a base theme js Library by overriden js Library in custom theme:
Two files are concerned:

custom_theme.libraries.yml
custom_theme.info.yml

In .libraries.yml file :
mycontextextual.links:
  js:
    js/override/contextual.js: {}

In .info.yml file:
libraries-override:
  contextual/drupal.contextual-links: custom_theme/mycontextual.links

I hope it will help.

Override core Js file


MLB The Show Players League

Question: Some clip in a MLB The Show Players League video looks like some kind of video games. The guy pointed out by the red arrow seems to be manipulating a playstation controller.

Is "MLB The Show Players League" some kind of video game?
Comment: I'm voting to close this question because [it is a question about video games, which are not sports](https://sports.meta.stackexchange.com/questions/67/).
Comment: If you have any more questions about the video game you should ask them on [Arqade](https://gaming.stackexchange.com/)
Answer:
Is "MLB The Show Players League" some kind of video game?

"MLB: The Show" is a video game.
"MLB The Show Players League" is a league of players, one from each MLB team, playing MLB: The Show, a video game.
This article sums up "MLB The Show Players League" quite succinctly:

The "MLB The Show" players league will provide fans an opportunity to
  watch their favorite players play the video game [MLB: The Show], while also allowing
  them to interact with them through various streaming services.

MLB The Show Players League


pandas reading date column in a strange way

Question: hope you are all doing great;
I am in the middle of a small project regarding the analysis of TMDB, the data set is csv file with release_date column following M/D/Y

when reading the csv file in a jupyter notebook I used
tmdb_df = pd.read_csv('tmdb-movies.csv', parse_dates=['release_date'])
but the dates are not set correctly some date go to 2070 as pandas do this read a date like 4/5/1970 as 4/5/70.
how can I fix something like that? or how should i read the file
Comment: Please format this properly. it's hard to read
Comment: **[No Screenshots](https://meta.stackoverflow.com/questions/303812/)** of code or data. Always provide a [mre] with code, **data, errors, current output, and expected output**, as **[formatted text](https://stackoverflow.com/help/formatting)**. If relevant, plot images are okay. Please see [How to ask a good question](https://stackoverflow.com/help/how-to-ask). Provide data with [How to provide a reproducible copy of your DataFrame using `df.head(10).to_clipboard(sep=',')`](https://stackoverflow.com/questions/52413246), then **[edit] your question**, and paste the clipboard into a code block.
Answer: df['Date'] = df["Date"].dt.strftime("%m/%d/%Y")


keep the name of the input vector's element in the output of the function in R

Question: I have two functions f1 and f2. In its output, f1 always keeps the name of the element of the inputted vector x.
But in its output, f2 always deletes the name of the element of the inputted vector x.
Is there a way for f2 to keep the name of the element in its output just like f1?
x <- 1:10
x <- setNames(x, letters[1:10])

f1 <- function(x, n){

  sort(x)[n]
}
# EXAMPLE OF USE:
f1(x, 2)

# OUTPUT:
# b       # Notice "b"
# 2

f2 <- function(x, n){

  len <- length(x)
  sort(x, partial = len-n+1)[len-n+1]
}

# EXAMPLE OF USE:
f2(x, 2)

# OUTPUT:
# [1] 9     # Notice no name is attached to 9.

Answer: In sort function, it says that if partial is not null, names are discarded. See sort function documentation.
In f2, sort(x, partial = len-n+1)[len-n+1], just little more messy,
f2 <- function(x, n){

  len <- length(x)
  x[x == sort(x, partial = len-n+1)[len-n+1]]
}
f2(x, 2)

i
9

but this will keep name of value.


a simple question about casting integers in c++

Question: i have the following very simple code -
int x=15000
int z=0.7*x
cout<<"z = "<<z<<endl;

i get the output
z=10499

but if i change it to
int z=0.7*15000
cout<<"z = "<<z<<endl;

outputs
z=10500

i understand it has something to do with z casting the result to int
but why is it different in both cases ?
thanks,
EDIT -
i'm using ubuntu's 10.10 GCC build
Comment: I have 10500 (gcc 4.2)... what compiler are you using? is it exactly the code you have?
Answer: I suppose it's because of compiler, that simplifies arithmetical expressions at the compile time.
The first expression was computed using FPU (with finite precision), and the second one: by preprocessor (with "infinite" precision). Try running the program in release mode (or with -O2), the results should be the same for both expressions.
Answer: int z=0.7*x;
The double-precision value 0.7 is not exactly representable as a floating-point number; its hex representation is 3fe6666666666666 on most machines, which is less than the true value 3fe6666666666666... So the double-precision result of 0.7*x is less than its true value, and is rounded down. This is correct behaviour.
int z=0.7*15000;
The compiler, on the other hand, is clever enough to see that 0.7 * 15000 is representable exactly as 7 * 1500 = 10500. So it uses the correct result, instead of the result that would be obtained by compiling the expression and executing it.
Answer: I think ruslik has the correct answer to your question.
I would just add: Always keep your calculations in either float or double until the very last moment. That way you don't lose precision.
Try changing your code to this:
double z = 0.7 * 15000.0;
cout<<"z = "<<z<<endl; // Will need to include some formatting

or
int z = (int) (0.7 * 15000.0);
cout<<"z = "<<z<<endl;

Comment: Both these suggestions are no-ops, and do nothing to solve the problem.
Comment: I think this is good advice. If you need double precision then keep your variables in doubles. Use rounding as the last step, if necessary.
Comment: The problem is that 0.7*x gives a different result to 0.7*15000. See my answer below/above.


how do I append to a text file in java without overwritting?

Question: I am working on making a chatbot in java and I want it to be able to generate preferences(at random) on specific topics and write the preference to a file.  For example, if I ask the chatbot "do you like cake?" and it has not yet been asked about "cake" before, it will generate a random preference(true or false).  It then writes to a file("chatbotPreferences.txt" or something similar) its preference, which can be retrieved later if the subject of "cake" arises again.  The main problem I am having with this is the file overwriting every time I run the program.  So if I discuss "cake" with it, and it writes "cake=true" in the file, then I run it again and ask it about "pie" and "pie=false" might appear in the file, but "cake=true" is not listed.
Is there a way to prevent it from being overwritten or does anyone have any other ideas for doing this?  Thank You
Comment: go to this link [how-to-append-text-to-an-existing-file-in-java](http://stackoverflow.com/questions/1625234/how-to-append-text-to-an-existing-file-in-java)
Comment: Have you tried using a search engine with your question *verbatim*? This is asked so often, you shouldn't have problems finding it.
Answer: I don't know how you write the file, but using a FileWriter, it's quite simple:
Pass true as second parameter to the constructor.
Comment: I'm not having trouble writing to the file.  The problem is when I write a new preference, it overwrites everything else in the file.  I can not add something without it deleting everything else.
Comment: How do you open the file?
Comment: As @Robert Koch said, don't use a PrintWriter. Use a FileWriter instead, and create it using append mode.
Answer: You could use Scanner and a String ArrayList, to read in the data like so:
import java.util.*;
Scanner in = new Scanner(new File("chatbotPreferences.txt"));
List<String> things = new ArrayList<String>();
while (in.hasNext())
   things.add(in.nextLine());
in.close();

Then you could add things to your list using the add() method in ArrayList, like so:
things.add("cake=true");

Finally, when it comes time to save, just read everything from your list. There are various ways to save (and it sounds like you've already done this), but here is an example:
import java.io.*;
try {
   PrintWriter writer = new PrintWriter("chatbotPreferences.txt");
   for (String s : things)
      writer.println(s);
   writer.close();
} catch (Exception e) {
   e.printStackTrace();
}

Comment: Could you please accept the answer if it responds to your question?
Comment: OK!  Thank you all for the help.  I think I can figure it out from here.   :D
Answer: Like mentioned above you need to add true to the FileWrite constructor. Here is an example that shows it in action. If you run this code more than once it will add the text not overwrite.
import java.io.*;
public class FileWriting{
  public static void main(String[] args)throws Exception{
    FileWriter fw= new FileWriter("test.txt",true);  //by adding true you    can add to a pre-existing file
    PrintWriter pw= new PrintWriter(fw);
    pw.println("line 1");
    pw.println("line 2");
    pw.println("line 3");
    pw.println("line 4");
    pw.close();

    FileReader fr= new FileReader("test.txt");
    BufferedReader br= new BufferedReader(fr);
    String x;
    do{
      x= br.readLine();
      System.out.println(x);
    }while(x!=null);
    br.close();

    }
}


How to fix time on NTP server with a lot of machines synchronized by it

Question: I have one NTP server which has a wrong time setting which are 7 hours in the future (timezone was changed after machine shipment, but not the time). The server itself is not synchronized, but only has its local clock. On this server >10 clients synchronize their clock which leads to a whole group of servers with a wrong time.
How can I change the time on the NTP server that the correction is slewed and all clients will get corrected, too? I first tested with just a fix via "date MMDDhhmm" which let to the clients to disconnect from server (the asterisk in front of the server name in ntpq disappeared).
I do not know how all the synchronized services will behave when I change the time on all servers manually by setting the clock back 7 hours leading the systems to have files from the future. There may be crashes and the systems provide services for a fab production.
Comment: This is why you set the HWCLOCK to UTC and then have system clock do the tz conversion.
Comment: If you learn anything from this - and it looks like it'll involve downtime - **learn not to lie to NTP**.  You shouldn't advertise a machine as being an authoritative server unless it has a stratum-0 time source directly attached to it, or is synced to upstream servers that eventually are so sync'ed.
Comment: +1 You are right. I would not setup something like that. I am only the messanger in danger to get shot for this. ;-)
Comment: If this were only 1 client that was off, then there is a way to slowly update the time.  As this is the server, you will likely have to take the hit during a maintenance window that you plan with your org.  Stop ntp on all the servers.  Ensure your server is sync'd up with some stratum 1 servers and stable.  Then use ntpdate -b4 ip.of.your.ntp.server and start ntpd on the clients.  Make note of the time you did this in your internal tracking system to answer questions during your various audits as log timestamps will change.  Check on clusters that are sensitive to chrono time vs. internal.
Comment: It is even worse: The machines I talk about are all VMs which are not host synchronized (and the hosts of course have no time sync at all). I also do not have a chance to connect the NTP server to another time source, because the machines are isolated from the customer network. BTW.: I did not set this up, I only found the issue... ;-) Has someone a better idea than switching everything off? In a 24/7 environment it is not a good solution. Hopefully not the best.
Answer: When you talk about slewing the time, you are usually talking about small amounts of time.  The fix is performed with a call to adjtime(), or on linux maybe adjtimex().
From the ntpd man page:
   -x     Normally, the time is slewed if the offset is less than the step
          threshold,  which is 128 ms by default, and stepped if above the
          threshold.  This option sets the threshold to 600  s,  which  is
          well  within  the  accuracy  window  to  set the clock manually.
          Note: Since the slew rate of typical Unix kernels is limited  to
          0.5  ms/s,  each  second  of adjustment requires an amortization
          interval of 2000 s.  Thus, an adjustment as much as 600  s  will
          take  almost  14 days to complete.  This option can be used with
          the -g and -q options.  Note: The kernel time discipline is dis‐
          abled with this option.

I doubt then that you are going to want to wait for a 7 hour correction to happen at this speed.  It'd take over a year.  On linux adjtime on a 32 bit system is effectively constrained to a delta of about 2000 seconds.  64 bit systems probably make that a non issue, but the speed at which the change would take effect is still a concern.
So there's a threshold in the linux implementation, and presumably others, under which you get a 'slew' which is very slow, but above this the system clocks on master and clients will be stepped, which can proceed much faster.
There will also be another threshold where if the time difference between master and client is too large, the client will assume an error and not update.  From the ntpd man page:
   -g     Normally, ntpd exits with a message to the  system  log  if  the
          offset  exceeds the panic threshold, which is 1000 s by default.
          This option allows the time to  be  set  to  any  value  without
          restriction; however, this can happen only once.  If the thresh‐
          old is exceeded after that, ntpd will exit with a message to the
          system log.  This option can be used with the -q and -x options.

Note that the -g option is almost certainly not set for a daemon.  It's usually used as ntpd -gq, run as a one-off at system start-up, or manually which behaves much like ntpdate.  The panic threshold is presumably configurable at compile time though, so check the man page for your OS vendor(s).
It is pretty straight-forward to write a program which will make a series of time adjustments using any frequency and size of adjustment you choose.  You can do this on the ntp master, and it will serve the adjusted time to its clients, but you need to know what maximum size adjustment the client systems will accept, and what minimum threshold will cause them to perform a very slow slew.  To be safe, You should survey the ntp implementations on the client systems.
If you are updating systems with characteristics similar to default ntpd on linux without the -x option, then you could use a regime like making a half second adjustment every 5 seconds, and you'd get into sync over the course of about 3 days.    Making sub-second adjustments that do not cross a second boundary might help to avoid things like triggering cron jobs twice, but expect that you'll probably find some sort of side effects.
If you wind up in a situation where your servers are no longer all in sync with each other, then it gets messier.  If feasible, I'd want to monitor the time differences, and automatically stop doing the automated periodic updates if some servers are no longer following along, and raise an alert.
Comment: @dfc: There are devices for which that's appropriate, but hopefully you wouldn't be running production web apps on them.  NTP is mostly for ongoing minor tuning.  If you are 1000 seconds out, someone should be looking into what went wrong, and the error might be upstream not local.
Comment: "-g option is almost certainly not set for a daemon" Bold claim, bolder disagreement. `-g` is great for operating ntp daemons. It lets ntp start and figure things out on its own without  manual intervention. Why would I want ntp to not start? Same answer if you are managing more than 3 or 4 servers?
Comment: I granted the +50 bounty. It is not the answer I expected, but a good explanation why the wanted solution is not possible. Thanks!
Answer: As you know, the clients will remain synchronised if the clock change is within a small interval. On some systems this is as little as five minutes. Yours may be 10 minutes. You can jump the clock within that interval and the clients will slew to keep track.
I can see four options:

Do nothing, and live with the incorrect time indefinitely.
Reset the clock by four minutes (or nine minutes if you've got a 600 second interval) and repeat ad nauseum during the year that mc0e has calculated is necessary. You would really want to do this with a script. Allow for the time being incorrect for much of this year. Take copious notes of the time offset to correlate against production reports.
Take the servers down for a seven hour maintenance period (Christmas Day, anyone?) and fix all the clocks properly, in one sitting.
Jump the clocks and ensure that everyone knows there will be a seven hour reporting overlap. However, these same people should already know that the production times are off by seven hours, so you may find this is acceptable. (Obviously I don't know what impact this would have on your fab processes.)

None of the solutions is ideal. If production reporting times are important then option 2 is probably the worst of a bad bunch.
Comment: I agree that a 'slew' probably isn't the best option, but there's a difference between a slew and a series of small steps, which can happen quicker.  I'll clarify this a bit in my answer.
Comment: @mc0e I totally agree with you. However, without knowing the implications of stepping the time backwards in the OP's scenario I can only recommend it with caution. (If it was stepping forwards it would be so much easier.)
Comment: Agreed. Various things could happen twice.  We certainly don't have the info to make that assessment, but your word of caution is well placed.
Comment: The whole situation is messed up. I talked to some people and it will be either solution 3 or 4. Solution 4 has the issue, that we do not know how robust the services are. There is a lot of software involved of questionable quality. :-(


Laço infinito com um if dentro de um do em Java

Question: Boa noite. Estou realizando um trabalho da faculdade sobre um caixa eletrônico e estou com uma pequena dúvida. Estou criando um do para fazer o menu de repetição do caixa eletrônico, mas antes do usuário entrar no caixa, ele irá setar um valor para as contas, pois a variável saldo esta setada para 0. Após isso, ele será liberado para o menu do caixa. Mas após setar o valor o valor ele fica repetindo a mensagem "teste". Gostaria de uma ajuda.
Eis o código:
do{
           if(saldoCC<=0 && saldoCP<=0) {
               System.out.println("-----------------------------------------------------------");
               System.out.println("Saldo zerado em ambas as contas!");
               System.out.println("Para utilizar o caixa eletrônico sete o valor!");
               System.out.println("-----------------------------------------------------------");
               System.out.println("DIGITE O VALOR PARA REPOR O SALDO");
               System.out.println("-----------------------------------------------------------");
               System.out.print("Saldo da CONTA CORRENTE: R$");
               saldoCC = teclado.nextFloat();
               System.out.print("Saldo da CONTA POUPANÇA: R$");
               saldoCP = teclado.nextFloat();

               System.out.println("-----------------------------------------------------------");
               System.out.println("SALDO SETADO!");
               System.out.println("Conta Corrente: R$"+ saldoCC);
               System.out.println("Conta Poupança: R$"+ saldoCP);
           }else{
            System.out.println("teste");
           }

        }while(op != 3);

Answer: Observe que ele vai repetir o laço enquanto op for diferente de 3. Dentro do laço, em lugar nenhum ele muda a variável op. Assim sendo, supondo que op seja 3, então após ao menos um dos valores saldoCC ou saldoCP ser definido com algo maior que zero, o laço resultante ficaria assim:
do {
    if (condição sempre falsa) {
        // não importa mais
    } else {
        System.out.println("teste");
    }
} while (condição sempre verdadeira);

O que é equivalente a isso:
do {
    System.out.println("teste");
} while (true);

Para corrigir isso, não sei exatamente o que você faria, pois depende de informações que vão além do que você postou na pergunta, em especial de como você espera obter ou alterar o valor de op. Mas algumas das possíveis soluções seriam:

Colocar uma instrução break; em algum lugar.
Colocar uma instrução op = 3; em algum lugar.
Colocar uma instrução return; em algum lugar.
Lançar alguma exceção em algum lugar.
Retirar o laço do.
Comment: Boa tarde! obrigado pela ajuda, coloquei um break; após o System.out.println("teste"); e funcionou! esta repetindo como eu queria!


How to exclude page from Redis cache?

Question: I'm using Redis and need one dynamic page to be excluded from being cached. How can I do that?
Answer: Not sure how you are generating this dynamic page, but somewhere in the mix, you could put something along the lines of:
drupal_set_header('Cache-Control', 'public, max-age=0');       // set max age to 0
drupal_set_header('Expires', 'Sun, 18 Dec 1983 02:28:00 GMT'); // some date in the distant past

before any other output, eg, at the top/start of your page's menu callback or in right before you select its custom template if it has one.
If this doesn't work, a quick hack would be to do a drupal_set_message('Welcome to my dynamic page'); which would cause drupal's core functions to try not to cache the page :)
Comment: Thanks Jim, I haven't yet tried your option, but I found a solution for my problem. The page was driven by Views so I went to Views settings and turned off caching there. It was that simple. If anyone is looking for it, it's at the bottom of the Advanced section.
Answer: How about this snippet in hook_init()?
$cache_class = variable_get('cache_class_cache', NULL);
if (isset($cache_class) && class_exists($cache_class)) {
  // Check if Redis is being actively used as a cache backend
  if ($cache_class == 'Redis_Cache') {
    if (TRUE) { // Add condition here for your page
      drupal_page_is_cacheable(FALSE);
    }
  }
}

Comment: Thanks Amarnath, According to [Drupal API](http://api.drupal.org/api/drupal/modules%21system%21system.api.php/function/hook_init/7) hook_init() is not called on cached pages. Instead you should use hook_boot()
Comment: Also look at http://drupal.org/project/cacheexclude

How to exclude page from Redis cache?