Why cant I configure or remove this module?

Question: I was trying to figure out Google Analytics and installing it broke my site so I uninstalled it.  Now I have reinstalled it, There is no link to configure it and the configuration page isn't even accessible from the URL.
So I tried to uninstall the module again and when I try to uninstall it goes to white screen and when I refresh I get back to the modules list and the module is still there.  I cannot configure or uninstall or get the module to work. It seems to be stuck there.
I have even tried to WinSCP into the server and straight up delete the module.  This removes the file from the list but when I reinstall the module I am back to square 1 where I cannot do anything with it.
I checked the error log and when I try to uninstall I get the following error PHP Fatal error: "Call to undefined function google_analytics_clear_js_cache()"
Is there anything I can do?
Comment: No, there isn't. google_analytics does not work right now.
Answer:
I checked the error log and when I try to uninstall I get the following error PHP Fatal error: Call to undefined function google_analytics_clear_js_cache()

This means that there is a bug in this module (and off-topic here).
But this is a general problem, and this anser provides is a general solution to this problem, that can also be used with other modules.
Whenever you get a WSOD upon uninstall and the log tell you it is because a "Call to an undefined function" - locate that call in the module's source code, and just delete the statement with the call.  Then try to uninstall again.
After doing this, make sure you report the problem to the module's issue queue on Drupal.org to make the maintainer fix it (and alert others about it).
Answer: No guarantee it will help, but I think it's worth trying: increase your php memory limit and try again.
Since you're experiencing problems because of "adding" modules, it could well be that you've reached a memory limit that causes these kinds of related problems ...
Comment: Well I checked the error log and when I try to uninstall I get the following error

PHP Fatal error:  Call to undefined function google_analytics_clear_js_cache()
Answer: Just uninstall the module and clear the cache.May be it will work.
Comment: Downvoted. This is really bad advice.  Removing a folder from the modules directory *without* making *sure* that the module has been properly uninstalled may leave all sorts of cruft in the database that may create problems later.
Comment: Yeah you may be right.But still i think this is related to cache.


Pegar todas as div dentro de um tbody sem jquery

Question: Tenho a seguinte estrutura em meu HTML:

            Nome do estado

                    Nome de uma oficina
                    <input type="hidden" value="id_do_objeto">

Através do javascript, estou usando a função document.getElementsByName('tbodyEstados') para obter um array com todos os tbody's de estados, mas depois preciso iterar cada um dos itens dessa lista e pegar de dentro deles, separadamente para cada estado,  os elementos div que estão com o nome: "divOficina". Alguém sabe como posso fazer isso?
Comment: O elemento `tbody` não deve se repetir várias vezes na mesma table. Revise sua lógica. Você poderia pegar diretamente as divs `divOficina` com `document.getElementsByName('divOficina')`
Comment: O problema de usar diretamente document.getElementsByName('divOficina') é que não terei como saber quais destas div's estão dentro de qual estado especificamente.
Comment: Adicione um atributo de estado ao escrever a div. Ex.: `...`. Ao fazer um loop na divs, vc verifica o attributo assim: `minhaDivOficina.getAttribute('estado')`.
Comment: É recomendado que atributos customizados sejam prefixados por `data-` para evitar incompatibilidades https://developer.mozilla.org/pt-BR/docs/Web/Guide/HTML/Using_data_attributes, https://pt.stackoverflow.com/questions/190859/atributos-personalizados-html
Answer: Podes dividir a pesquisa em dois passos, primeiro com document.getElementsByName('tbodyEstados'); e depois com tBody.getElementsByName('divOficina'); dentro de um loop executas a lógica que precisas. Algo assim:
const tbodyEstados = document.getElementsByName('tbodyEstados');
tbodyEstados.forEach(parent => {
    const divOficina = parent.getElementsByName('divOficina');
    // aqui podes usar `divOficina ` e `parent` que são respectivamente o
    // elemento interior e exterior que procuras...
});


as3 remove children in loop

Question: I'm working in Flash CS6 with Adobe AIR 3.3 and having trouble deleting movie clips after I have added them to the stage.  Here's my code:
for(var i = 0; i<starCount; i++)
{
    star = new newStar();
    choiceBoard.addChild(star);
    star.x = 195;
    if(i>=1)
    {
        star.x = 195 + 90*i;
    }
    star.y = 597
}

This is part of a function I've created that adds star shaped movie clips dynamically...It adds a movie clip, adds space between, adds the next movie clip etc.  How can I delete all the star movie clips after they are created?
I've tried:
for(var i = 0; i<starCount; i++)
{
    if(contains(star))
    {
        choiceBoard.removeChild(star);
        trace("removed star");
    }
}

But this only deletes one star, regardless what "starCount" is set to.  Thanks in advance.
Answer: private var stars:Array=[];
for(var i = 0; i<starCount; i++)
{
    star = new newStar();
    stars.push(star);
    choiceBoard.addChild(star);
    star.x = 195 + 90*i;
    star.y = 597
}

then try
for(var i = 0; i<stars.length; i++)
{
    choiceBoard.removeChild(stars[i]);
    trace("removed star");
}

Answer: Are the stars they only children of choiceBoard? If so, you can just remove all children like so:
choiceBoard.removeChildren();

Alternatively, you can add all the stars to an array and then iterate through the array to remove them:
var starArray:Array = [];

//...

for(var i = 0; i<starCount; i++)
{
    star = new newStar();
    //put the star into the array
    starArray.push(star);
    choiceBoard.addChild(star);
    star.x = 195;
    if(i>=1)
    {
        star.x = 195 + 90*i;
    }
    star.y = 597
}

And then to remove:
for(var i = 0; i<starArray.length; i++)
{
    //remove the star from the display
    choiceBoard.removeChild(starArray[i]);
    trace("removed star");
}
//clear the array
starArray = [];

Answer: If you have added all your stars into one container (looks like you have with choiceBoard), and there is nothing else in that container that you want to keep around, then you can remove them very simply (and quickly) by doing this:
while(choiceBoard.numChildren)
{
    choiceBoard.removeChildAt(0);
}

as3 remove children in loop


button "submit" inside a partial view

Question: I don't find how to submit a form that's in a partial view.
I've made a kind of search engine for a website. I'd like to add it in the layout from a partial view. My problem is that when I click on 'submit', nothing happens if I'm not in the search view.
Here is the code of the partial view
@Using Html.BeginForm(IsPost)
    @Html.TextBox("SearchString")
   @<input type="submit" value="Go!"/>
End Using

How should I parameter my button if I want it to work correctly?
Namespace MvcApplication4
Public Class SearchController
    Inherits System.Web.Mvc.Controller

    Private db As schema_crmEntities = New schema_crmEntities
'
' GET: /Search
Function Index() As ActionResult
    Return View()
    End Function

    '
    ' POST: /Search
    <HttpPost()>
    Function Index(search As String) As ActionResult
        Dim chaine As String = Request("searchString")

    [...]
        Dim model = New SearchModel With {
            .Meetings = meetings,
            .Interviews = interviews,
            .Opportunites = opportunites,
            .Clients = clients,
            .Contacts = contacts
            }

        Return View(model)
    End Function
End Class
End Namespace

;
  <form method="post" action="/(S(v1sax2fo0frbeuw1ul1xcoet))/Search"><input type="text" value="" name="SearchString" id="SearchString"/>

   <input type="submit" value="Go!"/>
  </form>

Answer: Make sure you specify the controller and the action you are posting to:
@Using Html.BeginForm("MyAction", "MyController", FormMethod.Post)
    @Html.TextBox("SearchString")
    @<input type="submit" value="Go!"/>
End Using

Comment: @Using Html.BeginForm("Index", "Search") or Using Html.BeginForm("Index", "Search", IsPost) redirect me to the gat-index action.
Comment: @patxy, what is the `IsPost` variable? Where does it come from? What's its type? If you have specified a GET verb it's normal that it will redirect you to the Index action. You should specify POST verb. I have update my answer to illustrate how to do this.
Comment: I need to write "IsPost" inside the () of the beginform, however, it does always redirect me to the get. It's not a type, I think it's just a parameter that I have to add to the forms.
Comment: @patxy, is it a variable you have declared somewhere? Did you see my updated answer and the usage of `FormMethod.Post` as third parameter?
Comment: I think that FormMethod.Post does exactly the same as "IsPost". Because I haven't declared it anywhere. I found it with a piece of chance while I was dealing with the same kind of problem. FormMethod.Post hasn't solved the problem. I'll edit my question with the controller code within a few seconds
Comment: @patxy, not at all. IsPost is a boolean variable whose value will be false in this case. Could you show the generated `` element in the resulting HTML? It should look like this: ``. Is it the case? Also did you try `@Using Html.BeginForm("Index", "Search", FormMethod.Post)`?
Comment: @patxy, WOW, what's this `/(S(v1sax2fo0frbeuw1ul1xcoet))`? You have activated cookieless sessions in your web.config - ``? Don't do that. This doesn't work well with ASP.NET MVC as it will completely mess up your routes.
Comment: I've not done this by purpose. Do I just have to do put this  becoming   ??? By doing this, it removes the (v1sax2fo0frbeuw1ul1xcoet) from the url, but I still don't go to the post verb
Comment: You should replace `cookieless="true"` with `cookieless="UseCookies"` in your web.config.
Comment: Ok, I'd made a stupid mistake. I was going to the controller, but the way I had made a mistake in my view :-(. So the things that I had to display weren't. And I though the problem was from the controller. Thx a lot both of you!
Answer: You want to change the overload of Html.BeginForm like this:
@Using Html.BeginForm("action", "controller", FormMethod.Post)

UPDATE:
It look like that the problem is related to cookieless session being enabled in web.config which prepends the (S(v1sax2fo0frbeuw1ul1xcoet)) string to the url.
Comment: Ok, I'd made a stupid mistake. I was going to the controller, but the way I had made a mistake in my view :-(. So the things that I had to display weren't. And I though the problem was from the controller. Thx a lot both of you!
Comment: Thanks for the update both of you. I'm glad you got it sorted eventually!

button "submit" inside a partial view


Referring to a predefined QMediaPlayer

Question: Hi I am still learning C++ and QT for my major project for school this year and I would like some help with some syntax of C++ and using certain QT functions. As I am making a media manager, I have managed to get a song to play from pressing a button from a form. Now I want to pause the same song by pressing another button, but I am not completely sure what to do, could you help?
I already have this to play a song:
void MainWindow::playAudioFile(){
    QMediaPlayer *player = new QMediaPlayer(this);
    player->setMedia(QUrl::fromLocalFile("LOCATION OF SONG FILE"));
    player->setVolume(50);
    player->play();
}

But I want to know how to pause the same audioi file from the QMediaPlayer called 'player', and at the moment all I have thought of is this and I am not sure if I am doing it correctly:
void MainWindow::pauseAudioFile(){
    player->pause();
}

Both of these functions (if that is what they are called) begin with a button press, which I know works for the first one.
Answer: You are trying to access a non-accessible object here:
void MainWindow::pauseAudioFile(){
    player->pause();
}

I am surprised if it was even compiling for you. The solution would be to change this:
QMediaPlayer *player = new QMediaPlayer(this);

to
player = new QMediaPlayer(this);

where the "player" object is the member of your MainWindow class, so basically you would put this into your MainWindow class:
#include <QMainWindow>
#include <QMediaPlayer>

class MainWindow : public QMainWindow
{
    Q_OBJECT
    public:
        explicit MainWindow(QObject *parent = 0)
            : QObject(parent)
            , player(new MediaPlayer(this))
    ...
    public slots:
        void playAudioFile() {
            player->setMedia(QUrl::fromLocalFile("LOCATION OF SONG FILE"));
            player->setVolume(50);
            player->play();
        }
        void pauseAudioFile(){
            player->pause();
        }
    private:
        QMediaPlayer *player;
}

That being said, you may not need a heap object in this case at all, and you can start using a stack object without dynamic memory allocation.
Comment: @Kinexd: fyi, it is not a Qt issue, but generic C++. I would suggest to read upon classes in C++. It is important to know how members work.
Comment: @Kinexd: I updated the answer to be copy/pasteable, but please take a look [at the recommended books](http://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list).
Comment: @Kinexd: sure, you have to do either `#include QMediaPlayer` in the header or `class QMediaPlayer;` before the class declaration, and include it in the source.
Comment: Sorry, but I am getting many errors trying your solution and it is confusing me. So inside the `void MainWindow::playAudioFile()` i have changed `QMediaPlayer *player = new QMediaPlayer(this);` to `player = new QMediaPlayer(this);`. Then in the MainWindow class I changed it to how you put it.
Comment: I really want to learn more C++ as you can tell I don't know a lot. Would you recommend anything that will help me learn C++ for my purposes?

Referring to a predefined QMediaPlayer


SEHException with simple DLL

Question: I am currently trying to use a simple C++ DLL in a C# program for a school project but I have trouble making the DLL and Program link with each other. When I try to call the DLL's function in the main program, I get a SEHExcpetion thrown from the DLL.
Here is the DLL code
#include <stdio.h>
#include <string>

using namespace std;

extern "C"
{
    __declspec(dllexport) string Crypter(string sIn)
    {
        return sIn+ " from DLL";
    }
}

And here's the C# code
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Runtime.InteropServices;

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        [DllImport("CryptoDLL2.dll")]
        public static extern string Crypter(string sIn);

        public Form1()
        {
            InitializeComponent();
        }

        private void BTN_Crypter_Click(object sender, EventArgs e)
        {
            TB_OUT.Text = ("");
            TB_OUT.Text = Crypter(TB_IN.Text); //exception thrown here
        }
    }
}

Answer: Strings in C# and C++ - Those are completely different types, layouts, etc. And you expect them to work.
Check out char* with marshalling.
Answer: you cannot use std::string from C#, it is a c++ class, .NET does not know how to handle it.
Try using wchar_t* or BSTR.
Answer: I did a test to make sure the linking was fine, here is a sample app showing it does work.
#include <stdio.h>
#include <string>

using namespace std;

extern "C"
{
    __declspec(dllexport) string Crypter(string sIn)
    {
        printf("test");
        return "from DLL";
    }
}

And
public class Test
{
    [DllImport("TestDll.dll")]
    public static extern string Crypter(string sIn);

    static void Main(string[] args)
    {
        Console.WriteLine(Crypter("a"));
    }
}

This prints me out
test

followed by a newline.
You need to probably marshal the data from c++ to .net, or use a c++/clr managed dll which would make things easier on you.

SEHException with simple DLL


Using migrate with a multi-page / paginated source

Question: I have a working module pulling a JSON feed into Drupal using the Migrate module. However, the feed is paginated, and I am only getting the first page of results (ordered DESC on creation, so giving the latest items).
I need to go back through all pages and get all/any changed items, but I can't see how to tell Migrate to iterate through the pages.
Answer: You can parse paginated sources with migrate but it takes a little work overriding MigrateListJSON - you may want to ignore the $jsonContainer part - that's just because the result set in our service is in a container (hence this class is abstract).
abstract class BSBaseMigrateListJSON extends MigrateListJSON {
  /**
   * String containing the JSON container name.
   */
  protected $jsonContainer;

  /**
   * Contains the default limit for pagination of the service.
   */
  protected $serviceLimit = 50;

  /**
   * Return an array of the IDs found in the list URL.
   */
  public function getIdList() {
    migrate_instrument_start("Retrieve $this->listUrl");
    $data = $this->getTree();
    migrate_instrument_stop("Retrieve $this->listUrl");
    if ($data) {
      return $this->getIDsFromJSON($data);
    }
    Migration::displayMessage(t('Loading of !listurl failed:', array('!listurl' => $this->listUrl)));
    return NULL;
  }

  /**
   * Returns the amount of items to be processed.
   */
  public function computeCount() {
    if ($data = $this->getTree()) {
      return count($data[$this->jsonContainer]);
    }
    // Else fail and return N/A results.
    return NULL;
  }

  /**
   * Returns an array of crids.
   */
  protected function getIDsFromJSON(array $data) {
    $ids = array();
    foreach ($data[$this->jsonContainer] as $item) {
      $ids[] = $item['id'];
    }
    return $ids;
  }

  /**
   * Returns the list URL decoded JSON response.
   */
  protected function getTree() {
    $items = array();
    $offset = 0;

    do {
      $url = $this->rebuildUrl($offset);
      $json = $this->getTreeData($url);
      $data = drupal_json_decode($json);
      $items = array_merge($items, $data[$this->jsonContainer]);
      $offset += $this->serviceLimit;
    }
    while ($data['moreResources'] == TRUE);

    // Return data if any is present.
    if (!empty($data)) {
      $data[$this->jsonContainer] = $items;
      // @todo Consider whether just returning $items is feasible.
      return $data;
    }

    Migration::displayMessage(t('Loading of !listurl failed:', array('!listurl' => $this->listUrl)));
    return NULL;
  }

  /**
   * Returns a constructed url with offset if required.
   */
  private function rebuildUrl($offset = 0) {
    $url_parts = parse_url($this->listUrl);

    // Build the query parameters.
    if (isset($url_parts['query'])) {
      parse_str($url_parts['query'], $url_parts['qparts']);
      foreach ($url_parts['qparts'] as $key => $value) {
        if ($value === '') {
          $url_parts['qparts'][$key] = NULL;
        }
        elseif ($key === 'q') {
          $url_parts['path'] = $value;
          unset($url_parts['qparts']['q']);
        }
      }
    }

    // If the offset is zero then we can simply return the original list URL.
    if ($offset == 0) {
      // Handles overriding the service limit if there's already a limit set in
      // the list URL.
      if (!empty($url_parts['qparts']['limit'])) {
        $this->serviceLimit = $url_parts['qparts']['limit'];
      }
      return $this->listUrl;
    }

    // Add the offset to the query parameters.
    $url_parts['qparts']['offset'] = $offset;

    // Build parameters to pass to the url function.
    $url_params = array(
      'path' => $url_parts['scheme'] . '://' . $url_parts['host'] . $url_parts['path'],
      'options' => array(
        'query' => isset($url_parts['qparts']) ? $url_parts['qparts'] : NULL,
        'fragment' => isset($url_parts['fragment']) ? $url_parts['fragment'] : NULL,
        'external' => TRUE,
        'https' => (bool) $url_parts['scheme'] == 'https',
      ),
    );

    return url($url_params['path'], $url_params['options']);
  }

  /**
   * Returns the data from the given list URL.
   */
  private function getTreeData($list_url) {
    if (empty($this->httpOptions)) {
      return file_get_contents($list_url);
    }
    $response = drupal_http_request($list_url, $this->httpOptions);
    if (!empty($response->data)) {
      return $response->data;
    }
  }
}

This code probably won't work as-is for you as it's specific for our service, you'll most definitely need to change this line: while ($data['moreResources'] == TRUE); and anything to do with offset depending on how your service works but it's a start for how to proceed.
Answer: I would do a 2 step process -- I'm not sure there is a better way using solely migrate.
Use drupal cron and a Queue to fetch all pagination results to a folder containing all the files with json data. Then use your migration(s) to process the data. Drupal has built-in cron and queue APIs; but you could just use a Linux system cron, bash or CuRL if you like.
Comment: This is in fact what we did, but I was rather hoping there was a one step process. Feels very much like something migrate should handle.
Comment: I hear what your saying. When using a filesystem source (xml, csv ,json, html files) Migrate assumes nothing about your source files. It assumes you've supplied the full dataset somehow.


How do you read load averages? (eg: Load Averages: 0.60 0.60 0.55)

Question:
Possible Duplicate:
How to understand the memory usage and load average in linux server

My hosting company provides "Load Average" stats when I login. There is no link to more information about them, and no explanation as to what they mean. I'm guessing they are a percentage, but I have no clue why there are three numbers, or what the percentage is actually out of (processor, memory, bandwidth, combination?), and is that this instant or over time? Is this a standard statistic that I should know about?
What are high / low / normal numbers?
Perhaps someone can shed some light on this for me.
Examples:
Load Averages: 0.60 0.60 0.55
Answer: The three numbers represent the number of processes, on average, that are ready to run but are blocked, over the last one, five, and fifteen minutes, respectively.
https://secure.wikimedia.org/wikipedia/en/wiki/Load_average
It varies very slightly from one unix-like OS to the next (e.g., different criteria for "waiting"), but they all work basically the same way.
Answer: Load averages measure the trend in CPU utilization by calculating all demand for the CPU over a period of time, which can be thought of as a moving average. The important point to notice is that the value decreases with age. The figures (which are read left to right) do not include any processes or threads waiting on I/O, networking, databases or anything else not demanding the CPU. It only focuses on what actively demands CPU time, which is entirely different from CPU percentage.
By using the function y == (2^11/2^((5 Log2[E])/(60 x))) with the parameters of the load-average bucket, a constant exponent, and the number of running/uninterruptible processes, an exponential decay function is produced. (EXP_1 / 1 min. average, EXP_5 / 5 min. average and EXP_15 / 15 min. average).
For example if there are four CPUs on a server and it reported a one-minute load average of 4.00, then this indicates the machine has been utilizing its processors perfectly during the past 60 seconds.


Crystal Reports: Refresh Dynamic Parameters in .NET

Question: I am using Crystal Reports 2008 and Visual Studio 2010 (.NET 4.0 framework) to build an ASP.NET web application to display Crystal Reports files through a "CrystalReportsViewer" web control. My application changes the data source of the report at runtime based on a configuration file.
Some of the reports I use have dynamic parameters that pull values from a database table. When I run the Crystal Report, it populates the parameter listbox and allows the user to choose one or many of them. When I run the report in the CrystalReportsViewer control on the ASP.NET page, it gives me an empty text box where the parameters list used to be.
Is there a way that I can 'refresh' or re-populate the dynamic parameters?
Thanks in advance,
-Steven
Answer: I've always had trouble with dynamic parameters. I don't use Crystal in the exact same way you are, but I've noticed that when my data comes from a Stored Procedure, the dynamic parameters are empty when I run the report. My workaround is to set the paramters to null when running the report and then clicking OK on the parameter screen. At that point crystal refreshes the parameters list and them I'm presented with the values in the db to select from. Dynamic parameters work well for me when I add the data tables directly to the report instead of using a stored procedure.
I don't know if this really answers your question but I hope it helps.


Rankings and Dates in Views (data architecture)

Question: I'm working on building a small name ranking database, but I'm having some issues coming up with how to architect the data. Here's the scenario:
You have a list of 100 names with rankings by year.
<code>|  Name  | 2012 rank | 2011 rank | 2010 rank
--------------------------------------------
|  Carl  |    1      |     4     |    15
| Frank  |   40      |    18     |    34
|  Lou   |    8      |     6     |     4
</code>
et cetera and so forth. If each name was a node, how would that content type be set up so you can filter rankings by year?
Would you have a new field for each year that has the ranking in it? ie: Field name: 2012 Rank, value: 8.
Just curious how someone might approach this.
Answer: I could propose using Entity Reference or Field Collection for the second item (Rank).
So, Rank should have 2 different fields eg an integer field (Ranking) and a taxonomy term reference (Year).
These modules will allow you for better data manipulation, Views integration, sorting etc.


Why this limit does not exist?

Question: $$\lim_{(x,y)\to(0,0)}\frac{1}{x+y}$$
I know that the limit does not exist because of the graphic $z=f(x,y)$, but I couldn't get the same thing approaching the limit with $y=mx,\ y=x$ or with polar coordinates. I always get $\frac{1}{0}$.
How do I show that the limit does not exist?
Answer: Let $f(x,y)=\frac{1}{x+y}$, then $\lim\limits_{x\rightarrow 0^+} f(x,x)=+\infty$ and $\lim\limits_{x\rightarrow 0-}f(x,x)=-\infty$ thus the limit $\lim\limits_{(x,y)\rightarrow (0,0)}f(x,y)$ does not exist.

Why this limit does not exist?


comparison between void pointer, is it defined or compiler dependent?

Question: I tried to compare casting an int to void* that worked , even comparison between them
int i=1,j=2;
float a=1.1;

if((void *)i > (void *)j )
cout<<"i>j"<<endl;
else
cout<<"i<j"<<endl;

output was
i<j

but this
if((void *)a > (void *)i )
cout<<"a>i"<<endl;
else
cout<<"a<i"<<endl;

gives an error
 error: invalid cast from type 'float' to type 'void*'

I thought we can cast any thing to void pointers?Is it not so?
Answer:
comparison between void pointer, is it defined or compiler dependent?

That is well-defined, but the results are usually unspecified, as described by C++11 5.9/3: "If both pointers represent the same address or are both the null pointer value, the result is true if the operator is <= or >= and false otherwise; otherwise the result is unspecified."
Note that std::less and friends are required to define a total order for pointers, even if the built-in operators don't.
However, doing just about anything with pointers that you've converted from arbitrary integer values will give undefined behaviour.

I thought we can cast any thing to void pointers?Is it not so?

No. reinterpret_cast (or an equivalent C-style cast) can convert between pointer and integer types. Converting a floating-point value to a pointer makes no sense at all.
Comment: If you are curious why it is unspecified, read up on segmented memory models: with the freedom the C++ standard provides, pointer comparisons can be done *on the segment offset only* in some cases, and in others, you can just compare segment and offset instead of working out where in memory it is (segments can overlap).
Comment: @ParagJain: Correct. You could come up with a nonsensical but valid conversion sequence like `float -> int -> void*`, but the language does not define a direct `float->void*` conversion.
Comment: ok "Converting a floating-point value to a pointer makes no sense at all."...what if somebody asking this question in an interview.So the answer should be it is not legal,?
Comment: Don't understand the standared quote. false otherwise, otherwise unspecified?
Comment: @NeilKirk: "and false otherwise" = "and false if the operator is not <= or >=". "Otherwise unspecified" = "If both pointers *don't* represent the same address or are both the null pointer value, unspecified"
Comment: @Yakk So if I take char pointer a and b = a + 1, cast to void and compare, it's not guaranteed that a < b?
Comment: @neilkirk That is guaranteed to work if and only if `a` was pointing at part of a data structure, and not `nullptr` or past-end. The addresses in each data structure, plus the address one-past-the-end, are valid addresses, and comparison within them is reasonable. If I did `char* buf=new char[10]; char* a = buf+10; b = a+1;` C++ does not guarantee that `b>a`, but it does guarantee that `a>buf`.  In fact, I think `a+1` may invoke undefined behavior (imagine if overflowing the segmented memory model segments can cause an overflow interrupt, and handling it has a performance penalty) technically.
Comment: @NeilKirk: If you cast to `void*` then the only specified behaviour is the quote in my answer; so there's no guarantee that `a<b` then. If you leave them as `char*`, then that is guaranteed *if* both pointers point to members of the same array (or one past the end). See C++11 5.9 if you want to know all the gory details.
Comment: @MikeSeymour I don't ;) I just never use void* if I can aVOID it!!??!
Answer:
I thought we can cast any thing to void pointers?Is it not so?

A void* is intended to allow you to cast to and from any object pointer type, not any type.
This means you could do:
if((void *)&a > (void *)&i )

However, checking and comparing pointer values like this is very rarely useful.
Answer: You can cast the address of "anything" (that's not a function or whose "address" is given by a pointer to member) to a void *. In addition, some integral types can be cast to pointers. I guess what you wanted to do is this
if((void *)&i > (void *)&j )
    cout<<"i>j"<<endl;
else
    cout<<"i<j"<<endl;

and that
if((void *)&a > (void *)&i )
    cout<<"a>i"<<endl;
else
    cout<<"a<i"<<endl;

However, notice that the results of such pointer comparisons are unspecified as per C++11 5.9/3 (as explained by Mike Seymour in his post.
The best way to compare pointers of the same type is using the templates greater, less, greater_equal and less_equal because 20.8.5/8 says:

For templates greater, less, greater_equal, and less_equal, the specializations for any pointer type yield a total order, even if the built-in operators <, >, <=, >= do not.

Therefore, you should use
if (std::greater<void*>()((void *) &i, (void *) &j))
    cout<<"i>j"<<endl;
else
    cout<<"i<j"<<endl;

Comment: @ParagJain: See C++11 5.2.10/8: "Converting a function pointer to an object pointer type or vice versa is conditionally-supported. The meaning of such a conversion is implementation-defined [...]"
Comment: Actually, only object pointer types.  (Not only function pointers but also pointer-to-members are excluded)
Comment: (that's not a function or whose "address" is given by a pointer to member)...that means only object  types not even pointer to a function...?But what is the problem in that if I can cast other addresses?
Answer: You can cast any object pointer type to void* not any type.
So you can solve your problem with:
if((void *)&a > (void *)&i )
//         ^            ^

But comparing the address of two variables is not the same thing as comparing the values. I don't think you will have the result you want... You will have Undefined behaviour here.
Comment: yes actually I made this mistake I should have noticed,I was trying to know about void pointers.thanks.


Totally disconnected topologies on countable set.

Question: Are there totally disconnected topologies $\tau$ on a countable set $X$ such that $(X,\tau)$ is not homeomorphic to one of the following?

$\mathbb{N}$ with the discrete topology;
one-point compactification of $\mathbb{N}$ with the discrete topology;
$\mathbb{Q}$ with the Euclidean topology;
$\mathbb{Z}$ with the $p$-adic topology for some prime $p$

?
Comment: Isomorphic is homeomorphic?
Comment: That's right. And thanks for your answer!
Comment: Another example with some doubts about the possible homeomorphism with $\Bbb Z_p$: the rational points of Cantor set.
Answer: If $\mathcal{F}$ is a free ultrafilter on $\omega$, we can define a topology $\mathcal{T}(\mathcal{F})$ on $\omega \cup \{p\}$, where all points of $\omega$ are still isolated and neighbourhoods of $p$ are $\{\{p\} \cup A: A \in \mathcal{F}\}$. This defines a scattered topology on a countable set, which is hereditarily normal, but not metrisable.
The spaces are homeomorphic (for different ultrafilters) iff they ultrafilters are equivalent (there is a permutation of $\omega$ that transforms one in the other); there are $2^{2^{\omega}}$ many non-equivalent ultrafilters on $\omega$, so that many non-homeomorphic such ultrafilter spaces.
Comment: Pretty awesome.
Answer: The obvious two point compactification of $\Bbb Z$ does the trick.
Answer: Given any countable ordinal $\alpha$, the order topology is a totally disconnected topology (it is homeomorphic to a subspace of the rationals).
If two ordinals are homeomorphic then they differ by finitely many isolated points. So different limit ordinals will give different spaces. There are uncountably many countable limit ordinals, which provides us with plenty of examples.
You get even more. Every successor ordinal is a compact space, so you get uncountably many compact examples that way too.
Comment: Asaf, I was writing "I'm missing some or $\omega+1\approx\omega+2$?" :-)
Comment: Yes yes, those pesky finite additions. But I fixed that on time. :-)


Why are most of my points classified as noise using DBSCAN?

Question: I'm using several clustering algorithms from sklearn to cluster some data, and can't seem to figure out what's happening with DBSCAN. My data is a document-term matrix from TfidfVectorizer, with a few hundred preprocessed documents.
Code:
<code>tfv = TfidfVectorizer(stop_words=STOP_WORDS, tokenizer=StemTokenizer())
data = tfv.fit_transform(dataset)

db = DBSCAN(eps=eps, min_samples=min_samples)
result = db.fit_predict(data)
svd = TruncatedSVD(n_components=2).fit_transform(data)
// Set the colour of noise pts to black
for i in range(0,len(result)):
        if result[i] == -1:
            result[i] = 7
colors = [LABELS[l] for l in result]
pl.scatter(svd[:,0], svd[:,1], c=colors, s=50, linewidths=0.5, alpha=0.7)
</code>
Here's what I get for eps=0.5, min_samples=5:

Basically I can't get any clusters at all unless I set min_samples to 3, which gives this:

I've tried various combinations of eps/min_samples values and get similar results. It seems to always clusters areas of low density first. Why is it clustering like this? Am I maybe using TruncatedSVD incorrectly?
Comment: @MichaelChernick: This comment seems misplaced. What do you mean by trend and why do we care about it in this clustering application? If anything the scatter of the first two PC scores show one obvious cluster. DBSCAN does not examine within cluster variance or anything like that...
Comment: Note that your probably should use DBSCAN with cosine distance rather than Euclidean distance here.
Comment: Welcome to [stats.se]!  Please take a moment to view our [tour].
Comment: The scatter plots show no trend but it could be that the variance is not constant.
Answer: The scatter-plot of the SVD projection scores of the original TFIDF data  does suggest that indeed some density structure should be detected. Nevertheless these data are not the inputs DBSCAN is presented with. It appears you are using as input the original TFIDF data.
It is very plausible that the original TFIDF dataset is  sparse and high-dimensional. Detecting density-based clusters in such a domain would very demanding. High-dimensional density estimation is a properly hard problem; it is a typical scenario where the curse of dimensionality kicks in. We are just seeing a manifestation of this problem ("curse"); the resulting clustering returned by DBSCAN is rather sparse itself and assumes (probably wrongly) that the data at hand are riddled with outliers.
I would suggest that, at first instance at least, DBSCAN is provided with the projection scores used to create the scatter-plot shown as inputs. This approach would be effectively Latent Semantic Analysis (LSA). In LSA we use the SVD decomposition of a matrix containing word counts of the text corpus analysed (or a normalised term-document matrix of as the one returned by TFIDF) to investigate the relations between the text-units of the corpus at hand.
Comment: And as @Tavrock said welcome to the community! :D
Comment: Yes, I was using the original TFIDF data. The clusters from DBSCAN seem reasonable when trying this with the same data in R, so I didn't expect that it would be much different with sklearn. K-means (with sklearn) also works fine on the TFIDF data. Does it make sense that it would work with these other things, but not for this particular DBSCAN implementation? Thanks for the info on LSA though -  I wasn't sure at all when it was valid to use the SVD values for fitting the models vs. using the TFIDF data.
Comment: Great, I am glad I could help. If you believe this post answers your question you could consider accepting the answer. $k$-means (probably) was able to find a clustering because it does not depend directly in a $\epsilon$-like factor like DBSCAN for the radius of its cluster; that doesn't mean that the clustering is sensible though. I have not used the `sklearn`'s Python DBSCAN implementation so I cannot comment on its quality. Notice though that some implementations might do default pre-processing steps and that might accidentally affect their performance when applied.
Answer: DBSCAN min sample should be more than the number of features by 1 and then increase by the number you want this is the number of points in the circle and eps is the radius of the circle.


2020 US Open theme music

Question: Before or after a match, there is a pop song that is played repeatedly on TV.
In the song, I hear a woman and chorus singing together. What is the name of this song? How do I find out about the different music they use every year at the US Open?
Comment: ESPNMusic has a twitter account (@ESPNMusic) which might be the easiest place to find this out; I can neither find an answer nor a Youtube clip of the music you're referring to (I can only find the clip they play at the start of the broadcast, which isn't it as there is no vocals).  Perhaps if you can find a Youtube clip you could post it?
Comment: And - there is the [ESPN Spotify playlist](https://open.spotify.com/user/espnmusic) which is a good source also to check.
Comment: @Joe Thanks a lot--I'll try looking on social media.
Answer: The song is "Kings and Queens" by Ava Max. It was released in 2020, and is featured before and after matches.
Comment: Nice!  Could you include how you figured it out, so others can perhaps follow your lead in the future?
Comment: I learned through the lyrics--just listening more closely helped.
Comment: Ah, thanks for clarifying!

2020 US Open theme music


Como colocar um loop de colunas da DB dentro de um array?

Question: Tenho um banco de dados com colunas dinâmicas que podem uma hora aparecer, outra hora não... também podem vir a ser adicionadas mais colunas ou mesmo extraídas as que já existem.
Eu fiz um código que me permite capturar estas colunas no meu banco de dados em tempo real e agora preciso fazer com que estas colunas apareçam em outra parte do código:
<?php

require("setup_do_banco.php");

$colunas    = $pdo->prepare("SHOW COLUMNS FROM imovel");
$colunas->execute();

###### Aqui tenho todos as colunas do meu banco de dados
while ( $coluna = $colunas->fetch() ) {
    $coluna = $coluna["Field"]; echo "$coluna
";
}

$array = array (
    'key'       => '8b0dc65f996f98fd178a9defd0efa077',
    'module'    => 'imoveis',
    'method'    => 'busca_imoveis',
    'field'     => array (
    ////////////////////////////////
    #                   <------------
    ////////////////////////////////
    )
);

$client = new SoapClient(null, array (
    'uri' => 'http://soap.imo.bi/',
    'location' =>
    'http://soap.imo.bi/soap.dll',
    'trace' => 'trace'
    )
);

$res = $client->get($array);

echo "
"; print_r($res); echo "
";

?>

Como podem ver, através de um loop eu recuperei todas as colunas do meu banco de dados e agora preciso plantá-las dentro do lugar que está a seta cada campo com vírgula no final e quebra de linha. Eu testei colocar o loop dentro do array mas não deu certo.
Como vou colocar as colunas do meu banco ali no lugar da flecha?
Comment: Porque não declarar essa array __antes__ do while, e no while pôr `$array['field'][] = $coluna["Field"];`
Comment: Marcos, tens estado a transformar a pergunta e a revelar problemas novos que não estavam na pergunta inicial. Assim as primeiras respostas perdem sentido e a pergunta fica uma salada. Por favor faz perguntas específicas para problemas específicos e se tiveres um novo problema que não consegues resolver sozinho faz uma nova pergunta. Como reparaste voltei atrás nas tuas atualizações da pergunta. Agora a resposta aceite fica meio descontextualizada...
Comment: Não vou saber fazer isso, pode me ajudar?
Comment: Se esse array deve ter o conteúdo que está na tabela então [a resposta do bigown](http://pt.stackoverflow.com/a/45206/129)  é o que você precisa e é bem mais limpo.
Comment: Podem me ajudar na **Atualização** do que eu consegui fazer. Ele está atribuindo o retorno em `$array['field']` mas este está inserindo o número do índice. Preciso exatamente do código demonstrado em **Atualização**.
Answer: Acho que precisas trocar a ordem das coisas para simplificar...
Sugestão:
require("setup_do_banco.php");

$array = array (
    'key'       => '8b0dc65f996f98fd178a9defd0efa077',
    'module'    => 'imoveis',
    'method'    => 'busca_imoveis',
    'field'     => array ()
);

$colunas    = $pdo->prepare("SHOW COLUMNS FROM imovel");
$colunas->execute();

while ( $coluna = $colunas->fetch() ) {
    $array['field'][] = $coluna["Field"];
}

Dessa maneira esse $array['field'] vai ser preenchido dentro do while, e passado este código a array está "preenchida".
Comment: +1 Solução boa se o problema requerer extrair uma coluna em particular do `SHOW COLUMNS`.
Answer: Não sei se entendi mas acho que seria só isto:
$array['field'] = $colunas->fetchAll(PDO::FETCH_ASSOC);

Coloquei no GitHub para referência futura.
O FetchAll retorna justamente um array associativo completo cujas chaves são os nomes dos campos e os valores que foram retornados nele.
Comment: +1 Solução excelente se a ideia é passar o que vem do `SHOW COLUMNS` para a entrada no outro `array`: `$array['field'] = $colunas->fetchAll(PDO::FETCH_ASSOC);`.
Comment: @Zuul bem notado mexi lá.
Answer: Simplesmente crie um array pegando os campos e depois faça com que o "field" receba esse array:
###### Aqui tenho todos as colunas do meu banco de dados
$fields = array();
while ( $coluna = $colunas->fetch() ) {
    $fields[] = $coluna;
}

$array = array (
    'key'       => '8b0dc65f996f98fd178a9defd0efa077',
    'module'    => 'imoveis',
    'method'    => 'busca_imoveis',
    'field'     => $fields
);

Ou como foi dito nos comentários apenas crie o array antes do loop e receba os dados direto no array:
$array = array (
    'key'       => '8b0dc65f996f98fd178a9defd0efa077',
    'module'    => 'imoveis',
    'method'    => 'busca_imoveis',
    'field'     => array()
);

while ( $coluna = $colunas->fetch() ) {
    $array ['field'][] = $coluna;
}

Comment: Pode me ajudar com esta pergunta que é semelhante mas diferente? Obrigado. http://pt.stackoverflow.com/questions/45259/como-buscar-dados-do-banco-de-dados-e-coloc%C3%A1-los-num-array
Answer: Baseado na atualização e aqui, a única mudanção é no lugar um índice numerico definir uma chave que é composta pela descrição do campo do banco que é representando por: $item['field'].
<?php
//O fetchAll() deve retornar um array nesse formato.
$array_banco = array(
                0 => array('field' =>  'DATA', 'description' => 'Data cadastro'),
                1 => array('field' => 'ENDERECO', 'description' => 'Endereço'),
                2 => array('field' => 'BAIRRO', 'description' => 'Bairro'));

$array = array (
    'key'       => '8b0dc65f996f98fd178a9defd0efa077',
    'module'    => 'imoveis',
    'method'    => 'busca_imoveis',
    'field'     => array()
);

foreach($array_banco as $item){
    $array['field'][$item['field']] = sprintf("'%s' => '%s'", $item['field'], $item['description']);
}
echo '
';
print_r($array);

echo $array['field']['DATA'] .' - '. $array['field']['ENDERECO'] .' - '. $array['field']['BAIRRO'];

Saída:
Array
(
    [key] => 8b0dc65f996f98fd178a9defd0efa077
    [module] => imoveis
    [method] => busca_imoveis
    [field] => Array
        (
            [DATA] => 'DATA' => 'Data cadastro'
            [ENDERECO] => 'ENDERECO' => 'Endereço'
            [BAIRRO] => 'BAIRRO' => 'Bairro'
        )

)
'DATA' => 'Data cadastro' - 'ENDERECO' => 'Endereço' - 'BAIRRO' => 'Bairro'

Comment: Só uma observação. esta saída não vai rodar meu SOAP. Preciso que seja `'DATA' => 'Data cadastro'` ... Ah e eu não vou conseguir montar `$array_banco`. Obrigado pela sua ajuda.
Comment: @MarcosVinicius, alterei a resposta, `$array_banco` tem a mesma estruta de um array retornado por `fetchAll()`, fiz ele apenas para teste.
Comment: Estou quase chegando ao que eu preciso. Pode me dar mais uma força em **Atualização 2**?
Comment: Não entendi, no código da pergunta você está recriando `$array` depois do foreach


possible to lookup address locations with graphhopper via url?

Question: I can't find any information so is it possible to lookup a address localtion (lat, long) with graphhopper via url like the search.php in nominatim?
thanks & regards
Answer: GraphHopper is a purely routing engine and there is no plan yet to add address search. Still we offer address search in our Directions API for business.


Drupal with frames

Question: I'm using Drupal 7 to create a musician's website. That musician would like to be able to play a sample of their music across multiple pages of the site without interruption. The only way I know to do this is to use frames. However, in the many sites I've used Drupal for, I've never used frames on a single Drupal site.
Has anybody else had experience with how to accomplish this?
EDIT: To clarify, the client wants an integrated music player within the site itself. Creating or finding a music player is easy. It's setting up to work with Drupal and not reload across pages that I don't know how to accomplish.
Answer: You can just open new window via js and play it there. You can now navigate through site and music will play until you don't close certain window. So you should create page/node with player, create page template for it (you should remove showing block, menus,  etc in this) and point for js:window.open to that page.
Comment: Frames are not a clean way to do anything. Frames are bad and dead. That's why you can't find a Drupal frame Site. http://www.google.ch/search?q=why+frames+are+bad If you don't want a Popup which is IMHO the best solution for you, you have to load your website content with an AJAX call. Therefore the page 'remains' the same while the Background music plays.
Comment: That would indeed allow me to play music across pages, but it's not a very clean way of having an integrated media player in the site itself.
Comment: Not really a solution, but I talked the client into not caring.

Drupal with frames


Alternatives to a one-dimensional Poisson process

Question: Say I have "arrival" times in what may or may not be a Poisson process.  I can think of at least three ways in which it can deviate from a Poisson process:

Clumping. One arrival is likely to be near other arrivals.  This raises a question of how to estimate where one clump ends and the next begins.  And sizes and shapes of clumps.  It's easy to see one way to reject the hypothesis that it's a Poisson process in favor of this alternative: Kolmogorov–Smirnov, assuming a uniform distribution in time.  How to proceed after rejection is not as clear.
Repulsion between arrivals close together in time.  It is said that crossovers between chromosomes behave this way.  Maybe times between arrivals could have a gamma distribution with shape parameter $>1$?  Or maybe something else?
Repulsion between adjacent arrivals regardless of the distance between them.  I have the impression that the distribution of eigenvalues of random Hermitian matrices might be distributed like this, but I don't know what the probability distribution of the gap sizes looks like, let alone how to reject a Poisson process in favor of this alternative.

Right now I'm suspecting I might mainly need to be concerned with the first possibility above.  So what is done, and one is there to read about what is done?
Comment: "What is done" in what sense? What are you trying to do? What is the goal of your study / analysis?
Comment: What is your actual question here? Do you want to test whether it's a Poisson process? Your last sentence does not make any sense.
Comment: Primarily I want to know what is done in cases where the null hypothesis that it's a Poisson process is rejected in favor of clumping.
Comment: *It's easy to see one way to reject the hypothesis that it's a Poisson process in favor of this alternative: Kolmogorov–Smirnov, assuming a uniform distribution in time.* – That's not a good way to decide about Poissonianity as there are other ways to achieve a uniform distribution in time. You better look at the distribution of inter-arrival times.
Comment: What I'm trying to do at the moment is clean up some problems in the data file so that I can get R to read it.  What I will try to do next is explore the data before deciding what to do after that.  My initial suspicion is that some clumping might be there.
Answer: I still not entirely sure what you want, but I'll give this a try:
If you suspect a process to be Poissonian or be close to it and still describable in terms of arrival probabilities, looking at the distribution of times between arrivals (inter-arrival distribution) is a good approach:

For a pure Poissonian process, the inter-arrival distribution is perfectly exponential. In this case, the distribution of waiting times for the next arrival (when starting to wait at random time points) is also exponential (this one may be easier to obtain). Processes that are close to being Poissonian can now be classified by how their inter-arrival distribution deviates from the exponential distribution for the average event-rate of the process (blue in all of the following).

If there is clumping, arrivals beget arrivals, i.e., if the arrival probability is higher after an arrival, you would expect the inter-arrival distribution (green) to be higher than the exponential distribution (blue) for short inter-arrival times:

If arrivals repulse each other, the arrival probability is reduced after an arrival and thus the inter-arrival distribution (green) should be lower than the exponential distribution (blue) for short inter-arrival times:

Repulsion between adjacent arrivals regardless of the distance between them.

Unless you specify how your repulsion works, I would not see a way to distinguish this from a Poisson process with a lower event rate:

Finally, if your process is nowhere near a Poissonian process, you would expect your inter-arrival distribution to look completely different from an exponential one. For example, if your arrival probability only assumes considerable values during short, regularly occuring time windows, you would get something like this:

Note that if your process is somwhere near a Poissionian one, it may help to think about it in terms of arrival probabilities while thinking of it in terms of arrivals attracting or repelling each other may be confusing. The latter is problematic as it implies that the whole series of arrivals is predetermined and ignores that arrivals are – as a first approximation – independent random events.
Comment: "Repulsion between adjacent arrivals regardless of the distance between them." and "Unless you specify how your repulsion works, I would not see a way to distinguish this from a Poisson process with a lower event rate". One should be able to _prove_ either that it's the same thing or that it's not.  I'll think about that.


Updating Nested Data in Flutter Firebase's Firestore database

Question: I need some help updating the following nested data in flutter:
{
  story: [
    0: {
      'views': {
        // Updated DATA here
      }
    },
    1: {
      'views': {
        // Or here
      }
    }
    // Some other data
  ]
}

How can I updated data in firebase using above structure in Flutter?
Answer: I think you need a SetOptions parameter when you set a new value
FirebaseFirestore.instance.collection('...').document(id).set(newObject, SetOptions(merge:true);

Answer: With this structure I believe the only option you have is to read the data first,
update it locally and then save it again into Firestore with either setData or updateData.


Calculate percentage difference for two sets of points

Question: As the title says, I'd like to calculate the percentage difference for two sets of points. For example, suppose I have $S_{1}=\{(1,x_{1}),(2,x_{2}),(3,x_{3})\}$ and $S_{2}=\{(1,y_{1}),(2,y_{2}),(3,y_{3})\}$. How can I know the difference in percentage between both sets of data. What is the correct way to do that? Is that kind of assessment meaningful to establish to which degree of precision a set of data is preferred over the other?
In my particular case, $S_{1}$ is simply a set of numerical results obtained by DSMC and $S_{2}$ was obtained by a theoretical result. I'd like to quantify how much difference exist between each other in order to establish when it is convenient to use one or the other.
By "difference in percentage" I mean percent difference. Hopefully that clarifies a bit the question.
UPDATE:
Another way to formulate my question would be: How can I arrive to conclusions such as "The results from experiment A are inaccurate by 10% with respect to experiment B", when experiment A and B are a set of values.
Comment: It's still not clear what you mean. Do you mean the number of points which are different? Do you mean the percent difference in the averages? Do you mean the mean percent difference for each of the pairs of points? There's no obvious way to interpret what you're asking for. Percentage difference is not something people normally think about for sets of points. Percent difference can fully specify how two individual points are different, but you need a lot more information to fully specify how different two sets of points are.
Comment: To keep the responses relevant to the question you have in mind, could you say a little more about what these data are, what you mean by "difference in percentage," and why that's important to you?
Comment: Alright. I will edit the post.
Comment: @John: Exactly, percentage difference works fine for a pair of points, but when someone says that certain result (as a function or as a set of numbers) is inaccurate by 10% or 15% with respect to another result, how can you arrive to such conclusion?
Comment: By the way, I don't mean any particular question as "How to calculate percent difference". I want to know what is the correct way to reach the kind of conclusion I mentioned before.
Comment: Let me give you an example, say you have 1 population of 50 individuals and 2 bathroom scales. You want to know if both bathroom scales work equally well? Or if one scale with give readings higher or lower than the other?
Comment: @carlosdc: No, sorry. Did you read the update?. I put an example there of what I want to know.
Comment: @Robert Smith, Yeah, sorry what you said doesn't make much sense. I'm trying to put it in statistical terms.
Comment: @carlosdc: See the answer posted by Dennis.
Answer: It seems to me like you need to formulate a question you want your data to answer. Let me suggest a few (perhaps you can edit your post to reflect what questions make sense for your data):

As the DSMC value increases, does the theoretical result also increase?
If I know the value of the theoretical result, how accurately can I estimate the value of DSMC?

If the points (1,x1) and (1,y1) refer to the same measurement or the same run of the experiment, or one is an estimate of the other. One natural way to see how related they are related is to plot {(x1,y1),(x2,y2) ...}.
You can read about Pearson correlation and Kendall tau and Spearman rho here:
http://en.wikipedia.org/wiki/Correlation_and_dependence
Comment: +1 For a valiant attempt at deciphering the question and providing good advice.
Comment: Thanks for your answer. Unfortunately, those questions are not what I want to know. I updated the question, though.
Answer: First, let's compare two lists of numbers — are they from the same distribution ?
For example, how close are the lists of 20 numbers, "|" marks,
<code>||||||.||.||...||.....||.|................|.....................................
|||.|...|..|...|.......||...|...|...|.....|..|.................|.....|..........
</code>
? To see, visualize, how such lists differ
(whether real, simulated or theoretical),
make a QQ plot:
sort X, sort Y, plot the pairs (Xj, Yj),
see how close that curve is to the line X = Y.
Also, search QQ plot here.
A K-S test
gives a number from 0, X and Y identical,
to 1, way off; you could flip this around to 100 % down to 0 %.
However a QQ plot shows more directly where X and Y differ.
Comment: You're welcome Robert; could you post what you ended up using (in a week or so) ?


Cannot change org.springframework-version in STS

Question: I just created a Spring MVC project in STS 3.3.0.RELEASE and just changed the default<org.springframework-version>3.1.1.RELEASE</org.springframework-version> to <org.springframework-version>3.2.1.RELEASE</org.springframework-version>, and Eclipse throws errors (see screenshot below). Any clue on how to remove these errors (perhaps the top one is the culprit)
Answer: Solved - http://www.captaindebug.com/2013/03/creating-spring-32-mvc-web-app.html#.Uf7V-WTbrus - quoting the author - Now, I could have used the fix outlined in my previous blog; however, the Guys at Spring have been busy and now the solution to this problem is to simply upgrade to Spring version 3.2.2-RELEASE


Methodological test for choosing 'worse' models that make 'better' (more realistic) predictions?

Question: I've run 4 models (simple LM, quadratic model, GLMM, and GLMM with quadratic) to predict tree age (age) from tree diameter (D) for each of 42 species (SPEC). The diameter data has all been log transformed to account for non-normality and heavy weighting of near-zero values. I've compared each of these models using AIC separately for each of the species and chose the model with the lowest AIC to use for each species.
I have a rough idea about what tree age predictions should look like (i.e., not super large or negative). The problem is that most of my 'best' models (generally the GLMM with quadratic) make essentially nonsense predictions for that species. However, if I look at the predictions of 'worse' models (typically the simple LM) for those given species, the predicted age values make more sense. So I would be more inclined to use these 'worse' models in these instances. The 'worse' model that is the best predictor is further not always consistent between species and some species' ages are best predicted from the model with the lowest AIC -- in other words, it's not consistent.
My question is: Is there a methodological way to choose the model post hoc regardless of how it ranks in terms of AIC (and instead by how it predicts sensible values with new data)?
Comment: I wonder if any of the models you have tried include interactions between species and other predictors. If not, you're assuming the same relationship for all species, with only a scale factor for each species. That sounds likely to be very limiting. It is true that interactions with species will create a lot of extra parameters - but maybe you can divide species into a small number of groups (based on biological criteria, preferably) and use interactions with the grouping factor instead.
Comment: I will admit that many of the discrepancies occur with trees with large D, of which few or none exist in the training data.
Answer: It sounds like you're looking for cross-validation. In many contexts, it's used to tune the parameters of a model when the primary goal is prediction, using a process summarized like so:

Select a subset of the available data, say 80%, and use it to train the model.
Select the parameter value that minimizes prediction error on the remaining, unseen subset.

There are diverse implementations of this technique, but that's the overall gist. You can also apply the same principle for model selection: Simply choose the model that minimizes prediction error on unseen data.
Comment: @theforestecologist both good questions. For the first, I'd search the cross-validation tag for questions about CV on small datasets. You may also want to look for questions about ensuring that a test set is representative. To the second question, my intuition is that no, one cannot count on CV error estimates to generalize well outside the range of inputs used to train the model. But justifying that formally is a little above my pay grade :) in any case, I'd suggest asking separate questions on these specific topics.
Comment: What if my data set is too small to split the data into training data? (because I assume I need to know the actual values  I'm trying to predict from the test the data in order to use them to determine prediction error).
Comment: Also, as I commented above, many of the issues I see in predicted values occur with trees with large D, of which few or none exist in the training data. (For example, the largest tree in the training data is D=25, but the largest tree needing a predicted value is D=75). Can cross-validation help with this?


Calling Method from Native dll works first time, instacrashes on second time (due to fortran modules)?

Question: I'm creating a C# net4.5 console project which consumes a fortran dll. The method from this dll works fine on the first call, and instacrashes on second call, no error messages of any sort.
Running some tests, i found that if i don't use the module1, meaning put the variable declaration on subroutine, it works fine, on any number of calls
C#
static void Main(string[] args)
    {
        TestMyArray();//WORKS FLAWLESLY
        TestMyArray();//INSTAKILLS PROGRAM
    }

    private static void TestMyArray()
    {
        Console.WriteLine("START");
        int size = 52;
        float[] myarray = new float[size];
        sub_(ref size, myarray);
        Console.WriteLine(myarray.Select(x => x.ToString()).Aggregate((x, y) => x + ";" + y));
        Console.ReadLine();
    }

    [DllImport("FortranArraySimpleTest.dll", CallingConvention = CallingConvention.Cdecl)]
    static extern void sub_(ref int size, float[] myarray);

FORTRAN
 !DEC$ ATTRIBUTES DLLEXPORT::ingammaextern
subroutine sub(size, myarray)
    use module1   ! * REMOVING MODULE USAGE FIXES THE PROBLEM
  implicit none
INTEGER  :: size
integer :: assignme
REAL, dimension(1:size) :: myarray

assignme = size
allocate(alocarray(1:assignme))

end subroutine
! ************************************begin another file***********
      MODULE module1
      IMPLICIT NONE

real, dimension(:), allocatable :: alocarray
      END MODULE module1

This solution, the removal of modules, is extremely cumbersome and a maintenance major headache, due to the code which made me post the question being very large.
Environment: GNU Fortran Compiler, windows 7 64bits, CodeBlocks for fortran, VS2012, i didn't change any compiler options.
Any ideas?
Thank you for your time
Answer: You should deallocate the array allocarray in the subroutine before leaving it. As it is a module variable used by host association in your routine, it will remain allocated after the subroutine is left. Trying to allocate it again when you enter the routine the second time may be the cause for your crash. Alternatively, you could check for its allocation status via the allocated() intrinsic function.


How to get the id from a click event

Question: I use query snapshot.forEach created something like for loop that will loop through all of my data in firebase, and print them out with a div tag with a click event. When other users click on the div event, the event will grab the document in cloud firestore with the id of the div tag, now I am looking for how to get the id from that div tag that triggered the click event.
db.collection("posts")
    .get()
    .then((querySnapshot) => {
        querySnapshot.forEach((doc) => {
        postData = doc.data()
        var wrapper = document.createElement('div')
        wrapper.classList.add('wrapper')
        wrapper.setAttribute('id',postData.title);
        var content = document.createElement('div')
        content.classList.add('content')
        content.setAttribute('id',postData.id);
        var title = document.createElement('h1')
        title.classList.add('title')
        var introduction = document.createElement('p')
        introduction.classList.add('introduction')
        title.innerHTML = postData.title
        introduction.innerHTML = postData.introduction
        postCollection.appendChild(wrapper)
        wrapper.appendChild(content)
        content.appendChild(title)
        content.appendChild(introduction)
        content.onclick=function(event){
      profilePage.classList.add('hide')
      forumePage.classList.add('hide')
      postPage.classList.add('hide')
      postComment.classList.remove('hide')
        }
            console.log(doc.id, " => ", doc.data());
        });
    })

Comment: Welcome to SO. You might find reading the site [help section](https://stackoverflow.com/help) useful when it comes to [asking a good question](https://stackoverflow.com/help/how-to-ask). To get the best answers to your question we like to see that you've attempted to solve the problem yourself first using a [minimal reproducible example](https://stackoverflow.com/help/minimal-reproducible-example). Here's a [question checklist](https://meta.stackoverflow.com/questions/260648/stack-overflow-question-checklist) you might find useful...
Answer: I think that should answer your question, or at least what I understood from it
db.collection('posts')
  .get()
  .then ( querySnapshot =>
    {
    querySnapshot.forEach( doc =>
      {
      let postData = doc.data()
        , wrapper  = document.createElement('div')
        , content  = document.createElement('div')
        ;
      wrapper.className = 'wrapper'
      wrapper.id        = postData.title
      content.className = 'content'
      content.id        = postData.id
      content.innerHTML = `

${postData.title}

${postData.introduction}
`

      wrapper.appendChild(content)
      postCollection.appendChild(wrapper)

      content.onclick = event =>   // in case of way 1 you need to use Arrow function
        {
        profilePage.classList.add('hide')
        forumePage.classList.add('hide')
        postPage.classList.add('hide')
        postComment.classList.remove('hide')
        console.log(content.id)               // way 1
        console.log(event.currentTarget.id)   //  way 2
        }
      console.log( doc.id, " => ", doc.data())
      })
    })

How to get the id from a click event


Can I move a constant function out of an integral?

Question: I have the following integral:
$$\int\exp(2\pi i \Omega t)\beta(\omega_0)d\Omega$$
while $\Omega$ is defined as
$$\Omega = \omega - \omega_0$$.
$\omega_0$ is handled as a constant value, while $\omega$ is a variable. Now I am not sure if I can move $\beta(\omega_0)$ out of the integral.

Reason for moving it out: It is a const. value, and never changes.
Reason for doubt: $\omega_0$ is also used in the integration variable $\Omega$.

Is there a reason not to move $\beta$ out?
Answer: Use
$d\Omega=d\omega$ and write the integral explicitly as
$$
I(\omega_0)=\int d\omega e^{-2\pi i\omega_0 t} e^{2\pi i\omega t}\beta(\omega_0)
$$
now it should be obvious which factors can be pulled out of the integral.
Comment: would the downvoter care to comment?
Comment: At least I don't see the problem here (just doing a facepalm that I forgot this possibility...)
Answer: If $ \beta ( \omega_0 )$ is a function of constant $\omega_0$ alone, it can be pulled out of the integral sign.  $ d \omega = d \Omega $ ,  $\omega ,\Omega $ are variables.


How do you show output of assert in Meteor?

Question: console.log 'before'
assert 1 is 2
console.log 'after'

When I run meteor, all that is printed is 'before', and nothing about an assertion failing. The assert package has been added with meteor add assert.
Answer: Try this (looks like you're using coffeescript):
console.log 'before'

try
  assert 1 is 2
catch error
  console.log error.message

console.log 'after'

Comment: Thanks, do you know of a way to get Meteor to log all thrown exceptions? Or in particular those thrown on the server side of a method.
Comment: Do you want them to be logged to the Node.js console, the browser console, a log file, a log collection, etc? However you are logging exceptions, you could always wrap the inner code of your methods in a try/catch block. It wouldn't be hard to abstract this into a more reusable wrapper function that does your error logging. Just basic first-class functions.
Comment: Would be awesome if all exceptions thrown were logged to the console, at least in development mode... :-)


How to pick value from list if gap(diff) is larger than a define number

Question: a = [44, 52, 59, 62, 174, 175, 178, 288, 292, 404, 408, 518, 521, 633, 637, 747, 751, 863, 867, 977, 980, 987]
For example, on above list, if the gap is 100, then first 3 items should be filter out.
final result should be:
b = [62, 174, 288, 404, 518, 633, 747, 863, 977]
here is my code:
def pick(lst, gap):
    result = []
    first_item_picked = False
    for idx, x in enumerate(lst):
        try:
            if not first_item_picked and idx < len(lst)-1 and lst[idx+1]-x > gap:
                first_item_picked = True
                result.append(x)
            elif x- lst[idx-1] > gap:
                result.append(x)
        except:
            print(idx,x)
    return result

b = pick(a,100)
print(b)

How to write a more simple algorithm to make it?
Comment: First, write down and understand the "rules" of the algorithm, step by step, then try to write Python code for it. If you have a specific issue while doing this, you can ask here with your code.
Comment: my code added. Just found if there is easier way.
Comment: explain what you mean by gap and what criteria needs to checked when filtering
Answer: You can use itertools.pairwise to iterate through the input list in pairs, and if the gap between a pair is greater than the threshold, append the latter of the pair to the output, but also append the former to the output if it is going to be the first output item:
from itertools import pairwise

def pick(lst, gap):
    output = []
    for a, b in pairwise(lst):
        if b - a > gap:
            if not output:
                output.append(a)
            output.append(b)
    return output

Demo: https://replit.com/@blhsing/KnobbyUsefulAbility
Comment: This is just what I need! pairwise !
Answer: >>> a = [44, 52, 59, 62, 174, 175, 178, 288, 292, 404, 408, 518, 521, 633, 637, 747, 751, 863, 867, 977, 980, 987]
>>> res = []
>>> for (v, nxt) in zip(a, a[1:]):
...  if res:
...   if res[-1] + 100 <= v:
...    res.append(v)
...  else:
...   if v + 100 <= nxt:
...    res.append(v)
...
>>> res
[62, 174, 288, 404, 518, 633, 747, 863, 977]


Is complex field validation possible with WebForm?

Question: WebForm is a very nicely done module, but (at least at first glance) it seems to lack some things that I expect to need.
Specifically, I'd like a way to specify more complex field requirements than just a boolean.  For instance, what if I have a form with an e-mail address field and a telephone field, and I want the user to be required to enter at least one of the two.  In other words, if they enter an e-mail address, they don't need to enter a phone number; and if they enter a phone number, they don't need to enter an e-mail address.
Is this possible with WebForm?
Answer: Try using the WebForm Validation module.

The following validation rules are currently included:

Numeric values (optionally specify min and / or max value)
Minimum length
Maximum length
Minimum number of words
Maximum number of words
Equal values on multiple fields
Unique values on multiple fields
Specific value
Require at least one of two fields
Require at least one of several fields
Minimum number of selections required
Maximum number of selections allowed
Exact number of selections required
Plain text (disallow tags)
Regular expression
Must be empty (Anti-Spam: Hide with CSS)
Words blacklist
Must match a username
Answer: If your validation logic is complex it might be better to do that through a custom module.
There are three ways:

Regular hook_form_alter() and adding your validation callback to the $form['#validate'] array.
Implement hook_webform_validation_validators().
Implement hook_webform_validation_validate().

See this article for more information about 2. and 3.


Programmatically restart a Windows Service

Question: I know this can be done in C#/.Net but I was wondering whether it can be done calling the Windows API?
I have a service which will service DHCP requests, when I want to update the configuration for the service I need to stop the service, rewrite its INI file and then start the service again.
Any help appreciated!
Answer:
Open the service control manager with OpenSCManager.
Open the service you want to control with OpenService.
Use ControlService or ControlServiceEx with a SERVICE_CONTROL_STOP parameter to stop the service.
Do whatever you need to do.
Use StartService to restart the service.
Use CloseServiceHandle to close the service and SCM handles.
Answer: Sure, there's a whole bunch of C API functions see for example http://msdn.microsoft.com/en-us/library/ms682108%28v=vs.85%29.aspx.
Answer: Sometimes you want to restart the service from the service itself. This solution worked for me.  I omitted the rather trivial timer code for clarity.  Note that this solution works only because the caller is a service and runs at an elevated level.
void Watchdog::OnTimeout()
{
    STARTUPINFO si = { };
    si.cb = sizeof(STARTUPINFO);
    GetStartupInfo(&si);

    PROCESS_INFORMATION pi = { };

    // is modified by the call to CreateProcess (unicode version).
    TCHAR szCmdLine[] = _T("cmd.exe /C \"net stop <yourservicenamehere> & net start <yourservicenamehere>\"");

    // send shell command to restart our service.
    if (!CreateProcess(NULL, szCmdLine, NULL, NULL, FALSE, CREATE_NEW_CONSOLE, NULL, NULL, &si, &pi))
    {
        // do some error reporting...
        LOG("*** ERROR *** Watchdog timeout.  Restart attempt failed. Last error: 0x%x\n", GetLastError());
    }
}

Answer: I'm late for the party, but I'd suggest the official detailed examples for both starting and stopping a service. The advantage over the other answers here is that they include error handling, edge cases and dependent services -
Stop: http://msdn.microsoft.com/en-us/library/windows/desktop/ms686335(v=vs.85).aspx
Start: http://msdn.microsoft.com/en-us/library/windows/desktop/ms686315(v=vs.85).aspx
Answer: Are you looking for something like this: Starting and stopping services ?
Answer: You'll need to open the service control manager (OpenSCManager), then open the service itself (OpenService) and finally ask it to start itself (StartService).  Close off all the handles you've used along the way, then you're done.
Wow, handling services in C++ really takes me back...
Good luck,
Answer: In a dos box, net start [service] would do what you need. If you don't find an API solution, you could always start a process for net.exe using start [service] as parameters.
Answer: You can also use WMI for this.  The sample code at that link is VB, but it should be pretty easy to port to just about any language on Windows.
If you are into automation on Windows, WMI is good to learn because it provides a language-neutral object-oriented interface to most of the interesting objects on the system.


Permutation restricted to subset, reorder the range

Question: Consider the set of numbers $N = \{ 1, \dots, n \}$ and let $S \subseteq N$ be a subset.
Now let $\pi : N \rightarrow N$ be bijective, so $\pi$ is a permutation of the numbers from $1$ to $n$.
Then $\pi(S) \subset N$ is another subset, and generally the permutation will not list the elements of $S$ in the correct order. What is the sign of the permutation over $\pi(S)$ that orders them back?
Comment: Generally the restriction of $\pi$ to $S$ will not be a permutation of $S$, so it is unclear what "list the elements of $S$ in the correct order" refers to.
Comment: Read the question again.
Answer: If $S=\{m_1,m_2,\dots,m_k\}\subseteq N$, then we can write
$$\pi(S) = \{\pi(m_1),\pi(m_2),\dots,\pi(m_k)\}.$$


bootstrap modal delegate eventype syntax

Question: var Modal = function (content, options) {
   this.options = options
   this.$element = $(content)
   .delegate('[data-dismiss="modal"]', 'click.dismiss.modal', $.proxy(this.hide, this))
                                          ^^^^^^^^^^^^^^^^^^^^
                                        What does this mean?
}

I am quite fresh. I haven't seen this sort of syntax before. My guess is click event, on any attribute which contains a 'dismiss' and have value of 'modal'???
Answer: I think, what you are seeing is Namespaced Events. This is used extensively when you have multiple event handlers for a same event. See example below,
DEMO
$('#test').on('click.a', function () {
    alert('A is clicked');
});

$('#test').on('click.b', function () {
    alert('B is clicked');
});

$('#unbindA').on('click', function () {
    $('#test').off('click.a');
});

In the above example it just demonstrates unbind but it can also be used for triggering a specific handler like $('#test').trigger('click.a').
All the above is not possible when you just bind 'click' to both the handlers.
jQuery docs on Namespaced Events
Comment: So in `.on('click.a'` the `.a` part is a name you can just make up, **correct?** It doesn't refer to anything in the framework, but is just a way to uniquely name your handler so you can reference it later in trigger/off/etc. ?
Comment: @AaronLS Yes, that is correct. You can read about it http://api.jquery.com/on/#event-names
Answer: To add to Vega's answer:
Calling on() (available since jQuery 1.7) or delegate() with the event click.dismiss.modal means to register a click handler that is fired when the dismiss or the modal namespaces are passed in the triggered event, or if click is called with no namespace.
The modal is not "nested" under dismiss (the syntax may be misleading), but they are treated as directly "attached" to click. That means click.dismiss.modal is equivalent to click.modal.dismiss.
Example:
$('#elem').on('click.dismiss.modal', function () {});
$('#elem').trigger('click.dismiss');  // handler is called
$('#elem').trigger('click.modal');  // handler is called
$('#elem').trigger('click');  // handler is called
$('#elem').trigger('click.abc');  // handler is NOT called

Note that trigger(), unbind(), and off() only accept one namespace.
$('#elem').off('click.dismiss');  // now the handler is just 'click.modal'

You can also unbind using .dismiss which will remove all events with that namespace (not just click). Triggering won't work with a namespace by itself; there must be an event name before the dot.


Typescript: How to type combined reducers?

Question: I am migrating my small React Native project from pure Javascript to Typescript. While it went well so far, I now have problems with Redux.
The reducer I'm struggling with is radioButtonSelectedReducer. In the application, there are two radio buttons. If the first one is clicked, it gives string "itemOne" and if the second one is clicked, it gives string "itemTwo". Therefore, radioButtonSelected must be of type string, I thought. But it gives the error: radioButtonSelected: string; -->
"The expected type comes from property 'radioButtonSelected' which is declared here on type 'ReducersMapObject<IApplicationState, AnyAction>'"

I am such a Typescript newbie and don't know what to do with this message.
imports ...

export interface IApplicationState {
  radioButtonSelected: string;
  searchBarInput: string;
  searchBarResult: string;
}

const rootReducer = combineReducers<IApplicationState>({
  radioButtonSelected: radioButtonSelectedReducer,
  searchBarInput: searchBarInputReducer,
  searchBarResult: searchBarResultReducer,
});

export type RootState = ReturnType<typeof rootReducer>;

When I leave combineReducers() without <IApplicationState> and call RootState in mapStateToProps(), it gives the error:
  error TS2339: Property 'itemSelected' does not exist on type 'CombinedState<{ radioButtonSelected: { itemSele
cted: string; }; searchBarInput: { inputValue: any; }; searchBarResult: { returnValue: any; }; }>'.

Here is the snippet from the component that implements the radio buttons:
...

function mapStateToProps(state: RootState) {
  return {
    itemSelected: state.itemSelected,
  };
}

Answer: You shouldn't have to declare IApplicationState or pass it as a generic to combineReducers().  In fact, that's explicitly the point of type RootState = ReturnType<typeof rootReducer>.  It infers what the combined state type is, so you don't have to declare it or keep updating it.
Please refer to the Redux docs page on "Usage with TypeScript" for more details.
Comment: That's because you aren't passing a field named `itemSelected` to `combineReducers`.  Either there's another reducer you forgot to add to the root reducer, or you've mismatched the field names (ie, `state.itemSelected` should actually be `state.radioButtonSelected`).
Comment: Thanks for your reply. I tried exactly this in the first run, but when I call mapStateToProps in the component, it says:  error TS2339: Property 'itemSelected' does not exist on type 'CombinedState<{ radioButtonSelected: { itemSele
cted: string; }; searchBarInput: { inputValue: any; }; searchBarResult: { returnValue: any; }; }>'. Updated my question.


Quartz Scheduler for java- How to run job every 5 minutes

Question: Friends,
  I am using quartz scheduler for running a task every 5 minutes starting when application deployed & running continuously so i have written code as:
SchedulerFactory sf = new StdSchedulerFactory();
Scheduler sche = sf.getScheduler();

JobDetail job = newJob(RomeJob.class).withIdentity("Id1", "Rome").build();
CronTrigger trigger = newTrigger().withIdentity("Id1Trigger", "Rome").withSchedule(cronSchedule("0 0/5 * * * ?"))
.build();
sche.scheduleJob(job, trigger);
sche.start();

But its working sometime sometimes not. Please tell me whether i am missing something here?
Answer: Instead of
0 0/5 * * * ?

use
0 */5 * * * *

Edit: This results in your task being run at 0 seconds of every minute that is divisible by 5.
Edit 2: 0/5 means only the minutes 0 and 5.
Comment: In latest version of Quartz: ' 0 */5 * * * ? '
Comment: once i deploy my website on tomcat task should run continuously with interval of 5 minutes it should not stop until tomcat stop but with interval of 5 minutes
Comment: thanks for quick responce , but i want to run my task every 5 minutes continuously will you helo to figure out cron string for this
Comment: What do you mean by "every 5 minutes continuously"?
Comment: @user2171669 Not everyone is running the latest version.  Our shop uses the top format.
Answer: Do not use Cron schedule but simple schedule instead:
Trigger trigger = newTrigger().
  withIdentity("Id1Trigger", "Rome").
  withSchedule(
    simpleSchedule().
      withIntervalInMinutes(5).
      repeatForever()
  ).build();

Comment: +1 since the OP asked for "every 5 minutes starting when application deployed", not every 5 minutes on the wallclock.
Answer: You have many ways one of them is use trigger builder something like
trigger = newTrigger()
    .withIdentity("mytrigger", "group1")
    .startNow()
    .withSchedule(simpleSchedule()
            .withIntervalInMinutes(5)
            .repeatForever())
    .build();

Answer: Now updated to new version!
            /* Instantiate the job that will call the bot function */
            JobDetail jobSendNotification = JobBuilder.newJob(SendNotification.class)
                    .withIdentity("sendNotification")
                    .build();

            /* Define a trigger for the call */
            Trigger trigger = TriggerBuilder
                    .newTrigger()
                    .withIdentity("sendEvery5Minutes")
                    .withSchedule(
                            SimpleScheduleBuilder.repeatMinutelyForever(5))
                    .build();

            /* Create a scheduler to manage triggers */
            Scheduler scheduler = new StdSchedulerFactory().getScheduler();
            scheduler.getContext().put("bot", bot);
            scheduler.start();
            scheduler.scheduleJob(jobSendNotification, trigger);

Hope this will help someone find new the version. Send repeatMinute, repeatHourly


Is it possible to have a custom italic css property that is less slanted?

Question: I am following a design that contains a slanted text.
I used font-style:italic but the result is too much.
I am finding a way to make a custom css to have class that will make the text a little less slanted than the default italic property.
See images below: (left = design; right = html/css)

Is there a way? Is this possible to achieve (even using a different approach)?
Comment: You can try some italic font. Many font has many is less slanted the default one.
Answer: You can try with CSS3 skew() property like this :
See this fiddle
h1
{
text-transform: uppercase;
font-family: arial;
transform: skew(-13deg);
-webkit-transform: skew(-13deg);
}

Comment: In my case I have a long text, it has been skewing the whole height.


CodeIgniter REST API calling nonexistent method

Question: Using Phil Sturgeon's Codeigniter REST SERVER, I've set up a basic REST server to interact with a Backbone application. The issue is that whenever the applcation tries to make a DELETE request to the proper URI (for instance, api/object/7 where 7 is the ID number in question), REST returns a 404 Not Found error. A bit of digging revealed that it was trying to reach the nonexistint 7_delete within the controller instead of calling index_delete as it should.
I've checked the requests, and they're routing to the correct URL; I've also checked that there are no custom routes set up which would interfere and there are none. Suggestions?
EDIT: For more detail, the Backbone routing is set up like this:
urlRoot: 'api/objective/',

The Objective controller in CI meanwhile is set up like this:
class Objective extends REST_Controller {

  /**
   *  Respond to a POST request;
   *  - If given an ID, update an existing record
   *  - If given no ID, create a new record
   */
  public function index_post() {
    // code here...
  }

  /**
   *  Delete an existing record from a passed URL
   */
  public function index_delete($id) {
    // Code here...
  }

  /**
   *  Get a single record
   */
  public function index_get($id) {
    // Code here...
  }

  /**
   *  Get the full objectives list
   */
  public function index_get() {
    // Code here...
  }
}

This is close to the example provided in the original example file. The CI routing has nothing set up however.
Comment: Could you provide some detailed code?
Comment: @moberemk how you have setup your routing in CI & Backbone ?
Comment: I've added some detail to the above post to answer your questions.
Answer: maybe it easy when you use url like this http://example.com/api/objective/deletecontent/id/7
    public function deletecontent_get() {
        if(!$this->get('id')) {$this->response(null,400)}
          $run = $this->some_model->delete_content_by_id($this->get('id));
          if($run) $this->response(true,200);
          else $this->response(null,304);
    }

Comment: The problem with this is that it completely negates the point of using a REST API by not making use of stuff like the DELETE method instead of simple GET URLs. Good try though.


Can LogisticRegressionCV be used with StandardScaler?

Question: If we apply StandardScaler to transform the training data before we fit the LogisticRegressionCV model, I think it is incorrect because during cross validation the entire data has been used to scale the dataset. Thus knowledge of the test fold leaks into the training fold.
So is the solution using StandardScaler along with LogisticRegression in a pipeline and then using GridSearchCV to find the best parameter?
Comment: Yes, that prevents the leakage.
Comment: I think `LogisticRegressionCV ` is for people who doesn't even want to deal with CV code. Unfortunately, I've seen code in lots of places ignoring this leakage.
Comment: @gunes I was racking my head over how to implement scaling with `LogisticRegressionCV`, I guess it should be mentioned somewhere in the sklearn documentation so that people dont get confused
Comment: Note that the scores from the hyperparameter search shouldn't be treated as estimates of performance anyway, so the actual impact of the leakage is that perhaps somehow different levels of regularization get boosted test scores based on the leaked scale information.
Answer: Can LogisticRegressionCV be used with StandardScaler without data leakage?
No, it can't.

Can LogisticRegression be used with Cross Validation and StandardScaler without data leakage?
Yes. As it is stated in the LogisticRegressionCV documentation (as explained below), that LogisticRegressionCV is equivalent to LogisticRegression used inside GridSearchCV.
So instead of using LogisticRegressionCV we can use LogisticRegression + GridSearchCV, which works in exactly the same way and produces exactly the same results, but this new duo is more modifiable and allows us to introduce StandardScalar the right way.
Can you explain this workaround in more detail and provide an example?
Let's do it in three steps. First, investigate how LogisticRegressionCV is implemented by just using the documentation. Then, implement it ourselves. Finally, extend our implementation with the StandardScaler.
1. Investigation
First, let's figure out how LogisticRegressionCV is implemented. From the documentation

It mentions ("For the grid of Cs values and l1_ratios values") that a grid search is used, therefore we will use grid search as well, it's implemented as GridSearchCV().
For l1_ratios it says Only used if penalty='elasticnet'. The default value of penalty is penalty='l2', therefore l1_ratios is not optimized by default. Only Cs are searched.
Default value of Cs is Cs=10. The documentation says, If Cs is as an int, then a grid of Cs values are chosen in a logarithmic scale between 1e-4 and 1e4. We can implement this behavior with Cs = numpy.logspace(-4, 4, num=10)
We know that the best hyperparameter is selected by the cross-validator StratifiedKFold, but it's also used by default by the GridSearchCV, so we can ignore this.

2. Create an equivalent to LogisticRegressionCV
Let's say we have this Logistic Regression example:
from sklearn.datasets import make_classification
from sklearn.linear_model import LogisticRegressionCV

n = 100
X, y = make_classification(random_state=1, n_samples=n, n_features=5, n_informative=3, n_redundant=2)

model = LogisticRegressionCV()
model.fit(X, y)

print(f'Train set accuracy: {100 * sum(model.predict(X) == y) / n:.2f} %')
# Train set accuracy: 88.00 %

Putting our knowledge together, we can equivalently replace it with:
import numpy as np
from sklearn.datasets import make_classification
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import GridSearchCV

n = 100
X, y = make_classification(random_state=1, n_samples=n, n_features=5, n_informative=3, n_redundant=2)

lr = LogisticRegression()
param_grid = {'C': np.logspace(-4, 4, num=10)}
model = GridSearchCV(lr, param_grid)
model.fit(X, y)

print(f'Train set accuracy: {100 * sum(model.predict(X) == y) / n:.2f} %')
# Train set accuracy: 88.00 %

3. Extend with StandardScaler
We add the StandardScaler to the pipeline like this:
import numpy as np
from sklearn.datasets import make_classification
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import GridSearchCV
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import StandardScaler

n = 100
X, y = make_classification(random_state=1, n_samples=n, n_features=5, n_informative=3, n_redundant=2)

pipeline = Pipeline(steps=[
    ('scaler', StandardScaler()),
    ('lr', LogisticRegression())
])
param_grid = {'lr__C': np.logspace(-4, 4, num=10)}
model = GridSearchCV(pipeline, param_grid)
model.fit(X, y)

print(f'Train set accuracy: {100 * sum(model.predict(X) == y) / n:.2f} %')
# Train set accuracy: 88.00 %

That's it!
Comment: What's the reason for the downvote?
Comment: This answer is misleading: the Q asks "can I use pipeline" and the answer states "it is incorrect, you need to use pipeline instead".
Comment: @Tim Thanks for your reply. The answer has now been revisited. The Q asks "can I use X to achieve Y" and the answer now states "no, it's not possible with X, but it is possible with Z", where Z is a straightforward native solution closest to X. Let me know if further changes are needed.
Comment: It wasn't my -1, I' just saying that the answer is a little bit confusing. There is a lot of text and code but it is hard to gather what exactly is the main message there.


help on two tail test

Question: Use the data below on the enthusiasm for Obama to test the hypothesis that the means are equal for men and women.   Use .01 significance level and  a two tail test.
<code>       women   men
  mean  57     62
  var   64     81
   n    50     40
</code>
Comment: why 2 quick consective question on pretty much the same topic? it would help if you tell people what you have learnt or where you are stuck...
Comment: We haven't learned anything. Our teacher didn't teach us at all.
Comment: possible duplicate of [Two Tail Hypothesis test](http://math.stackexchange.com/questions/357639/two-tail-hypothesis-test)
Comment: @Micah: Thanks for letting me know its a duplicate. I didn't know how to do it.
Answer: this should be a $t$-test with unequal variance, the formula can be found her:
http://www.itl.nist.gov/div898/handbook/eda/section3/eda353.htm
As a side note: I am pretty sure the contigency table is what you should be using for the other one. Your question would receive more attention if you indicated a bit more what you tried or already know.
Comment: I haven't tried some of the problems because I have absolutely no idea how to do it. Stackexchange is literally my teacher right now. Also thank you soo very much for helping me.

help on two tail test