Improvising: can't play what I hear (internally)

Question: When I play jazz/pop, I struggle to get the musical thoughts I "hear" in my head out onto my instrument. I can tell that what I've played isn't what I wanted to play, but I don't know how to correct it (other than by trial and error) to what I want it to be.
I've tried singing, and it helps: I've found that if I can sing it accurately usually I can get it out accurately. However, this has two problems: 1. my singing itself is not that accurate and sometimes I have to try several times before I get it right (I'm not a trained vocalist), 2. when I'm performing I can't stop to sing.
I've done ear training and can reliably identity single notes over a key center and do two-part dictation.
Are there ways to work around this? Is it just spending more time singing and learning how to translate my inner hearing into physical movement?
Answer: The number one issue I've had with this, and the number one issue I've seen in others, it that our internal ideas either move to fast, or we don't have the awareness/facility to execute them.
Getting to where you describe is a lifelong pursuit, so I can't tell you how to "get there", but here is an approach that has been helpful to me and others.

Practice slowing yourself down. This is not to say practice at a slow tempo. It means, practice slowing down your ideas so that you can slay with them on your instrument. This typically means setting limits on what you allow yourself to play. For example, maybe you're only "allowed" to play one note per measure. By giving yourself a framework, you can focus both on playing what you hear, but also on hearing what you (are about to) play.

There is a tendency to get into our heads when improvising and loosing the connection to what's happening around us. Maintaining that connection is key to developing and executing ideas.

There are a number of questions on this site that would also be worth your time to explore.

In a slightly different context, there are explicit, step-by-step instructions for how to practice as suggested above. Those steps will still apply here. How can you listen and judge where you are in the music whilst improvising?
How to close the gap between ideas and capabilities when improvising?
Question about Building My Composition/Improv Skill
You'll notice that some of these suggested posts, like this one, are closed for various reasons. I advise reading them anyway. They still may offer something unique. Jazz improvisation: what's going through your mind
Some might not seem relevant on their face, but at least skip to see if there's a nugget. How to know what notes will go together while improvising?
Keeping track of theme when improvising
Answer: Can you play existing song melodies by ear? IMO, there's almost no difference in playing by ear, and playing out what you hear "internally". When you hear a melodic line (or harmonic, whatever) and try to repeat it, the line you heard echoes in your head and you try to repeat what you hear internally. When improvising, it is the same, except you don't first hear it externally, you hear it only internally. To practice playing what you hear internally, repeat phrases by ear.
Practicing:

Listen to a line

(Now it echoes in your head internally)

Play what you hear internally

Improvising:

Imagine a line

(Now it echoes in your head internally)

Play what you hear internally

Only step 1 is different. You can train steps 2-3 by repeating phrases by ear. When you're very good in that, then I claim that it will help you bring out improvised lines as well.
That's not the only way to improvise though. Improvisation can be based on intellectual things like visual note patterns on a keyboard or fretboard, or even abstract theoretical concepts. In which case you don't necessarily "hear" the things in advance, you see something or imagine some "calculations", and then you execute those plans. For example by playing every other scale note mechanically, following a complex rhythm pattern.
Comment: IMO this isn't the same, because after each bad attempt at playing an idea in my mind, the idea fades... Whereas that obviously doesn't happen with transcription.
Comment: @LostCrotchet Are you saying that you're excellent at playing by ear and you can play any melody by ear instantly, just not the ones in your mind? My whole point is that you have actually developed that skill and are _good_ at playing by ear. Developing takes lots of work. It's a skill, not a trick you "know".
Answer: I think you are facing the existential struggle that comes from the simultaneous need both to control and to surrender control to your subconscious.
The solution, in my opinion, is to dig the tunnel from both sides of the mountain-- (1) use your consciousness not to play, but to train the subconscious-- lots of scale patterns, transposing pieces, and so on-- transposing being a great way of getting your brain to think in patterns instead of set notes.  (2) learn how to get out of the way of your subconscious-- when you are playing, your conscious mind should not be involved in any of the mechanisms of playing at all.  It should be busy experiencing the environment-- feeling the energy in the room, listening to how the room and instruments are interacting to affect timbre, and so on.
I know this all sounds woo, but woo is another word for "won't fit my pre-set world view."  I don't see how an adult musician can live without faith, or superstition, or drugs, or some other way to force the ego to drop its heavy chains of habitual control-- unless they were already great as children.


Add data to a legend, with different format? Or should I use a label?

Question: I am experimenting with the legend; trying to get as result, a panel where I display data about the chart.
I am planning to add the last value, and min and max.
Looking for some examples, and I found one that use a function called labelFormatter, altho I am not having luck in understanding how does it works.
I need to have values with different text color and different size, so I am not even sure if I can use the title of the legend for this purpose, or if I should hide the legend and create directly a label (altho the issue then is related to moving and resizing, right? Since the legend update its position if the chart window is resized).
Which is the best way to do what I am planning to do? a label or the legend?
Comment: Do you want to add text formatted with HTML code into the chart plot area ?
Comment: I think yes, otherwise I can't have different font size and color, is that correct? Tried with a Label and it may work, but I can't make its background transparent, so it will not stand out too much on the chart; that's why I am going for the Legend (but whatever method works is fine with me).
Comment: Do you consider a use of legend title to add custom text (http://api.highcharts.com/highcharts#legend.title), in other scenarios you need to use renderer or labelFormatter with set useHTML (to customise colors).
Answer: If you are considering adding HTML elements into the chart plot area then you will have to use Highcharts Renderer API.
You can refer this JSFIDDLE working demo
it works like:
var chart = new Highcharts.Chart({
....
.....
......
}, function(chart) { // on complete

    chart.renderer.text('This text is styled and linked', 150, 80)
        .css({
            color: '#4572A7',
            fontSize: '16px'
        })
        .add();

});

Comment: Happy to help you, newbiez ! Please consiser accepting the answer if that really helps, so the information can be useful to others also ! :)
Comment: I always wait a bit to give the best answer to see if anyone want to post; is not like I forgot :) Thanks again! Rendered is magic :)


Removendo todos os espaços de uma string usando Javascript

Question: Gostaria de saber se tem uma maneira de remover todos os espaços em branco num texto usando Javascript.
Answer: Você pode utilizar REGEX para realizar tal ação, segue exemplo de código:

var strDefault = 'Te s te de remo ção de es pa ço s';

document.querySelector('.default').innerHTML = strDefault;

var str = strDefault.replace(/\s/g, '');

document.querySelector('.new').innerHTML = str;

Recomendo a utilização do \s para remoção dos espaços pois ele removerá qualquer tipo de caractere que represente um espaço em branco, por exemplo: '\t\r\n';
O REGEX é bem útil em casos que você precise de um padrão dinâmico, seria uma boa dar uma pesquisada mais a fundo sobre o assunto.
Comment: Obrigado funcionou como eu queria.


How to put link around an Html::submitButton in yii2 framework

Question: how to put link on an Html::submitButton in yii2.
I am creating an application and want a logout button under the login form which when gets clicked(only if the user is still logged in), will take the user to the logout action.
I am using login button like this:
<?= Html::submitButton('Login', ['class' => 'btn btn-primary', 'name' => 'login-button']) ?>

Comment: Being a beginner does not justify lazynes. Read the [really good documentation about this.](http://www.yiiframework.com/doc-2.0/guide-helper-html.html#hyperlinks)
Comment: Why don't you just create link with `Html::a()`?
Comment: Thanks for replying yupik. But can you tell me how to do that. I am a beginner in yii2.
Comment: Thank you so much. It worked.
Answer: for logout use anchor instead of submit button.
try the following code :
Html::a('logout','site/logout',['class'=>'btn btn-primary','data-method'=>'POST']);


How to make a backing track from any song. (If possible)

Question: I've seen a lot of tutorials about how to remove vocals and such with audacity, which never seem to work. But I want to know if I can find a song like on YouTube or something and remove all the lead parts, be they vocal or guitar or what ever.
Could you do it say on this song, remove the leads but keep the drums and bass and stuff:
Comment: Simple answer, no; for the same reason the 'remove vocals' tricks never actually work either.
Comment: You pretty much have it, on both the cake analogy & how such as karaoke tracks are done. Games like Guitar Hero are done by actually obtaining copies the original multi-track recordings & re-mixing to suit the game.
Comment: Is it because all the stuff is already mixed together and you can't undo it?  Like making a cake batter and trying to just remove the flour, can't do it anymore? And other backing tracks would've just been made by "re-creating" the song but leaving out what ever you want to? Or something along those lines.
Comment: Added the complete youtube link for you. No reason to have a broken youtube link.
Answer: Removing vocals or other tracks from an already mixed and mastered file is very complex and depends on a lot of factors. There's no one size fits all answer because tracks can be mixed in all sorts of ways with many different effects.
In the case of Karaoke or Guitar hero, they typically get access to the master tracks and in the case of Karaoke mix it again with the vocals muted, or in guitar hero make several mixes, one for each instrument. The ideal way to make a backing track is to get the masters provided for you (very unlikely, unless you have a good reason and probably money), or look to see if the separate tracks have ever been released in a producer edition (several Dream Theatre and Lamb of God albums have been released with this as a bonus for instance). If the tracks have appeared on a guitar hero game you can usually find copies of the audio that have been pulled from the game.
Trying to remove vocals from an already mixed track:
To do it with a finished and mixed product is much harder. The way the tool works in audacity and others (I'm assuming) is to take the left and right tracks, and then compare to find which parts of the signal are the same (ie, centre mixed and coming from both speakers equally). This is usually your lead vocal, as well as some other things like Kick drum, lead guitar, etc depending on the mix.
With a track that is only the parts that match you can then remove that part of the signal from both tracks to remove that content. If you wanted to be more precise, you could use high and low pass filters to try and filter down to only the vocal content, leaving things like the kick alone. But you'll still lose the content of those sounds that exists in the frequency ranges of the vocals.
An easy way to do this would be to take the left and right track, invert the phase of one, then mix down to Mono. This would cancel out any of the signal which is the same in both speakers and leave only the differences. If vocals are centre panned and dry they would be cancelled out, as would other things.
The reason this doesn't work every time:
There is a big problem with this though: it only works to remove content that is the SAME between speakers. If there's are stereo effects which differ between speakers (reverb, chorus, delay), backing vocals panned to the sides, doubled vocal tracks panned to the sides some, that content will not perfectly cancel and will stay audible. Other mastering tricks like stereo widening can also make this harder to do.
Answer: A more practical approach
If you are searching for a temporary solution to, let's say use the backing tracks for improvising over them without being disturbed by vocals or mid-range buzz, there's some little tricks you can do with audio material in a simple sound-editor without the need of sophisticated and expensive tools.
Of course, because of the (in)-fidelity, the result is not usable for production-purposes!!!

A multi-band graphic EQ that filters out all the frequencies in the low-mid and mid range. Provide a curve like ---______------------
An EQ with a bell-characteristic and a steep curve Q-factor to achieve a similar effect as the graphic EQ
Put the same audio track on two tracks of your audio-editor or DAW and put a Lowpass and a Highpass filter on one track to cut the low and high frequencies. What remains is a midrange signal (depending on the settings of your two filters). Now phase invert one of the two audio tracks you've got. This will nullify the mid-range completely...

You can save these settings in your editor of choice and use it as a 'preset'  just by assigning a new song to your audio track(s).

All tree methods serve to get rid of the mid range and do in a simple way what more sophisticated tools are doing in a dynamical time and context-sensitive way - but, depending on the material, not always very good. I showed you the hardcore way that will eliminate the stuff for sure, independent of what the source material is.
But you have to keep in mind that both tracks (version 3) have to have the same volume in order to get the midrange 100% silenced. If you're shifting the volume-ratio by changing the volume of either one track you will get back the midrange step by step.
Of course, by cutting the midrange so bluntly you are also killing a lot of instruments that form the chord/harmony portion of the composition. You are essentially left with bass-drum, bass, low-harmonies, HH, Cymbals, high percussions regarding the rhythm-group. And that is what you actually want when you're searching for a play/sing-along track. But anyways you can regulate the effect by changing the cut-off frequency of both of your filters to narrow down the midrange in order not to loose too much.
Hope that that's it what you've been searching for...

EDIT: If you wanna get fancy with method 3 you can also add a third track and phase-reverse one of its channels (L or R) in case your source is stereo. With that - everything that is usually mono like - the 'dry' vocal signal, centered mono effects etc. - will get removed. Only the effect part of each signal which is on both channels like reverberation an the like will remain. Also effects that are using a modulation of the signal's phase like stereo chorus/phlanger/phaser etc. for e.g. pad-sounds. But usually these 'wet' signals are not very loud...
That signal will now fill the hole in the frequency range that you left with method 3 and give you back some of the harmonical context that might be missing after the brick-wall-method 3. But also the 'wet' signal of the things you want to get rid of.
But because of being on its own track you can adjust the volume of your new midrange to your liking.
And of course - the additional track of this extension of method 3 must have the same filters applied to it than the other phase inverted track so that you actually fill the very hole that you dug in the first place.  If you didn't do that you would definitely kill all your BD, base and other signals that are typically centered and more or less 'dry'.
But by storing your settings as a preset you have to do this work only once and can apply it later on to any song you like. You may just have to tweak your preset every now and then...


AWS HTTP Gateway: private integration routing without path variables

Question: I've been setting up an HTTP gateway for the first time and came across an issue with private integrations. I want all my integrations to be private but it doesn't work well with routing.
I have a private integration with a $default route and it works great.
Now I want another private integration to be mounted under, say, /microservice/ and have all its endpoints proxied.
This however seems impossible because private integrations ask you for a backend ARN rather than URI, so there's no way to use path variables like {proxy+}. This results in only root of my microservice being accessible through the gateway - all the other paths just go to the $default route.
How would one go about setting up a private integration like this? Ideally I would like something like this:
- /microservice1/{proxy+}
- /microservice2/{proxy+}
- $default

Currently as I understand it I only have two options:

Expose my services to the world and use public integration with greedy path variables {proxy+} - not ideal
Keep the private integration but define each microservice endpoint as it's own route on the gateway - extremely annoying to maintain

Is there a good way to do this that I'm missing?
Answer: To answer my own question - this is possible with request parameter mapping that transforms request before it reaches the backend:

Create a route with greedy path variable: /microservice/${proxy}
In your private integration create a path mapping: overwrite:path = /$request.path.proxy
Comment: @dmitrybelyajov, do you know how to implement path rewrite like this:

api.example.com/v1/app1/user/add => https://app1.example.com/user/add

I.e. without "/v1/app1" part.

https://repost.aws/questions/QU8_a_LKzJT86VCIV4-J3cpA/api-http-gateway-path-rewrite-question


What is the purpose of a private nested/inner class?

Question: I was under impression that a private inner/nested class is only used for/by/accessed by outer class. But experimenting I realized that the HashSet(which is not the outer class of Happy) can access the class. If so then what is the real use of private ? Is it only restricting creation of classes to within outer class ?
public class FreeMain {

    private static class Happy {
       int x;
       private Happy(int x) {
           this.x = x;
       }

       @Override
       public boolean equals(Object o) {
           return true;
       }

       @Override
       public int hashCode() {
           return 10;
       }
    }

    public static void main(String[] args) {
        Set<Happy> happiness = new HashSet<Happy>();

        Happy h1 = new Happy(10);
        Happy h2 = new Happy(20);

        happiness.add(h1);
        happiness.add(h2);
    }
}

Comment: been a while, but  the class HashSet wouldn't be able to stick its nose into FreeMain and access a private class or variable within it(along the lines of class.variable or class.innerclass. But I suppose(untested) if you created an instance of your private class and passed that to somebody, then it'd work with it.  and when I learnt java, long ago, it didn't have Set<...> so I dunno re that.
Comment: Even *what* HashSet? What's your question?
Answer: Compelling reasons for using nested classes include the following:
It is a way of logically grouping classes that are only used in one place: If a class is useful to only one other class, then it is logical to embed it in that class and keep the two together. Nesting such "helper classes" makes their package more streamlined.
It increases encapsulation: Consider two top-level classes, A and B, where B needs access to members of A that would otherwise be declared private. By hiding class B within class A, A's members can be declared private and B can access them. In addition, B itself can be hidden from the outside world.
It can lead to more readable and maintainable code: Nesting small classes within top-level classes places the code closer to where it is used.
Comment: My question is whats the benefit / use of making the inner/nested class a private class. Thanks for answer but question was different one.
Answer: Access modifiers in Java control the scope in which an identifier can be legally accessed or referenced. You are using your private nested (static => nested, non-static => inner) class as the type parameter to a HashSet—but the reference is still happening within the scope of the parent class.

If so then what is the real use of Private ? Is it only restricting creation of classes to within outer class ?

No, it doesn't just restrict creation. You can't even reference the type Happy outside the FreeMain class. If you try to declare something with type Happy, or use Happy as a type parameter (like Set<Happy>) outside class FreeMain, you'll get a compiler error.

To summarize, if reference to private nested class is passed to another class(like set), it works so long as its in scope of freemain.

Yes, that's basically correct. However, the type isn't really being "passed" to Set when you declare a Set<Happy>. None of the code in the Set class ever sees the actual type you provide in the parameter (due to type erasure). The Java compiler just uses the information you specify in the type parameters as a kind of type assertion to check the correctness of your program.
When you declare Set<Happy> happiness, the fact that the happiness contains Happy instances is not known anywhere but within the scope of happiness. Therefore, the Happy type is never actually used outside the scope of your FreeMain class, and that's why it's legal even though Happy is private.
Comment: To summarize, if reference to private nested class is passed to another class(like set), it works so long as its in scope of freemain.
Comment: @JavaDeveloper - Yes, that's basically correct. See my updated answer.


How to hook into fivestar_ajax_submit function?

Question: I have to add custom HTML element for rate stars and I tried to this with alter fivestar_custom_widget form and set:
$form['actions']['submit']['#ajax']['callback'] = 'MODULE_fivestar_ajax_submit';

I created MODULE_fivestar_ajax_submit function where I call original fivestar_ajax_submit.
My problem is that I can't instruct $form to use my function in place of original code.
-- edit --
In MYMODULE_form_alter() I'v got:
if ($form_id == 'fivestar_custom_widget') {
    $arg0 = arg(0);
    $arg1 = arg(1);
    if ($arg0 == 'node' && !empty($arg1) && ctype_digit($arg1)) {
        $node = node_load($arg1);
        $form['votes_counter'] = array(
            '#markup' => '
' . format_plural($node->field_rating[LANGUAGE_NONE][0]['count'], '1 vote', '@count votes') . '
'
        );
        $form['#submit'] = array(
            'MYMODULE_fivestar_form_submit'
        );

        $form['actions']['submit']['#ajax']['callback'] = 'MYMODULE_fivestar_ajax_submit';
        $form['#submit'] = array('MYMODULE_fivestar_ajax_submit');
    }
}

and submit function:
function MYMODULE_fivestar_ajax_submit($form, $form_state) {
    $result = fivestar_ajax_submit($form, $form_state);
    $result['#commands']['data'] .= format_plural(100, '1 vote', '@count votes');
    return $result;
}

Comment: You need a form_alter to change the submit function, form submit callbacks are not treated as hooks.
Comment: I also tried with MODULE_form_alter() and fivestar_custom_widget as $form_id, but in this table can't find any informations about original call to fivestar_ajax_submit(). Thus I don't know where to put/override information about my custom _submit().
Comment: You need to set the '#submit' property. https://api.drupal.org/api/drupal/developer!topics!forms_api_reference.html/7#submit_property
Answer: My friend helped me with this solution:
function MYMODULE_element_info_alter(&$info) {
    $info['fivestar']['#process'][] = 'MYMODULE_fivestar_process';
}

function MYMODULE_fivestar_process($element) {
    $element['vote']['#ajax']['callback'] = 'MYMODULE_fivestar_ajax_submit';
    return $element;
}

function MYMODULE_fivestar_ajax_submit($form, $form_state) {
    $result = fivestar_ajax_submit($form, $form_state);

    $type = $form_state['build_info']['args'][1]['content_type'];
    $id = $form_state['build_info']['args'][1]['content_id'];
    $votes = fivestar_get_votes($type, $id, 'vote', $GLOBALS['user']->uid);

    $result['#commands'][] = array(
        'command' => 'insert',
        'method' => 'replaceWith',
        'selector' => 'span.vote-count',
        'data' => '' . format_plural($votes['count']['value'], '1 vote', '@count votes') . '',
        'effect' => 'fade'
    );
    return $result;
}

This code adds and change votes counter displayed after fivestar voting widget.


Assumptions required for expected value of sum of products to equal zero.

Question: First define $x_i$ is determenistic variable, $v_i$ is random variable. Consider the expression:
$$\text E(\sum_{i=1}^{\ n} x_iv_i)= \sum_{i=1}^{\ n} \text E (x_iv_i)=\sum_{i=1}^{\ n} \text E (x_i) \text E(v_i) \text +{cov}(x_i,v_i)= E(x')E(v)+cov(x,v)\space \space \space \space \space \space = x'E(v)$$
Now, let's say we want to define the minimal assumption required so that the expression is zero. We can impose a restriction that $E(v_i)$= 0. However, I believe that it is too strong of a restriction to say ALL elements of $v_i$ have to have an expected value of 0. The problem here is that this can get quite complicated as the answer depends on the values of x. But, the question still remains, is there a comprehensive way to formulate the minimal condition so that the expression equals zero?
This applies to the OLS estimator, as in its derivation of bias it's assumed that a similar expression is zero if $\text E(v_i)=0$. However, I believe the assumption is too strict.
Comment: $x_i$ is deterministic, and you write $E(x_i)$ ? Something looks wrong here
Comment: @leonbloy Well, the expected value of $x_i$ is $x_i$. I suppose I should have removed the sign somewhere there...
Comment: But then it's way  simpler:  $E(\sum  x_i v_i) =\sum  x_i E(v_i)$. I don't understand why you deal with covariances. The covariance of a a deterministic value and a random variable is always zero.
Comment: @leonbloy It's still not very simple...
Comment: @leonbloy Edited now...
Answer: You have already written the condition: letting $ {\bf \mu} = E( {\bf v})$ you must have $ {\bf x}' {\bf \mu} =0$, i.e, the inner product must be zero, i.e., the expected value of $ {\bf v}$ should be orthogonal to ${\bf x}$.
Comment: is there a way to write the orthogonality assumption using expected value or covariance operators or something else?
Comment: That's written using expected value (of $v$). Covariances have nothing to do here - if $x$ is a constant.
Comment: I suppose so... Still wondering why the OLS conditions are not written in this form, since it's the correct one. Thanks for the answer in any case.


VBA code running horrendously slow

Question: I have a loop that can go on for ages, although the "Enheder" worksheet only has like 10 rows, and the dataset im loadin has maybe 300 rows, it's taking a REALLY long time when I try to import.
    Public Function ImportData()
    Dim resultWorkbook As Workbook
    Dim curWorkbook As Workbook
    Dim importsheet As Worksheet
    Dim debugsheet As Worksheet
    Dim spgsheet As Worksheet
    Dim totalposts As Integer

    Dim year As String
    Dim month As String
    Dim week As String
    Dim Hospital As String
    Dim varType As String
    Dim numrows As Integer
    Dim Rng As Range
    Dim colavg As String
    Dim timer As String
    Dim varKey As String

    year = ImportWindow.ddYear.value
    month = ImportWindow.ddMonth.value
    week = "1"
    varType = ImportWindow.ddType.value
    Hospital = ImportWindow.txtHospital.value

    Set debugsheet = ActiveWorkbook.Sheets("Data")
    Set spgsheet = ActiveWorkbook.Sheets("Spørgsmål")
    Set depsheet = ActiveWorkbook.Sheets("Enheder")
    Set resultWorkbook = OpenWorkbook()
    setResultColVars debugsheet

    'set sheets
    Set importsheet = resultWorkbook.Sheets("Dataset")
    numrows = debugsheet.UsedRange.Rows.Count

    'make sure that the enhed can be found in the importsheet, so the units can be extracted accordingly
    If Not (importsheet.UsedRange.Find("afdeling") Is Nothing) Then
        Dim DepColumn
        Dim aCell
        DepColumn = importsheet.UsedRange.Find("afdeling").column

        'sort importsheet to allow meaningfull row calculations
        Set aCell = importsheet.UsedRange.Columns(DepColumn)
        importsheet.UsedRange.Sort Key1:=aCell, Order1:=xlAscending, Header:=xlYes

        Dim tempRange As Range
        Dim SecColumn
        Dim secRange As Range
        'find row ranges for departments
        Application.ScreenUpdating = False
'**Here's the loop that will go on for aaaaaages until I decide to ctrl+pause**

 For Each c In depsheet.UsedRange.Columns(1).Cells
    splStr = Split(c.value, "_")
    If UBound(splStr) = -1 Then
    ElseIf UBound(splStr) = 0 Then
    totalposts = totalposts + IterateColumns(GetRowRange(importsheet, DepColumn, splStr(0)), spgsheet, importsheet, debugsheet, year, month, week, Hospital, splStr(0), 0, varType, False)
    ElseIf UBound(splStr) = 1 And Not (importsheet.UsedRange.Find("afdeling_" & splStr(0)) Is Nothing) Then
    totalposts = totalposts + IterateColumns(GetRowRange(importsheet, importsheet.UsedRange.Find("afdeling_" & splStr(0)).column, splStr(1)), spgsheet, importsheet, debugsheet, year, month, week, Hospital, splStr(0), splStr(1), varType, False)
    End If
    Next
    Application.ScreenUpdating = True

    ' go through columns to get total scores
    totalposts = totalposts + IterateColumns(importsheet.UsedRange, spgsheet, importsheet, debugsheet, year, month, week, Hospital, 0, 0, varType, True)

    resultWorkbook.Close Saved = True

    ResultsWindow.lblPoster.Caption = totalposts
    ImportWindow.Hide
    ResultsWindow.Show
Else
    MsgBox "Kunne ikke finde afdelingskolonnen. Kontroller at der er er en kolonne med navnet 'afdeling' i dit datasæt"
End If

End Function

Function GetRowRange(sheetRange, column, value) As Range
'check for a valid section column
sheetRange.AutoFilterMode = False
sheetRange.UsedRange.AutoFilter Field:=column, Criteria1:=value
Set GetRowRange = sheetRange.UsedRange.SpecialCells(xlCellTypeVisible)
sheetRange.AutoFilterMode = False
End Function

'iterates through columns of a range to get the averages based on the column headers
Function IterateColumns(varRange As Range, spgsheet, importsheet, resultsheet, year, month, week, Hospital, dep, sec, varType, sortspg As Boolean)
Dim numrows
Dim totalposts
Dim usedRng
totalposts = 0
numrows = resultsheet.UsedRange.Rows.Count
Dim insert
insert = True
If Not (varRange Is Nothing) Then
' go through columns to get scores
For i = 1 To varRange.Columns.Count
    Dim tempi
    tempi = numrows + totalposts + 1

    Set Rng = varRange.Columns(i)
    With Application.WorksheetFunction
        'make sure that the values can calculate
        If (.CountIf(Rng, "<3") > 0) Then
            colavg = .SumIf(Rng, "<3") / .CountIf(Rng, "<3")
            insert = True
        Else
            insert = False
        End If
    End With

    'key is the variable
    varKey = importsheet.Cells(1, i)
    'only add datarow if the data matches a spg, and the datarow is not actually a department
    If (sortSpgs(varKey, spgsheet, sortspg)) And (insert) And Not (InStr(key, "afdeling")) Then
    resultsheet.Cells(tempi, WyearCol).value = year
    resultsheet.Cells(tempi, WmonthCol).value = month
    resultsheet.Cells(tempi, WweekCol).value = "1"
    resultsheet.Cells(tempi, WhospCol).value = "Newport Hospital"
    resultsheet.Cells(tempi, WdepCol).value = "=VLOOKUP(N" & tempi & ",Enheder!$A:$B,2,0)"
    resultsheet.Cells(tempi, WsecCol).value = "=IFERROR(VLOOKUP(O" & tempi & ",Enheder!$A:$B,2,0),"" "")"
    resultsheet.Cells(tempi, WdepnrCol).value = dep
    resultsheet.Cells(tempi, WsecnrCol).value = dep & "_" & sec
    resultsheet.Cells(tempi, WjtypeCol).value = varType
    resultsheet.Cells(tempi, WspgCol).value = varKey
    resultsheet.Cells(tempi, WsporgCol).value = "=VLOOKUP(H" & tempi & ",Spørgsmål!$D:$I,6,0)"
    resultsheet.Cells(tempi, WtestCol).value = ""
    resultsheet.Cells(tempi, Wsv1Col).value = colavg
    resultsheet.Cells(tempi, Wsv2Col).value = (1 - colavg)
    resultsheet.Cells(tempi, Wsv3Col).value = ""
    resultsheet.Cells(tempi, WgrpCol).value = "=VLOOKUP(H" & tempi & ",Spørgsmål!$D:$I,4,0)"

    totalposts = totalposts + 1
    End If
Next
End If
IterateColumns = totalposts
End Function

'Function that gets the workbook for import
Function OpenWorkbook()
    Dim pathString As String
    Dim resultWorkbook As Workbook

    pathString = Application.GetOpenFilename(fileFilter:="All Files (*.*), *.*")

    ' check if it's already opened
    For Each wb In Workbooks
        If InStr(pathString, wb.Name) > 0 Then
            Set resultWorkbook = wb
            Exit For
        End If
    Next wb

    If Not found Then
        Set resultWorkbook = Workbooks.Open(pathString)
    End If

    Set OpenWorkbook = resultWorkbook
End Function

'find column numbers for resultsheet instead of having to do this in every insert
Function setResultColVars(rsheet)
WyearCol = rsheet.UsedRange.Find("År").column
WmonthCol = rsheet.UsedRange.Find("Måned").column
WweekCol = rsheet.UsedRange.Find("Uge").column
WhospCol = rsheet.UsedRange.Find("Hospital").column
WdepCol = rsheet.UsedRange.Find("Afdeling").column
WsecCol = rsheet.UsedRange.Find("Afsnit").column
WdepnrCol = rsheet.UsedRange.Find("Afdelingsnr").column
WsecnrCol = rsheet.UsedRange.Find("Afsnitnr").column
WjtypeCol = rsheet.UsedRange.Find("Journaltype").column
WspgCol = rsheet.UsedRange.Find("spg").column
WsporgCol = rsheet.UsedRange.Find("spørgsmål").column
WtestCol = rsheet.UsedRange.Find("test").column
Wsv1Col = rsheet.UsedRange.Find("Svar 1").column
Wsv2Col = rsheet.UsedRange.Find("Svar 0").column
Wsv3Col = rsheet.UsedRange.Find("Svar 3").column
WgrpCol = rsheet.UsedRange.Find("Gruppering").column
End Function

Function sortSpgs(key, sheet, sortspg As Boolean)
If Not (sheet.UsedRange.Find(key) Is Nothing) Then
    If (sortspg) Then
        ResultsWindow.lstGenkendt.AddItem key
    End If
    sortSpgs = True
Else
    If (sortspg) Then
        ResultsWindow.lstUgenkendt.AddItem key
    End If
    sortSpgs = False
End If
End Function

Function Progress()
iProgress = iProgress + 1
Application.StatusBar = iProgress & "% Completed"
End Function

Comment: Hej @Jakob! Very difficult to debug that much code without the source files! Can you share? Also, try debugging for yourself by stepping through the code with `F8` and `Shift`-`F8`. My guess is that `UsedRange` returns more rows/columns than you expect...
Comment: You could benefit from using more `With` blocks. For instance you reference `resultsheet...` about 15 times in the 'IterateColumns` function. Each time you call this object, Excel has to load the entire sheet in to memory. Same thing with `SetResultColVars` where you reference `rSheet` multiple times.
Answer: Difficult to debug without the source files.
I see the following potential problems:

GetRowRange: .UsedRange might return more columns than you expect. Check by pressing Ctrl-End in the worksheet and see where you end up
Some thing in your main routine - depsheet.UsedRange.Columns(1).Cells might just result in much more rows than expected
someRange.Value = "VLOOKUP(... will store the formula as text. You need .Formula = instead of .Value (this will not solve your long runtime but certainly avoid another bug)
In sortSpgs you add know or unknow items to a control. Not knowing if there's any event code behind these controls, disable events with Application.EnableEvents=False (ideally in the beginning of your main sub together with the .ScreenUpdating = False)
Also, set Application.Calculation = xlCalculationManual at the beginning and Application.Calculation = xlCalculationAutomatic at the end of your code
You're performing a lot of .Find - esp. in sortSpgs - this is potentially slow in large sheets, as it has to loop over quite some data, depending on the underlying range.

Generally, a few more "best practise remarks":
* Dim your variables with the correct types, same for returns of functions
* Use With obj to make the code cleaner. E.g. in setResulcolVars you could use With rsheet.UsedRange and remove this part in the following 15 or so lines
* In modules of small scope, it is okay to dim some variable with a module wide scope - esp. if you hand them over with every call. This will make your code much easier to read
Hope that helps a bit... mvh /P.
Comment: Just to update: I'm now confident, that it has nothing to do with the optimization, it must have something to do with the autofiltering not working, as I intend it to.
Comment: it sort of did - it's lightning fast now, but I am experiencing some issues with my GetRowRange function, possibly due to the .SpecialCells(xlCellTypeVisible) selection. It may also be something completely unrelated.
Answer: My guess is that Application.Screenupdating is the problem. You set to false inside the:
if Not (importsheet.UsedRange.Find("afdeling") Is Nothing) Then
block. So if the isn't the case then screenupdateing isn't disabled. you should move it to the beginning of the function.
Comment: @Jakob by removing you mean setting it to `Application.ScreenUpdating = false` right? because that yuo should do, but in the begining of the script, and call true only in the end of the script
Comment: Thank you for your input, I have now completely removed Screenupdating, unfortunately, it is still very slow
Comment: Thank you again, that is what I mean now anyway :)
Answer: you could also try to write the usedrange in an array, work with it , and write it back if needed.
code example
dim MyArr() as Variant

redim MyArray (1 to usedrange.rows.count, 1 to usedrange.columns)
MyArray=usedrange.value

'calculating with Myarray instead of ranges (faster)

usedrange.value=myarray 'writes changes back to the sheet/range

also, maybe you can use .match instead of .find, wich is faster.
with arrays you use application.match( SearchValue, Array_Name, False)  'false if for exact match
the same thing works for range.find() , becoming application.find()...
save first your master workbook under a new name before making such a big change...

VBA code running horrendously slow


TFS2018 Build CI Batch Changes Trigger stops does not execute

Question: This feels like an odd one.  In my current setup, if I enable batch changes on the CI trigger, the trigger is never executed.  I'm not even sure where to start on this issue.
Comment: Can you share a screenshot of the settings?
Answer: I couldn't reproduce your issue on my side. Once you select Batch changes option, when a build is running, the system waits until the build is completed and then queues another build of all changes that have not yet been built. You need to check the following items:

Whether there is a build running.
Whether you have specify correct path filters
Comment: Sorry for the delay.  Yes, I've checked up to this point.  My issue comes when I enable Batch changes, it won't trigger any builds.  I'm concerned this might be an issue with my configuration or something corrupted.
Comment: I'm not able to reproduce your issue on my side, could you try to create a new build definition to have another try?
Comment: I have.  I've built about 3.  Each pointing to different source branches.  (TFVC)
Comment: What I have not done is try it in a different project.
Comment: You could try in another team project to check the result.


Hot reload not working for Razor page VS2022

Question:
I just installed Visual studio2022 and create a project.NET6 web application with Razor page.
But I found that Hot re-load doesn't work even for little changes("TEST" to "TEST1" in screenshot) on Index.cshtml but error popup said "Edits were made which cannot be compiled.
So I had to re-build the project to see the changes.
But somehow it works when I use start without debugging.
Could anyone please help on this.

currently I have both VS2019 and VS2022 installed on my laptop.
Answer: I don't know that his is the best solution, but you can disable edit and continue so that you don't keep getting prompted. Go to Options->Debugging->General and unselect the 'Enable Edit and Continue and Hot Reload' option. Obviously if you want Edit and continue you may not want this as your solution.
VS options


$_FILES super global variable

Question: why doesn't the unset function remove $_FILES contents or empty it after uploading a file .
how can I empty my $FILES variable after uploading a file .

            <title>Files Upload</title>

            <form action="" method="post" enctype="multipart/form-data">
                <input type="file" name="pdf" id="pdf">

                <input type="submit" name="sumbit" value="upload">
            </form>

<?php
unset($GLOBALS['$_FILES']);
echo "
";
var_dump($_FILES);
echo "
";
?>

The Output is :
array(1) {
  ["pdf"]=>
  array(5) {
    ["name"]=>
    string(19) "Courses Degrees.pdf"
    ["type"]=>
    string(15) "application/pdf"
    ["tmp_name"]=>
    string(24) "C:\xampp\tmp\php6BBD.tmp"
    ["error"]=>
    int(0)
    ["size"]=>
    int(624129)
  }
}

Comment: If you `var_dump($GLOBALS);`, you'll see that the files is under `_FILES`, not `$FILES`
Comment: Your edit still has the dollar sign on _FILES
Comment: I have already tried all of these
Comment: You have tried `$_GLOBALS['_FILES']`? Hmm
Answer: You have to specify the key of the variable
unset($_FILES['key']);

Your key is probably "pdf" when looking at your output
unset($_FILES['pdf']);

Comment: You have an array of arrays. The first row of ```$_FILES``` ("pdf") contains all of your different files.
Comment: Thank you .. this is true
Comment: I want to remove all keys with one step

$_FILES super global variable


Control characters as delimiters

Question: I have a nodejs TCP server and a client. Basic network communication happens. Client sends "data + STX_CHARACTER + data + ETX_CHARACTER" (just an example).
How do I split the string using the STX Control Character as a delimiter or how do I reference the character at all in Javascript.
Answer: STX and ETX are characters 0x02 and 0x03 respectively, so it'd just be "\2" and "\3". Just use string.split("\2") and .split("\3") on the second chunk from the first split to get your data.
Answer: For example you need to split string by Control character (0x17).It is equal to Decimal 23. So you do simple this:
console.log(yourString.split(String.fromCharCode(23)));

Control characters as delimiters


Asp.net mvc radiobutton retrieve selected data

Question: I'm working with ASP.net MVC4 with razor and javascript.
I load my view as follow:
When Retrieve data from database not check the values of radiobutton, the radiobutton is empty, How I can resolve this problem? the values is in the Textbox are recovered the radiobutton no.

        Parte Frontal
        Cant.
        Bueno
        Regular
        Deficiente
        Observaciones

    @{int numitem = 0;}
    @for (var i = 0; i < ViewBag.DatosExtFrontal.Count; i++)
    {

        @ViewBag.DatosExtFrontal[i].cprp_descripcion
        @Html.TextBox(string.Format("txtpieza{0}", numitem), (int)ViewBag.DatosExtFrontal[i].piv_cantidad, new { id = string.Format("txtpieza{0}", ViewBag.DatosExtFrontal[i].cprp_idpartepre.ToString()), style = "width:25px;text-align:right;", onkeyup = "checkInt(this)", sololectura = false })

            @Html.RadioButton(String.Format("rbtestado{0}", numitem), "B", new { id = string.Format("B{0}", ViewBag.DatosExtFrontal[i].cprp_idpartepre.ToString()), sololectura = false })

            @Html.RadioButton(String.Format("rbtestado{0}", numitem), "R", new { id = string.Format("R{0}", ViewBag.DatosExtFrontal[i].cprp_idpartepre.ToString()), sololectura = false })

            @Html.RadioButton(String.Format("rbtestado{0}", numitem), "D", new { id = string.Format("D{0}", ViewBag.DatosExtFrontal[i].cprp_idpartepre.ToString()), sololectura = false })

        @Html.TextBox(string.Format("txtobservacion{0}", numitem), (string)ViewBag.DatosExtFrontal[i].piv_observacion, new { id = string.Format("txtobservacion{0}", ViewBag.DatosExtFrontal[i].cprp_idpartepre.ToString()), style = "width:150px;", sololectura = false })

        @{
            string IdPartePre = String.Format("{0}", numitem);
            string PartePre = String.Format("{0}", (int)ViewBag.DatosExtFrontal[i].cprp_idpartepre);
            numitem++;
        }
        <input id="@IdPartePre" type="hidden" name="@PartePre" value="@PartePre"/>

    }

Comment: for helpers tie the value to your model.  change your radio buttons to @Html.RadioButtonFor
Comment: check ur controller and show controller action with viewbug
Comment: @MattBodily If I use Html.RadioButtonFor it this generate the same names for all of my radiobuttons and I can't selected more that one radiobutton
Comment: @user1956570 my controller return DatosExtFrontal with current information because load the values in the textbox
Answer: if you can't use a for helper to tie it to your model then you will need to put a unique name on the field and then you can get the value on your controller using
Request.Form["RadioName"].ToString()

Comment: but the unique name is: @Html.RadioButton(String.Format("rbtestado{0}", numitem), "B", new { id = string.Format("B{0}", ViewBag.DatosExtFrontal[i].cprp_idpartepre.ToString()), sololectura = false })
Comment: look at how the radio button is rendered on the view and make sure the name in the request matches and you should be good


php. mkdir(). set $mode with leading zero from string variable

Question: Okay, we have example at php.net:
mkdir($structure, 0777, true);

How to set 0777 integer from variable?
I have environment variable, for example PERMISSIONS=0755. And 0755 is a string.
As I can see there is no way to convert string to int with leading zero.
So is there any way to set permissions from variable?
define('PERMISSIONS', '0755');
mkdir($structure, PERMISSIONS, true); // bad!
mkdir($structure, intval(PERMISSIONS), true); // bad too!

Answer: You want the function octdec:
$permissions = octdec($_SERVER['PERMISSONS']);
mkdir($structure, $permissions, true);

Answer: define initial set as integer.
define('PERMISSIONS', 0755);

OR
define('PERMISSIONS', '0755');
$permission = intval(PERMISSIONS);
mkdir($structure, $permission, true);

Comment: what difference between `$permission = intval(PERMISSIONS);` and `mkdir($structure, intval(PERMISSIONS), true);`? And I can't set OS environment variable as integer.


Derivative of $f(x) = y^4$

Question: $(x^3 \cdot y^4)' = ?$
$a = x^3$ , $b = y^4$
$$(x^3 \cdot y^4)'= a'\cdot b + a\cdot b' = 3x^2 \cdot y^4 + x^3 \cdot (b')$$
Not sure what the derivative of $y^4$ would be, $(4y^3)$? Since the derivative of $(x\cdot y) = 1\cdot y + x \cdot y'$ and the derivative of $y' = y'$ instead of following the power rule.
Comment: from where do you get $$x^3y^4$$?
Comment: That's the question I am solving but I don't know how to solve the derivative of $y^4$ which is needed to solve the derivative of $(x^3\cdot y^4)$
Comment: @lakada what is $y$. Is $y$ a function of $x$? If it is, what is this function? You are trying to find the derivative with respect to x, right?
Answer: If $y$ is a function of $x$, then $y(x)^4$ is a composite function and you need to apply the chain rule.
Comment: Derivative of $y(x)^4 = 4y(x)^3 \cdot (y+x\cdot y')?$
Comment: No, where do you get the extra factor $x$? $(y(x)^4)'=4y(x)^3·y'(x)$.
Comment: I took the derivative of $y\cdot x$ instead of $y(x)$ by mistake.
Answer: by the product and chain rule we get $$(x^3y(x)^4)'=3x^2\cdot y(x)^4+x^3\cdot 4y(x)^3\cdot y'(x)$$
Comment: Why does $y^4 = y(x)^4?$
Answer: I think you need to be a more specific in your question.
Are $x,y$ independent or $y = f(x) $ ? And towards which variable are you taking the derivative ?
If $y = f(x)$ then you probably want the answer of @Dr. Sonnhard Graubner.
If not, then it is probably an exercise concerning partial derivatives.

Derivative of $f(x) = y^4$


Solr 4.1 Core Initialization Failure

Question: I have updated my version of Solr from 3.5 to 4.1
I have removed the old war file from my apache tomcat (7) webapps, and deployed the new war file that has been provided in the apache-solr package.
I got the following error upon trying to access solr from the web browser!
I have one core only(dbTrial)
Solr opens but this error appears.

SolrCore Initialization Failures
dbTrial: org.apache.solr.common.SolrException:org.apache.solr.common.SolrException: RequestHandler init failure
There are no SolrCores running.
Using the Solr Admin UI currently requires at least one SolrCore.
Unable to load environment info from null/admin/system?wt=json.
This interface requires that you activate the admin request handlers in all SolrCores by adding the following configuration to your solrconfig.xml:

Can you help me out? I have tried adding the request handler as specified, but it didn't work.
It seems that the new versions of solr need a new format for solrconfig file. can you assist please! thank you!
the log is the following:
<code>????? ?????? 21, 2014 9:19:05 ? org.apache.solr.common.SolrException log
SEVERE: null:org.apache.solr.common.SolrException: RequestHandler init failure
at org.apache.solr.core.RequestHandlers.initHandlersFromConfig(RequestHandlers.java:168)
at org.apache.solr.core.SolrCore.<init>(SolrCore.java:657)
at org.apache.solr.core.SolrCore.<init>(SolrCore.java:566)
at org.apache.solr.core.CoreContainer.create(CoreContainer.java:850)
at org.apache.solr.core.CoreContainer.load(CoreContainer.java:534)
at org.apache.solr.core.CoreContainer.load(CoreContainer.java:356)
at org.apache.solr.core.CoreContainer$Initializer.initialize(CoreContainer.java:308)
at org.apache.solr.servlet.SolrDispatchFilter.init(SolrDispatchFilter.java:107)
at org.apache.catalina.core.ApplicationFilterConfig.initFilter(ApplicationFilterConfig.java:277)
at org.apache.catalina.core.ApplicationFilterConfig.getFilter(ApplicationFilterConfig.java:258)
at org.apache.catalina.core.ApplicationFilterConfig.setFilterDef(ApplicationFilterConfig.java:382)
at org.apache.catalina.core.ApplicationFilterConfig.<init>(ApplicationFilterConfig.java:103)
at org.apache.catalina.core.StandardContext.filterStart(StandardContext.java:4624)
at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5281)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:866)
at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:842)
at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:615)
at org.apache.catalina.startup.HostConfig.deployWAR(HostConfig.java:958)
at org.apache.catalina.startup.HostConfig$DeployWar.run(HostConfig.java:1599)
at java.util.concurrent.Executors$RunnableAdapter.call(Unknown Source)
at java.util.concurrent.FutureTask$Sync.innerRun(Unknown Source)
at java.util.concurrent.FutureTask.run(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
Caused by: org.apache.solr.common.SolrException: Error loading class         'solr.DisMaxRequestHandler'
at org.apache.solr.core.SolrResourceLoader.findClass(SolrResourceLoader.java:436)
at org.apache.solr.core.SolrCore.createInstance(SolrCore.java:469)
at org.apache.solr.core.SolrCore.createRequestHandler(SolrCore.java:540)
at org.apache.solr.core.RequestHandlers.initHandlersFromConfig(RequestHandlers.java:154)
... 25 more
Caused by: java.lang.ClassNotFoundException: solr.DisMaxRequestHandler
at java.net.URLClassLoader$1.run(Unknown Source)
at java.net.URLClassLoader$1.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at java.net.FactoryURLClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Unknown Source)
at org.apache.solr.core.SolrResourceLoader.findClass(SolrResourceLoader.java:420)
... 28 more
</code>
Answer: Check the Solr log for a better error of what the issue is when Solr is starting up - you'll probably have a better error message there than the one you can see in the Admin interface (which is the error triggered when the interface attempts to access the Solr core). The reason why the core or requestHandler isn't loading will be in the log file, and not in the message produced by the UI. Remember that logging also changed at 4.3, if you've updated to 4.10 (I see that you wrote 4.1, but if you're planning on going the whole way (or meant 4.10) - the logging might have to be configured as well).
You'll also want to consider the "going from 3 to 4" document, that details the changed to the configuration files (as solrconfig.xml changed a bit).
Update
The log shows that it's complaining about loading "solr.DisMaxRequestHandler". This has been deprecated for quite some time and has been removed - just use the standard request handler from the example solrconfig.xml instead.
<code><requestHandler name="standard" class="solr.SearchHandler" default="true">
  <lst name="defaults">
    <str name="echoParams">explicit</str>
  </lst>
</requestHandler>
</code>
Comment: i have added the log can you please assist! @MatsLindh

Solr 4.1 Core Initialization Failure


In Gauss-Jordan elimination, what does it mean to 'restore' a row?

Question: As seen here
I am familiar with the elementary row operations but I've never heard an step worded in this way.
Thanks!
Answer: I've never heard that word in that context before, but based on the picture, it seems to mean something like 'normalize'. After computing row 1 - row 2, the person multiplied row 2 by $-9/2$ in order for the entry on the main diagonal to be a 1, 'restoring' it to a form easier to work with.


How can I show the progress process to client

Question: I am using C# 4.0 and I want to show the progress after button click.
protected void ASPxButton_cloture_Click(object sender, EventArgs e)
{
    tell user that procedure 1 begin
    do procedure 1.....
    tell user that procedure 1 finish

    tell user that procedure 2 begin
    do procedure 2.....
    tell user that procedure 2 finish

    etc...
}

I have tried with an update panel, but it only works one per button. That means when I have 5 procedures, I have to have 5 buttons.
What I want is to have only 1 button click.
Answer: Try this:
protected void ASPxButton_cloture_Click(object sender, EventArgs e)
{
    Response.Write("procedure 1 begin");
    Response.Flush();
    // do procedure 1.....
    Response.Write("procedure 1 finish");
    Response.Flush();

    Response.Write("procedure 2 begin");
    Response.Flush();
    // do procedure 2.....
    Response.Write("procedure 2 finish");
    Response.Flush();

    // ...
}


Prove that k-cycles generate S_n for k even

Question: Prove that $k$-cycles generate $S_n$ for $k$ even, $k \leq n$.
How do I about proving this? I know I should do it by induction. The $k=2$ case is simple. I'm having trouble going from the inductive step to the $k+2$ case.
I'm thinking that I want to show something like: $k$-cycles can be expressed as a product of $k+2$-cycles. But I don't know how to do it.
Comment: It's actually the opposite you have to show, i.e., that a $(k+2)$-cycle can be written as the product of a $k$-cycle with some other permutation. This is easy since $$(a_1,a_2,\ldots, a_{k+1},a_{k+2})=(a_1,a_2,\ldots a_k)\circ ( a_k,a_{k+1},a_{k+2})$$
Comment: So say we write $(a_1, ..., a_{k+2})$ as the product of a $k$-cycle and another smaller cycle. We don't have a recipe for writing any permutation in terms of a $k+2$-cycle still, so I don't see how it's the opposite that we have to show.
Comment: bof has shown how to do this directly, but it is easy if you know that for $n \ge 5$ the only proper nontrivial normal subgroup of $S_n$ is $A_n$.
Answer: We know that $S_n$ is generated by the $2$-cycles. If $k$ is even, $2\le k\le n,$ then a $2$-cycle can be expressed as a product of three $k$-cycles in the following way:
$$(1\ 2)=(1\ 3\ 2\ 4)(4\ 3\ 2\ 1)^2$$
$$(1\ 2)=(1\ 3\ 5\ 2\ 4\ 6)(6\ 5\ 4\ 3\ 2\ 1)^2$$
$$(1\ 2)=(1\ 3\ 5\ 7\ 2\ 4\ 6\ 8)(8\ 7\ 6\ 5\ 4\ 3\ 2\ 1)^2$$
and so forth.


How to deal with NA in index for Panel data

Question: I want run regression in panel data. There is NA in my index (ID,time). I do not want to delete NA in index.
Result<-plm(TBL~Tang+Prof+LnSALES+MB,data=Panel,model="within",index=c("Firms","Time"))

When I the above code, it returns:
at least one couple (id-time) has NA in at least one index dimension in
resulting pdata.frame
to find out which, use e.g. table(index(your_pdataframe), useNA = "ifany")
Error in model.matrix.pFormula(formula, data, rhs = 1, model = model,  :
NA in the individual index variable

Without delete NA, how can I run panel regression with NA in index?
Thanks
Comment: Just think through the issue a little... If there's an `NA` in your index column, you have an observation of your variables that you don't know who it belongs to. How then is `plm` supposed to sort out the fixed effects for your `within` model?
Comment: Hi thanks, i mean just omit NA in index when regressing, not delete them from the data
Comment: How does `Result <- plm(TBL ~ Tang + Prof + LnSALES + MB, data=Panel[which(!is.na(Panel$Firms)), ], model="within", index=c("Firms", "Time"))` work?
Comment: Thanks a lot, it works
Comment: @duckmayr do you want to turn your comment into an answer?
Comment: @Helix123 yes, thanks for reminding me. I used the comment format first since I couldn't be sure it was a working answer without 1412MM's data, but hadn't gotten around to adding an answer after their feedback.
Answer: Since you are just looking to omit observations where your index is NA, you can do this:
Result <- plm(TBL ~ Tang + Prof + LnSALES + MB,
              data=Panel[which(!is.na(Panel$Firms)), ],
              model="within", index=c("Firms", "Time"))

Explanation
data=Panel[which(!is.na(Panel$Firms)), ] tells plm() to use as data a subset of Panel where Panel$Firms is not NA. Then you cannot have the issue where
at least one couple (id-time) has NA in at least one index dimension in
resulting pdata.frame


How to implement a http proxy for localhost in windows?

Question: So that all browser request(no matter firefox or IE) will be sending out via the proxy automatically without any configuration.
Is it kind of thing possible?
Answer: What do you want with the proxy? Fiddler is automaticly set as a proxy for ie when it is active. Firefox needs manual configuration. But there is no traffic possible as long fiddler is active without using the proxy.
fiddler
Comment: After some googling I find what I'm trying to do is similar to NDIS...http://www.ndis.com/  .But still far from getting started...


Digital Clock Imaging, How is it Done?

Question: I'm thinking about making a digital clock app in Xcode and I'm wondering how the imaging is done. I want it to look similar to this

Do I need to create individual background images for each hour, minute, and millisecond???
Answer: use custom font for display text in your app, download digital font and use in your project
1: displaying text on a uilabel in digital form
2: digital font

Digital Clock Imaging, How is it Done?


Managed builds on Linux

Question: We have a TFS server which runs builds of our Windows-based software.
Now we had to port part of our software to Linux and we want to run the builds in a similar manner on Linux.
The project on Linux is created using Eclipse CDT, written in C++. The question would be how to run builds of this project on a Linux machine, and will it be possible to somehow integrate it into TFS infrastructure? For quality control, etc.
Answer: There is no out-of-the-box solution: currently there are no agents for Linux.
But wait, I did this once for a customer. The solution's pieces were:

setup SSH on Linux
write a Linux build script and save it in TFS version control
modify the custom template using the Community Build Extensions to:
a. push the script
b. invoke the script remotely
c. collect the build log(s)
d. copy the logs to the OutDir

I wrote a blog post with detailed instruction: http://casavian.eu/wordpress/2014/02/13/integrating-linux-builds-in-tfs/.

Managed builds on Linux


Como adaptar um Activity para FragmentActivity

Question: Estou fazendo um NavigationDrawer, e daí tenho que fazer algumas adaptações, pois estou estendendo Fragment, mas preciso usar int's para Activity funcionar, tentei chamar dentro de OnCreateView o FragmentActivity mas não deu muito certo.
É esta classe aqui:
package player.kmk.com.kmk;

import android.content.Context;
import android.media.AudioManager;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.SeekBar;

import java.io.IOException;

/**
 * Created by Z0NEN on 10/22/2014.
 */
public class menu1_Fragment extends Fragment {
    View rootview;
    protected static final String TAG = null;
    private AudioManager audioManager;
    private StreamingMediaPlayer audioStreamer;
    private boolean isPlaying;
    private ImageButton playButton;
    private String urlStreaming;
    private menu1_Fragment station;

    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        rootview = inflater.inflate(R.layout.menu1_layout, container, false);
     //   listen.ouvir();
    //    listen.definirVolumeSlider();
         Bundle bundle;

        playButton = ((ImageButton).findViewById(R.id.play_button));
        this.playButton.setOnClickListener(new View.OnClickListener()
        {
            public void onClick(View paramAnonymousView)
            {
                if (isPlaying)
                {
                    audioStreamer.interrupt();
                    playButton.setImageResource(R.drawable.play);
                }
                if (!isPlaying)
                {
                    startStreamingAudio();
                    playButton.setImageResource(R.drawable.pause);
                }
                isPlaying=!isPlaying;
            }
        });
        this.audioManager = ((AudioManager)getSystemService(Context.AUDIO_SERVICE));
        int i = this.audioManager.getStreamMaxVolume(3);
        int j = this.audioManager.getStreamVolume(3);
        setVolumeControlStream(3);
        SeekBar localSeekBar = (SeekBar)findViewById(R.id.seekBar);
        localSeekBar.setMax(i);
        localSeekBar.setProgress(j);
        localSeekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener()
        {
            public void onProgressChanged(SeekBar paramAnonymousSeekBar, int paramAnonymousInt, boolean paramAnonymousBoolean)
            {
                audioManager.setStreamVolume(3, paramAnonymousInt, 0);
            }

            public void onStartTrackingTouch(SeekBar paramAnonymousSeekBar)
            {
            }

            public void onStopTrackingTouch(SeekBar paramAnonymousSeekBar)
            {
            }
        });
        return rootview;

    }

    public void startStreamingAudio()
    {
        try
        {
            if (this.audioStreamer != null)
                this.audioStreamer.interrupt();
            this.audioStreamer = new StreamingMediaPlayer(this, playButton);
            this.audioStreamer.startStreaming("http://sh.upx.com.br:10369", 5208L, 216L);
            return;
        }
        catch (IOException localIOException)
        {
            while (true)
                Log.e(getClass().getName(), "Error starting to stream audio.", localIOException);
        }
    }

    public void onDestroy()
    {
        super.onDestroy();
        if (this.audioStreamer != null)
            this.audioStreamer.interrupt();
    }

}

Do modo que está é insustentável, pois está como Fragment, como faço adaptações com Activity de determinadas funções como setar o player para tocar com o findByViewId ou controlar o volume com o Seek Bar.
Answer: Tente usar findViewById no método onCreateView() do fragmento assim:
rootView.findViewById(id);

Dentro do fragmento mas fora de onCreateView() faça assim:
getView().findViewById(id);

Para as demais situações em que uma Activity ou Context é requerida usar o getActivity().
Comment: Faça getActivity().getSystemService();
Comment: Bom, a resposta foi aceita então estou imaginando que conseguiu. De qualquer forma, seria this.audioManager = (AudioManager)(getActivity().getSystemService(Context.AUDIO_SERVICE));
Comment: Vou tentar e no caso do getSistemService()?
Comment: Pode mostrar um exemplo com o getView()?
Comment: Consegui:        playButton = (ImageButton) getView().findViewById(R.id.play_button);
no primeiro caso.
Comment: Não consegui neste situação:        this.audioManager = ((AudioManager)getSystemService(Context.AUDIO_SERVICE));
.
Comment: Obrigado. No .setVolumeControlStream(3) eu coloquei um getActivity() para pegar a atividade e não marcou erro, está certo?
Comment: Está certo sim.
Comment: E nestes casos que aparece o erro "Cannot resolve method ´get intent`" o que eu faço utilizando ainda o Activity no Fragment:
       feed = (RSSFeed) getIntent().getExtras().get("feed");
        int pos = getIntent().getExtras().getInt("pos");
Comment: Também, getActivity().getIntent().get...
Comment: Tinha tentado antes de perguntar e tentei novamente mas aparece o erro aonde invoca
Comment: Aí já não sei dizer o que pode estar acontecendo. Pelo erro que você citou parece que getIntent() está escrito errado: "get intent". Crie uma nova pergunta e forneça mais detalhes.
Comment: Não está com erro ortográfico, agora é de rodar. Veja aqui:http://pt.stackoverflow.com/questions/109202/erro-de-chamada.


show that a Sylow p-group lies in the center of $G$

Question: I'm stuck with the following problem:
Let $G$ be a finite group and $p$ be the smallest prime dividing $|G|$. Suppose the Sylow p-subgroup $H$ of $G$ is normal and cyclic. Show that $H$ lies in the center of $G$. Hint: Consider the order of automorphism group of $\mathbb{Z}/p^n \mathbb{Z}.$
My thought until now is assume $|H|=p^n.$ Let $G$ act on $H$ by conjugation and consider the class equation. Since $H$ is assumed to be normal and cyclic, each action on $H$ can be seen as an automorphism on $\mathbb{Z}/p^n \mathbb{Z}$. The order of the automorphism group of $\mathbb{Z}/p^n \mathbb{Z}$ should be $\phi(p^n)$, where $\phi$ is the Euler phi-function. But I don't know how to use this to show that all elements of $H$ are fixed points, and hence lies in the center of $G$. Are there any mistakes above? Could I ask for some help here? Thanks a lot.
Comment: The automorphism group of $\mathbb{Z}/p^n\mathbb{Z}$ has order $\phi(p^n)=p^{n-1}(p-1)$
Comment: It's been corrected. Thanks!
Answer: Every element of $G$ induces an automorphism on $H$ by conjugation since $H$ is normal, and since $H$ is abelian $H$ itself acts trivially. This means there is an induced homomorphism $G/H\to \mathrm{Aut}(H)$. All prime divisors of $|G/H|$ are larger than $p$, so by divisibility considerations this homomorphism must be trivial. Thus every element induces the trivial automorphism, meaning $H$ is in the center.
Comment: Just wondering why by divisibility considerations this homomorphism must be trivial?
Comment: @Sid None of the orders of the elements of $G/H$ except the identity divide the order of elements in the codomain.


Gaussian integral formula

Question: I have problem with this example so if somebody can explain how I can solve it or how I can simplify o write $f(x)$ function it will be great!
Find Gaussian formula in form:
$\int^{1}_{-1}|x|\cdot f(x) dx=w_0\cdot f(x_0)$
and with that formula solve next integral:
$\int^{1}_{-1}|x|\cdot \sin(x) dx$
I will probably be able to solve but I really don't know what to do with $\sin(x)$, because we only do exaples of this kind:
$\int \sqrt x f(x)dx=w_0\cdot f(x_0)$ to solve $\int x^2dx$ so in that case I know that I should write $f(x)$ as $x^k$ but here in case with $\sin(x)$ or any other function I'm in front of wall and don't have any idea.
I would be really happy if somebody have time to write this down also for other functions not only for $\sin(x)$.
Thank you!
Answer: Gaussian one-point formula is exact on affine functions. Since the weight function is even, the nodes are symmetric wrt. $0$, so $x_0=0$. Observe that the node $x_0$ is a root of a polynomial of degree $1$ orthogonal wrt. the weight function $|x|$. This is indeed $0$. Next, to determine $w_0$ let us integrate the $1$ function with the weight function $|x|$. The integral is $1$, so (because our quadrature is exact on affine functions), $$1=\int_{-1}^1 |x|\text{d}x=w_0\cdot 1$$ and finally $$\int_{-1}^1 f(x)|x|\text{d}x=f(0)$$ is our Gaussian formula. Applied to $f(x)=\sin x$ gives of course $0$. This example tells us that Gaussian quadratures are always exact on polynomials of the highest possible degree, nevertheless they could be exact on certain other functions.

Gaussian integral formula


Mysql select all from list and order by date on another list

Question: So I am making a warranty management system. Something to let you know when a warranty is about to end.
I am storing the warranties in a list called warranties, and each warranty renewal in a separate table called warranty_entries.
The warranties table only contains an Auto-Increment ID, the product name, the company, who it was made by and the date of creation.
The warranty_entries table contains an Auto_Increment ID, the id of the warranty it belongs to, the expiration date, the start date, the date or creation, and a few other fields.
I am trying to select * from warranties and order them by the end date of their most current entry in warranty_entries.
So a warranties expiration date is the expiration date of the latest expiring warranty entry.
I'll try to rephrase one more time, since I as well am getting confused describing this.
I want to order all the warranties by the expiration date of their most recently created entries' expiration date.
I can't seem to grapple my head around how to only select 1 entry in a table and sort another table by that entries expiration date.
UPDATE - TABLE STRUCTURE AND DESIRED OUTPUT
TABLE: warranties
-----------------------------------------------------------------
|      id       |       1        |      2        |       3      |
|     name      | chick warranty | duck warranty | cat warranty |
-----------------------------------------------------------------

TABLE: warranty_entries
----------------------------------------------------
|      id       |  1   |  2   |  3   |  4   |  5   |
|  warranty_id  |  1   |  2   |  2   |  3   |  3   |
|   end_date    | 2010 | 2005 | 2006 | 2010 | 2015 |
|  start_date   | 2008 | 2001 | 2005 | 2008 | 2010 |
----------------------------------------------------

I want to select everything from warranties and order them by the end date of their corresponding entry in warranty_entries. Since there are multiple warranty entries that have the same warranty_id I want to use the most recent end date to order by.
So after the query, the result set would look something like this:
RESULT SET:
-----------------------
| id |     name       |
| 3  |  cat warranty  |
| 1  | chick warranty |
| 2  | duck warranty  |
-----------------------

Comment: Show your table structure & your desired output you expect
Answer: You can do it in a sub query,  like so:
SELECT w.*, (SELECT end_date FROM warranty_entries we WHERE we.warranty_id = w.id ORDER BY end_date DESC LIMIT 1) AS end FROM warranties w ORDER BY end DESC
This should do the trick. Change the names of the tables and columns as necessary.
Comment: How would you select entries within a certain date. I can't add the between statement inside the sub query because it wouldn't always pick the newest one.
Comment: You would have to add the between in the sub query and it will pick the newest one between two dates.
Comment: But I only want to pick from the most recent date and check if it is between certain dates. Like check if a warranty's expiration date is between x and y. So it would never select from the non most recent entries per warranty.
Comment: If you want such a check,  use my query and do the check using your processing language like php,  because this logic would become a mess in sql, and it would slow down a lot


$ABC$ exists so $\overline{AX}$, $\overline{BC}$, and $\overline{CZ}$ are concurrent. $\overline{AB} = 6$, $\overline{AC} = 3$, $\overline {BX}$ is?

Question:
A certain triangle $ABC$ exists such that it's angle bisector $\overline{AX}$, median $\overline{BC}$, and altitude $\overline{CZ}$ are concurrent. If the lengths $\overline{AB} = 6$ and $\overline{AC} = 3$, then what is the length of line $\overline {BX}$?

Since the angle bisector, median, and altitude are all cevians of our triangle $ABC$, I figured that Ceva's theorem might help here. But after this, I'm not sure how to proceed. I've never seen a problem combine all three of these unique cevains and try to get the length of one of them. Does anyone have any ideas?
Answer: Ceva gives
$$BX\cdot CY\cdot AZ=BZ\cdot AY\cdot CX$$ and since $AY=CY$ and $BX=2CX$, we obtain:
$$2AZ=BZ$$ or in the standard notation
$$2\cdot b\cdot\frac{b^2+c^2-a^2}{2bc}=a\cdot\frac{a^2+c^2-b^2}{2ac}.$$
From here we can find a value of $a$ and after this $BX$.
Can you end it now?


Swift Save viewcontroller state using coder beyond app close

Question: I am using Xcode 8 and swift 2.3
I want to save the entire view controller to file and restore state even after app closes.
I searched everywhere and found we need to use coder for that. but all just shows to save an object.
but here I need to save entire ViewContoller and subviews.
ViewCotroller will have three buttons

Add Text
Add Image : User can add any number of textViews and Images. So I need to save all that info also.
Add ViewController : User may have an array of this viewController and need to save all.

Question 1)
Can just save self.view and can it save all subviews automatically ?
Question 2)
I need to init without coder at start by just using
let nameVccVar = nameVcc()

and
let nameVccVar = nameVcc(coder: CodeVar)

Question 3)
How do I save all this coded data to file using NSKeyedUnarchiver and retrieve back?
Kindly help me or give me tips to make all this work
class nameVcc: UIViewController
{
    var nameIntVar = 0
    var nameStringVar = "Save this"
    var nameImageVar = UIImage()

    override func viewDidLoad()
    {
        super.viewDidLoad()
    }

    required init?(coder NkdPsgVar: NSCoder)
    {
        super.init(coder: NkdPsgVar)
    }

    override func encodeWithCoder(DkdPsgVar: NSCoder)
    {

    }

    func addTextViewBtnClick()
    {
        let viewVar = UIView()

        // Set many values for view

        self.view.addSubview(viewVar)
    }

    func addImageViewBtnClick()
    {
        let imgViewVar = UIImageView()

        // Set many values for ImageView

        self.view.addSubview(imgViewVar)
    }
}

I also tired :
convenience init()
{
    self.init()
}

and
convenience init()
{
    self.init(coder: NSCoder())
}

Answer: TL;DR:
There are key steps and methods required to implement state restoration in your app.

Opting-in for App State Restoration in App Delegate by returning true for these methods shouldSaveApplicationState and shouldRestoreApplicationState.
Setting Restoration Identifier for view controllers that you want state restoration implemented in.
Implementing encodeRestorableStateWithCoder and decodeRestorableStateWithCoder methods in your view controller. The former is used to save any state information of your view controller to disk using encodeObjectForKey method. The latter shall be used to restore the state back from your saved contents to the disk by using decodeObjectForKey method.

Watch this awesome blog post about State Restoration for easier grasp. If you have time, also do spend on watching State Restoration WWDC Session.

There is no need to save your entire ViewController yourself. UIKit does that for you when you set your Restoration Identifier (In Interface Builder). The only thing we need to focus for state restoration is to save your essential properties needed to re-create your app's "State", for example, a Bool property which determines whether you want to display a specific button or not.
Now coming to your series of questions....

Can I just save self.view and can it save all subviews automatically ?

You do not need to save any of your views. All subviews will be handled by UIKit. Encode your required properties (such as Bool flags, count variables, key properties that can be used to fetch data from api call for your datasource etc.) inside encodeRestorableStateWithCoder method. Don't forget to re-contruct your view controller's state from decodeRestorableStateWithCoder. Both of these methods belond to UIStateRestoring protocol.

I need to init without coder at start by just using

No need to do any fancy inits.

How do I save all this coded data to file using NSKeyedUnarchiver and
  retrieve back?

As I said earlier, implement necessary UIStateRestoring protocol methods to save and restore your app's state.
Comment: All the links you have mentioned shows c coding... Is there any swift version of the same ?
Comment: Here is Ray Wenderlich: https://www.raywenderlich.com/117471/state-restoration-tutorial
Comment: How do I call encodeRestorableStateWithCoder and decodeRestorableStateWithCoder on button click.
Comment: You do not need to call it. It will be automatically called (`encodeRestorableStateWithCoder`) when the the app goes to background state. When you open your app back up, `decodeRestorableStateWithCoder ` will be called.
Comment: No that's not my case. I have explained as another question. Can you help me with this https://stackoverflow.com/questions/46398956/swift-store-and-restore-viewcontroller-state-on-button-click


How to get seleced values by jQRangeSlider

Question: I am trying to integrate jQRangeSlider into my jqplot applications, which means users can slide the x axis and decide the range of plots to be illustrated. However, I am having some difficulties of accessing the selected range.
Here is a demo of my approach.
It seems like selected values are saved in the following <divs>

2010-02-11

2011-02-11

I tried to use
alert($(".ui-rangeSlider-label-value").val())

but got empty return. I appreciate if anyone could give me some suggestions.
Answer: Finally, I found the method from the documents of jqrangeslider. Here is a quick example
var values = $("#slider").dateRangeSlider("values");
console.log(values .min + " " + values .max);


Show that there is no modulus with an odd prime number of primitive roots

Question: Show that there is no modulus with an odd prime number of primitive roots. I'm not really sure how to approach this at all. I was thinking of using the property that there exists a primitive root modulo $m$ if and only if $m = 2, 4$ or $m$ is of the form $p^k$ or $2p^k$, but I'm not really sure what to do next.
Comment: If $a$ is a primitive root is $-a$ ?
Comment: @RoddyMacPhee:  did you mean $a^{-1}$?
Comment: No but that's also a good consideration @J.W.Tanner
Comment: @RoddyMacPhee  But $5$ is a primitive root $\pmod 7$ while $2$ isn't, for example.  Or, more simply, $2$ is a primitive root $\pmod 3$ while $1$ is not.
Comment: Yes and what I was pointing out was that if $-1$ as a residue shows up in one line, $1$ is the residue of the line of it's additive inverse at that same exponent.  For multiplicative inverses they end up at multiplicative inverses.
Answer: If there are any primitive roots modulo $m$ at all, then there are $\varphi(\varphi(m))$ of them. Being a totient, it could never be an odd number greater than $1$, regardless of primality.


How do you sort or compare Strings in JavaScript based on a certain locale?

Question: I know there is a function called String.prototype.localeCompare which you can use, and you can send in as the second argument a list of locales.

string.localeCompare(compareString [, locales [, options]])

But if you look at the browser compatibility table, only Chrome supports it.

How do you sort or compare Strings in JavaScript based on a certain locale?
How does all the big websites do this, like ebay or amazon? They must have some kind of String sorting in the front-end.. right?
Comment: Why do they need to have String sorting in the front-end?
Comment: To avoid sending a back-end request, if we want to change the order of items in a list.
Answer: May be you need sorting, not compare?
Javascript array sort method sort strings on its Unicode(not ASCII) codes. You can sort array of strings to get it in alphabetical order.
['Собака', 'Кошка'].sort() will sort array to ["Кошка", "Собака"] which is right in Ru_ru locale.
You can add compare function like this:
['Собака', 'Кошка', 'Свекла'].sort(function(a, b) {
    return a[1] > b[1]?1:-1;
})

Javascript will compare strings by Unicode character by character. In my example compare is inside a[1] > b[1] on native low-level code. Return -1 or 1 needs for sort function to replace array elements.
Comment: If you know your native language it doesn't mean you can write anything you want just because other people don't understand you. I've corrected your answer, because SO isn't the place for filthy language.
Comment: Is this really ASCII? I thought it was only English-latin characters and symbols defined in ASCII. Regardless, lets say I want to sort "Кошка", "Собака" now based on en-US with array.sort?
Comment: Lets check first letter `('Кошка').charAt(0).charCodeAt(0)` is 1050? And you?


Can't access a shared folder using credentials

Question: We have a server with Windows Server 2008 Standard installed. We added users and user groups in order for other computers to have access to specific shared folders and files. Obviously, we've set some shared folders to be accessed by some users but not others.
It all worked well until some day. I don't know exactly what happened then. Now, the majority of times whenever I try to access one of my shared folders, I get the message You do not have permission to access \\server\foldr, even though I have been given access to the folder, both in the sharing permissions and the NTFS ones.
This happens equally to all the network users. Only the folders marked for access by Everyone can be accessed.
Another curious thing is that when I go to Computer Management\Shared Folders\Sessions on the server, my client computer is enlisted as GUEST, instead of the user's name, although the Guest property is set to No.
I've already tried resetting permissions on the folder, adding new users, changing credentials on the client computer... nothing seems to work. Do you know what seems to be the problem?
Edit: Follow-up to Dmitry's questions:
Security event 552 does not appear on the logs. Instead, I'm getting event 4776 stating that I have logged in with the "Guest" logon account.
Accessing \\server\c$ asks for my credentials, but either they're not accepted or I do not have permissions to access c$. I have experienced this already when trying to map a network drive to \\server\foldr with specific credentials, somehow my credentials are never accepted.
Turning off UAC didn't help.
The clients' PCs have a range of Windows OS's from XP to 7. My PC in particular has Win 7 RC.
2nd Edit: I disabled the Guest account and found out that my client PC's username is different from the username I was trying to use (I really thought that they were equal, but apparently I changed it when I formatted and reinstalled the OS). So now my question is: is there any way that I can access the shared folders while keeping the current usernames on both server and client computers?
Comment: are the users accounts on a domain, or local accounts on the server?  On the client computers, are the drives being mapped to (i.e. Map Network Drive) or just browsed to (Start->Run->)?  With the drive being mapped on the client PC, you can use different credentials to connect to it.
Comment: Normally I do Start->Run->, but I tried mapping the network drive and it keeps asking for my credentials, even though they are entered correctly.
Answer: Try to check your local security policy
run secpol.msc->Local policies->Network access->Sharing and security model for local account. It should be set to classical.
Comment: it was set to classic (local users authenticate as themselves)
Comment: As I can understand all your computers are in the workgroup?
Comment: yes, they are. It is a local network.
Comment: Is the server joined to a workgroup or may be it is joined to domain?
Comment: Workgroup, no domain.
Comment: Hm, very strange. Have you checked local policy on the server or on the client PC? I understand that this is insane in workgroup mode, but try to run RSOP in logging mode on the server and check Computer Configuration\Windows Settings\Security Settings\Local Policies\Security Options\ policy. Also try to reset saved credentials on client's computer with something like tinyurl.com/7qepg
Comment: with RSoP (on the server) all the settings are "Not Defined", but the "Sharing and security model" policy still shows "Classic" when you double-click it. I've reset credentials on the client: the server never asks for new credentials, it always shows the "Windows cannot access..." message. Unless I need to reboot or something...
Comment: Hm, may be you can find something interesting in Event logs especially Security logs for events 552 - Login attempt with logon type 3. and all near events
Comment: Which OS runs your clients?
Comment: Also my friend advised in this situation to try to switch off UAC on the server
Comment: And if you try to connect \\server\c$ does it show you Account details dialog?
Comment: Thanks for the help, check out the updated question above.
Comment: Seems this was not the case for djeidot, but it worked for me.
Answer: From your answer to another post that you are using a Workgroup, the most likely problems are that the user/pswd are different or don't exist on the server, or the user/pswd is not being passed in the correct syntax.  In a Workgroup Users are local to each machine, JSmith on the server is not the same as JSmith on the workstation.
A Domain solves both of these issues and has many other advantages if you have more than 4-5 workstations.  This is the best solution.
Option 2 is to setup a username and pswd on the server.  This can be 1 server user for each wkstn user, 1 server user for each user security group desired: Accounting, Sales, Marketing, etc, or 1 server user for all users.  The server username & pswd may, but are not required, to match the username and pswd on the wkstns.  Don't use any blank passwords.
Create a batch file on each machine to map the shares as a drive letter and force authentication on the server. Place the batch file in a C:\Admin folder, place a shortcut to the batch file in the All Users Startup folder to have it run on logon, set it to run minimized.   The syntax is:
"Net Use X: \Server\Share /User:Server\User Password".
"Net Use /help" will provide more examples.
Net Use X: /del will remove the drive mapping for testing, it will not delete any data.
You can also test authentication against the server with the Net Use command.  If the authentication fails with "incorrect user name or password" then either the syntax, username, password or some combination of all 3 are wrong.
Option #2 is not secure and not recommended but could work as a temporary solution.
Comment: Yes, the problem was the different usernames in server and client, as I put it on my second edit. However, I tried to use your Option 2 and I could never map a network drive that way...
Comment: If  Net Use isn't working then it's either the username/password combination, the syntax of the command or a firewall.  If access/mapping works with Everyone/Full on the share then it's not a firewall issue. From your 2nd Edit, the username/password on the workstations don't matter, you only use the server username/pswd. You can logon to a wkstn1 as BJones but the cmd to map to the server would still be "net use X: \\server\Share /user:ServerName\ServerUser ServerPassword".  If that doesn't work then take out the "ServerName\" and try .../User:Serveruser ServerPassword".  Try from the server.
Comment: I don't have workgroup machines to test on, it's very possible the correct syntax is:
Net Use X: \\server\share /user:ServerUserName ServerUserPassword
Comment: OK, i got the "net use" option working, but it's just easier to change my computer's username. I'm going to consider switching to a domain. Thanks for the help!
Answer: Just a thought but have you checked for a difference in time between the workstation you're on and the server you're trying to access? If the time is off for some reason or another it could cause issues in terms of accessibility.
Comment: I have just checked it but it is correct.
Answer: We have had similar problems with our network, and usually they point to a bork in the domain controller. Restarting the server that acts as a domain controller and then flushing the DNS caches in our client machines usually does the trick. After restarting your domain controller, from the command line (in all Windows OS's), you can try (in this order):
<code>ipconfig -flushdns
ipconfig -registerdns
</code>
From a different angle, when you log into your OS, are you logging into "yourlocalmachinename\yourlocalusername" or "yourdomain\yourdomainusername"? Try logging out and switching users to make sure you're in the right context.
Comment: We do not have a domain, just a workgroup.
Answer: I have strong feeling that you have changed something in local security policy. May be disabled NTLM, may be changed Log on locally or Deny log on locally policies. Please check if it was changed from its previous state when all worked fine.
Answer: I had the same issue. It is resolved now. Please check whether you have an entry of the server in the local s/m hosts file. If so, remove that entry and try again to access the share drive.
Answer: I have windows 2008 Server and one drive is shared on it. One day, some of my win 7 client can access shared drive but some can't . So i try to search the problem on many website and many forum. And I tried this
Go to windows 7 clients' control panel-> user account -> manage your credentials-> Add a Windows credential
And Type my server name
To all client  and it works!!!
Try this and let me know it works... :)


Is there an explicit number of 'notes' in microtonal music/scales?

Question: Western music consists of 12 unique notes that are repeated across octaves. Is there any set number of unique notes in microtonal music? Or does the number of notes vary depending on the octave?
Answer: There's no set number of notes outside a specific system — the term "microtonal" is very broad.  From Wikipedia:

Microtonal music can refer to all music which contains intervals smaller than the conventional contemporary Western semitone. The term usually refers to music containing very small intervals but can include any tuning that differs from the western 12-tone equal temperament. Traditional Indian systems of 22 śruti; Indonesian gamelan music; Thai, Burmese, and African music, and music using just intonation, meantone temperament or other alternative tunings may be considered microtonal

It's quite possible that there are systems where the number of tones depends on the octave (I'm not personally aware of one), but that is not generally a feature of most systems.  I would guess that this is because you would probably want to increase the number of tones as you ascended (since the absolute frequency difference between octaves is increasing and thus you have more "space" for division), but human perception of the distinction between notes also drops off as you go higher and counteracts the spacing.


query to select users who has answered all questions from set of answers of each question

Question: This is mysql table.
            User    Question    Answer
            20      1           answer1_2
            20      2           answer2_5
            20      3           answer3_1
            726     1           answer1_2
            726     2           answer2_5
            726     3           answer3_1

I want the users who has given answer of all questions and
we have predefined set of answers for each question.
like Question 1 can have answers from answer1_1, answer1_2, answer1_3
     Question 2 can have answers from answer2_1, answer2_2, answer2_3
Initially, I tried query like this:
            SELECT GROUP_CONCAT( DISTINCT CAST( User AS CHAR ) ) allUsers, COUNT( DISTINCT User ) totalUsers
            FROM survey
            WHERE
            (
                (
                Question =1
                AND Answer =  'answer1_2'
                )
                OR (
                Question =1
                AND Answer =  'answer1_2'
                )
                OR (
                Question =1
                AND Answer =  'answer1_3'
                )
            )
            AND (
                (
                Question =2
                AND Answer =  'answer2_1'
                )
                OR (
                Question =2
                AND Answer =  'answer2_2'
                )
                OR (
                Question =2
                AND Answer =  'answer2_3'
                )
            )

but then I see the result and realize that 'AND' among all questions won't work for my requirement
but I need the result with that logic.
Table structure cannot be changed.
Answer: You could do something like:
Select user, count(answer) from survey group by user having count(answer)=3

Comment: we have to specify possible answers per question, also.
your solution will ensure only all answers are given.
Comment: You can then link that and select all users matching the one in the query above - you didnt mention you needed the answers, you said you needed the users.
Answer: If you have a unique key on fields User and Question, then you could do something like this:
SELECT count(Question) answers_no, .... FROM survey GROUP BY User HAVING answers_no = num_total_questions

You could pass num_total_questions as a variable from application


Imprimir os dados dum vetor numa struct

Question: Quero fazer um sistema de cadastro de datas de aniversário. A dúvida final é: como imprimo os aniversário: 1/12/1990, 12/2/1977, 13/09/1999 e 19/04/1987. Seriam os exemplos da impressão das datas, mas me aparecem vários números que não tem nada a ver. Segue o código.
#include <stdio.h>
#include <stdlib.h>

typedef struct
{
    int dia;
    int mes;
    int ano;
} data;

int main()
{
    data data_aniversario[4];
    int i=0;

    while (i<4)
    {
        printf("Preencha sua data de nascimento\n\n");
        printf("Digite o dia: ");
        scanf("%d", &data_aniversario[i].dia);
        printf("\n\nDigite o mes: ");
        scanf("%d", &data_aniversario[i].mes);
        printf("\n\nDigite o ano: ");
        scanf("%d", &data_aniversario[i].ano);
    }

    printf("\n\nA data do seu aniversário é: \n");
    printf("%d/%d/%d\n", data_aniversario.dia, data_aniversario.mes, data_aniversario.ano);
    system ("pause");
    return 0;
}

Answer: Há dois problemas no seu código:

Falta você incrementar a variável que controla o loop onde pede os dados. Você está guardando as quatro datas no mesmo local e acho que não é o que você quer.
Quando você imprime as datas de nascimento não está usando um loop. Você está tentando imprimir o array e não os elementos dele. Não é possível imprimir o array como um todo, o array é apenas um endereço de memória, daí aparecem números estranhos. No caso específico você não pode nem imprimir os elementos mas sim os membros desses elementos, mas isto estava certo no seu código, faltava só indexar o array da mesma forma que você fez corretamente quando estava lendo os dados.

Além disto o nome da variável, apesar de não causar problemas no código, passa ideia errada do que ela guarda.
Veja:
#include <stdio.h>

typedef struct {
    int dia;
    int mes;
    int ano;
} data;

int main() {
    data data_aniversario[4];
    for (int i = 0; i < 4; i++) {
        printf("Preencha sua data de nascimento\n\n");
        printf("Digite o dia: ");
        scanf("%d", &data_aniversario[i].dia);
        printf("\n\nDigite o mes: ");
        scanf("%d", &data_aniversario[i].mes);
        printf("\n\nDigite o ano: ");
        scanf("%d", &data_aniversario[i].ano);
    }
    for (int i = 0;i < 4;i++) {
        printf("\n\nA data do seu aniversário é: \n");
        printf("%d/%d/%d\n", data_aniversario[i].dia, data_aniversario[i].mes, data_aniversario[i].ano);
    }
}

Veja funcionando no ideone. E no repl.it. Também coloquei no GitHub para referência futura.
Answer: Quando você imprime as datas, você está fazendo:
printf("%d/%d/%d\n", data_aniversario.dia, data_aniversario.mes, data_aniversario.ano);

E deve ser data_aniversario[0].dia, variando de 0 até 3 para imprimir todas as datas.

Obs: está faltando também um i++ para parar o while. Ou você pode utilizar um for.
while (i<4)
{
     // seu código
     i++;
}

Answer: data_aniversario é um array com 4 elementos data.
Você faz o input de 4 datas e guarda nesse array.
Para imprimir você terá de utilizar um loop que percorra todos os elementos de data_aniversario.
Qualquer coisa do género:
for(i = 0; i < 4;i++)
{
    printf("\n\nA data do seu aniversário é: \n");
    printf("%d/%d/%d\n", data_aniversario[i].dia, data_aniversario[i].mes, data_aniversario[i].ano);
}

Imprimir os dados dum vetor numa struct