Powershell for listing local admins on network

Question: I am using the following Powershell from http://iislogs.com/steveschofield/2009/01/09/list-local-administrators-on-a-machine-using-powershell-adsi/ to extract the local and domain admin accounts configured in PC and servers of an internal network.
Powershell script is below:
function LogToFile ([string]$strFileName, [string]$strComputer)
{
 Add-Content $strFileName $strComputer
}

$strComputer = "server1.loc.mydomain.com"
$computer = [ADSI]("WinNT://" + $strComputer + ",computer")
$Group = $computer.psbase.children.find("Administrators")
$members= $Group.psbase.invoke("Members") | %{$_.GetType().InvokeMember("Name", 'GetProperty', $null, $_, $null)}

ForEach($user in $members)

{
Write-Host $user
$a = $strComputer + "!" + $user.ToString()
LogToFile "C:\local-admins.txt" $a
}

When executed, it produces results in the txt file in following format:
server1.loc.mydomain.com!Administrator
server1.loc.mydomain.com!JohnDoe
server1.loc.mydomain.com!Support
server1.loc.mydomain.com!Domain Administrators

Can someone help me to change the output on txt file, so the results are shown in this format:
server1.loc.mydomain.com!Administrator!JohnDoe!Support!Domain Administrators

If reported in this way, then I can easily export to csv and work with it.
It'd be super cool if this can be transformed to export on CSV in desired format instead of txt.

How to make the code on line 6 so e.g. if I want to scan the whole subnet which has names: server1, server2, .... server38... I don't have to manually change that line for each machine. I tried server*, server[*] and it gives me errors.

I am a complete novice in PS, but trying to piece things together to address my needs and hope you may provide me with needed help.
Thanks.
Comment: `$a = @($strComputer;$members) -join '!'`
Comment: It's almost there. But it now produces the desired output in same lines depending on how many admins are. E.g. if there are 4 admins, the output is ( the > are added only for clearer emphasis)

>    server1.loc.mydomain.com!Administrator!JohnDoe!Support!Domain Administrators

>    server1.loc.mydomain.com!Administrator!JohnDoe!Support!Domain Administrators

>    server1.loc.mydomain.com!Administrator!JohnDoe!Support!Domain Administrators

>    server1.loc.mydomain.com!Administrator!JohnDoe!Support!Domain Administrators
Comment: Remove the whole `foreach(){}` loop, just do it once
Comment: Thanks, that worked. Can you also help do have some regex in place so I don't have to execute manually for each server1, server2, server3 etc..

I tried the basic $number = Select-String d{0,3} and by adding $strComputer = "server" + $number +".loc.mydomain.com" but it didn't work.
Answer: To change the output to have all accounts in one line, change the foreach() loop at the bottom to just:
$a = @($strComputer;$members) -join '!'
LogToFile "C:\local-admins.txt" $a

To generate a list of servers with successive numbers in their name, use the range operator ..:
$serverNames = foreach($number in 1..38){
    'server{0}' -f $number
}

So you end up with something like:
function LogToFile ([string]$strFileName, [string]$strComputer)
{
    Add-Content $strFileName $strComputer
}

foreach($ServerNumber in 1..38){
    $ServerName = 'server{0}.loc.mydomain.com' -f $ServerNumber
    $Computer = [ADSI]("WinNT://$ServerName,computer")
    $Group = $Computer.psbase.children.Find('Administrators')
    $Members= $Group.psbase.invoke('Members') |ForEach-Object { $_.GetType().InvokeMember('Name', 'GetProperty', $null, $_, $null) }

    $Output = @($ServerName;$members) -join '!'
    LogToFile 'C:\local-admins.txt' $Output
}

Comment: *wrongly clicked the Edit button above. No changes made to @Mathias' code. Thanks


Perdi meu script da para recuperar?

Question: Após uma tela azul, perdi meu trabalho no workbench, mas mantem o schema. Tem como recuperar ou terei de fazer novamente o trabalho?
Answer: O Workbench assim como o Office faz um auto save. Se você usar versão 6.3 que é a mais atual, vá até C:\Users\\AppData\Roaming\MySQL\Workbench\sql_history e você vai encontrar os scripts que você escreveu (salvos por você ou não) e os arquivos costumam estar salvos por data. Você pode abrir esses arquivos com um editor e decodificar os HTML entities. É meio trabalhoso mas você não perde o que já fez.

Perdi meu script da para recuperar?


Is it correct to state that this is 2/3 time signature?

Question: Basically, if this is 4/4 (i.e. 4 beats aka 1 bar, 4 clocks):

and this is 1/4 (i.e. 1 beat aka 1/4 bar, 4 clocks):

is it correct to state that this is 2/3? (i.e. 2 beats aka half bar, 3 clocks):
Comment: The short answer is "no." It seems that there's some confusion about the difference between time signature and rhythms. These examples have notes of different lengths (durations), but they could be part of many different time signatures. There's no such thing, though, as "2/3" (at least, not normally). Try reading up, here and elsewhere, about terms like "meter," "note value," and "rhythm." And you might call example 3 "hemiola," though I wouldn't worry about that before understanding the others.
Comment: Your question demonstrates that you do not understand how time signatures work.  I kindly suggest that you do some googling and read up on the subject.  Wikipedia is a free and convenient place to start.  If you still have questions after reading the relevant theory, then come back and ask a new question.  Notice that you will only ever see powers of 2 on the bottom of a time signature.  Anything else is invalid, a clue that you have misunderstood what is going on.
Comment: In conventional notation, the time signature tells you how many beats of what duration make up a full bar.  Your 1/4 example is incorrect because in a 1/4 time signature, one beat is one bar, not a quarter of a bar.
Answer: No.
What you have shown isn't a bar with an unusual length anyway.   It's a standard 4-beat bar partially filled by three triplet quarter-notes.
Time signatures work like this.   The top number is 'how many' the bottom number is 'what of'.   And the 'what of' is worked out by 'how many would add up to a whole note'.  (Just like fractions in math, really.)
The most common bottom number is 4.  Four quarter notes add up to a whole note. (That's why they're called 'quarter notes'.)
The most common top number is also 4.   How many quarter notes in each bar?  Four.  A standard rock beat has that. A waltz has 3, so the time signature would be 3/4.
You COULD, theoretically, make the 'what of' a third of a whole note.  But we don't, the convention is to use only 'what of' numbers divisible by 2.
(There is a modern-ish thing of 'irrational time signatures' where a signature such as 2/3 is used to indicate a tempo relationship with what came before.   And the top number 'how many' doesn't always directly count the beat.  But let's not get complicated.)
Answer: 3/4 means you have three beats of length 1/4 each measure. What you've given us would be rather a 6/8 (two groups of 3 subbeats per measure). But the way your program is handling this currently is to divide the space of a 1/2 note into three spaces, so you get two quarter note triplets. This is rhythmically the same as 6/8, but instead of 1/8 it uses two thirds of 1/4 as base unit (so for same output one has to increase the tempo 50%).
Your software should provide the option to select the time signature somewhere. So if you change the sig to 3/4 you should see in the top the "2" one block earlier.
Comment: @markzzz The grid in the background is what relates visually to the notion of "time signature." The notes shown here divide 8 cells into three—they're derived from triplets. But music is notated in certain conventions; there's no such thing as a "sixth note." Even "compound meter," in which notes fall in groups of three—like 6/8—calls these notes "eighth notes" even though there are 6 of them in a measure.
Comment: Not really a 6/8 so, since its not 6 beats with length 1/8 measure, but 3 beats of 1/6 measure. So maybe 3/6? Make sense? Also, I don't need to have "2" one block earlier anyway :)
Comment: @markzzz One of the important distinctions is: These are "notes," but they aren't necessarily "beats." "Notes" are "real"—you can hear differences in length—but "beats" are "imaginary"; they're an idea we use to organize the real sounds in time. And "meter" is another construct formed by adding up the imaginary "beats."
Comment: @markzzz The notes would fit into a 6/6 measure, if you so want. But what the grid in your software is suggesting is still 4/4 (note that the notes do *not* align to the grid).
Comment: @Lazy well, 6/6 if I fill all of them :) If I use 3/6, its like "filling" just 3 instead of 6 in the score. Similarly: 3/4 is like sequence 3 beats instead of 4. In any case, the length of the beats (3 vs 6, or 3 vs 4) shouldn't change. Does it make some sense?
Comment: I'm basically modelling a software that need to fill divisions :) So probably the terminology is wrong. In fact 6/6 duration will be longer than 4/4 given the same tempo/bpm... but in my case it just need to divide properly in the same time unit. Not sure how to describe that division, keeping the reference to a beat.
Comment: @markzzz Commonly bpm is used for quarters, so 4/4 and 6/6 are of same length given the same bpm. More classically we'd give a metronome number, which might refer to different beats. Anyway, I thing it should make sense to continue this discussion in chat if required.
Comment: @Lazy anyway, thats basically a 1/4T :)
Comment: @markzzz the bottom number in a time signature doesn't tell you what fraction of a measure each beat represents.  The top number tells you that.
Comment: @markzzz furthermore, given that the time signature tells you how many beats are in a measure, it should be obvious that 6/8 cannot mean 6 beats that each take up 1/8 of a measure, because if that were true then you would be saying that each measure is 0.75 measures long, which is nonsense.  (This is actually somewhat closer to what time signatures meant when they were first introduced, but measures hadn't quite been invented yet and the time signature was a true fraction, unlike its use today.  But getting into that in too much detail is probably more confusing than helpful.)
Answer: The math is right, but the music theory is wrong because the underlying time signature can't have a 3 as its beat value. Since the only context available is that your DAW seems to be subdividing as though it's 4/4, this is a triplet rhythm in 4/4, which isn't unusual in many styles of music. Specifically, this is a quarter note triplet.
This rhythm could easily be expressed in another time signature, for example something like 3/4 or 6/8 would this rhythm simpler since those time signatures are based around rhythmic patterns of threes. Whether or not that is appropriate depends heavily on the rest of the music, though.
Outside of experimental notation, there is no such thing as 2/3 time signature. This is because the beat value (bottom number) of a time signature represents a note value, usually the note value on which the beat falls. In 4/4, the bottom 4 represents a quarter note, or 1/4 of a whole note. The bottom note will always be a power of two in accordance with the value of notes.
The extreme example is irrational time signatures, where the 2/3 would mean something like the three represents a hypothetical note that takes up 1/3 of a whole note (duration of one of the three notes in a half-note triplet). The idea is this would be used to show that the new beat has some mathematical relationship to the previous tempo. Therefore, this notation is only used as an experimental way to describe metric modulations rather than a real time signature in the traditional sense. I would not advise using this in your sheet music unless you know that the reader of your music really really knows what they're doing.
Comment: @markzzz Correct, it's called a "triplet." Perhaps part of the problem is that you've come to a site about conventional music notation and practice, and want to propose some non-traditional practices. You can do whatever you want, you just can't expect others to understand you unless you use the language that's been established.
Comment: @markzzz the bottom number is always a power of two because the duration of each kind of note is twice as long as the next shorter note and half as long as the next longer note.  The factor is always 2.  There is an exception for tuplets, most commonly triplets, but these are written using the standard power-of-two notes and adding a number above them to indicate how much faster they are to be played; the time signature is never used for that because there is no way of drawing a note that (by itself) represents anything other than a power of two; you have to use the tuplet annotation.
Comment: Curious thing: why bottom need to be power of 2? If I can divide by 4 (or 8), why can't divide it also by 3?
Comment: @markzzz I mean, *in music you can have a note of any duration* including 1/12 of a whole note. The reason time signatures don't let you use 12 as the denominator is because time signatures come from *sheet music*, and sheet music is written in such a way that durations are expressed as powers of 2, hence why in sheet music we don't have a "one-twelfth note". Sheet music allows for notes to be 1/12th of a whole note, but it requires tuplet notation. Hence we would say that's an "eighth note triplet".
Comment: @AndyBonner "you just can't expect others to understand you unless you use the language that's been established": it would be possible to have people understand a novel nontraditional practice if there is a thorough specification describing the practice.  The real problem is convincing people to use it.
Comment: Maybe because by convention, a quarter note is a beat? So it must divide/multiply from this?
Comment: In fact, on a DAW, i can basically set 1/3 of beat, which would be 1/12 note. Are you saying 1/12 note doesn't exist?
Comment: And what if I want (for example) play a beat using 7 division? How can be noted this if 1/28 is not allowed and since this is not a triplet?
Comment: @markzzz There is a thing in conventional sheet music called a septuplet, notated as 7 eighth notes  in the time of 8. Other values are allowed as well.
Comment: @Jos so I can have both Quarter Septuplet or Eighth Septuplet?
Comment: Yes, and if that isn't complicated enough, you can have e.g. 7 septuplets in the time of three regular eights, notated as 7:3 above the notes.


Confused to use OR, str_replace, array or what?

Question: I have a code that finds the words Alabama and Michigan inside $l and return the if condition:
<?php if (trim($l) == "Alabama" || trim($l) == "Michigan"): ?>
   <?= $l ?>
 <?php else: ?>

<?php endif; ?>

Sometimes I don't have Alabama and Michigan inside $l but I have AL and MI that are related to Alabama and Michigan and in that case I want replace AL and MI with Alabama and Michigan. If I want to do it inside the code above to write a clean and short code, how should I do it? I have a lot more words to match and associate them together so please give me a clean code.
Comment: `so please give me a clean code` - this is not how SO works. We do not write your code for you. You will have to write it yourself and if it doesn't work, then you can ask about that.
Answer: you could use  a  regexp  as
  if(preg_match('(Michigan|Alaska|MI|AL)', $l) === 1) {

    ........

   }

in Your case
<?php if (preg_match('(Michigan|Alaska|MI|AL)', $l) === 1): ?>
   <?= $l ?>
 <?php else: ?>

<?php endif; ?>

or for replace
<?php
  $short = ["MI", "AL"];
  $long   = ["Michigan", "Alaska"];

  $newl = str_replace($short, $long, $l);
?>
<?php if (preg_match('(Michigan|Alaska)', $newl) === 1): ?>

   <?= $newl ?>
 <?php else: ?>

<?php endif; ?>

Comment: @AnwarNairi   ... the replace is un useful  .. the regexp can check for MI an AL directly  ,, without replacing  .. .. to me the use of regexp  without replace seems a lot of  more clear and clean
Comment: @Smith  i don't understand .. the difficult part for you is the replace of the string .. ???  let me know
Comment: You miss the part where the user wants to replace `AL` by `Alabama` for example.
Comment: Let's say I have 'Montgomery,-AL' in '$l' then your code should returns 'Alabama' for '$l'
Comment: Yes, exactly, replacing is the issue
Comment: that's very close, but please update your answer to replace 'Alabama' with whole 'Montgomery,-AL' not just with 'AL'
Comment: this is not a coding service  .. and looking to  your original question  .,. there is not refer  to you last comments  ... ..in your OP you tell just about changin the state CODE with the state name  ..not others ..  you should try yourself to buil the string you need .. non ask  to other to write code for you ..
Comment: ok, ill accept your abswer and will ask this question in another time. thanks


how to use kmeans on a hsv matrix

Question: I am trying to use kmeans clustering only on the h matrix (from the original picture) and I am having trouble with the size of the matrix that I use with kmeans. I know that I need to reshape it , but noting I tried works.
Here is what I tried :
x = imread('4.jpg');
hsv=rgb2hsv(x);
H=c(:,:,1);
[m,n]=size(H);
X = reshape(H,[m,n,3]);
X = double(squeeze(X));
IDX = kmeans(double(H),3);

I get the error:

to reshape the number of elements must not change.

Please help,
Thank you!
Comment: What's the purpose of the `reshape` and `squeeze` lines. I think it should work without them.
Answer: Note your reshape will not work because the original size is m*n and your are trying to reshape into something with a size of m*n*3. You can't change the size with reshape.
This works:
x = imread('peppers.png');
hsv=rgb2hsv(x);
H=hsv(:,:,1); %******H=c(:,:,1);
[m,n]=size(H);
figure(1), imshow(H);
%X = reshape(H,[m,n,3]);
%X = double(squeeze(X));
IDX = kmeans(double(H(:)),3);  % NOTE change to this line
H = reshape(IDX,[m,n]);
figure(2), imagesc(H)

Comment: @user2339198 You get the indices into the image just by reshaping H. Also, if you find a post helpful, it is a good idea to up-vote or accept it.
Comment: Ok thank you very much for your help!
I have another question , I need to take the result of the kmeans (IDX) and go over the H matrix and replace every picsel  with the value that kmeans gave to it : 1 or 2 or 3.
I tried writing :
H(IDX == 1) = 0;
H(IDX == 2) = 100;
H(IDX == 3) = 255;
But it doesn't replace all the matrix.,Just part of it.
Actually my  purpose is to separate the picture into clusters using kmeans but not on the original picture. Only on the H matrix.
Any ideas?

how to use kmeans on a hsv matrix


'NoneType' object has no attribute 'groups'

Question: Estou usando uma função na minha TemplateTagsDjango que basicamente verifica se o usuário está no grupo que tem a permissão para o determinado botão.
O retorno 'True ou False' funciona bem, ou seja, ele mostra o botão caso o usuário esteja no grupo, porém  ao tentar abrir o botão, eu tenho o seguinte erro no console AttributeError: 'NoneType' object has no attribute 'groups'
. Não sei se tem alguma coisa a ver por ser um modal que teria que ser aberto após clicar no botão, pois em outro botão que tem uma função de apenas enviar um e-mail e não muda o usuário de tela, funciona sem erros. Não encontrei na internet nada parecido com meu problema, agradeço qualquer luz.
Minha Função
@register.filter
def group_permission(user, grupo):
if user.groups.filter(name=grupo):
    return True

return False

Meu Template

        {% if user|group_permission:'GERENCIA' %}
        Adicionar

        {% endif %}

Minha View
@login_required
def inventario_create(request):
if request.method == 'POST':
    print('entrou no POST do create')
    form = InventarioForm(request.POST)
else:
    form = InventarioForm()
return save_insert(request, form, 'inventario_create.html')

Essa é meu JS que chama o Modal

var ShowForm = function(){
  var btn = $(this);
  $.ajax({
   url: btn.attr("data-url"),
   type: 'get',
   dataType:'json',
   beforeSend: function(data){
                waitingDialog.show('Carregando Inventários', {dialogSize: 'sm', progressType: 'success'})
   },
   success: function(data){
       waitingDialog.hide();
       $('#myModal .modal-content').html(data.html_form);
       $('#myModal').modal('show')
   },
    error: function (error) {
                    console.log(error);
                    alert('error handing here');
              }
  });
 };

**Tracerback do Erro**
Traceback (most recent call last):
  File "/Users/rodolfosousa/Documents/GitHub/InventoryPortal/venv/lib/python3.7/site-packages/django/core/handlers/exception.py", line 34, in inner
    response = get_response(request)
  File "/Users/rodolfosousa/Documents/GitHub/InventoryPortal/venv/lib/python3.7/site-packages/django/core/handlers/base.py", line 115, in _get_response
    response = self.process_exception_by_middleware(e, request)
  File "/Users/rodolfosousa/Documents/GitHub/InventoryPortal/venv/lib/python3.7/site-packages/django/core/handlers/base.py", line 113, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "/Users/rodolfosousa/Documents/GitHub/InventoryPortal/venv/lib/python3.7/site-packages/django/contrib/auth/decorators.py", line 21, in _wrapped_view
    return view_func(request, *args, **kwargs)
  File "/Users/rodolfosousa/Documents/GitHub/InventoryPortal/inventarios/views.py", line 103, in inventario_create
    return save_insert(request, form, 'inventario_create.html')
  File "/Users/rodolfosousa/Documents/GitHub/InventoryPortal/venv/lib/python3.7/site-packages/django/contrib/auth/decorators.py", line 21, in _wrapped_view
    return view_func(request, *args, **kwargs)
  File "/Users/rodolfosousa/Documents/GitHub/InventoryPortal/inventarios/views.py", line 123, in save_insert
    data['inventario_list'] = render_to_string('inventario_list.html')
  File "/Users/rodolfosousa/Documents/GitHub/InventoryPortal/venv/lib/python3.7/site-packages/django/template/loader.py", line 62, in render_to_string
    return template.render(context, request)
  File "/Users/rodolfosousa/Documents/GitHub/InventoryPortal/venv/lib/python3.7/site-packages/django/template/backends/django.py", line 61, in render
    return self.template.render(context)
  File "/Users/rodolfosousa/Documents/GitHub/InventoryPortal/venv/lib/python3.7/site-packages/django/template/base.py", line 171, in render
    return self._render(context)
  File "/Users/rodolfosousa/Documents/GitHub/InventoryPortal/venv/lib/python3.7/site-packages/django/template/base.py", line 163, in _render
    return self.nodelist.render(context)
  File "/Users/rodolfosousa/Documents/GitHub/InventoryPortal/venv/lib/python3.7/site-packages/django/template/base.py", line 937, in render
    bit = node.render_annotated(context)
  File "/Users/rodolfosousa/Documents/GitHub/InventoryPortal/venv/lib/python3.7/site-packages/django/template/base.py", line 904, in render_annotated
    return self.render(context)
  File "/Users/rodolfosousa/Documents/GitHub/InventoryPortal/venv/lib/python3.7/site-packages/django/template/loader_tags.py", line 150, in render
    return compiled_parent._render(context)
  File "/Users/rodolfosousa/Documents/GitHub/InventoryPortal/venv/lib/python3.7/site-packages/django/template/base.py", line 163, in _render
    return self.nodelist.render(context)
  File "/Users/rodolfosousa/Documents/GitHub/InventoryPortal/venv/lib/python3.7/site-packages/django/template/base.py", line 937, in render
    bit = node.render_annotated(context)
  File "/Users/rodolfosousa/Documents/GitHub/InventoryPortal/venv/lib/python3.7/site-packages/django/template/base.py", line 904, in render_annotated
    return self.render(context)
  File "/Users/rodolfosousa/Documents/GitHub/InventoryPortal/venv/lib/python3.7/site-packages/django/template/loader_tags.py", line 62, in render
    result = block.nodelist.render(context)
  File "/Users/rodolfosousa/Documents/GitHub/InventoryPortal/venv/lib/python3.7/site-packages/django/template/base.py", line 937, in render
    bit = node.render_annotated(context)
  File "/Users/rodolfosousa/Documents/GitHub/InventoryPortal/venv/lib/python3.7/site-packages/django/template/base.py", line 904, in render_annotated
    return self.render(context)
  File "/Users/rodolfosousa/Documents/GitHub/InventoryPortal/venv/lib/python3.7/site-packages/django/template/defaulttags.py", line 302, in render
    match = condition.eval(context)
  File "/Users/rodolfosousa/Documents/GitHub/InventoryPortal/venv/lib/python3.7/site-packages/django/template/defaulttags.py", line 876, in eval
    return self.value.resolve(context, ignore_failures=True)
  File "/Users/rodolfosousa/Documents/GitHub/InventoryPortal/venv/lib/python3.7/site-packages/django/template/base.py", line 698, in resolve
    new_obj = func(obj, *arg_vals)
  File "/Users/rodolfosousa/Documents/GitHub/InventoryPortal/inventarios/templatetags/check_permission.py", line 15, in group_permission
    if user.groups.filter(name=grupo):
AttributeError: 'NoneType' object has no attribute 'groups'

Comment: À primeira vista parece que o teu user é None, na função group_permission. A informação que colocaste não parece que seja suficiente para que alguém consiga saber ao certo o que se passa
Comment: @Miguel, é exatamente isso, a duvida e saber pq pois no modal q se abre, o user é carregado, tenho sucesso se carregar ele dessa forma no template {{ form.user }}.
Answer: Use desta forma:
from django import template

register = template.Library()

@register.filter(name='has_group')
def has_group(user, group_name):
    return user.groups.filter(name=group_name).exists()

No seu template:
{% if request.user|has_group:"GERENCIA" %}

Usuário pertente ao grupo
{% else %}

Ususário não pertence ao grupo

{% endif %}

Comment: show, funcionou @JACKSON, muito obrigado.


Can a smaller viola be used as a violin?

Question: My son plays the violin.
Recently, we saw that someone in the neighborhood is selling a viola,
I don't remember the exact size, perhaps it was 1/4.
Is it possible to string the viola using violin strings
and to play it as a violin?
I know that an adult-sized viola is larger than an adult-sized violin,
but are there any differences in the dimensions of a violin and a viola,
so that maybe a 1/8 sized viola is equivalent to a say 1/4 sized violin?
Comment: It isn't a bad idea at all.
Comment: This is a bad idea, don't do it
Answer: Yes, it is absolutely possible to restring a smaller size Viola into a Violin.  You will not damage the instrument by doing so.
Fractional size violins can roughly correspond with smaller size violas, although technically some will be slightly different in length.

4|4 Violin = 14 inch Viola
3|4 Violin = 13 inch Viola (Violin body often 13 ¼ inch)
1|2 Violin = 12 ½ inch Viola
1|4 Violin = 11 inch Viola

In most cases if the strings are good you can move the G D and A strings down and add a new E string.
The tension of viola strings run slightly higher than violin strings,  so keeping them may be similar to moving to a higher tension violin set, although looking at a string tension chart there is some pretty wide variation of tensions by brand across the smaller size instruments.
Technically the body of the viola is usually deeper than a violin, but in some brands I've seen the only difference between the viola and violin models was the label inside, and what set of strings were put on. The dimensions were otherwise identical.
I haven't personally made a viola, but checking my measurement book it looks like the full size viola top plate is made slightly thicker.  For mass manufactured student size instruments I seriously doubt that most models would have a different tooling than the violin plates.
Another difference you may see is the viola bridge can be set slightly higher than a violin bridge would be, up to a millimeter or so for the thicker strings.
If the viola you are converting does have a deeper body or thicker plates, there will be a tonal difference. In the mass manufactured student instrument market it is unlikely that the tonal difference will be significant.
If you have a hand made and plate-tuned smaller viola made by a trained Luthier, then I wouldn't recommend converting it, since it will have been made to respond to the viola tuning and it is better to keep that kind of instrument in the tuning it was designed for.
Comment: Yep.  Over the years I've converted many a violin into a small viola by putting what's sold as a "1/2 viola" C string on the bottom and moving the G, D, and A strings up one notch.  Should would perfectly well the other way around as well.
Answer: I would not recommend it. Full size violins and violas have significantly different lengths, so you may end up in something with a similar length, but:

viola strings are thicker and not as tensely stretched
the instrument is optimized for different resonance frequencies.

So you would have to restring the instrument, risk damage due to higher tension and it is not guaranteed, that it sounds well afterwards.
Given, that viola players are typically in short supply in amateur orchestras (quite the opposite with violin players), your son could switch to viola, however. The teacher of our son regularly let her students try playing the viola - it's always possibly, that the student finds it more pleasing. The need to learn the alto clef is a disadvantage, however, even if some casual players use mental short cuts to map the score to treble key.
Comment: Humorous: "Mothers, don't let your children grow up to be violists.."  Serious: the sooner a musician learns to read multiple clefs, the better.  While alto clef is relatively rare (other than for viola), once a kid gets used to the concept of multiple clefs, the easier it gets to learn to read additional clefs, or to transpose from one key to another.
Comment: @NeilMeyer - probably due to so much more music being available in treble, and to a lesser extent, bass clefs. If one only uses, say, alto clef, then one finds it more difficult to read others. I read treble and bass, but would struggle a bit with alto, as I'm not used to it. Yes, it's another trick up your sleeve, but I'd rather use my time more productively.
Comment: @NeilMeyer: I wish all musicians would be able to read music in _any_ of the four clefs...
Comment: Why is learning the alto clef a disadvantage?
Comment: Note that a small-sized viola will be designed to withstand the string tension *when strung as a viola* - and that will be lower than a full-size viola, because the strings are shorter. The fact that it is (approximately) the same size as a full-size violin doesn't mean it is built the same way as a full-size violin!
Comment: All musicians should be able to read music in all four the clefs regardless of what one your instrument uses.
Comment: @NeilMeyer  Theoretically,  you're allowed to put the "K" anywhere on the staff.  The central convergence point indicates where middle C is.  There's no law against making, say, the top line middle C :-) .   Clefs aside, it'd be nice if musicians were able to transpose the basics such as major 2 and major 5   (e.g. Bb to C  or Bb to Eb)
Comment: @NeilMeyer The bass and treble clefs are easy to learn together, since they nicely transition into the other at the middle C. The alto clef doesn't do that at all, not to mention the lines/spaces not matching up with the same notes on the treble clef. I think it's good to learn the alto clef later when you're comfortable with bass and treble, else it'll just confuse beginners.
Comment: @user3932000 as a matter of fact, it does --  the middle C between treble and bass clef happens to be the middle line on the alto staff. It would be more correct to say that the following lines up and down are overlap into treble and bass clefs. See http://www.viola.com/pix/clefs.gif
Answer: I transitioned from violin to viola by playing a 3/4 size viola for a while. While the 3/4 viola (a Boosey and Hawkes, from memory) was nominally the same scale length as a 4/4 violin, the body was notably deeper.
Answer: It's not an absolutely terrible idea, functionally speaking (14" viola = approx. 4/4 violin), but do keep in mind that this is mostly preferable for fractional instrument sizing.
Adult full size violas are much larger (most professionals play 16" or larger, a few play 15.5", and even fewer play 15"). Just be sure to use proper viola strings (you might need to have a viola bridge carved to accommodate the strings properly), and also be aware that the body of the violin is meant to resonate best at its intended frequencies, so the body is thinner than your average viola proportions and may not be as resonant especially in the lower frequencies.
In essence, it functionally works, but ends up being a sub-par instrument.
Answer: Regardless of the size of the viola or violin they operate in different registrars. If you play violin for music written for viola you will find a whole lot of notes impossible to play. The lowest notes on a Viola is the c an octave below middle c where the violin only goes as low as the g below middle c.
Also even if you have music that fits the compass you may know also find that the fingering is all wrong and this may make music again either impossible or a whole  lot harder than need be. This may be the case regardless of the size of the particular instrument
Comment: If you want to raise the pitch of the instrument by a fifth, you *absolutely* need to use thinner strings - otherwise the string tension would be more than double what the instrument was designed for.
Comment: This is true, but I do think that the OP would attempt to put violin strings on the viola.


How to marshal a DataHandler annotated as @XmlAttachmentRef with JAXB?

Question: I'm trying to marshal an object which has a DataHandler field with JAXB (2.1.12). For streaming support, the DataHandler is annotated with @XmlAttachmentRef. Serialization and streaming over web services (Metro on JBoss) work fine, but plain marshalling with JAXB doesn't.
Here is a stripped down example:
public class DataHandlerAttachmentSerialization {

    @XmlRootElement
    static class RootObject {
        @XmlElement
        @XmlAttachmentRef // Works without this, but required for streaming
        DataHandler dataHandler = new DataHandler(
                new com.sun.xml.ws.util.ByteArrayDataSource(
                " ".getBytes(), "application/octet-stream"));
    }

    @Test
    public void test() throws JAXBException {
        JAXBContext context = JAXBContext.newInstance(RootObject.class);
        Marshaller marshaller = context.createMarshaller();
        StringWriter writer = new StringWriter();
        marshaller.marshal(new RootObject(), writer);
        Assert.assertNotNull(writer.toString());
    }
}

Running this test yields the following stack trace:
javax.xml.bind.MarshalException
 - with linked exception:
[com.sun.xml.bind.api.AccessorException: java.lang.NullPointerException]
    at com.sun.xml.bind.v2.runtime.MarshallerImpl.write(MarshallerImpl.java:318)
    at com.sun.xml.bind.v2.runtime.MarshallerImpl.marshal(MarshallerImpl.java:244)
    at javax.xml.bind.helpers.AbstractMarshallerImpl.marshal(AbstractMarshallerImpl.java:96)
    ...
Caused by: com.sun.xml.bind.api.AccessorException: java.lang.NullPointerException
    at com.sun.xml.bind.v2.runtime.XMLSerializer.reportError(XMLSerializer.java:246)
    at com.sun.xml.bind.v2.runtime.XMLSerializer.reportError(XMLSerializer.java:261)
    at com.sun.xml.bind.v2.runtime.ClassBeanInfoImpl.serializeBody(ClassBeanInfoImpl.java:335)
    at com.sun.xml.bind.v2.runtime.XMLSerializer.childAsSoleContent(XMLSerializer.java:593)
    at com.sun.xml.bind.v2.runtime.ClassBeanInfoImpl.serializeRoot(ClassBeanInfoImpl.java:320)
    at com.sun.xml.bind.v2.runtime.XMLSerializer.childAsRoot(XMLSerializer.java:494)
    at com.sun.xml.bind.v2.runtime.MarshallerImpl.write(MarshallerImpl.java:315)
    ... 25 more
Caused by: com.sun.xml.bind.api.AccessorException: java.lang.NullPointerException
    at com.sun.xml.bind.v2.runtime.reflect.AdaptedAccessor.get(AdaptedAccessor.java:74)
    at com.sun.xml.bind.v2.runtime.reflect.TransducedAccessor$CompositeTransducedAccessorImpl.writeLeafElement(TransducedAccessor.java:250)
    at com.sun.xml.bind.v2.runtime.property.SingleElementLeafProperty.serializeBody(SingleElementLeafProperty.java:98)
    at com.sun.xml.bind.v2.runtime.ClassBeanInfoImpl.serializeBody(ClassBeanInfoImpl.java:332)
    ... 29 more
Caused by: java.lang.NullPointerException
    at com.sun.xml.bind.v2.runtime.SwaRefAdapter.marshal(SwaRefAdapter.java:80)
    at com.sun.xml.bind.v2.runtime.SwaRefAdapter.marshal(SwaRefAdapter.java:65)
    at com.sun.xml.bind.v2.runtime.reflect.AdaptedAccessor.get(AdaptedAccessor.java:72)
    ... 32 more

Line 80 in SwaRefAdapter is return am.addSwaRefAttachment(data); and am was assigned with AttachmentMarshaller am = XMLSerializer.getInstance().attachmentMarshaller; so it seems attachmentMarshaller is null at this point if the @XmlAttachmentRef is present.
Do I need to set up something differently, or use the JAXB API in a different way to handle attachments?
Answer: When using JAXB outside of a JAX-WS environment a JAXB implementation should be default inline the binary content in the XML document as base64Binary.
This appears to be a bug in the Metro implmentation of JAXB (the RI included in the JDK/JRE).  If you use another JAXB implementation such as EclipseLink JAXB (MOXy), this will work correctly.  To use EclipseLink MOXy add the eclipselink.jar (available here) to your class path and add a jaxb.properties file in with your model classes when the following content:
javax.xml.bind.context.factory=org.eclipse.persistence.jaxb.JAXBContextFactory

JAX-WS registers AttachmentMarshallers & AttachmentUnmarshallers to handle binary content in JAXB models.  You could specify your own when using JAXB standalone if you wanted.
http://download.oracle.com/docs/cd/E17409_01/javase/6/docs/api/javax/xml/bind/attachment/AttachmentMarshaller.html


Different functions use the same function, reduce overhead

Question: Code:
namespace Dialog {
    enum class Type {Info, Warning, Error};
    enum class Buttons {OK, OK_CANCEL, YES_NO, YES_NO_CANCEL};
    void Box(Pane* parent, Core::String, Core::String, Buttons, Type);
}

I could define InfoBox like this:
void InfoBox(Core::String title, Core::String text, Buttons b) {
    Box(nullptr, title, text, b, Type::Info);
}

but with this approach I have overhead due to the extra function call.
How can I reduce the overhead?
Comment: This is GUI code, right? You **won't notice** the overhead!
Comment: **Never** optimize without profiling and measuring!
Comment: Why do people micro optimize - and miss the bigger picture?
Comment: cause if people dont do it, you get software slow like windows :)
Answer: There won't be any. The compiler will trivially inline your function. Even if it didn't, the overhead of the call will add up to absolutely nothing compared to other GUI overheads.
Comment: @anhadikal you *also* forgot how often the code will be called. Overhead in a function that is called once per hour is completely insignificant. In something that's called millions of times per second, it's noticeable.
Answer: For the sake of argument, let's say a CPU can execute one instruction per cycle.
Let's say you're running on an old, slow CPU which runs at a mere 1GHZ. And let's assume it only has a single core.
A function call consists basically of pushing a few values onto the stack, jumping to another location, popping a few values off the stack, and, once the function is completely, pushing the return value onto the stack (under some calling conventions), and jumping back to where the function was called from.
Let's call it 10 instructions overall.
Let's say your user is completely and utterly insane, and he opens 1000 InfoBoxes every second.
That means you waste 1000 * 10 instructions = 10,000 instructions per second.
The CPU can run 1,000,000,000 instructions every second. That means you're wasting 0.0001% of the available CPU time.
Is that something to worry about?
And this is without taking compiler optimizations into account, which would probably reduce the overhead to, well, a big fat zero. (The function call is very likely to be inlined). But in the worst case, a rough approximation is that you're wasting one thousandth of one percent of your CPU's execution time in the worst case, if the user is unrealistically eager about displaying InfoBoxes.
Answer: If I am understanding you correct,you can use the concept of default argument
void InfoBox(Core::String title="Hello", Core::String text="Info", Buttons b=Buttons::OK,Type typ=Type::Info) {
    Box(nullptr, title, text, b, Type::Info);
}

Or Also,
void Box(Pane* parent=0, Core::String title="Hello", Core::String text="Info", Buttons b=Buttons::OK,Type typ=Type::Info);

And then your calls will range from
InfoBox();
InfoBox("Hi");
InfoBox("Hi","Welcome");
InfoBox("Hi","Welcome",b=Buttons::OK_CANCEL);
InfoBox("Hi","Welcome",b=Buttons::OK_CANCEL,Type::Warning);

Comment: This is not an answer to the question asked.


php get namespace of included file

Question: //file foo.php
<?php
namespace foo;
class foo{
    function __construct(){
        echo "hello";
    }
}
?>

//file index.php
<?php
require_once("foo.php");
echo __NAMESPACE__;
?>

My question is, from my index.php file, is it possible to know what the namespace of foo.php is without reading the file contents and doing a regular expression on it?  That just seems like a lot of overhead.
///EDIT
I'd really like to be able to dynamically add the namespace to the included file.
<?php
namespace dynamic;
require_once("foo.php");
echo __NAMESPACE__;
?>

I want to allow for third-party plugins, but php namespaces seems terrible.  I don't want to have the plugin editors have to create a namespace.
Comment: Is it possible to just use the keyword "use" IE: "use foo". Sorry -- not sure if this will work or not though
Answer: No. But you could trick it this way round:
//file foo.php
<?php
  namespace foo;
  //...
  return __NAMESPACE__;  // must be last line
?>

And for reading it out:
//file index.php
<?php
  $ns = require_once("foo.php");

Comment: n.b. returning values from includes may be regarded as bad practice, as it is not traditional behavior.
Answer: Well, you could scan the class namespace. It contains namespaces. It's the PHPUnit way of doing things. So i.e.:
$namespaces = get_current_namespaces();

include 'plugin/main.php';

$newNamespaces = get_current_namespaces();
array_diff($namespaces, $newNamespaces)

Here is how you can implement get_current_namespaces(): is it possible to get list of defined namespaces
Comment: I am not arguing, but this way, you will catch only "new" namespaces.
Comment: You're right @Nick. What it should be, is a variant of the function http://stackoverflow.com/a/5227353/181664 to detect all newly defined classes and get the namespace off that instead.
Answer: If you know the file, you can simply extract the namespace form it :).
function extract_namespace($file) {
    $ns = NULL;
    $handle = fopen($file, "r");
    if ($handle) {
        while (($line = fgets($handle)) !== false) {
            if (strpos($line, 'namespace') === 0) {
                $parts = explode(' ', $line);
                $ns = rtrim(trim($parts[1]), ';');
                break;
            }
        }
        fclose($handle);
    }
    return $ns;
}

And you will be not constrain to return something at the end of file that can be broke from exit or other return instructions.
Answer: I worked out the fairly laborious manual way to do this.
Like discussed at top the process itself is simple:

get your list of files for each file. Now for each file:
create a random namespace id
trim file and replace the first start tag
add namespace id and start tag to file
write to  temp file
import temp file
do any reflection required then cleanup

I've got an example with some zend here.... probably not the most efficient but it works.
<?php
//first setup zend
set_include_path(get_include_path() . PATH_SEPARATOR . dirname(__FILE__)."/../zend/library/");
require_once 'Zend/Loader/Autoloader.php';
$loader = Zend_Loader_Autoloader::getInstance();
$loader->registerNamespace(dirname(__FILE__)."/../zend/library/");

//include my extender class
class Zend_Reflection_File_WithNamespace extends Zend_Reflection_File {
    public function getFunctionsWithNamespace($namespace = '', $reflectionClass = 'Zend_Reflection_Function')
    {
        $functions = array();
        foreach ($this->_functions as $function) {
            $newName = $namespace . "\\" . $function;
            $instance = new $reflectionClass($newName);
            if (!$instance instanceof Zend_Reflection_Function) {
                require_once 'Zend/Reflection/Exception.php';
                throw new Zend_Reflection_Exception('Invalid reflection class provided; must extend Zend_Reflection_Function');
            }
            $functions[] = $instance;
        }
        return $functions;
    }
}

//find file(s)
$startDir = 'hello/';
//$tempDir = 'php://temp/resource=';
$tempDir = 'temp/';
$fileList = scandir($startDir);

function ppPrintR($data) {
    echo "
";
    print_r($data);
    echo "
";
}

//Now loop through each file, first writing to temp, including and then testing
foreach ($fileList as $key => &$fileItem) {
    if (is_file($startDir . $fileItem)) {
        //Take file and convert it
        $findDir = $startDir . $fileItem;
        echo $startDir . $fileItem;

        $inContents = file_get_contents($findDir);
        $randIden = 'm' . preg_replace('/\.|\s/', '', microtime());

        //Replace the <?[php] at the start of the file with <? namespace xyz;
        $inContents = trim($inContents);
        $addString = 'namespace ' . $randIden . '; ';

        $longTagPos = strpos($inContents,'<?php');
        $shortTagPos = strpos($inContents,'<?');

        if ($longTagPos !== false && $longTagPos < 10) {
            $inContents = str_replace('<?php', '', $inContents);
            $addString = '<?php ' . $addString;
        }
        else if ($shortTagPage !== false && $longTagPos < 10) {
            $inContents = str_replace('<?', '', $inContents);
            $addString = '<? ' . $addString;
        }
        $outContents = $addString . $inContents;

        //Now write and require new temp file
        $tempItem = $tempDir . $fileItem;
        file_put_contents($tempItem, $outContents);
        require($tempItem);

        //Now do normal things
        $reflectedFile = new Zend_Reflection_File_WithNamespace($tempItem);
        echo 'Before
';
        $functions = $reflectedFile->getFunctionsWithNamespace($randIden);
        echo 'After
';

        //Now foreach function, read params and consider execution
        foreach($functions as &$functionItem) {
            echo $functionItem->name . "
";
            $functionParams = $functionItem->getParameters();
            ppPrintR($functionParams);
        }

        //FIXME should clean here
    }
}
?>

Comment: Though your answer does provide something that works, it is overkill to turn to Zend just to do this. With just PHP itself, there are multiple ways of handling this far quicker. Please consider you're own knowledge and capabilities before turning to a framework ;)
Comment: True, I was just using zend throughout the project, so it wasnt really anything extra. Love to see a non framework solution.

php get namespace of included file


É possivel usar "alias" (as) no "Model.create()"?

Question: Quando uso findAll() consigo renomear (alias) as colunas da seguinte forma:
const response = await Cidades.findAll({
  attributes: [
    ['nomeCidade', 'nome']
  ]
});

Então a coluna nomeCidaded irá ter a chave apenas como nome:
console.log(response); // { nome: "São Paulo" }

A minha dúvida é se poderia fazer o mesmo com Model.create(). O retorno hoje é esse:
const response = await Cidades.create({
   nomeCidade: "São Paulo", //nome da coluna no banco de dados
   UF: "SP"
})

console.log(response) //{ nomeCidade: "São Paulo", UF: "SP" }

Comment: Espero que minha edição lhe dê uma ideia de como limitar a pergunta ao que é importante, havia muita coisa irrelevante na dúvida, esse é o segundo maior problema das perguntas novas no site. A pergunta tem um problema especifico e elas precisam ser focadas no especifico, sempre tento orientar para melhorarem nisso.
Comment: Em futuras perguntas que vier a fazer no site é importante sempre adicionar um [mcve], com um passo a passo do que já fez e explicar de forma clara e objetiva, focando no problema especifico. Para aproveitar melhor o site, entender e evitar fechamentos vale a pena ler o [Guia de sobrevivência do Stack Overflow em Português](https://pt.meta.stackoverflow.com/q/8045). Obrigado por compreender.
Comment: Obrigado pelas dicas, tentarei executa-las nas próximas duvidas!
Answer: Creio que não, o método create pode receber um options.returning como um array das colunas que devem ser retornadas (isso se você estiver usando o Postgres). Porém, esse array de returning não aceita um array de arrays (contendo o alias) como o findAll.


Does empty set entails everything?

Question: I am new to propositional logic, and I am trying to figure out whether the below statement is correct:
<code>[a |= c] or [ b |= c] → [a^b |= c]
</code>
First of all, it is obvious that
<code>a^b ⊆ a and a^b ⊆ b.
</code>
Moreover, because either a |= c or b|= c are correct(or both), it seems that a^b must also entail c.
In other words:
Ma ^ b ⊆  Ma  . Also, when we say that  a |= c,

we have M a ⊆ Mc.

But what if the intersection of a and b is empty? Does this argument still hold?
Comment: You are mixing symbols for statements: $a \land b$ is the *conjunction* of statements $a$ and $b$ (reads: "$a$ and $b$") and symbols for sets: $M_{a \land b}$ is the set of models of statement $a \land b$ and in this case we have *intersection* and *inclusion*: $M_{a \land b} \subseteq M_a$.
Comment: Then "^" cannot possibly be intersection, and statements like "a^b$\subseteq$a" are meaningless. I think "^" is supposed to be "$\wedge$" ("and").
Comment: The two are linked but different: $M_{a \land b}=M_a \cap M_b$
Comment: " because either a |= c or b|= c are correct(or both), it seems that a^b must also entail c" Why does that seem to be the case?
Comment: Because M a ^ b ⊆  M a  . Also, when we say that  a |= c, we have M a   ⊆ M c .
Comment: I don't understand your notation - use [mathjax](https://math.meta.stackexchange.com/questions/5020/mathjax-basic-tutorial-and-quick-reference). Regardless, the point is that it's wrong: $a\cap b\models c$ need **not** be true even of $a\models c$ and $b\models c$, let alone if either $a\models c$ or $b\models c$. Maybe $a,b,c$ are *individual* sentences rather than sets of sentences and "^" is **conjunction** ("and"), $\wedge$, rather than intersection, $\cap$? In that case we do indeed have $a\wedge b\models c$ if either $a\models c$ or $b\models c$.
Comment: Sorry for the inconvenience. I have edited my post and added those extra parts there.
Comment: Well, based on the problem description, a, b and c are sentences.
Comment: You said in a comment that $a,b,c$ are sentences, but in the question you talk about their intersection, and you write that some things are subsets of $a$ and $b$. Intersections and subsets make sense if you're talking about sets, but not if you're talking about sentences.
Answer: $a\land b\vDash c$ means that there are no interpretations(aka models) which value $a\land b$ as true but $c$ as false.
If there are no interpretations which value $a\land b$ as true, then the above holds.  (See also vacuous truths)
The intersection of the models $\mathbf M_a$ and $\mathbf M_b$ being empty means there are no models which simultaneously value $a$ and $b$ as true.   Thus $\mathbf M_{a\land b}$ will be empty.   Therefore...

Does empty set entails everything?


Slovenia - Germany last goal of the 25-25 tie in EHF Euro 2018

Question: Luckily, Germany was awarded a penalty after the game was already over, thanks to the video technology (Game report). Now Slovenia files a protest hoping to get the match replayed.
Although I like that decision I am not sure if it was a correct one.

Is it allowed to call the video proof after the final buzzer went off? The rules of the Game don't mention video tech at all.
Is the decision next to a red card (only within the 30-seconds rule) always a penalty if the attacking team didn't score in that situation? I believe it doesn't matter whether or not they passed or shot. No goal = penalty. But some press articles say otherwise.
Answer: Since, infractions and unsportsmanlike conduct that take place before or simultaneously with the final signal are to be punished (2.4), and for situations when referees have strong doubts in relation with the last 30 seconds rule involving the red card and seven-metres throws video proof system can be used (see below).
In this particular case, in the last 30 seconds of a game while the ball is in play, the opponents tries to prevent the team in possession from being able to take a shot on goal or to obtain a clear scoring chance, the guilty player is disqualified according to the corresponding Rules and the team in possession is granted a 7m throw (16:6, 14:1). So, for the last 30 seconds decision next to a red card is always a 7m throw if the player who was fouled, or a teammate, didn't score a goal before the game is interrupted. However, if the player who was fouled, or a teammate, scores a goal before the game is interrupted, the 7m throw is not be granted.

So, from the article that you linked.

When the final whistle sounded, the video technology was called and after analysis, the decision was made that Slovenia's Blaz Blagotinsek stopped Germany's final attempt in the middle circle. The line player was sent off with a red card, Germany received a penalty – and Tobias Reichmann netted to equalise the final result, 25:25 (15:10).

Other source: timeoutmag.com

From International Handball Federation Rules of the Game a) Indoor Handball rules applicable for this case: (emphasis added)

Final Signal
2:3 The playing time begins with the referee's whistle for the initial throw-off. It ends with the automatic final signal from the public clock or from the timekeeper. If no such signal comes, the referee, the timekeeper or the delegate whistles to indicate that the playing time is over (17:9).
Comment:
  If a public clock with an automatic final signal is not available, the timekeeper shall use a table clock or a stopwatch and end the game with a final signal (18:2, 2nd paragraph).
2:4 Infractions and unsportsmanlike conduct that take place before or simultaneously with the final signal (for half-time or end of game, and also for the end of the halves in overtime) are to be punished, also if the resulting free throw (under Rule 13:1) or 7-metre throw cannot be taken until after the signal.
  Similarly, the throw must be retaken, if the final signal (for half-time or end of game, also in overtime) sounds precisely when a free throw or a 7-metre throw is being executed or when the ball is already in the air.
  In both cases, the referees end the game only after the free throw or 7-metre throw has been taken (or retaken) and its immediate result has been established.

Disqualification due to extremely unsportsmanlike conduct also to be reported in writing
8:10 If the referees classify a conduct as extremely unsportsmanlike, a punishment is granted according to the following regulations.
d) if during the last 30 seconds of a game the ball is in play, and the opponents
1) through an infringement by a player of the Rules 8:5 or 8:6 as well as 8:10a or 8:10b (II)
2) through an infringement by an official of the Rules 8:10a or 8:10b (I)
prevent the team in possession from being able to take a shot on goal or to obtain a clear scoring chance, the guilty player or official is disqualified according to the corresponding Rules and the team in possession is granted a 7m throw.
If the player who was fouled, or a teammate, scores a goal before the game is interrupted, the 7m throw shall not be granted.

7-Metre Decision
14:1 A 7-metre throw is awarded when:
d) there is an infraction according to Rules 8:10c or 8:10d (however, see 8:10 last paragraph).

Disqualification
16:6 A disqualification is the appropriate punishment:
b) for seriously unsportsmanlike conduct under 8:9 and extremely unsportsmanlike conduct under 8:10, by a player or team official, on or outside the court;
16:7 After calling a time-out, the referees shall clearly indicate the disqualification to the guilty player or team official, and to the timekeeper/scorekeeper, by holding up a red card (hand signal no. 13, see also Rule 16:8).

Guidelines and Interpretations
Last 30 seconds (Rules 8:10c, 8:10d)
The last 30 seconds of the game occur during regular playing time (end of 2nd half) as well as at the end of the second half during both overtime periods. The start of the last 30 seconds of the game begins when the clock indicates 59 minutes 30 seconds (or 69:30, 79:30) or 0 minutes 30 seconds.

From insidethegames.biz article:

The IHF official added that the extent of the video proof system had been enlarged since 2015.
"We'll use the video proof in some new cases," he said. "When referees are not sure if a player deserves a red or a blue card.
"Situations when referees have strong doubts in relation with the last 30 seconds rule involving the red card and seven-metres throws.
"Situations in the last 30 seconds of the match when the defending team has no goalkeeper; if the referees are not sure if the decision must be a seven-metres throw or not.
"The last two cases only when the situation is crucial for the final score of the match."


Is it possible to get a reference to an Android Dialog from one of its children?

Question: I'm using a FragmentActivity with a FragmentStatePagerAdapter. In my fragments, I set click listeners on some views that respond by showing a Dialog. The Dialog layout is supplied via an XML layout resource, and some buttons in this layout use the onClick property to fire off a method in the FragmentActivity. And that works fine, the method gets called correctly when the buttons are clicked.
But I'd like to know how to get hold of a reference to the Dialog when the onClick method is called. All I have is the view (button) that was clicked, which is a child of the Dialog's layout. I actually just want to dismiss the dialog. And I'd really prefer not to have to make the Dialog some sort of global, static singleton or whatever, there must be a cleaner way. I'll try to illustrate it with some code:
public class MyFragment extends Fragment {
    ...
    ...
    @Override
    public View onCreateView(...) {
        ...
        dialogTrigger.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View src) {
                MyDialog dialog = new MyDialog(src.getContext());
                dialog.show();
            }
        });
    ...
}

public class MyActivity extends FragmentActivity {
    ...
    public void doIt(View src) {
        // dialog ref ???
    }
    ...
}

...and the Dialog layout XML:
<GridLayout ...>

    <Button
        ...
        android:onClick="doIt" />
...
etc.

Answer: No, not the way you are doing it, because the dialog only exists once clicked. If however you move the declaration to a member variable, yes (as below)
 public class MyFragment extends Fragment {

    private MyDialog dialog;

    @Override
    public View onCreateView(...) {
        ...
        dialogTrigger.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View src) {
                dialog = new MyDialog(src.getContext());
                dialog.show();
           }
        });
        ...

       protected MyDialog getDialog() {
           return dialog.
       }
   }

   public class MyActivity extends FragmentActivity {

   public void doIt(View src) {
      //TODO: seems you want to do this too (?):  dialogTrigger.callOnClick();
      //EDIT: oops i missed the following the first time
      MyDialog dialog = ((MyFragment)getSupportFragmentManager().findFragmentById(R.id.my_fragment)).getDialog()
      ....
   }

There are better ways to handle such a situation though
Comment: This did help, sorry for the delay.
Comment: Are you suggesting that I make the dialog static and include a static class method for retrieving the dialog ref? I tried that there, and it does work, but I'm concerned about the lifecycle. Should I be?. As for the TODO, the doIt method is not called by me. It's called by the framework as a result of a view inside the Dialog being clicked. So in doIt, I just want to close the dialog and then do some other stuff.
Comment: Yes I know its called from the XML, that's why I suggested it as it looked like you cant be sure dialogTrigger is clicked. If it should already be open just make sure you do a null check to be safe
Comment: Ok, well it's definitely being called, logging shows that much anyway.
Comment: I definitely prefer what you're suggesting, but I'm uncertain about how to go about it. My fragments don't have IDs. I'm using a ViewPager and FragmentStatePagerAdapter because the number of fragments is unknown and potentially large. I have an XML layout file with a RelativeLayout at the root, and this is inflated and used as the contents of each fragment. So, I'm not sure exactly what it is that I should reference? I suppose what I need is the currently active fragment...
Comment: It looks like getting the currently active fragment with a ViewPager and FragmentStatePagerAdapter is not straightforward, but I'm also wondering if the static approach is worthwhile. It's simple, it works and there's actually no reason why I would want a situation where multiple fragment instances have refs to different dialog instances. I suppose the only concern is if a fragment is resumed and still carries a ref to a stale dialog...
Comment: Did this solve your problem in the end? can you accept it, or add another answer and close the question so it's off of the android unanswered list, thanks


Local maxima anomalies of likelihood methods

Question: Likelihood methods have many desired properties. Sadly, local maxima in finite samples is not one of them. The fact a local maximum exists near the true parameter value is of no comfort if one converges to different local maxima.
I am looking for works reviewing this problem, demonstrating it, and offering solutions.
Comment: John, are you asking about works discussing, say, which *models* may have multiple local maxima or is your question about *optimization methods* and the risk that they might return maxima that are global but not local?
Comment: Where I'm confused is that ML does *not* say to find just any local maximum: it says to find a *global* maximum. It will--obviously--run into trouble when there exist multiple distinct global maxima, but that's not what you have been asking about here. Further, ML has *nothing* to do with mean squared errors. (That there happens to be a connection with MSE in a regression context through the Gauss-Markov theorem is a useful fact but is not an inherent general property of ML.) Depending on how you measure "performance," there are *loads* of better methods--answering that takes a huge book.
Comment: I'm still trying to understand your question, John, and that includes understanding more precisely what the *problem* itself is. As far as methods other than ML, there are entire multi-volume books written on this topic, so some clearer guidance about that is needed, too.
Comment: @whuber: I would like examples of models which generate the problem. As for the solutions- I would like estimation methods other than maximum-likelihood.
Comment: @whuber: OK- the problem I have is that while the likelihood might have one asymptotic maximum, in a finite sample it will have many local maxima. Some of them (I believe) might be far from the true parameter value. A possible solution is to look for the global maximum. Does this approach have any theoretical justification? Put differently- is there any guarantee the global maximum has lower MSE then any other local maxima? If not, might there be some other estimation method with better performance?
Comment: @whuber: The sequence of roots of the score function converging to the true parameter value, need not be the sequence corresponding to the (finite sample) *global* maximum. It is true that in the "nice" cases, there is a unique sequence so the issue does not arise (Theory of Point Estimation, p.445, Corollary 3.5). But in other cases, I believe the "best" (in MSE or any other sense) estimator might be a local maximum and not a global one. It is these cases I am interested in.
Comment: With this most recent comment, John, your question appears to have changed once again, because it seems to be concerned with *asymptotic* behavior of solutions.  The second part of your comment is opaque to me, because the "local maximum" language is particular to ML and does not apply to most other estimators.
Comment: @whuber: I do not believe this is another question. I was just trying to demonstrate that in finite samples, the global maximum need not be the best estimate (at least that is how I understand the reference I proposed).
Comment: I think you are confusing "best estimate" with "true value," John. This seems to be the difficulty @AdamO was trying to address, also.
Answer: As Cagdas Ozgenc points out in his answer, there is a simple sufficient condition to render this question moot: that the likelihood be concave in the parameter space (almost surely with respect to the sampling distribution of the data).  That does cover many interesting cases (ie, the exponential family), but basically leaves everything else out.
I don't have an answer here, but think that there are several ways this question could be refined or restated:

What properties does the MLE have in finite samples, and under what models?  Although everyone likes the MLE, it's usage (AFAIK) is predicated on asymptotic guarantees.  I can't think of any finite sample guarantees for it.
What properties, if any, does a local maxima have?

Bibliography
"Evaluation of the Maximum-Likelihood Estimator where the Likelihood Equation has Multiple Roots" VD Barnette 1966.
The Cauchy distribution with location parameter offers a canonical example of a likelihood with multiple roots (even asymptotically).
"Testing for a Global Maximum of the Likelihood" Christophe Biernacki, 2005.
A test for consistency for a root of the likelihood equation, based on comparing the observed maximized likelihood to its expected value under the putative argmax
"Eliminating Multiple Root Problems in Estimation" Small, Wang, Yang 2000.
If you are going to read one paper, this is probably it.  Discusses all of the above, also in the context of generalized estimating equations, plus suggests smoothing or penalizing the likelihood to help resolve multiple roots.
Answer: No estimator will converge in probability to the parameter value in finite samples due to the random nature of data in general. Maximum likelihood estimators are consistent and efficient among unbiased estimators of parameter values. In fact, MLEs are root-n consistent by the CLT, meaning that they converge to the parameter value as the sample size increases considerable faster than any other general unbiased estimator (in most cases) including method of moments. Simply put, in correct specifications of probability models for data generating mechanisms, MLE is one of the best tools around. If you're looking for a general probability theory text dealing with asymptotic estimation, I'd refer you to Lehmann & Casella's Theory of Point Estimation.
Comment: In most classical cases (say, the exponential family), the likelihood has a single local maximum. This is not the case for more complicated models.
Comment: MLEs obviously have many good asymptotic properties. It is the multiple local maxima in finite samples that bothers me and you did not adress this in your reply.
Comment: A slightly different problem is with unbounded likelihoods: https://xianblog.wordpress.com/2015/04/02/the-unbounded-likelihood-problem/   and   https://doi.org/10.1080/00031305.2014.1003968
Comment: MLEs *converge* to unique solutions in the long run. Do you not see how in finite samples the likelihood function varies with respect to the observed data to produce many local maxima? This is trivial. It would be impossible to produce estimators with any desirable properties that didn't have that feature.
Answer: This is not an issue of finite samples. It is related to the complexity of the combined error function and the link function. As long as it is quadratic there won't be multiple maxima. If not you will most likely get more than one. For example if you are hypothesizing that the data has a normal distribution then you have:
$N(f(y|x;\theta),\sigma)$
where f is the link function. Now if you consider the pdf:
$f(y) = \frac{1}{(2\pi)^{1/2}\sigma} e^{-\frac{(y-f(x;\theta))^2}{2\sigma^2}}$
The combined function, link function plugged into the distribution, in this scenario is quadratic (don't worry about the exponential as it disappears when you work with its logarithm) if $f(y|x;\theta)$ is a linear function. This happens in linear regression with Gaussian errors for example.
In any case if your distribution doesn't have a quadratic form or when combined with the link function ends up non-quadratic you will have the problem of multiple maxima.
There is no good solution to the problem as finding global maximum is NP-hard.
http://web.maths.unsw.edu.au/~rsw/lgopt.pdf
pages 20-21
There are algorithms that attempt to cover the entire parameter space, but they are very slow as one expects. So it is not an issue of MLE either. If you plug the Likelihood function to a more sophisticated optimizer like simulated annealing, it will search for the global solution.
http://en.wikipedia.org/wiki/Simulated_annealing
Comment: I write comments in my role as moderator: where there is some potential for posts to be misinterpreted, my job is to point that out and request clarification. Of course my interpretation could be incorrect, but the important message is that miscommunication is happening. Instead of accusing your readers of ill will or stupidity, please bear in mind that good communication requires honest effort by *both* parties and try to use what I have written to improve your post.
Comment: There is some misinformation in this reply.  Among the problems are (1) non-quadratic objective functions can have unique global maxima and even may have no other local maxima; (2) The reference to NP-hard is irrelevant (and potentially confusing or misleading) because "this problem" has not even been defined and it's definitely not true that all nonlinear programs involving non-convex functions are NP-hard.
Comment: Is there any reason to prefer the global maximum over a local maximum in finite samples?
Comment: When you think someone is being disrespectful, demagogic, slanderous (which is impossible in a written medium, but never mind), or worse, then please make use of the site's mechanisms for addressing such behavior. Begin by flagging the offending post for moderator attention. If you distrust the moderation (as you seem to), then you can escalate it by a chat, a meta discussion, or by contacting the SE team with a complaint. In the meantime, you have now twice attempted to deflect this conversation from its original point: if you wish to continue commenting, please focus on improving your post.
Comment: @whuber: I didn't say what you claim I said. I said for most of the non-quadratic cases you will have local maxima problem. Of course there are cases where you get unique global maximum when not-quadratic. But in real world most of the time you get stuck in local maxima. In general you have problem of not reading questions properly and bulking at people with comments. You are doing the same to my questions. Sometimes people don't have the basic knowledge to phrase the problems properly. And I understand them because I find myself in such situations most of the time.
Comment: @JohnRos: Of course you should pick the global maximum. That is the objective of the maximization process. The find the best, not the second best. But in real life sometimes you work with what you get.
Comment: There was no mention of stupidity, or implied whatsoever. You are being demagogical. Being a moderator doesn't give you the right to treat people disrespectfully. In this case you are doing it by using the word "stupid" as if I had ever used or implied it. That's either demogogy or slander.
Comment: Excuse me. I never used the word "stupid" but you claimed that I did. It is a lie and you should apologize for it. Being a moderator doesn't give you such rights.


Chrome showing "Error while loading PDF" in web

Question: I am getting an error in chrome while showing pdf on Web view : "error while loading pdf" many times. I am using object tag / iFrame tag for display but didn't get fix this issue. looking for a helpfull suggestion. Appreciating the answer in advance.
Answer: Possible scenarios

The file getting corrupted while downloading using tag / iFrame

better call a http get request to get file and Try creating a blob object with your response
var blob = new Blob([data], { type: blobType });
fileName = 'somename.pdf'
const downloadUrl = URL.createObjectURL(blob);
downloadLink.href = downloadUrl;
downloadLink.setAttribute("download", fileName);
this.$document[0].body.appendChild(downloadLink);
downloadLink.click();
this.$document[0].body.removeChild(downloadLink);

For IE browser specifically :
window.navigator.msSaveBlob(blob, fileName);


Proof of divergence in analysis

Question: I aim to show that the sequence $x_n := n^2 - 10n $ diverges to $+\infty$ by using the definition of divergence (i.e. for a given $M \in \mathbb{R}$, there exists $N$ such that $n \geq N$ implies $x_n > M$).
So my strategy for proving this is that if you give me $M$, I will give you $N$ such that $n \geq N$ implies $x_n > M$.
Somehow it is getting harder than I thought it was, though. I have tried to set $N = M+10$, but I realized that that does not make sense because $M \in \mathbb{R}$ and $N \in \mathbb{N}$.
Any suggestions?
Comment: You could always say something like "select an integer $N \geq M + 10$".  We generally take for granted that such an integer exists (the "Archimedian property" of $\Bbb R$).
Answer: Starting by taking any $M > 0$, we have $n^{2} - 10n = n(n-10) > M$ if $n > M+10$,  so taking $N := \lceil M+10 \rceil$ suffices.
Here $\lceil a \rceil$ denotes the least integer upper bound of $a$ for all $a \in \mathbb{R}$.
Comment: This has not dealt with the fact that $M \in \mathbb{R}$. We are not proving convergence so $M$ does not have to be a positive number.
Comment: @SeojunHong: Did you notice that $n \in \mathbb{N}$? Moreover, I think the OP's problem lies in the integer-taking function.
Comment: What does $n \in \mathbb{N}$ has to do with the fact that we have considered some $m \in \mathbb{R}$? What if $M=-2$? Then $9 > 8$, but $9 (9 -10) \ngeq -2$.
Comment: Well, because that means that the sequence of interest has only finitely many negative terms. @SeojunHong
Answer: Let $M>0$ be given. Choose $N>1$ such that $N-10>M$. Clearly $$\frac{M}{\left|N-10\right|}<1$$ and by choice of $N$ this means $$\frac{M}{\left|N-10\right|}<N$$ It follows for all $n \geq N$ that $\frac{M}{\left|n-10\right|}<n$ and so $$\begin{align}M<n\left|n-10\right| \\ =\left|n^2-10n\right|\end{align}$$ which shows that $x_n$ diverges.
Comment: This has not dealt with the fact that M∈R. We are not proving convergence so M does not have to be a positive number
Comment: @SeojunHong I disagree; The way the proof is written it leaves $M$ general enough to be anything. Second, $n^2-10n$ clearly tends to *positive* infinity. There is no need to consider any negative values of $M$. Lastly, I suggest you review the definition of convergence again. The standard definition is that $|x_n-x|<\varepsilon$ for all $\varepsilon>0$ and $n \geq N$, which means to diverge we'd need $|x_n-x| \geq M$ for all $M,x \in \mathbb{R}$ and some $n > N$. Given that the proof is done with absolute value, we necessarily require $M$ to be positive.
Comment: Well, it is the definition of divergence, so we cannot just prove one-sidedly for $M > 0$ and say there is not need to consider $M \leq 0$. I do not see that the conclusion holds clearly for $M \in \mathbb{R}$.
Comment: @SeojunHong Choose any $M$ you want. Seriously. It doesn't matter. Beacause I know how to find an $N$ such that $M<\left|n^2-10n\right|$ whenever $n \geq N$. This is immediately true for all $M \leq 0$ as $\left|n^2-10n\right|>0$ for all $n \in \Bbb{N}\setminus\{10\}$.
Comment: Yes, I see that. Thank you for your sharing. I really appreciate it.

Proof of divergence in analysis


How to validate for either form fields with vanilla JavaScript

Question: I'm attempting to send an error message when either the email field or the phone field of a form doesn't match the regex. The validation message shouldn't submit if either fields are filled in.
What happens right now when I go to submit the form with one of the fields filled in with the proper information the form gives me the error message and will not post the form. Once I enter the correct input into the other field it processes the form.
What I want it to do is to process the form if either the email field is filled out or the phone field is filled out with information that matches the regular expressions.
If neither of the forms are filled out correctly I want the form to throw the error message.
Here's the if statement I am working with so far.
<form id="contact_form"  action="" method="POST">
    <input type=hidden name="" value="">
    <input type=hidden name="" value="">

    <input  id="name" maxlength="80" name="form_name" placeholder="Name" size="20" type="text" />
    <input  id="email" maxlength="80" name="email" placeholder="Email" size="20" type="text" />
    <input  id="phone" maxlength="40" name="phone" placeholder="Phone number" size="20" type="text" />

    <textarea id="description" name="description" placeholder="How can we help you?"></textarea>

    <input type="submit" name="submit" value="Send message">
</form>

$(document).ready(function() {

  $overlay = $(".modal-overlay");
  $modal = $(".modal-frame");

  $modal.bind('webkitAnimationEnd oanimationend msAnimationEnd animationend', function(e){
  if($modal.hasClass('state-leave')) {
    $modal.removeClass('state-leave');
  }
});
$('.form-close-button').on('click', function(){
     $overlay.removeClass('state-show');
     $modal.removeClass('state-appear').addClass('state-leave');
   });

   $('#contactformbtn').on('click', function(){
     $overlay.addClass('state-show');
     $modal.removeClass('state-leave').addClass('state-appear');
   });

var formHandle = document.forms[0];

formHandle.onsubmit = processForm;

function processForm(){

  var emailInput = document.getElementById('email');

  var emailValue = emailInput.value;

  var phoneInput = document.getElementById('phone');

  var phoneValue = phoneInput.value;

  var regexPhone = /^(1?(-?\d{3})-?)?(\d{3})(-?\d{4})$/;
  var regexEmail = /^([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$/;

if((!regexPhone.test(phoneValue)) ||(!regexEmail.test(emailValue))) {
    nameErr = document.getElementById("name_errormsg");
    nameErr.innerHTML = "Please enter your phone number or a valid email address.";
    nameErr.style.color = "red";
    return false;
}

}
});

If any of you could point out where I went wrong this that would be great!
Thank you for taking the time to read this.
Have a good day.
Comment: When do you actually call this function?
Comment: Hey Dave, Sorry I didn't include all of the code before. I thought that possibly it was an easy statement that someone might know off the top of their head. I shouldn't be making those kind of assumptions given that there could be other errors with my code tho. Thank you for your quick response.
Comment: So what actually happens? What's in your JS console, anything?
Comment: Yep nothing seems to be showing up in my console.
Comment: So what actually happens? Instead of making people read and guess, particularly without a working jsfiddle (or equivalent), explain what precisely happens, what should happen, etc.
Comment: Okay I just added a description for what I would like to happen to my post. I apologize for not including that sooner. I will be sure to include this in any of my future posts.
Comment: What happens right now when I go to submit the form with one of the fields filled in with the proper information the form gives me the error message and will not post the form. Once I enter the correct input into the other field it processes the form.

What I want it to do is to process the form if either the email field is filled out or the phone field is filled out with information that matches the regular expressions.
Answer: Based on your last comment (which should be in the question) your logic is wrong.
You're currently checking for failure of either field. If phone fails or email fails. If one field isn't filled in it'll fail because you don't allow blank.
You want to test for failure of both fields (with a caveat):
if (!regexPhone.test(phoneValue) && !regexEmail.test(emailValue)) {
    ....

Or you can change your regex.
The caveat is that say a user enters in a valid phone, but an invalid email: what should happen in that case? Should validation pass or fail?
Comment: What I would like to have is if both fields are filled in they are both valid before the form processes. Although if one of the fields is left blank say a client doesn't want to give their phone number or email the form will also process.
Comment: @Cakewok Then change the logic to do that--if filled it at all, it must match, e.g., if the field after stripping has content, validate it. It's not difficult, although there are multiple ways it could be implemented. Start with something that works, then make it more elegant if necessary.


Generalized Least Squares: Estimation of Variance-Covariance matrix

Question: Linear model in matrix form is
$
\mathbf{y}=\mathbf{X}\beta+\epsilon\textrm{ where }\epsilon\sim\mathbb{N}\left(0,\sigma^{2}\mathbf{V}\right).
$
Then $\beta$ can be estimated through generalized least squares
as
$
\widetilde{\beta}=\left(\mathbf{X}^{\prime}\mathbf{V}^{-1}\mathbf{X}\right)\mathbf{X}^{\prime}\mathbf{V}^{-1}\mathbf{y}.
$
I'm wondering how to estimate $\mathbf{V}$ here. I'd highly appreciate
if you give me some pointer or give a reference for reading. Thanks
Comment: it depends on what structure you are willing to assume for $V$
Answer: From what you've written, it appears that you know $\mathbf V$ already. Usually, if you write your covariance matrix as $\sigma^2 \mathbf V$, it means that you know the structure given by $\mathbf V$ (e.g., exchangeable for cluster correlations, or something like that), and you only need to estimate the scale $\sigma^2$.
If you don't know $\sigma^2\mathbf V$, but (i) have a good idea about the structure that $\mathbf V$ should have, and (ii) expect the effects to be pretty strong (e.g., difference in variance for different $y_i$'s by a factor of 5, and/or correlations greater than 0.5), then you can proceed via the feasible GLS path (a random econometrics handout from the first page of Google): estimate your model by OLS, construct an estimate $\hat {\mathbf V}$, and plug that estimate in. To do that though does require some sort of a model for $\mathbf V$ so as to be able to describe it with at most a handful of parameters (e.g., correlation coefficient for exchangeable structure; an autoregression correlation or two for time series; a smoothed model for variance with heteroskedastic but uncorrelated errors; etc.). No good at all will come from forming $\hat{\mathbf V}={\mathbf e}{\mathbf e'}$, as this matrix won't even be invertible.
If you don't know much about this covariance at all, and potentially it may not affect results much, and may not provide any worthwhile efficiency gains, you would be better off leaving things as they are: if you are overdoing any sort of corrections on i.i.d. data, you are just unnecessarily increasing the variance of the estimates.
Amemiya's Advanced Econometrics treats the subject of generalized least squares and FGLS in and out.


Not getting appledoc to document NS_ENUM

Question: could someone please explain what I am doing wrong when documenting my typedef NS_ENUM?
This is my syntax:
/** The different menu items
 */
typedef NS_ENUM(NSInteger, kMenuItem) {
    /** The start page */
    kMenuItemStartPage = 0,
    /** The new round item */
    kMenuItemNewRound,
    /** The archive item */
    kMenuItemArchive,
    /** The participants item */
    kMenuItemMyParticipants,
    /** The locations item */
    kMenuItemMyLocations,
    /** The settings */
    kMenuItemSettings,
    /** The contact page */
    kMenuItemContact,
    /** The count */
    kMenuItemTotal
};

/**
 * This is the Menu View Controller.
 *
 * The menu view controller handles the menu the menu and its options. You can access the menu view controller using the `menuContainer` in the `ApplicationDelegate`
 *
 */
@interface MenuTVC : UITableViewController

@end

My run script build phase:
APPLEDOC_PATH=`which appledoc`
if [ $APPLEDOC_PATH ]; then
echo "Generating docs!";
$APPLEDOC_PATH \
--project-name "${PRODUCT_NAME}" \
--project-company "Sogeti Sverige AB" \
--company-id "se.domain.project" \
--output "Docs" \
--no-install-docset \
--exit-threshold "2" \
--keep-undocumented-objects \
--keep-undocumented-members \
--keep-intermediate-files \
--ignore "Pods" \
--ignore ".m" \
--index-desc "${PROJECT_DIR}/Readme.md" \
${PROJECT_DIR}/Prevent
else
echo "AppleDoc not found or installed!"
fi;

The result:

And build result:

From the terminal:
$ which appledoc
/usr/bin/appledoc
$ appledoc --version
appledoc version: 2.2 (build 963)

I just can't seem to figure it out.
Thanks in advance!
Answer: I just figured out that the enums are documented in the index.html file, and not the class documentation itself.
It does work.
Comment: Yes, that's how Apple does it. Appledoc is designed to mimic Apple's documentation. Enums are not part of any class, so they aren't in your class definition docs.
Comment: Thats what I learned today =) I just didn't expect it there and whatever I tried, when I refreshed the "class" page, it didn't document it [there]... now I know why ;)
Answer: Appledoc doesn't currently support enums. It's quite a, shall we say, popular feature request:
https://github.com/tomaz/appledoc/issues/2
Comment: It does support it, and I just figured out that its in the index.html, but expected it in the class documentation.
Comment: But enums are not really part of a class. They're just often declared in the same file.
Comment: Yeah, ideally they should be declared separately.
Comment: Thanks for the update. Things must have moved on since I last looked at this!
Comment: @PaulPeelen It probably supports them only as a list of constants?
Comment: @Sulthan did you read the above comments, or the answer on the question?


Verifying $\sec^2x + \tan^2x = (1-\sin^4x)\sec^4x$

Question:
Verify: $$\sec^2x + \tan^2x = (1-\sin^4x)\sec^4x$$

My solution:
$$
\begin{align}\sec^2x+\tan^2x&=\frac{1}{\cos^2x}+\frac{\sin^2x}{\cos^2x}\\
&=\frac{1+\sin^2x}{\cos^2x}\\
&=\frac{1+\sin^2x}{\cos^2x}\cdot\frac{1-\sin^2x}{1-\sin^2x}\\
&=\frac{1-\sin^4x}{\cos^2x\cdot\cos^2x}\\
&=\frac{1-\sin^4x}{\cos^4x}\\
&=\frac{1}{\cos^4x}-\frac{\sin^4x}{\cos^4x}\\
&=\sec^4x-\sin^4x\sec^4x\\
&=\sec^4x(1-\sin^4x)\\
\end{align}$$
Is it incorrect to multiply in $1-\sin^2x$ like in the fourth equality?
Answer: It's okay because $1-\sin^2 x=\cos^2 x$ so it can only become $0$ if $\cos x$ is zero, wich can be excluded due to the domain of the equality, thus no division by zero can occur and you may proceed.
Comment: @Earth52 Yes. You need to check that whenever you divide by something, that something cannot become zero in all of the original domain. Here $\frac{1-\sin^2 x}{1-\sin^2 x}=(1-\sin^2 x) \underline{\div (1-\sin^2 x)}$ so it falls into that case.
Comment: So what your saying is if I'm multiplying in other identities I only have to worry about whether the initial domains hold throughout the entire verification process?
Answer: No it's absolutely correct
You may be worried about What if (Sin^2)x= 1
But it can not be achieved in the domain of the equality otherwise (tan^2)x and (sec^2)x  at (sin^2)x=1 will not be defined
Answer: we have to show that $\sec(x)^2+\tan(x)^2-(1-\sin(x)^4)\sec(x)^4=0$, the left hand side is equivalent to
$\frac{\sin(x)^4-1}{\cos(x)^4}+\frac{\sin(x)^2+1}{\cos(x)^2}=\frac{(\sin(x)^2-1)(\sin(x)^2+1)+(\sin(x)^2+1)\cos(x)^2}{\cos(x)^4}$
the numerator is equivalent to
$(\sin(x)^2+1)(\sin(x)^2+\cos(x)^2-1)=0$
since $\sin(x)^2+\cos(x)^2=1$
Comment: I did not say you were wrong. I just said that you seem to have a habit of posting answers which have little to do with the posted question. You also need to start adding a bit more prose to actually explain what/why you are doing. [See AlexR's post to see why there is no problem, in this case, when multiplying by $1-\sin^2 x = \cos^2 x$]
Comment: You are so off with your answers, in terms of whether they address (or fail to address) the question posted! Please take more time to understand the actual questions that are posted (before jumping in to answer). Then, take a little more time composing answers that actually answer (well) the given question.
Comment: no i'm not off, my proof shows that we don't need to multiply with $1-\sin(x)^2$ which can be zero
Comment: @Dr.SonnhardGraubner You do implicitly multiply by $\cos^2 = 1-\sin^2 x$ when expanding the fractions.


find Menu Settings of node, given URL alias (or node ID)

Question: In the Drupal 8 screen for editing a node, we have these two sections:

URL Path Settings > URL alias
Menu Settings (Menu link title, Description, Parent item, Weight)

How, given the URL alias of a node, can we get those Menu Settings, particularly the Menu link title?
This may break down into two separate problems:

finding the node ID from the URL alias
finding the Menu Settings from the node ID

and in fact I would be thrilled at a solution to either one, even as a high-level explanation.
I would go into detail about how I've attempted to answer this question already, and the services & classes that appear to be relevant, but I don't want to post a complicated-looking question.  If data is that easy to put into those basic fields in the UI, it should at least be possible for some module code to get it back out.
Comment: Maybe use entity query on the menu_link_content and check for link__uri(maybe only uri will work) condition for entity:node/1
Comment: thank you, I think there may be a complete solution by combining this with the url_alias table lookup answer.  Will test both parts soon (for breadcrumb application) & post results.
Answer: Comments in my question getting URL from Route: breaks in localhost subdirectory have clarified that the solution of @4k4 is absolutely the right way to get the alias from the current path.  But the alias is not as useful as I thought in applying suggestion (@Ivan Jaros) to use entityQuery to take it the rest of the way, since the current path is able to match the link.uri field of menu_link_content, except for a leading slash in the pathname and the entity: protocol:
$current_path = \Drupal::service('path.current')->getPath();
$system_uri = 'entity:' . trim($current_path, '/');

$query = \Drupal::entityQuery('menu_link_content')
  ->condition('link.uri', $system_uri)
  ->condition('menu_name', 'main');

$result = $query->execute();
$menu_link_id = (!empty($result)) ? reset($result) : FALSE;

if ($menu_link_id) {
  $menu_link = MenuLinkContent::load($menu_link_id);
  $menu_link_title = $menu_link->getTitle();
} else {
  drupal_set_message(t('no Menu Link Content for ID that we found...'), 'error');
}

Comment: If you are trying to get a menu link for an entity uri besides the one at the current path it may be helpful to know the format for the uri is `entity:node/123`
Answer: I only can answer the first part of the question.
The path to the node is not a basic field, as it appears to be because it is in the node form beside the basic fields.
The url aliases are stored in the table "url_alias".
You can access the data directly or use the alias manager to access the alias by providing the node id or vice versa to get the path which then contains the node id:
$alias = \Drupal::service('path.alias_manager')->getAliasByPath('/node/'.$nid);
$path = \Drupal::service('path.alias_manager')->getPathByAlias($alias);


Practical examples use Hibernate FlushMode.ALWAYS

Question: Could you give me some practical examples that use FlushMode.ALWAYS in Hibernate session?
Thanks,
Answer: It's almost always unnecessary. It could be useful if the modifications made in the session cause some modifications when flushed in database, and these modifications can't be detected by Hibernate. For example, if some insert to table A causes a trigger to execute, if this trigger inserts rows to table B, and if you execute a query on table B. In this case, Hibernate can't detect that flushing the session is needed before the HQL query is executed.
Answer: I have encountered cases where it was required. One case is below:
Table A has a unique constraint on column B. You want to delete r1 and insert r2 in a single transaction, where r1.B == r2.B. Hibernate reordering within the single transaction caused a UniqueConstraintViolation. FlushMode.ALWAYS helps out here or you could do an explicit session.flush().
Answer: Tests
With @Transactional the default/implied behaviour for tests is @Rollback(true)... With Hibernate this means that the underlying database does not get involved at all. And whatever constraints you have defined on your tables they will not be evaluated either. Should your tests violate some of those constraints you will not know about it, the tests will be passing happily. Until you override @Rollback to false, or enforce the flush via flush() or FlushMode.ALWAYS.


Woo commerce Error: How to enable soap client on debian server?

Question: I have deployed WordPress on debian VM on GCP.
I am getting an error:

Your server does not have the SoapClient class enabled - some gateway plugins which use SOAP may not work as expected.

I have run below commands to install soap client:
sudo apt-get install php-soap

After installation, it is still same showing same error.
When I checked the php version, it shows below warning
PHP Warning:  PHP Startup: Unable to load dynamic library 'soap' (tried: /usr/lib/php/20190902/soap (/usr/lib/php/20190902/soap: cannot open shared object file: No such file or directory), /usr/lib/php/20190902/soap.so (/usr/lib/php/20190902/soap
.so: cannot open shared object file: No such file or directory)) in Unknown on line 0

What to do to remove this error?
Comment: Did you restart Apache?
Comment: Yes, I restart Apache. It is still showing same error.
Answer: Seems to be that the php7.3-soap package is corrupted, please try reinstalling it and after that restart the Apache service, then validate the error is no longer present.
$ sudo apt-get reinstall php7.3-soap
$ php -m | grep soap
$ php -v

Please note that Debian 10 (buster) default Php version is 7.3.


Python or Ruby for a new application on Linux?

Question: I'm a (daily) Ruby developer and a (only at home) Python developer.
I well known that Python is installed on (almost all?) Linux machine and so I was wondering if it make sense to write the new application with Ruby, and so having ruby as dependencies or if I should go more for Python ?
Answer: Or go for Perl. Perl is really on every single machine, even available on OpenWrt, and it's more similar to Ruby than Python. Hmmm?
PS: I'm ready for the downvotes. Bring them on. :-)