Performance of a bootstrap

Question: In the context of a simulation study, for a bootstrap methodology to estimate a parameter:
Should a lots of bootstrap (but each one have a few resamples) be favoured over doing few bootstrap (but each one have a lots of resamples)?
Answer: In general, each bootstrap resample consists of $N$ observations (sampled with replacement) from the original data set (which is also of size $N$). That is, each bootstrap resample has the same size as the original data set.
Regarding the number of bootstrap resamples to use, it will depend on the size of your original data set as well as what you are doing in each bootstrap iteration. These two things will dictate how fast each iteration is. You should find a good balance that gives you stable results and doesn't take too long to run. In my experience, anything above 500 bootstrap resamples tends to yield decent results, but it will ultimately depend on the characteristics of your data and objective. If your data isn't too big and you are not doing anything too computationally expensive in each iteration, using 10,000 bootstrap resamples seems to be the default for many people.

Performance of a bootstrap


Structure sheaf of $\operatorname{Spec} A$ with $A$ an integral domain

Question: Let $A$ be an integral domain, $K = \operatorname{Quot}(A)$ the field of fractions of $A$ and $X=\operatorname{Spec}(A) = \{p\subset A \mid \ p \ \text{prime ideal of }A \}$ the spectrum of $A$ with the Zariski topology.
For every $p\in X$ the localization $A_p$ is a subring of $K$.
We take $\mathcal{O}_X$ the structure sheaf of $X$; for every open subset $U\subset X$,
$\mathcal{O}_X(U)$ is the set of sections $s:U\rightarrow \bigsqcup_{p\in U}A_p $ such that $s(p)\in A_p$ for all $p\in U$ and locally a quotient of elements of $A$ (i.e. for each $p\in U$ there exists a neighborhood $V$ of $p$ contained in $U$ and elements $a,f\in A$ such that for each $q\in V$, $f\notin q$ and $s(q)=\frac{a}{f}\in A_q$)
We want to show that
$$
\mathcal O_X(U) = \bigcap_{p\in U}A_p \subset K
$$
My attempt
I found here a similar question, but there is not an answer. I think that the key point is the density of $\eta = (0)$ in $X$ thanks to the fact that $A$ is a domain.
I tried to show that a section $s\in \mathcal O_X(U)$ is not only locally a quotient of elements of $A$, but globally (on $U$) a quotient of elements of $A$. To do that, consider a neighborhood $V$ of $\eta$ and $a_1,f_1\in A$ such that for all $q\in V$, $s(q) = \frac{a_1}{f_1}$ and $f_1\notin q$ for all $q\in V$. Suppose that $V\neq U$. Hence there exists $p\in U \setminus V$ and a neighborhood $W$ of $p$ and $a_2,f_2\in A$ with the same properties as above.
Since $\eta$ is dense, $\eta\in W$ and we have $\frac{a_1}{f_1} = \frac{a_2}{f_2}$ in $A_\eta = K$. From here, I can find that $a_1\in p$, but I can't go any further if I don't add more hypothesis on $A$.
Could this be the right approach?
Thanks in advance
Comment: Please use `$\operatorname{Spec}$` to format $\operatorname{Spec}$ - this gives better spacing.
Answer: In an integral scheme, you can check that all restriction maps are injective. Thus, it follows that if $U \subset X$ is an open subset covered by the affine open subsets $V_i$, $\mathcal{O}(U) = \bigcap_i\mathcal{O}(V_i)$ (as subrings of $K$) by the sheaf property.
So it is enough to show the statement for affine open subsets $U$. In other words, we just need to show that if $A$ is an integral domain, $A = \bigcap_{\mathfrak{p} \in \operatorname{Spec}\,A}{A_{\mathfrak{p}}}$.
Of course, $\subset$ is obvious. Let's see the reverse inclusion. If $x \in \bigcap_{\mathfrak{p} \in \operatorname{Spec}\,A}{A_{\mathfrak{p}}}$, then there is an ideal $I \subset A$ such that $I = \{z \in A,\, zx \in A\}$. Since, for every $\mathfrak{p} \in \operatorname{Spec}\,A$, $x \in A_{\mathfrak{p}}$, $I \not\subset \mathfrak{p}$, and therefore $I$ is contained in no maximal ideal of $A$ so is $A$, and $x \in A$.
Comment: @User43029: $\mathcal{O}(V_i)$ is certainly not isomorphic to $A_{\mathfrak{p}}$. Why did you think it was?
Comment: Thank you very much!
Comment: Why $\mathcal{O}(V_i) \simeq A_{\mathfrak{p}}$?
Comment: Because of the phrase "So it is enough to show the statement for affine open subsets $U$. In other words, we just need to show that if $A$ is an integral domain, $A = \bigcap_{\mathfrak{p} \in \operatorname{Spec}\,A}{A_{\mathfrak{p}}}$." Is it not the case?
Comment: Not at all: in $\mathcal{O}(U)=\cap_i{\mathcal{O}(V_i)}$, $U$ is an arbitrary open subset and $V_i$ are affine. This is not the same situation as $A=\cap_{\mathfrak{p}}{A_{\mathfrak{p}}}$. The point of the first part is to prove that it's enough to consider $U$ affine in the problem statement; the goal of the second part is to solve the  problem when $U$ is affine – they're completely independent.
Comment: Thank you! I understand that on the left-hand side, one has $\mathcal{O}(Spec(A))=A$, but I can't understand why $\mathcal{O}$ in the open sets give us $A_{\mathfrak{p}}$.
Comment: Again, these two intersections are *unrelated*! The intersection $A=\cap_{\mathfrak{p}}{A_{\mathfrak{p}}}$ is the translation of the problem statement when $U$ is an affine open subset:


Even better support for HAML in Netbeans?

Question: This plugin is pretty good, definitely better than plain-text.. but I'm longing for a little more. Code completion, the Netbeans code generator shortcuts, 'ri' integration for looking up documentation like the .erb files have..
Does anyone have some tricks, is there a different plugin for this type of functionality in Netbeans?
Definitely would like SASS support for Netbeans as well!
Comment: The link is broken now, I have tried to search for the plugin to no avail. Do you have an updated link for this plugin?
Comment: I would also love to see even better Sass support in the mentioned plugin.
Comment: I'm in! We do need better SASS/HAML support in Netbeans
Answer: Here http://code.google.com/p/postcomment/downloads/detail?name=org-netbeans-modules-haml.nbm&can=2&q=
Answer: Everybody seems to be craving for proper Netbeans HAML/SASS support.
Let's motivate someone to code it :
http://www.donanza.com/jobs/p1413667-software_development_netbeans_haml_support_plugin
Comment: +1 for that, I would even say it would be nice if netbeans had a compass plugin as well.
Answer: I came across a problem in the HAML-plugin by Dylan Bruzenak (the one up on google) that it wouldn't recognize the new Ruby 1.9 hash syntax in HTML attributes.
So I did some hacking and modified the haml.nbs inside <nbm>/netbeans/modules/<org-netbeans-modules-haml.jar>/org/netbeans/modules/haml to support this.
Replace line 50 with
TOKEN:ruby_symbol:((':' [^ ' ' '=' '}' '"']+) | ([^ ':' '}' '"']+ ':'))

Comment: Thank you thank you thank you! I got it to work with NB 8
Answer: If you're talking about a new IDE:
RubyMine is popular, try that. http://www.jetbrains.com/ruby/index.html
Answer: You can find it here: http://code.google.com/p/postcomment/downloads/detail?name=org-netbeans-modules-haml.nbm&can=2.
Answer: The plugin is basic, but note that Oracle seem to be closing down the mediacast site where it is hosted. Has development/distribution been moved to another site? I am quite dependent on this plugin for haml work, and I would like to see a future for it.
Answer: There's an haml plugin that needs some teaks in order to change the default colors: How to change color of HAML tags in NetBeans?


How to trigger Drupal.attachBehaviors after successful Ajax

Question: I have a module that updates a node via ajax when a link is clicked.
The link is a toggle, it should update the node with value 1 on first click, then with value 0 on a subsequent click, etc. Like turning something on/off.
The code below works on the first click after page load, but not on subsequent clicks. I believe Drupal.attachBehaviors has to be called/triggered after each clicks, but I can't figure out how to do this.

The Module
function mymodule_menu() {
  $items['mypath/%/%/ajax'] = array(
  'title' => 'My title',
  'page callback' => 'mymodule_ajax_callback',
  'page arguments' => array(1,2),
  'access arguments' => array('access content'),
  'type' => MENU_CALLBACK,
  );

  ...
}

function mymodule_ajax_callback($id, $status) {
  //Validation[...]

  //Node Update using $id as the nid and $status as the field value[...]

  // Define a new array to hold our AJAX commands.
  $ajax_commands = array();

  // Create a new AJAX command that replaces the #div.
  $replacedivid = '#status'.$id;
  $replacestring = '
'.$status_text.'
';

  $ajax_commands[] = ajax_command_replace($replacedivid, $replacestring);

  return drupal_json_output($ajax_commands);
}

Javascript
(function ($) {
  Drupal.behaviors.mymodule = {
    attach: function(context, settings) {
      var $uilink = $('.midui'); //find all links

      for (var i=0;i<$uilink.length;i++) { //Loop
        var $link = $('#' + $uilink[i].id);
        if (!$link.hasClass("middone")) {

          new Drupal.ajax('#' + $uilink[i].id, $link, {
            url: $link.attr('data-url'),
            effect: 'fade',
            settings: {},
            progress: {
              type: 'throbber'
            },
            event: 'click tap'
          });

          $link.addClass("middone"); //add class when we're done

        }
      }
    }
  }
})(jQuery);

What I have tried so far:

(a)Add an ajax_command_invoke(NULL, 'mymodule'); to the $ajax_commands array coupled with a $.fn.mymodule function
(b)Add $('body').ajaxSuccess(Drupal.attachBehaviors); to my javascript. ajaxComplete tried as well. Tried it on the document as well.
(c)Create a custom command as detailed here http://www.jaypan.com/tutorial/calling-function-after-ajax-event-drupal-7
Note : I know that it's just a matter of triggering attachBehaviors after each click to 'ajaxify' the new html being inserted/modified. If I click the link and then type Drupal.attachBehaviors() in the console, the link will be processed again by my javascript, as evidenced by the addition of the 'middone' class, and can be clicked again.
Note: Also of interest, if I leave the $ajax_commands empty and return it (empty array) at the end of the callback function, the link will remain clickable on the first and subsequent clicks. It will have the functionality that I am looking for (a toggle). However, since no change is made to the html after each click, there is no way for the user to know if the toggle is on or off.
Any pointers would be greatly appreciated.
=======================================================
A partial Answer :
Drupal ajax.js success function only re-attaches behaviors for forms (I think ?)
    if (this.form) {
      var settings = this.settings || Drupal.settings;
      Drupal.attachBehaviors(this.form, settings);
    }

so I decided to hack all my ajax objects' success function.
The Javascript now becomes
    (function ($) {
      Drupal.behaviors.mymodule = {
        attach: function(context, settings) {
          var $uilink = $('.midui'); //find all links

          for (var i=0;i<$uilink.length;i++) { //Loop
            var $link = $('#' + $uilink[i].id);
            if (!$link.hasClass("middone")) {

              myAjax = new Drupal.ajax('#' + $uilink[i].id, $link, {
                url: $link.attr('data-url'),
                effect: 'fade',
                settings: {},
                progress: {
                  type: 'throbber'
                },
                event: 'click tap'
              });

              myAjax.options.success = function (response, status) {
                //Trigger Attach Behaviors
                setTimeout(function(){Drupal.attachBehaviors($(myAjax.selector))}, 0);
                // Sanity check for browser support (object expected).
                // When using iFrame uploads, responses must be returned as a string.
                if (typeof response == 'string') {
                  response = $.parseJSON(response);
                }

                return myAjax.success(response, status);
              }

              $link.addClass("middone"); //add class when we're done

            }
          }
        }
      }
    })(jQuery);

The success function is a copy paste of the default from ajax.js with an added line for reattaching behaviors.
For some reason, Drupal.attachBehaviors has to be within a timer. I can't just have it on its own for a reason that I ignore.
I'll leave this question open for few in case someone can either find a more elegant solution and/or explain the timer oddity.
Many thanks
Comment: Why would you want to attach behaviors again and again? they are automatically re-run on any new element created using AJAX, so why it's not enough?
Comment: behaviors are not automatically reattched in my case. thx
Comment: While slightly off topic, this is a good example of how to use a custom JS solution, while maintaining support for Drupal core ajax handling (e.g. commands).  For example, making an ajax call on page load (no UI trigger) that returns Drupal commands in the response.
Answer: It can be tricky attaching ajax behaviours to content that is returned from an ajax request itself. However, it is possible.
Although your hook_menu code snippet looks incomplete, assuming it's correct (returns $items and function is closed) - In your case, you may just need to adjust the delivery callback to 'ajax_deliver'
i.e:
/**
 * Implements hook_menu
 */
function mymodule_menu() {

  $items['mypath/%/%/ajax'] = array(
    'title' => 'My title',
    'page callback' => 'mymodule_ajax_callback',
    'page arguments' => array(1,2),
    'access arguments' => array('access content'),
    'delivery callback' => 'ajax_deliver',
    'theme callback' => 'ajax_base_page_theme',
    'type' => MENU_CALLBACK,
  );

  return $items;

}

Comment: Thanks for the suggestion but this does not work either. I use your code in hook_menu and behaviors are not re-attaching automatically.
Answer: After some debugging, I realized the issue was not with my code.
The problem was with another module, in my case the colorbox module, which was the source of a js error in its own behaviors function. I believe the error caused the attach behaviors process to halt, and as such, my own behaviors function was not re-attaching. The error could be seen in the console.
The colorbox error :
in 7.24
Uncaught TypeError: Cannot read property 'transition' of undefined colorbox_inline.js?

and
in 7.25
Uncaught TypeError: Cannot read property 'mobiledetect' of undefined

My solution was to disable the colorbox module.
Many thanks to everyone who helped.
Answer: I can't comment first answer, but you can set property for colorbox in settings. For example:
myAjax = new Drupal.ajax('#' + $uilink[i].id, $link, {
  url: $link.attr('data-url'),
  effect: 'fade',
  settings: {
    colorbox: {
      mobiledetect: false
    }
  },
  progress: {
    type: 'throbber'
  },
  event: 'click tap'
});


JavaScript window.scroll vs. window.scrollTo?

Question: Any idea what, if any, difference there is between window.scroll(x, y) and window.scrollTo(x, y) [not talking about jQuery]?
Also any ideas as to which browsers support which?
Thanks
Answer: There are no differences: https://developer.mozilla.org/en/DOM/window.scroll
As far as I know, all major browsers support both.
Comment: If they are the same, then why are there two different functions?
Comment: The authoritative answer is [here](https://drafts.csswg.org/cssom-view/#dom-window-scrollto): *When the scrollTo() method is invoked, the user agent must act as if the scroll() method was invoked with the same arguments.*
Comment: well, .scroll only went half way up the page, and .scrollTo worked, maybe it is chrome or iframe issue, anyways, bad, maybe use both .scroll and .scrollTo
Comment: Edge doesn't seem to like either scroll() or scrollTo(), at least on divs. You can still set the value of scrollTop though.
Comment: Actually, `scroll()` 'scrolls the window to a particular place in the document' and `scrollTo()` 'scrolls to a particular set of coordinates in the document' ;)
Comment: These are now in a draft specification: http://dev.w3.org/csswg/cssom-view/#widl-Window-scroll-void-long-x-long-y, they are all supported in the spec to maintain backwards compatibility
Comment: The Mozilla documentation seems to be wrong regarding the Options method of scroll() and scrollTo(). It says: "Top: Specifies the number of pixels along the Y axis to scroll the window or element.". And similarly for Left. This looks like a copy/paste from ScrollBy() error. I think it should be: "Top: Specifies the pixel along the horizontal axis that you want displayed in the upper left".
Answer: Window.scrollTo() is effectively the same as the window.scroll(x,y) method. For scrolling a particular distance, use Window.scrollBy().
Also see Window.scrollByLines(), Window.scrollByPages() and Element.scrollIntoView()
MDN - https://developer.mozilla.org/en-US/docs/Web/API/Window/scroll
Answer: In the absence of deprecation, I prefer window.scroll instead of window.scrollTo:

The specification only describes window.scrollTo by referring to window.scroll, suggesting that window.scroll is authoritative.
window.scroll has ~3M search results; window.scrollTo has ~0.5M.
Answer: There is scrollTo, scroll, and scrollBy! Apparently there is no standard covering this functionality so all Browsers may not implement it the same.
Comment: `scrollBy` is unlike the others in that it scrolls relative to the current position.
Comment: Ok, thanks - I did not know that and the MDC does not state it
Comment: These are now in a draft specification: http://dev.w3.org/csswg/cssom-view/#widl-Window-scroll-void-long-x-long-y, they are all supported in the spec to maintain backwards compatibility
Comment: Thanks, I was struggling with this and scrollBy was just what I needed!


Consonance vs Stability

Question: In the video below, the guitar teacher claims that

the m6 chord is more resolutive and stable than the m7 chord. What's tricky is that the m6 chord is more dissonant!! More dissonant but more stable, so you have to understand (and feel) that dissonance and stability are not necessarily correlated.

I can feel what he says, but that brings up two questions:
1. If not consonance, what actually makes a chord be stable?
2. What makes a chord feel "resolutive"?
Comment: Similar question here : https://music.stackexchange.com/questions/101465/can-a-chord-be-consonant-but-unstable/ - are the answers there useful?
Comment: Does this answer your question? [Can a chord be consonant, but unstable?](https://music.stackexchange.com/questions/101465/can-a-chord-be-consonant-but-unstable)
Comment: @topoReinstateMonica I understand from it that both term are sometimes not well defined, and that for "stability", we don't really have a way of predicting the stability of a chord, it really depends on the context and sensibility of the listener I guess ?
Comment: @topoReinstateMonica Yes it is helpful and relevant, however I'd like to hear more on it, if people have answers to my particular question. Thanks !
Comment: @021: Exactly, that's what I have tried to add in my answer.
Comment: @OwainEvans Not entirely, but it brings good hindsight, hindsight that are completed by some other answers in this question. (topo Reinstate Monocia already linked this question before)
Answer:
what makes a chord feel "resolutive" ?

It is our expectation of consonance and stability. The leading tones in a progression
are provoking the dissonance and evoking the tension for resolving.

if not consonance, what actually makes a chord be stable?

It's actually the consonance! But in Jazz a major 6 or maj 7 chord are considered as stable (at least as final chords).
In traditional western music the sixth ajouté was considered as a consonant chord like  the dominant V7 (even the latter has a great tension to resolve the tritone fa ti => to mi do.
So it depends of the function and the chord progression. As the V - I is dominant functionof the tonic this dominant chord so ti re wants to resolve to do mi so (g b d to c e g).
Even that both chords are major triads it is in functional listening and thinking logical to say: the triad of the dominant chord is less stable than the tonic.
While a tonic chord e.g. C maj7 is less stable than C6. The ear that isn't schooled listening to Jazz is expecting that the 6th will resolve to the 5th and the 7th to the octave. Now the tension of the 7th is greater than the 6th because of ti as lead tone and the minor second is more dissonant.
I hope you understand that there is a correlation between consonance and stability and that it is depending additional of our listening habits.
Edit:
My explanations above  are referring to major chords.
Your question is concerning minor chords with added 6th and 7.
In this case I'd leave the theoretical background of functional theory and dissonances, I can only refer to my own personal listening habits: as final chord I'd hear am6 as more stable than am7, as passing chords they are both similar unstable to me.
Comment: There seems to be a lot of difference between a set of notes ( a chord) standing alone, with its own components working with/against each other, and a chord as part of a sequence - particularly with reference to the following (expected) chord.
Comment: But in the case of the the `m6` vs `m7`, the `m6` feels way more dissonant that the `m7` because the `m6` features a tritone between `b3` and `6`, but the `m6` still feels more resolutive than the `m7`. In this situation, it seems that consonance does not mean stableness (or at least "resolutiveness").
Comment: I miss read m6 and m7, sorry. You're asking about  the difference of a minor chord with added 6th and added 7th.
Comment: Yes, Tim. In my first section I meant to write *in a progression*. Btw. I've read now topo's answer to the  earlier question (s. link). We agree.
Answer: If not consonance, what actually makes a chord be stable?
Tonal context as defining consonance and dissonance
Consonance does make a chord stable, but stability and instability are relative. A chord isn't so much stable or unstable as it is more stable or less stable. So, considering chords that all share the same root, and played individually (rather than as part of a progression), a major triad is highly stable, a diminished triad is highly unstable, and m6 is less stable that a major triad but more stable than m7, which is more stable than the diminished triad.
However, context matters. If you have a piece predominantly in C major, and you suddenly toss in a D major triad, that triad will sound far less stable than if the piece had been in D major or G major. The same holds true for any chord. The more alien it is from the primary (local) key area, the more unstable its sound.
Interval content as defining consonance and dissonance
One also must be careful is defining the "consonance" of a chord. Above I've discussed consonance within a given harmonic context. However, the video, contrary to my statement above, claims that m6 is more dissonant (and by my argument, therefore, less stable) than m7. This is also true.
A variation on my statements above: within the context of a minor key, the i6 chord (i.e., m6 built on the tonic pitch) is more stable than the i7 chord (i.e., m7 built on the tonic pitch). In the context of the key, i6 is more consonant than i7. This is the context of the chords as discussed in the video, but the video presenter is using a different context to define the consonance and dissonance of the chords.
Consider the chords in isolation, and look at the intervals present in the chords (in root position; dissonant intervals are in bold).

chord
intervals from root
... from 3rd
... from 5th

m6
m3 P5 M6
M3 A4
M2

m7
m3 P5 m7
M3 P5
m3

Notice that m6 has two dissonances — A4 and M2 — while m7 has only one — m7. Further, the A4 in the m6 chord is the "most dissonant" interval in either chord. So both in terms of number of dissonances as well as the level of dissonance, m6 is more dissonant than m7.
Chord function as defining consonance and dissonance
Finally, in the view of "music theory", the m6 chord is functionally in the same category as a minor triad — stable, though with an "extra" note that should be resolved. In jazz and pop, the need to resolve is removed, and the m6 is treated as actually equivalent to the minor triad).
By contrast, seventh chords are viewed as functionally distinct from triads — less stable, with a greater need to resolve. While jazz and pop again allow for seventh chords as consonances, in the case of the video under discussion, the presenter is taking the more "classical" view of things.
What makes a chord "resolutive"?
Stability; therefore, consonance — but "consonance" within the larger harmonic context, as opposed to "consonance" in terms of the specific intervals within the chord.
Answer: There might contention that sixth chords do not exist and are just a 1st inversion of a minor 7th chord. I was taught this way and it's taken years to accept the sixth chord as being legitimate! In common practice harmony (c. 1600–1900) a sixth chord does not exist, but in harmony after it does.
(There's also a sixth chord in common practice harmony which is different i.e. the 1st inversion of a chord [Wikipedia: Sixth chord explains further], that's not how I'll refer to a sixth chord from here forward.)
Sixth chords are root chords: they function as a root chord.
Minor 7th 1st inversion is not a root chord and are less stable than a root chord. Root chords are happy staying where they are (if their 5th is a perfect 5th) but can move; 1st inversion chords (or other inversions)  need somewhere to move to, to resolve.
Sixth chords are often I chords, so a chord progression with sixth chords on the I naturally grounds the sixth chord too, to being even more stable.
Your example, you have a minor sixth chord, as a root chord.
It occurs on:
i, ii, iv, -vi (enharmonically)
degrees of the melodic minor scale.
The corresponding half-diminshed chords (also called minor 7th flat 5) occur on:
+vi, vii, ii, vi (again enharmonically).
Diminished chords in general (and the half-diminished also) are very unstable and want to move. And in changing key, they are, maybe the most flexible in what chord they can move to (they have many options of chords that they can resolve to that sound good).
So I'd summarise that the half-diminished chord is more begging to move than the sixth chord which is quite happy where it is.

Consonance vs Stability


time-based temporary authentication

Question: Is anyone aware of a time-based rather than one-time login authentication module for Drupal?
We've discovered a problem where some email servers with advanced security tools will crawl through emails to verify the links in them. In so doing -- they invalidate the one-time login links, preventing some users from using them. Rather than verify on whether the link was clicked once, I want to invalidate it based on time. For example -- the link to login is valid for 1 hr from when it was generated.
Comment: This sounds like a security issue waiting to happen. I think your best bet is to figure out why the advanced security tools are doing this and work to comply with them by making sure your emails pass through unmolested.
Answer: In Drupal 7 you can do something like the following:
Set user_password_reset_timeout variable (i.e. in settings.php
i.e. in settings.php:
$conf['user_password_reset_timeout'] = '600000';

Then it will use this time after password generation link, when this much time elapsed the link will be invalidated.
You can follow the thread here

time-based temporary authentication


Does it make sense to restrict the number of observations for logistic regression?

Question: This is a theoretical question.
Lets assume I have performed a ordinal logistic regression on a large dataset.
my model:
y~x1+x2+x3

where y is an ordered factor with four levels,
x1is a binomial variable (0 or 1)
x2is a continous variable
x3is a binomial variable (0 or 1)

I got some OR let's say 1.5 for x1;1and 1.5 for x2 as well as x3;1.
I understand that the odds ratios are for a change in one variable, haveing other held constant.
So my question is:
If I restrict my observations to subjects who only had a certain x2 and had '1' in their x3 variable and run the regression with the same model --- would I expect to see a significant change in my x1 odds ratio?
If so would it be increasing or lowering the OR of that variable?
Is it even allowed to restrict the number of observations in such matter or would someone hang me for this?
Comment: How are we to judge what an unspecified reviewer with an unspecified background in statistics for an unspecified journal with unspecified editorial policies in an unspecified subject area might do? For example, a reviewer for the journal [*Basic and Applied Social Psychology*](http://stats.stackexchange.com/questions/139290/a-psychology-journal-banned-p-values-and-confidence-intervals-is-it-indeed-wise) might have a very different reaction to one for *Variance*.
Comment: How are we to judge what an unspecified "someone" might do?
Comment: If the final question isn't to the point, why not remove it?
Comment: You are right. Put an journal Peer Reviewer under the executioners hood for illustrational purposes.
Comment: I think you are missing the point. The point is IF the odds are expected to change
Comment: This is pointless...
Comment: Do you require an answer to "Is it even allowed to restrict the number of observations in such matter or would someone hang me for this?" or not? If you do, your question has problems that need to be addressed (well there are some issues with the rest of it, but that has the biggest issue). I'd like this to be an answerable question.
Answer: Why do you want to do this?  If you have a good reason, there should be no problem. A better question (until you tell us your reason) is what can be achieved by doing this?  Let us look at this in a simpler model (the issues will be the same for your more complicated model).
Let the response y be binomial, with two predictors, x1 is continuous and x2 is 0/1, that is, binomial. What happens if you estimate two models, one for the subset of data with x2=0, another for the subset with x2=1?
Lets suppose that  the model for the complete data is
$$
 \text{logit}(p) = \beta_0 + \beta_1 x_1 + \beta_2 x_2 + \beta_{12} x_1 x_2
$$
where the last term represents an interaction between x1 and x2   (in this model, in more concrete terms, this means that the slope of the continuous predictor x1 is different for the two groups coded by x2).  Now, for the subsetted data, it will not be possible to estimate $\beta_2$ and $\beta_{12}$, so we will get two models
$$
   \text{logit}(p^0) = \beta_0^0 + \beta_1^0 x_1
$$
and
$$
   \text{logit}(p^1) = \beta_0^1 + \beta_1^1 x_1
$$
where the superindex (0 or 1) indicates the subset used (x2=0, x2=1).
Comparing the models we can see that (first using subset x2=0) that
$$
   \text{logit}(p^0) = \beta_0 + \beta_1 x_1 \equiv \beta_0^0 + \beta_1^0 x_1
$$
and then subset with x2=1:
$$
   \text{logit}(p^1) = \beta_0 + \beta_1 x_1 + \beta_2 + \beta_{12} x_1 \equiv \beta_0^1 + \beta_1^1 x_1
$$
From this we see (assuming the full model is the true model) that
(from x2=0): $ \beta_0 = \beta_0^0 ; \beta_1 = \beta_1^0$ and from x2=1:
$ \beta_0+\beta_2 = \beta_0^1 ; \beta_1 + \beta_{12}= \beta_1^1$.
So from the two, separate subsetted models you can approximate $\beta_{12}=\beta_1^1 - \beta_1^0$ and the effect of x2, $\beta_2$ by
$ \beta_2 = \beta_0^1 - \beta_0^0$.  In more prectical terms, this says that the interaction can be recovered as the difference in slope between the two subsetted models, and the effect of x2 by the difference in intercept between the two subsetted models. You could develop similar relations for your more complex model, by similar arguments.
So you can recover all the information from the two subsetted models, if this can be done in an statistically efficient manner is another question!


Complex numbers with fractions

Question: So I need to hold something like this:
complex(fractions.Fraction(1, 3), fractions.Fraction(1, 3))

but python is changing fraction to floating point, and since I don't want to use floating point and stay with fractions is there any other implementation of complex numbers that can do what I want? or maybe there is a possibile way to do a small change to current implementation?
Comment: Possible starting point: https://github.com/gladstonedigital/mathvis/blob/master/mathvis/cfractions.py
Comment: @Nullman doing that would most likely break all methods defined for `complex` (or, at the very least, implicitly convert the stored values to floats before doing calculations)
Comment: you probably can subclass complex and replace the types with fractions
Comment: i wast checking this code above before while googling the problem, and it's slightly different, these are fractions that can hold coplex numbers, could you pelase elaborate the subclass part? I am kinda new to python
Comment: oh so it's not possible, ths subclass solution, does numpy or something else have different implementation of complex numbers?
Comment: @apologiessirnoclue "Implementation of complex numbers (a+b*j) where the real and imaginary components are represented as Fraction instances", how is that different from what you'd like to have? I'm not sure I understand
Comment: okay, I think I was wrong it might work, thank you
Answer: You could just use sympy.
from sympy import sympify, I, re, im, expand

z = sympify(1)/3+I/3

Notice that I had to use sympify(1) since otherwise 1/3 would evaluate to a float rather than a sympy expression. Now you can do calculations with complex numbers like so
re(z) -> 1/3

im(z) -> 1/3

z*z= -> (1/3+i/3)**2

expand(z*z) -> (2*i)/9

Comment: I'd say "You SHOULD use Sympy" …
Comment: Or `z = (1 + I) / 3` without `sympify`
Comment: @stef yea that works too but has the disadvantage that it does not explicitly show how to resolve the 1/3 problem in general.

Complex numbers with fractions


Launching Netflix iOS App from another iOS App

Question: I've found around the web you can use the nflx:// url scheme to launch the Netflix app. Has anyone worked out the params to actually land it on a specific movie or search?
Answer: From this thread:

Looks like Netflix does this already. Example URL:
nflx://www.netflix.com/WiPlayer?shopperId=G-510cf375-e838-41c3-b3bd-1ab5ae98b667-1&movieid=1179468&trkid=1462433&episodeid=0&returnUrl=http%3A%2F%2Fwww.netflix.com%2FWiPlayer%3Fmovieid%3D1179468%26trkid%3D1462433%26pbc%3Dtrue
nlfx:// anything opens up the netflix app. Not sure where the
  shopperId comes from. I replaced whatever netflix used with a new UUID
  using uuidgen.
In my case I simply tried using a nflx:// URL and using the movieid
  parameter - this did not work correctly.

But also, more importantly:

At this point, we aren't officially supporting any external launch points into the Netflix iPad application. If you suss them out yourselves and use them, the danger is that they may eventually go away.
Comment: Yep thanks, that's the page I referred too in my post. I need to search etc
Comment: Maybe you didn't understand the point of those answers: there is no publicly documented way to do this, and if you manage to find something it will probably break later. (This is why you're not allowed to use private APIs on the App Store.) Reach out to the Netflix folks to request this, or use their other APIs, but don't hack around with private stuff.


Need to convert datetime to date during D8 migration from non-drupal source

Question: I'm working on a migration where I have
2012-05-07 00:00:00.000000
in my timedate field, but I need to convert it to:
2012-05-07
I realize that I should put this in the prepareRow function, but I'm not sure what it should look like.
Answer: public function prepareRow(Row $row) {

   $date = $row->getSourceProperty('database_date_field');
   $date = strtotime($date); // -> 1336341600 unix timestamp
   $date = date('Y-m-d', $date); // -> "2012-05-07"

   // Here you 'rewrite' the field with the new value before it gets saved
   $row->setSourceProperty('database_date_field', $date);
   return parent::prepareRow($row);
}

Answer: Why not use a format_date process plugin:
process:
  field_my_date:
    plugin: format_date
    from_format: 'Y-m-d H:i:s'
    to_format: 'Y-m-d'

Answer: If the source property containing that value is, say, "timestamp", then in prepareRow you can do:
$row->setSourceProperty('timestamp', strtok($row->getSourceProperty('timestamp'), ' '));


Need help java to C++ ssl sockets

Question: Hello SSL socket Wizards,
I am trying to implement a SSL socket between a java server and an application in C++. I am looking for help in resolving the below issue wherein C++ server closes connection after first interaction.
Flow is something like this: In a single ssl connection, send request1 from Java server-->receive success from C++ application-->send request2 from java server-->receive final response from C++ server
what's working:

initial handshake
sending request1 from java server
receive success from C++ server

where is the failure: sending request2 from the java server
What is the exception: Not sure but the connection is being closed by C++ server. Here is the exception snapshot in the java server.
java.net.SocketException: Connection closed by remote host
    at sun.security.ssl.SSLSocketImpl.checkWrite(SSLSocketImpl.java:1490)
    at sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1335)
    at sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1323)

JAVA_OPTS during start up:
-Djavax.net.ssl.trustStore=/usr/java/jdk1.7.0_25/jre/lib/security/cacerts
-Djavax.net.ssl.trustStorePassword=<store Password>
-Dhttps.protocols=SSLv3
-Dcom.sun.net.ssl.rsaPreMasterSecretFix=true
-Dcom.sun.net.ssl.enableECC=false
-Djsse.enableSNIExtension=false -Djavax.net.debug=all

Here is my java code for the ssl connection
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.SocketException;

import javax.net.ssl.SSLSession;
import javax.net.ssl.SSLSocket;

try {
    SSLSocket socket= (SSLSocket) SSLSocketFactory.getDefault().createSocket(hostname, port)
    DataOutputStream outStream = new DataOutputStream(socket.getOutputStream());
    outStream.write(request1.bytes, 0, request.length);
    DataInputStream in = new DataInputStream(socket.getInputStream());
    response = new byte[1024];
    int bytesRead;

    while ((bytesRead = in.read(response)) > 0) {
    // do nothing
    }

    if (response == success) {
        // trying to re-negotiate the connection
        socket.startHandshake();
        outStream.write(request2);
        response = new byte[1024];
        int bytesRead;

        while ((bytesRead = in.read(final_response)) > 0) {
        // do nothing
        }
    }
} catch (exception e) {
  //Handle exception
}

C++ server protocol detais:
Protocol  : SSLv3
Cipher    : AES256-SHA
Secure Renegotiation IS supported
Compression: NONE
Expansion: NONE

C++ code
int MyClass::show(SSL* ssl)
{   X509 *cert;
    char *line;
    if(ssl == NULL)
    {
        cerr << "Invalid input " << endl ;
        return -1 ;
    }

    cert = SSL_get_peer_certificate(ssl);       /* Get certificates (if available) */
    if ( cert != NULL )
    {
        cerr << "Server certificates:" << endl ;
        line = X509_NAME_oneline(X509_get_subject_name(cert), 0, 0);
        if(line != NULL)
        {
    cerr << "Subject : " <<  line << endl ;
    free(line);
    line = NULL ;
        }
        line = X509_NAME_oneline(X509_get_issuer_name(cert), 0, 0);
        if(line != NULL)
        {
    cerr << "Issuer : " << line << endl ;
    free(line);
    line = NULL ;
        }
        X509_free(cert);
    }
    else
    {
        cerr << "No Certificate" << endl ;
    }
    return 0 ;
}

SSL *MyClass::setupSession(SSL_CTX *ctx, int fd, int inc)
{
    if(fd == -1 || ctx == NULL)
    {
        cerr << "Invalid argument " << endl ;
        return NULL ;
    }
    SSL *ssl = SSL_new(ctx) ;
    if(ssl == NULL)
    {
        cerr << "Unable to create session! SSL_new() - failed!" << endl ;
        return NULL ;
    }
    SSL_set_fd(ssl, fd) ;
    show(ssl) ;
    if(SSL_accept(ssl) == -1)
    {
        cerr << "Accept Failed!" << endl ;
        SSL_shutdown(ssl) ;
        SSL_free(ssl) ;
        return NULL ;
    }
    return ssl ;

}

SSL *MyClass::handleConnection(SSL_CTX *ctx, int fd,int inc)
{

    memset(request1 buffer);
    memset(request2 buffer);
    SSL *ssl = setupSession(ctx, fd, inc) ;
    if(ssl == NULL)
    {
        cerr << "Unable to establish session" << endl ;
        uclose(fd) ;
        SSL_CTX_free(ctx) ;
        return -1 ;
    }

    if( uisreadable(fd, 5000) > 0 && (readb = SSL_read(ssl, message, 200)) > 0)
    {
        cerr << "Read : " << readb << " Bytes" << endl ;
        ss << message;
        request1Size = readb ;
        cerr << "request1:: " << message << endl ;
    } else {
        memset(buf,0x00,sizeof(buf)) ;
        SSL_write(ssl, failure, strlen(failure)) ;
        SSL_shutdown(ssl) ;
        SSL_free(ssl) ;
        uclose(fd) ;
        exit(EXIT_SUCCESS) ;
    }
    cerr << "Writing : response" << success << endl ;
    nbytes =    SSL_write(ssl, success, strlen(success)) ;
    cerr << "Wrote " << nbytes << endl ;
    if(nbytes <= 0)
    {
        ERR_print_errors_fp(stderr) ;
        SSL_shutdown(ssl) ;
        SSL_free(ssl) ;
        uclose(fd) ;
        exit(EXIT_SUCCESS) ;
    }
    util::hex2byte(message, request1, request1Size) ;
    util::hexprint(request1,request1Size) ;
    int total = 0 ;
    while( total <= request2_max_size && uisreadable(fd, 2000) > 0 && (readb = SSL_read(ssl, buf, sizeof(buf))) > 0)
    {
        cerr << "Read : " << readb << " Bytes" << endl ;
        memcpy(request2+total, buf, readb) ;
        total += readb ;
    }

    ....
    do some processing
    ....
    nbytes = SSL_write(ssl, final_response, final_response_size) ;
    cerr << "Generated Size: " << final_response_size << endl;
    cerr << "Write Size: " << nbytes << endl ;

    if(nbytes <= 0)
    {
        ERR_print_errors_fp(stderr) ;
    }
    SSL_shutdown(ssl) ;
    SSL_free(ssl) ;
    uclose(fd) ;
    exit(EXIT_SUCCESS) ;
}

// utility functions
int uisreadable(int fd, int ms)
{
    USOCK_VERIFY(fd,-1) ;
    fd_set recvfds ;
    FD_ZERO(&recvfds) ;
    FD_SET(fd, &recvfds) ;
    struct timeval to = { ms/1000, 1000000 * ((int)ms%1000) } ;
    int ret = select(1+fd, &recvfds,0,0,(ms > 0 ? &to : NULL) ) ;
    return ret ;
}
int uiswritable(int fd, int ms)
{
    USOCK_VERIFY(fd,-1) ;
    fd_set wrfds ;
    FD_ZERO(&wrfds) ;
    FD_SET(fd, &wrfds) ;
    struct timeval to = { ms/1000, 1000000 * ((int)ms%1000) } ;
    return select(1+fd, 0,&wrfds,0,(ms > 0 ? &to : NULL) ) ;
}

Comment: Caught with some thing urgent. Added the C++ code Ray. -ve points was harsh :(
Comment: The down vote was not mine :l
Answer: OK, I solved this problem by re-writing everything in JNI with a single method call and loading the C server business logic as a library.
This way I could reduce lot of overhead and it is much faster now and hassle free.

Need help java to C++ ssl sockets


Is it permissible to wear caps while playing football?

Question: I couldn't see any football players wearing caps while playing international matches, but I could see some of them wearing large headbands.
What's the rules for Football say about this?
If the football players are not allowed to wear cap means, what is the reason for allowing large head-bands but not head caps?
Comment: +1 a good question but i think goalkeeper is an exception as he is allowed to wear a cap
Comment: Example: Inter's Chivu (an outfield player) typically plays with a medical helmet/skull cap https://www.google.se/search?q=chivu&safe=off&source=lnms&tbm=isch&sa=X&ei=4qscUpWhGIaYtAbK4oH4Bw&ved=0CAkQ_AUoAQ&biw=1345&bih=1047.
Answer: As per FIFA's "Equipment Regulations", Section 22, only the goalkeeper is permitted to wear a cap.

22.1 All goalkeepers may, irrespective of the prevailing conditions, wear a
  goalkeeper cap of any Colour. The goalkeeper cap must be produced by the
  Manufacturer of a Playing Equipment item. The goalkeepers of the same team
  may wear different goalkeeper caps.

The rule regarding caps was brought in to afford goalkeepers better visibility in sunny conditions, with the cap shading the eyes from the glare of the sun.  The rule includes the line "irrespective of the prevailing conditions" so that goalkeepers can also where a cap even if there is no sun.  Some goalkeepers will wear a cap in the rain so that their vision is not impaired by rainwater in their eyes.
Regarding headbands (and wristbands), section 24 states:

24.2 The Players may wear a headband or wristbands. Neither the name, or
  any abbreviation thereof, nor the number of a Player may be displayed on a
  headband or wristband.

Headbands and wristbands reduce the problem of sweat and rain and remain a personal choice as to whether the player wears them.
Answer: On p. 90 of the document @Ste linked to, we read

2.3 Goalkeeper cap and further caps [My emphasis.]

This seems to indicate that caps may be worn by other players as well.
Law 4 stipulates

A player may use equipment other than the basic equipment provided that its
  sole purpose is to protect him physically and it poses no danger to him or any
  other player. [My emphasis.]

and

Modern protective equipment such as headgear, facemasks and knee and
  arm protectors made of soft, lightweight padded material are not considered
  dangerous and are therefore permitted.

My interpretation would be that a non-goalkeeper is allowed to wear a hat or cap, but that such a hat may not be peaked, because that would serve a purpose beyond protection.
Comment: @Ste Apparently FIFA has approved patkas, keskis and turbans, but whether they have ruled on beanies, I don't know.
Comment: I'd like to see 20 outfield players in chefs' hats!
Comment: I actually interpret that to mean "goalkeeper caps and caps worn by non-playing staff", as there are no explicit provisions for caps for outfield players.  Any headwear worn by outfield players will need FIFA approval.  Obviously interpretation could mean that I am wrong too!
Answer: Although headgear is allowed to be worn, it is not advised for anyone other than the goalkeeper. This could be because:

The beak of the cap is hard, a player going for a header could end up hurting the opposing player with it, thus making it dangerous to another player and becoming an infringement of Law 4 of FIFA guidelines.
Beanies could end up falling off a player's head and since nothing other than the football should be allowed on the field of play, play might have to be stopped till the beanie is picked up and placed back over the player's head. The law states that the game may not be stopped in case of an infringement. But I have seen referees stop games so that a player can put back his shoe, this would mean that the referee has the last call on such cases.
Comment: This question is thoroughly answered in Law Four; this answer only adds confusion. Who is 'advising'? Hard brimmed caps are not allowed for field players. Beanies and other soft, no-protruding headgear, is allowed for field players.
Answer: Goalkeepers can wear caps. Field players can wear beanies. I often wear a cycling-style cap with a small brim to help when I'm looking into the sun playing keeper.
Lev Yashin, who is kind of the Russian goalkeeper version of Pele, often wore a hat:

He often played wearing a cloth cap of burnt-brick colour.

From The Laws of the Game, Law 4:

Other equipment

Non-dangerous protective equipment, for example headgear, facemasks
and knee and arm protectors made of soft, lightweight padded material
is permitted as are goalkeepers' caps and sports spectacles.
Head Covers
Where head covers (excluding goalkeepers' caps) are worn, they must:

be black or the same main colour as the shirt (provided that the players of the same team wear the same colour)
be in keeping with the professional appearance of the player's equipment
not be attached to the shirt
not be dangerous to the player wearing it or any other player (e.g. opening/closing mechanism around neck)
not have any part(s) extending out from the surface (protruding elements)
Comment: @user67275 It was mentioned in the linked Wikipedia article, but buried quite deep. I've edited the relevant quote into the answer.
Comment: Do you have any supporting information about Yashin wearing a hat? I'm not saying that you are wrong. But if there is, it would be more helpful.
Comment: @user67275 there are many pictures and even a few statues of him wearing his signature cap, it's kind of his 'thing', like how Petr Cech became associated with his soft keeper helmet after his skull injury.


How to add a result count in exposed filters?

Question: For theming purposes, I need to display the views results in the exposed form.  Right now, through the UI, it's easy to add "Global: Result summary" to the views header, section.  But how would one display it within the exposed form?
Answer: There's no use trying to use hook_form_alter, as you need to wait until the view is rendered.  You can do this in hook_preprocess_views_view__VIEWNAME like this:
<code>function examplemodule_preprocess_views_view__exampleview(&$variables) {
  $result = $variables['header']['result'];
  unset($variables['header']['result']);
  $variables['exposed']['result'] = $result;
}
</code>


Recuperar arquivo .gz corrompido

Question: tenho um arquivo em .gz que está corrompido.
Existe a possibilidade de extrair os dados desse arquivo? Mesmo que seja parcialmente?
Esse arquivo é um dump de banco de dados sql.
Valeu.
Answer: Sim, é possível tentar recuperar um arquivo .gz, mas espere ter grandes perdas de dados do meio dele.
Primeiro, faça uma cópia do arquivo e trabalhe só com a cópia.
Faça um
<code>gunzip  < arquivo_com_erro.gz > arquivo_saida
</code>
E o seu arquivo saida terá tudo que foi possível recuperar até a primeira falha.
Para recuperar o que está depois da falha, um método é compilando o programa gzip com algumas linhas a mais de código. Para isto, sugiro seguir o recomendado em http://www.gzip.org/recover.txt (em ingles, e já adianto que levará tempo e não será fácil)
Outra solução: consulte as ferramentas disponíveis em http://www.urbanophile.com/arenn/coding/gzrt/gzrt.html
Comment: Isso funcionou e eu consegui abrir o arquivo ".sql" que estava dentro dele.
Apareceram vários caracteres desconhecidos (que eu acredito ser da parte corrompida).
Vou fazer o up da base agora (que tem mais 1,4GB) e ver no que dá.
Obrigado pela ajuda.

Recuperar arquivo .gz corrompido


Date picker and select2 not initialize in w2ui grid on invisible column

Question: I have dynamic columns in w2grid column, In such column we have add date picker and select2. Date picker and select2  initialize in visible column but not initialize when horizontal scrolling. And when i horizontal scrolling to last column my all initialize datepicker and selct2 not working and they are not working.
Please help me.
https://i.stack.imgur.com/hBye7.png
Comment: I have found issue, it's due to scrolling. When grid records scroll then grid refresh. So how can i reinitialize select2 and date picker on frid refresh?
Answer:

Check every second either it is initialize or not.


Merge document word in order that i want with spire.doc

Question: i'm trying to merge multiple word document into one document using spire.doc, but I would like the order to be my choice.
Document doc = new Document();

//document1
doc.LoadFromFile(sourcefile1, FileFormat.Docx);
doc.InsertTextFromFile(@"C:\document.docx", FileFormat.Docx);
doc.SaveToFile(@"C:\document.docx", FileFormat.Docx);

//document2
doc.LoadFromFile(sourcefile2, FileFormat.Docx);
doc.InsertTextFromFile(@"C:\document.docx", FileFormat.Docx);
doc.SaveToFile(@"C:\document.docx", FileFormat.Docx);

//document 3
doc.LoadFromFile(sourcefile3, FileFormat.Docx);
doc.InsertTextFromFile(@"C:\document.docx", FileFormat.Docx);
doc.SaveToFile(@"C:\document.docx", FileFormat.Docx);

For example I would like document1 to be on the front page but currently it is put on the last page.
Thank you all
Answer: You can use the following code to achieve your requirement:
Document doc = new Document();
doc.LoadFromFile("file1.docx");

string[] files = new string[] {"file2.docx", "file3.docx" };

//Insert contents from multiple files into file1.docx
foreach (string file in files)
{
    doc.InsertTextFromFile(file, FileFormat.Docx);
}

//Save the result file
doc.SaveToFile("merge.docx", FileFormat.Docx);


Android: How to detect when a user stops talking into the microphone

Question: I have an Android application that begins recording from the microphone when the application starts. In my current version, the user must press a STOP button to stop recording.
How do I detect that the user has stopped talking and use that to trigger the recorder to stop?
Similar to what is implemented in the Speech Recognition functionality in Android. The user stops talking and then the speech is translated. I have seen other apps that do it, like Talking Tom type apps.
As a side note I would also love to show some type of visual indicating that the microphone is receiving sound. Something to show the sound level coming in.
Any help appreciated.
Comment: https://stackoverflow.com/a/55793671/7476938 - will help you
Answer: An approach is to use threads on recording and the speech power analyzing process on the recorded bytes,
there's a sample code for your reference: http://musicg.googlecode.com/files/musicg_android_demo.zip
Answer: What are you using to record audio? This may provide some clues:
android.media.MediaRecorder:

the constant MEDIA_RECORDER_INFO_MAX_DURATION_REACHED can be used with an onInfoListener.

android.speech.SpeechRecognizer:

attach a RecognitionListener and call onEndofSpeech().
Comment: I am using MediaRecorder to record. And I can't use SpeechRecognizer because I need to save the audio file. I can't find a way to save to audio from SpeechRecognizer and I can't connect both the MediaRecorder and the SpeechRecognizer to the mic at the same time.

I will check out MEDIA_RECORDER_INFO_MAX_DURATION_REACHED
Comment: it looks as though others want to also recognize speech from an saved audio file: http://stackoverflow.com/questions/2319735/voice-recognition-on-android-with-recorded-sound-clip

If you don't need the same voice you could convert the response of speechrecognizer and then record the TextToSpeech output of the text. Although these seems needlessly complicated and probably very prone to transcription errors.
Comment: I saw that thread too. Actually, I want the opposite. I want to use Google's STT engine and get the text transcription back but also save the audio that the user spoke. Well, not the opposite but a different order. Can't do it though.
Comment: what's your final conclusion?
Comment: did you get any solution to this problem, i am also looking into it.
Comment: You cant use recognizer and recorder together; because you have only one microphone. Microphone must be used only one listener in one time


Switching a boolean variable (applied)

Question: I am trying to make a game (tacky, I know) and given the fact that I am not all that good with javascript/jquery I've managed to become stuck with switching a boolean variable. I tried the whole var = !var (no idea what that means) but some speculated it only works in objective C (again, no idea). I have made a JS fiddle http://jsfiddle.net/clarinetking/mLG6c/1/ and it works at the moment but I want to add a variable to all my objects called 'equip' and have it start out as false and be switched to true whenever the correct button is pressed.
var sword = {
nam:'Sword',
atk:5,
def:1,
spd:-1,
type:'LeftH',
//equip = false
};

etc
switch ( $(this).attr('id') ) {
        case 'equipsword':
            atk += sword.atk;
            def += sword.def;
            spd += sword.spd;
            //insert equip switch here
            break;

Comment: yes `!` works in javascript not just C, the `!`, is the NOT operator, it basically takes the opposite of whatever it is in front of, so `!true === false`, `!false === true`, this also goes for truthy/falsy values, `!null === true`, `!0 === true`, `!15 === false`, `!"" === true`
Comment: That's brilliant! I've tried it and it didn't work though so hopefully someone will come along and use it practically so I can see how much of an idiot I've been
Comment: All you really want to do is set sword.equip to true, right? I don't think you really need `!` here. If you wanted clicking sword to toggle it equipped or not equipped, you'll need to do more than just toggle the equip value.
Answer: yes ! works in javascript not just C, the !, is the NOT operator, it basically takes the opposite of whatever it is in front of, so:
!true === false
!false === true

this also goes for truthy/falsy values:
!null === true
!0 === true
!15 === false
!"" === true

So to toggle a boolean value just use the following:
var sword = {
   nam:'Sword',
   atk:5,
   def:1,
   spd:-1,
   type:'LeftH',
   equip:false
};
switch ( $(this).attr('id') ) {
    case 'equipsword':
        atk += sword.atk;
        def += sword.def;
        spd += sword.spd;
        sword.equip = !sword.equip;
        break;

but since case 'equipsword' from the looks of it will only be triggered when equipping and not unequipping might as well just do sword.equip = true;, especially since there might be a chance that some other code might change the value of equip, and then the toggle would not work as expected for instance if the following code ran before the equipsword case was triggered:
function someFunctionThatGetsCalled(){
   sword.equip = true;
}

it would cause equip to be true and then when the equipsword case is triggered sword.equip would then become false because its using the !sword.equip toggle.
Answer: You'll need to do more than just !bool here, you'll want to reverse the stat changes too. For example:
        if (sword.equip) {
            atk -= sword.atk;
            def -= sword.def;
            spd -= sword.spd;
        }
        else {
            atk += sword.atk;
            def += sword.def;
            spd += sword.spd;
        }
        sword.equip = !sword.equip;

http://jsfiddle.net/mLG6c/2/
Note, you should likely refactor this code so that you don't need the switch statement, since the action you are performing for each piece of equipment is identical.

Switching a boolean variable (applied)


Index 5 out of bounds for length 5 when trying to add an element to an array of objects

Question: public static Groceries [] addGrocery(Groceries[] arr, String name, int price) {
        int arrayLength = Array.getLength(arr);
        System.out.println(arrayLength);
        Groceries[] newGrocery = new Groceries[arrayLength + 1];
        int arrayLength2 = Array.getLength(newGrocery);
        System.out.println(arrayLength2);
        int i;
        for(i = 0; i < arrayLength; i++) {
            newGrocery[i] = arr[i];
            System.out.println("New item added" + i);
        }
        newGrocery[i+1] = new Groceries(name, price);
        return newGrocery;

    }

I have this method where I input an array containing 4 objects and it creates a new array of objects copying the previous 4 objects and then adding one more to the array. But I keep getting this exception.
Comment: You need to write `newGrocery[i] = new Groceries(name, price);` because `i` has already been increased 4 times in the loop. Increasing it again with `i + 1` will get you out of range for the new array. It would be better to write `newGrocery[newGrocery.length - 1] = new Groceries(name, price);` instead, so that you're not dependent on `i`
Comment: `Array.getLength(newGrocery)` why not just `newGrocery.length`?
Comment: Note: always have variables with the smallest scope possible. For example: declare your loop counters WITHIN the for loop `for (int i ...)` ... because that ENSURES that you won't use that `i` afterwards. And just for the record: as you seem to be allowed to use library methods from the Array class ... that class has a method that  copies content from one array into another. There is no need to do that manually. Besides learning how to loop arrays and not go "off by one" in the end.
Answer: The exception occurred because you're trying to add an element to an array index (i+1) that just doesn't exist, here:
newGrocery[i+1] = new Groceries(name, price);
Its because i has already been incremented by the for loop at the end to the last index value in the array, by doing i+1 you're trying to access the index = arrayLength2 which doesn't exist.
May be what you want is a List that is capable of expanding its size when a new element is added, unlike array which has a fixed size.
Comment: I thought I made the new array length to be 1 index larger than the old array length with this though? ```Groceries[] newGrocery = new Groceries[arrayLength + 1];```
Comment: Right, I've updated the answer.
Comment: Ah I see now tyvm!


Count no IReport

Question: Tenho um relatório onde tenho a coluna Status, nessa coluna tenho os seguintes status: Finalizado e Pendente.
Criei uma variável e adicionei ela na banda Sumary e configurei as seguintes propriedades:
Variable class = java.lang.Integer
Calculation = Sum
ResetType = Report
Increment type = None
Variable expression = $F{tbl_suspensao_status}.equals("Finalizado")  ? 0 : 1

Porém o resultado é sempre o total tudo, seu eu tenho 2 Finalizados e 2 Pendentes o resultado fica igual a 4.
Como posso contar corretamente quantos Status são Finalizados e quantos são Pendentes?

Query:
SELECT
     tbl_suspensao.`codigoBeneficiario` AS tbl_suspensao_codigoBeneficiario,
     tbl_suspensao.`contrato` AS tbl_suspensao_contrato,
     tbl_suspensao.`data_fim` AS tbl_suspensao_data_fim,
     tbl_suspensao.`data_inicio` AS tbl_suspensao_data_inicio,
     tbl_suspensao.`status` AS tbl_suspensao_status,
     tbl_usuario.`nome` AS tbl_usuario_nome,
     tbl_suspensao.`nomeBeneficiario` AS tbl_suspensao_nomeBeneficiario
FROM
     `tbl_usuario` tbl_usuario INNER JOIN `tbl_suspensao` tbl_suspensao ON tbl_usuario.`codigo` = tbl_suspensao.`usuario_id`
WHERE
 AND tbl_suspensao.`data_inicio` BETWEEN  $P{Data_Inicio} AND $P{Data_Fim}

GROUP BY
      tbl_suspensao_status

Comment: Tem que fazer ou `groupBy` por Status.
Comment: Aonde eu coloco esse groupBy? Na query?
Comment: Isso mesmo. `Select Status, Count(Id) as Total From Tabela Group By Status`
Comment: Ainda não funcionou, coloquei o group By no final, além de não mostrar todos os registros no relatório também não conta os totais
Comment: Como você está montando a query ? Coloca ela no tópico.
Comment: Pronto, coloquei
Comment: O `GROUP BY` funciona assim... O que você colocar no `SELECT` tem que colocar no `GROUP BY`. Mas se os dados do `SELECT` forem diferentes, sua contagem não vai ser exata. Eu sugiro que você faça apenas um `SELECT` para a contagem. Bem simples. `SELECT Status, Count(tbl_usuarios.nome) as Total Group By Status`. Ou seja, vão ter duas query no seu iReport. Uma para os registros e uma para o total. Mas eu não lembro se o iReport tem a função que já pega o total de registros. Não tem ?
Comment: Acho que a função `Count` faz isso
Comment: Também não sei como colocar duas querys no mesmo relatório
Comment: @Techies, tente fazer isso `Select Coluna,count(*) from Tabela group by Coluna`
Answer: coloca uma coluna para fazer a contagem tipo assim:
    SELECT
     sum(1) as contador,
     tbl_suspensao.`codigoBeneficiario` AS tbl_suspensao_codigoBeneficiario,
     tbl_suspensao.`contrato` AS tbl_suspensao_contrato,
     tbl_suspensao.`data_fim` AS tbl_suspensao_data_fim,
     tbl_suspensao.`data_inicio` AS tbl_suspensao_data_inicio,
     tbl_suspensao.`status` AS tbl_suspensao_status,
     tbl_usuario.`nome` AS tbl_usuario_nome,
     tbl_suspensao.`nomeBeneficiario` AS tbl_suspensao_nomeBeneficiario
FROM
     `tbl_usuario` tbl_usuario INNER JOIN `tbl_suspensao` tbl_suspensao ON tbl_usuario.`codigo` = tbl_suspensao.`usuario_id`
WHERE
 AND tbl_suspensao.`data_inicio` BETWEEN  $P{Data_Inicio} AND $P{Data_Fim}

GROUP BY
      tbl_suspensao_status;

Assim a coluna contador fica sendo seu Field lá no iReport.
Comment: Obrigado @NinjA

Count no IReport


NuGet: Do Not Set Assembly Reference

Question: I have created a nuget package containing a DLL that I want to share with multiple applications.  I want to add this package to applications without setting a reference to the DLL.  I am using dependency injection to load this DLL or a test DLL at run-time.
By default, nuget automatically sets a reference to all DLLs contained lib during installation.
Is there any way to configure the nuget package to not set a reference to the DLL when it is installed into my project?
Answer: Explicit assembly references. Although if your dll is loaded entirely at runtime (using MEF or Assembly.Load or something similar), then the build system might not copy the dll to the project's output directory. Note these docs are only correct for packages.config projects. I have a PR to improve the docs to explain how to do the equivalent thing for PackageReference.
Comment: I didn't get that your package contained only 1 dll before. You could try using the `` element with whatever target framework you use, to see if that allows you to specify no references. But I don't think this will work for packages.config projects because of how ResolveAssemblyReference works (see my docs PR for links and a brief description). I think it might work for ProjectReference projects if you create an empty `ref\\_._` file
Comment: PR has some [package compatibility](https://learn.microsoft.com/en-us/nuget/reference/migrate-packages-config-to-package-reference#package-compatibility-issues) differences. For ASP.NET it's most often about getting css or js from the package. But if you don't use that, then you can use PR in ASP.NET. You need to uninstall all packages, ensure that the visual studio nuget options asks you which format on first package install, then install your packages again.
Comment: PackageReference was added before I joined the team, but I think it was around NuGet 4.2 or 4.3. As long as you use a NuGet version greater than this, yes. Unsurprisingly I recommend using the latest version of NuGet.
Comment: But this describes how to explicitly add a reference where one does not exist.  My problem is that nuget is adding a reference where I do not want one.   There does not seem to be a "don't reference" flag for the main assembly.
Comment: when the nuspec doesn't have any `` element, NuGet will add references to every dll in the package (for the selected TFM). By using ``, it tells NuGet which dlls to add references to in the project's csproj, and any dll you don't list in the nuspec `` section will not get added to the csproj.
Comment: I also don't understand what you mean by "explicitly add a reference where one does not exist". What do you beleive the docs are explaining?
Comment: I know what the documentation says, zivkan.  It does not work that way.  Even when you define the  element with nothing in it, nuget still sets a reference to the main DLL.
Comment: Try it yourself.
Comment: My package contains one DLL that I DO NOT want the project to reference. What should I put between ?  Nothing?  It still reference the DLL.  Sorry,  I'm not sure how much clearer I can be.
Comment: Interestingly, when I add ``, `` elements are _required_.
Comment: Evidently PackageReference is not supported for ASP.net projects yet. :-(
Comment: Do you happen to know if the PackageReference format is supported by the Azure DevOps build pipeline?

NuGet: Do Not Set Assembly Reference


Polynomial With Prime Powers

Question: Suppose that $p$ and $q$ are distinct primes. Prove that for all $a \in \mathbb{Z}$, we have $   a^{pq} - a^{p} - a^{q} + a \equiv 0 \pmod{pq}. $
I have tried using variations of Fermats Little theorem but have made little headway
Comment: Please do not delete the body of your question after it has been answered.
Comment: You only need $a^p\equiv a\mod p$ for every prime $p$ and every ineteger $a$ (See the answer below)
Answer: We have $$a^{pq}=(a^q)^p\equiv a^q\mod p$$ and $$a^p\equiv a\mod p$$
This implies $$a^{pq}-a^p-a^q+a\equiv 0\mod p$$
For $q$, the proof can be made completely analogue.

Polynomial With Prime Powers


Approximating a sum of two binomial distributions

Question: A club basketball team will play a 60-game season. Thirty-two of these games are against class A teams, and 28 are against class B teams. The outcomes of all the games are independent. The team will win each game against a class A opponent with probability .5 and it will win each game against a class B opponent with probability .65. Let X denote its total number of victories in the season.
(a) What is the relationship between $X_A$, $X_B$, and $X$? Is $X$ a binomial random variable?
(b) Approximate the probability that the team wins 45 or more games this season.
What I did:
$$X=X_A+X_B \\
X_A \text{ is a binomial random variable with } n=32 \text{ and } p=0.5 \\
X_B \text{ is a binomial random variable with } n=28 \text{ and } p=0.65 \\
p_X(k) = \sum_{a=0}^k P(X_A=a)P(X_B=k-a) $$
Can I express $p_X(k)$ as a binomial distribution somehow? Also, I think it is possible to approximate $P(X\ge45)$ using a normal distribution by the Central Limit Theorem, but I'm not sure how to apply it.
Answer: $X$ is not a binomial random variable.  One way to see this is using the moment generating function.
You can approximate $X$ by a normal random variable having the same mean and variance.
You may want to use the continuity correction, if your instructor has mentioned that.
Comment: I know the mean for $X$ is $32(.5)+28(.65) = 34.2$, but how do I calculate the variance?
Comment: Variance of the sum of independent random variables is the sum of the variances.  Do you know (or can you look up) the formula for variance of a binomial random variable?
Comment: Okay, so I found that the variance is $(32)(.5)(.5) + (28)(.65)(.35)=14.37$. Does applying the continuity correction mean that $P(X\ge45)=P(X>44)$?
Comment: Yes.  The continuity correction would mean using $P(X > 44.5)$ (i.e. we want to include $X=45$ but not $X=44$).


Conditional change row colors

Question: Say I have a content type "task" with one field "status", which is output by views. Now I want when the status is "finished", the color of that row will be red, when the status is "failed", the color of that row will be yellow, when the status is "ongoing", the color of that row will be green.
Is there any way to realize this? BTW, I know very little about code.
Comment: [views table highlighter](https://www.drupal.org/project/views_table_highlighter)?
Answer: There are 2 ways to do this, but you should do this the Drupal way.

You can use JavaScript to iterate through each
 adding a class to the
 if it finds finished in the last column.
You can do it the Drupal way in views. I assume you are using the table view to output your data since that's what you are showing us.

Under your edit view mode, you'll see "Format" and then "Format:Table | Settings".
Click on Settings. Under settings you should see an option that says "Row Class".
You want to set your row class equal to the value of the status field. To do this. Look under Fields to find the field that is displaying your status column and click to edit it. Once there, select "Rewrite results" and then click the "Override the output of this field with custom text" checkbox.
This will open a textbox with an option below it stating "Replacement Patterns." when you click this, you should see some options inside of {{ }}. There will likely be one that looks something like {{ status }} == Status.
The {{ status }} part is your replacement pattern. Copy it and paste it into the row class field under table settings.
What this will do is add a class to your
 in your view.
Example of what the view output will then look like:

  3/5/19>
  write article
  finished

After completing this step, you need to add a bit of CSS to your stylesheet in your theme.
Something like:
tr.finished td { color: red; }
tr.ongoing td { color: green; }
tr.failed td { color: yellow; }

So you end up changing the row class to be the replacement pattern of your status field and adding 3 lines of CSS code to your theme's style sheet.
Comment: The CSS Editor module https://www.drupal.org/project/css_editor allows you to enter CSS through the interface, without modifying your theme. It's useful when you only need to make small style adjustments or don't know how to create subthemes.

Conditional change row colors


Over sampling imbalance data in SVM

Question: Basically I have a medium size data set (20,000 observations) with only 200 being in group 1, thus an imbalanced data set. My goal is to predict as much group 1 class as possible without sacrificing too much false positive.
With some research, I understand putting class.weight = c('1'=100,'0'=0.5) in svm() would be a method to specify different misclassification  penalty for groups. Over sampling the minority group or subset the majority group would also be solutions to the data imbalance. However, I am not sure how the latter would help the situation because the prediction proportion for positive should ultimately be small even the training data set is "balanced."
So my question would be the following:
1) When using over sampling the minority class, how would I adjust the prediction (or the model) so the prediction will ensure only a small proportions are assigned to be class 1?
2) During the fitting for svm() with the original data, how should I specify the value cost ? I could tune it with tune() but the running time increase tremendously after I put class.weight=c('1'=100,'0'=0.5)
Thanks!
Answer: 1) Using SMOTE method to oversample would make a better classification on future prediction even the training data set doesn't consist of balanced result.
2) The class.weight argument in svm() doesn't perform well, one could use SMOTE or other method to create a balanced data instead of using weight argument. Alternatively, using a tree rpart might be a option where it can specify the loss matrix.

Over sampling imbalance data in SVM


Is there a way for one player to have a solo but the rest of the instrument keep playing?

Question: I'm writing a piece where there is like a bass line which is made up of all 5 string section parts (orchestra) that each have a similar rhythm, and that all together makes a cool sound.
I want to add a sort of melody that bounces around the ensemble, but only one player per section plays. I feel like making it divisi might work, but that would be for multiple players.  It is also a pizzicato part and I'm not sure if there is a way to have divisi, with the top part pizz and the bottom part arco.
For reference, this is what all five parts look like together:

I want to add pizz for the notes "E" and "F" for violin parts, and notes "A" and "G" for cello with the first note being a grace note for the second which will be a quarter note thrown in, in a couple spots.
I'm aware I could just add another part and have it only be given to one player, but that is a lot more paper for just a few notes.
Comment: So what is the question you are asking?
Comment: I think the question is how to notate two parts (solo player and the rest of the section) on one staff.  Is that right?
Answer: Each of the sections with a soloist should split into two staves for the solo.  Connect these staves with a thin margin bracket.  Mark the solo staff solo, and the other staff gli altri (the others).  These extra staves collapse away when the solo is over, mark this with tutti (everyone).
It looks neatest when the splitting and merging coincides with a system break (line break/page break).
NB-1: "Viola" is a feminine noun in Italian, so sola and le altre are used for this part instead.
NB-2: If you want say 2 soloist playing the same part, use the plural soli e.g. 2 soli, (2 sole for violas).
If each of the string sections has the solo at the same time, it should look something like this:

Then you can add pizz. and arco to the respective staves.
Don't worry about taking a little extra paper; it's more important that the music is easy to read.
Answer: You can write divisi and mark the "melody" parts as "solo pizz."


Drupal Commerce Mirgrate product displays

Question: I'm trying to create a migration class for my product displays. I already have one for the product variations which is seperate because it has a different CSV source.
So I'm just trying to create the drupal nodes of the product displays. When I check the database in the node table, the nodes are there with the correct type. However when I go to the product page, I don't see the new items there.
I think it has something to do with this line:
<code>$this->destination = new MigrateDestinationNode('video_storage_recorder');
</code>
or
<code>$this->map = new MigrateSQLMap($this->machineName,
      array(
        'Name' => array(
          'type' => 'varchar',
          'length' => 255,
          'not null' => TRUE,
          'description' => 'Recorder',
        ),
      ),
      //MigrateDestinationCommerceProduct::getKeySchema('commerce_product')
      //MigrateDestinationEntityAPI::getKeySchema('video_storage_recorder')
      MigrateDestinationNode::getKeySchema('video_storage_recorder')
    );
</code>
where video_storage_recorder is my content type.
Also I tried
<code>$this->destination = new MigrateDestinationEntityAPI('video_storage_recorder');
</code>
But no different behaviour.
I think the nodes are created but not considered products for Drupal Commerce. But I don't know why.
Also Migrate does not give any (error) messages and just says 9 items were created.
Answer: When I added a product variation in code the product appeared in the list. It's required to have at least one variation to be linked for the product display to be considerd a product display.


Comparar data sql

Question: Estou precisando comparar data em um certo intervalo de tempo. Preciso pegar o campo DAT_REPOT_REALZ e verificar as datas entre HOJE e sete dias atrás. Preciso também contar o numero de V (visitante) e o numero de L (lider) e M (participante), na query que fiz não deu muito certo pois não tenho muita familiaridade com sql.
Vale salientar que estou utilizando o MYSQL.
Tentei fazer assim
select case FLG_IDENT_PESSO when 'V' then count(FLG_IDENT_PESSO) when 'M' then count(FLG_IDENT_PESSO) end from tbl_PRESENCA WHERE FLG_IDENT_PRESE = 'S' and DAT_REPOT_REALZ <= now()-7

A estrutura de minha tabela:
COD_IDENT_REUNI bigint(20) UN PK
COD_IDENT_PESSO bigint(20) UN PK
FLG_IDENT_PRESE char(1) //PODE SER S (presente) ou N (nao presente)
FLG_IDENT_PESSO char(1) // PODE SER V (visitantes) ou L (lider) ou ainda M (participante)
DAT_REPOT_REALZ datetime // É O DIA EM QUE FOI FEITO O REPORTE

Comment: Tu precisa usar um `BETWEEN` ou duas verificações no `WHERE` pra funcionar do jeito que você quer.
Comment: Como ficaria a query?
Answer: É possível fazer assim:
select
    count(COD_IDENT_PESSO);
FROM
    tbl_PRESENCA
WHERE
    DAT_REPOT_REALZ BETWEEN DATE_SUB(CURDATE(), INTERVAL 7 DAY) AND CURDATE() AND
    FLG_IDENT_PRESE = 'S';

O SQL acima vai retornar o número total de pessoas que estiveram presentes na reunião. Para contar separado, basta usa uma outra condição no WHERE
select
    count(FLG_IDENT_PESSO);
FROM
    tbl_PRESENCA
WHERE
    DAT_REPOT_REALZ BETWEEN DATE_SUB(CURDATE(), INTERVAL 7 DAY) AND CURDATE() AND
    FLG_IDENT_PRESE = 'S' AND
    FLG_IDENT_PESSO = '?';

Onde '?' seria o que você quer procurar em especifico, V, M ou L
select
    sum(case FLG_IDENT_PESSO when 'V' then 1 else 0 end) as 'Visitantes',
    sum(case FLG_IDENT_PESSO when 'L' then 1 else 0 end) as 'Lideres',
    sum(case FLG_IDENT_PESSO when 'M' then 1 else 0 end) as 'Participantes',
FROM
    tbl_PRESENCA
WHERE
    DAT_REPOT_REALZ BETWEEN DATE_ADD(CURDATE(), INTERVAL -7 DAY) AND CURDATE() AND
    FLG_IDENT_PRESE = 'S';

Ou tudo em um select, dividindo como foi citado na outra resposta.
Comment: Porque a ideia é contar a quantidade de participantes que esteve presente , então tenho a flag FLG_IDENT_PESSO e tenho a possibilidade no campo de colocar V que teria que contar, e L + M que preciso contar, ou seja irei contar o numero de visitantes, depois contar numero de lider e participante juntos.
Comment: Tenho também um campo FLG_IDENT_PRESE que pode colocar 'S' e 'N', preciso contar apenas os que tem FLG_IDENT_PRESE = 'S'
Comment: Poderia colocar a sua tabela (ou o SQL dela) na sua pergunta pra eu entender melhor?
Comment: Atualizei a pergunta
Comment: Atualizei minha resposta, qualquer dúvida só perguntar aqui nos comentários
Comment: Juntamente na mesma query tem como fazer não ?
Comment: COM LEFT JOIN CONSIGO FAZER ISTO NAO ?
Comment: é possivel usar um UNION para juntar os selects, cada um com um where usando um  `FLG_IDENT_PESSO = '?'` diferente
Answer: Você pode usar BETWEEN e a função DATE_SUB
Seu where fica assim : where DAT_REPOT_REALZ between DATE_SUB(now(), interval 7 day) and now()
Segue um fiddle de exemplo .
Em relação ao count , você pode colocar um sum em um case
exemplo :
SUM(case FLG_IDENT_PESSO when 'V' then 1 else 0 end) as Visitantes

query completa :
    select sum(case FLG_IDENT_PESSO when 'V' then 1 else 0 end) as visitantes ,
    sum(case FLG_IDENT_PESSO when 'M' then 1 when 'L' then 1 else 0 end) as participantes
  from tbl_PRESENCA where DAT_REPOT_REALZ between DATE_SUB(now(), interval 7 day) and now()

Comment: você é 10, justamente o que precisava
Comment: Aeew \o// ! Que bom que deu certo
Comment: so teria uma coisa para acrescentar porque o M pode ser L também, ou seja preciso contar se for M e se for L também, como ficaria ?
Comment: Mesma lógica Renan , vou editar a resposta , mas vc tem que colocar um SUM() com um case dentro dele ,  e depois adicionar 1 pra cada vez que a comparação é atendida e 0 no else .( pra resolver desse jeito , existem outras soluções)
Comment: Não você nao entendeu se o cara for lider ou se ele for participante terá que somar mais um, por exemplo tem 3 L e 2 M então terá 5 participantes
Comment: entendi !! então você tem que colocar mais um when , vou modificar de novo !

Comparar data sql


No of integral solutions to an equation confusion?

Question: For an equation like ${ x }_{ 1 }+{ x }_{ 2 }+{ x }_{ 3 }=60$, I am seeing that in some books they are using $( (60 + 4 - 1) C (4) )$ as solution whereas in some book they are using $( (60 + 4 - 1) C (4 - 1) )$ as solution..My doubt is when to use whom ?
Comment: Could you please explain what is $C(4)$?
Comment: It is basically r of nCr (combinatorics)
Comment: Well, you are looking for the number of solutions for the  equation. Am I right? Or you need to find the solutions.
Comment: Yes, i need to count the no of solutions..Am not looking for enumerating them
Comment: No,they are non negative
Answer: The $x_i$ are non-negative integers, this means determining the number of ways $n = 60$ identical objects (the $60$ units in $60$) can be put into $r = 3$ bins ($x_1, x_2, x_3)$, where a bin can be empty.
The number of ways to do this is $\binom{n+r-1}{r-1} = \binom{62}{2} = 1891$.
Comment: Thanks,It cleared the doubt..:)
Answer: $\newcommand{\angles}[1]{\left\langle\,{#1}\,\right\rangle}
 \newcommand{\braces}[1]{\left\lbrace\,{#1}\,\right\rbrace}
 \newcommand{\bracks}[1]{\left\lbrack\,{#1}\,\right\rbrack}
 \newcommand{\dd}{\mathrm{d}}
 \newcommand{\ds}[1]{\displaystyle{#1}}
 \newcommand{\expo}[1]{\,\mathrm{e}^{#1}\,}
 \newcommand{\half}{{1 \over 2}}
 \newcommand{\ic}{\mathrm{i}}
 \newcommand{\iff}{\Leftrightarrow}
 \newcommand{\imp}{\Longrightarrow}
 \newcommand{\ol}[1]{\overline{#1}}
 \newcommand{\pars}[1]{\left(\,{#1}\,\right)}
 \newcommand{\partiald}[3][]{\frac{\partial^{#1} #2}{\partial #3^{#1}}}
 \newcommand{\root}[2][]{\,\sqrt[#1]{\,{#2}\,}\,}
 \newcommand{\totald}[3][]{\frac{\mathrm{d}^{#1} #2}{\mathrm{d} #3^{#1}}}
 \newcommand{\verts}[1]{\left\vert\,{#1}\,\right\vert}$
\begin{align}
&\color{#f00}{\sum_{x_{1} = 0}^{\infty}\sum_{x_{2} = 0}^{\infty}
\sum_{x_{3} = 0}^{\infty}\delta_{x_{1}\ +\ x_{2}\ +\ x_{3}\ ,\ 60}} =
\sum_{x_{1} = 0}^{\infty}\sum_{x_{2} = 0}^{\infty}
\sum_{x_{3} = 0}^{\infty}\oint_{\verts{z} = 1^{-}}
{1 \over z^{61 - x_{1} - x_{2} - x_{3}}}\,{\dd z \over 2\pi\ic} =
\oint_{\verts{z} = 1^{-}}{1 \over z^{61}}
\pars{\sum_{x = 0}^{\infty}z^{x}}^{3}\,{\dd z \over 2\pi\ic}
 \\[3mm] = &\
\oint_{\verts{z} = 1^{-}}{1 \over z^{61}\pars{1 - z}^{3}}
\,{\dd z \over 2\pi\ic} =
\sum_{k = 0}^{\infty}{-3 \choose k}\pars{-1}^{k}
\oint_{\verts{z} = 1^{-}}{1 \over z^{61 - k}}\,{\dd z \over 2\pi\ic} =
\sum_{k = 0}^{\infty}{-3 \choose k}\pars{-1}^{k}\delta_{k,60}
\\[3mm] = &\
{-3 \choose 60} = {3 + 60 - 1 \choose 60}\pars{-1}^{60} =
{62 \choose 60} = {62 \times 61 \over 2} = \color{#f00}{1891}
\end{align}


How do I code Scalable Vector Graphics (SVG) output with SAS Enterprise Guide 6.1?

Question: The title says it all. I have used the OUTPUTFMT=SVG in the ODS GRAPHICS statement without any problems in Base SAS, but this methods seems not to be appropriate for SAS Enterprise Guide.
Comment: Need a tiny bit of information, like, what code are you running?  And is this using local server, or an actual server?
Answer: If you look in the log you will see the issue:
27         ods graphics on / OUTPUTFMT=SVG;
28
29         proc reg data=test;
30         model y=x;
31         run;

WARNING: SASREPORT13 destination does not support SVG images. Using the default static format.

So it is the default output type that EG produces that is the problem.  You can see that in the log as well:
15         ODS tagsets.sasreport13(ID=EGSR) FILE=EGSR
16             STYLE=HtmlBlue
17             STYLESHEET=(URL="file:///C:/Program%20Files/SASHome/SASEnterpriseGuide/7.1/Styles/HtmlBlue.css")
18             NOGTITLE
19             NOGFOOTNOTE
20             GPATH=&sasworklocation
21             ENCODING=UTF8
22             options(rolap="on")
23         ;

Got to Tools->Options.  In the window select "Results General" and change to HTML as your results format.
Now when you run the code, you get HTML and SVG files produced.  They will be in the GPATH location defined.
It does not look like the SAS HTML viewer is capable of displaying the SVG files.  You will have to download them yourself and look at them.
NOTE: I'm using EG 7.1, but the file menu choices should be very similar.
Comment: Switching: 1) HTML on  +  2) "SAS Report" result format off did the trick. Working perfect now, thank you very much for your help.
Comment: I imagine SVG viewer uses IE internally, which prior to I think version 9? or 10? couldn't display SVG.  I would think you could change that, presumably by using the Viewer option.
Comment: I have mine set to Chrome.  I think the problem is the SVG files are put into the HTML with static links to their location on the server.  You are viewing locally and Chrome/IE/Whatever cannot get to them.
Comment: Hmm, actually I do too, and still can't see it.  And that's with Local Server.
Comment: If I switch to Local, I get a button that says results will be displayed externally to EG.  Clicking that opens the HTML in Chrome (Windows default) and I see the SVG images.
Comment: There was a post on SAS communities recently that showed how to embed the image directly into an HTML5 pages so the reference issue disappears.


What do we mean by "Random" in the science's context

Question: What do we mean by 'Random' in the science's context. Especially in the statistics and signals processing field. I looked to the dictionary definition of Random and this is what I found:

Made, done, happening, or chosen without method or conscious decision.
Unfamiliar or unspecified. Odd, unusual, or unexpected.

For the first one, I do not think that there are signals or phenomena happens in an arbitrary way. Furthermore, we cannot understand the complex structure that come up with this signal or phenomena. So, we use statistics to express/define our uncertainty. So, I think the second one is the correct definition in the science's context. Is that correct?
Comment: Neither of those could possibly be a scientific or mathematical definition, because they are both personal and subjective: the first refers to "conscious decision" while the second refers to the observer's expectations and state of mind.  Dictionaries rarely provide accurate technical definitions of terms.  Use textbooks instead.
Comment: To clarify the comment of whuber the text said "without conscious decision" but the idea is that it discusses personal decision.
Comment: Language evolves and these are relatively recent uses of "random," neither of which is related to how "random" is used in statistics or science.
Answer: Not my area, but in signal processing I'd guess it is well defined (although perhaps circularly) as white noise. E.g. (current Wikipedia)  "having equal intensity at different frequencies, giving it a constant power spectral density". In statistics that is just one type of random distribution though (uniform).
More generally though, it might just be a folly to try to define random for all of science, especially given how much many like to attach adjectives to it.


Can I import "id" into "uid"?

Question: I'm trying to import over 5000 users into drupal by using Feeds module. Can I import user "id" into "uid"? If so, how can I do that? I saw the GUID mapping target, but that is not "uid". Thanks.
Comment: I'm not sure whether or not this is possible however in the past I've created an 'Original ID' field to hold entities ID's from legacy systems.
Comment: Does it has to custom script the Feeds module? I hope there is a way to add uid into a new target.
Answer: The user ID field on Drupal is auto-incremented, so you don't want to import your ID values into that field. It's much better to add an original_id field to retain the legacy user IDs.
Comment: We need that for "created by" such user. If we not use the id into uid, then we have to modify over 800+ uid on articles, plus the issue with the double quotes database on body content.

Can I import "id" into "uid"?


Video not playing on iPhone

Question: I have just got a simple video going. When I run the app in Simulator the video plays but when I run it on my iPhone it says video missing. Any help would be much appreciated thanks!
Here is my code :
import UIKit
import AVKit
import AVFoundation

class ViewController: UIViewController {

    var playerviewcontroller = AVPlayerViewController()
    var playerview = AVPlayer ()

    @IBAction func playMusic(sender: AnyObject) {
        var fileURL = NSURL(fileURLWithPath:"/Users/MorganEvans/Documents/Apps/32134.mp4")
        playerview = AVPlayer(URL: fileURL)

        playerviewcontroller.player = playerview

        self.presentViewController(playerviewcontroller, animated: true){

            self.playerviewcontroller.player?.play()
        }

    }
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

}

Comment: You are using a video path for your machine in disk which definitely will not work in device. Try add the video in the project files and use `NSBundle` to get its path.
Comment: Please tell me how/where I add it to. Thanks
Comment: I have added how/where as answer. Please check
Answer: The video file should be added in Xcode project like this:

Then you can get the video url like this:
let movieURL = NSBundle.mainBundle().URLForResource("ElephantSeals", withExtension: "mov")!

Comment: It comes up with the error - fatal error: unexpectedly found nil while unwrapping an Optional value
(lldb)
Comment: double check the name of your video file and extension
Comment: Yep its correct but its not in a common file. how to i find that folder`/ thanks
Comment: Common folder is just for clarification. You can create any folder with any name to combine your videos inside.
Comment: Ok please see the photo I have put on of the error. I really appreciate your help
Answer: Please put the video file into your project bundle. Simply drag and drop the video into your project.
NSURL *url=[[NSBundle mainBundle]URLForResource:@"arreg" withExtension:@"mp4"];
AVPlayer *video=[AVPlayer playerWithURL:url];
AVPlayerViewController *controller=[[AVPlayerViewController alloc]init];
controller.player=video;
[self.view addSubview:controller.view];

controller.view.frame=self.view.frame;
[self addChildViewController:controller];

[video play];

Video not playing on iPhone


Função Hide/Show não funciona no IE 8

Question: Tenho um JavaScript que faz a função de agrupar itens em uma tabela.
Por exemplo clico nele e ele expande trazendo mais valores desse item. O problema é que no IE 8 não funciona. No Chrome e Mozilla a função funciona normalmente.
<code>function ocultarColunasNaoAgrupadas(){
    $('#tabelaPainelCnab tbody tr td').each(function() {
        var idCell = $(this).attr('name');

        if (idCell == 'identQuebraMes') {
            var cellTextMes = ''+ $(this).html();
        }
        if (idCell == 'identQuebraCarteira') {
            if ($(this).html().length > 0 ) {
                $(this).closest('tr').attr('agrupador', 'N');
                //$(this).closest('tr').slideToggle(300)
                $(this).closest('tr').hide();
            } else {
                $(this).closest('tr').hide();
                $(this).closest('tr').attr('agrupador', 'S');
                $(this).closest('tr').attr('class', 'header');
                $(this).closest('tr').show();
            }
        }
    });
}
</code>
Comment: Seria bom especificar qual a versão do IE. Uma formatadinha no código também não faria mal =)
Comment: Estou aprendendo a usar o stack , me perdoe os erros, versao do IE 8, obrigado pelas dicas.
Comment: Note que tenho 3 perguntas, responda todas por favor: 1. Ocorre algum erro no console do IE8? 2. Está usando qual versão do jQuery? 3. Tem como postar uma estrutura simplificada da parte HTML?
Comment: Boa noite guilherme, não ocorre nehum erro no IE8, Versao Jquery-1.6.2.js, Segue codigo aqui https://paste.ofcode.org/h7D5652nR2A2ignaCvHG4t
Answer: O jQuery atual não da Suporte ao IE 8
Navegadores suportado
Desktop
Chrome: (Current - 1) and Current
 Edge: (Current - 1) and Current
 Firefox: (Current - 1) and Current
Internet Explorer: 9+
Safari: (Current - 1) and Current
Opera: Current
Mobile
Stock browser on Android 4.0+
Safari on iOS 7+
Solução
Se você precisa de suporte a navegadores mais antigos como o Internet Explorer 6-8, Opera 12.1x ou Safari 5.1+, use jQuery 1.12
Comentários condicionais
<code> <!--[if IE 8]>
<script src="js/jQuery-1.12.js"></script>
<![endif]-->
</code>
fonte: http://jquery.com/browser-support/

Função Hide/Show não funciona no IE 8


Explicitly declaring a function pointer and not a data pointer

Question: I am converting a program from C++ to C, using Microsoft Visual Studio. It's a Windows app, but I don't think that's relevant to this question.
I am using the /W4 switch to turn on more warning messages. I would like my program to compile with no warnings. The program compiles and runs fine. This is just about warning messages.
Before when the program was C++, it compiled with no warnings, but now that I've converted it to C as best I can, there's a warning that I do not know how to deal with.
Here is the relevant code. The idea is that I'm creating a menu system for a GUI. Each menu contains a collection of menu items, and each menu item contains a function pointer that represents the action that will be performed when the user chooses that menu item.
typedef struct MENUITEM
{
    wchar_t* Name;
    void*    Action;
} MENUITEM;

typedef struct MENU
{
    wchar_t*   Name;
    uint8_t    SelectedItem;
    uint8_t    ItemCount;
    MENUITEM** Items;
} MENU;

Elsewhere in the program, this the code that handles the event when the user chooses a menu item:
void(*FP) (void) = NULL;
FP = (void(*)())MyMenu.Items[MyMenu.SelectedItem]->Action;
FP();

Here are the compiler warnings that are generated:

C4152 nonstandard extension, function/data pointer conversion in expression

And

C4113 'void (__cdecl *)()' differs in parameter lists from 'void (__cdecl *)(void)'

The MSDN documentation for the warning message C4152 states:

A function pointer is converted to or from a data pointer. This conversion is allowed under Microsoft extensions (/Ze) but not under ANSI C.

OK, so I think this explains why it did not produce a warning as C++, but when compiling as C, it does. But I don't know how to deal with it. To be honest, I did not realize before now that there was a difference between a function pointer and a data pointer.
I cannot figure out how to change the declaration of my function pointer such that it is explicit to the compiler that this is a function pointer, not a data pointer.
Answer: You probably need this (with a typedef):
typedef void(*FP) (void);

typedef struct MENUITEM
{
    wchar_t* Name;
    FP   Action;
} MENUITEM;

int main() {

    MENUITEM it;
    // ... more code

    FP fp = it.Action;
    fp();

    return 0;
}

Answer: You forgot the void in the cast. That's what C4113 is telling you.
You can avoid the cast altogether by declaring Action as a function pointer:
void (*Action)(void);

Comment: Danny_ds's answer was good, but IMO this answer was the best. Now, not only does the code compile without warnings, but it also allowed me to eliminate the extra local FP declaration in my code and use just `MyMenu.Items[MyMenu.SelectedItem]->Action();`
Comment: @Danny_ds I See. Thank you. Both your answers are valuable. I think both of your answers, when taken in combination, helped it "click" for me. I wish I could accept them both.
Comment: @RyanRies - Just to be clear: that extra local declaration isn't needed of course - it was there for clarity, to show the usage. Using a typedef for function pointers is usually a good idea.