Tom Misch - It Runs Through Me Theory Question

Question: I have a question regarding the chord progression for It Runs Through Me and how it works from a theory standpoint.
It seems to be in the key of Bm. With the chord progression going something like [Bm7 -> D7sus2 -> Gmaj7 ->B/F# ->Bb aug?]. The last chord is up for debate. A couple of chords are not diatonic, like D7sus2 which looks like a secondary dominant to me.
But I'm not sure how he fits in B/F# and Bb aug? How do these chords fit in to the key? Chord substitution?
Answer: I just had a listen and it sounds to me like the chords on the chorus are
Bm7  | D7sus4 | Gmaj7 | C#m7b5 F#7#9

which you seem well-equipped to analyze on your own. The bassist occasionally plays a C on the final chord, creating a C13 sound (a tritone substitution: notice that the shell voicings for F#7#9 and C13 are identical).
On the verses, he substitutes B/C# for the C#7b5, which you can think of as a hollowed-out C#m11 (without the third and fifth), itself an embellishment of ii7 borrowed from the parallel major. The guitar voicing is x4x442, as you can see in this screenshot at 2:02:

Playing a B triad over a C# root in a C#m7 context is a common guitarist trick. It lets you incorporate the upper extensions of the C#m11 chord without the muddiness (and fingering challenges) that can occur when the minor third is present.
Meanwhile, substituting ii7 for ii7b5 in a minor key is a common flourish in bossa nova because it allows you to create chromatic motion in a middle voice: here G♯, the fifth of C#m11 → G♮, the ♭9 of F#7b9 → F♯, the fifth of Bm. This guitarist didn't choose voicings that do this, but that possibility may help explain why the borrowed ii7 is relatively common in this genre.
Comment: I got a chance to work this out a little more at my instrument and have added a screenshot of the suspect chord. Take a look, @jrock, and see if this answers your question, and thanks for showing us a cool tune!
Answer: I'd say that B/F♯ is, in context, an attempt to pull off a I 6/4 of iv - a tonicization of the subdominant.
Then we learn that's abortive (assuming your last chord is correct) and it moves to the altered dominant of A♯aug. A♯aug works as an altered dominant chord because it contains the leading tone of B minor, A♯. (A♯aug is enharmonic with B♭aug but makes more sense in B minor.)
The B/F♯ chord's movement to A♯aug is something I cannot fully explain. The voice leading is smooth for the upper voices but a small leap for the lowest notes. Maybe a I - Valt - i feel is what's aimed for?
Comment: `B/F#` could be `I 6/4` borrowed from the parallel major, and then one might think of the `A#+` instead as a `F#+` in first inversion, `V+` being a common substitution for the dominant in minor.


What are some good pop-up dialog boxes for Ruby on Rails

Question: I want to use modal pop-up windows in our web app in Ruby on Rails.  Note that I don't want to create a new browser window, but a sub-window inside the existing webpage.  We've tried things like TinyBox, but there are issues with returning error information from inside the controller.  Any good method or tool that works well in ruby?
Comment: Do not use TinyBox.
It's undocumented and the source code is obfuscated.
You'll have trouble all the time.
Answer: There's also prototype-window.
Comment: Worked with is some and its easy and powerful to use.
Answer: I've never used it myself (not yet at least) but have you tried RedBox?
Comment: Redbox looks pretty basic.  Does anyone know how to get it making some nice (transparent) borders etc like linkedin or facebook?  Would like to get something that is a littler prettier, for lack of a better word.
Answer: I'm investigating ModalBox at the moment and it's looking promising.
There's a Google Group and Rails plugin which replaces the basic confirm popup with a modal dialog box.
Answer: Try TopUp! It is developed in a Rails application and you can get it from GitHub.
Please note that it is still beta. Feedback is always welcome ;)
Answer: Facebox, jquery, that Github use is the best one. There is also a prototype version.
Comment: Sweet!  I always wanted to use facebox but couldn't justify loading jquery on top of prototype JUST for that.  Awesome to know there is a prototype version, thanks!
Answer: I've used Lightbox Gone Wild for a while now, though I've modified it to display a DIV or other element that's already on the page (though hidden) and then return it to it's parent when the box is closed.  I've used it make make Wizards that guide the user through a process.
Answer: I've used facebox_render for all my rails projects. It's really easy to use and provided complete helper. You can easily render html or javascript in your RESTful controller.
Answer: I have tried several of the ones mentioned above but after twiking it a bit I found that http://www.methods.co.nz/popup/popup.html works better for me, the only problem is that you have create an error routing similar to the one Rails uses, when returning to the popup window with errors the pop up window does not have a way to handle it


Wordpress plugin to display new content from other websites

Question: It there such a plugin in wordpress that can take a list of links to arbitrary websites and return/display the newest content, like for example newest published article?
Answer: You're going to want an RSS plugin for this, the best one available seems to be http://www.wprssaggregator.com/
This will let you import RSS feeds from external websites into posts and such.
Comment: What if the website does not offer RSS feed? Is it possible to do if for any website with arbitrary content?
Comment: @Jaka not unless you want to scrape content from their websites manually to put on your own, it's a questionable practice and I doubt you'll find any WordPress tools for doing that.


Linux gateway forwarding issue

Question: how do I enable packet forwarding for an ethernet dsl modem? Must this be done with iptables?
Comment: Why did you remove 95% of your question? You've removed all the useful information and made it harder to answer for your specific problem.
Answer: You enable packet forwarding on a Linux (2.6.x kernel) router by executing the following command as root ...

# echo "1" >/proc/sys/net/ipv4/ip_forward

You will need to execute this command every time you start/reboot your machine.  Add the command to your equivalent of /etc/rc.local so that it is automatically executed for you.
Comment: or put "net.ipv4.ip_forward=1" in /etc/sysctl.conf, which is the easiest way of setting values in proc.
Answer: Log in as root.
Type the following exactly as it appears
echo 1 > /proc/sys/net/ipv4/ip_forward

Then type this exactly as it appears
echo "net.ipv4.ip_forward = 1" >> /etc/sysctl.conf

The first line sets packet forwarding in the kernel; the second line ensures that it survives a reboot.
Answer: I'm assuming this is an DSL router presented as an ethernet device. Are you able to ping the internal interface of the router? If not, there's a configuration problem on the lan side of the device.
Does the router have diagnostic tools built in? Can you ping out from the router? Can you ping an internal device? If you can, then the problem lies in the forwarding between the two interfaces. It could be a firewall or a possible NAT problem.
If you can't ping out, then there is a problem with the DSL connection. If you can't ping in, then there's a problem with the LAN interface.
Comment: It hasn't logged onto your ISP properly, I'm guessing it hasn't been given the external gateway address. Use it's admin screen to disconnect and then reconnect.
Comment: I can ping the address on ppp0, just not the isp
Comment: Is this a USB or Ethernet modem?
Comment: ethernet modem..
Comment: Yes, it would appear that some settings were not correctly set on the new modem. I'd contact the ISP support and get them to help you check all your settings.
Answer: If I understand your question correctly, iptables won't help you.  It sounds like you can ping your ethernet router, but nothing beyond it.  To figure this out, you need to tell us what router model you have and whether you have static or dynamic IP addresses.

Linux gateway forwarding issue


Search in encrypted fields without decrypting the field

Question: I want to encrypt my data before save them in my database.
One of my fields is a numeric value and I want to search in the table items upper or lower than a specified item. For example I save my data 3287 encoded, and I want to find which items has value upper than 500.
In the case of huge rows (For example 100,000,000 rows) it is too inefficient to decrypt each element and check the value.
Is there any better solution for my problem?
Comment: Try to research in the [homomorphic encryption](http://en.wikipedia.org/wiki/Homomorphic_encryption) direction. There is not lot, if any at all, of ready to use things in that field yet. Also check [this](http://stackoverflow.com/questions/1023981/practical-applications-of-homomorphic-encryption-algorithms), [this](http://stackoverflow.com/questions/2576145/calculate-the-average-of-three-encrypted-numbers) and [this](http://stackoverflow.com/questions/15109530/encryption-that-allows-performing-mathematical-operations-on-encrypted-numbers) questions.
Comment: This is a very challenging problem for which you aren't likely to find excellent solutions readily available.
Comment: @owlstead Sorry, but I didn't understand your comment.
Comment: @Mohammad Ah, yes, I was responding to Oleg's comment as homomorphic encryption is possibly the answer (or at least the problem) you are looking for. As a workaround, you may add an attribute to each encrypted value to show in which range it resides. This is much easier to accomplish, but you leak the range information.
Answer: Old Q but maybe you wanted an encrypted database index.
For something FOSS that front-ends MySQL and Postgres, check out CryptDB. Supports some homomorphic encryption and much more. Paper Another paper MSFT arguable crack
For encrypted full-text search Hitachi Credeon is built on Solr. It uses homomorphic encryption IIRC.
There's also the NSA's project on Apache which is likely deployed on a massive scale to search everyone's underwear drawer and pr0n collection... it's basically CouchBase meets Solr.


rsync pull disregards my umask, why?

Question: My umask is 0002.
So when I rsync -r me@remote:new ., why aren't the results group-writable?
drwxrwsr-x 10 root       developers 4096 Aug 22 12:55 .
drwxrwsr-x 12 root       developers 4096 Jul 14 19:05 ..
drwxrwsr-x  3 root       developers 4096 May 16 15:04 old
drwxr-sr-x  4 aaronadams developers 4096 Jun 26 15:17 new

Answer: I incorrectly assumed that an rsync push/pull without the -p flag would work similar to a git push/pull, and that new files would have full permissions minus the umask.
However, even without the -p flag, rsync still preserves the source file's permissions. The -p flag merely instructs rsync to (attempt to) ignore the receiver's umask.
As per man rsync:

New files get their "normal" permission bits set to the source file's
  permissions masked with the receiving end's umask setting, and their
  special permission bits disabled except in the case where a new
  directory inherits a setgid bit from its parent directory.

Better yet, there's a simple suggestion for how to create a flag that ignores source permissions:

To give new files the destination-default permissions (while leaving
  existing files unchanged), make sure that the --perms option is off
  and use --chmod=ugo=rwX (which ensures that all non-masked bits get
  enabled).  If you'd care to make this latter behavior easier to type,
  you could define a popt alias for it, such as putting this line in the
  file ~/.popt (this defines the -s option, and includes --no-g to use
  the default group of the destination dir):
rsync alias -s --no-p --no-g --chmod=ugo=rwX

You could then use this new option in a command such as this one:
rsync -asv src/ dest/

(Caveat: make sure that -a does not follow -s, or it will re-enable
  the --no-* options.)

I guess I'll be doing this!
Comment: Use --chmod=ugo=rwX,Dg+s to presetve the setgid bit on target directory, and its subdirectories (otherwise they become rwx instead of rws). D is rsync specific and allows to chmod only directories (for files only it would be F).
Answer: I think the setgid is confusing things. Look at the -p option in the rsync man page.
Comment: It wasn't `setgid`, but the complete description for `-p` does indeed clear things up.
Comment: Great glad to get you pointed in the right direction, upvoted your anwser
Answer: What is the permissions set in the original?
The umask is a filter not a setting.  On other words it limits the permission bits that can be set for files (and directories).  It doesn't force or require that any permissions get set, only that certain bits cannot be set.
If you need group write to be set, you may need to run chmod after the rsync.
Comment: Since there's a `-p` option described as "preserve permissions", I assumed omitting `-p` would not preserve source permissions. It turns out this is wrong! Thanks for leading me in the right direction.

rsync pull disregards my umask, why?


How to vary x-axis scales by column in facets

Question: I am creating a 2x2 ggplot using facet_wrap where the columns are two different groups.
This means that the x-axis on the columns is the same between the top row and the bottom row, but different between the columns. I want to remove the repeated x-axis tick labels, when they are repeated.
Is it possible to have the x-axis vary between columns in facet_wrap?
This is a toy example of the data, and what I have tried so far. What you will see is that the x-axis is repeated in the top and bottom row, when I use the argument "scales = free_x". If I don't use free_x then the scale of the x-axis is too wide for each plot.
Is there an argument I could use, or should I be looking at something like patchwork to link the plots together?
library(ggplot2)

n = 100

df = data.frame(x = c(rnorm(n/2), rnorm(n/2, mean = 100)),
                y = rnorm(n),
                group = rep(1:2, each = n/2),
                facet = rep(c("A", "C", "B", "D"), each = n/4))

ggplot(data = df, aes(x = x, y = y)) +
  geom_point() +
  facet_wrap(~facet + group, scales = "free_x")

Answer: Depending on your desired result patchwork will give you the most flexibility. A second option which at least gets you close to your desired result would be to use ggh4x::facetted_pos_scales which allows to set the scales individual per panel. However, I only found an option to remove the axis labels for the top row but not the tick marks.
library(ggplot2)

set.seed(123)

n <- 100

df <- data.frame(
  x = c(rnorm(n / 2), rnorm(n / 2, mean = 100)),
  y = rnorm(n),
  group = rep(1:2, each = n / 2),
  facet = rep(c("A", "C", "B", "D"), each = n / 4)
)

scale_y <- df |>
  split(~ group + facet, drop = TRUE) |>
  lapply(
    \(x) {
      labels <- if (!unique(x$facet) %in% c("A", "B")) waiver()
      limits <- range(df[df$group == unique(x$group), "x"])
      scale_x_continuous(
        labels = labels,
        limits = limits
      )
    }
  )

ggplot(data = df, aes(x = x, y = y)) +
  geom_point() +
  facet_wrap(~ facet + group,
    scales = "free_x"
  ) +
  ggh4x::facetted_pos_scales(
    x = scale_y
  )

Answer: Here's another approach which relies on adding dummy points for each facet + group with the desired range of x and a y value greater than the maximum of the whole data. Those points will be taken out (not shown on the plots) by defining the desired ylim.
n = 100
set.seed(123)
df = data.frame(x = c(rnorm(n/2), rnorm(n/2, mean = 100)),
                y = rnorm(n),
                group = rep(1:2, each = n/2),
                facet = rep(c("A", "C", "B", "D"), each = n/4))

library(ggplot2)
library(dplyr)

df %>%
  bind_rows(
    reframe(df, x = c(min(x), max(x)), y = max(df$y) + 10,
                    facet = unique(facet),
                    .by = group),
    reframe(df, x = c(min(x), max(x)), y = max(df$y) + 10,
                    facet = rev(unique(facet)),
                    .by = group)) %>%
ggplot(aes(x = x, y = y)) +
  geom_point() +
  facet_wrap(~ facet + group, scales = "free_x") +
  coord_cartesian(ylim = range(df$y))

Created on 2024-03-22 with reprex v2.0.2


Telerik object data source - access complex list items

Question: How to access fields from a complex list structure?
I have custom Object data source that works.  But I cant access the embedded list.
I can access the values main structure.  =Fields.ObjectId  works as expected.
But how do i access a specific row the sublist?
I have tried =fields.sublist[int].value and got a run time error.

" The expression contains object 1 that is not defined in the current
  context."

psuedoCode  of what im attempting

=Fields.BODPropValList.[PropertyName("XYZ")].Value

I cant find any docu explaining how to do this.
EDIT:
I dont want to bind it to a table since I need to access a single field from single sub row.
The data access object
  [DataObjectMethod(DataObjectMethodType.Select)]
   public List<BODRow> GetBODRowData(string dirId)        {
        .. code retrieves the list and delivers it..
        return bodRowList;
    }
}

public class BODRow   {
    public string ObjectId { get ;set; } }
    public string DirId { get ; set; } }
    public string ViewDirId { get; set; }
    public  List<BODPropVal>  BODPropValList { get; set; }
    }
}

public class BODPropVal {

    public virtual string PropertyName { get; set; }
    public virtual string Value { get; set; }

}

Answer: found a solution.
You can call static method you add to the reports partial class section.
Then in expression editor it can be called
=Namespace.Report.StaticMethod()
you can even pass parameters into the call.
If you declare the static routine with attribute   [DataObjectMethod(DataObjectMethodType.Select)]
it will appear in a special list of methods under Object Data sources
namespace MyNameSpace.MyTelerikReportLibrary
{
[DataObject]
public class ReportDataSource {

[DataObjectMethod(DataObjectMethodType.Select)]
    public static string GetBodDataLabel(string propName, string lang)        {
        return "code that returns your text"
    }
{

Comment: can you show the example of the static method you created for this?
Answer: Found this on Telerik's forum. Looks like you need to add initialization of List<BODPropVal> in a default constructor for BODRow.
http://www.telerik.com/forums/bind-data-to-table-form-nested-objects-nested-list
Comment: thx for trying CamperWill.  I want to address the subslist as using a field expression. There is not table to  bind to and the data delivered has main record and sublist set.


How can I learn statistical a/b testing?

Question: I need to learn statistical a/b testing. I have machine learning and probability background, how can I learn about this topic? Which books should I read? Or maybe someone has article suggestions?
Answer: Two books come to mind:

Trustworthy Online Controlled Experiments by Kohavi, Tang, and
Xu
Statistical Methods in Online A/B Testing by Georgi Georgiev

The first book collects a great deal of wisdom distilled from years of experience that was scattered in obscure field journals and touched only briefly in textbooks on statistics and field experimentation. There is also a treasure trove of practical examples and institutional details about online experimentation that is missing from those sources. It covers a great deal of terrain but includes references for those who want to go a bit deeper.
The second book covers some esoteric, but relevant topics like one-sided hypothesis tests and confidence intervals, holdouts, and percentage changes standard errors, that are ignored or touched on briefly in the conventional treatments. It has an exhaustive list of common misunderstandings of these and many other concepts. The presentation is thoughtful and deep, though not in an excessively mathematical way. I think this has become my go-to book for these topics and a very good complement to textbooks on statistics and field experiments and as well as the Kohavi, Tang, and Xu book.
These are both applied books, but they are not exactly cookbooks for how to analyze experimental data. If you lack a background in applied statistics, you may need to supplement with that to implement their advice.
Comment: Do you have any suggestion for learning applied statistics
Comment: That's a very broad question and hard to answer without additional detail (exactly what you want to learn, your level of mathematical training, plus other constraints like software). These books include references to such applied texts and they do have some formulas, but they won't teach you what to type in a piece of software to carry out that analysis. They are more about the things you have to think about, like how to match the right type of hypothesis test with your business question.
Comment: My advice to you would be to read them both, and then come back with a concrete question to search this site or ask if the search comes up dry.


Como fazer action edit com view model?

Question: Estou tentando fazer em meu projeto a parte de edição dos dados que foram cadastrados. Bem, a parte de cadastramento dos dados está funcionando bem certinha, mas agora eu preciso editar esses dados. Antes, eu andei procurando pela web para ver o que podia achar sobre isso. Achei link no SOus. Só que não entendi direito o código...
Alguém poderia me ajudar?
Answer: Basicamente é o mesmo princípio da criação, mas alguns detalhes a mais precisam ser observados:

O identificador do Model original precisa existir de alguma forma;
Você precisará trazer do banco o Model duas vezes: uma para preencher o ViewModel e outra para atualizá-lo.

Um clichê de edição de um Model Produto com duas propriedades, Id e Nome, seria algo como:
public async Task<ActionResult> Editar(int? id)
{
    if (id == null)
    {
        return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
    }
    Produto produto = await db.Produtos.FindAsync(id);
    if (produto == null)
    {
        return HttpNotFound();
    }

    var produtoViewModel = new ProdutoViewModel
    {
        ProdutoId = produto.ProdutoId,
        Nome = produto.Nome
    };

    return View(produtoViewModel);
}

A construção da sua View será exatamente igual como a construção usando um Model. O que muda é só a anotação @model:
@model MeuProjeto.ViewModels.ProdutoViewModel

No POST:
[HttpPost]
public async Task<ActionResult> Editar(ProdutoViewModel viewModel)
{
    if (ModelState.IsValid)
    {
        var produto = db.Produtos.FirstOrDefault(p => p.ProdutoId == viewModel.ProdutoId);

        if (produto == null)
        {
            return HttpNotFound();
        }

        produto.Nome = viewModel.Nome;

        db.Entry(produto).State = EntityState.Modified;
        await db.SaveChangesAsync();
        return RedirectToAction("Index");
    }

    return View(viewModel);
}

Vantagens da abordagem:

Segurança: você não expõe diretamente seus Models em formulários;
Flexibilidade: regras de validação mais específicas, sem necessariamente impactar o Model.

Desvantagens da abordagem:

Complexidade: seu sistema ficará inevitavelmente maior e mais complexo, e a manutenção será mais difícil;
Retrabalho: estender um Model significará estender todos os ViewModels associados ao Model.
Comment: Mesmo que eu tenha vários models [como nessa pergunta minha](http://pt.stackoverflow.com/questions/131105/relacionamentos-n%C3%A3o-salvos), funcionaria dessa forma?
Comment: Não está dando certo. =(
Comment: Acho que é hora de outra pergunta.
Comment: Criei já a pergunta!

Como fazer action edit com view model?


Help understanding an equivalent definition of completeness for a metric space M

Question: In my textbook there is a theorem that states that the following is equivalent to a metric space, $M$, being complete:
For any descending sequence $A_1 \supset A_2 \supset A_3 \supset \cdots$ of nonempty closed sets with diameters approaching 0, the intersection $\cap A_i$ is nonempty.
Would this definition of completeness not imply that all metric spaces are complete? If we let $A_1$ be a closed subset of $M$. Then we let $A_2 = \{a\}\subset A_1$. Here we have a sequence $A_1 , A_2$ where the diameter approaches (even becomes) 0, and $A_1\cap A_2\ne \emptyset$. Furthermore $A_2$ is also a closed set (right?). What have I missed?
Comment: In this case, "any" is supposed to mean "every".
Comment: It's a similar mistake to saying "every space $X$ has a finite cover $\{X\}$ so every space is compact". One example shows nothing here. It's about *all* decreasing sequences and *all* open covers.
Answer: Absolutely not. Consider the sequence of closed sets in $\mathbb{Q}$ defined by:
$$A_n=\Bigg[\sqrt{2}-\frac{1}{n},\sqrt{2}+\frac{1}{n}\Bigg]\cap\mathbb{Q}$$
These sets are closed in $\mathbb{Q}$, with diameter going to $0$, but their intersection is the empty set.
In fact, I think you have misenterpreted the definition, A metric space $M$ is complete if and only if every sequence with such properties have a nonempty intersection. The example you just gave is a simple case.


Setting XML attribute with PHP

Question: I'm trying to create .xml files with PHP, with a certain layout, using SimpleXMLElement.
Currently I'm struggling setting an attribute to an element.
What I tried so far:
<?php
$att = 'name="tc1"';
$xml = new SimpleXMLElement('<configuration/>');

$track = $xml->addChild('testcase');
$track->attributes()->$att;
$track->addChild('pfad', "none");
$track->addChild('aktiv', "false");
$track->addChild('file', "none");
$track->addChild('wert', "none");

Header('Content-type: text/xml');
print($xml->asXML());
?>

I can't figure out, why it's only displaying:
( XML Output: )
<configuration>
  <testcase>
    <pfad>none</pfad>
    <aktiv>false</aktiv>
    <file>none</file>
    <wert>none</wert>
 </testcase>
</configuration>

...instead of:
...
<testcase name="tc1">
...

Could you please help me set the attribute correctly?
Answer: $track->addAttribute('name', 'tc1');

Source
Comment: Thanks a lot! ...how could I miss addAttribute() ...
Comment: Everyone starts somewhere :) Glad I could help

Setting XML attribute with PHP


Datatables aaSorting is not sorting by the correct column

Question: I am trying to get a roster page to sort by player number onload. I plugged in aaSorting  and told it to sort the first column (the number) but it is sorting the second column (name). Can someone please tell me what I did wrong?

            <?php if( ! empty($vars['sport']->field_sport_show_number) && 1 == $vars['sport']->field_sport_show_number['und'][0]['value'] ): ?>
                #
            <?php endif; ?>

            Name

            <?php if( ! empty($vars['sport']->field_show_class) && 1 == $vars['sport']->field_show_class['und'][0]['value'] ): ?>
                Class
            <?php endif; ?>

            <?php if( ! empty($vars['sport']->field_show_position) && 1 == $vars['sport']->field_show_position['und'][0]['value'] ): ?>
                Position
            <?php endif; ?>

            <?php if( ! empty($vars['sport']->field_show_height) && 1 == $vars['sport']->field_show_height['und'][0]['value'] ): ?>
                Height
            <?php endif; ?>

            <?php if( ! empty($vars['sport']->field_show_weight) && 1 == $vars['sport']->field_show_weight['und'][0]['value'] ): ?>
                Weight
            <?php endif; ?>

            <?php if( ! empty($vars['sport']->field_show_b_t) && 1 == $vars['sport']->field_show_b_t['und'][0]['value'] ): ?>
                B/T
            <?php endif; ?>

            <?php if( ! empty($vars['sport']->field_show_hometown) && 1 == $vars['sport']->field_show_hometown['und'][0]['value'] ): ?>
                Hometown
            <?php endif; ?>

            <?php if( ! empty($vars['sport']->field_show_highschool) && 1 == $vars['sport']->field_show_highschool['und'][0]['value'] ): ?>
                Highschool
            <?php endif; ?>

        <?php $i=0; foreach($vars['athletes'] as $athlete): ?>

                <?php if( ! empty($vars['sport']->field_sport_show_number) && 1 == $vars['sport']->field_sport_show_number['und'][0]['value'] ): ?>

                        <?php echo $athlete->field_athleets_number['und'][0]['value'] ?>

                <?php endif; ?>

                    <a href="#" href="" rel="imgtip[<?php echo $i; ?>] "><?php echo $athlete->title ?>

                <?php if( ! empty($vars['sport']->field_show_class) && 1 == $vars['sport']->field_show_class['und'][0]['value'] ): ?>

                        <?php echo ( $athlete->field_class['und'][0]['value'] ) ? $athlete->field_class['und'][0]['value'] : 'No Data' ?>

                <?php endif; ?>

                <?php if( ! empty($vars['sport']->field_show_position) && 1 == $vars['sport']->field_show_position['und'][0]['value'] ): ?>

                        <?php echo ( $athlete->field_position['und'][0]['value'] ) ? $athlete->field_position['und'][0]['value'] : 'No Data' ?>

                <?php endif; ?>

                <?php if( ! empty($vars['sport']->field_show_height) && 1 == $vars['sport']->field_show_height['und'][0]['value'] ): ?>

                        <?php echo ( $athlete->field_height['und'][0]['value'] ) ? $athlete->field_height['und'][0]['value'] : 'No Data' ?>

                <?php endif; ?>

                <?php if( ! empty($vars['sport']->field_show_weight) && 1 == $vars['sport']->field_show_weight['und'][0]['value'] ): ?>

                        <?php echo ( $athlete->field_weight['und'][0]['value'] ) ? $athlete->field_weight['und'][0]['value'] : 'No Data' ?>

                <?php endif; ?>

                <?php if( ! empty($vars['sport']->field_show_b_t) && 1 == $vars['sport']->field_show_b_t['und'][0]['value'] ): ?>

                        <?php echo ( $athlete->field_b_t['und'][0]['value'] ) ? $athlete->field_b_t['und'][0]['value'] : 'No Data' ?>

                <?php endif; ?>

                <?php if( ! empty($vars['sport']->field_show_hometown) && 1 == $vars['sport']->field_show_hometown['und'][0]['value'] ): ?>

                        <?php echo ( $athlete->field_hometown['und'][0]['value'] ) ? $athlete->field_hometown['und'][0]['value'] : 'No Data' ?>

                <?php endif; ?>

                <?php if( ! empty($vars['sport']->field_show_highschool) && 1 == $vars['sport']->field_show_highschool['und'][0]['value'] ): ?>

                        <?php echo ( $athlete->field_high_school_state['und'][0]['value'] ) ? $athlete->field_high_school_state['und'][0]['value'] : 'No Data' ?>

                <?php endif; ?>

        <?php $i++; endforeach; ?>

            <?php if( ! empty($vars['sport']->field_sport_show_number) && 1 == $vars['sport']->field_sport_show_number['und'][0]['value'] ): ?>
                #
            <?php endif; ?>

            Name

            <?php if( ! empty($vars['sport']->field_show_class) && 1 == $vars['sport']->field_show_class['und'][0]['value'] ): ?>
                Class
            <?php endif; ?>

            <?php if( ! empty($vars['sport']->field_show_position) && 1 == $vars['sport']->field_show_position['und'][0]['value'] ): ?>
                Position
            <?php endif; ?>

            <?php if( ! empty($vars['sport']->field_show_height) && 1 == $vars['sport']->field_show_height['und'][0]['value'] ): ?>
                Height
            <?php endif; ?>

            <?php if( ! empty($vars['sport']->field_show_weight) && 1 == $vars['sport']->field_show_weight['und'][0]['value'] ): ?>
                Weight
            <?php endif; ?>

            <?php if( ! empty($vars['sport']->field_show_b_t) && 1 == $vars['sport']->field_show_b_t['und'][0]['value'] ): ?>
                B/T
            <?php endif; ?>

            <?php if( ! empty($vars['sport']->field_show_hometown) && 1 == $vars['sport']->field_show_hometown['und'][0]['value'] ): ?>
                Hometown
            <?php endif; ?>

            <?php if( ! empty($vars['sport']->field_show_highschool) && 1 == $vars['sport']->field_show_highschool['und'][0]['value'] ): ?>
                Highschool
            <?php endif; ?>

Page output

Athletics: Baseball: Roster

                            #

            Name

                            Class

                            Position

                            Height

                            Weight

                            B/T

                            Hometown

                        17

                    Aaron Woller

                        SO

                        OF

                        6'0

                        170

                        R/R

                        St. Joseph, IL

                        15

                    Austin Calhoun

                        SO

                        OF

                        6'1

                        170

                        L/L

                        Danville, IL

                            #

            Name

                            Class

                            Position

                            Height

                            Weight

                            B/T

                            Hometown

Comment: Can you provide output html (taken in browser), not php source?
Comment: What version of datatables you are using?
Comment: @Justinas How do I find that out?
Comment: Look at the head of the .js file for a version.
Comment: @skobaljic added the output (minus some rows for space)
Comment: @isherwood I am not using a js file at the moment... it is commented out. but I was using the file from http://www.kryogenix.org/code/browser/sorttable/#externalcall
Comment: If you're using DataTables, you're using a .js file.
Comment: I think the problem is that somehow it is not seeing the first column as the first column. I have set it to sort the first column on load and it is actually sorting the second column.
Comment: Open DataTables js file that you include in header and check comments, there must be version number.
Comment: @Justinas  that may be part of my problem because I don't have a datatables.js file. at least not that I included..might be a global thing, but the snippet of code I put in there I found on a site and it never said about including a datatables js file.....
Comment: @Justinas added the datatables file ..version DataTables 1.10.4 fromCDN but it is still sorting from the second column.
Answer: Since you told, that you are using datatables 1.10.4 please double check documentation.
Old documentation | New documentation
As you can see, 1.10 parameters are rewritten and is changed from 1.9. You are using 1.10 version DataTables plugin, but using 1.9 version parameters
$(document).ready(function() {
    $('#roster').dataTable({
        'order': [[ 0, 'asc' ]]
    });
});

Answer: Added the following to the header
<link href="/jscript/jquery.dataTables.css" rel="stylesheet" type="text/css" />

Tweaked the javascript a bit and now it is working perfectly.
Answer: stateSave Setting
One thing to watch out for is the stateSave setting.  If this is true, the order is saved to localStorage.  So even if you change your javascript, a page reload will replace your new order with the old one.
Clearing the Saved Order Setting
To clear the old setting, you can manually delete the entry from localStorage or click the reset button if it's displayed.


How to create a login application using Google web tool kit?

Question: I am new in gwt.I want to create a login application using google web tool kit.Thanks in advance.
Answer: Google provides a short tutorial which describes how to create a login page with user/password authentication and storing the data in a server-side secure fashion: google-web-toolkit-incubator Login Security FAQ


Tem como fazer um evento após uma impressão em Javascript?

Question: Gostaria de fazer uma ação pós impressão, ou seja, só quando o usuário confirmar a impressão que o javascript vai executar um evento programado. Se eu colocar um evento embaixo do window.print() o javascript executa mesmo sem o usuário ter imprimido ainda. Algo como:
window.print() = function(){
    [...]
}

Ouvi falar sobre matchMedia, mas não entendi. Teria como exemplificar a partir do código abaixo?
1) Antes da impressão quero o fundo da tela amarelo;
2) Após a impressão quero o fundo da tela verde;

  <title>teste</title>

  <input type="button" value="imprimir" onclick="imprimir()" />

Answer: Encontrei esse trecho de código na versão em ingles que parece resolver a questão:
(function() {

    var beforePrint = function() {
        console.log('Antes de imprimir...');
    };

    var afterPrint = function() {
        console.log('Depois de imprimir...');
    };

    if (window.matchMedia) {
        var mediaQueryList = window.matchMedia('print');
        mediaQueryList.addListener(function(mql) {
            if (mql.matches) {
                beforePrint();
            } else {
                afterPrint();
            }
        });
    }

    window.onbeforeprint = beforePrint;
    window.onafterprint = afterPrint;

}());

Maiores detalhes sobre o MatchMedia no autor da questao original aqui.


Show that if $\sum_{i \in I} a_i < \infty$, then $I_0=\{i \in I : a_i > 0 \}$ is countable.

Question:
Let $I$ be an indexing set and $a_i \ge 0,$ $i\in I$, real numbers. Show that if $\sum_{i \in I} a_i < \infty$, then $I_0=\{i \in I \mid a_i > 0 \}$ is countable.

How should I approach the problem? I don't think I can find an injection between $\Bbb N$ and $I_0$. Is there some property of the convergent sum I should consider? I only now that if the sum converges, then the tail tends to zero, but not sure how it is of help here.
Comment: @Snaw . When every $a_i\ge 0$ we can define $\sum_{i\in I}a_i=$ $=\sup\{\sum_{i\in J}a_i:J\subset I\land |J|<\aleph_0\}.$
Comment: I think you mean $I_0=\{i \in I \mid a_i > 0 \}.$ Hint: a union of countably many finite sets is countable.
Comment: What does $\sum_{i\in I} a_i$ mean when $I$ is not countable?
Comment: @DanielWainfleet Makes sense. Thanks.
Answer: Proof that $I_0=\{i\in I: a_i>0\}$ is countable.
Assume that $\sum_{i\in I}a_i=s<\infty$.
Then, for every $k\in\mathbb N$, the set
$$
J_k=\{i\in I: a_n\ge s/k\},
$$
contains at most $k$ elements, since
$$
s=\sum_{i\in I}a_i\ge \sum_{i\in J_k}a_i\ge\frac{s}{k}|J_k|.
$$
Here $|J_k|$ is the number of elements of the set $J_k$.
But $I_0=\bigcup_{k\in\mathbb N}J_k$.
And hence $I_0$ is countable.


Erro tentando desenhar grafico: "comprimento do objeto maior não é múltiplo do comprimento do objeto menor"

Question: Tenho uma função:
my_gamma = function(x)
{
    f = function(t){t^(x-1) * exp(-t)}
    integrate(f, 0, Inf)
}

Estou tentando desenhar o seu gráfico com ggplot2:
plot = ggplot(data.frame(x = seq(0.01, 10)), aes(x=x))
(plot + stat_function(fun = my_gamma))

Mas está me dando o erro:
Warning messages:
1: In t^(x - 1) :
  comprimento do objeto maior não é múltiplo do comprimento do objeto menor
2: In t^(x - 1) * exp(-t) :
  comprimento do objeto maior não é múltiplo do comprimento do objeto menor
3: Computation failed in `stat_function()`:
evaluation of function gave a result of wrong length

O que estou a fazer de errado?
Answer: O principal problema é que a função não está vetorizada.
O segundo problema é que integrate retorna uma lista, mas stat_function precisa de um vetor de números.
Então, primeiro corrige-se a função.
my_gamma <- function(x){
  f <- function(t){t^(x - 1) * exp(-t)}
  integrate(f, 0, Inf)$value
}

Agora vetoriza-se e testa-se a forma vetorizada.
myGamma <- Vectorize(my_gamma)
myGamma(seq(0.1, 10, length.out = 20))
# [1] 9.513504e+00 1.442807e+00 9.356940e-01 9.021743e-01 1.092452e+00
# [6] 1.551187e+00 2.488839e+00 4.409250e+00 8.490126e+00 1.756589e+01
#[11] 3.871311e+01 9.026446e+01 2.214427e+02 5.690236e+02 1.525743e+03
#[16] 4.255200e+03 1.230969e+04 3.684868e+04 1.139016e+05 3.628800e+05

Finalmente, o gráfico. Incluí um argumento length.out em seq.
plot <- ggplot(data.frame(x = seq(0.01, 10, length.out = 20)), aes(x=x))
plot + stat_function(fun = myGamma)


Qual as vantagens de usar namespaces em Delphi?

Question: A partir da versão 2009 do Delphi (se não me engano) veio os namespaces.
Gostaria de saber, num exemplo simples se possível que ilustre um caso de vantagem, qual seriam as vantagens dos namespaces no Delphi?
Explanando um pouco sobre namespaces, em C# poderíamos ter três arquivos, contendo o mesmo namespace:
Arquivo Contas.cs:
namespace Projeto.Forms {
    public class ContasForm : Form {
       ...
    }
}

Arquivo Compras.cs:
namespace Projeto.Forms {
    public class ComprasForm : Form {
       ...
    }
}

Arquivo Cliente.cs:
namespace Projeto.Forms {
    public class ClienteForm : Form {
       ...
    }
}

Em um quarto arquivo, MainForm.cs, eu teria acessa às três classes apenas por referências Projeto.Forms:
using Projeto.Forms;

namespace Projeto {
    public class ContasForm : Form {
       private ContasForm contasForm;
       private ComprasForm comprasForm;
       private ClienteForm clienteForm;
    }
}

Já em Delphi isso não ocorre:
Arquivo Projeto.Forms.Contas.pas:
unit Projeto.Forms.Contas;
interface
uses ...
type
  TContasForm = class(Form)
  ...

Arquivo Projeto.Forms.Compras.pas:
unit Projeto.Forms.Compras;
interface
uses ...
type
  TComprasForm = class(Form)
  ...

Arquivo Projeto.Forms.Cliente.pas:
unit Projeto.Forms.Cliente;
interface
uses ...
type
  TClienteForm = class(Form)
  ...

Enfim, ao querer referenciá-las em Projeto.Forms.MainForm precido fazer da seguinte maneira:
unit Projeto.Forms.MainForm;
interface
uses Projeto.Forms.Contas, Projeto.Forms.Compras, Projeto.Forms.Cliente;
type
  TMainForm = class(Form)
  ...

Não é possível fazer algo como uses Projeto.Forms; e a partir dai ter acesso às três classes. Muito menos é permitido em Delphi ter mais de um arquivo com o mesmo nome.
O único meio que vi de ter tal benefício seria manipulando. Exemplo:
Criar mais uma unit com o nome Projeto.Forms.pas:
unit Projeto.Forms;
interface
type
  TContasForm = Projeto.Forms.Contas.TContasForm;
  TComprasForm = Projeto.Forms.Compras.TComprasForm;
  TClienteForm = Projeto.Forms.Cliente.TClienteForm;
...

E então fazer a referência como havia citado, uses Projeto.Forms; e a partir dai ter então acesso às três classes.
Bom, não sei se isso teria consequências e, claro, foi apenas para ilustrar.
Diante disso, pergunto: Qual as vantagens em utilizar namespaces em Delphi?
Peço um pequeno exemplo só para ilustrar.
Grato!
Comment: Esta pergunta é específica de C# mas o conceito é o mesmo ou muito semelhante: http://pt.stackoverflow.com/questions/11199/como-funciona-namespaces-no-c
Comment: @Caffé, no ***Delphi*** acho que não dá para dizer que ***namespaces*** trazem diretamente a mesma utilidade/funcionalidade.
Comment: Qual seria a diferença entre namespaces Delphi e namespaces C#?
Comment: @Caffé, rapaz, pior que a única coisa que consigo pensar agora é que não consigo ter o mesmo ***namespace*** em mais de um arquivo. A não ser que eu manipule, exemplo: em **`Modelos.Usuario`** eu fazer **`type TTipoAcesso = Modelos.Usuario.TipoAcesso.TTipoAcesso;`**. Então, em Java e C#, por exemplo, em mais de um arquivo você consegue ter ***namespaces*** iguais e com isso criar um "**pacote**" de classes/tipos.
Comment: Por arquivo você se refere *packages* ou *units*? Ter o mesmo namespace para diferentes units é justamente a função do namespace, ou não seria um namespace mas apenas uma unit com nome grande. Quanto a declarar o mesmo namespace em diferentes packages (diferentes arquivos BPL), faz uns anos que não uso Delphi e nem tenho nenhum pra verificar, mas não vejo nenhum motivo para não poder fazê-lo. Você tentou?
Comment: @Caffé, pelas minhas tentativas, dá apenas para ter um ***namespace*** por ***unit***, já que o arquivo tem que ter o mesmo nome da ***unit***. Então, sim, é apenas um arquivo com nome grande. Exemplo: ***`Projeto.Forms.MainForm.pas`***. Não me referi a nada sobre ***packages*** ainda.
Comment: Não, não é apenas um arquivo com nome grande. É um namespace de fato, com todos ou muitos dos benefícios daquelas respostas em C# que eu linkei no meu primeiro comentário. Veja, em *Projeto.Forms.MainForm.pas*, o namespace é *Projeto.Forms*, e nele eu posso ter quantas units eu quiser: *Projeto.Forms.Contas.pas*, *Projeto.Forms.Compras.pas*, *Projeto.Forms.Cliente.pas*...
Comment: @Caffé, se eu fosse fazer uso delas em uma outra unit, exemplo na ***`Projeto.Forms.MainForm.pas`*** eu teria que adicionar: ***`uses Projeto.Forms.Compras, Projeto.Forms.Cliente, Projeto.Forms.Contas;`***. Ou seja, arquivo por arquivo da mesma forma que faria: ***`uses UntContasForm, UntComprasForm, UntClienteForm;`***. Não dá para adicionar apenas ***`uses Projeto.Forms;`*** e a partir dai poder ter acesso à todas as classes dos três arquivos (***`TClienteForm, TComprasForm, TContasForm`***). Elucidando que estou falando de três arquivos e cada um contendo uma classe, para fazer sentido.
Comment: Com esse ultimo comentário e a melhora da pergunta eu entendi o seu ponto. Enquanto em C# os tipos são agrupados logicamente em um namespace, em Delphi os tipos são agrupados em uma unit, e os namespaces não são agrupamentos de tipos mas sim agrupamentos de units. Mais tarde eu posto uma resposta.
Answer: Vantagens de usar namespaces em Delphi

Namespaces em Delphi têm o objetivo de organizar units e tipos de maneira lógica.
Namespaces servem ainda para oferecer um identificador único global para um tipo ou unit, de modo que podemos ter mais de um tipo ou unit com o mesmo nome, no mesmo projeto.

Em um sistema grande, não é incomum que units ou tipos diferentes, de diferentes contextos, tenham naturalmente o mesmo nome.
Por exemplo, um produto no estoque pode ser uma entidade distinta do produto no front-end de vendas (ver DDD - bounded context). Namespaces nos permitem de fato chamar ambas as entidades de "Produto", com diferentes namespaces, proporcionando uma nomenclatura mais expressiva e mais próxima do negócio, sem ter que forjar prefixos e sufixos para diferenciar units e tipos de diferentes contextos.
Além disso, há mais clareza em chamar uma unit de Business.Estoque.Produto do que BusinessProdutoEstoque.
Diferenças entre namespaces Delphi e namespaces C Sharp
Uma diferença importante entre  namespaces C# e namespaces Delphi é que em C# eles agrupam tipos, e em Delphi eles agrupam units e as units é que agrupam tipos (cada unit é um arquivo de código fonte).
Então, em C#, para trazer para o contexto todos os tipos de um namespace, fazemos assim:
using Business.Estoque.Produto;

Agora, todos os tipos deste namespace que estiverem referenciados pelo projeto estarão imediatamente disponíveis no contexto.
Em Delphi, o comando acima (seria uses em vez de using) estaria referenciando a unit Business.Estoque.Produto do namespace Business.Estoque, trazendo para o contexto todos os tipos declarados nesta unit.
Semelhança entre namespaces Delphi e namespaces Java
Se no projeto a prática é declarar apenas um único tipo público em cada arquivo, neste aspecto namespaces Delphi são mais semelhantes a namespaces Java (onde são chamados de packages), pois em Java o arquivo de código fonte tem o nome da classe pública contida nele, e o padrão é referenciar não um namespace de modo a trazer todos os seus tipos para o contexto, mas sim referenciar cada uma das classes que se deseja trazer para o contexto.
Em Java, o comando import Business.Estoque.Produto traz para o contexto apenas a classe Produto, tal qual em Delphi estaria trazendo apenas, digamos, uma classe chamada TProduto (contida na unit Produto).
Aqui, Java tem um recurso que o Delphi não tem. Em Java há a opção de trazer para o contexto todos os tipos do namespace de uma só vez:
import Business.Estoque.*;

No comando acima, não apenas a tal classe Produto mas também todas as classes do namespace Business.Estoque estarão disponíveis no contexto. Delphi não tem este recurso, então cada unit do namespace Business.Estoque teria que ser referenciada explicitamente, exemplo:
uses Business.Estoque.Produto, Business.Estoque.Produto.Categoria,
    Business.Estoque.Inventario;

Conclusão
Namespaces em Delphi tem o mesmo objetivo que em C# ou Java: organizar logicamente o projeto, com o benefício de poder ter identificadores únicos globais para tipos ou units com nomes iguais.
A diferença mais importante é que enquanto em C# ou Java um namespace (em java, package) agrupa tipos, em Delphi um namespace agrupa units e as units agrupam tipos.
Em Java, é comum a prática de referenciar explicitamente cada tipo, mas também é possível referenciar de uma vez todos os tipos de um namespace usando o coringa *. Em Delphi a única opção é referenciar explicitamente cada unit.
Apesar de não simplificar a referência a tipos no contexto (não permitir referenciar de uma vez tipos contidos em diversas units), namespaces em Delphi ainda oferecem a vantagem de organizar logicamente o projeto, permitindo nomes mais expressivos para units e tipos.
Por exemplo, em vez de ter no meu código units e tipos com nomes como CategoriaCliente, CategoriaProduto, CategoriaFrete... Eu posso ter Vendas.Cliente.Categoria, Estoque.Produto.Categoria, Transporte.Frete.Categoria.
Comment: Poxa, ficou uma resposta muito legal!! =D Obrigado!


Using win32com with excel I added a textbox to chart, how do I assign a formula to that textbox

Question: I can add the textbox:
<code> x = chart.Shapes.AddTextbox(msoTextOrientationHorizontal, 180, 8.75, 31.5, 21)
</code>
I can write text in the box:
<code> x.TextFrame2.TextRange.Characters.Text = 50
</code>
I did a macro recording in excel and added a formula:
<code> ActiveSheet.Shapes.Range(Array("TextBox 2")).Select
 Selection.Formula = "=$F$2"
</code>
But I can not figure out how to set it from win32com.  The .Formula doesn't seem to be under the Shape, or under TextFrame2 or TextRange or Characters.  Not sure where else to look.
Answer: Finally, found it.
<code> chart.TextBoxes(2).Formula = "=$F$2"
</code>


$f$ is continuous at $c$ $\implies$ $f$ has a limit at $c$. True?

Question: Further to Another simple/conceptual limit question where I was questioning David Brannan's assertion in his A First Course in Mathematical Analysis that $f(x)=\sqrt x,x\geq 0$ has no limit at $0$ (Example 2c if you type in page 184 in the box on http://www.scribd.com/doc/74564079/Mathematical-Analysis), I just noticed that in an earlier section he asserted that the same function is continuous on its domain i.e. including at $0$ (Example 3 if you type in page 148 in the box).
Does this not violate the well-known theorem (Thm 2 if you type in page 185 in the box) implying that if $f$ is continuous at $c$, then $f$ has a limit at $c$ ? Is David Brannan contradicting himself (by setting up his definition of limits badly)?
EDIT:  Thanks, Wisefool. It turns out that there is no contradiction in Brannan's assertions (that the square root function is continuous at 0 yet has no limit at 0) after all, but only because of his peculiar definition of "limit" and his analogously peculiar statement of the theorem relating continuity at a point to the limit at that point.
Comment: @IttayWeiss. What I understood the problem here is, is that the author of the book claims that there is no limit for $\sqrt{x}$ in $0$, while in other place he claims that for a continuous function the limit exists in every point of its domain.
Comment: IMO this is exactly the kind of trouble you get into when you try to define functions like $\sqrt{x}$ over all of $\mathbb{R}$ and start talking about "defined" and "undefined" points, instead of making full use of topology and subspaces.
Comment: I fail to see the problem. The function you mention is continuous on its domain and it does have a limit at x=0.
Comment: Yes, Thomas, that's exactly the issue- thanks.
Comment: @user7530 It's simply David Brannan being clumsy in dumbing down the definition of limit (not letting the limit to exist at $c$ when $c$ is an end-point of $f$'s domain) to suit whatever purpose he has. But I agree that the trouble run into is the same.
Answer: It is a simple matter of terminology: in that example (or in that section/chapter/book) a limit is understood to be a two-sided limit.
$f$ has limit $l$ in $x_0$ if:

$f$ is defined in a (puntcured) neighborhood of $x_0$
for every $\epsilon>0$ there exists $\delta>0$ such that if $|x-x_0|<\delta$ then $|f(x)-l|<\epsilon$.

In that example, it is the first condition which fails.
This isn't exactly standard and personally I would have said that the function had a limit for $x\to 0$, but I can see the book's point...
EDIT: moreover, Thm2 on page 185 speaks about a point $c$ contained in an open interval $I$ where the function is defined. There is no open interval of the real line containing $0$ where the function $\sqrt{x}$ is defined.
Comment: Thanks for pointing out that Thm 2 mandates that the point in question isn't an end-point. I had missed that.


Get a JSON array with HTTP Get using javascript (jquery)

Question: I've been trying some code from here to achieve my goal but I haven't found the solution yet.
Goal: I have to get a JSON objects array from a web (through the URL) using GET method. I have to do that in Javascript or HTML. I have been trying in javascript with jquery and with ajax. The idea is when the webpage I'm making loads I have to get the JSON objects array. I would want to save the JSON objets array fetched in a string to manipulate it.
Example of JSON array that I have to get from http://www.example.com/example
[
    {
        "type": "1",
        "id": "50a92047a88d8",
        "title": "Real Madrid"
    },
    {
        "type": "1",
        "id": "500cbb1a5ef23",
        "title": "Fernando Alonso"
    }
]

When I run my code in the browser I always get no response.
These are some pieces of code I've tried:
HTML Code

    <link type = "text/css" rel = "stylesheet" href = "stylesheet.css"/>

Javascript code
function httpGet(theUrl)
{
$.getJSON(theUrl, function(data)
{
    $.each(data, function()
    {
        console.log(this['title']);
    })
});
}

Other Javascript code
$.ajax(
{
    url: theUrl,
    type: 'GET',
    dataType: 'json',
    accept: 'application/json',
    success: function(data)
    {
        console.log(data);
        var objets= $.parseJSON(data);

        $.each(objets, function(i, obj)
        {
           console.log(obj.title);
        });
    }
});

And I have prove a lot of code from here (stak overflow)...
Thank you very much and excuse me for my English.
Edit:
Some time ago I tried with stringify, but I don't really known how can it works.
I proved the following:
function httpGet(theUrl)
{
    var xmlHttp = null;
    xmlHttp = new XMLHttpRequest();
    xmlHttp.open("GET", theUrl, true ); // I tried with true and with false
    xmlHttp.send();
    var answer= xmlHttp.responseText;
    var str = JSON.stringify(answer);
    console.log(str);
    var jsonResponse = JSON.parse(str);
    console.log(jsonResponse);
}

Comment: So what's in `data` upon success? Does it ever hit `success`. Maybe it hits `error` instead. Did you try adding a callback for that and seeing what happens? Also, checking your Network tab in Chrome/Firefox Inspector is usually helpful for this too.
Comment: Is the specified URL pointing at _your_ domain, i.e., the same domain your page loaded from? A standard ajax request (for JSON or any other format) won't work cross-domain.
Comment: use stringify for this
Comment: The URL is not pointing at my domain, so have I to reject using an ajax request?
Comment: Yes, I've tried using a callback function. I always see the result of executing my code with Firebug Firefox complement.
Comment: and I always see 200 OK and no response. I don't understand why I obtain a 200 OK but I don't obtain the json array.
Answer: You can't fetch data cross domain with javascript, you have to put the data under your domain or using jsonp to get it, or just print it on the page.
Comment: I think you haven't understood me, or I haven't explained myself well, or both.
I want to save in a variable the JSON objects array retrieved with the GET call.
Comment: if the GET call address is not the same domain as your script, your call will fail, and there is no response. just check this [link](http://www.w3.org/TR/access-control/)
Comment: Then, what the hell should I do? With jsoup is possible doing this?
Comment: i am sorry, it's a typo for jsonp, it's not easy to discus jsonp in comment, you can view more about it [here](http://en.wikipedia.org/wiki/JSONP)
Comment: But in the answer header I see this:
Content-Type application/json
So, if the content-type expected by the server is json, can I do the request with a dataType:'jsonp'?
If I do this I don't receive neither the 200 OK nor the answear headers.
Comment: that depends on the server, if it support jsonp, every thing is ok, otherwise you can do nothing. :(
Comment: I guess that if the answer header shows that the content-type is application/json it means that the server doesn't support jsonp, no?
Isn't there any other possible solution?
Comment: maybe you will ask server provider if they are support jsonp. there is no other way if you use **Only javascript**.
Comment: and what are other possible ways without using only javascript?
Comment: Another thing I don't understand is this: When I prove my code in chrome i get the following message "Origin null is not allowed by Access-Control-Allow-Origin." I don't know if this could be the problem, and I don't know how could I solve this.
Comment: Access-Control-Allow-Origin. means you are try to do a cross domain request, Chrome will add a header and ask server whether they support cross domain call. if the server recognize this header, and allow cross domain request, you will success. however not all browser will add this header. if you can do the request in backend server, there will be ok, java/php/python ext.
Answer: I have found the solution to my problem with one line php code
<?php
    echo file_get_contents("http://www.example.com/example");
?>

After that, I needed to reference the php file in the javascript file.
Finally I could access to the key-value pairs of the JSON objects array.
function httpGet()
{
    $.getJSON('phpfile.php', function(data)
    {
        $.each(data, function(i, obj)
        {
            console.log("object: " + i + ", title: " + obj.title);
        });
    });
}

In the HTML file I modified the next line:


Porque o comando this(6) dentro de um construtor inicializa o array da classe?

Question: No código:
public class Lista{

        int [] a;
        int n;

        public Lista(){

                this(6);
        }

        public Lista(int i){

                this.a = new int [i];
                this.n = 0;
        }

        public static void main(String [] args){

                Lista l = new Lista();
                System.out.println("tamanho: " + l.a.length);

        }

}

Como o primeiro construtor Lista() identifica que o comando this(6); esta inicializando o array int a[] com o tamanho?
Answer: O this() só está chamando o construtor, neste casos é um alias dele. É a forma de chamar este método especial chamado construtor. Como é possível ter um método normal existir na classe com o mesmo nome, no momento que está construindo ele não pode chamar pelo nome porque pode ser o construtor ou pode ser um método normal, por isso usa-se o nome this(). Então de uma certa forma podemos dizer que na verdade ele está chamando Lista(6) que é o outro construtor. E é neste outro construtor que está inicializando o array normalmente.
Então um construtor que tem uma assinatura, no caso sem parâmetros está chamando o outro construtor que aceita um parâmetro com o tamanho. Se você chamar o construtor sem parâmetros que é dito formalmente pela linguagem de construtor padrão ele assume um valor para você, no caso é 6.
Obviamente que esse segundo construtor não está só inicializando o array, o outro campo também, mas não tem porque deixar ele ser configurado pelo programador fora da classe, pelo que dá para perceber.
Para um exercício não é um problema, mas frequentemente esse método main() dentro dessa classe não é adequado, ele deveria estar em classe própria, isso fica como um ruído.
Seu código tem um vazamento de abstração (expõe o array pra fora) e não é considerado adequado, ainda que funcione, pesquise mais sobre o assunto.
Coloquei no GitHub para referência futura.
Answer: Porque a expressão this(6) invocará o método construtor que recebe um inteiro como parâmetro, pois é o tipo de parâmetro que você está passando. Por sorte esse método está definido logo abaixo:
public Lista(int i){
    this.a = new int [i];
    this.n = 0;
}

E ele é responsável por inicializar a lista a com o valor de i, que é o parâmetro recebido, neste caso o 6.
Answer: Porque Lista l = new Lista() se refere a chamada do construtor Lista().
Dentro deste construtor, há o construtor Lista(int i) que está sendo chamado da seguinte forma
this(6)
Quando o segundo construtor é chamado, ocorre a inicialização do array
this.a = new int [i]


Is this function $f : \mathbb{N} \times \mathbb{N} \to \mathbb{Z}^+$ bijective?

Question: Let $\mathbb{N}=\{0,1,2,...\}$ be the set of all natural numbers and $\mathbb{Z^+=N-\{0\}}$. We define
$$f:\mathbb{N\times N}\rightarrow\mathbb{Z^+}\;\;\text{by}\;\;f((m,n))=2^m3^n\;\;\text{for all}\;\;(m,n)\in\mathbb{N\times N}.$$
Then I can't show it is a bijective function from $\mathbb{N\times N}$ onto $\mathbb{Z^+}$. I'm not sure it is surjective.
Thanks.
Answer: This function is not surjective, because there do not exist $m$, $n$ for which $$2^m 3^n = 5$$
This is a result of unique factorzation; on the other hand, the function is injective (again by unique factorization).

To show that there is a bijection (which must, in particular, be an injection) we use the Schroeder-Bernstein Theorem. We have that $f$ is an injection, and the map
$$g : \mathbb{Z}^+ \to \mathbb{N} \times \mathbb{N}, g(a) = (a, 0)$$
is also an injection. Hence there exists a bijection between $\mathbb{Z}^+$ and $\mathbb{N} \times \mathbb{N}$.
Comment: I think so. Can you find a function for this problem ?
Comment: @Sommanee.W I've added a way to give an injection.
Comment: I denote the cardinal number of $A$ by $|A|$. It is well-know that $\mathbb{|N\times N|=|N|=|Z^+|}$. So I want to see a map which is bijective.
Answer: If you don't want to use the Schroeder-Bernstein Theorem, which is a heavy and quite difficult result, you can also define an explicit bijection between $\mathbb N\times\mathbb N$ and $\mathbb Z^+$.
There are several ways to do it. One is to start with pairs of sum $0$, (only $(0,0)$, mapped to $1$), then pairs of sum $1$: $(0,1)$ is mapped to $2$ and $(1,0)$ to $3$, and so on...
An explicit formula for this bijection is $f(i,j)=1+i+\frac{(i+j)(i+j+1)}{2}$.
You can also use the prime factorization, but not exactly as you did: map $(n,2^{a_1}3^{a_2}\dots p_n^{a_n}-1)$ to $2^n3^{a_1}5^{a_2}\dots p_{n+1}^{a_n}$. I added the $-1$ to avoid problems with $0$, which has no factorization.
Notice that this way, you can reach $1$ as the image of $(0,0)$.
Answer: Another possibility
(not original with me)
is
$\frac{n}{m}
\to 2^{n-1}(2m+1)
$.
It's harder
if you only want to consider
$\frac{n}{m}$
in lowest terms,
but it has been done.


Is there a way to integrate wordpress database with ionic app?

Question: I already have a webpage developed on WP, with the default localhost DB. Is there a way to integrate this DB with my app? This app will be developed with IONIC 2.
If it isn't possible, can i use some external DB and access this one remotely with both applications?
Or i'll need to develop something like own CMS to have a better result?
Thanks and sorry about my english!
Good Vibes :)
Answer: i think You not understand what is Mobile App and what is it difference to Web App. So Mobile App is client like web browser, web browser do not connect to server database, it connects to server and server to database.
Do get data from Your Wordpress on server should be some API, for example REST API, this api on every request will query database and send results in response. So You send tipical http ajax calls from ionic app in javascript to API and get result in response.
Answer: If it's WordPress, install and activate the WP REST API plug-in. It will give you some API endpoints to consume data from WordPress. Later, you can use these API endpoints to fetch data on your Ionic App.


Bayesian statistics example

Question: I am learning Bayesian statistics for a data mining module. We were given a set of practice questions but no answers and I want to make sure that I am going about Bayes in the right way.
Suppose Manchester United were about to play Arsenal in the Premiership and you assess the probability
of Manchester United winning to be 0.7. You also feel that if they did win, there is a probability of
0.9 that your local pub will be packed with fans celebrating their club's victory. Alternatively, if they
loose, you believe that there is still a probability of 0.6 that the pub will be packed with fans albeit for
drowning their sorrows. As someone not interested in football, you enjoy a quiet day at work and on
the way home, notice a big crowd in the pub. Can you assume that Manchster United won the game?
If so, what is the probability of them having won the game?
Attempted solution:
let $p(w)$ denote prob of manchester united winning
let $p(f)$ denote prob of pub being full
$p(w|f)=\frac{p(f|w)*p(w)}{p(f)}$ ,
where $p(f)=p(f|w)*p(w)+p(f|¬w)*p(¬w)$
$p(f)= 0.9*0.7+0.6*0.3=0.81$
$\rightarrow$$p(w|f)=\frac{0.9*0.7}{0.81}=0.78$
So prob of Manchester untied having won is 0.78.
I don't think we can assume they won just because there were people in the pub  as there was a 0.6 prob of them drowning their sorrows.
Have I got this right or have I misunderstood Bayesian statistics?
Thanks very much
Comment: Your answer is correct.
Answer: You have correctly applied Bayes rule but this is a far cry from understanding Bayesian statistics.  Bayesian statistics is a way of doing statistical inference that is different the frequentist approach.  Suppose you want to get an interval estimate of the mean of a normal distribution.  You first put a prior distribution on the mean then you collect data. Bayes' theorem is used to relate the prior distribution for the mean to the posterior distribution by posterior is proportional to prior times likelihood.  The posterior distribution is then used for inference.  An interval estimate for the mean that is the Bayesian analog of a 95% confidence interval is a 95% credible interval.  You get this by picking points equal distant in each direction from the mean of the posterior distribution and far enough so that the integral from the lower endpoint to the upper endpoint is 0.95.  This is what Bayesian statistics is about. It is much more than just Bayes theorem.  Bayes theorem is an uncontroversial mathematical result in probability.  Bayesian statistics is a paradigm for statistical inference and is somewhat controversial because it assigns probability distributions to unknown parameters.
Comment: +1 for going above and beyond, @Michael Chernick. I certainly got stuck at this exact point: I could walk through a Bayes Rule application, but actually analyzing a set of data is a bit more complex. Trying to figure out how people were doing it with JAGS/BUGS was a puzzle. The book "Doing Bayesian Data Analysis: A Tutorial with R and BUGS" by John K. Kruschke has really helped me and I can highly recommend it.
Comment: You may want to look at Speigelhalter et al.  They are the British group that developed BUGS.  Also George Casella's book on Monte Carlo covers MCMC and Jeff Gill wrote a book on Bayesian Methods for the social sciences that is excellent and also goes pretty deeply into MCMC.  Bayesians use MCMC to analyze hierarchical models which can get complicated in their multiple levels of parameterization.
Comment: @MichaelChernick: do you mean [Robert and Casella's book](http://www.amazon.com/gp/product/1441919392?ie=UTF8&tag=chrprobboo-20&linkCode=as2&camp=1789&creative=390957&creativeASIN=1441919392)?!
Answer: Both your reasoning and your computations are correct.

Bayesian statistics example


Why SQL Server cut precision to 3 or 6 places

Question: I have a big problem with calculations in sql(sql server management studio)
I have a variable declare @KursEur decimal(32,10) = 4.2617000000
I need 10 places after dot presicion
I need the result of multiplying the values from the database with a variable with 10 places after the dot precision
ColumnName = decimal(32,10)
examples:
select ColumnName*@KursEUR
from TableName

Result: 364947858427.467456
 select ColumnName*4.2617000000
 from TableName

Result: 364947858427.46745556204873 <-i need this result
I tried it but it doesn't give the expected result :
 select CAST(ColumnName as numeric(32,10))* CAST(@KursEUR as numeric(32,10))
 from TableName

select CAST(ColumnName as float)* CAST(@KursEUR as float)
 from TableName

 select CAST(ColumnName  as numeric(32,10))* CAST(@KursEUR as float)
 from TableName

 select CAST(ColumnName as float)* CAST(@KursEUR as numeric(32,10))
 from TableName

 select ColumnName* CAST(@KursEUR as float)
 from TableName;
select ColumnName* CAST(@KursEUR as numeric(32,10))
 from TableName

select CAST(ColumnName as numeric(32,10))* @KursEUR
 from TableName

select CAST(ColumnName as float)* @KursEUR
 from TableName

 select CAST(ColumnName*@KursEUR as float)
 from TableName

 select CAST(ColumnName*@KursEUR as numeric(32,10))
 from TableName

Comment: The [rules](https://learn.microsoft.com/sql/t-sql/data-types/precision-scale-and-length-transact-sql) for how precision and scale are determined based on input precision and scale and operation are quite complicated, but they do explain your result. In all of this you've failed to state what the type of `ColumnName` is, though.
Comment: You might want to consider the documentation for [precision and scale](https://learn.microsoft.com/en-us/sql/t-sql/data-types/precision-scale-and-length-transact-sql?view=sql-server-ver15) and especially the table that shows the result after multiplication.
Comment: ColumnName = decimal(32,10)
Comment: The *real* question here is, do you "*need"* a precision of 32? The largest number you can store with a `decimal(32,10)` is 9,999,999,999,999,999,999,999.9999999999; that's 10  Sextillion - 1... A truly *huge* number.
Comment: Well you can't multiply two `decimal(32, 10)` and maintain full precision, as that exceeds what SQL Server can support. How many digits does your input *actually* have? The usual solution to precision woes is to cut down on the precision (leaving the scale intact).
Comment: Besides, casting to a lower precision type like `float` *guarantees* loss of precision. `numeric` is still a floating-point number, with far greater precision than `float` but *still* susceptible to scaling errors `364947858427.467456` has a *very* different scale from `4.2617`.
Comment: i dont care about 32. I need 10 places after dot.
Comment: this is application for bank , they want (32,10)
Comment: Then use the lowest precision that works for your input. `SELECT 85634338040.5630277969 * 4.2617` yields `364947858427.46745556204873`; that's a `DECIMAL(21, 10)` multiplied by a `DECIMAL(5, 4)`.
Comment: *"i dont care about 32. I need 10 places after dot. "* Then why make the precision 32? If you don't *need* 22 digits *before* the decimal place, then don't declare your data type to state you *do*. Declare the data type to have an **appropriate** precision. If you need  (at most) 10 digits before the decimal point, and 10 after, for example, then you would use a `decimal(20,10)`.
Comment: Adding to that, your desired result has *14* decimal digits instead of 10. And what you see is the *formatted* number displayed by your client tool (SSMS is a client tool). If you specified more digits to display, eg with the `FORMAT` command, you may see the entire result. I'd still expect it to be `numeric(32,10)` though
Comment: `this is application for bank` and banks know all about rounding, which is why they use specific rounding strategies instead of depending on infinite precision decimals. This goes back at least to Superman 2. That's why eg XR conversions *require* a specific number of digits instead of arbitrary precision
Comment: Note that if your solution truly requires that *any* two `DECIMAL(32, 10)` numbers should be multipliabe without loss (which I sincerely doubt) then you simply can't use SQL Server, and would need to look at something like an arbitrary precision numerics library on the client end. This is seldom necessary, though; more typically people fail to appreciate that reducing the number of *total* digits ("precision") has positive effects for the number of digits available after the separator ("scale").
Comment: i change (32,10) to decimal(11,10) in @kursEur and its working!
Comment: So you don't need more than 1 digit prior to the decimal place?
Comment: 1? i dont understand. @KursEur is now(11,10)
Comment: I always think that decimal(11,10) means = 11111111111,2222222222
Comment: omg im so stupid, i understand now
Comment: 11 all digits, 10 after dot so (11,10) means 1,1111111111
Answer: When you multiply two numbers in SQL Server, the product's precision is determined by adding the precision from both numbers together plus one. In your case, if both numbers have a precision of 32, then the resulting product would need a precision of 65! The max is 38 (or smaller on earlier versions)!!
The trick is to use smaller variable sizes. If you cast @KursEur as decimal(11,10). and cast the ColumnName as something like decimal(25,10) it will work. Balance the precision between the two numbers as your needs require, just make sure they add up to 37 or less.
SELECT CAST(85634338040.5630277969 AS DECIMAL(25,10)) * CAST(4.2617000000 AS DECIMAL(11,10))


How to create separate tablespaces in Oracle XE?

Question: Creating separate tablespaces is possible in expensive versions of Oracle, but I can't seem to find a way to do so with the free version Oracle XE.
The administration interface just has a "View tablespaces" button, where I can see four tablespaces, SYSAUX, SYSTEM, UNDO, and USERS where all of my data seems to reside.
Is it a limitation of Oracle XE?
Or did I overlook something?
Answer: If you create a new APEX workspace it should offer to create it in a new tablespace.
Alternatively, fire up SQL*Plus (called the Command Line Interface in XE) and use the CREATE TABLESPACE command.
That said, given the 4GB limit, for a home install I resize the USERS tablespace to the maximum and just use that. Too annoying having reached the 4GB max and having space available in tablespace_a and not being able to expand tablespace_b when you want it there.
In theory you can shrink tablespace_a but that only works if the free space is at the end and not at the start or in the middle.
Comment: Using Oracle XE I can't seem to be able to create a new APEX workspace. There is nothing like this: http://www.dba-oracle.com/images/htmldb_manage_workspaces.jpg

But the SQL command line allows the CREATE TABLESPACE command so I will give it a try, thanks :-)


Duas strings partindo de uma, em C

Question: Olá, preciso um software que leia um nome completo, composto por um nome simples e um sobrenome, separados por "_" e os imprima separados.
O código deverá usar a seguinte função main:
#include <stdio.h>

int main(){
    char nome[30];
    char * sobrenome;
    scanf("%s", nome);
    sobrenome = extraiSobrenome(nome);
    printf("Nome\n%s\nSobrenome\n%s\n",nome, sobrenome );
    return 0;
}

Tentei escrever a função extraiSobrenome(nome);, mas sem sucesso:
#include <stdio.h>
#include <string.h>

extraiSobrenome(nome){
    int i=0, j=0, aux;
    char nova[30], michael[30];
    char sobrenome[30];
    strcpy(nova, nome);
    for(i=0;i<(int)strlen(nova);i++){
        if(nova[i]==95){
            i++;
            break;
        }
    }
    aux=i;
    while(i<strlen(nova)){
        sobrenome[j]=nova[i];
        i++;
        j++;
    }
    sobrenome[strlen(nova)-aux] = '\0';

    return sobrenome;
}

int main(){
    char nome[30];
    char * sobrenome;
    scanf("%s", nome);
    sobrenome = extraiSobrenome(nome);
    printf("Nome\n%s\nSobrenome\n%s\n", nome, sobrenome );
    return 0;
}

O problema não é apenas conseguir separar o sobrenome, mas alterar o nome também, podem me ajudar?
Answer: Faltou declarar o retorno da função extraiSobrenome. Que no caso seria um ponteiro de caracter, ou char*.
Note que você precisa alterar a variável nome original, caso contrário não terá sucesso ao imprimir nome separadamente.
Você poderia usar a função da biblioteca padrão strtok para fazer essa divisão a cada _, mas creio que aqui o interesse não seja em usar a biblioteca padrão mas sim em treinar escrita de algoritmos em C.
Uma versão adequada de extraiSobrenome sem usar a biblioteca padrão:
char *extraiSobrenome(char *nome_com_sobrenome) {
  char *fim_nome = nome_com_sobrenome;
  while (*fim_nome != '_' && *fim_nome != '\0') {
    fim_nome++;
  }
  if (*fim_nome == '\0') {
    // oops, fim da palavra antes de achar o delimitador '_', devo retornar nulo ou um sobrenome vazio?
    return fim_nome; // estou retornando um sobrenome vazio para evitar falhas de segmentação
  }
  // se não caiu no 'if' anterior, então garanto que achou um '_'
  * fim_nome = '\0'; // estou marcando o fim do nome, substituindo o '_' pelo caracter nulo, portanto indicando que a string acabou
  return fim_nome +1; // usando aritmética de ponteiros para indicar que o sobrenome começa na próxima letra
}

Alguns outros pontos que gostaria de levantar sobre seu código:

você comparou um caracter com 95; ok, no final das contas letras são números com zeros e uns, mas o que é 95?
Por que não comparar diretamente com '_'? Muito mais expressiva essa comparação e todo mundo que ler seu código e que não saiba a tabela ASCII decorada vai entender essa versão da comparação
você retornou um vetor criado internamente na função, e isso não é bacana...
Essas variáveis são guardadas na pilha, e elas só fazem sentido dentro do contexto da execução da função propriamente dita; quando ela retorna, não há mais como garantir o significado do resto da pilha da última chamada... e esse código é válido sintaticamente porque internamente o C trabalha apenas com o endereço do vetor, então você está retornando um endereço de um valor que está na pilha que pode ser sobrescrito a qualquer momento.

Leia mais sobre pilha, heap, escopo de variável... vou listar algumas sugestões de leituras:

O que são e onde estão o "stack" e "heap"?
Como funciona a C99 em relação à C90 para declaração de variáveis no meio do código?
Passando por referência em C
Como funciona o tempo de vida de variáveis estáticas?
Qual a diferença entre escopo e tempo de vida?
Alocação de objetos e ponteiros
nessa resposta o @Maniero trata da terminologia elegantemente: https://pt.stackoverflow.com/a/215832/64969
Por que pode passar um vetor de chjar para o scanf como endereço ou a variável direto?

Sobre strtok:

Separar pequenas strings de uma string gigante; particularmente gosto muito da resposta que o @Isac deu
Answer: O que você acha de depois de gravar o primeiro nome você acrescentar um espaço assim:
strcat(nome, " ");

Comment: Usar `strcat` simplesmente não tem como atender ao problema em questão.
Comment: Achei que você só quisesse separar as duas strings...
Comment: Com essa intenção de "separar duas strings" `strcat` também não vai ajudar em nada
Comment: #include
#include

int main()
{
   char nome[10];
   char sobrenome[10];

   printf("Informe nome: ");
   gets(nome);
   strcat(nome, " ");

   printf("\nInforme sobrenome: ");
   gets(sobrenome);
   strcat(nome, sobrenome);

   printf("%s", nome);

    return 0;
}
Comment: Você leu que o nome e o sobrenome são dados divididos por um '_'? Então, não, não vão ser dadas duas leituras... Note também que a impressão é com nome e sobrenome separados, a intenção não é juntar
Comment: hummmmmmmmmmmmmmmmmmmmmmmmmmmmmm ta bem, então boa sorte aí!!!

Duas strings partindo de uma, em C


Explaining why the absolute value of an odd function is even.

Question: For the following:

If $f(x)$ is an odd function, then $|f(x)|$ is _____.

I said even, because I graphed an odd function and then the absolute value of it and ended up with an even function. The answer is correct but then my professor says this as an explanation:

$h(x)=|f(x)|$
$h(-x)=|f(-x)|=|-f(x)|=|f(x)|=h(x)$

He didn't explain very well and I don't know what is quite going on. I know this might be like a homework question but I would love to know what topic this is and what this process is. So I can look it up and figure it out.

EDIT: The process makes sense but what are we trying to prove here?
Answer: He was using the property of odd function:
$$f(-x) = -f(x)$$
to prove that $h$ has the property of even function:
$$h(-x) = h(x)$$
Answer: I will go through the last equation you wrote step-by-step and say why it is true.
$$h(-x)=|f(-x)|$$
Since $h(x)=|f(x)|$, this follows immediately from the definition.
$$|f(-x)|=|-f(x)|$$
This is because $f$ is an odd function and $f(-x)=-f(x)$ for all $x$.
$$|-f(x)|=|f(x)|$$
By the definition of absolute value, $|y|=|-y|$ for all $y$ (absolute value is an even function).
$$|f(x)|=h(x)$$
This is again, the definition of $h$.
The principle here is actually deeper. If $g(x)$ is an even function and $f(x)$ is an odd function, $g(f(x))$ is even and $f(g(x))$ is also even. Can you see how to prove these in the same way as above?
Comment: @Zephyr No, consider $f(x)=e^x$. Then $|f(x)|=|e^x|=e^x$, which is not an even function. $|f(x)|$ is only even if $f(-x)=\pm f(x)$ for each $x$.
Comment: I don't understand how the first statement could be true?
Comment: By first statement do you mean $h(-x)=|f(-x)|$?
Comment: Yes please. I don't quite understand that. Just looking at it makes sense, but I can't find any proof.
Comment: Since $h(x)$ is defined to be $|f(x)|$ for every value of $x$, if we just change $x$ to $-x$ on both sides, the equation is still true.
Comment: Let us say that the function is $f(x)=|x|$, so then it really doesn't matter if it is $h(x)$ or $h(-x)$ right?
Comment: True, but then $f(x)$ is an even function, not odd.
Comment: The process makes sense but what are we trying to prove here?
Comment: Let us [continue this discussion in chat](http://chat.stackexchange.com/rooms/25734/discussion-between-alex-s-and-asker123).
Comment: @Alex S, So modulus of any function is an even function right ?
Comment: @AlexS Yeah. I forgot to consider the functions which are neither even nor odd.


what can a computer do without an operation system

Question: An operation system is a program that controls all the other programs so that the user can manipulate he's work.
What will happen if the os seize to exist?
Could the user still be able to perform some tasks or not?
Comment: It can blink its lights.
Comment: Well, it will display you an error on your display.
Comment: 'program that controls all the other programs' sorta.  It's more of a resource manager, controlling access to CPU. memory, disk, networks, KB, mouse, display etc.  If your computer system has only one application with only one  thread of execution, then it can freely use all the resources, and the need for an OS disappears.
Answer: The OS is not just needed to control other programs, but also to do all the heavy-lifting involved with dealing with the hardware, so the actual programs don't have to do it or even know about it.
The user can do whatever his programs allow him to do, while the programs need the operating system to function properly (or at all). If there where no OS, all the programs would have to do everything that OS was doing for them before (which is A LOT).
Among many things that OS does the most important for the user is that it allows to run several programs simultaneously without them interfering with each other.
Answer: Computers do not need operating systems. If the computer does not have an operating system, the application needs to perform the operating system functions. Such applications as operating systems used to be more common than they are today. They are most common in real-time systems where the computer is performing only one general function.


NGNIX 1.6.2 on Debian8: Won't start after adding SSL

Question: I can't figure out even the text of the error I get from starting it
● nginx.service - A high performance web server and a reverse proxy server
   Loaded: loaded (/lib/systemd/system/nginx.service; enabled)
   Active: failed (Result: exit-code) since Fri 2015-06-05 16:52:14 UTC; 8s ago
  Process: 17285 ExecStop=/sbin/start-stop-daemon --quiet --stop --retry QUIT/5 --pidfile /run/nginx.pid (code=exited, status=0/SUCCESS)
  Process: 17273 ExecStart=/usr/sbin/nginx -g daemon on; master_process on; (code=exited, status=0/SUCCESS)
  Process: 17386 ExecStartPre=/usr/sbin/nginx -t -q -g daemon on; master_process on; (code=exited, status=1/FAILURE)
 Main PID: 17275 (code=exited, status=0/SUCCESS)

Jun 05 16:52:14 ip-172-31-33-65 systemd[1]: Starting A high performance web server and a reverse proxy server...
Jun 05 16:52:14 ip-172-31-33-65 nginx[17386]: nginx: [emerg] BIO_new_file("/etc/ssl/www_mydomain_me.pem") failed (SSL: error:02001002:system libr...ch file)
Jun 05 16:52:14 ip-172-31-33-65 nginx[17386]: nginx: configuration file /etc/nginx/nginx.conf test failed
Jun 05 16:52:14 ip-172-31-33-65 systemd[1]: nginx.service: control process exited, code=exited status=1
Jun 05 16:52:14 ip-172-31-33-65 systemd[1]: Failed to start A high performance web server and a reverse proxy server.
Jun 05 16:52:14 ip-172-31-33-65 systemd[1]: Unit nginx.service entered failed state.
Hint: Some lines were ellipsized, use -l to show in full.

My additional "server" configuration in the "default" under "sites-available" is:
server {

        listen  443 ssl;
        ssl on;
        ssl_certificate /etc/ssl/www_example_com.pem;
        ssl_certificate_key /etc/ssl/www_example_com.key;

        access_log      /var/www/laravel/access.log;
        error_log       /var/www/laravel/error.log;

        server_name example.com;

}

If I remove this block, my NGNIX restarts correctly and serves our web app via port 80. My goal is to support HTTPS and even redirect any HTTP call into HTTPS. I don't want non secure traffic on my website.
We just got our EV SSL certificate from Symantec today but I just can't get the NGNIX server to accept it or its configuration.
Comment: As the message told you, use `systemctl status nginx -l` to see the full log lines. Otherwise they are truncated and useless.
Comment: U can check with comman nginx -t
& fix ploble
Answer: First thing is to check if the path you specified is correct
$ ls /etc/ssl/www_mydomain_me.{pem,key}
If yes, check if the permission is proper for them. If not, update as below:
$ chown root:root /etc/ssl/www_mydomain_me.{pem,key}
$ chmod 600 /etc/ssl/www_mydomain_me.{pem,key}

edit: the first answer is similar to mine. sorry, around same time.
Answer: I am going to assume that the full text of the relevant ellipsed error code should be:
 error:02001002:system library:fopen:No such file

Either the path to your file is incorrect, or the permissions on /etc/ssl/www_mydomain_me.pem are incorrect.  The ownership be root:root, unless you use the ssl_cert group, and the permissions should be 600 at the most.


É possível nomear um parâmetro no momento da chamada da função?

Question: Posso "acessar" um parâmetro especifico de uma função de JavasScript, ou seja, dar um valor para um determinado parâmetro? Como exemplo é melhor do que texto (já que não sei me explicar direito), aqui vai um:
Em Python, tendo uma função:
def funcX(A="A",B="B",C="C"):
    print(A+B+C)

...que resultaria em:
'ABC'

...eu posso mudar o valor de determinado parâmetro assim:
funcX(C = "c")

...o que resulta em:
'ABc'

Quero saber se há alguma forma de fazer o mesmo em JavaScript.
Exemplo:
function funcX(A,B,C){
    if(typeof A != 'string'){A= "A"}
    if(typeof B != 'string'){B= "B"}
    if(typeof C != 'string'){C= "C"}

    alert(A+B+C)
};

Resultaria em:
'ABC'

E ai gostaria de fazer algo como:
funcX(C = "c")

...para resultar em:
'ABc'

Aproveitando, gostaria de fazer uma pergunta paralela (se é que isso é permitido):
Existe uma forma melhor de dar "valores padrão" para os parâmetros das funções em Javascript do que if(typeof A != 'string'){A= "A"}?
Como em Python def funcX(A="A")
*(desculpem tanta comparação, mas é que aprendi a programar em Python, e é a única referência que tenho)
Answer: Em JavaScript tens mesmo de chamar a função passando os parâmetros todos. A função que colocaste é bem no caminho certo, se tiveres:
function funcX(A,B,C){
    if(typeof A != 'string'){A= "A"}
    if(typeof B != 'string'){B= "B"}
    if(typeof C != 'string'){C= "C"}

    alert(A+B+C)
};

então se só queres mudar o C terias de chamar a função com funcX(null, null, 'c');.
jsFiddle: http://jsfiddle.net/kdxerxpw/
Outra maneira de dar valores padrão seria:
function funcX(A,B,C){
    A = A || 'A';
    B = B || 'B';
    C = C || 'C';

    alert(A+B+C)
};

jsFiddle: http://jsfiddle.net/kdxerxpw/1/
mas acho  que como tens é melhor, mais específico.
No caso de não precisares de redefenir nenhum parâmetro podes chamar a função somente com funcX();
jsFiddle: http://jsfiddle.net/kdxerxpw/2/
Comment: Obrigado Sergio, queria poder economizar digitação, mas infelizmente não posso passar apenas um parâmetro. Fazer o que
Pelo menos agora não to com a duvida, eu sei que não posso

Outra coisinha, vi ali que você editou meu tópico
Foi você quem colocou os Highlights?
Answer: A maneira usual de fazer parâmetros nomeados ou opcionais em Javascript é passar um objeto (dicionário) como parâmetro. Um exemplo famoso é a função ajax da biblioteca jQuery.
No seu caso ficaria mais ou menos assim:
function funcX(kw){
    var A = kw.A || "A";
    var B = kw.B || "B";
    var C = kw.C || "C";
    console.log(A+B+C);
}

funcX({a:"oi", c:"!", b:"mundo"});

É bem comum usar || em parâmetros opcionais em JS porque o código fica bem sucinto mas se você quiser aceitar valores "falsy" como 0 ou "" você pode fazer testes mais precisos usando typeof ou o operador in:
 var A = "A" in kw ? kw.A : "defaultA";

Comment: Não tem muita mágica. O análogo em Python seria passar um dicionário como parâmetro ao invés de usar *keyword arguments*. Pra implementar parâmetros opcionais você pode usar o operador `in` para testar se o dicionário contém um certo campo (funciona igual a Python) ou você sair acessando os campos diretamente mesmo (em Python acessar um campo inexistente de um dicionário é um erro mas em Javascript você simplesmente obtem o valor `undefined`, que é tipo um `null` só que um pouco diferente).
Comment: Muito bom, eu voltei aqui justamente pra comentar que acabei de descobrir que poderia usar um objeto para fazer parâmetros com "valores padrão" (descobri justamente usando JQuery, mais precisamente com jQuery Ui).
Fazendo algo como `funcX({C:'c'})`.

Mas na verdade não descobri muito bem como funciona por dentro


Jenkins: Waiting for next available executor on master, 4 workers idle

Question: I have a jenkins (initially 1.596.2, later upgraded to .3) master on Ubuntu, with some jobs.
Last week i started seeing jobs being put on queue (pending—Waiting for next available executor).
I checked the job config (Restrict where this project can be run) and it says Slaves in label: 1.
The master workers all report idle.
I upgraded to 1.596.3, restarted the node, but after a couple of hours of working (around 10-12) it starts to put jobs on queue although workers are idle.
It doesn't have any slaves, there are plenty of resources (node is a VM with 8 GB of RAM and 500 GB disk) and there are no errors in dmesg or logs.
What can i do to unblock it?
Thanks,
Ed
Answer: I ran into a similar problem where I have "Batch Tasks" (Batch Tasks plugin) in the queue that don't kick off and block the execution queue. By removing the tasks from the queue, it resumes execution for regular jobs.
It may or may not be your issue.
Answer: I had this issue as well with Jenkins 1.639

I restarted Jenkins the first time and still had the issue

I had 2 executors in the master node, added 3 more for a total of 5

Restarted Jenkins again and this time it worked!


Tempo:Mendelssohn's Song without Words, op.53. No. 3

Question: All the professional recordings of Mendelssohn's "Song without Words" op.53. No. 3 last below three minutes (look at this list). As a matter of fact, some recordings last just 2 minutes! What's the purpose/idea behind playing it so fast? Isn't the musicality lost this way? Is anything wrong with a lower tempo, for example like this one?
Thanks.
Comment: If the title of the YouTube video you linked to is right it is 'presto agitato', which means incredibly fast as if you are in a hurry, loosely translated. The melody is in the left hand and is relatively slow, so the musicality of the melody is not lost if you play it fast, playing the accompanying broken chords though is kind of boring if you play it slowly.
Answer: Maybe one reason is that Mendelssohn wrote Presto agitato (fast and agitated) at the beginning of the piece! Don't confuse musicality and slowness. In fact, in my opinion the performance in the video you gave is not (yet) very musical. It feels heavy and lacks direction, and that's partly because it's so slow. But that's not the whole reason. I think that with good phrasing and some imagination (musicality!) one can give a convincing performance of the piece at that tempo.
Comment: Partly because melody and accompaniment are played equally loud, while normally one would play the accompaniment softer than the melody. And I don't have the sheet music at hand, but the man in the video in the OP seems to apply excessive force to the keyboard.
Comment: @11684 I don't know the copyright condition in your country, but here it is: http://imslp.org/wiki/Lieder_ohne_Worte,_Op.53_(Mendelssohn,_Felix)
Comment: I would interpret that as arpeggiation with rhythm, not like slow and lyrical chords because of the tempo, the f and sf and the staccato points on the last notes of every broken chord.
Comment: And indeed, a single f is less than what is played in th video.


SQL Server stored procedure - SELECT statement then use results in INSERT statement

Question: I am writing a stored procedure that will get results from one table then copy them to another. It isn't an exact match, I'm changing 1 column and ignoring another. There are 5 columns and on average 3-5 results if that is relevant.
I basically need to:
SELECT * FROM sometable WHERE somecolumn = 1

Then for every result
INSERT INTO anothertable (a,b,c) VALUES (@a, @b, @c)

What is the best way to do this within a stored procedure?
Answer: You can do this in one statement:
INSERT AnotherTable (a, b, c)
SELECT a, b, c
FROM SomeTable
WHERE SomeColumn = 1

Wherever possible, avoid doing things in loops/cursors/RBAR (Row By Agonizing Row) and instead try to think in SET-based approaches like above.
Comment: Could 'a' be replaced with @z, a predefined variable outside of the table?
Comment: @MattP - yes, that would result in each row inserted having that same value
Answer: I would try something like
insert into anothertable (a,b,c)
select a, b, c from sometable where somecolumn = 1

Answer: You can insert directly from a select query:
INSERT INTO anothertable (a,b,c)
SELECT @a, @b, @c FROM sometable WHERE somecolumn = 1

Comment: Will this work when @a is a separate variable defined before the statement and only b and c are in the table?
Comment: Yes - you can mix and match if needed - you could declare @a as a variable, and then replace @b and @c with column names from sometable and then you'd be inserting all the values of columns, with the same value of @a for each.


Oops!! Method create.en not found for resource chats

Question: I am using apipie gem for api documentation.
Under my api folder, there is one version**(api/v1)
When I access http://localhost:3000/apipie it shows me the documentation but when clicking on api document url ie POST /api/chats
It redirects to  http://localhost:3000/apipie/public/chats/create.en.html
It displays error
 Oops!! Method create.en not found for resource chats.
But when I remove .en form url manually it displays right api documentation.
ie http://localhost:3000/apipie/public/chats/create.html.
I am confusing why api doc redirect to .en.html and how I avoid adding .en in api doc url.
Comment: Thanks Fabrizio for help i solve these by creating apipie custom view and comment @doc[:link_extension]  these code in view.
Comment: how does your `rake routes` looks like? how does that link looks like?
Answer: This is an bug which is already reported here
You can fix the problem by adding following line into apipie.rb file
config.translate = false

Answer: If you dont want to translate, you can add the following to apipie.rb file
config.translate = false

or if you want to translate and if you are using I18n to translate you can simply use
config.languages                = %w[en fr] #replace this with list of #locales you use in your app
  config.default_locale           = 'en'
  config.locale                   = lambda { |loc| loc ? I18n.locale = loc : I18n.locale }
  config.translate                = lambda do |str, loc|
    return '' if str.blank?

    I18n.t str, locale: loc, scope: 'doc'
  end


Alterar classe do label para active após requisição http angular

Question: Tenho um componente do material design bootstrap que depois de uma requisição http ele é preenchido, o problema é que ele não altera para a classe "active", tendo o resultado da foto.

            <input type="text" id="form2" value="{{cliente.whatsapp}}" class="form-control">
            Whatsapp

Se eu tentar trocar a label class="active", eu ainda não consigo o resultado da label no topo, como posso corrigir isso?
Whatsapp não funciona
Devo aplicar a classe active quando tiver valor no input.
Answer: Voce poderia usar o ngClass
ele tem a seguinte sintaxe ngClass="{classe: condicao}"

            <input [ngClass]="{active: cliente.whatsapp}" type="text" id="form2" value="{{cliente.whatsapp}}" class="form-control">
            Whatsapp