Application .NET c# VisualStudio DEBUG MODE

Question: I've got some problem with a C# .NET application.
Then I tried to run VS 2022 (v 17.5.2 ) in DEBUG MODE without a breakpoint and it works. But when I add a breakpoint (it doesn't matter where) the application doesn't start.
Chrome starts but still refreshing the page ( page is blank ). When I run the .NET APP in standard option - I see new changes and everything is working.
I always run APP in IIS MODE on localhost (http://localhost:6257/) - probably with ISS Express.
Any ideas ? I've remove all breakpoints from project, restart PC, redownload project from GIT.
Comment: This virus is striking many programmers without an obvious solution beyond removing all breakpoints.  VS2022 is currently too broken to be usable.  Stay below version 17.4.0, perhaps by using the "rollback update" installer feature.
Comment: See my answer to the same problem today: https://stackoverflow.com/questions/75765170/debugger-is-not-working-on-visual-studio-2022/75766454#75766454 three similar problems in the last days start to appear to be some kind of bug
Comment: First of all, please update VS to the latest version. Then in Visual Studio, there is a drop-down bar on the left side of running your project => Debug Properties => IIS Express => IIS Express digits => choose x86 or x64 according to your own situation. If it doesn't work you can delete the .vs (hidden folder).
Answer: As the first step try to enable native code debugging option in the app properties:
Properties -> Debug -> General -> Open debug launch profiles UI
Another try would be to delete solution.suo file

close solution
remove solution.suo file
reopen solution

These and the rest options are listed in this topic:
Debugging doesn't start


Como fazer if em sql - Postgres

Question: Preciso fazer um if no postgres exemplo.
SELECT
log."data" AS log_data,
log."tipomovimento" AS log_tipomovimento,
     log."nomefornecedor" AS log_nomefornecedor,
     log."nomeproduto" AS log_nomeproduto
FROM
"public"."log" log
WHERE
     if(log."nomefornecedor" != null) {
 log."data" BETWEEN '2018-01-01' and '2018-06-30'
     and log."tipomovimento" IN ('S') and
    "nomefornecedor" = 'x';
}else{
log."data" BETWEEN '2018-01-01' and '2018-06-30'
     and log."tipomovimento" IN ('S')
}

Se o fornecedor não for nulo ele vai filtrar fornecedor, se for nulo ele não vai filtrar fornecedor no where.
Alguem teria alguma ideia ?
Answer: Não precisa de IF, utilize OR:
where log."data" BETWEEN '2018-01-01' and '2018-06-30'
and log."tipomovimento" IN ('S')
and (log."nomefornecedor" = null OR "nomefornecedor" = 'x')

Comment: Também funcionou, obrigado
Answer: Do jeito que está na questão, não é preciso usar if nem case. A resposta do @Lisângelo Berti resolve seu problema.
Você não precisa checar se o valor de uma coluna é nula, e então aplicar um filtro. O filtro é para filtrar justamente o valor daquela coluna.
A utilização correta, seria algo assim: O usuário informa o parâmetro para filtrar como nulo. Se ele for nulo, retorna todos os nomes, se não aplica-se o filtro aquela coluna.
Exemplo:
WHERE log."data" BETWEEN '2018-01-01' and '2018-06-30'
and log."tipomovimento" IN ('S')
and
(case when [parametro] is null then
    1=1
else
    log."nomefornecedor" = [parametro];
end)

Comment: Muito bom, funcionou pra mim, obrigado

Como fazer if em sql - Postgres


How can I record on a different octave then what is transposed on Yamaha E363

Question: I want to be able to record a piece of this song that is outside the 5 octave length of the keyboard. The idea I had was to record the section I can't play and transpose it but that transposes everything along with it
Comment: I just left an answer, but then realized a clarification is needed. Are you transposing the keys on the keyboard or the recorded result?
Answer: Method #1
The E363 manual (page 45) explains how to transpose the keyboard pitches, which can be done up to one octave.

Press the FUNCTION button until TRANSPOSE appears.
Enter 12 (directly or using the + button) on the number pad to raise the keyboard an octave.

So you would record up to the point needed, transpose, record the high part, transpose back, and finish recording.
Method #2
If that fails, and the range of the song allows, record the entire piece one octave too low, then raise transpose the entire recording up one octave.


Conditional on binomial question

Question: Here goes the question from textbook:
A small restaurant seats 20 diners, and is full every night. The chef knows from previous experience that 40% of the diners order steaks, so she always has 12 in her fridge at the beginning of the evening. If a customer orders steak, what is the probability that he/she will receive one?
Apparently, the solution in here https://nz.answers.yahoo.com/question/index?qid=20120626203618AAsWm24 talks about correction factor. What is the correction factor? and where may I apply it in this context? Thanks in advance for any suggestion related to the theory of this question.
Comment: The question seems slightly ambiguous.  For example, if the customer in question orders *first* then the probability of getting a steak is 1. If she orders *last* then there's a 3.5% chance she gets no steak. The answers you link to presuppose that orders are made simultaneously and that steaks are then randomised over customers who order them.
Answer: I don't think I'd actually call it a 'correction factor' -- it's just using the right constant of summation(/integration) so that the truncated distribution has the correct pmf (/pdf).
A truncated distribution "cuts off" some of the distribution. So for the new, truncated random variable to have a distribution that integrates to 1, you need to divide by the proportion of the original distribution that lies within the bounds.
Since we have a binomial which we know is at least 1, the pmf for the truncated variable is the original density divided by ${1-F(0)}$ (since the new variable is on $1, 2, \ldots n$).

Conditional on binomial question


How does an interface in Android Studio work?

Question: So I read a lot about creating interfaces in an Android app but there is one way that I don't really understand. I will include my questions in the code, so you can see them directly. Please be gentle with me, I'm a beginner and really trying to understand it (sitting here for three hours on this one problem) but I just don't get it. :)
The construction is the following:
I have the MainActivity.java class and a MessageFragment.java class. So basically I have a fragment with a "Plain Text" View and a button. When the user inputs something in the text box and clicks the button, the input should be transmitted from the fragment to the MainActivity and it should be shown there on the screen.
The MessageFragment.java looks like this (sorry for the long code, but I thought you might have to see everything):
package and import...

public class MessageFragment extends Fragment {

    private EditText editText;
    private Button button;
    OnMessageReadListener messageReadListener;

    public MessageFragment() {
    }

    public interface OnMessageReadListener{
        public void onMessageRead(String message);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        View view = inflater.inflate(R.layout.fragment_message, container, false);

        editText = view.findViewById(R.id.text_message);
        button = view.findViewById(R.id.bn);

        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                String message = editText.getText().toString();
                messageReadListener.onMessageRead(message);

???QUESTION 1??? What is the last function doing? It looks to me that it calls the method
onMessageRead() but this method doesn't contain any activity in it's definition.

            }
        });

        return view;
    }

    public void onAttach(Context context){
        super.onAttach(context);

        Activity activity = (Activity) context;
        try{
            messageReadListener = (OnMessageReadListener) activity;
        }catch (ClassCastException e){
            throw new ClassCastException((activity.toString()+" must override OnMessageRead..."));
        }
    }

???QUESTION 2??? What is the whole onAttach method doing? I read things like "Called when
a fragment is first attached to it's context" but I don't understand this. What is the context here?
And what does the line messageReadListener = (OnMessageReadListener) activity; do?
Also, why does this method come before the "onCreateView" method (it seemed like it while debugging)?

}

and the MainActivity.jave looks like this:
package and import...

public class MainActivity extends AppCompatActivity implements  MessageFragment.OnMessageReadListener{

    private TextView textView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        if(findViewById(R.id.fragment_container) != null)
        {

            if (savedInstanceState != null){
                return;
            }

            MessageFragment messageFragment = new MessageFragment();
            FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction().add(R.id.fragment_container, messageFragment, null);
            fragmentTransaction.commit();
        }
    }

    @Override
    public void onMessageRead(String message) {

        textView = findViewById(R.id.txt_display_message);
        textView.setText(message);

    }

???QUESTION 3??? I really don't get it, when this last method onMessageRead() get's called here.
I know from debugging, that it get's called after I click the button in the fragment, but why?

}

EDIT:
First of all, a huge thanks to you guys for your effort :) So, I think I got it a bit clearer but it would be nice, if someone could approve or disapprove the following:
Basically the onAttach() method is the link between the fragment and the activity. This method makes sure, that I have a variable in my fragment (messageReadListener) in which the MainActivity is "stored". So the onCreateView() method in the fragment gets processed after the onAttach() method. Thus, when the onClickListener in the fragment gets triggered, the line
messageReadListener.onMessageRead(message);
is basically saying
MainActivity.onMessageRead(message);
because the MainActivity is already "stored" in the variable messageReadListener.
And this is also the reason why the method onMessageRead() in the MainActivity is triggered.
I still think that I have an error somewhere, because why wouldn't I just write this
MainActivity.onMessageRead(message);
immediately?
And why don't I just define the onMessageRead() method directly in the MainActivity and get rids of the interface in the fragment?
Comment: i'd highly recommend u to go through these topics then. Pretty sure these things will make more sense to you after that,good luck !
Comment: No, not really. I am going through an online course (YouTube) right now and didn't hear about that yet.
Comment: Ok, then I'll try these topics now. Thank you :)
Comment: So, from what I understand the function `onMessageRead()` in the MainActivity.java has an anonymous subclass (which contains `textView=...`)? But when the `onMessageRead()` gets calles in the MessageFragment.java (in the `button.setOnClickListener`), how is it transmitting the information to the MainActivity?
Or is it the case in Java that, when a function in an interface gets called, this function gets called everywhere?
Comment: It's you who calls it, when you invoke the onMessageReader() method  on the variable messageReadListener, you initiallized at the OnAttach method that points to the MainActivity. It seems a bit convoluted at first sight, but it makes sense when you get it.
Comment: @iagorubio your last comment here was very important. That brings a lot of clarity to the whole process. Thanks once again :)
Answer: QUESTION 1 - What is the last function doing? It looks to me that it calls the method onMessageRead() but this method doesn't contain any activity in it's definition.
The last function is the call to the method onMessageRead() your listener implements.
You have declared a variable with the type OnMessageReadListener, that is, it implements the method onMessageRead (String message).
OnMessageReadListener messageReadListener;

....

public interface OnMessageReadListener{
   public void onMessageRead(String message);
}

QUESTION 2 - What is the whole onAttach method doing? I read things like "Called when a fragment is first attached to it's context" but I don't understand this. What is the context here?
This is somewhat confusing but it boils down to the android activity life cycle.
The Android system, invokes some callbacks when the activity enters new states to allow developers to act on those state changes.
In this case, the Android system calls the OnAttach method when the fragment is attached to your Activity.
 Activity activity = (Activity) context;
 try{
     messageReadListener = (OnMessageReadListener) activity;
 }catch (ClassCastException e){
     throw new ClassCastException();
 }

As you see, what is happending here is the developer is telling Android "when you attach my fragment to the cointainer activity, set the messageReadListener
 variable to the Activity itself, that must implement the OnMessageReadListener  interface or a ClassCastException will be thrown".
QUESTION 3 - I really don't get it, when this last method onMessageRead() get's called here.
It's called on your QUESTION 1 code.
  button.setOnClickListener(new View.OnClickListener() {
      @Override
      public void onClick(View v) {
          String message = editText.getText().toString();
          messageReadListener.onMessageRead(message);
    }
  });

So, What's going on here ?
The developer is simply using interfaces to allow that fragment to send a message to the main activity when you click a button in your fragment.
Here you say "I got a variable that holds anything that implements the OnMessageReadListener interface".
Then on the main Activity you implement that interface by creating the method , onMessageRead().
When Adroid attaches the fragment to the main activity you assign that activity to your Fragment's variable messageReadListener, on the OnAttach callbak.
And after that, you just use that variable to call, at the OnClik button event, the  onMessageRead() method on the main activity.
That allows your fragment and the main activity to comunicate untangled, that is without holding one, a reference to the other.
EDIT: QUESTION 4 I still think that I have an error somewhere, because why wouldn't I just write this MainActivity.onMessageRead(message); immediately? And why don't I just define the onMessageRead() method directly in the MainActivity and get rids of the interface in the fragment?
You can do that, but that would mean those classes get tangled. That is you need a reference to the MainActivity on your fragment.
With the interface, you can use your fragment on ANY activity. You just need it to implement the interface, on any new activity to use it.
So it is easier to reuse your code, and will be much cleaner to implement that interface on any activity you want your Fragment to be used, than to get an instance of each activity you want your Fragment to be used in, and check around what is the caller one.
To code to interfaces is considered a good practice on Object Oriented programming.
Comment: Hey iagorubio, thanks for your answer. I am still not quite sure if I got it and therefore added an EDIT section in my question. It would be nice, if you could look at it :)
Answer: I like your question and I am going to explain it to you in a simplified manner. Just like explaining to someone who has no idea about Java.
First thing first, a "class" is a blue print lets say for example you want to build a house. Firstly you need a plan to build the house, in Java a "class" is a plan and a finished product(which is a house in this case) is an "object". Going back to your code, "MainActivity" is what your user sees on the screen of the phone when opening the app, it is part of an interface. Let's say you built a news app for example. When the user open the news app, first thing that they see is normally 'news' which is your "MainActivity". And "extends" which will be for example 'World News'. What this means is that 'World News' is a continuation of "MainActivity" it is an inheritance. In real life I am sure you sometimes hear people say that you look like your mom or dad. Same thing that is happening here with "MainActivity" and "extends". "implements" is also a continuation of "MainActivity". The main reason for "implements" is that you want to build a more cleaner code.
"Override" in real world is the same as bypassing. In Java what this means is that "MainActivity" is still continuing but its inheritors are now customised, though they inherited their characteristics, properties or even behaviors from their main parent "MainActivity". They are now independent, same thing like the "news app". 'News', can have children 'World News', 'Motoring', 'Politics', 'Finance' and 'Weather'. All those are news, they inherited from 'News'. Some apps usually have more than one "MainActivity", depending on the size of the app. In simple terms an interface is the face of an application 'News App' in our example, that a user experiences while using the app. This is a more simplified explanation.
Here is a simple example:
@Override
 public void onClick(View v) {

 String enteredText;

 enteredText = mEditText.getText().toString();

 mTextView.setVisibility(View.VISIBLE);
 mTextView.setText(enteredText);

}
});
Comment: Hi tshele, thank you for your explanation but I am not quite sure, how this explanation helps in regards to my 3 questions.
Answer: Jt's super easy ,
Escape if you don't need to know what is interface: interface is just like the name says , a class between two classes so they don't have to directly communicate each other
Why? Because you may still don't know how exactly you want to handle the event that fired the interface function
Question 1:  it doesn't need the activity inside it , the activity should implement this interface so when the user clicks the button , What ever this activity told the interface method to do will be executed
I'll stop here , i'll answer the rest if you understand the first one
Comment: Hey moumenShobakey, based on all the answers I added an EDIT section to my question which represents my current understand. Could you maybe check this EDIT and tell me, if I got it right or wrong? :)
Comment: Not exactly , onAttach method checks if the mainactivity is what java -Object Oriented language- calls , a subclass of the interface so it can be converted (eg.casted) to the interface type , so you can call the interface method from it , If it implements the interfcae (a subclass of it) , You cast the variable 'activity( the paramater of 'onAttach' )' which referece to the activity the fragment is attached to , to the interface (onMessageListener) , now when you call onMessgeRead , the system checks how you implemented it in MainActivity
Comment: Please if you still don't get it , tell me i may write a blog for you
Comment: Thanks for your offer to write a blog, but I think it won't be necessary :) With the help of iagorubio and you I think I got it now.
Comment: I hope i was useful , have a nice day
Answer: You must create funtion setOnMessageReadListener in fragment and setup it in Activity
 public void setOnMessageReadListener(OnMessageReadListener messageReadListener){
    this.messageReadListener = messageReadListener;
}


Is there a standard for storing and displaying Pratt certificates of primality?

Question: Is there a standard using XML tags or something else for storing a Pratt certificate of primality?
What is the standard for the display?
I am aware that one would need the prime $p$, a primitive root $a$ and the factorization of $p-1$ along with a certificate for each prime in the factorization of $p-1$.  I just don't know how this is expected to be stored or displayed.
Comment: Typically http://factordb.com is used.  It accepts Primo certificates.  The verifier also supports MPU certificates but the web site has a pre-test that only takes Primo.  It also takes N-1, N+1, and hybrid N-1 / N+1 proofs by storing a helper file of factors, and possibly a base.  I believe this is done so PFGW can be used (PFGW does not output a certificate or any intermediate info however).  I wish it would use a more formal certificate for these methods.
Comment: It is more a matter of how a mathematician would communicate a prime discovery to another mathematician for verification.  This would have to be done electronically to avoid errors.  I was wondering how this was done.  I prefer using a standard format to avoid confusion.
Comment: This would be another reason to have a standard for the certificates.  Then there would be no ambiguity when entering results into such databases. The factordb site looks interesting.
Comment: It's certainly possible, but you'd need to construct the format and get people to use it.  There would be a bunch of constructive and destructive criticism, as well as endless bikeshedding.  You'd probably want a verifier that reads it or there wouldn't be much point for anyone to adopt it.
Answer: To the best of my knowledge, there is no standard in use.  Every program uses their own method, with varying levels of documentation.
I came up with my own format, described here, along with a verifier (used by factordb) and proof software that generates these forms.  The documentation could be improved.  It covers ECPP (with simple n-1 and n+1) as well as BLS75 (T3, T5, T15) and Lucas.
My code doesn't generate strict Pratt certificates (e.g. using type Lucas) because BLS75 theorem 5 is much more efficient, not to mention ECPP.  But the certificate allows them and the verifiers handle it.
A small example using the Lucas type (as used for a Pratt certificate) would look like:

[MPU - Primality Certificate]
Version 1.0

Proof for:
N 8087094497428743437627091507362881

Type Lucas
N  8087094497428743437627091507362881
Q[1]  6360775529
Q[2]  1237110551
Q[3]  98277749
Q[4]  3631
Q[5]  5
Q[6]  3
Q[7]  2
A     13

Any Q[i] larger than $2^{64}$ would need its own entry as well (which for a Pratt certificate would also be of type Lucas, but the verifiers will accept any type).  Without that, the certificate will not verify.  I chose $2^{64}$ since we can run BPSW on anything smaller and have a verified result.  Primo chose $34 * 10^{13}$ as its cutoff (the BPSW result was not known when Primo chose its format).  [Update: Just two days ago he released a new "format 4" certificate that uses the BPSW result]

Addendum for certificates:

Primo, the gold standard of free primality provers, defined its own format for ECPP certificates.  It is well defined, will verify its own certificates, and there are two independent open source tools that also verify them.
Perl/ntheory is what I describe above (MPU certificates).  I believe it is well defined, it has proof software in Perl and C+GMP, and verifiers in Perl and C+GMP.  ECPP as well as BLS75-T5 and some other methods.
Pari/GP will produce a $p-1$ certificate with isprime(p,1).  It looks like BLS75 theorem 5 using the BPSW ($2^{64}$) cutoff (technically it's C&P's theorem 4.1.5 based on BLS75-T5).  Its documentation is very brief but basically is a matrix with rows of "Q A x" where x is either 1 (Q < 2^{64}) or another matrix.  Factorization only is done to $p^{1/3}$ which is what BLS75-T5 needs.
Mathematica's PrimeQCertificate[n] will produce certificates.  It doesn't seem to have any documentation on how to parse them.  It will verify its own certificates.  For small inputs it generates Pratt certificates, while larger inputs use a "Atkin-Goldwasser-Kilian-Morain" certificate.
Morain's very old ecpp program will output ECPP certificates.  I have not attempted to decipher them.
I wrote a Perl program to turn the output of GMP-ECPP into MPU certificates, which can then run through its verifier.  GMP-ECPP is significantly slower than ecpp-dj or Primo however.
I also wrote a Perl program that converts ECPP certificates produced by SAGE's ecpp function (which AFAIK never got merged into master) to MPU certificates, which can then run through its verifier.  It's a neat small implementation that's good for not-very-large inputs.
MuPAD, related to MATLAB, seems to generate ECPP certificates.  I haven't looked closely since I don't have their software, but it looks like converting to MPU certificates would be straightforward.
Comment: I was influenced somewhat by Marcel Martin's Primo certificates, which have this simple per-line variable space value format.  It's easy to parse in C or Perl without having to pull in XML/YAML/JSON parsing.  I admit XML could have some advantages.  One difference with MPU certs is that they are a hash rather than a tree (it gives more freedom in operation order in the prover).  A certificate description IMO needs to have enough info for a third party to write their own verifier.  Again Marcel Martin did this excellently.
Comment: BPSW is used at all steps of Primo and ecpp-dj (MPU), so composites get rejected almost immediately.  No luck involved, but sometimes weeks or months to complete the proof.  For Primo, the input is taken as a text file which can contain comments, which are copied to the cert, so technically we don't need to edit the cert.  Anyway, the point seems to be that ideally a cert should have extra additional metadata.  Hashing it out is probably best on a forum (e.g. mersenneforum) or as part of a research group.
Comment: It makes sense not to add a separate certificate for small primes.  I liked the way your certificate in the link gave verification steps in the comments in case the verifier personally opened the file.  I assume if you were communicating your results electronically you would assume the verifier's computer could parse the certificate.  That is why I was thinking XML or some other tagging mechanism would have been used, but what you have here seems easy to parse.
Comment: Marcel Martin's certificates also include who found the prime and when and on what computer.  That is all valuable information although not required to verify the certificate.  The reason I prefer some type of markup language is that it gets this standardized like LaTeX does for text.  It also can be stored in a database better although they may both be stored as blobs.
Comment: Are you sure?  The certificate documentation doesn't include that information, nor does Primo add it to the certificates.  There is a theoretically unique ID, a created date, a file name, run times, comments, and a signature.  The certificates it generates, and most of those found on factordb, do not include who or any info about the computer used.  I don't see anything like that in the certificates from his page nor the ones from new or old Primo.  Of course we can add it to comments.
Comment: The one I looked at was on the top 20 page: http://www.ellipsa.eu/public/primo/top20.html.  I downloaded and unzipped the one by Giovanni and Marco La Barbera at the bottom of the page.  The ecpp400.zip file unzipped to new400.out.  In the Comments sections was that information.
Comment: But it's not in Cami's 2015 certificate, for instance.  Tom Wu's 2014 one has the comment "Put here any comment..."  The MPU format allows comments almost anywhere using a "#" at the start of a line.  Either one makes automated parsing problematic.
Comment: It looks like this is information one has manually inserted after the certificate was created.  Although the comment information isn't useful for verifying, it is nice to know since it takes weeks for someone to find that prime if they are lucky to not select a composite number to check.  Also the software should be able to tell more precisely the hardware specifications of the computer and the operating system and also date when the certificate was created.  The certificate shouldn't have to be opened up and then modified by the user to add the comments.
Comment: It looks like W3C has an ISO standard MathML using conceptual tags, that is, the tags aren't just to display something.  There may be enough here to generate a type of certificate based on standards.  I plan to ask PrimeGrid what they use to store data.  Thanks.  You have got me past some conceptual problems related to this issue.  There may be no specific standard for certifications, by what standards do exist could be used to build one without it being totally arbitrary.


How to send Multiple Requests and fetch data to update multiple UI Labels in iOS

Question: I have to call two web services simultaneously and then update the UI components, say, two labels (each getting data from different service response). What is the best possible way to achieve this?
I tried NSURL sendSynchronousRequest, but it takes huge time.
Thanks
Comment: Why don't you try with `sendAsynch..` if it takes huge time.
Comment: I can not update the UI if i use Async.
Comment: Yes, exactly. But you can update the UI in the main thread know
Answer: For your Comment,  You need to do request with dispatch_async and update in the main Thread
 dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
                // Request the WebService calls here
                dispatch_sync(dispatch_get_main_queue(), ^{
                    // Update the UILabel's here
                });

            });

Comment: I received null response for this! However I am using - NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
Comment: Try this `[NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];` and also ensure the URL is corrct


using Iperf3 to test upload and download

Question: How to use Ipfer3 to  test upload and download speed or in other words which data of the output given below represents upload and download speed ?
Iperf3 output
Answer: The iperf client initiates a connection to an iperf server, and the default test is the upload speed:
$ iperf3 -c la.speedtest.clouvider.net -p 5209
Connecting to host la.speedtest.clouvider.net, port 5209

when you use the -R switch, it downloads from the server. note the 3rd line:
$ iperf3 -c la.speedtest.clouvider.net -p 5209 -R
Connecting to host la.speedtest.clouvider.net, port 5209
Reverse mode, remote host la.speedtest.clouvider.net is sending

Answer: The default is download speed. Use option -R for upload speed.
iperf3 -c 192.168.1.xxx -R

This represents "Reverse Mode": run in reverse mode (server sends, client receives).
Comment: I believe this is wrong. iperf3 defaults to upload speeds from client to server. Using -R option as mentioned in the [iperf3 docs](https://iperf.fr/iperf-doc.php) states it the server sends and client receives thus acting as Download.
Answer: As the other said:
iperf3 per default just tests the upload speed.
But you can perform a simultaneous upload and download by using --bidir on the client side:
iperf3 -c 192.168.1.xxx --bidir

On some newer Linux distributions, the -d flag is used instead:
iperf3 -c 192.168.1.xxx -d

This way you can get both results in a single test.
Answer: IF you are new to iperf, I suggest you look into jperf, it is a graphing front end for iperf, that provided the options in selectable form in a GUI, that also displays the command syntax for the tests you are running to learn how to test the same direct from terminal.
https://code.google.com/archive/p/xjperf/downloads
Makes interpreting the results visually a bit nicer as well.


Migrate String from Java class to resources

Question: I working in a Quiz Question.
I have on "Questions.java"
package com.example.luisbalmant.quickquiz_science;

import android.widget.TextView;

/**
 * Created by LuisBalmant on 15/07/2017.
 */

public class Questions {
    public String mQuestions[] = {
            "My question here",

    };
}

I'm trying use string language of "strings.xml" on "My question here".
Eg:
<string name="Q1_function_insulin">What is the function of insulin?</string>

I'm trying this:
getString(R.string.Q1_function_insulin),

Can someone help me please?
Answer: If i got your question right, i assume you want to load all questions from the strings.xml file and place them inside the mQuestions array. What you wrote there (getString(R.string.Q1_function_insulin)) should work without any problem. I suggest that you put all your questions in an array inside the xml and load the whole array at once with getStringArray(R.array.questions).
Comment: Oh and also, next time please say where the exact problem is and what part of your code is not working. If possible, attach logs and stack traces.
Comment: Thanks. I try use "(getString(R.string.Q1_function_insulin)), " but is not working. I erased everything and rewrote it. I did not succeed.
Comment: You need a context to get resources from xml. If you try to call getString() in the Questions-class, there is no such method. Try loading the questions inside an Activity or pass a valid context to Questions to you can call getString() on the resource returned from context.getResources(). Take a look at the [documentation](https://developer.android.com/guide/topics/resources/string-resource.html)
Comment: Thank you dedda1994. Now that's ok.
Answer: You need a Context object in order to perform getString(). Thus, you can refactor your class this way:

    public class Questions {

        private static final int QUESTIONS[] = {
                R.string.text1,
                R.string.text2
        };

        private Context context;

        public Questions(Context context) {
            this.context = context;
        }

        public String getString(int index) {
            return context.getString(QUESTIONS[index]);
        }
    }

And then, from your activity:
Questions questions = new Questions(MainActivity.this);
questions.getString(0);


jquery select the option list with dynamic id

Question: I have an option list with an id that could sometimes be one of these:
edit-panes-billing-billing-zone
edit-panes-billing-billing-zone--1
edit-panes-billing-billing-zone--2
edit-panes-billing-billing-zone--3
edit-panes-billing-billing-zone--4

There is only one select element at a time.
Is it possible to select the option list dynamically with jQuery?
This is what I've tried, but it's not working:
$("select[id^='edit-panes-billing-billing-zone--']").each(function() {
    alert('test'):
}

Comment: can you share your HTML code ?
Comment: is your code wrapped in `document.ready`?
Comment: what error its gave in firebug.?
Comment: jQuery may not give any error, it just found 0 element :p
Comment: @user1073122 may be OP getting and setting ids of options rather then select...
Comment: update your post with your HTML code
Answer: You have a number of failing syntax errors in your code:
alert('test'):

should be
alert('test');

And
alert('test'):
}

should be
alert('test');
});

The final result should be:
$("select[id^='edit-panes-billing-billing-zone--']").each(function() {
    alert('test');
});

This succeeds in all the tests I've run.
Answer: Try
$(document).ready(function() {
    $('select option[id^="edit-panes-billing-billing-zone--"]').each(function(){
         alert($(this).text());
    });
});
Answer: Give attribute class for each select that you have, for example
<select class="my-select" id="edit-panes-billing-billing-zone"></select>
<select class="my-select" id="edit-panes-billing-billing-zone--1"></select>
<select class="my-select" id="edit-panes-billing-billing-zone--2"></select>
<select class="my-select" id="edit-panes-billing-billing-zone--3"></select>
<select class="my-select" id="edit-panes-billing-billing-zone--4"></select>

and then the code is (get the element by class) :
$(document).ready(function() {
    $(".my-select").each(function() {
       alert('test');
    });
});

Comment: That's a solution, but this is not solving the problem, and getting element with id has better perf. that with a CSS class
Comment: can it be selected by name? the name is panes[billing][billing_zone]
Comment: can you post the html in your question?
Answer: Your question is not very clear I have an option list with an id:
option list, i believe these are the bunch of <select> tags.
$("select[id^='edit-panes-billing-billing-zone--']").change(function() {
    alert('test'):
});

of if we go with your code then you should try this way:
$("select[id^='edit-panes-billing-billing-zone--']").each(function() {
    $(this).change(function(){
        alert('test');
    });
});

note:
Your code is missing }); at the end and your alert is ending with colon-> : not semicolon ';'
instead .each() try .change() event.
Comment: if alert doesn't fire within `each`, assuming no errors, there's no reason it will fire within a change handler


Number of integral values of $\lambda$

Question:
From$\lambda cosx> -2$
how they have derived the value of $\lambda$
Comment: I'm seeing some kind of Indian writing that I don't understand. This question has been nominated to be closed, and the Indian writing does not help.
Comment: @RobertSoupe It has both language Hindi and english . and both means the same .
Comment: I would advise you in the future to not include Hindi in your questions (or answers) unless it is absolutely necessary.
Answer: For all $x \in \mathbb R$, we have
$$- 1\leq \cos x \leq 1$$
so if $\lambda \geq 0$ one has
$$ - \lambda \leq \lambda\cos x \leq \lambda$$
So if one wants $ \lambda\cos x >-2$ one must have $-\lambda \geq -2$ that is to say $\lambda \leq 2$. Since $\lambda$ is an integer $\lambda = 0,1,2$.
Now if $\lambda < 0$ one has
$$ - \lambda \geq \lambda\cos x \geq \lambda$$
so $\lambda \geq -2$ that implies $\lambda = -1,-2$ (using the same argument).

Number of integral values of $\lambda$


What songs are possible to play on a 25-key keyboard?

Question: I am currently quarantined, locked away with a 25-key MIDI keyboard. Are there any songs that only make use of this 25-key range that I can learn? Just two octaves but the controller has the ability to shift these two octaves in either direction, the music just needs to use two side-by-side octaves only.
Just need a list of songs that are possible to play, I do not require a lecture on how having a tiny keyboard isn't good enough. I am already aware. It is just not the best climate to pop to a music shop for a bigger keyboard.
Hopefully there is a wizard on the keys out there who can get me some music to try play.
Thanks, Jason.
Comment: Do you have a sequencer or looper? You multi-track record things with a "DAW". First play drums, then bass, then chords, then solo over it with a lead sound. After you have it recorded, mute the chords and bass and invent new chords. Infinite possibilities and no need for special sheet music for 2-octave keyboard.
Comment: So far I have got Beethoven - Ode to joy. I was thinking more along the lines of piano pieces that I can learn the sheet music too. I already make my own house / D&B tracks using the keyboard, just wanting to actually learn some sheet music to up my skills a bit.
Comment: Why not record the bass and treble staves in separate passes into your DAW? Just pick songs that don't extend too far in either direction.
Comment: Not an answer, but.... why not practice a different skill instead, like working out the chords of some songs by ear? Or trying to come up with your own mini keyboard arrangements of songs? 25 keys probably isn't much fun for learning to play from score, but it's plenty for other things. My instrument of choice ATM is an 8-key kalimba...
Comment: you can play everything you want, just when the song goes out of the range of your keyboard you play the r.h. an octave lower respectively  the l.h. an octave higher.
Comment: I'm voting to close this question because finding lists or examples of songs are off-topic
Answer: Do you necessarily want to use both hands to play the keys? You could try learning pieces meant for a monophonic instrument such as a clarinet, or a polyphonic instrument that can't normally be used for wide chords, like a violin. The best part is that, with your other hand freed, even for compositions that span more than two octaves, you can just switch octaves using the octave change button. You can even use the mod wheel (if you have one) and the volume control to substitute for the lack of access to other techniques. You can even make a game of mapping techniques specific to one instrument to keyboard specific techniques: you can't flutter-tongue, but you can modulate.


Terminal startup error: object 0x7fe089600420: pointer being freed was not allocated

Question: I have recently tried opening up Terminal and have this come up:
<code>Last login: Tue Jun  9 13:11:07 on console
login(67618,0x7fff71d59300) malloc: *** error for object 0x7fe089600420: pointer being freed was not allocated
*** set a breakpoint in malloc_error_break to debug

[Process completed]
</code>
But it also does not let me type in any commands.
I do not know what caused this, but if you don't mind helping me with it, please do!
Thanks in advance -CamelInATardis
Answer: It happens to me and that what i did to resolve it:
open "Disk Utility" app and chose "Repair Disk Permissions".


In Pythagorean tuning, what's the frequency of the tonic of each key?

Question: When playing a fretless instrument (like violin), what frequency should be used to tune beginning of each key?
I believe that for A major and A minor, 440Hz is the tonic. What will be the frequency of the C in C Major?
How about Bb major? What frequency should be the Bb tonic? Is it like the m2 of the A major scale? Maybe like the 7th of the C Major scale?
Is it tuned according by Just Intonation? Equal Temperament?
I'm rather looking for the formula that enables calculating the tonic of each key, rather than a list which could also be handy.
UPDATE
I'm afraid I wasn't so clear, so let me try to explain again.
In general I'm talking about fretless instruments in standard tuning (A=440Hz). The standard playing on these instruments would be Pythagorean. However, what if you want to play in Bb major. Do you use the Bb of Equal Temperament or what?
UPDATE on Caleb Hines' and leftaroundabout's answers.
This is almost obvious that the low Bb (465.12Hz) of the Pythagorean C Major (C=261.63Hz), and even the high A# (471.47Hz), both make no sense to use as the tonic of Bb major.
So you're right that the open-string A is anyway going to be a bit low for a Pythagorean-expecting ear. Anyway the question is what compromise do we take, is it the Bb of ET (466.16Hz) or the JI's (466.16Hz).
I'm curious what's the standard among orchestral string players (fiddlers should obviously tune to ET).
P.S. I picked Bb as an example, but the question applies to other keys like A# (question solved if answer is ET).
Comment: A = 440Hz only rings true in some parts of the world, and even some individual orchestras choose to have a different datum point.But for your concept, 440 is a good start. Bb would be the 7th of C harmonic or natural minor rather than Cmaj. That's B natural.
Comment: @Tim In Just Intonation, what are the frequencies of the other notes as root notes (not as intervals, not in relation to other notes).
Comment: In a previous answer, Wheat Williams posted a chart with comparative frequencies for notes. It's not answering the question, but it may be a start point.Sorry, I can't track it down.
Comment: How does the first paragraph of my response not answer this, since it specifies that you want to use 12TET (which is Equal Temperament), unless the people you're playing with are specifically using something different. You also asked for a formula which I gave. (Also, the title of your post doesn't really ask the same question).
Answer: First of all, Pythagorean (PT), Just Intonation (JT) and Equal Temperament (ET) are different (families of) tunings. Therefore, note frequencies will be different in each case. You can find frequency charts for them on Wikipedia.
For any tuning, you need a reference frequency. Currently, 440 Hz for A above middle C is the most widely used standard. But historically it wasn't the case and some orchestras still tune differently.
Pythagorean tuning
PT is a family of tunings based on just perfect fifths, so it's a subset of the just intonation family. Perfect fifth is the transposition of the third harmonic of musical tones down to the same octave as the fundamental. Dividing a frequency by two transposes it down by one octave. Third harmonic's frequency is three times the fundamental. Therefore a perfect fifth is 3/2 the frequency of the fundamental.
PT works by starting on a selected frequency and moving in perfect fifths (and transposing them down to the same octave). So the frequency ratios are 1, 3/2, 9/8, 27/16... The general formula is 3^n/2^n (and then you transpose it back to your octave by dividing it by two as many times as necessary).
One problem is that a stack of perfect fifths can never add up to an octave. Circle of fifths cannot be closed. After 12 consecutive steps, starting from C, (C G D A E B F# C# G# D# A# E# B#) you end up with a B# that is close, but not quite equal to C; the ratio is 3^12/2^19 and it's about a quarter of a semitone sharper, which is very noticeable. In other words, C# ≠ Db in PT. As a result of this, if you want to live with only 12 notes, some of your fifths will be out of tune. It's called a wolf interval.
There is also another problem: The Pythagorean major third (81/64) is too sharp compared to the JT major third (5/4, see below). This renders this tuning mostly useless for triadic harmony.
Just Intonation
JT is based on integer ratios. It strives to make all intervals just (if we only make the fifths just, it's usually labeled as PT). For example, a major scale can be created with the major triads (ratios = 4:5:6) built on the fundamental, perfect fourth (4:3) and perfect fifth. It will give you C=1 D=9/8 E=5/4 F=4/3 G=3/2 A=5/3 B=15/8.
This is harmonically very pleasing as long as you stick to the I, IV, V, iii and vi triads. But the ii triad is out of tune. These are the wolf intervals of this particular JT major scale. You can fix it by lowering the D for example, but this will break the G chord, and trying to fix it will break something else. It's impossible to get all the chords right without adding new notes to the scale.
What are the frequency ratios of the notes with accidentals then? The answer is, it depends. The minor seventh (Bb) can have the 16/9, 9/5 or 7/4 ratio depending on what effect you want to achieve.
Again, you will need more than 12 notes to use JT, even in a single key.
Equal temperament
ET just divides the octave into 12 equal intervals. None of the intervals are "just" (save for the octave), but most of them are within almost tolerable limits: It's a compromise; there is no way of having the perfectly tuned just chords and freedom to modulate to any key you want with a reasonable amount of pitches (e.g. piano keys).
To hear the difference, listen to a good barbershop quartet and then play the same chords on an ET instrument like a piano. The nice, ringing qualities of the chords will be gone.
Anyway, ET divides the octave  equally into 12, so the ratio between adjacent notes (like C and C#) is the twelfth root of 2 (2^(1/12) ≈ 1.05946309436). You start from your reference frequency (say, A=440), and multiply it by this number for every consecutive note. Here's a chart.
Comment: Also, while this is very informative and interesting, I don't think it answers the question. I believe the asker knows what ET and JI are. His doubt is regarding the frequency of the root note. He knows how the intervals are formed, but he doesn't know how the frequency of the fundamental is chosen.
Comment: Your sources label Pythagorean Tuning as Just Intonation. Is Pythagorean Tuning really a "different family"? Isn't Pythagorean Tuning a form of Just Intonation? Pythagorean Tuning is based on integer rations too.
Answer: Short answer, these days, for finding a tonic, you probably want to use ET (specifically 12-TET) because that's what everyone else uses. However it may depend on who else you're playing with, and what they're using, so tune to them.
First, none of the tuning systems you mention specify an inherent reference pitch, so you'll need that as well. Sounds like you're going with the modern standard A4=440. Secondly, strictly speaking, JI is not actually a single tuning system, but rather a specification that two (or more) intervals must be small ratios of each other. I'll focus on the other two.
Pythagorean Tuning uses justly-intonated fifths and octaves (but no other intervals) to generate all of it's notes. Because a justly-tuned series of fifths will never close the octave (as cyco mentions), PT specifies pitches for an entire line-of-fifths. Only 12 of these actually appear on a keyboard, and there will be ugly "wolf fifth" where they don't match up. The formula is:
f = f0 * (3/2)^x

where f0 is the frequency of your reference pitch and x is the number of fifths you are away from the reference note (negative x is OK). Note that you may need to multiply or divide your answer by 2 several times to get the frequency into a usable range. (f0 < f < 2 f0 is in the octave above f0, while f0/2 < f < f0 is in the octave below, etc...).
For 12-tone Equal Temperament (12TET) each fifth is squeezed so that the octaves line up, and the circle is closed. There is no ugly wolf fifth, but no intervals (besides octaves) are justly-intonated. The formula is:
f = f0 * 2^(x/12)

where f0 is again the frequency of your reference pitch, but here x is the number of half steps above (positive) or below (negative) your reference pitch. Note that for x=12, you just get the octave doubling.
Answer: Well, it depends.
When playing with 12-edo tuned instruments, basically you have no option but to adapt to their root: that tone needs to be spot on, regardless of whether you render third / leading tones in just / Pythagorean intonation in a way those instruments can't.
Even when playing in a string ensemble or alone, 12-edo is quite a reasonable option for the root, being such a good "one size fits all" compromise. However, it's not really practical to pick up a 12-edo reference before you start playing. Also, it remains just that: a good compromise!
A far more natural way of seeking a reference is in the open strings. Two obvious ways to do it:

Stick to Pythagorean. You can brachiate down the circle of fifths, i.e. G-c, C-f, f-B♭. That brings you to the "perfect Pythagorean B♭" (the frequencies given in dan04's answer). However, apart from being awkward to find, this is not really useful for playing music in B♭ major. The main problem: a double-stop between that B♭ and the open D string is a Pythagorean major third. Fine if you like Gregorian chants, but for anything post-1600 this is pretty horrible. And there's no way to correct an open string downwards.
You can live with that if you avoid the open strings, at least the low ones. Common enough thing to do since the Romantic period. The open A-string actually makes for a usable leading note in this tuning.
But much preferrable IMO is to tune that very double stop B♭-d to just intonation (5-limit). This is quickly done and fits naturally with double-stops actually found in many pieces. You can still play the melodic aspects in Pythagorean, in particular the leading note A should be a good bit higher than the empty string. But for harmony, the empty strings are much harder to avoid, so you should adapt the tuning to go naturally with this.
A perhaps more convincing argument for this strategy is to think you're actually playing in g-minor. Tuning the g-minor triad G-D-b♭ gives you that same high1 b♭. Then you just omit the G root.
The frequency of this JI-B♭4 is

                       440 Hz ⋅ ⅔ ⋅ ⅘ ⋅ 2 ≈ 469.3 Hz

Notably higher than in both Pythagorean and 12-edo.

So what's the standard? I don't think it's possible to say. The diapason actually sways quite a bit, even (particularly?) in good performances. In this rendition of the 6th string quartet in the end of the exposition we can hear an extremely high C double-dominant, followed by a rather lower (comparing WRT 12-edo) B♭ in the repetition. But I wouldn't conclude from this that they tune so extremely high (would be about 447 Hz) and then use a Pythagorean B♭, rather I reckon they use substantially "narrowed" tuning so a very high cello's C-string2 matches a rather more ordinary, perhaps 444 1st violin e-string to JI. I'm pretty sure the open D (prominent in the 2nd violin's arpeggio at the beginning) is even lower than that standard, to make a nice just major sound together with the viola's B♭.
The overall tuning is then always somewhere in between JI and Pythagorean, but not in the same sense as with 12-edo: notes that would nominally be the same may be intonated to different pitches, depending on the musical context.
Kurt Sassmannshaus has made a couple of nice videos discussing overall string intonation.

1Note that this tone is actually often replaced with the lower Pythagorean b♭ whe playing downwards-motifs in g minor, but not within vertical harmony.
2More so because the cello open C has quite a tendency to go up when played loudly.
Answer: Assuming A = 440 Hz, the octave starting on Middle C has the frequencies (in Hz):

C♭ = 244.1687412149232
C = 260.74074074074076
(B♯3 = 264.298095703125)
D♭ = 274.6898338667886
C♯ = 278.4375
D = 293.3333333333333
E♭ = 309.02606310013715
D♯ = 313.2421875
F♭ = 325.5583216198976
E = 330.0
F = 347.65432098765433
E♯ = 352.3974609375
G♭ = 366.2531118223848
F♯ = 371.25
G = 391.1111111111111
A♭ = 412.0347508001829
G♯ = 417.65625
A = 440.0
B♭ = 463.53909465020575
A♯ = 469.86328125
B = 495.0
(C5 = 521.4814814814815)
B♯ = 528.59619140625

This is obtained from the formula f = f0 * (3/2)^n, where f0 is the reference frequency and n is the number of steps along the Circle of Fifths.  Then multiply or divide by 2 as necessary to get all the notes into the same octave.
Comment: The next C would be, yes, but Pythagorean Tuning has no enharmonics. B# is defined as 12 just perfect fifths (ratio of 3:2) above C (count them: C,G,D,A,E,B,F#,C#,G#,D#,A#,E#,B#), so you get (3/2)^12. If you then bring that back down 6 octaves (e.g. divide by 2 six more times) you get: (3^12)/(2^18) = 531441/262144 ~ 2.02729, which is not equal to 2. If you multiply this number by the starting frequency of C, you get the value listed here. This difference is known as the "Pythagorean Comma", and is a major problem that all tuning systems must deal with.
Comment: would the next C, as opposed to B#, be 521.4 as in twice the original C? If not, what went wrong, as an octave needs to be exactly twice the frequency of the 'root'.And how is B# differing from C ?
Comment: While this correctly explains how you can find an arbitrary root note _in Pythagorean tuning_, it doesn't answer whether it would be a good idea to do that. Indeed I would argue it isn't a good idea.
Answer: Use the frequencies of the open strings for the notes of the scale played on them, and calculate the tonic from there.
You probably do this automatically when you play, so that a high G excites sympathetic vibrations on the G string and makes the tone sound richer.
Comment: This is an excellent answer, if I understand it correctly. Could you please expand it with an example or two?


Capturar div pela class

Question: Estou tentando capturar uma div apartir de sua classe porem nao obtive exito, observe: eu tento capturar a div com a classe class='m-definicao-conteudo' do site que informo ao curl, porem me retorna esse error:

Warning:
  DOMDocument::loadHTML(): Unexpected end tag : a in Entity, line: 102 in /Applications/XAMPP/xamppfiles/htdocs/teste.php on line 13

$ch = curl_init ("");
curl_setopt($ch, CURLOPT_URL, 'http://dicionarioinformal.com.br/aham/');
curl_setopt($ch, CURLOPT_USERAGENT, "Opera/9.80 (J2ME/MIDP; Opera Mini/4.2.14912/870; U; id) Presto/2.4.15");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE);
$html = curl_exec($ch);

$dom = new DOMDocument;
$dom->loadHTML($html);

$xpath = new DOMXPath($dom);

$results = $xpath->query("//*[@class='m-definicao-conteudo']");

if ($results->length > 0) {
    echo $review = $results->item(0)->nodeValue;
}

Comment: Parece que o HTML não está em condições ou não está a ser recolhido na totalidade.
Comment: Estranho pois ele é recolhido inteiro pelo curl
Answer: Altere o USER_AGENT.
Altere:
curl_setopt($ch, CURLOPT_USERAGENT, "Opera/9.80 (J2ME/MIDP; Opera Mini/4.2.14912/870; U; id) Presto/2.4.15");

Para:
curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows NT 5.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/38.0.2125.104 Safari/537.36");

Você pode alterar para qualquer outro, desde que seja um navegador de Desktop.
Utilizando o atual(Opera Mini) o site está redirecionando para o modelo 'mobile' do site, que não contem a div. ;)
Comment: +1 Boa, nem tinha visto o UA em uso :)
Answer: O teu problema parece-me ser a forma como estás a passar o nome da class a ser localizada:
$html = '
Ora que raio!

Ola meu nome é pseudomatica (sou normal), etc. Meu nome é assim pq sim

Encontrei

';

$dom = new DOMDocument;
$dom->loadHTML($html);

$class = 'minhaClasse'; // guarda nome da classe numa variavel

$procura = new DomXPath($dom); // instancia o DomXPath

$div = $procura->query("//*[contains(@class, '$class')]"); // Procura passando a variavel

Ver exemplo no Ideone:
var_dump($div->item(0)->nodeValue); // string(9) "Encontrei"

Comment: Fiz como me mostrou e retornou os mesmos erros, qual problema de meu curl?
Comment: Hmm... Dificil de dizer sem fazer testes com o teu código... mas aqui são 4:30h da manhã, já não tenho cabeça para ver isso a esta hora. Tentarei ajudar mais amanhã!
Comment: Boa noite, ate!

Capturar div pela class


Algorithm to define min-Max ranges with some defined bound

Question: Having to populate the following table of MIN-MAX cells, starting with only the knowledge of the IC value

I was thinking about a formula to get the values of A, B, C, D, E, F, G
which works also for the values of IC and 2xIC
I'm able to get the values from 0 to IC using the following formula:
$$K = 3$$
$$LEVEL.MIN = \frac{IC}{K} \times (LEVEL-1)$$
$$LEVEL.MAX = \frac{IC}{K} \times (LEVEL)$$
I need another similar formula for the values of E, F, G, 2xIC.
Maybe, since $E=IC$, the formula should have $+IC$ as a fxed part.
Comment: What do the different levels mean? What is IC? So I understand that "MIN" is the minimum value of some set, and "MAX" is the maximum value of some set, but what are these sets? Could you give more context to your problem? And how did you obtain the formulae that you wrote?
Comment: Each level is a rang of economic values, and I have the IC value as input.
They are needed to know in which level to put an item based on its value.
Comment: Are there some conditions for the values of A, B, C, D, E, F, G .... ?
Comment: Each level from 1 to 3 needs to have the same width = max - min
Each level from 4 to 5 needs to have the same width = max - min
and Level[N].min = Level[N-1].max
Answer: Let's look at the conditions that you gave. You say that the MIN of level $n$ should be equal to the MAX of level $n-1$. Using this condition, we should rename the variables like so:

Level 1: MIN = 0, MAX = A
Level 2: MIN = A, MAX = D
Level 3: MIN = D, MAX = E= IC
Level 4: MIN = E, MAX = G
Level 5: MIN = G, MAX = 2IC = 2E

The next condition is that each level from 1 to 3 needs to have the same difference between MAX and MIN. In other words,
$$
A = D-A = IC-D
$$
From this condition we see that $D = 2A$ and of course $$A=IC-D \qquad \Rightarrow \qquad D = 2IC - 2D \qquad \Rightarrow \qquad 3D=2IC$$
The next condition is that levels 4 and 5 need to have the same difference between MAX and MIN. In other words,
$$
G-E = 2E - G
$$
Adding $E+G$ to boths sides, this is the same as $2G = 3E$. Now we can plug in these results to get the new level hierarchy:

Level 1: MIN = $0$, MAX = $A$
Level 2: MIN = $A$, MAX = $2A$
Level 3: MIN = $2A$, MAX = $IC$
Level 4: MIN = $IC$, MAX = $\frac{3}{2} IC$
Level 5: MIN = $\frac{3}{2} IC$, MAX = $2IC$

With these conditions, the hierarchy is left with two free variables, IC and A. But otherwise, the hierarchy now follows the conditions that you gave.
Comment: $$A=\frac{IC}{K}=\frac{IC}{3}$$
I think I found the equivalent formula for the other values.
Answer: Ok, I finally got it.

The values from E to 2xIC can be calculated using the following formula:
$$W=2$$
$$LEVEL.MIN = \frac{LEVEL-1-1}{W} \times IC$$
$$LEVEL.MAX = \frac{LEVEL-1}{W} \times IC$$


L2TP/IPSec VPN setup Windows Server 2012 R2

Question: I am trying to setup a VPN server in Microsoft Azure to use for private/secure browsing. I found many tutorials on how to setup L2TP/IPSec on Windows Server and I was able to set it up and connect to it. However, I think I am missing a few steps to make client internet traffic go through the VPN server.
All the tutorials I found are work-related VPNs so they're not mentioning those extra steps. I think it has something to do with enabling NAT but I am not exactly sure what to do.
If anyone can provide any tutorials or give me guides/hints on what to do for setting up L2TP/IPSec on Windows (or linux) for the purpose of private/secure browsing would be great!
Thanks
Answer: Disclosure: I am the author of this GitHub repository.
Please see Setup IPsec VPN for a "one-click" IPsec VPN server setup script intended for use on Ubuntu, Debian or CentOS, for the purpose of private/secure browsing. Additionally, you may refer to Deploy to Microsoft Azure as well as Configure IPsec/L2TP VPN Clients from the same repository.
Comment: Thanks, i will try it out tomorrow and report back here.


Use for the AWS Free Tier

Question: I've just completed a Blog Project in Django. While looking for hosting solutions, I found that running the project on the Shared Hosting offered by majority of the Hosting Providers wasn't possible. Dedicated Hosting/ VPS would be too expensive for a simple  project such as these - A small Blog, a few static websites which probably won't have a lot of traffic etc.
A friend told me about AWS Free Usage Tier today and after checking it out, I had a few questions:

Does signing up for this give me a complete VPS over which I have complete control?
Can I monitor/regulate traffic from a browser-based console so that I don't exceed their bandwidth cap (this is highly unlikely but I'd like to be prepared)
I understand that this probably isn't production grade material and Amazon's offering this so that we can give it a try. Is this correct?
OS - I found that they offer a special kind of OS called AMI. Does this function like a normal OS with all its features (a little confused because I saw different stacks and I don't have a clue what they are). Are these preconfigured or can we customize the?

Thanks in advance
Answer: Answers:

Yes - it does
No, can't cap bandwidth
No. They are just like any other VM
AMI stands for 'Amazon Machine Image' - not an OS.  All kinds of OS images are available, including Amazon's own Linux flavour.  On the community tab, you can find Ubuntu, Fedora and many ohers.  Yes, they work exactly like they do on any other VM.  Just pick a new one like Ubuntu 12.10 or 12.04LTS - they have kernels more optimised for virtual machines.
Answer: Full features of AWS Free Tier is applicable for new users who registers with them. Free Tier has some limitations in using the EC2 Instnaces.
AWS AMIs(Amazon Machine Instances) are nothing but Linux and Windows server Instances.
You will have the complete control of all your virtual cloud server Instance that you create.
-Palaniappan

Use for the AWS Free Tier


preg_replace incorrect or strange behaviour in PHP

Question: I have a complitely reproducible example, which demonstrates strange behaviour of PHP preg_replace function. So, I have two files with such content:
//new.txt
Replacement 2\1

//before.txt
Text to replace

When I do this:
$regex = "`<!-- start -->(.*?)<!-- end -->`";
$replacement = file_get_contents("new.txt");
$target = file_get_contents("before.txt");
$after = preg_replace($regex, $replacement, $target);
echo $after;

it prints:
Replacement 2Text to replace

which is indeed incorrect. But when I do this:
$regex = "`<!-- start -->(.*?)<!-- end -->`";
$replacement = "Replacement 2\1";
$target = "Text to replace";
$after = preg_replace($regex, $replacement, $target);
echo $after;

it prints:
Replacement 2

which is more correct (though, as you can see, the last "\1" disappeared). BTW, if I remove "\1", both examples start to work correctly. So, how can I fix it?
Comment: I wonder why people are voting down, even though I provided reproducible examples and my own code snippets.
Comment: Besides, please, pay attention, that I said "incorrect or strange behaviour", so I'm not insisting that it is some PHP bug. Probably, I'm just doing something wrong.
Comment: So, if I asked some stupid thing, why not to point to this stupidity? What for is this silent voting down?
Answer: Big mix of different things is happenning here.
(I've gone with a supposed expected result of Replacement 2\1)
For the first topic, in regex replacement, \1 is a backreference. This will be replaced by the chars matched in the first parenthesis in the pattern.
It could also be written as $1.
You can use numbers from 1 to 99. You can find more info here in PHP doc for regexes and for preg_replace (see replacement)
This explains why the \1 is replaced by Text to replace as this is the part matched by (.*?)
The second thing is to remember the difference between single quoted ('str') and double quoted strings ("str").
In single quoted strings, the backslash doesn't have a special meaning (except to escape a single quote : echo 'str\'str' produces str'str or to escape itself : echo 'str\\str' produces str\str).
But in double quoted strings, backslash has special meaning and introduces an escape sequence (\n, \r,...) and can also represent a char in octal notation. This happens here in your
second string. It's a double quoted string and \1 is replaced with the SOH char, which is not a visible char.
The third thing is that a string read from a file is not changed like a double or single quoted string, you get it exactly like it is in the file.
The solution :
You need to escape the backslash, but how many times needs ?

Condition : the preg_replace function needs to recieve this exact sequence of char \\1 so it doesn't see it as a backreference, after changes made to escape sequences if any.
In the text file, as backslash is not interpreted, use : Replacement 2\\1
In the PHP code file, in a single quoted string, \\ produces \ and \1 is not changed : use 'Replacement 2\\\1'
In the PHP code file, in a double quoted string, \\ produces \ and \1 is seen as octal char : use 'Replacement 2\\\\1'

Now you'll get addicted to the backslash...


How to display specific button for certain user?

Question: I have a simple Drupal 7 page with 3 buttons. Page is only accessible by logged-in users.
I have 3 roles - role 1, role 2 & role 3
What I would like to do is to show only button 1 when a user with role 1 logged in, hide the other 2.
How can I achieve this, please?
Answer: To hide and show buttons by role you can use the $GLOBALS to get the user and check on user role, something like.
<code> <?php if (in_array('role 1', $GLOBALS["user"]->roles)): ?>
    <button value="button 1">button 1</button>
  <?php else: ?>
    <button value="button 2">button 2</button>
    <button value="button 3">button 3</button>
  <?php endif; ?>
</code>


Negative inner fence value in a box and whiskers plot?

Question: I calculated a negative lower inner fence value. I've double checked my work but I can't figure out what's wrong. I was under the impression that these values couldn't be outside of the min and max (duh).
My values range from 0.06188 to 1.90957 and when I plot them in Graphpad it looks fine. I'm plotting with the 10% and 90% percentile whiskers (calculated as 0.515 and 1.359 respectively by Graphpad).
I'm calculating the fraction of my datasets that are outside of the Tukey range (+/- 1.5*IQR), and the 10% and 90% range (possibly outliers). But when I calculate the Tukey fences myself using
lower inner = Q1-1.5(IQR)
upper inner = Q3+1.5(IQR)

I get a negative number for the lower value (-0.06758).
I calculated the 10%/90% using Graphpad, so that's not a problem for now.
Here's are the values, if anyone wants to recreate my calculations.
0.06187564,0.2931995,0.4433044,0.4908953,0.4992562,0.5123487,0.5188922,0.5326462,
0.5400167,0.5722309,0.6232626,0.6340977,0.6361935,0.6417624,0.6618853,0.6727413,
0.6990075,0.7250414,0.7575482,0.8221549,0.8573231,0.8732418,0.8749654,0.8751485,
0.88039,0.8831163,0.8842309,0.8927583,0.9143585,0.9371856,0.9644587,0.9662355,
0.9758021,0.9919777,1.004403,1.027557,1.037168,1.057354,1.075599,1.110754,1.120563,
1.135613,1.135632,1.135986,1.137239,1.148205,1.156857,1.175097,1.197407,1.21761,
1.219516,1.265934,1.304216,1.310815,1.336853,1.341317,1.357579,1.359387,1.462214,
1.552785,1.621189,1.760872,1.909566

It has to be something dumb I'm missing.
Answer: You just calculated the limits on where the whiskers can go, not the whisker ends themselves (which are limited to the range of the data).
The actual whiskers go out to the furthest-out data value inside the (inner) fences. The fences can go outside the data, but aren't actually plotted.

(for more details see this image, which is from this page)
Comment: For another way to see this, imagine a simple data set with 5 values of 0 and 5 values of 1. Then the quartiles are 0 and 1 and the IQR is 1. So the fences are at -1.5 and 2.5. It is very easy even for the fences to be completely outside the range of the data.
Comment: The standard Tukey definition of the whisker positions is the largest value not exceeding the upper quartile + 1.5 IQR and the smallest value not less than the lower quartile - 1.5 IQR. When Tukey was asked why 1.5, he just said that 1 would be too small and 2 would be too large.
Comment: @captainentropy If that's the definition it's using, then it's not quite following Tukey; in his definition the whiskers are supposed to go to data points. Not that it especially makes a lot of difference to the look in most cases. (Boxplots are one of those things that have a lot of slightly different variations.)
Comment: OK, thanks. I see now that with Graphpad "Traditional Tukey whiskers go 1.5 times the interquartile distance or to the highest or lowest point, whichever is shorter." That last part being the source of my grief. The lower whisker stopped at ~0.0625 (my Y-axis is on log2 scale) when I have the whiskers set to "Tukey". It's the same for "Min to Max" whiskers.


Cypress freezing (Your tests are loading)

Question: Cypress for me is often stuck in the "Your tests are loading" screen. I am really confused as to why it happens, and restarting Firefox/crome doesn't help either. It doesn't depend on any code, happens completely randomly and today my luck was down so I was looking more at that then at my code. any help is welcome, and thank you in advance.
Comment: Doing a force refresh once the test page opens up makes it work most times. But I am yet to figure out why it is happening.
Answer: Late reply, but are you using webpack-preprocessor? I am and the same issue happened to me when I upgraded to Webpack 5 lately.
The solution was to downgrade to Webpack 4.
In this case it is a known issue, there is an open Pull Request on Cypress github that should hopefully fix it: https://github.com/cypress-io/cypress/pull/15611
Answer: If you're coding a project that's using another version and you install the project without using nvm use it will install the latest dependencies which may break the code that doesn't support the new dependencies version.
Check the original code Webpack version and be sure it is the same installed locally


Como um "if" funciona internamente?

Question: O if é muito usado na programação, e ele cumpre vários papéis importantes no dia a dia de um programador. O código parece que magicamente é executado se uma expressão  passada no if for verdadeira, caso contrário aquele código simplesmente é ignorado.
Mas como que ele funciona internamente?
Usem esse código como base (pseudocódigo):
var x = 8;
if (x < 4) {
    print("x é menor do que 4!");
} else {
    print("x é maior do que 4!");
}

Comment: Esta [resposta](https://pt.stackoverflow.com/a/41504/110782) te ajudaria?
Comment: @LuizAugusto eu estou falando como um if funciona **internamente**, como que a "mágica" acontece
Answer: Vamos dizer que não existisse o bloco de comandos, então ficaria mais ou menos assim (sem otimização):
var x = 8;
if (x < 4) goto TRUE;
print("x é maior do que 4!");
goto FIM;
:TRUE
print("x é menor do que 4!");
:FIM

Coloquei no GitHub para referência futura.
imaginando que entenda o conceito de goto e label que usei em TRUE, se não souber cabe pergunta específica.
Mas ainda não explica como o if é executado.
Bom, o processador sabe como tomar uma decisão, existe pronto um código que sabe se deve fazer algo ou não deve fazer algo, só isso, ele não analisa a condição. Isto costuma ser chamado de branch, ou seja, ele pega um galho ou outro galho. No Intel é a instrução jz ( ou je, jne, ou outras veja uma lista).

Internamente tem um monte de portas lógicas que executarão um algoritmo para tomar essa decisão, mas basicamente o que ela faz é desviar a execução (muda o registrador PC que é o registrador que guarda o endereço da próxima instrução a ser executada) se existir um valor em uma flag do registrador (veja a lista delas).
Essa flag do registrador terá um valor de acordo com a última execução de uma instrução anterior possivelmente de comparação (não necessariamente) que tenha alterado uma das flags que será verificada. Então a condição é feita de forma separada do if. Eu sempre disse que no fundo o que acontece é isto (muitas pessoas não entendem e acham que a condição faz parte do if:
var x = 8;
var cond = x < 4;
if (cond) goto TRUE;
print("x é maior do que 4!");
goto FIM;
:TRUE
print("x é menor do que 4!");
:FIM

Note que o if e o goto ainda são uma coisa só, apenas uma instrução causa o desvio condicionalmente (diferente da instrução JMP que causa o desvio incondicionalmente e é o goto simples).
Claro que em algumas linguagens isso funciona um pouco diferente até porque rodam em máquinas virtuais, mas em essência é a mesma coisa. O mesmo vale para processadores diferentes.
De fato em C compilaria mais ou menos para isto:
.LC0:
        .string "x \303\251 menor do que 4!"
.LC1:
        .string "x \303\251 maior do que 4!"
teste:
        push    rbp
        mov     rbp, rsp
        sub     rsp, 16
        mov     DWORD PTR [rbp-4], 8
        cmp     DWORD PTR [rbp-4], 3
        jg      .L2
        mov     edi, OFFSET FLAT:.LC0
        mov     eax, 0
        call    printf
        jmp     .L3
.L2:
        mov     edi, OFFSET FLAT:.LC1
        mov     eax, 0
        call    printf
.L3:
        nop
        leave
        ret

Veja no Compiler Explorer.
No caso o jg é a instrução que toma a decisão (ela é jump if flag value is greater). A instrução CMP é que faz a comparação e gera um valor na flag ZF.
Em C# seria isto:
.class private auto ansi '<Module>'
{
} // end of class <Module>

.class public auto ansi beforefieldinit C
    extends [System.Private.CoreLib]System.Object
{
    // Methods
    .method public hidebysig
        instance void M () cil managed
    {
        // Method begins at RVA 0x2050
        // Code size 26 (0x1a)
        .maxstack 8

        IL_0000: ldc.i4.8
        IL_0001: ldc.i4.4
        IL_0002: bge.s IL_000f

        IL_0004: ldstr "x é menor do que 4!"
        IL_0009: call void [System.Console]System.Console::WriteLine(string)
        IL_000e: ret

        IL_000f: ldstr "x é maior do que 4!"
        IL_0014: call void [System.Console]System.Console::WriteLine(string)
        IL_0019: ret
    } // end of method C::M

    .method public hidebysig specialname rtspecialname
        instance void .ctor () cil managed
    {
        // Method begins at RVA 0x206b
        // Code size 7 (0x7)
        .maxstack 8

        IL_0000: ldarg.0
        IL_0001: call instance void [System.Private.CoreLib]System.Object::.ctor()
        IL_0006: ret
    } // end of method C::.ctor

} // end of class C

Veja no SharpLab.
E em Assembly:
; Core CLR v4.700.19.46205 (coreclr.dll) on x86.

C..ctor()
    L0000: ret

C.M()
    L0000: mov ecx, [0x10998940]
    L0006: call System.Console.WriteLine(System.String)
    L000b: ret

Veja no SharpLab. Aí você pergunta: onde está a condição? O compilador percebeu que poderia resolver em tempo de compilação e matou o if :). Em C se ligar todas otimizações ele fará o mesmo. Algumas linguagens sabem otimizar bem.
Não vou entrar na questão das portas lógicas que fica baixo nível demais, mas é só manipulação de dados existentes no processador (foi colocado lá antes), como já dito antes, a condição gerará um valor em uma das flags do processador que não deixa de ser um registrador, e um valor é mudado no PC (IP para alguns), depois a execução continua no endereço da memória que está marcado nesse registrador.
Por ser algo mais difícil para a maioria se tiver algum ponto não entendido avise, eu posso melhorar a resposta de acordo com a necessidade.
Comment: @JeffersonQuesado agora pode apreciar a foto aqui tb, roubei :D
Comment: Você falou nos _branches_  de execução e obviamente me lembrei desta resposta https://stackoverflow.com/a/11227902/4438007
Answer: Um compilador converte seu código fonte para código de máquina, no qual é entendível pelo computador. Durante o processo de conversão, o código fonte passa por várias fases do compilador.
Uma dessas fases é  a fase geradora de código intermediária, no qual o código intermediário para o seu código fonte é gerado, no qual é otimizado na fase de otimização de código para aumentar a eficiência do código no geral, e assim, finalmente ser convertido em código de máquina na última fase de geração de código.
Agora para responder sua pergunta.
Um código intermediário é representado usando a Notação de 3 Endereços. Um código de 3 endereços é representado da seguinte maneira:
Result := Argument_1 operator Argument_2

É chamado Código de 3 Endereços porque há 3 referências para o endereço das variáveis.
Por exemplo esse bloco de código (Essa é a resposta que você procura):
var x = 8;
if (x < 4) {
    print("x é menor do que 4!")
} else {
    print("x é maior do que 4!");
}

Agora a representação do código de 3 Endereços vai ser a seguinte:
1) var x = 8;
2) var Result = x < 4;
3) if Result then goto (5)
4) goto (7)
5) print("x é menor do que 4!");
6) goto (8)
7) print("x é maior do que 4!");
8)

Sim, o if funciona usando goto. É assim que isso funciona:

Ele primeiro verifica se x < 4 em uma variável usando notação de 3 endereços.
Se a condição for true, o programa vai para a linha 5.
Se a condição for false, ele vai para a próxima linha, na qual manda o programa para a linha 7.
As linhas 5 e 6 é o bloco de código dentro do if. A linha 6 manda o programa para a linha 8, no qual está basicamente saindo do bloco if-else e continua processando o resto do código.
A linha 7 é o pedaço de código no bloco else. Como o else "está" no fim, ao terminar de executá-lo automaticamente o programa já vai para o código após o bloco if-else, então não é necessário um goto.

Então é assim que o if funciona. goto é usado extensivamente pelo compilado através do código. Isso não é limitado ao bloco if.
Note que também é possível em alguns lugares que a condição seja executada diretamente no if, como if x < 4 then goto (5) baseado no exemplo acima.
Comment: Eu tenho a impressão que pra ser mais próximo da linguagem de máquina a instrução 8 deveria ser `nop`, o _no operation_, exceto se tiver alguma comando após a execução da condicional
Comment: O `3AC` é muito importante nos processos de optimização dos código gerados pelo compilador.

Como um "if" funciona internamente?


Harmonizing melody exercise question with specific parameters

Question: I'm reading the book Harmony for the computer musician and there's an exercise where you need to harmonize 3 notes of a melody in D major, parameters are:

you must use the same note length as the upper voices
root position triads only
triads are I - V - I
4 voices
Avoid consecutive 5ths and octaves
Have the leading note of the dominant triad rise up to the tonic

He proposes 2 solutions to the problem which are in the image below, one by choosing to not use the leading note of the dominant to rise up to the tonic and another one by using only 3 voices on the third chord.
I came to another solution but I'm guessing it's wrong but I can't figure out why it's wrong. Here's my solution:
Comment: What is the book?
Answer: The answer you have given has parallel fifths in the bottom two voices between the last two chords. To be more specific, the bass (bottom voice) plays D-A-D while the tenor (second from bottom) plays D-E-A. It is the interval A-E in the second chord, moving to D-A in the last, that gives the parallel fifths.
Answer: In addition to the parallel fifths that @Reina pointed out, your solution also breaks the sixth rule since it does not resolve (or rise) the leading tone of the dominant (C#) up to the tonic root (D) as it should, but instead drops a fifth to the third of the tonic (C#-F#).
Comment: +1 Good catch. Much agreed. Though this resolution doesn't "break the rules," it still just doesn't sound right.


Insert directly multi data rows with multi column to DynamoDB using API Gateway

Question: I'm trying to insert data to DynamoDB directly with API Gateway. I can insert single, but get stuck with insert multiple data rows. May be problem with the mapping template (always get com.amazon.coral.service#SerializationException error)

My dynamoDB table structure ex_table: time, column1, column2
My gateway mapping template:

#set($inputRoot = $input.json('$.items')})
{
    "TableName": "ex_table",
    "Item":
    [
        #foreach($elem in $inputRoot) {
            "time": {"S": $input.json('$.time')},
            "column1": "$elem.column1.S",
            "column2": "$elem.column2.S",
        }#if($foreach.hasNext),#end
        #end
    ]
}

And this is my request body:

{
  "time": "2021-03-31 16:50:00",
  "items": [
    {
      "column1": "Item1",
      "column2": "Attr1"
    },
    {
      "column1": "Item2",
      "column2": "Attr2"
    }
  ]
}

Can you guys help me this. Many thanks !
Answer: I think what you're looking for is "BatchWriteItem" in the DynamoDB API Reference.  Instead of the normal Item{...} syntax for single writes, BatchWriteItem takes a slightly diff style:
{"RequestItems":{
    "TableName": [
        {"PutRequest" : {
            "Item": {
                "Name":{"S" : "Some Name"},
                "Category":{"S" : "Some Category"}
            }
        }},
        {"PutRequest" : {
            "Item": {
                "Name":{"S" : "Some Name 2"},
                "Category":{"S" : "Some Category 2"}
            }
        }}
    ]
}}

Combined with changing the action within APIGateway to BatchWriteItem and updating your mapping template like this (untested) should get you there (or close):
#set($inputRoot = $input.json('$.items')})
{
    "RequestItems": {
        "ex_table" : [
            #foreach($elem in $inputRoot) {
                "PutRequest" : {
                    "Item" : {
                        "time": {"S": $input.json('$.time')},
                        "column1": "$elem.column1.S",
                        "column2": "$elem.column2.S",
                    }
                }
            }#if($foreach.hasNext),#end
            #end
        ]
    }
}


Ip Configuration in Fortigate 60d

Question: I have a fortigate 60d which bought around 3-4 years ago. Today i tried to install over of fiber internet. I connected my forti with 192.168.3.1 then i clicked wizard and entered new values and new ip range (192.168.0.50 - 192.168.0.210). Also i set ip of machine 192.168.0.1. But now when i am trying to enter 0.1 or 3.1 i couldn't login the forti.
When i looked to my ip configuration it is giving a different ip as 169.254.96.217 . I pressed around 15 seconds to the reset button backside of the forti but nothing changed.
How can i connect the machine again or how can i reset my machine
Answer: When i modified fortigate it will disable dhcp. I made static ip as 192.168.3.20 and subnet mask 255.255.255.0 then i can enter the system.

Ip Configuration in Fortigate 60d


Where can I access my index.js file if I deployed to heroku parse from the website

Question: So after parse shut down I started to use a parse heroku datatbase setup and I deployed it for free from the website. I now need to access my index.js file for my app on heroku. How can I do that
Answer: It should be in the root directory of the build you committed to heroku.  if you don't know where this is any more you can pull your heroku build to your computer.
These instructions are on the deploy tab of your heroku build.
enter image description here
Install the Heroku CLI
Download and install the Heroku CLI.
If you haven't already, log in to your Heroku account and follow the prompts to create a new SSH public key.
<code>$ heroku login
</code>
Clone the repository
In terminal go to the directory you want to clone the build to
<code>$ cd your-parse-server-name
</code>
Use Git to clone parse-server-nextbreath's source code to your local machine.
<code>$ heroku git:clone -a your-parse-server-name
$ cd your-parse-server-name
</code>
your index.js will be in this folder
Deploy your changes
Make some changes to the code you just cloned and deploy them to Heroku using Git.
<code>$ git add .
$ git commit -am "make it better"
$ git push heroku master
</code>
Comment: is says that when I clone the project its empty
Comment: I don't know then sorry.  when i run $ heroku git:clone -a your-parse-server-name my project is cloned onto my local drive


SearchApiException: Unknown or invalid item type node

Question: I was working on site, when I got this error:

WD php: SearchApiException: Unknown or invalid item type node. in
  [error] search_api_get_datasource_controller() (line 1396 of
  /var/www/luken/shop/sites/all/modules/search_api/search_api.module).
  SearchApiException: Unknown or invalid item type node. w
  search_api_get_datasource_controller() (linia 1396 z
  /var/www/luken/shop/sites/all/modules/search_api/search_api.module).
  Drush command terminated abnormally due to an unrecoverable error.
  [error]

Site is telling me about "Unexpected error", the above error I'm getting thanks to the Drush. Last thing that I did, was:

Removing one Product Display content type (I'm using Commerce),
Changing indexed fields in Search API,
Clearing the cache - after that, site was down.

I even don't know where to start with fixing this. I was trying to disable Search API module with Drush, but it appeared that I can't, because I'm getting above error all the time. I can access to /admin/modules but still I cannot disable Search API, because of unexpected error.
What can I do to fix this?
Added:
I deleted my search index, now I was able to disable Search API, but error still appears when entering the site. I checked log, there is an error:

EntityMetadataWrapperException: Unknown data property
  commerce_product. w EntityStructureWrapper->getPropertyInfo() (linia
  339 z
  /var/www/luken/shop/sites/all/modules/entity/includes/entity.wrapper.inc).
Comment: See also: https://drupal.org/node/1903004
Answer: I managed to fix the site with the help of Commerce Repair:

This module is designed to repair missing fields from various commerce entities. After installing, visit the menu item that does the repair, admin->store->config->Repair Commerce Fields (admin/commerce/config/repair). Once you've done that you can uninstall the module.


java.lang.IllegalStateException: SimpleTypeImpl should not be created for error type

Question: Have been facing this error after migrating to AndroidX.
java.lang.IllegalStateException: SimpleTypeImpl should not be created for error type: ErrorScope{Error scope for class <ERROR CLASS> with arguments: org.jetbrains.kotlin.types.IndexedParametersSubstitution@14ac19e7}

This link does not help much
Comment: I found that the next line after the `java.lang.IllegalStateException` line gives you the name of the problematic class. In my case, I didn't have the gradle dependency (for rxjava) in the offending library module.
Comment: In addition to @AgileNinja's suggestion, my error was outputting `[ERROR: Response]`. It was because I had removed the retrofit dependency from one of my modules. Nice 2 hours wasted...
Comment: Make sure you updated all: IDE, Gradle, Kotlin version, Kotlin IDE plugin etc. I believe I had this once and it was IDE/plugin related.
Comment: I also see this! Were you able to resolve this?
Comment: @UtkarshBarsaiyan I had to make changes manually even after choosing Migrate to AndroidX from Android Studio and I have realised until everything is up to date(versions, IDE, gradle, code etc), this error wont go.
Comment: Have you got the solution?
Answer: For me, the error was appearing due to invalid import statement. Android Studio didn't show anything regarding the same. I had to go to every single file, then studio shown the invalid import error. Fixed it and the build error's gone.
Comment: It is indeed the missing imports are the caused on my side. Use the *Analyze > Inspect Code* menu if you don't want to go every single file checking the missing imports.
Comment: For me, it was a similar problem. Also, the import was in a test file, which I've observed in the past that don't get a compiler check by the IDE until they are run or opened...
Comment: Similar problem. Thank you for your experiences.
Comment: It actually showed in the preview of each file when searching for "import", which gave me more clues of what had gone wrong.
Comment: @pablisco you saved my day. My missing import statement was indeed located in a test file
Answer: I updated to Kotlin 1.3.20 but it still did not work. Then I decided to check the Kotlin source code. I found this link
I had an interface called DisplayItem<T> and I removed its type parameter. After this, I started to get the error. Actually, at the end of the error in logcat it says DisplayItem
So i checked all DisplayItem types in code and I found I forgat to remove one type parameter in a LiveData variable like the follwoing:
MediatorLiveData<DataHolder<List<DisplayItem<MessageViewEntity>>>>

After removing type parameter from the variable it started to compile. I hope this'll help you.
Note: You can use git grep for a quick search.
Comment: `git grep` on what?
Comment: I have many classes in which I use `` and I cannot remove them as it is needed. Is there any other solution?
Comment: @IgorGanapolsky In my case the problematic broken class was `Event' *` and I found a ViewModel with a wrong import. Godspeed, my friend.
Comment: when you check the logs it says the type. you should grep the type and check in which one you missed to remove the type parameter.
Comment: This may be late. But search for LiveData in my case I found that some templates were referring to non existent types
Answer: My main tip to solve this issue would be when you're just getting the error message with no clue where the real error is, try the Android studio Analyze/Inspect code option. Digging through the output from this I found the actual compile errors that were triggering the problem and then could easily fix them.
The actual problem in my case was when changing a generic class, that had a nested class, into an abstract class and creating two sub-classes to replace it's previous usage. I still had references my code to the original abstract base class where I should have replaced them with one of the two new sub-classes.
Answer: Migrate to AndroidX option in Android Studio didn't help much. I solved this error by making changes in every file manually, changed the package names according to AndroidX in both code and xml. If any file is left unchanged, you will see this error. Please make sure your Kotlin plugin version, gradle plugin version, build tools and Android studio version is up to date.
Answer: I did following steps to solve the issue.
1-Updated android studio from 4.1.1 to 4.2.1
2-Update below line in gradle-warepper.properties file
distributionUrl=https\://services.gradle.org/distributions/gradle-6.9-all.zip

3- Update some kotlin extentions like below
buildscript {
    ext.kotlin_version = '1.3.72'

to
buildscript {
    ext.kotlin_version = '1.4.32'

 dependencies {
        classpath 'com.android.tools.build:gradle:4.0.1'

to
dependencies {
        classpath 'com.android.tools.build:gradle:4.2.1'

It will take some time for gradle sync etc but finnaly for me solved the problem after waisting whole day.
Answer: I just updated my kotlin-gradle-plugin version in root build.gradle and it resolved my issue
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:1.3.72"

to
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:1.4.32"

Comment: Probably an outdated version of kotlin plugin...
Answer: Upgrade your Kotlin dependency to 1.7.20 and the compiler will highlight the source of your issues.
Comment: yep, post was from Jan 2019
Comment: Seems like an old version of Kotlin...
Answer: If this error is related to import.
So we can also do this
Right click on module -> Optimise Imports.
In this way we can save time from going to every single file and findout that import.
Comment: This definitely saves time from going to every file, and displays meaningful compiler errors.


Select table with name from column value

Question: I have this SQL query
SELECT table_name
INTO #LukaTestTable
FROM information_schema.columns
WHERE column_name = 'GUID'
ORDER BY TABLE_NAME ;

How get the value of the column GUID in all tables with the name from TABLE_NAME?
Or can I get table like?
TABLE_NAME GUID_VALUE

Comment: Are you using MySQL or SQL Server? Those are two different databases.
Comment: Are you sure that all the columns GUID have the same data type?
Comment: @JustinasMarozas SQL Server
Comment: @sepupic yes, same data type
Comment: Then you can construct dynamic select with union all
Answer: In order to be able to query a table before you know what table you want you have to use dynamic queries. If you have an arbitrary number of tables, in SQL Server you could achieve this with cursors:
DECLARE
    @column VARCHAR(256) = 'GUID',
    @table VARCHAR(256),
    @query VARCHAR(4000);

DECLARE #Tables CURSOR LOCAL FAST_FORWARD
FOR
SELECT TABLE_NAME
FROM INFORMATION_SCHEMA.COLUMNS
WHERE COLUMN_NAME = @column
ORDER BY TABLE_NAME;

OPEN #Tables
FETCH NEXT FROM #Tables INTO @table

WHILE @@FETCH_STATUS = 0
BEGIN
    SET @query = 'SELECT ' + @column + ' FROM ' + @table
    EXEC(@query)

    FETCH NEXT FROM #Tables INTO @table
END

CLOSE #Tables
DEALLOCATE #Tables;

If you're sure your 'GUID' column will have same data type - you can create a temp table and insert to it in WHILE loop and SELECT everything in one go at the end.
Comment: Thanks! Works, just EXEC (@query)
Answer: You can use dynamic sql like this:
   declare @sql varchar(max) = cast (' ' as varchar(max));
    select @sql = @sql +
    (select ' select GUID from ' + quotename(table_name) + ' union all ' as 'text()'
    from #LukaTestTable
    for xml path(''));

    set @sql = reverse(stuff(reverse(@sql), 1, 10, ''));
    --print @sql
    exec(@sql);

And if you want table_name as e separate column you should first save it in your     #LukaTestTable
Answer: Try this below script using While loop and dynamic Sql
IF OBJECT_ID('tempdb..#GetSqlQuery') IS NOT NULL
DROP TABLE #GetSqlQuery
IF OBJECT_ID('tempdb..#GetSpecficcolumnvalue') IS NOT NULL
DROP TABLE #GetSpecficcolumnvalue
GO
CREATE TABLE #GetSqlQuery
(
ID INT IDENTITY
,SELECtQuery nvarchar(max)
,TableName varchar(200)
)

CREATE TABLE #GetSpecficcolumnvalue
(
ID INT IDENTITY
,GetValue nvarchar(max)
,TableName varchar(200)
)

INSERT INTO #GetSqlQuery(SELECtQuery,TableName)
SELECT 'SELECT GUID,'''+TABLE_NAME+''' As TableName FROM '+QUOTENAME(TABLE_NAME) AS SELECtQuery,QUOTENAME(TABLE_NAME) AS TableName
FROM(
SELECT
    TABLE_SCHEMA,
    TABLE_NAME,
    COLUMN_NAME

FROM INFORMATION_SCHEMA.COLUMNS
WHERE COLUMN_NAME ='GUID'
)dt
ORDER BY TABLE_NAME

DEclare @MinId INt,@MaxId INT,@Sql nvarchar(maX),@TableName varchar(1000)
SELECT @MinId =MIN(Id),@MaxId=MAX(ID) FROM #GetSqlQuery
WHILE (@MinId<=@MaxId)
BEgin
SELECT @Sql=SELECtQuery ,@TableName=TableName   From  #GetSqlQuery WHERE ID=@MinId

PRINT @Sql
INSERT INTO #GetSpecficcolumnvalue(GetValue,TableName)
EXEC (@Sql)
SET @MinId=@MinId+1
END

  SELECT  ROW_NUMBER()OVER(ORDER BY (SELECT 1)) AS Seq,GetValue,TableName
   FROM
   (
 SELECT *, ROW_NUMBER ()OVER(PArtition by GetValue,TableName    ORDER BY
 TableName) AS dup FROM #GetSpecficcolumnvalue
  )dt where dt.dup=1