Execute shell command from service

Question: I am trying to execute a shell command from within a C# service that I created.  However, this command does not seem to execute.  As a standard console application, it works perfectly though, so I know there is no issue with the command itself or how it is being executed form within the code.  Can anyone tell me why this would not work?  Please keep in mind I am pretty new to C#, so this may just be a matter of my inexperience.  Below is the code from the service itself:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Management;
using System.Diagnostics;
using System.ServiceProcess;
using System.Threading;

namespace AdapterDisableTest
{
    class Program : ServiceBase
    {
        //private static Timer workTimer;

        static void Main(string[] args)
        {
            ServiceBase.Run(new Program());
        }

        public Program()
        {
            this.ServiceName = "AdapterDisableTest";
        }

        protected override void OnStart(string[] args)
        {
            base.OnStart(args);

            Process myProcess = new Process();

            myProcess.StartInfo.FileName = @"C:\Program Files\Oracle\VirtualBox\VBoxManage.exe";
            myProcess.StartInfo.Arguments = "controlvm test setlinkstate1 off";
            myProcess.StartInfo.UseShellExecute = false;
            myProcess.StartInfo.CreateNoWindow = true;
            myProcess.Start();

        }

        protected override void OnStop()
        {
            base.OnStop();

            //TODO: clean up any variables and stop any threads
        }

    }
}

Comment: Is the process you are launching interactive (i.e. does it have a UI?).  It's bad news if so - check this similar thread out which has some excellent information linked within it http://stackoverflow.com/questions/4147821/start-a-windows-service-and-launch-cmd
Comment: Incidentally if it is an interactive process you can still launch it from a service, but it requires using the Win32 API as opposed to using the built in `Process` functionality in .Net.
Comment: No, there is no GUI with the application that I am attempting to run (VirtualBox itself does have a GUI, but this utility is purely cli driven).  I am not entirely sure what you mean by an interactive service, but I can tell you that the application takes arguments, executes them immediately, and then self-terminates after doing so, all from within the command prompt.  I am assuming this is what you were needing to determine?
Comment: It may be worth adding a working directory to the `StartInfo` of the process as the starting folder behaviour is different when launching processes from a service - try setting `StartInfo.WorkingDirectory = @"C:\Program Files\Oracle\VirtualBox"` and see what happens.
Comment: Good thought, but unfortunately that didn't work either.
Answer: If it's a windows app that requires the desktop, you're pretty much SOL. If it's a standard console application, you need to redirect standard input, standard output and standard error. You also need to set the ProcessStartInfo's UseShellExecute property to false: you service can't start the OS shell (cmd.exe) as that requires access to the desktop...and further, you can't redirect standard input with that property set to true.
Standard input is normally wired up to the keyboard. Your service does not have access to the keyboard. Standard out and standard error are normally wired up to the cmd.exe console window.
Once you have standard output and standard error redirected, you'll need to wire up handler to these Process object events:

Exited. Raised when the process ends.
OutputDataReceived. Raised when data is written to standard output by the process (in reality, occurs when any buffers on the output stream are flushed, so it may lag from the actual write operation).
ErrorDataReceived. Raised when data is written to standard error.

I tend to redirect standard output and standard error to the same stream and make sure that that stream is unbuffered. It's the equivalent of the cmd.exe incantation
some-command 2>&1

to redirect stdout and stderr into the same file handle.
Comment: This particular utility does not require the desktop.  It is just a standard console app which is executed using a few arguments that I had specified using myProcess.StartInfo.Arguments = "controlvm test setlinkstate1 off".  I'm sorry but your explanation is a bit over my head.  Could you break this down a bit for me?
Comment: That's what I'm saying. Unless you specify `UseShellExecute = false ;`, your executable process is going to started under an instance of CMD.EXE. That requires a desktop and your service doesn't have access to it.
Comment: This has already been set on the line: myProcess.StartInfo.UseShellExecute = false
Answer: As it turns out, the reason why this was not working was due to Application Compatibility - Session 0 Isolation.  Essentially, the service launched the process as intended, but it was being launched inside of session 0, so it was hidden from the user, and as such, the user could not interact with it.
In order to get around this constraint, I was able to follow the guide Subverting Vista UAC in Both 32 and 64 bit Architectures written by Pero Matić.  This brief guide allowed me to spawn a process from a service inside the currently logged on user's session, rather than inside of session 0.  Sadly, I no longer have the completed code that I used to get this to work as the project I was using it for was cancelled.

Execute shell command from service


How to get fitted values, prediction, and residual plots for Exponential GLM?

Question: To get Exponential GLM, you can do:
fit = glm(formula =...,  family = Gamma)
summary(fit, dispersion=1)
But how do you get the fitted values, prediction using new data, and Pearson's residuals easily? I used to do fitted.values(fit), predict(fit, newdata, type = 'response'), and residual(fit, type = 'pearson') after fitting a GLM as the object fit. But this isn't fitting an Exponential GLM to the object fit...
Comment: This appears to be a question only about how to use these R functions (& hence off topic here).
Comment: @gung I believe there's an underlying statistical issue to explain here. This question could be modified to reflect that aspect and some of the present question relating to R functionality is then partly moot -- the remainder could be posted as a new question.
Comment: I'd be happy with this question if it were edited to focus on the underlying statistical issue.
Answer: The distinction between exponential and general gamma has no impact on the fitted or predicted values from the GLM. So you can calculated them as normal.
Depending on how exactly you want to define Pearson residuals, it may impact the Pearson residuals by a scale factor related to the square root of the estimated deviance. Any plots based on Pearson residuals will have the same appearance either way, so unless you're calculating some quantity based on the Pearson residual it probably won't matter. However they can be rescaled by the square root of the ratio of deviances as desired (R doesn't seem to adjust its Pearson residuals by an estimated dispersion in any case, so it should make no difference).
Comment: Thanks. My response has 0's in it. When I fit a Gamma GLM, I got this error "Error in eval(expr, envir, enclos) :
  non-positive values not allowed for the 'gamma' family". I wanted to use Exponential distribution because 0 is in the support.
Comment: Actually, you should have exactly the same problem with exponential as with the Gamma, because in both cases the support is the same  -- $(0,\infty)$ (don't believe Wikipedia's page on the exponential in this regard; you can't have exact zeros with the exponential)
Comment: @ Glen_b: Gah, you're right; I wasn't thinking. I guess my only option for continuous response is Tweedie.
Comment: Hardly your only option. I'd think zero-inflated or hurdle models; the problem with Tweedie is that a $p$ parameter than matches the proportion of zeros well is rarely one that matches the rest of the distribution well.
Comment: @ Glen_b: Actually, 0 is allowed in the support of exponential distribution. I looked at a textbook. Yeah, I think I need a zero-inflated model of some sort because the histogram of the response seems spiked towards 0. Hmmm...I guess Tweedie is not good for prediction a lot of the times?
Comment: Even if you did put 0 in the support, you still cannot accommodate an exact zero observation in an exponential GLM fitted by ordinary means because $\log(0)$ would appear in numerous formulas that are used in GLM fitting (such as the deviance). With a log-link (or an inverse link) you'd stall at the calculation of starting values before you even began your first iteration. And even if you put 0 in the support, two exact zeros would still indicate that your continuous model was wrong.
Comment: Tweedie may be perfectly adequate for prediction if your interest is in forecasting a mean. If your interest is broader (in the whole distribution), it is sometimes fine and at other times not.


Exact Fisher Test for testing algorithms

Question: I developed two version of the same algorithm to detect and analyze some medical data through iPhone's camera and I want to compare the result in a mathematical way in order to know which algorith gives better results.
The results of the test can be : SUCCESS, FAIL or INVALID.
I tested 56 samples with both the algorithms.
These are the results:
<code>          ALGORITHM 1             ALGORITHM 2
FAIL           12                     14
INVALID        12                      0
SUCCESS        32                     42
</code>
Is correct Applying Fisher Test to these data? I had done it with R Studio and I obtained a p-value << 0.05, so I think this show that one of the algorithm Is better than the other, but I'm not sure I can do it.
Thanks a lot
Comment: Are the outcomes ordered? (i.e. is "invalid" less serious - and thereby closer to success - than "fail" is?) ... and if not, what does "better" mean?
Answer: TLDR: No.
The data is compatible with Fisher's exact test, in your case using the algorithm as the categories and fail/invalid/success as the input. However, what Fisher's Exact test shows is whether the two algorithms give significantly different patterns of categorisation. It is not the appropriate test for your hypothesis of one being 'better'.
see https://www.ncbi.nlm.nih.gov/pmc/articles/PMC5426219/ for a useful scientific article explaining Fisher's exact, many more can be found on scientific search engines.
To determine which is 'better' you need to have a ground truth to compare against. I.e. do you know how which samples should be fails, should be invalid and should be success? You need a statistical test based on contingency tables, but which one applies depends on what exactly matters most about the comparison.
Does it matter more it gets fails right? Or maybe successes or even correctly flagging invalid result? Are all of equal importance? I would advise you search around and learn about contingency tables and associated metrics such as accuracy, sensitivity, specificity, positive and negative likelihood ratios, area under the curve etc.
Comment: Yes I know in advance the result of the sample.
-SUCCESS means: the sample is positive/negative and the algorithm detects  positive/negative.
-NEGATIVE means: the sample is positive/negative and the algorithm detects negative/positive
- INVALID means:  the sample is positive/negative and the algorithm can't detect it
Which other test do you suggest to me in this case?Thanks
Comment: Hi Fab, In that case looking at the means for success will be the most useful next step. However, the methods in the last paragraph in my answer are probably the more appropriate approach overall. There is not enough info here to provide a useful answer.
Comment: Thanks a lot. One last question: Can I say that fisher show me that the two algorithms give significantly different results , so one is probably better than the other BUT  to know who is better (because fisher don't give me this information) I will use different methods? For example the means that you suggested before or precision and recall , etc. ?
Comment: That is correct


How can I develop a regular rehearsal programme?

Question: I've been learning scales and chords, and tried a few songs. It sounds nice and by practising, I'm becoming faster and more comfortable. I also use the things I learn to improvise and jam. But I get the feeling I should rehearse more regularly. I notice I'm not progressing much in terms of expanding the scales and chords, or learning more difficult techniques.
How can I develop a regular rehearsal programme that allows me to enjoy the creative parts of guitar playing while still moving me forward on the basic techniques and theory?
Answer: What you can try is to setup something concrete; a practice routine. Whether you practice daily, or not, when you sit down to practice you should have a clear goal of what you want to accomplish. When I was a classical guitar student my goal was Mon-Fri 4 hours a day, Sat 2 hours, Sunday off. I'd highly suggest you strive for a greater number of successive days practicing, rather than one marathon day.
When I could get a perfect practice session in, my sessions were usually broken down into a few areas. These are not necessarily concrete, and it's been some years since I was really practicing a lot... (also forgive me if some of these areas are classical guitar-oriented) :

(15min) I would begin with very simple left and right hand exercises. Really easy, like one finger, one string... pluck, release tension, watch, listen.
(15min) I'd pick a scale [I had dozens to pick from] and work on various aspects, some days it would be one or more areas of focus. Concepts like shifting, left or right hand, phrasing, speed, clarity, sound were all important.
(90min) New pieces that I needed to learn. Sometimes these were broken down into little bits of technical exercises, or phrase repetitions.
(120min) Current pieces I needed to maintain for recitals, competitions, etc. Again, sometimes I'd break down phrases or sections, other times I'd practice to perform, that is, pretending I was actually at a recital (no stopping, cursing, freaking out)

So for you, what you could do is this....

X minutes - work on some old chords, adding a new one each session. At some point you'll have enough to make progressions and you'll have some nice variety.
X minutes - pick a scale [for a day, week, month] and only work on that until you reach your goal [all X positions, a certain speed, etc.]
X minutes - new songs. spend time breaking apart new songs you want to learn, don't just play the parts that you know, like, or are easy. The hard sections are the ones that will need the most focus, and that sort of analysis turns hard songs into easy ones.
X minutes - old/current songs. Songs that you want to maintain, improve, or otherwise jam with. You have to keep them fresh by practicing or you'll forget them.

With a practice routine like this you have some time for the theory aspects [numbers 1 and 2], as well as the more fun, song-oriented practicing [3 and 4]. Naturally none of this is set in stone, and I switched my exercises within my routine all the time. The biggest piece of advice I can give is that you really need to make sure you have a goal in mind when you sit down with your instrument or you'll just waste time.
There's also some good advice at this post.
Answer: I think @bluevoodoo1 has the right answer, apart from one thing that was important to me, but might not be to you depending on circumstances:
Booking practice rooms and playing with people - a band, or just jamming with friends!
I always found I would slowly imporve technically when practicing with a metronome or to music on my own, but I would make great jumps when actually riffing with musicians; the feel of the music would come to me much more naturally, and I could try things out in a real world scenario.
Seriously, find a good place to practice, book regular slots and find a group of like minded musicians (or even rotate who you play with to improve your variety)
Answer: Your guitar routine should depend on your style of playing, level and on the amount of time you've got to play guitar. Check out Steve Vai's 30hr guitar workout. It's a bit extreme but has some awesome ideas in there.
Decide on what type of guitar player you want to be. That will tell you the areas you want to work on. If you want to be a metal player, concentrate on picking technique, muting etc. If you want to play jazz, work on music theory - stuff like chord-scale relationship, understanding harmony(this will take you a few years).
Choose 3-4 techniques and work on them 1 technique a day. For example, I'm a rock player inclined towards improvisation. Here's what I try to work on:
Mon & Thu: Alternate Picking
Tue & Fri: Legato/Tapping
Wed & Sat: Economy/Sweep Picking
Sun: Music Theory
Now, I try to work on 3 things each session -
Warmup - very IMPORTANT. You're going to feel like shit if you jump into the exercises directly. 10 mins of this should be enough.
Exercises - Pickup exercises from books/magazines/videos and work on them. Try doing all of them in the same key. Its pointless doing an exercise if you can't do it in a musical context. @bluevoodoo1's post talks in depth about this.
Jam - Play over chords/backing tracks/with a friend and use only the technique you've decided to work on for the day. This is my favorite part of the routine and IMO the most helpful. Try to spend equal time on exercises and jamming.
Have a day off every week. Use it to read up on music theory or to write new music. Be creative.
Remember, this is a mere guideline. Try to be consistent but make sure you don't burnout by changing things around regularly. Take a day off once in a while to learn a new song or just jam. Any routine is pointless if you're not having fun doing it.
I hope this helps.
Answer: Part of what you are doing is to learn skills mechanically enough that you don't have to think about what muscles need to move over here, and what amount of pressure over there is right. That means consistency. And for music, that means daily practice - 20 minutes every day is far better than 2 hours once per week.


Why is playing to the spirit of the game considered so important in cricket?

Question: It's something I've always wondered about. I, myself, do not like to see players and sometimes even whole teams use the Laws to their advantage. In other sports, notably football (soccer), playing by the spirit of the game is much less of an issue.
Answer: Cricket was a game formed in England by the gentry. The English have a long and strong historic tradition of being the better man.
The ethos of playing the game for the game's own sake was reflected in many sports of English origin, notably football and field hockey - early rule books of these sports exhorted players to adhere to the spirit of the game and of fair play as late as the 1920s and 1930s.
Cricket is not exceptional in this regard in the modern era of sports either. The Pyeongchang Winter Olympics 2018 were marred by controversy in its curling competition after one team chose an entirely valid and legitimate penalty instead of a less useful one, solely because this choice was so far outside the expectations of politeness and good manners within the game. To a lesser extent this politeness exists in golf, related by culture to both curling and cricket, and reflects a similar cultural pride in "doing one's best regardless of the result". Ultimate (frisbee) requires adherence to the spirit of  the game for a game to even proceed, in the deliberate absence of referees and umpires to control violations of rule.
In summary, cricket (and other sports with such an attitude) treat it as important because they have always treated it as important, and the basis of this importance stems from wider cultural attitudes.
Comment: This is pretty much my view on the subject: cricket is a gentleman's game, and gentlemen play the game a certain way... but I'd love to see some supporting references.
Answer: Its viewed by the organisations in charge that the spirit of the game is an important part of history and what makes Cricket different and so players, officials and organisers are encouraged to support the spirit of the game to keep crickets special place in society.


Imported variable in nodejs showing undefined

Question: I'm new to nodejs. trying out a simple export(using module.export) and import using require() but when i try to print out the imported constants i get "undefined". Please help. Code provided below. Also i realise there is the export/import ES6 way but i'd like to fix this particular error by still using module.export and require(). Same error on intelliJ IDEA and VScode.
constants.js
const fname = 'Abdulraqib';
const lname = 'Olayanju';

module.export = {
    fname : fname
};

index.js
const name = require('./constant');

console.log(name.fname);

package.json
{
  "name": "fe-workshop",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "start": "node index.js",
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC"

}

Comment: It has to be `module.exports` in your contants.js file.
Comment: check the name of the file too. It should be `./constants` where you import I believe. Also check the path of your files.
Comment: Yeah... It's a typo the file name is constant.js... thanks
Answer: It is module.exports not module.export
const fname = 'Abdulraqib';
const lname = 'Olayanju';

module.exports = {
    fname : fname
};


If p $\equiv$ 3 (mod 4) with p prime, prove -1 is a non-quadratic residue modulo p.

Question: If p $\equiv$ 3 (mod 4) with p prime, prove -1 is a non-quadratic residue modulo p.
I suppose this would not be true if p $\equiv$ 1 (modulo 4).
To prove something is a non-square I find to be tricky. It's difficult to see any straightforward way to do this using only the definition of congruence for example.
Answer: Assume $$x^2\equiv-1\pmod{p}$$
$$(x^2)^{2k+1}\equiv - 1\pmod{p}$$
$$x^{4k+2}\equiv -1\pmod{p}$$
For all $k$. Now $\exists k$ such that $4k+2=p-1$
Thus,
$$x^{p-1}\equiv-1\pmod{p}$$
Which is in clear violation of fermat's little theorem.
Comment: Very neat and simple. +1
Comment: @DonAntonio thank you. :)


Erro ao tentar observar o conteúdo de uma variável ou propriedade de um objeto no debugger do VS 2013

Question: Em praticamente todas as vezes que tento observar o conteúdo de uma variável ou propriedade de um objeto, recebo o erro abaixo:

Function evaluation disabled because a previous function evaluation timed out. You must continue execution to reenable function evaluation.

Isso não acontecia no VS210 e nem no VS2012, pelo menos não até o ultimo patch de atualizações.
A pergunta é. Existe alguma configuração, ou definição de aplicação para que o Watcher do Debugger volte a funcionar corretamente?
Answer: Eu tive a oportunidade de experimentar este aviso no VS2010 também. Na verdade, ele pode aparecer sempre que o conteúdo que você estiver inspecionando tomar muito tempo para sofrer Eval.
Para fins de debugging, Eval equivale ao sequestro da thread observada pelo debugger, que então permite que você não apenas tenha acesso ao conteúdo da thread mas também a manipule (por exemplo rodando código diretamente na Debug CLI).
O problema principal dessa técnica é que, para poder congelar o estado da aplicação, o debugger pára todas as outras threads. O problema óbvio ocorre se a thread observada tenta interagir com alguma das threads congeladas.
Se este é o seu caso, a resolução do seu problema vai depender da maneira como seu código foi implementado.
Comment: Faz sentido agora. Visto que normalmente ocorre num trecho de código assíncrono.
Comment: Exato. Isso também pode acontecer se uma das threads congeladas está consumindo um objeto em *SyncLock*, e a thread principal tenta fazê-lo durante debugging.


JavaScript src link

Question: Boas,
tenho o seguinte código, em uma função Javascript,
function(){
   var noDataIcon = document.createElement("img");

   noDataIcon.src = "~/Images/delete_database.png";

}

acontece de me deu erro no src, não consegue encontrar a imagem.
Como resolvo este problema?
Obrigado
Comment: "Images"... acho que o "I" é minúsculo.
Comment: Corrija o caminho da imagem o código está correto. :)
Comment: ja corrigi, ele está nesta pasta, mas continua a dar erro
Comment: Obrigado, já funcionou mas tive de retirar o ~
Answer:
Como resolvo este problema?

Não usando esta notação:
"~/Images/delete_database.png";

Ela só é válida dentro do código do servidor. Não em código de cliente.
Utilize no lugar:
noDataIcon.src = "/Images/delete_database.png";

Se a aplicação estiver em um subdiretório, pode ser necessário ter que tratar o endereço.

JavaScript src link


Set default value to an image field form element using form_alter

Question: I am using this code, but the form doesn't get default image value:
The image is created and exists in the server:
<code>$image = file_get_contents($url);
$destination = 'image.jpg';
$file = file_save_data($image, $destination, FILE_EXISTS_RENAME);
</code>
And $form is populated this way:
<code>$form['field_user_picture']['und'][0]['value']['#default_value']['fid'] = $file->fid;
</code>
I think I am missing something, could anybody help?
Answer: Try it like this:
<code>$form['field_user_picture']['und'][0]['#default_value']['fid'] = $file->fid;
</code>
(Remove <code>['value']</code> key.)


Go to another view on button click - view is not found

Question: "Test.cshtml" view is never found.

ERROR: The view 'Test' or its master was not found or no view engine supports the searched locations.
  The following locations were searched:

Among listed locations there are:

~/Views/SecondGroup/Test.aspx
~/Views/SecondGroup/Test.ascx
~/Views/SecondGroup/123.cshtml

but not correct location which should be "~/Views/SecondGroup/Test/123" ??
ViewOne.cshtml (generated by FirstController)
<button onclick= "@("window.location.href ='" + @Url.Action("Test",
"SecondController", new { id = "123" }) + "'");">
 GO TO ANOTHER VIEW
</button>

SecondController
public ActionResult Test(string id)
{
    return View("Test", id);  // here id = '123'
}

Test.cshtml
@model String
@{
   Layout = "~/Views/Shared/_Layout.cshtml";
}

 ....

Here is the folder structure:
---Controllers
     --- HomeController
     --- FirstController
     --- SecondController

-- Views
     --- FirstGroup
         --- ViewOne

     --- SecondGroup
         --- Test

Why "Test.cshtml" view is never found?
Thank you
Answer: In your Test(string id) method, you're using return View("Test", id); which uses this overload because the type of id is a string.
In that overload, the 2nd parameter is the name of the master page or template to use when the view is rendered.
You need to use this overload where the 2nd parameter is object (your model).
Change the code to cast the string to object:
public ActionResult Test(string id)
{
    return View("Test", (object)id);
}

Comment: Thank you, it works. For others who may have same issue: there are more ways to pass string model here https://stackoverflow.com/questions/48796982/go-to-another-view-on-button-click-view-is-not-found


Android ndk-build error make.exe: *** create_child_process: DuplicateHandle(In) failed (e=6)

Question: I'm relatively new to Android and I have a problem using the ndk-build command.
I use the NDK r9d under Windows 7 64bits.
When I run my build system which creates my Android project (makefiles etc...) and then creates a process running ndk-build.cmd (I checked that it is call in the Android project) I get the error:
make.exe: *** create_child_process: DuplicateHandle(In) failed (e=6)
But when I run ndk-build.cmd "manually" in the windows command console in the same Android project created by my build system (or any Android project) everything is working.
I did find some related questions like here:
https://www.ibm.com/developerworks/community/forums/html/topic?id=77777777-0000-0000-0000-000014825836
https://cygwin.com/ml/cygwin/2004-09/msg01506.html
But all I found says either that it's a problem of make version which is not (I think) since ndk-build works fine when I use it "manually" or it says that it is related to stdin handling and again I don't think that the issue here. Plus all the anwsers that I found was related to a similar error but not exactly the same:
process_easy: DuplicateHandle(In) failed (e=6)
Maybe someone knows the meaning of my error message. I don't think that's specific to Android ndk-build but maybe.
Thank you for reading (and sorry for any english mistakes, I am french and not fluent in english)
Answer: Finaly, I found a solution to my problem here:
http://www.zeusedit.com/zforum/viewtopic.php?t=174
I am not sure about what the problem was but according to this link, it was related to the make environment and the handles.
The solution : Instead of using the createProcess function (from Windows) directly to call ndk-build.cmd, I created a batch file containing:
start ndk-build.cmd
And I called this batch (.bat) via the createProcess function.
I let you see the link for more details.


clang-AST traversal - How to get member variables of a class

Question: I want to traverse the AST of a simple class having one member variable and one method. I have figured out that the class is represented as CXXRecordDecl.
What is the api within CXXREcordDecl to get the list of member variables which are represented as FieldDecl ?
Comment: It would be easier to override VisitFieldDecl instead.
Answer: The fields can be retrieved with RecordDecl::fields (there exist also methods the get the begin and end iterators of that range), e.g. for a CXXRecordDecl
CXXRecordDecl* cl = ...;
for (const auto& field : cl->fields) {
    const auto& name = field->getName();
    const auto field_cl = field->getType()->getAsCXXRecordDecl();
}

Similarly you would access the methods with methods().


Unreachable Statement

Question: Preciso de ajuda, na linha 107 o android studio mostra um erro que diz:

"Error:(107, 48) error: unreachable statement"

Sendo que a Linha 106 que é o AdapterView.AdapterContextMenuInfo info fica em vermelho. Quando removo a linha 107 que é o int id a linha do AdapterView deixa de ficar vermelha indicando o erro.
Ja tentei de todas as formas mas não consigo achar o erro.
Listar.java
package cliente.api_dominando.devmedia.hugo.estudos.br.devmedia_cliente.Activity;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.text.StaticLayout;
import android.util.SparseBooleanArray;
import android.view.ContextMenu;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;

import java.util.List;

import cliente.api_dominando.devmedia.hugo.estudos.br.devmedia_cliente.ADAPTER.ClienteAdapter;
import cliente.api_dominando.devmedia.hugo.estudos.br.devmedia_cliente.DAO.ClienteDAO;
import cliente.api_dominando.devmedia.hugo.estudos.br.devmedia_cliente.R;
import cliente.api_dominando.devmedia.hugo.estudos.br.devmedia_cliente.VO.ClienteVO;

public class Listar extends Activity {

    ListView ltv;
    List<ClienteVO> lista = null;
    private Button btn_apagar;

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

        ltv = (ListView) findViewById(R.id.ltv_dados);
        ltv.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);

        registerForContextMenu(ltv);

        btn_apagar = (Button) findViewById(R.id.btn_apagar);

        ltv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                btn_apagar.setVisibility(View.VISIBLE);
            }
        });

    }

    public void Apagar_click(){
        String nome = "";
        SparseBooleanArray checkeds = ltv.getCheckedItemPositions();

        for(int i = 0; i<checkeds.size(); i++){
            nome += lista.get(checkeds.keyAt(i)).getNome();
        }
        Toast.makeText(getBaseContext(), nome, Toast.LENGTH_LONG).show();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_listar, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
        super.onCreateContextMenu(menu, v, menuInfo);
        AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) menuInfo;

        menu.setHeaderTitle(lista.get(info.position).getNome());
        menu.add(Menu.NONE, 0, 1, "Editar");
        menu.add(Menu.NONE, 0, 0, "Apagar");

    }

       @Override
        public boolean onContextItemSelected(MenuItem item) {
            return super.onContextItemSelected(item);

            AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();
           int id = lista.get(info.position).getId();

            if(item.getItemId()==1){
                startActivity(new Intent(getBaseContext(), Editar.class).putExtra("id", id));
            }
           return true;

        }

    @Override
    public void onResume(){
        super.onResume();
        ClienteDAO dao = new ClienteDAO(getBaseContext());
        lista = dao.getAll();
        ltv.setAdapter(new ClienteAdapter(getBaseContext(), lista));

    }

}

/**package cliente.api_dominando.devmedia.hugo.estudos.br.devmedia_cliente.Activity;

import android.app.ListActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ListView;

import cliente.api_dominando.devmedia.hugo.estudos.br.devmedia_cliente.ADAPTER.ClienteAdapter;
import cliente.api_dominando.devmedia.hugo.estudos.br.devmedia_cliente.DAO.ClienteDAO;
import cliente.api_dominando.devmedia.hugo.estudos.br.devmedia_cliente.R;
import cliente.api_dominando.devmedia.hugo.estudos.br.devmedia_cliente.VO.ClienteVO;

public class Listar extends ListActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

    }

    @Override
    protected void onListItemClick(ListView l, View v, int position, long id) {
        ClienteVO vo = (ClienteVO) l.getAdapter().getItem(position);
        startActivity(new Intent(getBaseContext(), Editar.class).putExtra("id", vo.getId()));

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_listar, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onResume(){
        super.onResume();
        ClienteDAO dao = new ClienteDAO(getBaseContext());
        setListAdapter(new ClienteAdapter(getBaseContext(), dao.getAll()));

    }

}
*/

Answer: O erro está aqui:
public boolean onContextItemSelected(MenuItem item) {
    return super.onContextItemSelected(item);

    AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();
   int id = lista.get(info.position).getId();

    if(item.getItemId()==1){
        startActivity(new Intent(getBaseContext(), Editar.class).putExtra("id", id));
    }
   return true;

}

De fato, nada após a primeira linha do método será executado, já que essa primeira linha contém um return, que força a saída do método. Então todo o código que segue é unreacheable, ou seja, nunca será executado.
Comment: Nossa meu velho, "no creo"!!! E não é q deu certo, heheheh. VLW

Unreachable Statement


Distance of binary strings to produce the lexicographical order

Question: Indexing objects like elements of a Cantor Set or nodes of a Binary Tree can result in a enconding system of binary strings like illustrated bellow:

The illustrated indexes form a finite set,  $$C_3=\{0,00,000,001,... ,111\}$$
We can provide the set $C_3$  of a comparison operation, offering the same elements in a sequence with the lexicographical order (also illustred with the sequence into square breakets), that is a total order relation.
The same set can be mapped into a set of numerical pairs (bitLength,value), $$V_3=\{(1,0), (2,0), (3,0), (3,1), (2,1), ... , (3,7)\}$$
where 0=(1,0), 00=(2,0), 000=(3,0), 001=(3,1), 01=(2,1), ... etc. Any element $x$ is a pair $(x_{bitLength},x_{value})$.  A generic $V_k$ have elements with $bitLength \le k$. In fact this generic set was defined in this other question as:
$$V_k = \{\forall x = (l,n) ~|~  l,n \in \mathbb{N} ~\land~ bitLength(n) \le l \le k  \}$$
where the function $bitLength(n>0)=\lceil log_2(n)+1 \rceil$ and the bit-length of zero is one.
Now we can express a distance $d(x,y,k)$  of two elements $x$ and $y$ of $V_k$, that can be used as mathematical reference to the lexicographical order... What is the $d(x,y,k)$ function? How to proof that is the correct function for any $k$?

... Or more simples, What the comparison function $cmp(x,y,k)$?
There are no special "metric", the aim is to sort, that is, to check the value of comparison. As usual convention is $cmp(x,y,k)=1$ when  $x>y$, $cmp(x,y,k)=0$ when $x=y$ and $cmp(x,y,k)=-1$ when $x>y$.

NOTES
Supposing that there are someting as dyadics that can be used in the proof... Seems good in some tests, but I do not know how use mathematical foundations or how to proof: d(x,y) = x.value/2^x.bitLength - y.value/2^y.bitLength
Some raw  data to tests, illustrating with all elements of $C_4$ and $V_4$:
(bits,value)    Binary representation
(1,0)           0
(2,0)           00
(3,0)           000
(4,0)           0000
(4,1)           0001
(3,1)           001
(4,2)           0010
(4,3)           0011
(2,1)           01
(3,2)           010
(4,4)           0100
(4,5)           0101
(3,3)           011
(4,6)           0110
(4,7)           0111
(1,1)           1
(2,2)           10
(3,4)           100
(4,8)           1000
(4,9)           1001
(3,5)           101
(4,10)          1010
(4,11)          1011
(2,3)           11
(3,6)           110
(4,12)          1100
(4,13)          1101
(3,7)           111
(4,14)          1110
(4,15)          1111

Some distances to test:

d(00,01) = d(10,11)
|d(000,0)| = |d(1,111)|
d(1101,11) < d(1100,1101)
...
Comment: Hi, please comment your down-vote: we can **simplify** or redo the question. Redo is possible, there are no external answer, I can **delete all** and restart the question.
Answer: The distance function $d(x,y,k)$ is arbitrary and can be simple... With scalar values we can use $d(x,y)=x-y$. In this problem $x$ and $y$ are vectors: $x=(x_l,x_n)$ and $y=(y_l,y_n)$. To keep simple we can suppose that exists a "score function" that transforms the vectors into scalars.
Lets start with the suggested score, based on  dyadic numbers: $score1(x)=x_n/2^{x_l}$. The only problem is about 0, 00, etc. (also 101 and 1010, etc.) that need different scores. A simple correction is to add a fraction $\alpha x_l$  that is less tham the minor value of $score1$, that is $\alpha k<score1(1)$. So:
$$score2(x,k) ~=~ score1(x)+\alpha_k x_l ~=~ x_n/2^{x_l}+\frac{x_l}{k \times 2^{k+1}}$$
Using the example of $k=4$ (the set $V_4$), the result is:
x               Binary      Score1      Score2
(1,0)           0           0.000       0.008
(2,0)           00          0.000       0.016
(3,0)           000         0.000       0.023
(4,0)           0000        0.000       0.031
(4,1)           0001        0.063       0.094
(3,1)           001         0.125       0.148
(4,2)           0010        0.125       0.156
(4,3)           0011        0.188       0.219
(2,1)           01          0.250       0.266
(3,2)           010         0.250       0.273
(4,4)           0100        0.250       0.281
(4,5)           0101        0.313       0.344
(3,3)           011         0.375       0.398
(4,6)           0110        0.375       0.406
(4,7)           0111        0.438       0.469
(1,1)           1           0.500       0.508
(2,2)           10          0.500       0.516
(3,4)           100         0.500       0.523
(4,8)           1000        0.500       0.531
(4,9)           1001        0.563       0.594
(3,5)           101         0.625       0.648
(4,10)          1010        0.625       0.656
(4,11)          1011        0.688       0.719
(2,3)           11          0.750       0.766
(3,6)           110         0.750       0.773
(4,12)          1100        0.750       0.781
(4,13)          1101        0.813       0.844
(3,7)           111         0.875       0.898
(4,14)          1110        0.875       0.906
(4,15)          1111        0.938       0.969

Concluding: there are many possible functions, this one seems simple,
$$d(x,y,k)=score2(x,k)-score2(y,k)  ~=~ x_n/2^{x_l}-y_n/2^{y_l}+\frac{x_l-y_l}{k \times 2^{k+1}}$$

Algorithm of  lexicographical comparison
When using $d()$ as comparison function, it can be optimized; for example for $x_l=y_l$ can be replaced by the usual $d(x,y) ~=~ x_n-y_n$. Here a Javascript function to compare arbitrary-precision integers in the form x=(x.l,x.n), where  x.l is the bitLength (a small integer) and x.n the value, a BigInt.
function cmp_lexic(a,b) {
  let bdif = a.l - b.l
  if (bdif) {
   dif = (bdif>0)
     ? a.n/BigInt(2**bdif) - b.n     // normalize a
     : a.n - b.n/BigInt(2**(-bdif)); // normalize b
   if (!dif) dif = bdif;
  } else
   dif = a.n - b.n
  return dif? ((dif>0n)? 1: -1) : 0;
}

The comparison not depends on the maximal length k.


VMWare server host agent service won't start

Question: I'm using VMWare Server 2.0 on Windows Server 2003 R2. Sometimes after restarting the host machine, the VMWare host agent service won't start due to an error.
This is the error messages from Event Viewer:

[Service control manager] Timeout
  (30000 milliseconds) waiting for the
  VMware Host Agent service to connect.
[Service control manager] The VMware
  Host Agent service failed to start due
  to the following error:  The service
  did not respond to the start or
  control request in a timely fashion.

I've set the service to automatically restart after subsequent failure using services.msc (using a 10 min. delay), but it still won't start. Only starting the service manually seems to work.
Has anyone experienced this before? What workarounds or fixes are there?
-- updated --
Here's a small vbs script that i use to check whether a service is running or not, and automatically starts it if it's not running. I use the scheduler to run this script every 15min.
strComputer = "."
strSvcName = "VMWareHostd"

set objWMI = GetObject("winmgmts:\\" & strComputer & "\root\cimv2")

set objService = objWMI.Get("Win32_Service.Name='" & strSvcName & "'")

If objService.State= "Stopped" Then
    call SendEmail("email@example.com","firstname.lastname@example.com","Service X stopped","")
    objService.StartService()
End If

Private function SendEmail(From, Destination, Subject, Textbody)

    sch = "http://schemas.microsoft.com/cdo/configuration/"

    Set objEmail = CreateObject("CDO.Message")
    Set objCdoConfig = CreateObject("CDO.Configuration")

    With objCdoConfig.Fields
        .Item(sch & "sendusing") = 2 ' cdoSendUsingPort
        .Item(sch & "smtpserver") = "127.0.0.1"
        .update
    End With

    with objEmail

        set .Configuration = objCdoConfig

        .From = From
        .To = Destination
        .Subject = Subject
        .Textbody = Textbody

    end with

    call objEmail.Send

end function

--
Answer: create a scheduled task to run on startup that does
sc start vmware-service etc, or schedule a task to run every minute and try and start the task.
VMware server 2.0 sucks.
VMware server 1.0 was and is great.
Comment: This is a good answer. I scheduled a task to check if the service is running and start it if it isn't running.


Case Statement to determine if value in column is unique

Question: I am trying to find out if an 'Activity_ID' is unique for each 'Provider', and ideally I would like to do this via a Case Statement.
If I write a case statement to show you how I would like to approach this, then it would perhaps make more sense;
 CASE WHEN Concat (Activity_ID,Provider) IS **UNIQUE/DISTINCT** THEN 'Yes'
   ELSE 'No'
   END 'Unique_Flag'

   --Concat has been used as it is possible for a Provider to have an Activity_ID
     which is also used by another provider, however there is no connection and i am
     only interested in if an Activity_ID is unique for an indvidual provider

I would like the desired outcome to be something like below. I believe I am close and just need to replace UNIQUE/DISTINCT in the above with the appropriate command
Provider       Activity_ID    Unique_Flag
ProvA              11           Yes
ProvA              22           No
ProvA              22           No
ProvA              33           Yes
ProvA              44           Yes
ProvA              55           Yes
ProvB              55           No
ProvB              55           No

Comment: You can do it for example using (select count(*) from thesametable) > 1
Answer: SELECT CASE WHEN COUNT(*) OVER (PARTITION BY Provider, Activity_ID) > 1 THEN 'No' ELSE 'Unique' END, *
FROM ...

Using the OVER clause like this will run the aggregate across different windows of data, thereby letting you group by those two columns without destroying the rest of the set.
Answer: There are several ways to achieve this. You could use a derived table for example:
    --Sample Table and Data
    DECLARE @table TABLE
    (
        Provider VARCHAR(5),
        Activity_ID TINYINT
    )

    INSERT INTO @table
    VALUES
    ('ProvA',11),
    ('ProvA',22),
    ('ProvA',22),
    ('ProvA',33),
    ('ProvA',44),
    ('ProvA',55),
    ('ProvB',55),
    ('ProvB',55)

    -- Your desired query using a derived table
    SELECT  t.Provider, t.Activity_ID,
            CASE WHEN t2.Cnt = 1
                THEN 'Yes'
                ELSE 'No'
            END AS Unique_Flag
    FROM    @table t
            INNER JOIN
            (SELECT Provider, Activity_ID, COUNT(*) AS Cnt
            FROM    @table
            GROUP BY Provider,Activity_ID) t2
                ON t.Provider = t2.Provider
                AND t.Activity_ID = t2.Activity_ID


Extrato MySql a partir de tabelas ENTRADA e SAIDA

Question: Sou iniciante em MySql e PHP, estou construindo uma aplicação de gerenciamento financeiro para uma instituição beneficente, (trabalho voluntário), e não consigo resolver este problema:
Realizar uma consulta MySql nas tabelas ENTRADA e SAIDA que retorne os resulta como um extrato bancário.
Desde já minha gratidão por sua ajuda. God Bless you!!
Segue as tabelas e resultado esperado:
01 - TABELA ENTRADA
CREATE TABLE IF NOT EXISTS `entradas` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `data` date DEFAULT NULL,
  `mes_referencia` varchar(50) DEFAULT NULL,
  `conta` varchar(255) DEFAULT NULL,
  `doador` varchar(255) DEFAULT NULL,
  `valor_entrada` decimal(32,2) DEFAULT NULL,
  `n_documento` varchar(300) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=2465 DEFAULT CHARSET=latin1;**

02 - TABELA SAIDA
CREATE TABLE IF NOT EXISTS `saidas` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `data` date DEFAULT NULL,
  `mes_referencia` varchar(50) DEFAULT NULL,
  `valor_saida` decimal(10,2) DEFAULT NULL,
  `conta` varchar(100) DEFAULT NULL,
  `favorecido` varchar(100) DEFAULT NULL,
  `cpf` varchar(30) DEFAULT NULL,
  `categoria` varchar(100) DEFAULT NULL,
  `numero_doc` varchar(10) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=1079 DEFAULT CHARSET=latin1;

03 - RESULTADOS DOS MEUS SONHOS (kkkk)
Comment: dicas: armazene o saldo anterior e o saldo atual na tabela de movimento... e... justamente, faça uma tabela só de "movimentos" não precisa de duas...
Answer: Há alguns problemas nesse modelo, pode ser que seja apenas de um exercício conceitual, não utilizaria isso em um problema real. Certamente terá problemas com movimentos retroativos ou estornos.
Quando você separa em duas tabelas sendo que o resultado esperado será apenas uma, você adiciona uma complexidade desnecessária, precisando usar UNION na sintaxe, e isso piora ainda mais quando precisa acessar os mesmos dados várias vezes, como também é necessário para calcular os saldos.
Repare que a estrutura dos registros é a mesma, ainda que colocado nomes diferentes nas colunas [doador/favorecido] tudo se trata de uma pessoa relativa ao movimento. Isso também acontece com a coluna de valor, é Colocado [valor_entrada / valor_saida] sendo que se trata do mesmo dado, apenas valor; Ainda tem o uso do sinal +- para indicar se é uma entrada ou saída, que também facilita, se os valores estiverem sinalizados, basta somar todos.
Utilizando a estrutura apresentada, fiz a seguinte Query para extrair os dados desejados:
select
max(data) as data,
null as documento,
'Saldo Anterior' as conta,
null as pessoa,
0 as entrada,
0 as saida,
sum(valor) as saldo
from
(select data, valor from entradas where data < '2020-01-01'
union all
select data, valor from saidas where data < '2020-01-01') x

union all

select
data, documento, conta,pessoa,entrada,saidas, entradas_anteriores - saidas_anteriores + entrada - saidas as saldo
from (
  select
    id, data, documento, conta, pessoa, valor as entrada, 0     as saidas, (select coalesce(sum(x.valor),0) from entradas x where x.data < e.data) as entradas_anteriores, (select coalesce(sum(x.valor),0) from saidas   x where x.data < e.data) as saidas_anteriores  from entradas e where e.data >= '2020-01-01'

     union all
  select
    id, data, documento, conta, pessoa, 0     as entrada, valor as saidas, (select coalesce(sum(x.valor),0) from entradas x where x.data < s.data) as entradas_anteriores, (select coalesce(sum(x.valor),0) from saidas   x where x.data < s.data) as saidas_anteriores  from saidas   s where s.data >= '2020-01-01'
) m

order by data;

Você pode ver funcionando no SQLFiddle
Resultado:

Agora, utilizando a seguinte estrutura:
CREATE TABLE IF NOT EXISTS `movimentos` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `data` date DEFAULT NULL,
  `conta` varchar(255) DEFAULT NULL,
  `valor` decimal(32,2) DEFAULT NULL,
  `pessoa` varchar(255) DEFAULT NULL,
  `documento` varchar(300) DEFAULT NULL,
  `saldo_anterior` decimal(32,2) DEFAULT NULL,
  `saldo_atual` decimal(32,2) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=2465 DEFAULT CHARSET=latin1;

Com a seguinte query posso ter o mesmo resultado:
select
x.data,
null as documento,
'Saldo Anterior' as conta,
null as pessoa,
0 as valor,
x.saldo_atual
from movimentos x
where x.data < '2020-01-01'

union all

select
m.data,
m.documento,
m.conta,
m.pessoa,
m.valor,
m.saldo_atual
from movimentos m
where m.data >= '2020-01-01'

Mais simples não!?

Segue o SQLFiddle
Resultado:

Observações:

Eu não colocaria pra exibir o saldo anterior como uma linha do resultado, possivelmente seria exibido em outro local na tela, assim como o somatório total.
Nesse exemplo ainda há problema para o caso de movimento retroativo.
Comment: Olá, querido amigo @Rovann Linhalis
Meu **muito obrigado** por sua generosidade em usar um pouco do seu precioso tempo para me ajudar. De fato sua explicação **me ajudou bastante!**
como já tenho um sistema rodando onde há varios registro em 2 tabelas. Resolvi usar o seu primeiro exemplo.
OK, funcionou, mas tenho ainda um problema; AS ENTRADAS SÃO LISTADAS NA CONSULTA E SE REPETEM COMO SAÍDAS, JÁ AS SAÍDAS NÃO SÃO LISTADAS.
Segue aqui o MEU CÓDIGO REAL
[Meu código é este aqui]( http://sqlfiddle.com/#!9/72e0aac/1)
Caso possa me ajudar ainda agradeço muitíssimo!
Fica com Deus!
Comment: @Maggy no select dos pagamentos, você continuou usando a tabela de lancamentos... http://sqlfiddle.com/#!9/72e0aac/8
Comment: Uau!!! Valeu!!
Realmente, pronto. resolvido. obrigado mais uma vez
Comment: Deixo aqui meus parabéns a esta maravilhosa comunidade, e especialmente a você @Rovann Linhalis pela pronta atenção, sua explicação foi excelente e fundamental pra resolver meu problema. Vc é nota 1000!!

Deus te recompense

Obrigada, Obrigada!!
Comment: @Maggy, por nada, seja bem vinda e disponha, mas observe que há algumas regras na comunidade, como não usar o campo de respostas para fazer comentários ou complementar as perguntas, você pode editar a pergunta ou usar o campo de comentários. Se estiver com dúvida sobre isso também, há bastante material na comunidade e também fique a vontade para perguntar (lá no meta: https://pt.meta.stackoverflow.com/)
Comment: Ok. entendido. Obrigada


ServiceStack - dictionary to csv

Question: In my project I use ServiceStack to allow user to export data in csv format. It's ServiceStack that makes the job but it always sorts my dictionary by alphabetical and I don't want that. I want that my csv file have his columns in exact order that I inserted my data in the dictionary.
There is a way to configure ServiceStack to don't make this sort ?
My dictionary :
var excelResult = new Dictionary<string, string>();

                    excelResult["Id"] = x.Id.ToString();
                    excelResult["IBS Account Id"] = x.IBSAccountId.ToString(CultureInfo.InvariantCulture);
                    excelResult["IBS Order Id"] = x.IBSOrderId.ToString();

And in my csv file, instead of "Id, IBS Account Id,IBS Order Id" I have "IBS Account Id,IBS Order Id,Id"
Thank you very much !!
Comment: I'm looking for a solution to custom or override CSV serializer of ServiceStack. If you have any idea about that. ^^
Answer: Here is how to unregister the default 'text/csv' content-type and serializer.
In AppHost.cs,
using ServiceStack.Common;

In AppHost Configure()...
SetConfig(new EndpointHostConfig
{
    EnableFeatures = Feature.All.Remove(Feature.Csv),
});

Your apphost will no longer do any special handling for text/csv. At that point, you should be able to register it again as you wish, as explained in How to register your own custom format with ServiceStack.
Substitute your TapasSerializer for CsvSerializer and you should be good.
I discovered a clue how to do it from this SO answer.
Answer: Finally, I discover it's impossible(?) to override or custom ServiceStack CsvSerializer.
So, my solution (because I have to do something after all) : Create a new custom type, serialize it and write it in a csv file :)
Step 1 : (AppHOst.cs) Register my new type "tapas" (because I like tapas but I don't think my lead will be ok with that :p)
ContentTypeFilters.Register("text/x-tapas",
TapasSerializer.SerializeToStream, TapasSerializer.DeserializeFromStream);

Step 2 : (AppHOst.cs) Configure the response for the creation of the file
ResponseFilters.Add((req, res, dto) =>
        {
            if (req.ResponseContentType == "text/x-tapas")
            {
                res.AddHeader(HttpHeaders.ContentDisposition,
                    string.Format("attachment;filename={0}.csv", req.OperationName));
            }
        });

Step 3 : (myPage.handlebars) Swap csv with my new type in my request link (in java for my project)

{{localize "ExportOrders"}}

Step 4 : Your Tapas Serializer !
public class TapasSerializer
{
    static TapasSerializer()
    {
    }

    public static void SerializeToStream(IRequestContext requestContext, object response, Stream stream)
    {
       //TO DO
    }

    public static object DeserializeFromStream(Type type, Stream stream)
    {
        //TO DO
    }

}

Thank you for reading !

ServiceStack - dictionary to csv


$A,B$ are $n×n$ matrices such that $A^2B^2=0$.

Question: If $A$ and $B$ are two matrices of order $n×n$ such that $A^2B^2=0$ then show that $B^2A^2=0$.
Pre- and post-multiplying the given equation $A^2B^2=0$ by $B^2$ and $A^2$ respectively, I get $(B^2A^2)^2=0$, so at least we have that $B^2A^2$ is nilpotent of degree at most $2$. But I don't see how to proceed from here.
Comment: The statement isn't true (with $n=4$ at least); could you check if you have any more assumptions?
Comment: Please show some effort: What have you tried? MSE is not a place where monkeys make your homework for you.
Comment: What I have tried is as follows::A^2B^2=0.then pre and post multiply by B^2 and A^2 respectively. Thus I get (B^2A^2)^2=0 implies nilpotent.but couldn't prove the required thing.
Comment: I also think some more assumptions are needed!!
Answer: A counterexample with $n=2$:
$$A=\begin{pmatrix}1&0\\0&0\end{pmatrix}\qquad
B=\begin{pmatrix}0&0\\1&1\end{pmatrix}.$$
These are both idempotent i.e. $A^2=A$ and $B^2=B.$ We have
$$AB=\begin{pmatrix}0&0\\0&0\end{pmatrix}\qquad
BA=\begin{pmatrix}0&0\\1&0\end{pmatrix}.$$


Elasticsearch java API fuzzy search with prefix_length

Question: I hope to perform this query using elastic search using Java API. For the fuzzy query, how do I get the "prefix_length" argument?
Query:
{"query":{"bool":{"should":[

    {"fuzzy":{"object.name":{"value":"appl", "max_expansions":"1", "prefix_length" : 3}}},

    {"prefix":{"object.name":"appl"}},

    {"term":{"object.name":"appl"}}

]}}}

Java API:
QueryBuilder result = QueryBuilders.boolQuery()
            .minimumNumberShouldMatch(1)
            .should(QueryBuilders.fuzzyQuery(Company.FIELD_NAME, query)) ...

The documentation here doesn't explain how to get the "prefix_length" argument. Can someone explain? Thanks!
Answer: Aha. Can add like this:
should(QueryBuilders.fuzzyQuery(Company.FIELD_NAME, query).maxExpansions(1).prefixLength(query.length() - 1)


How to parse grouped text data in R and convert to data frame / time series

Question: I spent a lot of time trying to parse text from a data API outputting stock ticker data in groups contained within curly braces, data format as below :
/mktdata/ticker/AAA ?fields=ASK,BID:
MarketDataEvents = {
    BID = 600
    ASK = 605
    BID_ASK_TIME = 09:47:48.000
}

/mktdata/ticker/AAA ?fields=ASK,BID:
MarketDataEvents = {
    BID = 608
    ASK = 610
    BID_ASK_TIME = 09:47:49.000
}

/mktdata/ticker/AAA ?fields=ASK,BID:
MarketDataEvents = {
    BID = 602
    ASK = 605
    BID_ASK_TIME = 09:47:50.000
}

I tried the following to parse by line but can't seem to find a way to convert this text into a table:
rawData <- readLines(paste (filepath, filename, sep="/"))
DataTab <- data.table(txt = rawData[!grepl(pattern = '\\/mktdata/ticker/AAA ?fields=ASK,BID:', rawData)])

The end result I would like to see is :
BID ASK BID_ASK_TIME
600 605 09:47:48.000
608 610 09:47:49.000
602 605 09:47:50.000

This is the first time i request help here, please feel free to comment if my question is not clear.
Thanks a lot for your help !
PS : The actual data looks like this in the original "less well behaved" sample :
/mktdata/ticker/AAA ?fields=ASK,BID:
MarketDataEvents = {
    BID = 600
    BID_ASK_TIME = 09:50:48.000
}

/mktdata/ticker/AAA ?fields=ASK,BID:
MarketDataEvents = {
    ASK = 610
    LAST_PRICE = 610
    BID_ASK_TIME = 09:50:49.000
}

/mktdata/ticker/AAA ?fields=ASK,BID:
MarketDataEvents = {
    ASK = 605
    LAST_PRICE = 610
    BID_ASK_TIME = 09:50:50.000
}

/mktdata/ticker/AAA ?fields=ASK,BID:
MarketDataEvents = {
    BID = 599
    BID_ASK_TIME = 09:51:05.000
    LAST_PRICE = 601
}

Answer: You could keep only the lines where you have a specific pattern in the text. Here, I have kept lines where a word followed by = and a number, put them in a matrix and convert it to dataframe.
I have used pipes (%>%) for readability.
library(magrittr)

rawData <- readLines(paste(filepath, filename, sep="/"))

matrix(grep('\\w+ = \\d+', rawData, value = TRUE), ncol = 3, byrow = TRUE) %>%
  sub('.*=\\s', '', .) %>%
  as.data.frame() %>%
  type.convert(as.is = TRUE) %>%
  setNames(c('BID', 'ASK', 'BID_ASK_TIME')) -> DataTab

DataTab

#  BID ASK BID_ASK_TIME
#1 600 605 09:47:48.000
#2 608 610 09:47:49.000
#3 602 605 09:47:50.000

For the updated dataset we can find the position of { and } and create a sequence between them. Using regex we extract the data between them and bind all of them in one dataframe.
rawData <- readLines(paste (filepath, filename, sep="/"))
open <- grep('{', rawData, fixed = TRUE)
close <- grep('}', rawData, fixed = TRUE)

dplyr::bind_rows(Map(function(x, y) {
  tmp <- stringr::str_match(rawData[x:y], '(\\w+) = (.*)')
  setNames(data.frame(t(tmp[, 3])), tmp[, 2])
}, open + 1, close-1)) -> result

result

#   BID BID_ASK_TIME  ASK LAST_PRICE
#1  600 09:50:48.000 <NA>       <NA>
#2 <NA> 09:50:49.000  610        610
#3 <NA> 09:50:50.000  605        610
#4  599 09:51:05.000 <NA>        601

Comment: Thanks a lot it totally solves the simplified version. In reality, the data is a little less well behaved as is will randomly have more or fewer fields, and only bid or ask will be displayed in a group within `{...}`
The data looks more like :
`/mktdata/ticker/AAA ?fields=ASK,BID:`
`MarketDataEvents = {`
`    BID = 600`
`    BID_ASK_TIME = 09:47:48.000`
`}`

`/mktdata/ticker/AAA ?fields=ASK,BID:`
`MarketDataEvents = {`
`    ASK = 610`
`    LAST_PRICE = 610`
`    BID_ASK_TIME = 09:47:49.000`
`}`
Comment: Without an actual example of your data it would be difficult to help. Can you somehow share your text file?
Comment: Thanks a lot for your help and effort, I attached a sample file to the original post.
Comment: Is that any different than the file that you shared earlier? Looks same to me.
Comment: Hi Ronak, the fields between {..} can be different for each instance, for example, the first update packet only had "BID" and "BID_ASK_TIME" while the next update featured "ASK", "LAST_PRICE" and "BID_ASK_PRICE"
Comment: @SMA Can you check the updated answer if that helps.
Comment: Thanks for your help, this does the trick, I just need a bit of time to digest how you combined the regex with the wrangling stuff. Cheers


Correct way of upgrading with huge data

Question: I have a Drupal 6 site that contains hundred of thousands of node and bunch of custom and contributed modules. My problem now is how can I upgrade this correctly in Drupal 7. I tried to steps presented in DrupalCon Denver which is a good steps for me, but I have a problem in converting the data when running update.php which stops the process.
Is there any good way to handle this case?
Comment: It is always possible that you detected a bug related to your amount of nodes or something else. Or maybe your memory limit or execution time limit is too low. Please provide more details than just "which stops the process". Do you get an error? WSOD? Check your error logs...
Answer: Option 1:

Inventory your 3rd party modules as well as your custom modules. Identify those modules that has a Drupal 7 version or if it's included in Drupal 7 core.
Update the Drupal 6 core.
Update the contrib modules and themes.
Disable contrib modules.
When everything is up-to-date and contrib modules are disabled, run update.php. This process will take time depending on how big is your database.
Enable your modules and start fixing some API that is not supported by Drupal 7. Use coder module to assist you.
Check, check, check.

Option 2:

Build from scratch.
Use migrate module to migrate you Drupal 6 db to Drupal 7.
Answer: I have done upgrade of a Drupal website from 6.x to 7.x along with thousands of nodes migrated successfully to new one.
Drupal upgrade steps are listed in this link https://www.drupal.org/node/570162. I have followed these steps to make migrate successful.

Correct way of upgrading with huge data


DropDownLists Value Resetting

Question: I have a DropDownList populated with a set of values. When I click a value, the DropDownList value should stay to that value, but it resets to the default value (Select a Type) most of the time.
Here is the DDL:
<code>            <asp:TemplateField HeaderText="Criteria Type:" SortExpression="CriteriaType">
                <EditItemTemplate>
                    <asp:DropDownList ID="CriteriaType" AutoPostBack="True" runat="server" SelectedValue='<%# Bind("CriteriaType") %>'>
                        <asp:ListItem Value="0">Select a Type</asp:ListItem>
                        <asp:ListItem Value="TMEL Table">TMEL Table</asp:ListItem>
                        <asp:ListItem Value="Risk Matrix">Risk Matrix</asp:ListItem>
                        <asp:ListItem Value="Alarm Rationalization">Alarm Rationalization</asp:ListItem>
                    </asp:DropDownList>
                </EditItemTemplate>
                <InsertItemTemplate>
                    <asp:DropDownList ID="CriteriaType" AutoPostBack="True" runat="server" ViewStateMode="Enabled"
                        SelectedValue='<%# Bind("CriteriaType") %>'>
                        <asp:ListItem Value="0">Select a Type</asp:ListItem>
                        <asp:ListItem Value="TMEL Table">TMEL Table</asp:ListItem>
                        <asp:ListItem Value="Risk Matrix">Risk Matrix</asp:ListItem>
                        <asp:ListItem Value="Alarm Rationalization">Alarm Rationalization</asp:ListItem>
                    </asp:DropDownList>
                </InsertItemTemplate>
                <ItemTemplate>
                    <asp:Label ID="Label1" runat="server" Text='<%# Bind("CriteriaType") %>'></asp:Label></ItemTemplate>
            </asp:TemplateField>
</code>
Here is the code behind:
<code>        protected void Page_Load(object sender, EventArgs e)
    {
        DropDownList criteriaType = (DropDownList)DetailsView1.FindControl("CriteriaType");
        if (criteriaType.SelectedValue == "TMEL Table")
        {
            DetailsView1.Fields[5].Visible = true;
            DetailsView1.Fields[6].Visible = false;
            DetailsView1.Fields[7].Visible = false;

        }
        else if ((criteriaType.SelectedValue == "Risk Matrix"))
        {
            DetailsView1.Fields[5].Visible = true;
            DetailsView1.Fields[6].Visible = true;
            DetailsView1.Fields[7].Visible = true;
            DetailsView1.Fields[8].Visible = true;
        }
        else if ((criteriaType.SelectedValue == "Alarm Rationalization"))
        {
            DetailsView1.Fields[5].Visible = true;
            DetailsView1.Fields[6].Visible = true;
            DetailsView1.Fields[7].Visible = true;
            DetailsView1.Fields[8].Visible = true;
        }
        else if (criteriaType.SelectedValue == "Select a Type")
        {
            DetailsView1.Fields[5].Visible = false;
            DetailsView1.Fields[6].Visible = false;
            DetailsView1.Fields[7].Visible = false;
        }
    }
</code>
Answer: make sure you add check if it not postback
<code>   protected void Page_Load(object sender, EventArgs e)
{
       if(!IsPostBack)
       {
        DropDownList criteriaType = (DropDownList)DetailsView1.FindControl("CriteriaType");
        if (criteriaType.SelectedValue == "TMEL Table")
        {
            DetailsView1.Fields[5].Visible = true;
            DetailsView1.Fields[6].Visible = false;
            DetailsView1.Fields[7].Visible = false;

        }
        else if ((criteriaType.SelectedValue == "Risk Matrix"))
        {
            DetailsView1.Fields[5].Visible = true;
            DetailsView1.Fields[6].Visible = true;
            DetailsView1.Fields[7].Visible = true;
            DetailsView1.Fields[8].Visible = true;
        }
        else if ((criteriaType.SelectedValue == "Alarm Rationalization"))
        {
            DetailsView1.Fields[5].Visible = true;
            DetailsView1.Fields[6].Visible = true;
            DetailsView1.Fields[7].Visible = true;
            DetailsView1.Fields[8].Visible = true;
        }
        else if (criteriaType.SelectedValue == "Select a Type")
        {
            DetailsView1.Fields[5].Visible = false;
            DetailsView1.Fields[6].Visible = false;
            DetailsView1.Fields[7].Visible = false;
        }
    }
  }
</code>
Comment: The value of the DropDownList now sticks, but there is no manipulation of the fields. When I click any DDL value, none of the DetailsView1 fields that are supposed to be visible become visible.
Answer: Do you know how the IsPostBack event works and Page state? basically the controls refresh when the IsPostBack event works.
Every time that you update the page from the codebehind, a magic little piece of Javascript is fired which either hits the server through an XMLHTTTP post ( I think ) or a true hard post back hits the server, like a form post. So when the server see this it checks for the IsPostBack flag, it is like an automatic field that is added to every ASP.net page.
Then you check the IsPostBack flag to change the state of things.
If you populate your list box in the IsPostBack=true, it won't appear to be selectable. If you populate your ListBox without it, it will appear that the value keeps changing.
This may be as simple as setting the selcted value in the PostBack.
HTH

DropDownLists Value Resetting


Why is a batsman not permitted to consult with team on DRS?

Question: Australian captain Steven Smith was recently embroiled in controversy after looking towards the dressing room while deciding whether to call for review of his LBW decision.
I gather the rules state that the batsman may only consult with other players on the field, and not with the umpires or his team on the sideline.
Why do the rules forbid the batsman consulting with his team on the sideline? What is the problem that this rule is trying to avoid?
Answer: The Umpire Decision Review System (or DRS) is designed so that teams can review decisions that they feel the umpire may have got wrong. However, there is a catch, in that the team that asks for a review loses the review if the umpire decision stands.
In a test match, each team gets 2 reviews per innings for the first 80 overs, and should they exhaust one or both of them, their quota of 2 reviews is replenished. By providing a limited number of reviews, which are lost when unsuccessful, the teams are forced to judiciously use their reviews.
Suppose a player had a way to know every single time if an umpire's decision is correct or not, would that not be unfair to the other team? Unlike the players on the field, the players and support staff in the dressing room have access to TV replays, which often show Hawk Eye predictions for leg-before dismissals. A batsman can be given a signal from the dressing room, where TV replays are easily available, on whether he should review his decision or not and this would make it easier for the batting team to get the review correct each time. This way, the risk associated with the use of reviews is lost and players can always look to the dressing room to review successfully each time.
Comment: I don't quite see how it would be "unfair" if both teams had access to the same information.
Comment: @PhilipKendall: "the risk associated with the use of reviews is lost and players can always look to the dressing room to review successfully each time." In a way, the DRS questions an umpire's decision and doing so incorrectly results in loss of options to do so. If you can always question an umpire when he's wrong, it severely undermines his authority on the field. The risk factor keeps things balanced.
Comment: May I add that websites like Cricinfo usually produce their own hawk-eye almost instantly.


Universal enveloping algebra vs algebra of continuous functions

Question: I'm a physicist studying quantum groups, but this question is about the usual classical Lie groups (though it is related to the language that is used to describe the deformation to quantum groups, thus the quantum-group tag).
Suppose I have a finite-dimensional Lie algebra $\mathfrak{g}$ (you can assume it to be compact and/or semisimple, whatever suits your needs) and its universal cover Lie group $G$.
I can always make the universal enveloping algebra $U(\mathfrak{g})$ into a Hopf algebra by defining:

The co-product is defined as:
$$\Delta(1) = 1 \otimes 1$$
$$\Delta(t_a) = t_a \otimes 1 + 1 \otimes t_a$$
where $\{t_a\}$ are the set of generators of $\mathfrak{g}$, or, equivalently, the basis of the order-1 subspace of $U(\mathfrak{g})$.
This definition is then extended to the rest of $U(\mathfrak{g})$ through bialgebraic properties.
The trace is defined as
$$ \varepsilon(1) = 1$$
$$ \varepsilon(t_a) = 0$$
and extended to the rest of $U(\mathfrak{g})$ through bialgebraic properties.
The antipode is defined as
$$ S(1) = 1$$
$$ S(t_a) = - t_a $$
and extended to the rest of $U(\mathfrak{g})$ through bialgebraic properties.

Question: please mark the following claims as "true" or "false", and for those which are true, please provide a draft of the proof.

The group-like elements of the Hopf algebra $U(\mathfrak{g})$ (those which satisfy $\Delta(g) = g \otimes g$) form a Lie group, which is exactly the universal cover Lie group $G$.
The Hopf algebra $U(\mathfrak{g})$ is to some extent (which?) equivalent to the commutative algebra of functions over $G$. (I've seen this claim made many times in one form or another, see e.g. here, but I never actually understood this. How can a commutative algebra be equivalent to a noncommutative one? Anyway, looks like this duality is taken as the definition of the quantum group as a deformed Hopf algebra, so I assume it has to be valid in the classical case, too).
Comment: Let me briefly answer your second question. The correct statement is that the (commutative) space of function $C^\infty(G)$ on $G$ embeds into the *dual* $U(\mathfrak{g})^*$ of the universal enveloping algebra $U(\mathfrak{g})$. It is clear from the cocommutativity of $U(\mathfrak{g})$ that taking dual is essential. Roughly, this can be seen by observing that $\mathfrak{g}$ acts on $C^\infty(G)$ as derivation via left invariant vector fields, and $U(\mathfrak{g})$ acts as left invariant differential operators. I guess this is explained in more detail in https://arxiv.org/abs/hep-th/9111043.
Answer: In the meantime, I have posted an answer to the question Duality between universal enveloping algebra and algebras of functions you are citing. So, for the second question I suggest to check the corresponding literature. But the idea is that there is a pairing $\langle\cdot,\cdot\rangle\colon U({\frak g})\otimes O(G)\to\mathbb C$, where $O(G)$ is the algebra generated by the coordinate functions on $G$. If you interpret elements of $\frak g$ as tangent vectors of $G$ at identity, then elements of $U({\frak g})$ indeed act on $O(G)$. Namely by
$$\langle x_1\cdots x_n,f\rangle=\left.{\partial^n\over \partial t_1\cdots\partial t_n}\right|_{t_1,\dots,t_n=0}f(\exp(t_1x_1)\cdots\exp(t_nx_n)),$$
where $x_1,\dots,x_n\in{\frak g}$.
As for the first question, the answer is no. More precisely, the only group-like element in $U({\frak g})$ is the identity. To gain some insight, let's maybe look on the motivation behind group-like elements.
Let $\Gamma$ be a finite discrete group, then the group algebra $\mathbb C\Gamma$ forms a Hopf algebra with respect to the coproduct $\Delta(g)=g\otimes g$. In addition, for any Hopf algebra $A$, it holds that, if $g,h\in A$ are group-like, then also the product $gh$ is group-like. So, the set of all group-like elements forms a group – it somewhat cuts of exactly the part of $A$, which looks like $\mathbb C\Gamma$.
For instance, if $G$ is a Lie group or a compact group, so $O(G)$ forms a Hopf algebra, then the group-like elements of $O(G)$ are exactly all the one-dimensional representations of $G$. We know, that those indeed form a group. By the way, if $G$ is compact and abelian, then all the irreducible representations are one-dimensional and the group they form $\hat G$ is exactly the Pontryagin dual of $G$.
But what you are suggesting is that you would like to discover somehow the group algebra $\mathbb CG$ inside $U({\frak g})$. But in order to do that, you would have to somehow exponentiate the elements of ${\frak g}$ to get the elements of $G$, which is not possible inside $U({\frak g})$ (since you have only finite products and linear combinations here).
There is even a classification statement by Cartier–Gabriel (see Theorem 3.8.2 here) saying that every cocommutative Hopf algebra is of the form $A=U({\frak g})\rtimes \mathbb C\Gamma$. So, the property of being primitive (i.e. $\Delta(x)=1\otimes x+x\otimes 1$) and being group-like (i.e. $\Delta(x)=x\otimes x$) are rather complementary than compatible. Every cocommutative Hopf algebra consists of a part that looks like group algebra $\mathbb C\Gamma$ (generated by group-likes) and of a part that looks like an enveloping algebra $U({\frak g})$ (generated by primitives).
Comment: Thanks for your answer Daniel. What if we take a closure of the enveloping algebra? Surely there are sequences that converge to exponentials
Comment: Well, then it could work, I guess, but I am not sure about the technical details. But, for instance, the definition of the quantum deformation $U_q({\frak sl}_2)$ involves the element $K=e^H$, which is then indeed group-like.


With vocal or guitar pedals, Is there a difference between one side of a stereo signal (with no panning) vs. a mono signal?

Question: I wanted to try to get two mono XLR signals out of my TC Helicon "Play Electric" Vocal Processor, (which only has the option of ONE mono signal, or TWO stereo signals) so this led to a question which is not explained in the owners manual.
After doing a little research I think the answer may lie in whether the "stereo" signal is just "stereo" or "true stereo" and which of these exists in the outputs of guitar pedals, or in this case a XLR vocal mic pedal.
So here's my question:  Is there any difference between 1 side of a "stereo signal" (compared to a mono signal), if you do not run the L+R stereo signals into a mixer and "PAN" them to either side?  In other words (I was hoping to have 2 mono signals, but instead) if I take the 2 STEREO XLR signals that ARE available (for my Mic outputs) on the back of my Play Electric pedal, and if I do NOT use a mixer to pan them in any way.  Then is there any audible difference between each side of those 2 L+R "stereo" signals, and an actual "Mono" signal?
Comment: I have tried to make this question readable, and get rid of all but the core question - please don't ask multiple questions in one post.
Answer: As I read it, the question is, is the L or R signal of a stereo source the same as a mono signal.
No. If they were the same, you'd have double-mono. But carry on reading anyway.
The TC Helicon "Play Electric" Vocal Processor has Left and Right Stereo outputs at the back. Often, devices which output in stereo (e.g Keyboards, or some guitar pedals) also supply a mono output if only one of the connectors is plugged in. That doesn't seem to be the case with the Helicon, but you shouldn't see a problem unless you're using an effect that needs stereo output (e.g a Ping-pong delay). For a looper, you won't have an issue - just use one output cable, and you'll be fine. There will be a difference between L and R, but it'll be so minor, you can ignore it.
In live performance, it's actually pretty rare to see a stereo feed - we have enough issues with speaker delay times in a big room, so we don't want to worry about left and right as well.
To clear up the confusion of stereo and panning; Stereo will be the signal from the performer, generally a keyboard player. We can either convert that to mono (they'll never notice :p ), or we can let their left signal go left, and their right signal go right. If a performer sends us a mono signal (much more common) - e.g a guitarist - we'll pan their signal to the left or right of the stage, usually to match where they're physically standing on stage. Doing that gives some perception of width in the sound stage.


How can I get data from google url in flutter web

Question: I use package [http]https://pub.dev/packages/http to get data from this url https://trends.google.com.vn/trends/api/stories/VN_lnk_GMomYwEwAAA_GM_vi?hl=en-US&tz=-420
import 'package:http/http.dart' as http;

String url = "https://trends.google.com.vn/trends/api/stories/VN_lnk_GMomYwEwAAA_GM_vi?hl=en-US&tz=-420";
http.Response response = await http.get(url);

Then it throw error:
Running with unsound null safety
For more information see https://dart.dev/null-safety/unsound-null-safety
Debug service listening on ws://127.0.0.1:54796/m1rEikri7V4=/ws
/
/home
Error: DioError [DioErrorType.RESPONSE]: XMLHttpRequest error.
    C:/b/s/w/ir/cache/builder/src/out/host_debug/dart-sdk/lib/_internal/js_dev_runtime/patch/core_patch.dart 906:28                get current
packages/dio/src/adapters/browser_adapter.dart 79:20                                                                           <fn>
C:/b/s/w/ir/cache/builder/src/out/host_debug/dart-sdk/lib/async/zone.dart 1446:54                                              runUnary
C:/b/s/w/ir/cache/builder/src/out/host_debug/dart-sdk/lib/async/future_impl.dart 150:18                                        handleValue
C:/b/s/w/ir/cache/builder/src/out/host_debug/dart-sdk/lib/async/future_impl.dart 703:44                                        handleValueCallback
C:/b/s/w/ir/cache/builder/src/out/host_debug/dart-sdk/lib/async/future_impl.dart 732:32                                        _propagateToListeners
C:/b/s/w/ir/cache/builder/src/out/host_debug/dart-sdk/lib/async/future_impl.dart 526:7                                         [_complete]
C:/b/s/w/ir/cache/builder/src/out/host_debug/dart-sdk/lib/async/stream_pipe.dart 61:11                                         _cancelAndValue
C:/b/s/w/ir/cache/builder/src/out/host_debug/dart-sdk/lib/async/stream.dart 1302:7                                             <fn>
C:/b/s/w/ir/cache/builder/src/out/host_debug/dart-sdk/lib/_internal/js_dev_runtime/private/ddc_runtime/operations.dart 324:14  _checkAndCall
C:/b/s/w/ir/cache/builder/src/out/host_debug/dart-sdk/lib/_internal/js_dev_runtime/private/ddc_runtime/operations.dart 329:39  dcall
C:/b/s/w/ir/cache/builder/src/out/host_debug/dart-sdk/lib/html/dart2js/html_dart2js.dart 37312:58                              <fn>

    at Object.createErrorWithStack (http://localhost:54668/dart_sdk.js:4368:12)
    at Object._rethrow (http://localhost:54668/dart_sdk.js:38289:16)
    at async._AsyncCallbackEntry.new.callback (http://localhost:54668/dart_sdk.js:38283:13)
    at Object._microtaskLoop (http://localhost:54668/dart_sdk.js:38115:13)
    at _startMicrotaskLoop (http://localhost:54668/dart_sdk.js:38121:13)
    at http://localhost:54668/dart_sdk.js:33618:9

I tested with other work well. How can I get data from this url ?
Comment: Could you paste the exact error message you get please.
Comment: I have already updated error message.
Comment: You get an error from the dio package while you said that you are using the http package ?
Comment: They are the same, dio package is wraped http
Answer: XMLHttpRequest error normally means your Cors policy is not configured correctly.
See here
Comment: Do you try to request with my url?


UI-Router and Angularjs: main content isn't being displayed

Question: index.html:

app.js:
.state('root', {
    url: '',
    abstract: true,
    views: {
        'header': {
            templateUrl: 'views/header.html',
            controller: 'HeaderCtrl'
        },
        'footer': {
            templateUrl: 'views/footer.html'
        }
    },
    data: {
        requiresLogin: true
    }
}).state('root.home', {
    url: '/',
    views: {
        '@': {
            templateUrl: 'views/home.html',
            controller: 'HomeCtrl'
        }
    },
    data: {
        requiresLogin: true
    }
})

So I have a header and footer that are properly being called and shown on the screen but for some reason, my home.html isn't being shown. For now, the home.html just includes a h1 heading of "Home" in it. It seems like space is being created for the content but it's just not showing it.
Answer: Please try this
.state('root', {
    url: '',
    abstract: true,
    views: {
        'header': {
            templateUrl: 'views/header.html',
            controller: 'HeaderCtrl'
        },
        'main': {
            template: '
This is default main content placeholder
'
         },
        'footer': {
            templateUrl: 'views/footer.html'
        }
    },
    data: {
        requiresLogin: true
    }
}).state('root.home', {
    url: '/',
    views: {
        'main@': {
            templateUrl: 'views/home.html',
            controller: 'HomeCtrl'
        }
    },
    data: {
        requiresLogin: true
    }
})

and in index.html:

Comment: I tried that, still doesn't work... I can't figure out what the issue is.
Comment: Apparently it did - the issue was that my header has a sidebar which blocks off my main content...


A discrete metric space is complete

Question: We can read here that every discrete metric space (where the topology is the same as the discrete topology, i.e. where all the singletons are open) is complete, but an example bothers me because I don't see where I am wrong :
The space $(\{\frac{1}{n}\,;\,n\in\mathbb{N^*}\},d)$ where $d(x,y)=|y-x|$ is discrete because you have for all $n\in\mathbb{N}^*$ that
$$B\Big(\frac{1}{n},\varepsilon_n\Big)\cap S=\Big\{\frac{1}{n}\Big\},\text{ where }\varepsilon_n=\frac{1}{2n(n+1)}\text{ for example.}$$
But this space is not complete, as the sequence $(\frac{1}{n})_{n\geq 1}$ is Cauchy but doesn't converge in $S.$ My questions are the following :

Did I tell something wrong in my example ?
Is the property only true for uniformly discrete metric spaces, where we don't allow $\varepsilon_n$ to become as little as it wants as in this example ?

Thank you for your help !
Comment: Your example is a metric space where the metric induces the discrete topology. But it is not a space that is equipped with the discrete metric. -- See the definition of **discrete metric space** on the linked WP page
Comment: @HagenvonEitzen : So I can tell that $S$ is a discrete space because the topology on $S$ is the discrete topology, but not a discrete metric space because $d$ is not the discrete metric ? Thank you for this clarification !
Comment: Indeed. If you endow the same space with a different (namely the discrete) metric from the inherited metric, you arrive at a space with the same topology, but with different state of completeness. This example is great to visualize that completeness is *not* a *topological* property.
Comment: @HagenvonEitzen : Thank you for that explanation. If you want, you can copy your two comments and make an answer with them, as they totally satisfied me.
Answer: We have to be careful and distinguish between
a) a metric space that happens to induce the discrete topology (i.e., where each singleton set is open, such as in  your example) and
b) a discrete metric space, that is a set endowed with the discrete metric $$d(x,y)=\begin{cases}0&x=y\\1&x\ne y.\end{cases}$$
Of course, the topology induced by the discrete metric is also the discrete topology, but two metrics defining the same topology need not be equivalent. Your very example is excellent to remind us that some properties of metric spaces (such as completeness) are really properties of the metric space, not of the induced topology: The set $\{\,\frac1n:n\in\Bbb N\,\}$ endowed with the metric inherited from $\Bbb R$ is discrete, but is not a discrete metric space; and it is not complete with respect to this metric. Endowed with the discrete metric, however, it becomes complete (without changing its topology): In a discrete metric space every Cauchy sequence is eventually constant, hence convergent.

We might say that discrete metric space should be understood as being "linguistiucally parenthesized" as (discrete metric) space and not as discrete (metric space). I am not sure if it would we ok to write discrete, metric space for a metric space with discrete topology; and even if so, I'd rather be more explicit about the distinction than hiding it in the presence or absence of a comma. Thus I'd prefer to say "metric space with discrete topology" and "space endowed with the discrete metric" if the distinction is needed.
The underlying problem may be that the associative law does not hold for natural languages. The standard example of the German language for this is Mädchenhandelsschule which is (of course) intended to mean Mädchen+(handels+schule) ("business school for girls) and not (Mädchen+handels)+schule ("school where you learn girl trafficking")

A discrete metric space is complete


Some pages hide content unless "Read more" is clicked

Question: If I have multiple pages on Drupal, some show the full page, and others say "Read more" and will only show the whole page when it is clicked. It doesn't seem to have anything to do with the size of the content of the page or how long it is. What's up with that?
Answer: What you're probably looking at is a "View". This view is probably showing a list of "Content" (nodes).
Now each node is probably being set to render in "Teaser" view mode. But since some of your node types (article for example) doesn't have a "teaser" view mode configured, it shows the "Full" (or "Default") view mode, which renders the "whole" thing.
What you need to do is find the View Mode that your content listing View is using, the Node Type of the content that's showing up as Full, (for example 'Basic Page'), then go to:
Structure > Content Types > [Content Type you want to configure] > Manage Display
And configure the view mode that your View is using to display the Read More link, show the body text as "Summary or Trimmed" etc.


create module that load index.php

Question: I have a php code written in index.php that contain a form with method post.
It also read from an external database and fill a table.
To load this form I created a .module file with 2 functions _menu and _block, but I am not able to load the form (index.php)
I need to load the form and to open it in the main content of the drupal page
i used :
header("location
drupal_goto(
$external_link

but nothing is going right and it open in new blank page not in the main content like i want.
please it is urgent
any help
Answer: The Drupal way
In Drupal we create similar form like this:
Create a custom module

Create a file sites/all/modules/own/form_test/form_test.info with this in it:
name = form_test
description = form_test
core = 7.x
package = Own
Create a file sites/all/modules/own/form_test/form_test.module

(start it with <?php tag, but don't add ending ?> tag)
Write these functions in your module:
function form_test_menu() {
  $items['formtest'] = array(
    'title' => 'Form Test',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('form_test_form'),
    'access callback' => TRUE,
    );
  return $items;
}

An explanation
form_test_menu
creates a menu item in your navigation menu so we can have a place where to show our custom form. You can think that menu address referring to a page yoursite/formtest.
title
Title of the page.
page callback
Calls a function drupal_get_form which returns a render array for drupal_render().
page arguments
Here we pass our custom render array (which form_test_form returns) as an argument for drupal_get_form.
access callback
We define it TRUE so that everyone can access this page.
(Rendering means turning a structured array into HTML.)
function form_test_form($form,&$form_submit) {
  $form['firstname'] = array(
    '#title' => t('Firstname'),
    '#type' => 'textfield',
    '#required' => TRUE,
  );
  $form['lastname'] = array(
    '#title' => t('Lastname'),
    '#type' => 'textfield',
  );
  $form['submit'] = array(
    '#value' => 'Submit',
    '#type' => 'submit',
    );
  return $form;
}

An explanation
So we use render arrays to describe a form in drupal.
When you use a function to return a render array for drupal_get_form, there are two default parameters that are in use:
$form   Holds the form array items we define inside the function when this function is called again.
&$form_submit   This parameter holds various data items like the values you pass when you submit the form.
(Ampersand & means that this is a reference to a variable, so if we change this variable in this function, changes will show in the parent function too.)
Form items are added as arrays to the $form variable. Hash (#) sign refers to an attribute of the item.
Enable the module in admin/modules
Flush the caches
Form can be seen in yoursite/formtest, but it doesn't do anything yet.
OR
more links are :
Drupal 7 - How to Make a Simple Module with a Form and Menu Link
Ten Step-by-Step Code Samples for Learning Form API
Comment: so i can not load my form i need to re-program the form using drupal function
Comment: @hibanajjar Yes. Drupal implements pretty good form processing with advanced anti-tamper solutions and simply won't cooperate if you ignore them. You can make it, of course, but it's bad idea to try. You won't have your homemade solution as thoroughly tested as Drupal's one is.

create module that load index.php


Find the area below $y=\sqrt{4-x^2}$ and above the x-axis between $x=0$ and $x=2$

Question: I'm trying to figure out how to go about this, but I'm not entirely sure. Is there a specific way to find the area under a curve or line (and strictly above the x-axis) before doing Riemann sums?
Answer: It is quarter of the circle whose radius is $2$ and center origin, so the answer is $\pi$.

You can also substitute $x=2\sin \theta\;(0 \le \theta \le \frac{\pi}{2})$, then
\begin{align}
\int_0^2 \sqrt{4-x^2}dx &= \int_0^{\frac{\pi}{2}} 2\cos \theta\sqrt{4-4\sin^2\theta}  d\theta\\
&=\int_0^{\frac{\pi}{2}} 4\cos^2\theta d\theta\\
&=\int_0^{\frac{\pi}{2}} 4 \frac{1+\cos 2\theta}{2}d\theta\\
&=\left[2\left(\theta+\frac{1}{2}\sin2\theta\right)\right]_0^{\frac{\pi}{2}}\\
&=\pi
\end{align}
Comment: That sort of makes sense, but is there any algebra to show that?
Comment: @user10984587 I'll edit my post to show it. Wait a minute, please :)
Comment: I'll take a stab and say you use the integral and the integral of $\sqrt{4-x^2}$ at $x=2$ is pi + constant?
Comment: @user10984587 I can't understand what "the integral of $\sqrt{4-x^2}$ at $x=2$" is.
Comment: I meant what you just showed. Thanks for the explanation!
Answer: substitute $$x=2\sin { \theta  } \\ dx=2\cos { \theta d\theta  } $$ and change bounders so that:
$$\int _{ 0 }^{ 2 }{ \sqrt { 4-{ x }^{ 2 } } dx } =\int _{ 0 }^{ \frac { \pi  }{ 2 }  }{ \sqrt { 4-4\sin ^{ 2 }{ \theta  }  }  } 2\cos { \theta d\theta  } =4\int _{ 0 }^{ \frac { \pi  }{ 2 }  }{ \cos ^{ 2 }{ \theta  } d\theta = } 2\int _{ 0 }^{ \frac { \pi  }{ 2 }  }{ \left( 1+\cos { 2\theta  }  \right) d\theta = } 2{ \left( \theta +\frac { \sin { 2\theta  }  }{ 2 }  \right)  }_{ 0 }^{ \frac { \pi  }{ 2 }  }=\pi \\ \\ $$


Podio Api:use java lib create space success,but in my podio board page can't find the new wordspace

Question: when use java lib to create a space,it repsponse success,but in my podio board page can't find the new wordspace. and I use java lib to create app,it samely can't find in my podio board page.
it seems some thing not working.
by the way,my account is free.
the java client print log
not find the new space
Comment: the java client log as flow:[Link](https://p5.zdusercontent.com/attachment/1544/eU6Pa39Cfk2Ua173BcjNYcTd3?token=eyJhbGciOiJkaXIiLCJlbmMiOiJBMTI4Q0JDLUhTMjU2In0..OypMH3krH-xJc7tZnbtVcg.ZCKsef5btFhphIfb7y0cLdaQZhhQ7anJI0BbjpsvrVKsq2ZzLLth7bQ1tdGpgCV7UXn0uiFYoPmmVExlDWMVL43JlsF8MuyiY1-oEcxl11CDYaEeGz8lI4H50a8YB4yrAXt9qdfmj2AVcT8jXcL6-2qpzJX9pRZt3LyDKw8qeyQ00YoFZbsv-RlBNhy0U04h2rZAEL6Qj-iuEV-s0Bnar--BACWqmdhh-N8vybxsHHrPrLZHZ0UTzHYdxqNyvngKLyxUOpgmuy0sssMWVhiIXn_uyQ3GuyO1fjXRWd8QVXs.t3I3-4nNanXn-qkWkXWohA)
Comment: All of those images are the same. Have you tried `GET /space/org/{org_id}` ?
Answer: yes,it have bean solved,
beacuse the java client lib test case is debug mode,
after modify the param,it works.
api = new ResourceFactory("api.podio.com", "files.podio.com", 443, true, false, CLIENT_CREDENTIALS, USER_CREDENTIALS_MAP.get(userId));