Chest voice & Head voice? Or Chest voice, Throat voice AND Head Voice?

Question: The concept of chest/voices is pretty basic, but I feel more like I have 3 main sections to my range:

Chest voice, from the bottom of my range to about G3
Throat voice, which has some sort of tone to it, from G3 to D4/E4
Head voice, which is much purer and cleaner, up to about B4 (the top of my range)

My "head voice" I pretty much have to make an "ah" sound, so it's not something I can easily use to sing. It's not forced like a falsetto, so are these 3 voices real or am I getting confused?
Comment: You need some lessons with a qualified voice teacher. These are matters that can't be quantified in writing on a site such as this. You need to interact with another human being, over several lessons, to shape the technique necessary to control all this and get the best sound out of your voice.
Comment: Here is an answer on Music Practice and Theory that speaks about the "throat" voice. http://music.stackexchange.com/a/669/16897
Comment: All I'm asking is if these 3 separate voices are recognised, or only chest/head as often discussed. Not how to use them.
Comment: One of these days I'm gonna have to go see what a vocal teacher would tell me about all this chest/head stuff. I just don't get it & I've only been singing professionally for 35 years. You do it. If it works you do it live. If it doesn't, dump it & pick a different song, or rework it in another key. End of. [posted as a comment to avoid getting -20]  ;)
Comment: I like the answer linked by @RockinCowboy. It seems accurate to me. It just comes down to where the sound is resonating. As the resonance moves up from your chest into your head, there probably is a transition point where it is resonating in-between, in the throat area. However, it may not be well-defined and whether it is distinct enough to deserve it's own 'voice category' is probably a matter of debate/semantics.
Answer: Technically I don't know if they're three separate "voices"; perhaps it's better to say they "feel" like three different things.
I think your ranges are a little off too. I'm a trained singer and my range currently is:
Chest: around C3 -> F5
"Mid": E5 -> G#5
Head: A5 and up to at least D6
Most men have a range that's basically similar, once the proper technique is learned.
My "mid" voice really is a Chest voice where I'm blowing slightly more air until I feel the vocal folds "blow open" slightly while phonating. In other words, it's a normal Chest voice blown a little harder.
This starts to fail (badly) at around B5, so I cut-out and enter Head at A5.. especially if I'm going up in the melody.
These terms (Chest, Head) are only what the singer is perceiving; specifically where the resonance is felt in the singer. Head voice "feels" like it's blasting out of the top of my head, but of course that isn't happening.
"Laryngeal tilt" is what's happening in the "Mid" and "Chest" voices. This video might clear up some things as well:
"Mixed Voice is Dead" by Robert Lunte:
Comment: Not everyone's ranges are the same. If you're singing in modal voice through B5, you have an unusually high modal range. I'm a trained tenor 1 and my modal voice cuts out at B4. Many basses and baritones can't sing an E4 in modal voice. Tenor C, C5, is considered to be around the top of a typical tenor's useful range (including head voice).

If you are actually singing modally nearly an octave above me, you're probably a true countertenor, which is impressive, but not typical, and should definitely not be used as an example of a typical male range.
Comment: Middle C is C4, the C above it is C5, and F5 is another perfect 4th above that. ("On top of the treble clef" is a little less useful than it might seem, as in choral music, the Tenor part is written an octave above where it sounds, so that can refer to F4 or F5, depending on the context).

I've never met a tenor with chest voice up that high. I know they exist, but it's rare, and should definitely not be taken as typical. Also, be very careful... if you're doing anything that could be described as "straining", you could be hurting yourself. That's not part of your useable range at tat point.
Comment: It's a strain starting at around D5; I'm also not a classically trained singer. Perhaps we're not using the same notation. When I refer to F5 I mean the F sitting on top of the treble clef (or "Fine" in Every Good Boy Does Fine). Middle C is C4 -> https://www.youtube.com/watch?v=FtqgqYRDTDg I'm guessing you can sing higher than that in Chest. If not then we have wildly different training sets. I learned a lot from Robert Lunte's program.
Comment: Sure, I'm also trained in rock/pop singing, so I'm familiar with that trend. Keep in mind that "chest voice" and "head voice" are described not by what it sounds like, but by how the vocal cords are vibrating, so would be the same across all styles, despite different sounds.
Comment: I agree Greg; my main point was that regardless of what's really happening it's more important what it "feels like".. but that's correct.
Comment: I should also add that classical singing is a strict Chest tone because it sounds fuller, and higher tones are simply sung by a female in their normal range- everyone in a booming Chest voice. Modern rock, metal etc. uses mics and effects that help create the illusion that singers are singing high notes in Chest. It's affected to sound like Chest but it's a Head tone.
Answer: That clip of Robert is not really demonstrating the mixed voice.  What he does is "twang in the head" which basically is singing in a disconnected falsetto and making it "sound like" your real voice by using deeper vowels and lots of reverb.
To whoever mentioned blowing air as you ascend.  You don't achieve mixed voice by blowing more air, in fact it's the opposite.  As you sing higher you want to resist the air more to create breath compression.  If your folds are strong enough, they will resist this air and give you more power.  When you blow air and let the cords open up you are moving closer to falsetto.
Training yourself to blow more air as you sing higher only takes you away from your real voice, puts you closer to falsetto and risks damaging your voice as excessive breathiness is what causes hoarseness, lack of ping in the sound and lack of power.
I have written a big article on the registers, mixed voice etc you can check it out here:
http://www.grow-the-voice.com/free-singing-tips/
Answer: A falsetto is not in any conceivable meaning defined by being "forced", and there is no useful singing voice where the perceived resonance (what some voice types are named after) would be in the throat.
Basically you are throwing around words in the hope that they mean something you can read up upon using the internet.  But in the internet you have no guarantee of consistent terminology between two articles from people who know what they are talking about, and consequently no guarantee of consistent terminology in even a single article that is more likely than not a melange of distributed knowledge and half-knowledge from different places.
Even when you get a serious anatomically correct book about singing, there is no guarantee that it will converse in the same terms as any given vocal teacher or student.
Don't rely on hearsay for your vocal health.  It's like learning watch repair on your own: more likely than not you'll already damage a watch when trying to open it.  Even the worst repairmen have enough of a clue to avoid most inadvertant damage from forcing things where it does not help at all.
A voice tends to be comparatively robust and not easily damaged unless you convince yourself that stuff that neither works nor sounds nor feels great is as it should be and just piling on more of the same will make it work.  And angling for half-knowledge is half the road there.
Watches are possibly less forgiving when you try forcing something you shouldn't.  But watches can be replaced, chalked off as probably unnecessary learning cost.  Your voice not.
So if you are finding yourself collecting a hotchpotch of advice fragments from the internet, you may even be better off trusting your own feeling instead.  But it will be more useful to get an actual teacher to listen to you.
Comment: I don't think the lecture is terribly helpful. The guy is asking what seems to be a valid question. Besides, the whole point of this site is to provide 'information from the internet' ;-)


GARCH diagnostics via standardized residuals: interpreting my findings

Question: I have fit a GARCH(1,) model in Python, assuming the residuals are $t$ distributed. I am checking the standardized residuals. ARCH and Ljung-Box tests don't reject the null hypothesis. However, I am having trouble understanding the behavior of the graphs.
The first graph displays the distribution of standardized residuals. As you can see it is not normally distributed.

The second one is the QQ plot.

The last one is a scatter plot of standardized residuals versus estimated volatility.

How do I interpret these graphs of standardized residuals?
Answer:
"As you can see it is not normally distributed." + "I assumed that the residual of the GARCH are t distributed." = What problem do you see in that? I do not see any.
For the second plot, what reference distribution did you use? You should have used Student's $t$ distribution. If you did, you see it is not a great match at the left tail. You probably need an asymmetric distribution (skewed Student's $t$? Johnson's $S_U$?) to fix that. But actually it is easier to just study the probability integral transform of the standardized residuals. For a statistically adequate model, it should be Uniform[0,1] regardless of what distribution you have assumed for the standardized innovations.
I am not sure the third plot is all that informative. I am not used to seeing it as part of GARCH diagnostics.
Comment: @Mattia, you are welcome!
Comment: thank you so much for your replies!!


Load a variable displayed in devel

Question: I'm using devel to find specific fields I'd like to be able to access in a template I have for a user profile page (user-profile.tpl.php)
The field values are present in devel just fine however I'm not sure what to do with the path it gives me.

I see the info I need, (created = 1349810890)
and I see a path that devel has given me $...->created but I'm not sure what to replace $... with to get access to that field.
I've attempted the following
<code>$node->created;
$page->created;
$user->created;
$node['created'];
$content->created;
$variables->created;
$variables->node->created;
</code>
And several others with no luck
Answer: Are you operating on the user account object?
If so, it should be:
<code>$variables['account']['user']->created;
</code>
Which would be used at the template_preprocess function level. From the actual template itself, unless you have intimate knowledge of what was passed to $variables, you will sit there and guess all day long and not get far. Even I am guessing. The only way to know exactly what you have to work with is by using a real debugger.
The best option is implementing a debugger like xdebug so you can get a better idea of whats going on.

Atom has a package: https://atom.io/packages/php-debug
PHPStorm is
simple to setup: https://www.youtube.com/watch?v=jkv0dzW3IM4

It will save a lot of time if you leverage it over devel. You can then set a breakpoint in your template_preprocess function in template.php, inspect all the variables being passed to that appropriate template, and print or modify as you need.

Load a variable displayed in devel


calling a javascript function in onClick

Question: When i deploy my code it gives me an error:
saveRows is not a function
So what's wrong ?

dataGrid.prototype = {
      display: function() {
        var self = this;
        var html = [];
        var check = 0;
        var lastSelection;
        html.push("
");
        html.push("<input class='btn btn-default' type='button' value='Save All Rows' onclick='saveRows()'' />");
        html.push("
\n
");
        html.push("

");
        html.push("
");
        $('body').append(html.join(""));
        $("#" + this.id).jqGrid({
          // ...
        });
      },
      // ...
      saveRows: function() {
        var ids = $("#" + this.id).jqGrid('getDataIDs');
        for (var i = 0; i < ids.length; i++) {
          $("#" + this.id).jqGrid('saveRow', ids[i]);
        }
      }
    };

so any other suggestions ??
Comment: Shouldn't it be `onclick='saveRows()'`instead of `onclick='saveRows()''` (with two `'`) ?
Comment: and try `dataGrid.saveRows()`
Comment: typo error sorry .. but still the same problem remains
Comment: @TimB still the same
Comment: You post fragments of JavaScript code only, which are difficult to follow. Do you have some working demo online to see what you try to implement? I'd recommend you to make more changes in your code to simplify other code. First of all the usage of `onclick='saveRows()'` is bad way. It's better to use `beforeSelectRow` to process onclick event *on any cell of the grid*. It's important to know which version of jqGrid you use and from which fork of jqGrid.
Comment: @HugoS.Mendes  the function is not called when debugging
Comment: If you use `onclick='saveRows()'` then `saveRows` must be global function. It `dataGrid` global or `$.dataGrid.saveRows` is global or ... then you can use full path to access it. If you would use `beforeSelectRow` then the problem will not exist. If the button is **outside of the grid** then you can add id to `` and use `$("#theId").click(function () { alert("Cllicked");})` instead.
Comment: The html you append to the page has no context to `saveRows()`. Where's the context? It can't magically infer that you mean the instance of the data grid that created it without being explicit.
Comment: @Oleg what is beforeSelectRow  ?? .. sorry but i am beginner
Comment: @dinaosama: It's the callback function of `jqGrid` which could be placed in the part between `$("#" + this.id).jqGrid({` and `});` Look at [here](http://stackoverflow.com/a/31647943/315935) or [the demo](http://jsfiddle.net/OlegKi/HJema/190/) created for [the answer](http://stackoverflow.com/a/32951019/315935)
Comment: @dinaosama check my answer and the fiddle.
Answer: You can try this
$('body').on('click','#yourButtonId',function(){
    saveRows();
});

Answer: You can change
<input class='btn btn-default' type='button' value='Save All Rows'
       onclick='saveRows()'' />

to
<input id='mysave' class='btn btn-default' type='button' value='Save All Rows'/>

and to use
$("#mysave").click(function () {
    // any code executed on click on the button
});

Answer: The saveRows function is part of the dataGrid prototype. It is therefore not defined as a global function - and cannot be defined as an onclick handler in plain HTML.
You could solve your issue by creating the DOM elements using jQuery, instead of HTML strings, and directly bind the onclick callback. For example (untested):
$(body).append(
    $('
').style('margin-left', '20px').append(
        $('<button/>', {
            'class': 'btn btn-default',
            'text': 'Save All Rows'
        }).on('click', function () {
            self.saveRows();
        }),
        $('
', {
            'id': self.id,
            'class': 'table'
        }),
        $('
', {
            'id': 'pager_' + self.id
        })
    )
);

Answer: change this:
html.push("<input class='btn btn-default' type='button' value='Save All Rows' onclick='saveRows()'' />");

to actually an object:
var theInput = $("<input class='btn btn-default' type='button' value='Save All Rows'>");
    $(document).on("click", theInput, function(){self.saveRows()});

and then, add it to the html array.
html.push($(theInput)[0].outerHTML);

https://jsfiddle.net/atg5m6ym/3524/


How to prove there's an upper bound on a series

Question: There's a series as following.
$$
\sqrt{3}, \sqrt{3 + \sqrt{3}}, \sqrt{3 + \sqrt{3 + \sqrt{3}}} + \cdots
$$
Is there any way I can find the upper bound to prove the limit exist?
I've tried to write down the formula of this series as following:
$$
x_n = \sqrt{3 + x_{n - 1}}
$$
but still find no way to modify it to get to the upper bound.
Comment: More similar questions: https://math.stackexchange.com/questions/linked/115501
Answer: Hint : Show inductively that all the terms are bounded by $$\frac{1+\sqrt{13}}{2}$$


two binomial distributions of widely different size - confidence intervals, p-values or z-scores?

Question: I was hoping for a bit of help.
I have two very different sized samples of binomial distribution, and I want to figure out if they are significantly different. A previous question posted on here has been helpful, but the answer is different from what I have been advised + I have the added complication of widely different sized samples, so I was hoping to get a bit more input.
An example of the two samples:
<code>Group 1: Successes = 10000, Trials = 40000
Group 2: Successes = 150000, Trials = 3500000
</code>
Like the previous posted question, I have no predicted probability of success.
My first approach had been using Chi-squared (producing a nice familiar p-value).
However, I was told that I should use a binomial test of proportions, due to the widely different sample sizes. I should use the larger sample (group 2) as my control, and then create confidence intervals for group 1 to see if they capture the control.
Nevertheless, reading around the topic, it appears statistical hypothesis testing is potentially more appropriate (and again the linked question has that as the proposed answer), thus making use of a z-score. But I'm unsure if my samples meet the requirements for a normal distribution (although large enough, they do not have proportions near 0.5).
So what should I use? I feel like I'm back to chi-squared, but I don't feel confident enough to simply discard all the points above.
Answer: $\chi^2$-test on a 2x2 contingency table is completely equivalent to proportion comparison, so go ahead with the approach you understand better.
Check https://www.dummies.com/education/math/statistics/how-to-compare-two-population-proportions/ for a quick review on how to compare proportions.
On the $\chi^2$-test of independence: https://www.statisticssolutions.com/non-parametric-analysis-chi-square/
Anyway, if the data looks like that you presented, you don't even have to do the math! There is statistically significant difference with a p-value of virtually 0!
Comment: Excellent thanks! and I know what you mean, my data really looks like this and it feels silly when it's obviously different, but a significant p-value makes everyone sleep safely at night.


How to import Ant Design css styles in GlobalStyles of styled-components.?

Question: How i can make an import of antd.css in styled-components? instead of App.css
@import '~antd/dist/antd.css';

The whole purpose is, i want my GlobalStyles from styled-components by default to have all Ant Design styles.
And when i will use elements from AntD it will have all default classes on it.
Answer: You shouldn't.

NOTE: At this time we recommend not using @import inside of createGlobalStyle. We're working on better behavior for this functionality but it just doesn't really work at the moment and it's better if you just embed these imports in your HTML index file, etc.

Altought you can try:
import { createGlobalStyle, css } from 'styled-components';

const antdCss = css`
  ${import('antd/dist/antd.css')}
`;

const GlobalStyle = createGlobalStyle`
  ${antdCss}
`;

export default GlobalStyle;

Comment: Nice answer. One comment, it should be `${require('antd/dist/antd.css')}` instead of `${import('antd/dist/antd.css')}` at least in a TypeScript project


Counting Weeks by Monday using DATEPART

Question: I am trying to track orders per week using this simple query, where the week starts on Monday. The issue is, while the count is correct, all the weeks are one up (week 1 is displayed as 2 etc)
SET DATEFIRST 1;
SELECT DATEPART(yyyy,[ORDER-DATE]) as Year, DATEPART(wk, [ORDER-DATE]) as Week, count(*) as Count from PAYMENTS
    where [ORDER-DATE] >= '2022-01-03' and [ORDER-DATE] <= '2022-01-31'
    group by DATEPART(yyyy,[ORDER-DATE]), DATEPART(wk, [ORDER-DATE])
    order by DATEPART(yyyy,[ORDER-DATE]), DATEPART(wk, [ORDER-DATE]);

The output looks like this:
Year    Week  Count
2022    2     25
2022    3     15
2022    4     19
2022    5     31

Now, the first week count is correct (25 payments between January 3rd and January 9th, 2022). However it's showing that as week 2. Weirdly enough, if I run the same query for 2019 (start date being 2019-12-30) it actually works as expected and week 1 is displayed and accurate!
If I change the first queries date to start on "2022-01-01" instead of "2022-01-03", it shows week 1 as only being January 1st and January 2nd (weekend).
EDIT:
The desired result is like follows:
Year    Week  Count
2022    1     25
2022    2     15
2022    3     19
2022    4     31

Comment: Why would you type `yyyy` when you could type `year`? And why not just write `week` instead of `wk`?
Comment: Please provide sample data and desired results which illustrates the problem.
Comment: We also need sample data i.e. the data that will produce those results.
Comment: Anyway just create a calendar table if built-in week definitions don't work for you. https://www.mssqltips.com/sqlservertip/4054/creating-a-date-dimension-or-calendar-table-in-sql-server/?utm_source=AaronBertrand
Comment: @Dalek I added my desired result to the main post. Basically, Week 1 of 2022 is January 3rd to January 9th (Monday starts week). However, my output is setting Week 1 as January 1st and 2nd (Weekend, not monday). So the query output starst on week 2
Comment: Whats wrong with yyyy and wk?
Comment: yyyy and wk are documented abbreviations (aliases) for year and week, so technically there is nothing wrong with them as long as they match your intent. As a matter of style and readability, some prefer using the primary keywords from the documentation.
Comment: @DaleK I don't know how to produce those results, that's the problem. I want Week 1 to start on Monday January 3rd, 2022 and not Saturday Jan 1st, 2022. That's all
Comment: I understand, but we need to see the data you are attempting to use to produce those results, i.e. the data you are querying. (Made up of course to reproduce the issue).
Comment: There's nothing technically wrong with `yyyy` I guess, but if you're going to type four letters anyway, why not type four letters that spell the actual word that explains what you mean? https://sqlblog.org/2011/09/20/bad-habits-to-kick-using-shorthand-with-date-time-operations
Answer: Year 2022 started on a Saturday. SQL Server DATEPART() always treats January 1 as week 1. With SET DATEFIRST 1, Monday 2022-01-03 becomes the start of week 2.
If you don't care about weekends, perhaps you should redefine your weeks as Saturday through Friday. This can be done with SET DATEFIRST 6.
See this db<>fiddle.
Comment: The DATEPART function is operating as designed. If that doesn't suit your needs, you can always calculate an adjustment. `DATEPART(week, [ORDER-DATE]) - CASE WHEN /* year start on a weekend */ THEN 1 ELSE 0 END` or define your own function.
Comment: I suppose setting datefirst as 6 basically works as I want. Thank you
Comment: SET DATEFIRST 1 already sets the start of the week as Monday, I do care about weekends. I just don't consider January 1st and January 2nd as Week 1 like the query is suggesting. Week 1 of 2022 should start on Monday (January 3rd) until Sunday January 9th
Comment: (Sorry I missed that you already had SET DATEFIRST 1. I have edited my original answer and updated the fiddle to reflect that.)
Comment: Another consideration (that may not be obvious for 2022) is what you need to do when the year starts mid-week. Will you need to report the entire week together as either the last of the year-ending or the first of the year-starting? If so, you may need further customization of both your rear and week calculations.

Counting Weeks by Monday using DATEPART


Code design. Multicast delegate to the rescue?

Question: I'm currently struggling with a design issue and I'm looking for some advice :)
Imagine I have a collection of INotificationHandler objects and the interface is defined as follows:
public interface INotificationHandler
{
    void Notify(string message);
}

Now I want to call Notify(...) for each INotificationHandler instance. I thought of using a multicast delegate for that. However only recently I stumbled across a piece of code where expression trees where used for a similiar task (I imagine)... unfortunately I cannot remember where I saw that piece of code :(
My key concern is performance as this type of method call would occur quite frequently.
As this runs in a web application context, can I be sure every instance's method was called?
The ultimate goal is to have one single "wrapper" class to invoke all other instances of a certain interface type. I thought about applying this to logging as well...
    ILogger dispatcher.Trace(...)  // does nothing itself, only calls other existing ILogger instances.
    --> calls NLogLogger(:ILogger).Trace(...)
    --> calls SomeOtherLogger(:ILogger).Trace(...)
    --> calls SomeOtherLogger2(:ILogger).Trace(...)
    --> calls SomeOtherLogger3(:ILogger).Trace(...)

My motivation to do something like that is to implement a NullObject pattern where I can be sure that any call to my ILogger (which will always be my delegating dispatcher class) will succeed. And secondly the number of living ILogger instances will vary depending on application configuration.
Any feedback is very appreciated :)
Btw.. is there any known pattern for this? Couldn't think of one...
Comment: did you look at the reactive extensions? http://msdn.microsoft.com/ru-ru/data/gg577609.aspx
Comment: If you want to do it just for logging consider instead using existing configuration system for logging you are using - most logging libraries allow multiple listeners already, wrapping it with another layer of interfaces is fun but feels wasteful. Otherwise you should be able to generate IL on the fly (or delegates/expressions) to call each method of interface you are wrapping.
Comment: Take the .NET INotifyCollectionChanged interface as a guiding example.  Note how its CollectionChanged member is an *event*, not a method.
Answer: You may want to take a look at the Mediator design pattern.
You can register a callback for a given message:
Mediator.Instance.Register(callback, message);

And then when you notify a given message all the registered callbacks are called:
Mediator.Instance.NotifyColleagues(message, parameters);

Here is an example using Action<object> delegates, but it is more recommended to use WeakReference instead of delegates to ensure garbage collection.


Are all adjoints lattice homomorphisms?

Question: Obviously something must be wrong in the following reasoning proving that any linear operator $T:X\to Y$ between Banach lattices has a lattice homomorphic adjoint: $\forall a,b\in E':$
$$T'(a\wedge b)=(T'a)\wedge(T'b)$$
if and only if $\forall x\in E:$
$$(T'(a\wedge b))x=((T'a)\wedge(T'b))x$$
if and only if (by definition adjoint)
$$(a\wedge b)T x=((T'a)\wedge(T'b))x$$
if and only if (by definition $\wedge$ on dual $E'$)
$$(a T x)\wedge(b T x)=((T'a)x)\wedge((T'b)x)$$
if and only if (by definition adjoint)
$$(a T x)\wedge(b T x)=(a T x)\wedge(b T x)$$
which is always true (and the same logic holds for $\vee$). Is this correct?
Comment: I'm not very familiar with Banach lattices, but your "definition" of $\wedge$ on $E'$ seems very suspect...the pointwise meet of two linear functionals will usually not be linear.
Comment: @EricWofsey You are right, thank you! I will post the definition as an answer.
Answer: The definition of the lattice structure on the dual is (see [1], Proposition II.4.2):
$$(a\wedge b)(x)=\sup\left\{f(y)+g(z):y+z=x,y\geq 0,z\geq 0\right\}$$
which is not the 'pointwise meet' as I assumed in the question.
<code>[1] Banach Lattices and Positive Operators, Schaefer
</code>
Comment: This is still not the correct definition.  You need also to assume that $y \ge 0$ and $z \ge 0$.  Also note that there are many Proposition 4.2's in the [cited book](http://link.springer.com/book/10.1007/978-3-642-65970-6); it seems that you mean Proposition II.4.2.

Are all adjoints lattice homomorphisms?


Sybase cursor for delete

Question: In sybase, using a cursor can one delete the currently referenced row?
If so what does the cursor end up referencing?
Comment: Why use cursors at all? They are slow and never have to be used (there are always work-arounds). Set-based deletes are faster and much more efficient.
Answer: From manuals.sybase.com - Updating and deleting rows using cursors:
Using the where current of clause of the delete statement, you can delete the row at the current cursor position. When you delete a row from the cursor's result set, the row is deleted from the underlying database table. You can delete only one row at a time using the cursor.
After you delete a row from a cursor, Adaptive Server positions the cursor before the row following the deleted row in the cursor result set. You must still use fetch to access that next row. If the deleted row is the last row in the cursor result set, Adaptive Server positions the cursor after the last row of the result set.

Sybase cursor for delete


What makes 'Drop 2, Drop 3' in chord nomenclature?

Question: Occasionally, 'Drop x' is used to clarify chord voicing. I guess it's a more focussed way of explaining how notes of a chord are voiced. Certainly more specific than 'inversions', which only specify what the lowest note is.
What is the ruling behind 'drop x', how important is it in our playing, and where did it come from originally?
Answer: Start from an assumption that the 'normal' construction of a chord is to have all the notes as close as possible - basically a 'pile of 3rds'.    Take the second-highest note, drop it an octave.  That's Drop 2 voicing.   Third-highest - well, you get the idea!
Drop 2 fits the layout of a guitar rather well.  Here's a nice discussion of it in guitar-specific terms:
https://www.guitarlessonworld.com/lessons/drop-2-chords/
On keyboard, or when arranging for other instruments - e.g. a 5-piece sax section - open voicings are very common.
Comment: Any ideas who started it?
Comment: Isn't it more "when did music get dumbed down to 'chord sequences' and an assumption that anything other than a close-position voicing was unusual"?
Comment: Not sure (at all) that 'chord sequences' are 'dumbing down', and never really considered close-voicing was any more un/usual than open. I just play what I think will sound best in each circumstance, but with 'drop x', that's being stipulated.
Comment: @LaurencePayne Music being simplified to favour close-position voicings and *then* getting named as such is one way to look at it. An alternative hypothesis is that theorists named the close position voicings because the open ones happen to be harder to taxonomize, and then music followed suit. Not sure if it is known which angle is true though.


Is it possible to use a TXT record for CAA (Certification Authority Authorization)

Question: My domain name provider doesn't allow CAA records in their DNS editor for some reason. When I mailed them about it they said I could just use a TXT record instead. After a good hour of Googling this appears to have been incorrect. I can't find any information about using a TXT record for this. I have even skimmed through the RFC and I can't find any mention of TXT records.
Is a TXT record commonly supported for CAA, or was my domain name provider straight up wrong about that?
Answer: "Never attribute to malice that which is adequately explained by stupidity."
I would guess that your domain provider didn't purposefully lie to you so much as misunderstand what you were asking for because they didn't know what a CAA record was. They probably saw the word certificate somewhere in the conversation and assumed you were talking about the validation records you might need to create to prove domain ownership.
In any case, no. You can't use a TXT record in place of a CAA record to limit which CAs are allowed to issue certs for your domain.
If you like your domain registrar, you can likely move just the DNS hosting to another provider that supports CAA records. Or if this is the proverbial straw that broke the camel's back, transferring to a different registrar is also an option.
Comment: Yeah I was probably just a bit grumpy after wasting my time :P I edited the question to sound less harsh. Thanks for your answer.


Node ends with error Exit status 3221225786

Question: Good day everyone!
On package.json, I have a line under scripts that reads "serve": "node index -test". If I run node index -test directly in the Node command prompt, the error doesn't occur. If I run npm run serve, which is suppose to do the same thing, the error occurs when I stop the process with Ctrl+C. Here's the log:
0 info it worked if it ends with ok
1 verbose cli [ 'C:\\Program Files\\nodejs\\node.exe',
1 verbose cli   'C:\\Users\\SOUSA\\AppData\\Roaming\\npm\\node_modules\\npm\\bin\\npm-cli.js',
1 verbose cli   'run',
1 verbose cli   'serve' ]
2 info using firstname.lastname@example.com
3 info using email@example.com
4 verbose run-script [ 'preserve', 'serve', 'postserve' ]
5 info lifecycle firstname.lastname@example.com~preserve: firstname.lastname@example.com
6 info lifecycle firstname.lastname@example.com~serve: firstname.lastname@example.com
7 verbose lifecycle email@example.com~serve: unsafe-perm in lifecycle true
8 verbose lifecycle firstname.lastname@example.com~serve: PATH: C:\Users\SOUSA\AppData\Roaming\npm\node_modules\npm\node_modules\npm-lifecycle\node-gyp-bin;C:\Alloy_Server_v3\node_modules\.bin;C:\Users\SOUSA\AppData\Roaming\npm;C:\Program Files\nodejs\;C:\Program Files (x86)\Common Files\Oracle\Java\javapath;C:\ProgramData\Oracle\Java\javapath;C:\Program Files\ImageMagick-6.9.3-Q16;C:\Program Files (x86)\NVIDIA Corporation\PhysX\Common;C:\Program Files\ImageMagick-6.9.1-Q16;C:\Program Files\ImageMagick-6.9.0-Q16;C:\Program Files (x86)\Common Files\Intel\Shared Files\cpp\bin\Intel64;C:\WINDOWS\system32;C:\WINDOWS;C:\WINDOWS\System32\Wbem;C:\WINDOWS\System32\WindowsPowerShell\v1.0\;C:\Program Files (x86)\ATI Technologies\ATI.ACE\Core-Static;C:\Program Files (x86)\git\cmd;C:\Program Files (x86)\Windows Live\Shared;C:\ProgramData\chocolatey\bin;C:\WINDOWS\system32;C:\WINDOWS;C:\WINDOWS\System32\Wbem;C:\WINDOWS\System32\WindowsPowerShell\v1.0\;C:\Program Files (x86)\GtkSharp\2.12\bin;C:\Program Files\Microsoft SQL Server\110\Tools\Binn\;C:\Program Files (x86)\Microsoft SDKs\TypeScript\1.0\;C:\Program Files\Microsoft SQL Server\130\Tools\Binn\;C:\Program Files\Git\cmd;C:\Program Files\PuTTY\;C:\Program Files\nodejs\;C:\Users\SOUSA\.cargo\bin;C:\NVPACK\gradle-2.9\bin;C:\NVPACK\jdk1.8.0_77\bin;C:\Users\SOUSA\AppData\Local\Microsoft\WindowsApps;C:\Program Files\Microsoft VS Code\bin;C:\Users\SOUSA\AppData\Local\Microsoft\WindowsApps;C:\Users\SOUSA\AppData\Roaming\npm
9 verbose lifecycle firstname.lastname@example.com~serve: CWD: C:\Alloy_Server_v3
10 silly lifecycle email@example.com~serve: Args: [ '/d /s /c', 'node index -test' ]
11 silly lifecycle firstname.lastname@example.com~serve: Returned: code: 3221225786  signal: null
12 info lifecycle firstname.lastname@example.com~serve: Failed to exec serve script
13 verbose stack Error: email@example.com serve: `node index -test`
13 verbose stack Exit status 3221225786
13 verbose stack     at EventEmitter.<anonymous> (C:\Users\SOUSA\AppData\Roaming\npm\node_modules\npm\node_modules\npm-lifecycle\index.js:283:16)
13 verbose stack     at EventEmitter.emit (events.js:182:13)
13 verbose stack     at ChildProcess.<anonymous> (C:\Users\SOUSA\AppData\Roaming\npm\node_modules\npm\node_modules\npm-lifecycle\lib\spawn.js:55:14)
13 verbose stack     at ChildProcess.emit (events.js:182:13)
13 verbose stack     at maybeClose (internal/child_process.js:957:16)
13 verbose stack     at Process.ChildProcess._handle.onexit (internal/child_process.js:246:5)
14 verbose pkgid email@example.com
15 verbose cwd C:\Alloy_Server_v3
16 verbose Windows_NT 10.0.16299
17 verbose argv "C:\\Program Files\\nodejs\\node.exe" "C:\\Users\\SOUSA\\AppData\\Roaming\\npm\\node_modules\\npm\\bin\\npm-cli.js" "run" "serve"
18 verbose node v10.1.0
19 verbose npm  v6.0.1
20 error code ELIFECYCLE
21 error errno 3221225786
22 error email@example.com serve: `node index -test`
22 error Exit status 3221225786
23 error Failed at the email@example.com serve script.
23 error This is probably not a problem with npm. There is likely additional logging output above.
24 verbose exit [ 3221225786, true ]

Things that I tried to no avail:

This answer
Running the node command prompt as administrator
Creating a new folder, copying source files there and running npm install

I have been looking for more information on this Exit status 3221225786, but after three hours I still can't solve the problem. Any help is much appreciated.
EDIT: the error also doesn't happen when I user the VS Code console. It only happens with the Node.js command prompt.
Answer: In case someone stumbles across the same error, the problem went away when I updated to Node 10.2.0 and NPM 6.0.1. So I guess updating, or maybe fresh installing, can solve it.


C# the type or namespace Bunifu could not found

Question: When I run C# GUI (Bunifu UI) project in debug mode, project runs fine. When I run the same project in release mode, the compiler shows so many errors, one of them being:
Error (cs0246) :the type or namespace name 'Bunifu' could not found (are you missing a using directive or an assembly reference?
Please help me fast I have very less time to submit my project.
Answer: Maybe you are missing an assembly reference? I have the same problem and solved.
In Solution Explorer, Right-click Reference,
click Add Reference, Browse the Bunifu's dll file and add into.
Remove Bunifu (if this exists) may help.
Answer: Right click on the solution,click clean than rebuild the solution.
or you should use full namespace path like using solutionName.projectName.yourClassName
Answer: The compiler treats Bunifu as a function which is not defined anywhere. This is why you get this error message. You forgot a uses clause, linking to the namespaces where Bunifu is defined.


RUBY-RAILS 4 UPDATE MODEL

Question: I want to update a model on my db. if an user checked the checkbox, it must not be appear again on the view.
I have some view like this:
<%= form_tag( riepilogo_path, method: "post", id: "sel") do %>

    <%= hidden_field_tag "sala", params[:sala] %>
  <%= hidden_field_tag "spectacle_id", params[:spectacle_id] %>

  <%= hidden_field_tag "num", params[:num] %>

    Numero

<% for posti in @postis %>

    <%= check_box_tag "posti_ids[]", posti.id %>
    <%=h posti.numero %>

<% end %>

<%= submit_tag "OK", id: "sub"%>
<% end %>

controller of Postis is something like so:
class PostisController < ApplicationController
 def index
    @postis = Posti.where(:stato => "unchecked" , :spectacle_id => params[:spectacle_id] , :hall_num => params[:sala])
  end

def posti_multiple
    @postis = Posti.find(params[:posti_ids])

   end
end

In the Posti's model i have attributes: spectacle_id, hall_num, seat(integer) and stato (:default => "unchecked").
When he submit, seats be load in posti_ids[]. I want to update stato of seats which are present in posti_ids from "unchecked" to "checked".
Comment: I try this: @postis.update_column(stato: "checked"), but i have error like so: undefined method `update_column' for #
Comment: It should be just `Posti.update_column(stato: "checked")`
Answer: As per your comment,you have tried to perform update_column on an Array.So is the error

undefined method `update_column' for # Array:0xb881584

Here @postis returns.You should be giving it like this
Posti.update_column(stato: "checked")

Comment: I have the same error with Posti.update_column(stato: "checked")

RUBY-RAILS 4 UPDATE MODEL


Como passar array php para javascript

Question: Estou com problema para passar o array $json[] para a o Javascript, será que alguém poderia me ajudar.
<?php
    include_once ('../conf/conexaoBanco.php');
    $mensagem = "";

    $stmt=$conectarBanco->prepare("SELECT * FROM orcamento");
   $stmt->execute();
   **$json = [];
   while ($row=$stmt->fetch(PDO::FETCH_ASSOC)) {
       extract($row);
       $json[] = (int)$quantidade;
   }**

?>

Orçamento Mensal

                    <canvas class="line-chart"></canvas>

Comment: E por que precisa passar um array do PHP para o JSON? Conhece os conceitos de Client-Side e Server-Side? Poderia [edit] sua pergunta e elaborar um [mcve]?
Comment: Anderson Carlos Woss preciso passar esse array para o Javascript para poder gerar um gráfico do Chartsjs com base nas informações do meu banco de dados. Sim conheço o conceito Client-Side e Server-Side, mais caso tenha alguma sugestão melhor fica a vontade para me informar pois estou aqui para aprender
Comment: Bruno, vc diz estar com problema para passar um array PHP para o JS, mas não explicou qual é o problema. Vc apenas disse que está com problema e colocou um código. Isso não ajuda muito em conseguir uma solução, pois não se sabe qual é o problema ou o objetivo disso.
Comment: Sam o problema que estou tendo é que não sei como passar o array $json[] para o atributo data do Chatsjs e já tentei de varias formas buscando pela internet só que nenhuma me da uma solução que eu consiga compriender como fazer esse procedimento
Answer: Enviar o Json do Php para o Javascript pode facilitar as coisas, em especial quando trabalhamos com arquivos em base64 usando JsonURL, já que as funções do PHP não tem suporte para isso e as strings precisam ser normalizadas (https://base64.guru/developers/php/examples/base64url).
Para facilitar, uma das soluções pode ser converter da seguinte forma:
$arrayJson = array(
  "nome"  => "joao",
  "idade" => 35
);

//codificar para Json (isso será passado para o Javascript)
$json = json_encode($arrayJson);

No Javascript você vai receber este valor normalmente (passando uma variável do Php para Js):

Answer: Aqui tem um exemplo com base no conteúdo que você informou:

<?php
$quantidade = [10, 15, 8, 5, 6, 9, 10, 7, 8, 11, 4, 5];
?>

Orçamento Mensal

  <canvas class="line-chart"></canvas>

Answer: Utilize a função json_encode para converter um valor PHP em uma representação JSON.

Pode ser qualquer valor PHP, exceto resource.

$json = [];
while ($row=$stmt->fetch(PDO::FETCH_ASSOC)) {
    extract($row);
    $json[] = (int) $quantidade;
}

$json = json_encode($json);

Em seu código javascript, basta printar a variável $json que já está em formato JSON.
data: <?php echo $json ?>,

Answer: Transform array and JSON using json_encode. In javascript get this JSON
const MyArrayJS = JSON.parse('<?= json_encode($myArrayPHP); ?>');

Como passar array php para javascript


How to create booking according to its pitch?

Question: I have a model pitch where i am fetching grounddetail_id. I want to show all the pitch available in the ground. How i can book pitch of ground..
grounddetails_controller.rb
class GrounddetailsController < ApplicationController

 before_action :find_ground, only: [:show, :edit, :destroy, :update]

def index
 @grounddetails = Grounddetail.all.order('created_at DESC')
end

def new
 @grounddetail = Grounddetail.new
end

def edit
end

def show

end

def create
  @grounddetail = Grounddetail.new(ground_params)
  if @grounddetail.save
   redirect_to @grounddetail
  else
   render 'new'
 end
end

def update
  if @grounddetail.update(ground_params)
    redirect_to @grounddetail
  else
    render 'edit'
  end
end

def destroy
  @grounddetail.destroy
   redirect_to root_path
end

private

  def find_ground
   @grounddetail = Grounddetail.find(params[:id])
  end

  def ground_params
   params.require(:grounddetail).permit(:name, :working_hours, :end_time, :address, :contact_no, :email, :number_of_grounds, :description, :featured_ground)
  end
end

routes.rb
Rails.application.routes.draw do

 devise_for :users
 devise_for :admins

 resources :grounddetails do
   resources :pitches
 end

 root "grounddetails#index"
end

model
grounddetail.rb
class Grounddetail < ActiveRecord::Base
 has_many :pitches, dependent: :destroy
end

pitch.rb
class Pitch < ActiveRecord::Base
 belongs_to :grounddetail
end

for now i just have pitch model and routes but in controller i am confused what to use. i can i book pitch of the ground. But for single ground i am able to book.
Answer: In the grounddetails#show action
def show
  @pitches = @grounddetail.pitches
end

Then in the groundetails/show.html.erb, you can just use <%= @pitches %> to display the pitches of that grounddetail.
Update:
#in the show.html.erb

<% @pitches.each do |p| %>
  <%= form_tag book_pitch_path(p) do %>
  #your attributes here
  <%= submit_tag "Book this Pitch" %>
  <% end %>
<% end %>

#routes.rb
post :book_pitch/:id, to: 'pitches/book_pitch', as: 'book_pitch'

#in pitches_controller.rb

def book_pitch
  #your actions here
end

Comment: i am fetching number of pitches from grounddetail ...i am able to show it from grounddetail but don't know how to create booking for a pitch of a ground.
Comment: @AbhiShetAacharYeah What do you mean booking? Do you want to create a form to book each pitch?
Comment: yes...booking for pitch and it should be booking from it grounddetail_id
Comment: @pravin how can i do it if i don't wanna do with pitches controller and model...i have number of pitch column in grounddetail model..


Construir um Array com o intervalo de datas

Question: Vou receber duas datas, Exemplo: 01/10/2017, 31/10/2017. Como posso criar um array com todos os dias entre essas datas.
Array = ["01/10/2017", "02/10/2017", "03/10/2017", ... ,"31/10/2017"]

Answer: A idéia aqui é acrescentar os dias à data usando data.setDate. Enquanto a data inicial for menor do que a final, irá sendo acrescentada e incluída no array. As duas funções extras são para manter as datas no formato brasileiro.

let d1 = toDate("01/10/2017"),
    d2 = toDate("31/10/2017"),
    intervalos = [];

intervalos.push( toString(d1) );

while ( d1 < d2 ) {
  d1.setDate( d1.getDate() + 1 );
  intervalos.push( toString(d1) );
}

console.log(intervalos);

function toDate(texto) {
  let partes = texto.split('/');
  return new Date(partes[2], partes[1]-1, partes[0]);
}

function toString(date) {
  return ('0' + date.getDate()).slice(-2) + '/' +
    ('0' + (date.getMonth() + 1)).slice(-2) + '/' +
    date.getFullYear();
}
Comment: Exatamente isto que eu precisava, estava com dificuldade de adicionar um dia quando mudava o mês, mas assim funcionou muito bem, Obrigado
Comment: De nada! Você pode marcar a resposta como aceita se lhe serviu @ErickZanetti


Meta website is starting to lose its purpose.

Question: The meta website associated to each stackexchange website is there to discuss things about the main website.
I see that this meta website is starting to turn into something else.
I admit I contributed to this "state" with these questions:

Funny / Useless / Horrible code from Magento Extensions
Let's make this fun(-ish)
Funny / Useless / Horrible code from Magento Extensions

In my defense, I tried to make it a little funnier for all of us. But now I realize my mistake and I will stop.
But lately I've seen some questions that should not be here that seams to me like hidden promotion (I don't want to say spam).

https://magento.meta.stackexchange.com/q/703/146
Who would like to participate in developing and maintaing a Blog Overflow Community Blog for Magento StackExchange
Are you a Magento Ninja? (Just for fun)
Teaching magento flow

My opinion is that we should stop posting or migrating this kind of questions in here.
Otherwise we risk turning this meta into a showcase / self promotion / sales channel.
Like I said, this is my opinion. I would love to see other views on this topic.
Comment: I agree about the promotion stuff. But still I love and thus would not ban a bit of general/overall fun (referring to the funny/useless/horrible code questions) here :)
Comment: Marius, in general I'm in favor of your suggestion.  The only caveat I'd add was #2 (which I submitted) which I believe was, at the time submitted, specifically relevant to a StackExchange Meta topic on the blogs being added when sites exited Beta.  It seems inevitable that SE is going to revisit features that are provided to full community sites and I feel that Meta is the appropriate place for those discussions & seeking volunteers for SE-related activities.  Blatant promotion of services doesn't have a place, though I kind of share your & Anna's perspective on injecting SOME levity here :D
Comment: http://magento.stackexchange.com/help/whats-meta "Meta Magento Stack Exchange is the part of the site where users discuss the workings and policies of Magento Stack Exchange rather than discussing the Magento e-Commerce platform itself. It is separated from the main Q&A to reduce noise there while providing a legitimate space for people to ask how and why this site works the way it does. Meta is for...

...Magento Stack Exchange users to communicate with each other about Magento Stack Exchange (asking questions about how the websites work, or about policies and community decisions)
Answer: Hm, I'm in favor. Makes it easier to get through the content posted here.
The rest can be posted on community.magento.com. They have several misc. channels.
Answer: I think we can remove if there are such question like spam but sometimes we dont need answer but its about discussion on some important topic and need input from experts on meta.
I am referring here question Teaching magento flow. Here users will come to know the proper way of learning magento and proper way to explain the magento system.
I agree that few questions are spams but not all. This is my personal views because we could post question in magento or meta if question is related to magento.


generating random numbers in C++ using TR1 /dev/random (resilient to <1 second runs)

Question: I would like to generate uniform random numbers in C++ between 0 and 1, in a way which does not use the standard rand() and srand(time(NULL)) method.  The reason for this is that if I run the application more than once within the same second of my clock, the seed will be exactly the same and produce the same output.
I do not want to rely on boost or OS/compiler specifics.  x86 can be assumed.
It seems as though an alternate way to do this is to use TR1 (I do not have C++11) and seeding with /dev/random in some way?
Right now I have this, but it still uses time(NULL) as a seed which will not work well within 1 second runs:
#include <iostream>
#include <tr1/random>

int main()
{
  std::tr1::mt19937 eng;
  eng.seed(time(NULL));
  std::tr1::uniform_int<int> unif(1, RAND_MAX);
  int u = unif(eng);
  std::cout << (float)u/RAND_MAX << std::endl;
}

Comment: As a platform-specific trick that only very slightly impacts code portability, if you are willing to assume that the target system has stack address randomization (common nowadays on desktop OSes), you only need to cast the address of a local variable to `uint_ptr_t` and use that as seed. Oh, and if you aren't 100% confident in it, you can xor it with any other methods you find, and the seed will be as good as the best one.
Comment: Ok, then see my answer here: http://stackoverflow.com/questions/7617587/is-there-an-alternative-to-using-time-to-seed-a-random-number-generation/7617612#7617612 If you want I can post it as an answer here as well.
Comment: Are you willing to use OS/compiler-specific functions?
Comment: I'd like to avoid this... I will be deploying this on various systems
Comment: How various? Are they still all x86?
Comment: i think x86 32-bit and 64-bit are reasonable assumptions
Comment: @Mysticial: That's still compiler-specific!
Comment: @OliCharlesworth I know, that's why I didn't make it an answer - but those two together should work on nearly all x86-targeting compilers. MSVC, GCC, ICC, etc...
Comment: wow, that worked out really nicely as a seed.  the entropy is good.  I think it's worth posting as an answer
Answer: Posting at request of the OP:
This is still somewhat compiler-specific, but will still work on nearly all x86-targeting compilers:
#ifdef _WIN32

//  Windows
#define rdtsc  __rdtsc

#else

//  For everything else
unsigned long long rdtsc(){
    unsigned int lo,hi;
    __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
    return ((unsigned long long)hi << 32) | lo;
}

#endif

int main()
{
  std::tr1::mt19937 eng;
  eng.seed( rdtsc() );    //  Seed with rdtsc.
  std::tr1::uniform_int<int> unif(1, RAND_MAX);
  int u = unif(eng);
  std::cout << (float)u/RAND_MAX << std::endl;
}

The idea here is to seed your random number generator with the rdtsc cycle-counter.
The reason why this works is because the rdtsc cycle-counter iterates at about (often the same) speed as the CPU frequency. Therefore, the chances of two calls to it returning the same value are extremely slim - thereby, making it an excellent seed for a RNG.
Answer: TR1 in [tr.rand.device] specifies a random_device class that generates unsigned ints from an implementation-dependent source. So the following should work, although I haven't compiled it myself:
int main() {
  std::tr1::random_device dev_random;
  std::tr1::mt19937 eng(dev_random());
  ...

In TR1, passing dev_random directly without calling it works and initializes eng's state more randomly, but in C++11 you have to wrap seed arguments into another class. Since calling the argument works in both libraries, I'd do that for maintainability, unless you have more demanding needs.
Comment: random_device is a function object, so `eng(dev_random())`
Comment: ah, indeed. Another TR1 vs C++11 difference.
Comment: Do note that there's no guarantee about _which_ random device you get from the `random_device()` constructor. It could be `/dev/random`, `/dev/urandom`, `rdtsc`-based, http://en.wikipedia.org/wiki/RdRand, or even another pseudo-rng. Implementations can define a string argument to the constructor that selects between the choices, but the default is supposed to be decent.
Comment: @Cubbi: Nope: the engines have both a constructor taking an integer, and a constructor taking a function object: "`X(g)` — creates an engine with the initial internal state given by the results of successive invocations of `g`." --[tr.rand.req] table 16.  This allows them to fill their entire state instead of just the first word of it. (Of course, it's possible that any given implementation hasn't implemented the whole spec.)
Comment: @Cubbi: Oooh. I didn't notice that this had changed. I'll change my answer to recommend calling the random_device on the theory that you only rarely need more than UINT_MAX possible different sequences, that's all the time()-based code provided anyway, and keeping the same source code between TR1 and C++11 is nice. Thanks!
Answer: Your problem is related to the way you seed the random number generator.  Obviously seeding with time(NULL) is going to produce the same PRNG sequence within that second when seeded.  This is the most common way to seed rand, but is unfortunately bad practice because of this very issue.  Not only that, I have read that it can cause bias in the results.
Note that EVERY PRNG will produce the same result if seeded with the same values.  So your problem is not related to the generator, more to seeding.
I asked a question about seeding on here just a few weeks back and was given a link to the following article which you may also find useful.
Good Practice in (Pseudo) Random Number Generation for Bioinformatics Applications
See the section on seeding or warming up the generator.
rand() is not the best random number generator, but is suitable in many cases provided it is properly seeded.  If you want something better where the repeat sequence is very large then there are some provided in that link.  Or use the TR1 based ones.  Personally, I'd go with more portable C++03 based code and steer clear of TR1.
Also consider Multiply with carry as an alternative PRNG algorithm.


Why the String permutation swap twice in the program?

Question: I recently learn the algorithm,today I am strained with a problem:why the swap function run twice in the string permutation recursive way? How can I understand it?Could you help me?
<code>public class Permutation {
    public static void swap(char[] str, int i, int j) {
        char temp = str[i];
        str[i] = str[j];
        str[j] = temp;
    }

    public static void permutation(char[] str) {
        if (str==null)return;
        permutation(str,0);
    }

    private static void permutation(char[] str, int begin) {
        if (begin == str.length) {
            System.out.println(Arrays.toString(str));
        } else {
            for (int i = begin;i<str.length;i++) {
                swap(str, begin, i);
                permutation(str, begin + 1);
                swap(str, begin, i);
            }
        }
    }

    public static void main(String[] args) {
        char[] a = {'a', 'b', 'c', 'd'};
        permutation(a);
    }
}
</code>
Comment: check this answer, especially the diagram https://stackoverflow.com/a/21843611/940923
Answer: <code>   for (int i = begin;i<str.length;i++) {
                swap(str, begin, i);
                permutation(str, begin + 1);
                swap(str, begin, i);
</code>
This code fragment calls the next recursion level with modified string, then restores string back
Comment: Why does first iteration swap element with itself? Why are we not starting with `i = begin+1`


How to add validate data search

Question: I am using laravel for this project, i'm newbie at laravel then i want to add validate data if there is true then go to pdf blade, unless the data is false or wrong (i don't know what is it call so i named it True and False, but i hope you understand what i mean)
there is code in controller method search pdf
$id = $request->id;
    $date = $request->date;

    $pegawai = DB::table('pegawais')
            ->where('id', $id)
            ->whereDate('date', $date)
            ->get();

    $pdf = PDF::loadview('pegawai_pdf', [
        'pegawai'=>$pegawai
    ]);

    return $pdf->stream();

and this is the output blade when i searched the data is true or exist
here
and this is the output blade when i searched but the data is false or not found data exist
here
fyi the data are fake data from seeder,
Answer: From your example, I will assume that you want to check if there is a result or not in $pegawai right? Then just count it.
if (count($pegawai) > 0) {
    // show your pdf output here
} else {
    // there is no data, do something here
}

Answer: to check this does not need to be a true false variable you can check this like this
if($pegawai){
 $pdf = PDF::loadview('pegawai_pdf', [
        'pegawai'=>$pegawai
    ]);

    return $pdf->stream();
}else{
    //show error here
}

Comment: it still didnt work in when im trying to get wrong data, it is still appear blank page pdf as before...

How to add validate data search


Prove by induction $\sum_{k=1}^n\left(1-\tfrac{1}{(k+1)^2}\right)=\tfrac{n+2}{2n+2}$

Question: How to prove this by induction?
$$\sum_{k=1}^n\left(1-\tfrac{1}{(k+1)^2}\right)=\tfrac{n+2}{2n+2}$$
Comment: @Ak Okay I will add my attempt in a few minutes, sorry about it
Comment: Kindly add what you've tried. Cause, we don't know who really has doubt and who wants us to solve their online exam paper.
Comment: Are you struggling with the base step, the inductive step or both?
Comment: Anyway, this formula looks very wrong. The left-hand side is asymptotic to $n$, the right-hand side to $\tfrac12$.
Answer: I think the problem should be a product on the left side:
$$
\prod_{k=1}^n\left(1-\dfrac{1}{(k+1)^2}\right)=\dfrac{n+2}{2n+2}
$$
rather than summation.
Now let's begin.
For $n=1$, it is obviously true.
Assume it is true for $n=p$. That is, $\displaystyle \prod _{k=1}^p \left(1-\frac{1}{(k+1)^2}\right) = \frac{p+2}{2 p+2}$ is already true. Now let's check $p+1$:
$$
\begin{aligned}
&\quad\prod_{k=1}^{p+1}{\left( 1-\frac{1}{\left( k+1 \right) ^2} \right)}
\\
&=\prod_{k=1}^p{\left( 1-\frac{1}{\left( k+1 \right) ^2} \right)}\times \frac{p^2+4p+3}{\left( p+2 \right) ^2}
\\
&=\frac{p+2}{2p+2}\times \frac{p^2+4p+3}{\left( p+2 \right) ^2}
\\
&=\frac{p+2}{2\left( p+1 \right)}\times \frac{\left( 1+p \right) \left( 3+p \right)}{\left( p+2 \right) ^2}
\\
&=\frac{p+3}{2p+4}
\\
&=\frac{\left( p+1 \right) +2}{2\left( p+1 \right) +2}
\end{aligned}
$$
Thus we finished the proof.
Comment: Would the downvoter care to leave a comment?
Comment: I am not the downvoter, I don't know who also downvoted my question!!
Comment: I upvoted your answer, thanks
Comment: This makes way more sense because in the limit, the left side diverges whereas the right side converges. Great catch.
Comment: @FFjet I've noticed quite a few valid answers to poor quality questions, such as PSQs (Problem Statement Questions), being down voted. Since your answer looks correct, the down vote may be due to you answering a PSQ. Also, I agree with Cameron Williams that noticing the problem should be using a product instead of a sum is a "great catch".
Answer: We have the following:
Base case: $k=1$
We have: $1-\frac{1}{2^2}=\frac{1+2}{2+2}=\frac{3}{4}$ which is correct.
Assuming this is true for $n$ such that $\sum_{k=1}^n\left(1-\tfrac{1}{(k+1)^2}\right)=\tfrac{n+2}{2n+2}$ is true, we need to show it is true for $n+1$ such that  $\sum_{k=1}^{n+1}\left(1-\tfrac{1}{(k+1)^2}\right)=\tfrac{n+3}{2n+4}$
We have $\sum_{k=1}^{n+1}\left(1-\tfrac{1}{(k+1)^2}\right)=\sum_{k=1}^n\left(1-\tfrac{1}{(k+1)^2}\right)+ 1-\tfrac{1}{(n+2)^2}=\tfrac{n+2}{2n+2}+1-\tfrac{1}{(n+2)^2}\neq \tfrac{n+3}{2n+4}$
Which means your preposition is wrong and this can't be proven.


What are the conclusions we can draw from Kleene's Recursion Theorem regarding computability?

Question: Kleene's Recursion Theorem in his Introduction to Metamathematics $\S66$ is written

Theorem XXVI:
  For any $n\geq0$, let $\textbf{F}(\zeta;x_1,...,x_n)$ be a partial recursive functional, in which the function variable $\zeta$ ranges over partial functions of $n$ variables. Then the equation
  $$\zeta(x_1,...,x_n)\simeq\textbf{F}(\zeta;x_1,...,x_n)$$
  has a solution $\phi$ for $\zeta$ such that any solution $\phi'$ for $\zeta$ is an extension of $\phi$, and this solution $\phi$ is partial recursive.

After proving this he very briefly discusses how this theorem supports Thesis I (Church): Every effectively calculable function is general recursive.
My question is: In w does this theorem support Church's thesis?  What might be a good example of an effectively calculable function using ordinary language which through Theorem XXVI is shown to be partial recursive?
Answer: The theorem you quote says, essentially, that the class of "partial recursive" functions is closed under general recursive definitions. ($\mathbf F$ serves as a defintion of $\phi$ in terms of itself, that is, a general recursive definition).
This sounds somewhat tautological, but I assume that "partial recursive" at this point already has a meaning that has been defined without allowing general recursive definitions.
Church's thesis states that there is a natural class of functions that we ought to call "effectively calculable", in the sense that a wide range of attempts to formalize "effectively calculable" functions turn out all to define this class.  Whenever we investigate a new proposal for formalizing "effectively calculable" and find that it gives us the same class as before, that's a measure of support for the general thesis.
In this case, I think the idea is that we have already tentatively identified the "partial recursive" functions as the effectively calculable ones. Now we're considering this class of functions

Everything that we already allowed for "partial recursive" functions is allowed, and in addition you can use general recursive definitions.

The theorem then shows that this gives you exactly the partial recursive functions once again. So this is one of the many equivalent ways to define "effectively calculable", supporting the thesis that there are many such ways.

Since the point is that the new form of definition does not increase the expressive power, you can't get a function where you need this theorem to show it is partial recursive. But it can be a shortcut. For example, if we want to define Ackermann's function,
$$ A(m, n) =
\begin{cases}
n+1 & \text{if } m = 0 \\
A(m-1, 1) & \text{if } m > 0 \text{ and } n = 0 \\
A(m-1, A(m, n-1)) & \text{if } m > 0 \text{ and } n > 0.
\end{cases} $$
we can apply the theorem to the functional
$$ \mathbf F(\zeta; m, n) =
\begin{cases}
n+1 & \text{if } m = 0 \\
\zeta(m-1, 1) & \text{if } m > 0 \text{ and } n = 0 \\
\zeta(m-1, \zeta(m, n-1)) & \text{if } m > 0 \text{ and } n > 0.
\end{cases} $$
Since the $A$ we have defined (informally) above is clearly (?) the unique solution to $\zeta(\cdots)=\mathbf F(\zeta;\cdots)$ in this case, the theorem tells us that there is some way to define $A$ using the machinery already allowed for partial recursive functions (which is typically something like primitive recursion, plus successor, projections and composition, plus some kind of minimization or unbounded search operator). This definition might be complex and not particularly intuitive, however -- all the theorem tells us that it exists.
Comment: @BENG: Hmm, no, then I've got nothing.
Comment: I reread what you mentioned where you allow partial recursive functions as well as general recursive functions.  That is the class you are talking about, highlighted.


Python random.uniform not generate 0

Question: I want to use random.uniform to generate a float in between say [-2, 2], but not generate 0, this is how I do it in a loop,
from random import uniform

flag = True

while flag:
    if uniform(-2, 2) is not 0:
        flag = False

I am wondering is there better way to do it?
cheers
Answer: This is more something for Code Review, but very briefly:
from random import uniform

while True:
    if uniform(-2, 2) != 0.0:
        break

is probably the more Pythonic / standard way to do this (standard, as in that this pattern occurs in other languages as well).
It's rare that a flag variable is necessary to break out of a (while) loop. Perhaps when using a double loop.
Note: I changed your is not to !=, and your 0 to 0.0 (the latter is more so that it's clear we're comparing a float to a float).
Because you're comparing a float to an int, so they'll never be the same item. Besides, comparing numbers using is is a bad idea:
>>> 2*3 is 6  # this may work, but don't rely on it
True
>>> 10*60 is 600  # this obviously doesn't work
False
>>> 0 is 0   # sure, this works...
True
>>> 0.0 is 0  # but this doesn't: float vs int
False

Of course, to answer the actual question if there are other ways to generate those random numbers: probably a dozen.

With a list comprehension inside a list comprehension*:
[val for val in [uniform(-2, 2) for i in range(10)] if val != 0]

Using numpy:
vals = uniform(-2, 2, 10)
vals = vals[vals!=0]

* I don't want to call it nested, since I feel that belongs to a slightly different double list comprehension.

Python random.uniform not generate 0


Scroll to element IDs in mobile

Question: I am having issue with using skrollr on mobile. I have attached
id="skrollr-body"

to the html element (white screen and other odd behaviour if I attach it to body), which allows my responsive site to be scrolled. I have attached
s.refresh();

to any js function which changes an elements height so page height is always correctly figured out. This all seems to work nicely except I have two functions that should scroll to elements via their ID.
jQuery(".scrolldown").click(function() {
    jQuery('html, body').animate({
        scrollTop: jQuery("#article-bottom").offset().top
    }, 800);
});

jQuery(".scrollup").click(function() {
    jQuery('html, body').animate({
        scrollTop: jQuery("#article-top").offset().top
    }, 800);
});

These functions work nicely in desktop version but struggle in mobile (particularly going up to the top of the page). The scrolldown kind of works, in that the page will scroll down - but I notice that no transformations are occurring on the html element.
This means once I scroll down, I cannot scroll back up as the transformation is still at 0,0. I tried
jQuery(".scrolldown").click(function() {
    jQuery('html, body').animate({
        scrollTop: jQuery("#article-bottom").offset().top
    }, 800);
    s.refresh();
});

adding s.refresh() after (and before) the animation but I am stumped. I think these functions should be using transforms in mobile (like the main page) but I don't know if I am writing these functions correctly.
Answer: "These functions work nicely in desktop version but struggle in mobile (particularly going up to the top of the page)"
I'm not entirely sure what your question is asking specifically - but I believe what your talking about is the animation when scrolling around the page is choppy, or as you put it 'struggling'.
A general rule when working with mobile - CSS animations always win. This is because anything animated via CSS can take advantage of being hardware accelerated by the devices GPU. What this means is CSS animations look super smooth whereas the .animate() method is less reliable and often looks choppy.
While I don't have a code example to go with this - I do have a link which describes this in more detail and I believe it will put you in the right direction to fixing your "struggling" issues.
http://www.sitepoint.com/easily-improving-jquery-animations/
It talks about a nice JS lib called Velocity - https://github.com/julianshapiro/velocity
Add this small script to your site and replace all instances of ".animate()" with ".velocity()" and it should solve your problem.
Like I said I'm not sure this answer is what you're after due to the wording of your question. Hope it helps though.
Answer: I have fixed the issue. Firstly, I read the documentation. Secondly, I included skrollr.menu.min.js and added the code like this.
jQuery(".scrolldown").click(function() {
    jQuery('html, body').animate({
        scrollTop: jQuery("#article-intro").offset().top
    }, 800);
});

var s = skrollr.init({forceHeight: false});

skrollr.menu.init(s, {
    animate: true,
    easing: 'sqrt',
    scale: 2,
    duration: function(currentTop, targetTop) {return 800;}
});

Scroll to element IDs in mobile


How to convert the dateTime long into hh:mm:ss, dd/mm/yyyy format

Question: How can i convert the date-time which i have defined in java.Long to the format of 'hh:mm:ss, dd/mm/yyyy'. I get the output as Finishing-time = 1527666638657, where Finishing-time is in java.long. How can i convert this into 'hh:mm:ss,dd/mm/yyyy' format.
Thank you.
Comment: It sounds like you did exactly *no* research before posting this question.
http://idownvotedbecau.se/noresearch/
Comment: This question has been asked and answered a number of times before. Please use your search engine before asking and find a good answer even faster.
Answer: <code>public String convertTime(long time){
    Date date = new Date(time);
    Format format = new SimpleDateFormat("HH:mm:ss dd MM yyyy");
    return format.format(date);
}
</code>
Comment: Please don't teach the young ones to use the long outdated and notoriously troublesome `SimpleDateFormat` class. At least not as the first option. And not without any reservation. Today we have so much better in [`java.time`, the modern Java date and time API](https://docs.oracle.com/javase/tutorial/datetime/) and its `DateTimeFormatter`.
Comment: While your answer is correct simple code-pastes are discouraged. Add some explanation around it maybe to have a good answer. Also the format you are using is not similar to the one OP asked for.
Comment: @Ben ..updated but i don't think there is a need to explain the code, its already very simple and clear
Comment: Thank you all. Thank you for noticing so quick and asking me to search. Sorry i did search. Instead writing a long sentence and down voting, all i ask for help, maybe a link  would help which i couldn't find. So i can really be faithful. Thank you @hatched for taking your time and helping out.
Comment: Welcome to Stack Overflow, @user9630935. When you've searched in vain, please give this information in your question. Tell us what you've searched for and how the hits were unhelpful. You'll avoid the downvotes (most of them, at least) and you'll get help improving your search abilities. And probably even more helpful links than you got here.


Get length of Azure queue from Python via REST API

Question: Has anyone got an example of this?
This page describes the REST API function I'm trying to use:
https://learn.microsoft.com/en-us/rest/api/storageservices/get-queue-metadata
This page describes the authorization process. Unfortunately it doesn't seem to specify how to form the authorization string that would be suitable for the above API function:
https://learn.microsoft.com/en-us/rest/api/storageservices/authentication-for-the-azure-storage-services
Here's what I've tried. I get a 403 "Forbidden" response code:
import base64, datetime, hashlib, hmac, requests

account_name = 'account123'
account_key = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmn=='
queue_name = 'stuff-to-process'

resource = '/{}/{}?comp=metadata'.format(account_name, queue_name)
rfc1123date = datetime.datetime.utcnow().strftime('%a, %d %b %Y %H:%M:%S GMT')
x_headers = 'x-ms-date:' + rfc1123date
string_to_hash = 'GET\n\n\n\n' + x_headers + '\n' + resource
bytes_to_hash = bytes(string_to_hash).encode('utf-8')
decoded_key = base64.b64decode(account_key)
encoded_hash = base64.b64encode(hmac.new(decoded_key, bytes_to_hash, digestmod=hashlib.sha256).digest())

url = 'https://{}.queue.core.windows.net/{}'.format(account_name, queue_name)
headers = {
    'Authorization': 'SharedKeyLite ' + account_name + ':' + encoded_hash,
    'x-ms-date': rfc1123date
}

response = requests.get(url, params={'comp':'metadata'}, headers=headers, timeout=5)
print 'Response code was', response.status_code

Answer: I tried to reproduce the issue, and the error response below has shown the reason via print response.text.

<?xml version="1.0" encoding="utf-8"?>
<Error>AuthenticationFailed
  <Message>Server failed to authenticate the request. Make sure the value of Authorization h
eader is formed correctly including the signature.
RequestId:927f38e8-0003-0023-76ad-c84979000000
Time:2017-05-09T10:14:33.8632801Z</Message>
  <AuthenticationErrorDetail>Authentication scheme SharedKeyLite is not supported.</AuthenticationErrorDetail>
</Error>

The key is Authentication scheme SharedKeyLite is not supported. So please use SharedKey instead of SharedKeyLite in the request header Authorization of your code, then it works and you can extract the queue length value from the responce header x-ms-approximate-messages-count via response.header["x-ms-approximate-messages-count"]
Comment: Very useful info Peter. Many thanks. I will try what you say. But, the authentication docs I linked to say, "You may use Shared Key Lite authentication to authenticate a request made against the 2009-09-19 version and later of the Blob and Queue services". Are they wrong, or do I need to explicitly request a recent version?


Float over iframes html

Question: Is it possible to float a nav bar over a iframe here is the code that i have so  far?
the nav bar as you will be is in the html page and contains buttons that trigger the iframe to go to the next page etc.
Any ideas?
 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <title>Fraud Protection - Course</title>

     <input type="button" class="backbutton" id="butPrevious" onclick="doPrevious();" value="<- Previous"/>
        <input type="button" class="nextbutton" value="Next ->" img src="/images/Btn.PNG" id="butNext" onclick="doNext();"/>
        <input type="button" class="savebutton" value="Save Progress"  img src="/images/Btn.PNG" id="butExit" onclick="doExit();"/>

Answer: It's possible with position: absolute;
Answer: It is possible. You have to position the element to be floated, as absolute with negative margin.
Demo
Comment: @Teemu, margin is element dependent, if I do margin-top: -50px, It will go up from its original position, but if you do margin: 0; It will remain the same. But, in case of top, left, ..., top: 0; jumps the elements to the nearest relatively positioned element, by default its body.
Comment: Why not simply use position rules: `top, right, bottom, left`? Instead of setting some margin I mean, `position:absolute` is ofcourse needed.
Comment: top, and similar starts their positive from their nearest relative container, unlike margins, which is self dependant.
Comment: Basically i need the html page to float over the top of the iframe so that the iframe has 100% of the screen?

Confusing i know lol...
Comment: @Starx Please explain your comment. Margins are acting precise in the same way as top, left.. etc.
Comment: @Starx AFAIK, by default, positioned elements have a value `0px` set for `top` and `left`. Margins are calculated according this position.
Answer: Simple CCS for your nav bar:
.navDiv{
  position: absolute;
  top: 100px;
  left: 100px;
}

Just change the values for top and left as you need. In this case, these values are relative to document.body.
You have a misstypo in height-attribute for iframe in your code. Also it seems that percentage is not allowed for iframe height, you have to use some other unit instead.

Float over iframes html


Asp.net Core OpenIdConnect (OIDC) Where to Validate State Parameter

Question: Where is the suggested place to validate the state parameter in the OIDC middleware and possibly reject the request?
OnRedirectToIdentityProvider = (RedirectContext context) =>
{
    context.ProtocolMessage.State = "ENCODED_STATE_PARAMETER";
    return Task.CompletedTask;
}

Thanks,
Ruben
Comment: I recently blogged about the state and nonce parameter here:
* Demystifying OpenID Connect's State and Nonce Parameters in ASP.NET Core - https://nestenius.se/2023/12/13/demystifying-openid-connects-state-and-nonce-parameters-in-asp-net-core/
Answer: After digging around the OIDC source I found this solution,
options = new OpenIdConnectOptions()
// ...
options.ProtocolValidator = new MyOIDCProtocalValidator();

public sealed class MyOIDCProtocalValidator: OpenIdConnectProtocolValidator
{
    public MyOIDCProtocalValidator(): base()
    {
        // not sure if these are needed
        base.RequireState = true;
        base.RequireStateValidation = true;
    }

    protected override void ValidateState(OpenIdConnectProtocolValidationContext validationContext)
    {
        // validate state here
        // if(valid) do nothing
        // else throw new OpenIdConnectProtocolInvalidStateException();
    }
}


Probability, Uniform Distribution

Question: Every week a family visits their favourite restaurant. The restaurant has
15 tables, and on each visit the family is seated at a table chosen uniformly
at random, with all choices being independent. Show that the probability
is at least 1/2 that the family will sit at every table in the restaurant over
the course of a year.
Comment: What have you tried? (Or I will close this question.)
Comment: I am just not sure what is the right thing to do
Comment: I know the birthday problem, but that's to share the 2 outcomes instead of covering all outcomes
Answer: This is the coupon collector's problem with $n=15$ coupons. There is a bound on the probability that not all coupons are obtained after some multiple of $n\log n$ tries (weeks in this case):
$$P(T>kn\log n)\le n^{1-k}$$
If we set $k=1.27$ we get for this problem
$$P(T>51.588\dots)=P(T\ge52)\le0.481\dots<\frac12$$
which immediately proves the claim.

Probability, Uniform Distribution


Erro CORB/CORS ao requisitar api do google

Question: Tenho um projeto ionic-angular com servidor desenvolvido em nodejs. Estou tentando fazer uma autenticação de usuário enviando uma request para a api do google através do framework Passport utilizando a Google-Strategy.
Ao fazer a requisição, o seguinte erro acontece:
"Failed to load https://accounts.google.com/o/oauth2/v2/auth?response_type=code&redirect_uri=http%3A%2F%2Flocalhost%3A3000%2Fuser%2Fgoogle%2Fredirect&scope=profile&client_id=976813214537-0a1kl69viqpgg5ibtcgt743secpsmrld.apps.googleusercontent.com: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access. The response had HTTP status code 405"

No meu servidor, já estou concedendo permissão à todas as origens de requisição. Por isso, não consigo entender por que estou tendo este problema.
O problema parece acontecer por eu estar utilizando o browser para testar a aplicação através do comando ionic serve. Até já adicionei uma extensão ao chrome que concede permissão às origens, porém não resolveu meu problema.
Answer: Isso acontece porque antes da reuisição que você faz, é feita uma requisição "preflight" do tipo OPTIONS.
Esse problema pode ser corrigido nas configurações de CORS no servidor, mas quando você não tem acesso ao servidor, você pode usar um proxy.
Encontrei duas soluções que funcionaram:
1 - Usar o plugin HTTP
Instale o plugin:
ionic cordova plugin add cordova-plugin-advanced-http
npm install --save @ionic-native/http

Inclua no app.module.ts:
import { HTTP } from '@ionic-native/http';
...
providers: [
    ...
    HTTP
  ]

Na sua página.ts:
import { HTTP } from '@ionic-native/http';

const endereco: string = 'https://...'; //seu endereço

Component({
  selector: 'page-home',
  templateUrl: 'home.html'
})
export class HomePage {

  constructor(public navCtrl: NavController,
    private http: HTTP) {
    })

  }

  requisicao(){
    this.http.get(endereco, {}, {})
      .then(data => {
        console.log(data.data);
      })
      .catch(error => {
        console.log(error);
      });
  }

}

2 - Usar um proxy
Adicione um proxy antes do endereço que está tentando acessar.
Vi essa resposta em: No 'Access-Control-Allow-Origin' header is present on the requested resource—when trying to get data from a REST API.
Exemplo usando o HttpClient:
Inclua no app.module.ts:
import { HttpClientModule } from '@angular/common/http';
...
imports: [
    ...
    HttpClientModule
  ]

Na sua página.ts:
import { HttpClient } from '@angular/common/http';

const endereco: string = 'https://...'; //seu endereço

const proxyurl = "https://cors-anywhere.herokuapp.com/";

Component({
  selector: 'page-home',
  templateUrl: 'home.html'
})
export class HomePage {

  constructor(public navCtrl: NavController,
    private http: HttpClient) {
    })

  }

  requisicao(){
    this._http.get(proxyurl + endereco)
      .subscribe(
        (data) => {
          console.log(data);
        },
        (err) => {
          console.log(err);
        }
      );
  }

}

Comment: Na minha requisição, o ionic chama um "router" que está codificada no meu servidor nodejs e o servidor faz a requisição para a api do google. Em ambas as soluções que você me passou, a requisição é feita diretamente do ionic para a api do google, sem chamar o servidor beck-end. A resposta que você me passou faz todo o sentido, porém, como eu faço este procedimento para que a requisição seja feita pelo servidor? Pois lá está a Google-Strategy configurada para fazer a autenticação. Ficaria assim: Ionic -> servidor nodejs -> Api Google.
Comment: Você consegue incluir o proxy no seu servidor? Assim, o endereço de envio da requisição seria proxy + endereço do Google-Strategy.
Comment: Nunca fiz isto, mas posso pesquisar a respeito. Muito obrigado


Netbeans created a default constructor in c++. What does it do?

Question: Netbeans created this default constructor. I was curious what is its purpose. I don't know what to call it, or what it does. It more of a curiosity. My only thought was maybe cloning? something tells me I am wrong.
#ifndef     FOO_H
#define FOO_H

class Foo {
public:
    Foo();
    Foo(const Foo& orig);
    virtual ~Foo();
private:

};

Comment: There is a default constructor declared `Foo();` and a copy constructor `Foo(const Foo& orig);` as well as a virtual destructor `virtual ~Foo();`. For each of these terms (with respect to C++) an explanation should be easy to find on the web.
Comment: You should find a way to stop Netbeans from doing this.
Answer: Yes Netbeans has kindly created explicitly created the default and copy constructors.
It has also supplied you a virtual destructor to help you avoid memory leaks when inheriting from this class (Consider BabyFoo to be a child class of Foo): if you write Foo* foo = new BabyFoo(); delete foo; then you'll leak memory as the member data in BabyFoo will not be deleted unless Foo has a virtual destructor.
I don't like the way Netbeans does this because:
1) I think that a copy constructor can be difficult to maintain (it's easy to forget to copy a newly added member datum) and is unnecessary to supply if your member data don't need to be explicitly copied (bare pointer data would probably need to be explicitly copied). The one automatically generated by the compiler will (shallow) copy all member data.
2) A virtual destructor introduces a virtual function pointer table into your class which is an overhead.
3) Acknowledge Oli Charlesworth's comment: http://en.wikipedia.org/wiki/Rule_of_three_(C%2B%2B_programming)
Comment: Unfortunately, this is really unhelpful behaviour by Netbeans, because it misses the point of the Rule of Three.
Comment: @C.W. Indeed; this kind of memory leak is difficult to spot; only rectifiable by having a the base class destructor marked as virtual.
Comment: I understand the deconstructor, I was curious more about the Foo(const Foo& orig);
Comment: @C.W. That's the copy constructor. I'd rely on the default one if you can for the reasons I give in my answer.
Comment: This is my first time asking a question on StackOverflow, Thanks for the positive experience.
Comment: @C.W. Indeed you had some big guns on this one: Oli Charlesworth & juanchopanza. I'm just a humble newbie.
Answer: Foo(const Foo& orig);

This is copy constructor, every class has a a default copy constructor which is provided by the compiler
there purpose is to create a copy of an existing object
Refer http://en.wikipedia.org/wiki/Copy_constructor for more details about copy constructor


Adding a class to a parent div if it contains invalid ASP.NET validation controls

Question: I have an ASP.NET application that makes use of the built in validation controls. The end goal is to fire validation client side when the submit button is clicked, and add a class to a div element if it contains an invalid control. I'm basically trying to turn the label for the form element red if it's invalid. :)
I have markup like this (one div for each form element):

        First Name: * <asp:RequiredFieldValidator ID="rfv_fromFirstName" ControlToValidate="fromFirstName" Display="None" CssClass="validationError" ErrorMessage="From first name is required." runat="server" />

        <asp:TextBox ID="fromFirstName" runat="server" />

Using jQuery, how would I intercept the submit event, fire validation on the .NET validation controls, and then add an "error" class to the parent div element for each div that contains an invalid validator?
Bottom line is I'd like to add an "error" class to the div if it contains an invalid validator control. I'm open to other ideas for implementation as well.
Answer: Scott,
I ran across your post when facing a similar problem.  One issue I had is since the page did not reload the DOM when validation was fired my JQuery was not being triggered and the error class was not being applied.
After reading the following article and your post I came up with the following solution which worked very well for me.  Posting it here in hopes that it may help someone.  Basically it overrides one of the original asp.net validation scripts and has some JQuery to clear/add the error class to div.
Add this script to the bottom of your page:

Answer: Found the answer...
$.each(Page_Validators, function (index, validator) {
    if (!validator.isvalid) {
        $(validator).closest("div").addClass("error");
    }
});

Answer: You can use jquery for this its very simple please refer the below code.
  $(document).ready(function () {
        $("#<%=  ButtonName.ClientID %>").click(function () {
        if(validation here)

        {

            }
            else{
              $('.friendFormElementfloat_leftbold').css("background-color", "Red");
              return false;
            }
        })

    })

Comment: That doesn't answer at all the question I had. This appears to be for writing a custom javascript validation routine. My question dealt directly with interaction with the .NET validation controls.


In django admin how do I add a field for the reverse side of a ManyToManyField

Question: I have two models, 'Product' and 'Range', to be linked by a many to many field. The 'Product' class is in an app I didn't write, so It can't be modified (I can edit the modeladmin for it tho). I want to have the 'Ranges' a 'Product' is in to be editable in the admin, and I want to do it with a FilteredSelectMultiple, not inline admin.
simplified 'models.py':
class Product(models.Model):
    name = models.CharField(max_length=64)
    #etc...
    #I can't modify this class

class Range(models.Model):
    name = models.CharField(max_length=32)
    products = models.ManyToManyField(Product, related_name='ranges')

and admin.py:
class ProductAdmin(admin.ModelAdmin):
    # What do I put here to get a multi-select box for ranges?
    # Preferrably with one of those 'add' buttons to popup a window
    # to add ranges.

If I could modify Products I could put a ManyToManyField on it using the existing through table, and this works fine, but as stated I can't (or won't as it'll make upgrades to the external app a real pain).
Thanks in advance for any help! (PS I hope its easy to see here why I don't want to use inline admin forms - it makes the UI unnecessarily complex).
Answer: Sorry it may be a little late, but anyone googling may benefit from this answer. It's not so easy, but it is feasible. You have to build your own form (which may descend from the existing form, if you want), and then manually load and save items.
from django import forms
from django.contrib import admin

class ProductForm(forms.ModelForm):
    # <- your own fields declaration
    ranges = forms.ModelMultipleChoiceField(
        label='Ranges',
        queryset=Range.objects.all(),
        required=False,
        widget=admin.widgets.FilteredSelectMultiple("ranges", is_stacked=False))

    class Meta:
        model = Product

class MyProductAdmin(admin.ModelAdmin):

    def save_model(self, request, obj, form, change):
        # Save first to obtain id
        super(MyProductAdmin, self).save_model(request, obj, form, change)
        # Clean and re-add related objects
        obj.range_set.clear()
        for range in form.cleaned_data['ranges']:
             obj.range_set.add(range)

    def get_form(self, request, obj=None, **kwargs):
        if obj:
            ProductForm.base_fields['ranges'].initial = [o.pk for o in obj.range_set.all()]
        else:
            ProductForm.base_fields['ranges'].initial = []
        return ProductForm

# unregister and register again
admin.site.unregister(Product)
admin.site.register(Product, MyProductAdmin)

Comment: Much appreciated, I came up with something similar, was going to post it as an answer but real life got in the way.


Downsampling a 2d MATRIX in matlab, by taking average block wise

Question: Say I have a matrix A, which is of dimension 4x4.
Now I want to downsample this matrix by a factor 2 to get a new matrix B of dimension 2x2.
I want to downsample in the following way :
Let A be
 1     5     9    13
 2     6    10    14
 3     7    11    15
 4     8    12    16

I want B to be
3.5000   11.5000
5.5000   13.5000

To get B(1,1) = I take mean (1, 5, 2 and 6)
To get B(1,2) = I take mean (9, 13, 10 and 14)
To get B(2,1) = I take mean (3, 7, 4 and 8) and so on.
So for every element in B, I take the corresponding 2x2 block from A and take the mean of it.
In my case, the matrix A is of large dimension.
Also, the downsampling factor could be arbitrary.
For example,
A =
 1     7    13    19    25    31
 2     8    14    20    26    32
 3     9    15    21    27    33
 4    10    16    22    28    34
 5    11    17    23    29    35
 6    12    18    24    30    36

For downsampling of size 3/2.
Matrix B will be of size 4x4.
For every B unit I would have to take non-overlapping 1.5x1.5 blocks of A.
For example,
B(1,1) = mean(1, 0.5x7, 0.5x2, 0.5x8)
B(2,1) = mean(0.5x2, 0.5x8, 3, 9)
B(3,1) = mean(4, 0.5x10, 0.5x5, 0.5x11)
B(4,1) = mean(0.5x5, 0.5x11, 6, 12)
and so on.
Is there a faster way to do this without for loops?
Comment: The `(1,1)` element of B should be 3.5 right?
Comment: Sorry, I have corrected it now.
Answer: How about this:
A = [1     5     9    13;
 2     6    10    14;
 3     7    11    15;
 4     8    12    16];

B = ones(2)/4;

out = conv2(A,B,'valid');

%{
out = [3.5000    7.5000   11.5000;
4.5000    8.5000   12.5000;
5.5000    9.5000   13.5000];
%}

This gives you a little more than what you asked for, but you can throw away the information you don't need. For this case, you'd only be interested in out(1,1) ,  out(1,3)  out (3,1)  and out(3,3)
Comment: You can complete the answer by doing `out = out(1:2:end,1:2:end);`.  This is pretty much the same approach I took in the duplicate post.
Comment: Oh shoot @rayryeng I didn't even think to look for a duplicate haha that's good you marked it.
Comment: @Benoit_11 - Haha no worries.  I only knew about it because I answered a similar question a couple of days ago.  If I didn't do that, I wouldn't have marked as a duplicate because I wouldn't know where to look!  I still upvoted both answer regardless.
Comment: @Benoit_11 - BTW, lots of activity on my question.  I've revised my post to take advantage of `scatter`.  Thanks for the tip!
Comment: @rayryeng Awesome then glad to help! I'll follow the updates on your question :)
Comment: @rayryeng : I edited the question now. I want arbitary downsampling factor.
Comment: @AdithyanIlangovan - That's a new question all together.  Editing won't guarantee that it will be reopen.  Please make a new question.
Comment: @rayryeng Sorry, I am new to this. I just added an extra example to make it more clear. I wanted arbitary non-integer downsampling in the first place.
Should I open a new question? Thanks for the help.
Answer: If you have the Image Processing Toolbox you can make use of blockproc:
fun = @(block_struct) mean2(block_struct.data) * ones(size(block_struct.data));
B = blockproc(A,[2 2],fun);

B = reshape(unique(B),2,[])

Output:
A =

     1     5     9    13
     2     6    10    14
     3     7    11    15
     4     8    12    16

B =

          3.5         11.5
          5.5         13.5

Where you can replace the block size by any factor you want. Note that for non-integer factors MATLAB will truncate them.
Comment: Thanks it works perfectly for integer downsampling factors. I want non-integer sampling factors. I edited question now, please see.


Suppose $X$ and $Y$ are independent Poisson random variables. Find the conditional probability mass function $P(X=k\mid X+Y=m)$

Question: Suppose $X$ and $Y$ are independent Poisson random variables with parameters $\lambda$ and $\mu$, respectively. Find the conditional probability mass function $P(X=k\mid X+Y=n)$.

Don't know how to approach this. Additionally, the question asks me to find $E[X\mid X+Y=n]$. What is the distinction? Does it have a different distribution?
Comment: It turns out (but perhaps you know this already) that $X+Y$ has Poisson distribution parameter $\lambda+\mu$. Calculate the conditional probability using $\Pr(A|B)=\Pr(A\cap B)/\Pr(B)$. You will get something that looks very familiar.  And then the expectation question will be just quoting a result you know.
Answer: You need to provide more context for your question; in particular, even if you say you don't know how to approach the problem, you need to be able to demonstrate what you DO know.
The one question I will answer, however, is that $$\Pr[X = k \mid X + Y = n]$$ is a conditional probability.  Specifically, it is the probability that, given you observe the sum of the Poisson variables to be equal to $n$, that you also observed $X = k$.  So, obviously, this probability cannot be less than zero, nor greater than one.
By contrast, $$\operatorname{E}[X \mid X + Y = n]$$ is a conditional expectation.  It is, in some sense, the "average value" of $X$ given that the sum $X+Y$ was observed to be $n$.  This is a number that need not be between zero and one; in fact, if $n$ is very large, say $1000$, we would also intuitively reason that the expected value of $X$ should be quite a bit larger than one.
Answer: First you need to find the distribution of $X+Y$, there are several ways to do this,you can use the moment generating function to find the distribution of $X+Y$
$E[e^{t(X+Y)}]=E[e^{tX}]E[e^{tY}]=e^{\lambda(e^t-1)}e^{\mu(e^t-1)}=e^{(\lambda+\mu)(e^t-1)}$~Poisson($\lambda+\mu)$.
After you can computate the probability making
$$P(X=k|X+Y=n)=\frac{P(X=k)P(Y=x-n)}{P(X+Y=n)}$$