Lista de objetos em Java

Question: Qual a diferença entre usar:
List<NomeClasse> lista;

E usar:
List<NomeClasse> lista = new ArrayList<Classe>();

Já vi das duas formas em projetos diferentes e aparentemente as duas trazem o mesmo resultado, por isso fiquei na dúvida se tem algum jeito que é o certo ou que é considerado boa prática ou se tanto faz a forma de listar.
Answer: As duas não trazem o mesmo resultado nem de perto.
A primeira linha está declarando a variável e mais nada, ou seja, a variável valerá o valor padrão dela que é nulo para este tipo, então quando for acessar dará erro, a não ser que inicialize depois, mas aí teríamos que observar o resto do código, e não o que foi postado.
A segunda linha, além de declarar a variável, está inicializando uma instância da classe ArrayList e colocando um valor para ela com a atribuição, e assim quando for usar encontrará um objeto e não dará erro. No primeiro momento, se não tiver outras partes do código, a lista estará vazia se acessar logo em seguida.
Tipos por referência sempre tem como valor padrão o nulo, então se não vai inicializar pouco depois não existe razão para deixar sem inicialização de forma mais adequada.
Por que vai inicializar depois? Se não tiver uma explicação não faça isso, faça tudo o que precisa o mais rápido possível e evitar problemas. Raramente é interessante inicializar depois, e quase sempre que ver isso é estilo ruim. Mas pode ter algum caso útil.
nomeObjeto é algo estranhíssimo aí, então se pegou de algum código jogue ele fora porque está te ensinando errado. Aí deveria ter o nome de uma classe (geralmente começando em maiúsculo) e não algo como que soa ser o nome de uma variável.
Boa prática é a muleta de quem não aprendeu como funciona o que está usando. Quando aprende o mecanismo, a motivação, o porquê de fazer cada coisa, no contexto específico, deixa de ser boa prática e passa ser conhecimento. Conhecimento só existe quando há justificativa. Boa prática é a crença em alguém que não conhece seu cenário concreto.

Nada indica isso ter alguma relação com DTO, parece até estranho, mas pode ser só porque está fora de contexto.
Coloquei no GitHub para referência futura.

Lista de objetos em Java


Invoke custom JS function in AJAX callback?

Question: Is it possible to invoke a custom JS function in an AJAX callback?
function MY_MODULE_ajax_callback() {
  // Define a new array to hold our AJAX commands.
  $ajax_commands = array();

  // Create a new AJAX command that replaces the #page text with our own text.
  $ajax_commands[] = [CUSTOM JS FUNCTION]

  // Return our commandS
  return array('#type' => 'ajax','#commands' => $commands);
}

Comment: Yes, it is. Or at least it should be possible. Any particular problems?
Comment: this seems to be a duplicate of http://drupal.stackexchange.com/questions/18867/how-can-i-trigger-a-javascript-function-when-a-drupal-ajax-call-is-complete
Answer: Yes, it is.
Code sample:
$commands = array();
$commands[] = array(
    'command' => 'your_js_callback', // the name of your javascript callback
    'value1'  => 'My first value',
    'value2'  => 'My second value',
);

JS Code:
(function($, Drupal) {
    Drupal.ajax.prototype.commands.your_js_callback = function(ajax, response, status) {
        alert(response.value1);
        alert(response.value2);
    }
})(jQuery, Drupal);

Comment: this is a good example too
Answer: You can't run an arbitrary script, but if you can wrap your JS functionality in a jQuery plugin you can use ajax_command_invoke to get the same effect, e.g.
$selector = 'body';
$method = 'myJqueryPlugin';
$args = array('arg1', 'arg2');

$ajax_commands[] = ajax_command_invoke($selector, $method, $args);

When that comes out in the front end it'll execute something equivalent to
$('body').myJqueryPlugin('arg1', 'arg2');


Why is argparse capitalizing options?

Question: In the following:
$ python df.py -h
optional arguments:
  -h, --help            show this help message and exit
  -v VERBOSE, --verbose VERBOSE
                        Print debug info on script run.

Why does python capitalize the VERBOSE arg and why does it print it twice? How can I get it to show like the help line, where it has -h for the short option and --help for the long option? I am initializing it as follows:
my_parser.add_argument('-v', '--verbose',     required=False, help='Print debug info on script run.')

Comment: Try `action='store_true'`
Comment: @IsmailBadawi thanks, can you link to the place in the docs where it shows that?
Comment: it shows two times because this shows that it needs agument and you should run it `df.py --verbose some_value`. If you want only to keep `True/False` then you should use option `action='store_true'`
Comment: see [action](https://docs.python.org/3/library/argparse.html#action) in `argparse` doc.
Answer: The capital VERBOSE represents where the user is supposed to provide a value for the option, because you've declared this option as one that takes a value.
You probably didn't want this option to take a value. You probably wanted action='store_true', which would store True if the option is provided and False otherwise.

Why is argparse capitalizing options?


Debugging Eclipse performance problems

Question: To debug Eclipse performance problems, I created this .options file:
org.eclipse.jdt.ui/debug=true
org.eclipse.jdt.launching/debug = true
org.eclipse.jdt.launching/debug/classpath/jreContainer = true

# trace generation of type constraints and create toString info for debugging
org.eclipse.jdt.ui/debug/TypeConstraints=false

# timing output for code assist
org.eclipse.jdt.ui/debug/ResultCollector=false

org.eclipse.jdt.debug/debug=false
org.eclipse.jdt.debug/debug/jdiEvents=false
org.eclipse.jdt.debug/debug/jdiRequestTimes=false
org.eclipse.jdt.debug/debug/astEvaluations=false
org.eclipse.jdt.debug/debug/astEvaluations/callingThreads=false

# Turn on debug tracing for org.eclipse.jdt.core plugin
org.eclipse.jdt.core/debug=true

# Reports java  builder activity : nature of build, built state reading, indictment process
org.eclipse.jdt.core/debug/builder=true

# Reports java builder stats
org.eclipse.jdt.core/debug/builder/stats=true

# Reports compiler activity
org.eclipse.jdt.core/debug/compiler=true

# Turn on debugging for the org.eclipse.core.resources plugin.
org.eclipse.core.resources/debug=true

# Reports the start and end of all builder invocations
org.eclipse.core.resources/build/invoking=true

# Reports the start and end of build delta calculations
org.eclipse.core.resources/build/delta=true

# For incremental builds, displays which builder is being run and
because of changes in which project.
org.eclipse.core.resources/build/needbuild=true

# Prints a stack trace every time an operation finishes that requires a
build
org.eclipse.core.resources/build/needbuildstack=true

The file is in the same folder as eclipse.ini.
When I open the about dialog, I can see the option -debug in the eclipse.commands variable:
...
-product
org.eclipse.epp.package.jee.product
-console
-consoleLog
-debug
$HOME/tools/eclipse/kepler-SR2
-data
$HOME/workspace
-vm
$HOME/tools/java/jdk1.8.0_25/bin/java
...

(I replaced my home folder with $HOME for privacy reasons).
But I don't see any trace output in the console where I started Eclipse. I can see output from the m2e:
2015-01-19 17:04:46,892 [Worker-12] INFO  o.e.m.c.i.embedder.EclipseLogger - Using 'UTF-8' encoding to copy filtered resources.
2015-01-19 17:04:46,892 [Worker-12] INFO  o.e.m.c.i.embedder.EclipseLogger - Copying 1 resource

When I press Enter, I get an OSGi prompt.
But no trace of a trace output. What did I miss?
Comment: Are you specifying -debug on the command line? That should list on the console where the various configuration files, including the debug file, are being read from.
Comment: @greg-449: That might be a clue. I see `Debug options:` and `file:$HOME/tools/eclipse/kepler-SR2 loaded`. I'd expect `.../kepler-SR2/.options` here; `kepler-SR2` is a folder.
Answer: When starting Eclipse with -debug, you can see which configuration files it loads during startup. The output looks like this:
...
Install location:
    file:$HOME/tools/eclipse/kepler-SR2/
Configuration file:
    file:$HOME/tools/eclipse/kepler-SR2/configuration/config.ini loaded
Configuration location:
    file:$HOME/tools/eclipse/kepler-SR2/configuration/
Framework located:
    file:$HOME/tools/eclipse/kepler-SR2/plugins/org.eclipse.osgi_3.9.1.v20140110-1610.jar
Framework classpath:
    file:$HOME/tools/eclipse/kepler-SR2/plugins/org.eclipse.osgi_3.9.1.v20140110-1610.jar
Splash location:
    $HOME/tools/eclipse/kepler-SR2//plugins/org.eclipse.platform_4.3.2.v20140221-1700/splash.bmp
Debug options:
    file:$HOME/tools/eclipse/kepler-SR2/.options loaded
Time to load bundles: 5
...

Note the last path which gives the debug options. In the case above, this was:
Debug options:
    file:$HOME/tools/eclipse/kepler-SR2 loaded

which is a folder ... Why would Eclipse do this? Because it was told so:
-debug
$HOME/tools/eclipse/kepler-SR2
-data

Notice the path between -debug and -data? Get rid of that and it will work (or specify the path to a real options file).
Comment: You should accept your own answer as correct. I was useful to me and possibly others.

Debugging Eclipse performance problems


What is the difference between mutable array & immutable array in ember-data?

Question: I've been running into issues while dealing with ember-data related to immutable arrays like for example "Uncaught Error: The result of a server query is immutable. " This is what I got when i tried to apply removeObjects() method on a filtered list of array.
So, I'd like to know the difference & if possible how to convert them to the other
Answer: An immutable array just means that it can't be altered directly (as opposed to a mutable array which can be changed).
According to Ember Data documentation, deleting records should be done like this:

To delete a record, call its deleteRecord() method:
var person = App.store.find(App.Person, 1);
person.deleteRecord();

The record will not be deleted in the persistence layer until the store's
  commit() method is called. However, deleted records will immediately
  be removed from its ModelArray and associations.

Source: https://github.com/emberjs/data#deleting-records
If that's not helpful, could you write a jsfiddle?
Comment: deleteRecord() should alter the client. (at least in the sense that all of ember is inherently on the client) Your view's content array is bound the Store, which is what we are altering by using person.deleteRecord(). removeObjects() would only be useful if you had created the array yourself (ie: not from some data-source that needs to be synced whenever something changes in ember)
Comment: yes this works, thanks :) but when should we use removeObjects() then?
Comment: But I don't think deleteRecord() alters the collection on the client , right?
Comment: Hope I've answered your question. Could you mark that as the answer?
Comment: thanks,I think i missed the binding which is why my view was not being updated...just signed in today(sat n sunday off)


Fazer uma procedure SQL Server recebendo string com caracter especial e obtendo apenas os números

Question: Olá, estou com um sistema desenvolvido em ASP Clássico, no qual eu seleciono até 5 horários em uma tela.
Esses horários são enviados à outra página via querystring, porém o formato que vem é seguido por uma exclamação. Exemplo 7!10!19!
O que preciso é pegar esses códigos (7, 10 e 19) e usá-los para inserir um registro em uma tabela SQL Server com cada um deles.
Estou tentando fazer isso via procedure, pois meus conhecimentos em ASP são muuuuito pequenos.
Alguém poderia me dar uma luz?
Answer: Crie primeiramente uma função para dividir sua string em valores separados:
CREATE FUNCTION dbo.splitstring ( @separador CHAR, @stringToSplit VARCHAR(MAX) )
  RETURNS
  @returnList TABLE ([Name] [nvarchar] (500))
AS
BEGIN

  DECLARE @name NVARCHAR(255)
  DECLARE @pos INT

  WHILE CHARINDEX(@separador, @stringToSplit) > 0
    BEGIN
    SELECT @pos  = CHARINDEX(@separador, @stringToSplit)
    SELECT @name = SUBSTRING(@stringToSplit, 1, @pos-1)

    INSERT INTO @returnList
    SELECT @name

    SELECT @stringToSplit = SUBSTRING(@stringToSplit, @pos+1, LEN(@stringToSplit)-@pos)
 END

 INSERT INTO @returnList
 SELECT @stringToSplit

 RETURN
END

Chame a função criada passando uma string contendo os valores separados por "!":
SELECT * FROM dbo.splitstring('!', '91!12!65!78!56!789')

O resultado para essa consulta será esse abaixo:

Para inserir os valores em sua outra tabela, basta adaptar o seguinte comando de acordo com as colunas que você tem em sua tabela:
INSERT INTO TabelaDeDestino SELECT Name FROM dbo.splitstring('!', '91!12!65!78!56!789')

Essa é uma adaptação da resposta em inglês https://stackoverflow.com/questions/10914576/t-sql-split-string
Comment: Muito obrigada Ulysses! Já me ajuda muuuuito!!!!! :D


Post a string to restful webservice in C#

Question: I am provided a webservice url similar to:
http://ericdev35:7280/persons/persons/
and a username and password.
I want to make a post call on this web service from WPF application.
The data to be sent to the service is the first name and last name of a person in the format:
"fname=Abc&lname=Xyz"
How can I make a call for this in C#?
Here is the code that I have tried:
<code>        HttpWebRequest httpWebRequest = (HttpWebRequest) WebRequest.Create("http://ericdev35:7280/persons/persons/");
        httpWebRequest.Method = "POST";
        httpWebRequest.ContentType = "application/json";
        httpWebRequest.Credentials = new NetworkCredential(username, password);
        string data = "fname=Abc&lname=Xyz";
        StreamWriter writer = new StreamWriter(httpWebRequest.GetRequestStream());
        writer.Write(data);
        writer.Close();
</code>
This does not give me any error but I cannot see the data that I have posted. Is there anything that needs to be corrected?
Is the Content Type correct?
Comment: Your data is not in valid Json Format!
"{"fname":"Abc", "lname":"Xyz"}" would be valid...
Comment: https://stackoverflow.com/a/4015346/588734
Answer: This Method posts json.
After that it gets the response and deserialize the Json Object.
<code>private static string PostJson<T1>(string p_url, string p_json, string p_method, out T1 p_target)
{
    var httpWebRequest = (HttpWebRequest)WebRequest.Create(p_url);
    httpWebRequest.UseDefaultCredentials = true;
    httpWebRequest.ContentType = "application/json";
    httpWebRequest.Method = p_method;

    using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
    {
        streamWriter.Write(p_json);
        streamWriter.Flush();
        streamWriter.Close();
    }
    HttpWebResponse httpResponse;
    try
    {
        httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
    }
    catch (WebException ex)
    {
        httpResponse = ex.Response as HttpWebResponse;
    }

    using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
    {
        var a_result = streamReader.ReadToEnd();

        //If you dont need a Json object delete anything behind here
        try
        {
            p_target = JsonConvert.DeserializeObject<T1>(a_result);
        }
        catch { p_target = default(T1); }
        return a_result;
    }
}
</code>
Comment: How should I pass my data as json. Is the following statement correct ?
string data = "fname=Abc&lname=Xyz";
Comment: string data =  "{\"fname\":\"Abc\", \"lname\":\"Xyz\"}";
Comment: I passed it as:
string data = "{fname:" + "\"" + "Abc" + "\"" + ",lname:" + "\"" + "Xyz" + "\"}";
The response that I get is 403 Forbidden error
Comment: Did you try to look at the full response? It may contain a more detailed error description.
Comment: httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
This line gives a 403 forbidden exception. I tried catching this WebException and the status property of the exception says "Protocol Error"
Comment: The `try catch` part of my methode provides you the complete response if the status is not `Ok`.
Comment: You could try http and https. Depending on the configuration of the webservice one is may not accepted.


leaflet pattern . trying to add a path pattern not working

Question: based on the documentation here leaflet.pattern
i can create my custom patterns ,here is an example
I have done the same steps  as mentioned in the example for our custom pattern . i have only changed the d element (related to svg path) .
but things did not went as i expected .
any help would be thankful .
Here is the code :
   var mapCenter = new L.LatLng(50.68, -120.34);

    var baseLayer = new L.TileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
        maxZoom: 18,
        attribution: '© OpenStreetMap contributors'
    });

    var _map = new L.Map("map", {
        center: mapCenter,
        zoom: 14,
        layers: [baseLayer]
    });

    var shape = new L.PatternPath({
        d: 'M10 0 L7 20 L25 20 Z',
        fill: true
    });

    var pattern = new L.Pattern({width:50, height:50});
    pattern.addShape(shape);
    pattern.addTo(_map);

    var circle = new L.Circle(mapCenter, 400.0, {
        fillPattern: pattern,
        fillOpacity: 1.0});
    circle.addTo(_map);

I have only changed ( d: 'M10 0 L7 20 L25 20 Z')
to ('m206.38471,149.50017a1.52869,1.64413 0 0 1 3.0574,0a1.52869,1.64413 0 0 1 3.05738,0a1.52869,1.64413 0 0 1 3.0574,0a1.52869,1.64413 0 0 1 3.0574,0a1.52869,1.64413 0 0 1 3.05738,0a1.52869,1.64413 0 0 1 3.0574,0a1.52869,1.64413 0 0 1 3.05738,0a1.52869,1.64413 0 0 1 3.0574,0a1.52869,1.64413 0 0 1 3.0574,0a1.52869,1.64413 0 0 1 3.05738,0a1.52869,1.64413 0 0 1 3.0574,0a1.52869,1.64413 0 0 1 3.0574,0a1.52869,1.64413 0 0 1 3.05738,0a1.52869,1.64413 0 0 1 3.0574,0a1.52869,1.64413 0 0 1 3.05738,0a1.52869,1.64413 0 0 1 3.0574,0a1.52869,1.64413 0 0 1 3.0574,0a1.52869,1.64413 0 0 1 3.05738,0a1.52869,1.64413 0 0 1 3.0574,0a1.52869,1.64413 0 0 1 3.0574,0a1.52869,1.64413 0 0 1 3.05738,0a1.52869,1.64413 0 0 1 3.0574,0a1.52869,1.64413 0 0 1 3.05738,0a1.52869,1.64413 0 0 1 3.0574,0a1.52869,1.64413 0 0 1 3.0574,0a1.52869,1.64413 0 0 1 0,3.28828a1.52869,1.64413 0 0 1 0,3.28827a1.52869,1.64413 0 0 1 0,3.28828a1.52869,1.64413 0 0 1 0,3.28828a1.52869,1.64413 0 0 1 0,3.28827a1.52869,1.64413 0 0 1 0,3.28828a1.52869,1.64413 0 0 1 0,3.28827a1.52869,1.64413 0 0 1 0,3.28828a1.52869,1.64413 0 0 1 0,3.28828a1.52869,1.64413 0 0 1 0,3.28827a1.52869,1.64413 0 0 1 0,3.28828a1.52869,1.64413 0 0 1 0,3.28828a1.52869,1.64413 0 0 1 0,3.28827a1.52869,1.64413 0 0 1 0,3.28828a1.52869,1.64413 0 0 1 0,3.28827a1.52869,1.64413 0 0 1 0,3.28828a1.52869,1.64413 0 0 1 0,3.28828a1.52869,1.64413 0 0 1 0,3.28827a1.52869,1.64413 0 0 1 -3.0574,0a1.52869,1.64413 0 0 1 -3.0574,0a1.52869,1.64413 0 0 1 -3.05738,0a1.52869,1.64413 0 0 1 -3.0574,0a1.52869,1.64413 0 0 1 -3.05738,0a1.52869,1.64413 0 0 1 -3.0574,0a1.52869,1.64413 0 0 1 -3.0574,0a1.52869,1.64413 0 0 1 -3.05738,0a1.52869,1.64413 0 0 1 -3.0574,0a1.52869,1.64413 0 0 1 -3.0574,0a1.52869,1.64413 0 0 1 -3.05738,0a1.52869,1.64413 0 0 1 -3.0574,0a1.52869,1.64413 0 0 1 -3.05738,0a1.52869,1.64413 0 0 1 -3.0574,0a1.52869,1.64413 0 0 1 -3.0574,0a1.52869,1.64413 0 0 1 -3.05738,0a1.52869,1.64413 0 0 1 -3.0574,0a1.52869,1.64413 0 0 1 -3.0574,0a1.52869,1.64413 0 0 1 -3.05738,0a1.52869,1.64413 0 0 1 -3.0574,0a1.52869,1.64413 0 0 1 -3.05738,0a1.52869,1.64413 0 0 1 -3.0574,0a1.52869,1.64413 0 0 1 -3.0574,0a1.52869,1.64413 0 0 1 -3.05738,0a1.52869,1.64413 0 0 1 -3.0574,0a1.52869,1.64413 0 0 1 0,-3.28827a1.52869,1.64413 0 0 1 0,-3.28828a1.52869,1.64413 0 0 1 0,-3.28828a1.52869,1.64413 0 0 1 0,-3.28827a1.52869,1.64413 0 0 1 0,-3.28828a1.52869,1.64413 0 0 1 0,-3.28827a1.52869,1.64413 0 0 1 0,-3.28828a1.52869,1.64413 0 0 1 0,-3.28828a1.52869,1.64413 0 0 1 0,-3.28827a1.52869,1.64413 0 0 1 0,-3.28828a1.52869,1.64413 0 0 1 0,-3.28828a1.52869,1.64413 0 0 1 0,-3.28827a1.52869,1.64413 0 0 1 0,-3.28828a1.52869,1.64413 0 0 1 0,-3.28827a1.52869,1.64413 0 0 1 0,-3.28828a1.52869,1.64413 0 0 1 0,-3.28828a1.52869,1.64413 0 0 1 0,-3.28827a1.52869,1.64413 0 0 1 0,-3.28828')
any help would be thankfull
Answer: You can fix it by making x and y position of your svg path same as the sample's x and y positions.
I've put two paths in same svg file and opened it with an online editor.
As you can see in this screenshot, sample path is located top-left corner, but your path is located in the middle.

After setting its position same as sample's values: 6px, -1px pattern displayed like this:

used path: m8.278722,2.394142a1.52869,1.64413 0 0 1 3.0574,0a1.52869,1.64413 0 0 1 3.05738,0a1.52869,1.64413 0 0 1 3.0574,0a1.52869,1.64413 0 0 1 3.0574,0a1.52869,1.64413 0 0 1 3.05738,0a1.52869,1.64413 0 0 1 3.0574,0a1.52869,1.64413 0 0 1 3.05738,0a1.52869,1.64413 0 0 1 3.0574,0a1.52869,1.64413 0 0 1 3.0574,0a1.52869,1.64413 0 0 1 3.05738,0a1.52869,1.64413 0 0 1 3.0574,0a1.52869,1.64413 0 0 1 3.0574,0a1.52869,1.64413 0 0 1 3.05738,0a1.52869,1.64413 0 0 1 3.0574,0a1.52869,1.64413 0 0 1 3.05738,0a1.52869,1.64413 0 0 1 3.0574,0a1.52869,1.64413 0 0 1 3.0574,0a1.52869,1.64413 0 0 1 3.05738,0a1.52869,1.64413 0 0 1 3.0574,0a1.52869,1.64413 0 0 1 3.0574,0a1.52869,1.64413 0 0 1 3.05738,0a1.52869,1.64413 0 0 1 3.0574,0a1.52869,1.64413 0 0 1 3.05738,0a1.52869,1.64413 0 0 1 3.0574,0a1.52869,1.64413 0 0 1 3.0574,0a1.52869,1.64413 0 0 1 0,3.28828a1.52869,1.64413 0 0 1 0,3.28827a1.52869,1.64413 0 0 1 0,3.28828a1.52869,1.64413 0 0 1 0,3.28828a1.52869,1.64413 0 0 1 0,3.28827a1.52869,1.64413 0 0 1 0,3.28828a1.52869,1.64413 0 0 1 0,3.28827a1.52869,1.64413 0 0 1 0,3.28828a1.52869,1.64413 0 0 1 0,3.28828a1.52869,1.64413 0 0 1 0,3.28827a1.52869,1.64413 0 0 1 0,3.28828a1.52869,1.64413 0 0 1 0,3.28828a1.52869,1.64413 0 0 1 0,3.28827a1.52869,1.64413 0 0 1 0,3.28828a1.52869,1.64413 0 0 1 0,3.28827a1.52869,1.64413 0 0 1 0,3.28828a1.52869,1.64413 0 0 1 0,3.28828a1.52869,1.64413 0 0 1 0,3.28827a1.52869,1.64413 0 0 1 -3.0574,0a1.52869,1.64413 0 0 1 -3.0574,0a1.52869,1.64413 0 0 1 -3.05738,0a1.52869,1.64413 0 0 1 -3.0574,0a1.52869,1.64413 0 0 1 -3.05738,0a1.52869,1.64413 0 0 1 -3.0574,0a1.52869,1.64413 0 0 1 -3.0574,0a1.52869,1.64413 0 0 1 -3.05738,0a1.52869,1.64413 0 0 1 -3.0574,0a1.52869,1.64413 0 0 1 -3.0574,0a1.52869,1.64413 0 0 1 -3.05738,0a1.52869,1.64413 0 0 1 -3.0574,0a1.52869,1.64413 0 0 1 -3.05738,0a1.52869,1.64413 0 0 1 -3.0574,0a1.52869,1.64413 0 0 1 -3.0574,0a1.52869,1.64413 0 0 1 -3.05738,0a1.52869,1.64413 0 0 1 -3.0574,0a1.52869,1.64413 0 0 1 -3.0574,0a1.52869,1.64413 0 0 1 -3.05738,0a1.52869,1.64413 0 0 1 -3.0574,0a1.52869,1.64413 0 0 1 -3.05738,0a1.52869,1.64413 0 0 1 -3.0574,0a1.52869,1.64413 0 0 1 -3.0574,0a1.52869,1.64413 0 0 1 -3.05738,0a1.52869,1.64413 0 0 1 -3.0574,0a1.52869,1.64413 0 0 1 0,-3.28827a1.52869,1.64413 0 0 1 0,-3.28828a1.52869,1.64413 0 0 1 0,-3.28828a1.52869,1.64413 0 0 1 0,-3.28827a1.52869,1.64413 0 0 1 0,-3.28828a1.52869,1.64413 0 0 1 0,-3.28827a1.52869,1.64413 0 0 1 0,-3.28828a1.52869,1.64413 0 0 1 0,-3.28828a1.52869,1.64413 0 0 1 0,-3.28827a1.52869,1.64413 0 0 1 0,-3.28828a1.52869,1.64413 0 0 1 0,-3.28828a1.52869,1.64413 0 0 1 0,-3.28827a1.52869,1.64413 0 0 1 0,-3.28828a1.52869,1.64413 0 0 1 0,-3.28827a1.52869,1.64413 0 0 1 0,-3.28828a1.52869,1.64413 0 0 1 0,-3.28828a1.52869,1.64413 0 0 1 0,-3.28827a1.52869,1.64413 0 0 1 0,-3.28828
If you scale down your path, it is displayed like this:

used path: m7.27872,1.318623a0.528694,0.568619 0 0 1 1.057396,0a0.528694,0.568619 0 0 1 1.057389,0a0.528694,0.568619 0 0 1 1.057396,0a0.528694,0.568619 0 0 1 1.057396,0a0.528694,0.568619 0 0 1 1.057389,0a0.528694,0.568619 0 0 1 1.057396,0a0.528694,0.568619 0 0 1 1.057389,0a0.528694,0.568619 0 0 1 1.057396,0a0.528694,0.568619 0 0 1 1.057396,0a0.528694,0.568619 0 0 1 1.057389,0a0.528694,0.568619 0 0 1 1.057396,0a0.528694,0.568619 0 0 1 1.057396,0a0.528694,0.568619 0 0 1 1.057389,0a0.528694,0.568619 0 0 1 1.057396,0a0.528694,0.568619 0 0 1 1.057389,0a0.528694,0.568619 0 0 1 1.057396,0a0.528694,0.568619 0 0 1 1.057396,0a0.528694,0.568619 0 0 1 1.057389,0a0.528694,0.568619 0 0 1 1.057396,0a0.528694,0.568619 0 0 1 1.057396,0a0.528694,0.568619 0 0 1 1.057389,0a0.528694,0.568619 0 0 1 1.057396,0a0.528694,0.568619 0 0 1 1.057389,0a0.528694,0.568619 0 0 1 1.057396,0a0.528694,0.568619 0 0 1 1.057396,0a0.528694,0.568619 0 0 1 0,1.137245a0.528694,0.568619 0 0 1 0,1.137241a0.528694,0.568619 0 0 1 0,1.137245a0.528694,0.568619 0 0 1 0,1.137245a0.528694,0.568619 0 0 1 0,1.137241a0.528694,0.568619 0 0 1 0,1.137245a0.528694,0.568619 0 0 1 0,1.137241a0.528694,0.568619 0 0 1 0,1.137245a0.528694,0.568619 0 0 1 0,1.137245a0.528694,0.568619 0 0 1 0,1.137241a0.528694,0.568619 0 0 1 0,1.137245a0.528694,0.568619 0 0 1 0,1.137245a0.528694,0.568619 0 0 1 0,1.137241a0.528694,0.568619 0 0 1 0,1.137245a0.528694,0.568619 0 0 1 0,1.137241a0.528694,0.568619 0 0 1 0,1.137245a0.528694,0.568619 0 0 1 0,1.137245a0.528694,0.568619 0 0 1 0,1.137241a0.528694,0.568619 0 0 1 -1.057396,0a0.528694,0.568619 0 0 1 -1.057396,0a0.528694,0.568619 0 0 1 -1.057389,0a0.528694,0.568619 0 0 1 -1.057396,0a0.528694,0.568619 0 0 1 -1.057389,0a0.528694,0.568619 0 0 1 -1.057396,0a0.528694,0.568619 0 0 1 -1.057396,0a0.528694,0.568619 0 0 1 -1.057389,0a0.528694,0.568619 0 0 1 -1.057396,0a0.528694,0.568619 0 0 1 -1.057396,0a0.528694,0.568619 0 0 1 -1.057389,0a0.528694,0.568619 0 0 1 -1.057396,0a0.528694,0.568619 0 0 1 -1.057389,0a0.528694,0.568619 0 0 1 -1.057396,0a0.528694,0.568619 0 0 1 -1.057396,0a0.528694,0.568619 0 0 1 -1.057389,0a0.528694,0.568619 0 0 1 -1.057396,0a0.528694,0.568619 0 0 1 -1.057396,0a0.528694,0.568619 0 0 1 -1.057389,0a0.528694,0.568619 0 0 1 -1.057396,0a0.528694,0.568619 0 0 1 -1.057389,0a0.528694,0.568619 0 0 1 -1.057396,0a0.528694,0.568619 0 0 1 -1.057396,0a0.528694,0.568619 0 0 1 -1.057389,0a0.528694,0.568619 0 0 1 -1.057396,0a0.528694,0.568619 0 0 1 0,-1.137241a0.528694,0.568619 0 0 1 0,-1.137245a0.528694,0.568619 0 0 1 0,-1.137245a0.528694,0.568619 0 0 1 0,-1.137241a0.528694,0.568619 0 0 1 0,-1.137245a0.528694,0.568619 0 0 1 0,-1.137241a0.528694,0.568619 0 0 1 0,-1.137245a0.528694,0.568619 0 0 1 0,-1.137245a0.528694,0.568619 0 0 1 0,-1.137241a0.528694,0.568619 0 0 1 0,-1.137245a0.528694,0.568619 0 0 1 0,-1.137245a0.528694,0.568619 0 0 1 0,-1.137241a0.528694,0.568619 0 0 1 0,-1.137245a0.528694,0.568619 0 0 1 0,-1.137241a0.528694,0.568619 0 0 1 0,-1.137245a0.528694,0.568619 0 0 1 0,-1.137245a0.528694,0.568619 0 0 1 0,-1.137241a0.528694,0.568619 0 0 1 0,-1.137245


Regression when both input and dependent variables are percentages

Question: I have a dataset where I am trying to understand if there is a correlation between two variables: an input which is the percentage of a group that is white (which varies between 40% and 95%), and an output which is the annual percentage increase in the housing values for that group (which varies between 0.1% and 10%, e.g. the value of the houses for a neighborhood where the population is 85% white have gone up by 7.5% since last year)
Setting aside for a moment if a linear relationship is at all appropriate for this question, if I ask Excel to plot a scatter plot of X = percentage white and Y = percentage value increase this year, and fit a line, Excel gives me one back: y = 0.0087x + 0.0371. R^2 is 0.0021
Am I correctly interpreting what Excel is telling me - for every percentage point increase of the population mix towards more white, the percentage points for home value increases goes up by 0.087? Or in another way, if there was a neighborhood that was 82% white and if its housing values went up 6% last year, if that neighborhood had been 92% white property values would have gone up 6.87% last year?
I think this is basic question, but I'm just a little lost with percentage increases of percentages and the like. Actually, I'm not even completely sure that this is an allowable question for linear regression, so I'm hoping my example is simple enough that someone can point me in the right direction
Again, I don't actually think the causality here is actually that simple, but before I go on to try to talk about better approaches with more data, I want to make sure that I'm using the math right and explaining what the math is telling me in the basic approach, even if it's not going to give me the "correct" answer of what's really happening with housing prices.
Answer: Your R-squared indicates there is no correlation.  Being white is not impacting the increase in value. An R-squared of 1 is a perfect correlation, and an R-squared of -1 is a perfect negative correlation.
It appears you are seeing a scatterplot similar to the bottom image below (or otherwise one where it's hard to draw a line in "middle" of it).
The top image below shows a positive correlation.
Comment: Thank you, that's very helpful, and yeah, the lower image is closer to what I was seeing. One minor followup - if my R-squared had been much closer to 1, would I have been interpreting the percentage point increase correctly from the slope of the equation? I'm still a little confused about the units to use.


Best practice for third-party PHP class-based library

Question: I am currently working on a module that requires a third-party PHP library, which is essentially a single PHP class.  Normally, I would place it in an includes/ subdirectory and add
files[] = includes/Foo.php

to my .info file and let the Drupal 7 class auto loader do its thing when I do a  $foo = new Foo().
I have permission, though, to release this module to the public and would rather not include the library with the module.  I am well aware about the complications regarding licensing, but for the sake of this question, I would like to ignore it.
There is a similar question, How do I include a PHP library?, but I don't really think this answers my dilema.
This answers to this question essentially say to use the Libraries API, but every single module that I have found that uses this just does alibraries_get_path() to get the basepath (and includes fallback path when it isn't available) and then does a require or include with some error checking (or not).  All do something like:
if (!class_exists('Foo')) {
  $path = function_exists('libraries_get_path') ?
    libraries_get_path('foo') : 'sites/all/libraries/foo';
  if (!include($path . '/Foo.php')) {
      // handle this error
  }
}

In this case, the Libraries API isn't really doing anything.  I don't see the advantage to using this, over the old method of asking users to download a copy and place it in the module folder itself.  And, there is still the issue that the module developer still needs to manually do the load with include/require.  For example, the Facebook module just loads the library in a hook_init and the HTML Purifier module has an internal function to check-and-load every time the library is needed.
This may be a widespread practice, but it doesn't seem like a best practice.
Should my module take the initiative and declare a hook_libraries_info so I can use libraries_load('foo')?  This, too, seems odd.
Comment: Another issue is whether or not the third party library's license matches drupal's.  If it does, and it's not huge, I'd just include it.  If it doesn't, you can't/shouldn't include it to begin with, so the library approach seems better, and have your eventual end users download it themselves.
Comment: One purpose of `if (libraries_load($name)) {..}` is to avoid a WSOD in case the library is not present.
Answer: Branch 2.x of the Libraries API module allows developers to define, through hook_libraries_info(), or a .info file for the library, the following information (see libraries.api):

The dependencies of the library
The version with which the library is compatible, for each of the dependencies
The list of the files that needs to be loaded (CSS, JavaScript, or PHP files)

The list of files that needs to be loaded is used to load those files, when the library is required. This means that your module doesn't need to load CSS, and JavaScript files with drupal_add_css(), or drupal_add_js(), as that is already done from the Libraries API module. Loading the dependencies is a task done from the Libraries API module, without the calling module doing anything.
All the module does is using the following code, for loading a library. (See Using Libraries API 2.x (as module-developer).)
// Try to load the library and check if that worked.
if (($library = libraries_load($name)) && !empty($library['loaded'])) {
  // Do something with the library here.
}

If you just need to detect if a library is present, the module should use code similar to the following one.
if (($library = libraries_detect($name)) && !empty($library['installed'])) {
  // The library is installed.
}
else {
  $error = $library['error'];
  $error_message = $library['error message'];
}

Between the properties hook_libraries_info() can return, there is also 'download url', which is not actually used, not even in the branch 3.x. Probably it will be used in future, or a third-party modules could hook into the Libraries API module, and download the libraries that are requested, but missing.
Comment: Can you point out any popular modules that do this with PHP libraries?  Part of the motivation for the question was so that I could follow best practices for a public module, so I started to seek out ones that use the libraries API.  I did not find any that implemented hook_libraries_info() and used libraries_load() internally.
Comment: zencorderapi module (part of Video module) uses hook_libraries_info()
Comment: @mpdonadio There is a partial list on [Examples of contributed modules using Libraries API](http://drupal.org/node/1570568).
Comment: @kiamlaluno, thanks, that was the first place I looked.  Of the six, only two of those libraries implement hook_libraries_info.  I don't think your answer is wrong, but I am not convinced that this is a widespread best practice right now.  One of the libraries did have an interesting technique that I am going to test out and possibly post about later.
Comment: @mpdonadio Version 7.x-2.0 has been released on July 29; it is probable that most of the modules are still using the 7.x-1 approach.
Answer: After a decent amount of digging, I am still unconvinced about what the best practice is.  Inspired by the PHPMailer module, I am offering this for class based PHP libraries:
function foo_registry_files_alter (&$files, $modules)
{
  if (!class_exists('Foo')) {
    $library_path = function_exists('libraries_get_path') ?
      libraries_get_path('foo') : 'sites/all/libraries/foo';

    $files[$library_path . '/Foo.php'] = array(
      'module' => 'foo',
      'weight' => 0,
    );
  }
}

This uses hook_registry_files_alter to check for a class's existence, and if not found, add a file to the class registry (the equivalent to a files[] = ... line in a modules .info file).  Then, classes defined in foo.php will be available with the autoloader, so there is no need to explicitly load the file before using the class.
This also creates a soft requirement on the Libraries API, and will use it if available, otherwise use a reasonable default.
Adding some checks via a hook_requirements to make sure the file exists, that the autoloader finds the class, version check, etc, is also be a good idea.
It is also worth noting that an autoload approach for the Libraries API is being discussed in the issue queue.
Comment: Dont forget to clear your cache after implementing hook_registry_files_alter, otherwise it wont trigger ;)
Answer: In short:
If you are planning to release module to public and the (third party) library is not GPL'd, you will need to use Libraries as a dependency or ask users to download these files manually (but you will not be able to autoload it from .info file)
In little longer:
The reason why we need Libraries module is basically licensing. No matter you use that module or not, you are including that file in some way.
Well I think you didn't find good examples for such libraries-shipped-with-the -module cases.
Check out SMTP module and it comes with the necessary classes as it's in GPL. (.info file blob).
Also see simplehtmldom module which just include the file but nothing else.
Where Libraries module comes handy is that, you can ask users to upload the file anywhere they want. It's not obvious that users will upload it to sites/all/libraries folder. It could be sites/example.com/libraries or something like that. Libraries module can help you to focus on your actual work by doing the directory discovery stuff for you.
For custom modules that I develop for my clients, I usually include files in module folder and use require_once or .info file entry depending on use of the library.
Also, licensing problems are not the only reason to use Libraries module. What if the third party library has rapid release cycles and your module is minimally developed ? If you include it in the module, you will have to make a new release everytime. You will not want to have a release 7.x-1.99 which is much similar to 7.x-1.0 i guess.
Comment: Thanks for taking the time to answer.  I edited my question a bit to clarify.  The question is not really about the complications of licensing and release schedules, and how the Libraries API helps with this.  I am more curious about best practices about actually loading third-party libraries.
Answer: It seems the major problem is the autoload.
You can use libraries module plus xautoload module.
Then in your own module, you do
function mymodule_libraries_info() {

  return array(
    'mymodule-test-lib' => array(
      'name' => 'My test library',
      ..
      'xautoload' => function($api) {
        // Register a namespace with PSR-0 root in <library dir>/lib/
        // Note: $api already knows the library directory.
        // Note: We could omit the 'lib', as this is the default value.
        $api->namespaceRoot('XALib\TestNamespace', 'lib');
      },
    ),
  );
}

This is explained in more detail here:
xautoload.api.php
More about the $api argument.
Note: You can also write your own "handlers", to implement more exotic old-school patterns beyond PSR-0 or PEAR. If you need help with that, post an issue on the xautoload queue.
Note: There is more than one way to register your library namespaces. This one is the easiest, if you want the namespaces to be registered in every request.
Comment: I should add, this does not help with loading procedural files. This needs to be done manually, as soon as you need the library in a request.
Comment: Also, some libraries have their own class loading solutions. Still, it can be more convenient to use a loader already available in Drupal / contrib.


Built-In PowerShell Module Path

Question: I'm trying to figure out where the built-in modules are hosted in the filesystem. I would've thought it an easy task, but I'm not having much luck. Most/all of the Google results are about getting the path of the current script or adding a search-path. I'm searching the hard drive for the nouns in the names and have not been successful. I've searched for general "ps1" files, in general, and haven't been successful. I've searched both "Program Files" directories and the "Windows" directory as well.
I'm using the ISE to find scripts whose nouns I can search for, but the built-in ones seem uselessly-generically named (too many results) and the proprietary ones are probably located somewhere non-general (as I understand that there's a search-path that might've been updated by the install-process).
Any ideas? Thanks.
Comment: Did you forget to use google? ;-)
Comment: @Colyn1337 Have you? Most/all of the results are about getting the path of the current script or adding a search-path.
Comment: Actually yes, it's how I found the answer to this question when I needed to know years ago.
Answer: For a specific user(s):
<code>%UserProfile%\Documents\WindowsPowerShell\Module
</code>
For all users on the computer:
<code>%ProgramFiles%\WindowsPowerShell\Modules
</code>
Documented here in the MSDN document.
Comment: Also, C:\Windows\System32\WindowsPowerShell\v1.0\Modules (for reference, this is a PS 4.0 system).
Comment: is this really correct? `get-module | select path` gives me other paths, especially for the Built-In modules which the OP asked for. as he said correctly they are in `C:\Windows\System32\WindowsPowerShell\v1.0\Modules`and some are in `C:\program files\windowsPowerShell\modules`. Why does the command give me other results, is the command not correct for this task?

Built-In PowerShell Module Path


How to add a constraint to the final phase of simplex tableau?

Question: How does one go about adding a new constraint in the final phase of the simplex tableau?
In the case where our optimal solution satisfies the constraint, we can conclude that the optimal solution stays the same.
But what if the constraint is not satisfied? Do we have to start over again?
Comment: Please clarify your specific problem or provide additional details to highlight exactly what you need. As it's currently written, it's hard to tell exactly what you're asking.
Answer: In order to add a new constraint into the optimal Simplex Tableau, we'll need to do two things to the tableau:

Add a new row
Add a new slack column

In addition, we'll have a new $B^{-1}$ under the slack columns from the addition of the new slack variable, thus we'll have to recalculate the Reduced Cost of all the non-basic variables, and recalculate all the $\bar{A}_j$ (their columns) of each non-basic variable (which is calculated from $B^{-1}A_j$ where $A_j$ is the column of the variable $j$ in which it appeared in the original constraints of the model). From here, if the tableau is violated in some way that's irrecoverable, then the addition of the new constraint made the model infeasible.
Two things to keep in mind about adding new constraints in terms of the Objective Solution:

It can make the existing solution worse, as adding a new constraint could cut off a section of the feasible region.
It'll leave the existing solution alone as the new constraint was redundant and did nothing for the model.

Under no circumstance does adding a new constraint makes the model better in terms of increasing the objective function output (maximization) or reducing it (minimization), as at best it'll do nothing to the existing model, and at worst it cuts off more of the feasible region.
Answer: If the previously optimal basic feasible solution violates the new constraint, then the basis (adjusted to include a basic variable in the new constraint) is "superoptimal" (at least as good as, and possible better, than optimal) but infeasible. In that case, you can use the dual simplex algorithm. Whereas the primal simplex algorithm starts with a feasible basis and works toward optimality while maintaining feasibility, the dual simplex algorithm starts with a superoptimal but infeasible basis and works toward feasibility while maintaining superoptimality. Most (all?) text books that discuss the simplex method also discuss the dual simplex method. Dual simplex is the most common way that solvers handle cuts being added to an LP tableau.
Comment: I haven't encountered the term "superoptimal" before, but I like it! (Previously, I used the term "dual feasible", which is also accurate but less suggestive of what it means.)
Comment: I don't recall where I first encountered "superoptimal" (it was a long time ago), but I definitely did not coin the term. It does seem to be rather sparingly used.


Python syntax error in a while block

Question: I get a syntax error in the following code:
if value[0] == "ta" or "su":
        num_var = len(value)
        i = 0
        while value[i][0] != "-" and i <= num_var:
            if i == 0 and value[0][0].isdigit():
                f3["var_%s" %i] = VARFD[[value[0].split("/")[1]]
            else:
                f3["var_%s" %i] = VARFD[[value[0]]
            f4["val_%s" %i] = "T"
            i += 1

it claims that the syntax error is on line that starts with "else:". What's wrong with it?
Comment: you know that `value[0] == "ta" or "su"` is not the same as `value[0] == "ta" or value[0] == "su"`, right?
Comment: `value[0] in ('ta', 'su')` would be even nicer. And please do not inline if bodies. It's ugly to read, especially for longer lines.
Comment: this is actually a very non-readable code: bad indentation, too much inlines and more than 80 chars per line
Answer: You're missing a square bracket in the
        if i == 0 and value[0][0].isdigit(): f3["var_%s" %i] = VARFD[[value[0].split("/")[1]]

line.  But Python code really isn't meant to be this densely written.  Space and light!
Answer: Is your supply of new lines limited or why are you writing code like this?
Your error is here, one ] is missing:
VARFD[[value[0].split("/")[1]]

Comment: if i add new lines, won't the program be slower?
Answer: It's as simple as that you're missing an end bracket on the line before the else.
VARFD[[value[0].split("/")[1]]

I suspect the expression should be
VARFD[value[0].split("/")[1]]

It's pretty much sure sign that you should break apart and simplify your code when errors like this show up :)

Python syntax error in a while block


Java get published external IP Address?

Question: I have been going through so many stackoverflow answers and none answers my question accurately.
My question is, how can I get my real internet external IP Address, not the local one, but my published IP Address which other people see & connect to?
Eg : 220.127.116.11
and not. 188.8.131.52
Currently im pooling the IP Address from whatismyip.com, but that takes a few seconds to get, since i have to buffer read it.
Is there a way to do it without reading the ip from a website?
Comment: What kind of router do you have? You'll have to connect to your router, and pull the information out.
Answer: I do not know a solution to your problem that you are asking for, but I tried out your solution and I'm not getting the same "few seconds" delay as you, so I decided to share my solution:
<code>public static String getIp() throws IOException{
    URL whatismyip = new URL("http://icanhazip.com");
    BufferedReader in = new BufferedReader(new InputStreamReader(whatismyip.openStream()));
    return in.readLine();
}
</code>
Maybe whatismyip.com is slower, or has more information to parse?
Comment: Not really. You'd have to have direct access to your firewall and query it for its external IP. This is probably not feasible.
Comment: As you see, you're using a reader to get the ip, I am asking if its possible to get the ip without using any website.

Java get published external IP Address?


Replace com variavel - mysql

Question: Como posso fazer Replace utilizando uma variável?
Uma determinada variável recebe valores de uma consulta, então preciso fazer um Replace em uma determinada coluna, com os valores obtidos ,como posso fazer isso? segue exemplo no fiddle:
http://sqlfiddle.com/#!9/6f8f1f/16/0

Ocorre que os valores obtidos, aparecem como único valor e os
  resultados não são o esperado

 SELECT
@enderecoHashImagem := concat(substr(contenthash,1,2),'/',substr(contenthash,3,2),'/',contenthash) as enderecoHashImagem,
@nomeImagem := filename as nomeImagem,
Replace(questiontext, concat('@@PLUGINFILE@@/',@nomeImagem), GROUP_CONCAT(@enderecoHashImagem)) AS questiontext

FROM mdl_question q

inner join mdl_files f on f.itemid=q.id

where component = 'question'

Comment: Isso esta ocorrendo porque sua variável `@grupoEndereco` esta retornando `null`.
Comment: Executa assim: `SELECT
@enderecoHashImagem := concat(substr(contenthash,1,2),'/',substr(contenthash,3,2),'/',contenthash) as enderecoHashImagem,
@nomeImagem := filename as nomeImagem, @grupoEndereco := GROUP_CONCAT(@enderecoHashImagem) AS grupoEndereco,
@grupoEndereco, Replace(questiontext, concat('@@PLUGINFILE@@/',@nomeImagem), @grupoEndereco) AS questiontext

FROM mdl_question q

inner join mdl_files f on f.itemid=q.id

where component = 'question'` você verá que na segunda vez que usar essa variável retornará `null`.
Comment: @RobertodeCampos  no exemplo fiddle esta é saída de @grupoEnderco: `8c/a7/8ca79795dc7c3c7fc836faac6d0d7422627486cb,8c/a7/8ca79795dc7c3c7fc836faac6d0d7422627486cb`
Comment: dois endereços separados por vírgula
Comment: @RobertodeCampos vdd, a segunda retorna null
Comment: Será que é possível fazer o que pretendo, usar replace com os valores desta variável ?
Comment: @RobertodeCampos agora não estou mais recebendo `null`, mas o resultado ainda não é o esperado, se puder dar uma olhada, obrigado
Comment: Pra te falar a verdade, nunca utilizei variáveis dessa forma, o que eu faço geralmente é duplicar o código, vou colocar como resposta para você entender melhor.
Answer: Nunca trabalhei com variáveis desta forma, o que faço geralmente quando preciso tratar a informação no SELECT mais de uma vez é, duplicar o código, no seu caso ficaria assim:
SELECT
  concat(
    substr(
      contenthash,
      1,
      2
    ),
    '/',
    substr(
      contenthash,
      3,
      2
    ),
    '/',
    contenthash
  ) as enderecoHashImagem,
  filename as nomeImagem,
  GROUP_CONCAT(
    concat(
      substr(
        contenthash,
        1,
        2
      ),
      '/',
      substr(
        contenthash,
        3,
        2
      ),
      '/',
      contenthash
    )
  ) AS grupoEndereco,
  Replace(
    questiontext,
    concat(
      '@@PLUGINFILE@@/',
      filename
    ),
    GROUP_CONCAT(
    concat(
      substr(
        contenthash,
        1,
        2
      ),
      '/',
      substr(
        contenthash,
        3,
        2
      ),
      '/',
      contenthash
    )
  )
  ) AS questiontext
  FROM mdl_question q
  inner join mdl_files f on f.itemid=q.id
  where component = 'question'

Comment: neste caso o resultado permanece o mesmo, o valores da consulta estão sendo tratados como único valor
Answer: Fiz o seguinte, faço a consulta usando group_concat dos valores que desejo para substuir outros , para obtê-los concatenados separados por vírgulas. Uso o Replace e Substring_index para, a cada substituição, o valor que já foi usado seja excluído, para determinar o próximo valor a ser obtido uso Substring_index novamente.

Está funcionando, talvez não seja o método adequado, pois se houver
  mais de 20 valores que desejo susbtituir dá erro, mas até 20 funciona.

Segue sqlfiddle:
http://sqlfiddle.com/#!9/6f8f1f/16/0
-- borrowed from https://stackoverflow.com/q/7745609/808921

CREATE TABLE IF NOT EXISTS `mdl_question` (
  `id` int(6) unsigned NOT NULL,
  `questiontext` varchar(200) NOT NULL,
  PRIMARY KEY (`id`)
) DEFAULT CHARSET=utf8;
INSERT INTO `mdl_question` (`id`, `questiontext`) VALUES
  ('1', '  ');

CREATE TABLE IF NOT EXISTS `mdl_files` (
  `id` int(6) unsigned NOT NULL,
  `contenthash` varchar(200) NOT NULL,
  `filename` varchar(200) NOT NULL,
  `component` varchar(200) NOT NULL,
  `itemid` varchar(200) NOT NULL,

  PRIMARY KEY (`id`)
) DEFAULT CHARSET=utf8;
INSERT INTO `mdl_files` (`id`, `contenthash`, `filename`, `component`, `itemid`) VALUES
  ('1','8ca79795dc7c3c7fc836faac6d0d7422627486cb','imagem1.svg','question', '1'),
  ('2','418679c9ecac4eb42452d4c51332710d24f6de8a','imagem2.svg','question', '1'),
  ('3','418679c9ecac4eb42452d4c51332710d24f6de8a','imagem3.svg','question', '1')

SELECT
Replace(Replace(Replace(Replace(Replace(Replace(Replace(Replace(Replace(Replace(Replace(Replace(Replace(Replace(Replace(Replace(Replace(Replace(Replace(Replace(questiontext,
concat('@@PLUGINFILE@@/',SUBSTRING_INDEX(SUBSTRING_INDEX(GROUP_CONCAT(filename),',',-20),',',1)), SUBSTRING_INDEX(SUBSTRING_INDEX(GROUP_CONCAT(concat(substr(contenthash,1,2),'/',substr(contenthash,3,2),'/',contenthash)),',',-20),',',1)),
concat('@@PLUGINFILE@@/',SUBSTRING_INDEX(SUBSTRING_INDEX(GROUP_CONCAT(filename),',',-19),',',1)), SUBSTRING_INDEX(SUBSTRING_INDEX(GROUP_CONCAT(concat(substr(contenthash,1,2),'/',substr(contenthash,3,2),'/',contenthash)),',',-19),',',1)),
concat('@@PLUGINFILE@@/',SUBSTRING_INDEX(SUBSTRING_INDEX(GROUP_CONCAT(filename),',',-18),',',1)), SUBSTRING_INDEX(SUBSTRING_INDEX(GROUP_CONCAT(concat(substr(contenthash,1,2),'/',substr(contenthash,3,2),'/',contenthash)),',',-18),',',1)),
concat('@@PLUGINFILE@@/',SUBSTRING_INDEX(SUBSTRING_INDEX(GROUP_CONCAT(filename),',',-17),',',1)), SUBSTRING_INDEX(SUBSTRING_INDEX(GROUP_CONCAT(concat(substr(contenthash,1,2),'/',substr(contenthash,3,2),'/',contenthash)),',',-17),',',1)),
concat('@@PLUGINFILE@@/',SUBSTRING_INDEX(SUBSTRING_INDEX(GROUP_CONCAT(filename),',',-16),',',1)), SUBSTRING_INDEX(SUBSTRING_INDEX(GROUP_CONCAT(concat(substr(contenthash,1,2),'/',substr(contenthash,3,2),'/',contenthash)),',',-16),',',1)),
concat('@@PLUGINFILE@@/',SUBSTRING_INDEX(SUBSTRING_INDEX(GROUP_CONCAT(filename),',',-15),',',1)), SUBSTRING_INDEX(SUBSTRING_INDEX(GROUP_CONCAT(concat(substr(contenthash,1,2),'/',substr(contenthash,3,2),'/',contenthash)),',',-15),',',1)),
concat('@@PLUGINFILE@@/',SUBSTRING_INDEX(SUBSTRING_INDEX(GROUP_CONCAT(filename),',',-14),',',1)), SUBSTRING_INDEX(SUBSTRING_INDEX(GROUP_CONCAT(concat(substr(contenthash,1,2),'/',substr(contenthash,3,2),'/',contenthash)),',',-14),',',1)),
concat('@@PLUGINFILE@@/',SUBSTRING_INDEX(SUBSTRING_INDEX(GROUP_CONCAT(filename),',',-13),',',1)), SUBSTRING_INDEX(SUBSTRING_INDEX(GROUP_CONCAT(concat(substr(contenthash,1,2),'/',substr(contenthash,3,2),'/',contenthash)),',',-13),',',1)),
concat('@@PLUGINFILE@@/',SUBSTRING_INDEX(SUBSTRING_INDEX(GROUP_CONCAT(filename),',',-12),',',1)), SUBSTRING_INDEX(SUBSTRING_INDEX(GROUP_CONCAT(concat(substr(contenthash,1,2),'/',substr(contenthash,3,2),'/',contenthash)),',',-12),',',1)),
concat('@@PLUGINFILE@@/',SUBSTRING_INDEX(SUBSTRING_INDEX(GROUP_CONCAT(filename),',',-11),',',1)), SUBSTRING_INDEX(SUBSTRING_INDEX(GROUP_CONCAT(concat(substr(contenthash,1,2),'/',substr(contenthash,3,2),'/',contenthash)),',',-11),',',1)),
concat('@@PLUGINFILE@@/',SUBSTRING_INDEX(SUBSTRING_INDEX(GROUP_CONCAT(filename),',',-10),',',1)), SUBSTRING_INDEX(SUBSTRING_INDEX(GROUP_CONCAT(concat(substr(contenthash,1,2),'/',substr(contenthash,3,2),'/',contenthash)),',',-10),',',1)),
concat('@@PLUGINFILE@@/',SUBSTRING_INDEX(SUBSTRING_INDEX(GROUP_CONCAT(filename),',',-9),',',1)), SUBSTRING_INDEX(SUBSTRING_INDEX(GROUP_CONCAT(concat(substr(contenthash,1,2),'/',substr(contenthash,3,2),'/',contenthash)),',',-9),',',1)),
concat('@@PLUGINFILE@@/',SUBSTRING_INDEX(SUBSTRING_INDEX(GROUP_CONCAT(filename),',',-8),',',1)), SUBSTRING_INDEX(SUBSTRING_INDEX(GROUP_CONCAT(concat(substr(contenthash,1,2),'/',substr(contenthash,3,2),'/',contenthash)),',',-8),',',1)),
concat('@@PLUGINFILE@@/',SUBSTRING_INDEX(SUBSTRING_INDEX(GROUP_CONCAT(filename),',',-7),',',1)), SUBSTRING_INDEX(SUBSTRING_INDEX(GROUP_CONCAT(concat(substr(contenthash,1,2),'/',substr(contenthash,3,2),'/',contenthash)),',',-7),',',1)),
concat('@@PLUGINFILE@@/',SUBSTRING_INDEX(SUBSTRING_INDEX(GROUP_CONCAT(filename),',',-6),',',1)), SUBSTRING_INDEX(SUBSTRING_INDEX(GROUP_CONCAT(concat(substr(contenthash,1,2),'/',substr(contenthash,3,2),'/',contenthash)),',',-6),',',1)),
concat('@@PLUGINFILE@@/',SUBSTRING_INDEX(SUBSTRING_INDEX(GROUP_CONCAT(filename),',',-5),',',1)), SUBSTRING_INDEX(SUBSTRING_INDEX(GROUP_CONCAT(concat(substr(contenthash,1,2),'/',substr(contenthash,3,2),'/',contenthash)),',',-5),',',1)),
concat('@@PLUGINFILE@@/',SUBSTRING_INDEX(SUBSTRING_INDEX(GROUP_CONCAT(filename),',',-4),',',1)), SUBSTRING_INDEX(SUBSTRING_INDEX(GROUP_CONCAT(concat(substr(contenthash,1,2),'/',substr(contenthash,3,2),'/',contenthash)),',',-4),',',1)),
concat('@@PLUGINFILE@@/',SUBSTRING_INDEX(SUBSTRING_INDEX(GROUP_CONCAT(filename),',',-3),',',1)), SUBSTRING_INDEX(SUBSTRING_INDEX(GROUP_CONCAT(concat(substr(contenthash,1,2),'/',substr(contenthash,3,2),'/',contenthash)),',',-3),',',1)),
concat('@@PLUGINFILE@@/',SUBSTRING_INDEX(SUBSTRING_INDEX(GROUP_CONCAT(filename),',',-2),',',1)), SUBSTRING_INDEX(SUBSTRING_INDEX(GROUP_CONCAT(concat(substr(contenthash,1,2),'/',substr(contenthash,3,2),'/',contenthash)),',',-2),',',1)),
concat('@@PLUGINFILE@@/',SUBSTRING_INDEX(SUBSTRING_INDEX(GROUP_CONCAT(filename),',',-1),',',1)), SUBSTRING_INDEX(SUBSTRING_INDEX(GROUP_CONCAT(concat(substr(contenthash,1,2),'/',substr(contenthash,3,2),'/',contenthash)),',',-1),',',1))

AS questiontext

FROM mdl_question q

inner join mdl_files f on f.itemid=q.id

Comment: Sei que deve ter um jeito profissional de fazer mas não sei

Replace com variavel - mysql


Is it possible to perform a regression where you have an unknown / unknowable feature variable?

Question: Is it possible to perform a regression where you have an unknown / unknowable feature variable?
Say I have $y_n = a_0 + a_1 x_1 + a_2 x_2 + a_3 x_3$ but I do not / cannot measure the value of the feature variable $x_3$. Can I still perform a regression to ascertain the coefficients $a_i$?
How about if I have some knowledge of the statistics of how $x_3$ is distributed? If I know that $x_3$ is drawn from a Gaussian distribution $\mathcal{N}(0, \sigma^2)$, with known $\sigma$ does this allow me to perform the regression to ascertain the values of $a_i$?
Comment: If it was possible, world would be beautiful! Just imagine: no data collection! no data wrangling! no people sending you data as screenshot embeded in Word document...
Comment: No, how would you know what is attributable to the feature and what is just random?
Comment: @SomeRandomPhysicist See, for example, section 2 of [this paper](https://pdfs.semanticscholar.org/853f/fd345232e6f052a2bf50c31d76238a06c5a5.pdf) - Measuring Potential Output within a State-Space Framework by Maral Kichian (Bank of Canada).
Comment: Thanks for the answers, just wanted some confirmation that this was the case as I suspected. I guess one could still perform the regression on the other feature variables if the effect of $x_3$ was very weak relative to the other feature variables, and so could be neglected entirely, but in the case where it is a large contribution regression is impossible.
Comment: @user2974951 Why not turn that into an answer? I don't even think you would need to expand on that.
Comment: What about a state space model?
Comment: Yes. An unobserved component model / state space model can be used to do this. A classic example is modeling potential output  (unobserved or latent variable) in economics. Essentially, you assume how this state variable evolves over time and can estimate it using a Kalman filter.
Comment: @GraemeWalsh In other words... "assume a can opener".
Answer: The complete formula for a linear model is (in quasi matrix form)
$$Y=\beta X+\epsilon$$
So we have multiple coefficents for the variables that we are controlling for, and then we have $\epsilon$, which is everything else which we did not explain with our included variables.
In this error term belong all the variables which we did not consider, either because we do not have information for them or because we simply do not know of them (random deviation).
So there is just no way for you to know what in this term belongs to what unknown term.
Comment: Upvoted for the excellence and clarity of the answer.
Answer:
How about if I have some knowledge of the statistics of how x3 is
  distributed?

If you do the regression of $y$ on $x_1$ and $x_2$, then if you're willing to make educated guesses how $x_3$ correlates with each of these, you can calculate what these guesses would entail for how the coefficients you estimate would change if you could observe $x_3$ and ran the full regression.
Suppose for instance that $x_3$ isn't correlated with $x_1$. Then
$\alpha_{2, \text{your regression}} =\alpha_{2, \text{full regression}} + \alpha_3 \cdot \frac{cov(x_3, x_2)}{var(x_2)}$
So if $x_3$ is likely to be only weakly correlated with $y$ or $x_1$ and $x_2$ not much would change. And if it is, you can use these omitted-variable-bias formulas to predict how things would change.
Answer: It is always possible... but your estimates will be biased in many cases. The most favorable case occurs:
(a) When $x_{3n}$ is not correlated with the other regressors, in this case, regress $y_n$ on $(\iota,x_{1},x_{2})$ and you have unbiased estimates of $a_0,a_1,a_2$ (Frish-Waugh-Lovell theorem)
(b) If in addition to (a) you know $\sigma$ and $x_3 \sim \mathcal{N}(0, \sigma^2)$, then you can even identify $a_3$: draw $N$ iid values for $x_{3n} \sim \mathcal{N}(0, \sigma^2)$ and regress $y_n$ on $(\iota,x_{1},x_{2},x_{3})$.
Comment: Could you explain further how to perform the regression in situation (b)? Do you generate values for the unknown $x_3$ by drawing them from $\mathcal{N}(0, \sigma^2)$ and then regress on that?
Comment: Yes, this is the way to do it. It is possible to iterate on random number generation and estimation, but this does not seem interesting in your simple case. There is a burgeoning literature on simulation based methods using a similar approach, but they are a bit more involved than in your example: see Gouriéroux and Monfort, for instance. See also the pedagogical description in the texbook of Cameron and Trivedi (2005).


determine value differences between form submissions

Question: I have an entity form that user can submit multiple times. What i would like to do is during validation get current values in the database and compare with the once that user just entered. I'm using
$form['#validate'][] = 'my_function';.
So really the questions is how do I get 'current values' that are already stored in the database to one array and 'about to be submitted values' (just updated by user) to the other array. The reason why I want those to be saved, temporary only, in the array is to do comparison.
Comment: Sounds reasonable - what's your question? Do you need to know how to query the database? How to store values in the database? How to set a form error? Please expand...
Comment: the questions is: how do I get current values to one array and about to be submitted values to the other array (questions updated)
Comment: What are 'current' values, and what are 'about to be submitted values'? Please remember _we can't see your code_, _we weren't involved in the spec meeting for this_; you need to provide as much background as you can so your situation can be understood. Do you know how to save/retrieve values to/from the database? Adding your current code would be very helpful
Comment: current values would be the once that user has already submitted and are saved in the databases. what happens next is, after a while user comes again and submits the same form for the second time. now before those values ('about to be submitted') are saved to the database I would like to be able to compare them with the once that are already saved in the database.
Comment: So breaking your question down to what you're actually asking - you need to know how to query data from the database, right? (bearing in mind comparing two arrays is a language issue and has nothing to do with Drupal)
Comment: correct. but potentially using API if possible rather than querying database myself
Comment: Is this a custom form, webform, node form, or something else?
Comment: its entity form
Answer: If you're looking for a non-SQL way to get data out of the database the db_select() function (which returns an SelectQuery) is the way to go. For obvious reasons there's no implicit API implemented for your custom data tables (you'd need to create that yourself).
Without knowing your schema this can't be totally accurate, but the basics are:
$query = db_select('my_table', 't')
  ->fields('t', array('field1', 'field2'))
  ->condition('some_column', 'some_value');

$results = $query->execute();
foreach ($results as $result) {
  // $result is an object, use it...
}

SelectQuery has a bunch of helper methods to get specifically formatted data out of the database, so chances are you won't need to loop over the data. You can find a list of those helper functions (and info on the alternative, SQL based approach that still uses the API) here
Comment: thanks for the answer Clive. is there an other way of doing that if I were to tell you, and should have, that I am using entity forms


Data sufficiency -- determining from aggregate

Question: I am working with a dataset which looks essentially like the following:
Name     Average Score
-------- --------------
John     34.9381
Susan    22.2718
Stu      29.1009
...

The assumption is that each average score is composed of integer-value single scores.
I would like to know if there are any standard techniques out there for determining the quantity of data underlying the aggregates.  For the purposes of simplification, we can assume that number of records is consistent among names.
I've tried a few hacked-together techniques for guessing, but the brute-force method of trying n=2, then 3, then 4, etc. of every possible value is computationally miserable for anything other than test cases.
I've also attempted to shave it down by assuming first value = round(average), then adding next value to get closest possible on n=2, etc. (e.g., 2.666: first is 3; for second, subtract 3/2 from 2.666, round to nearest 0.5, multiply by 2: result = 2, so best average=2.5; etc.).
This works for trivially simple numbers -- rather, single floats.  Run until minimized, and it gives a rough idea for a small n.  But this may be theoretically full of holes, which I'd like to know.
Worse, for many decimal places, large datasets, and lots of rounding problems, this ugly method isn't great.  And I feel like I must be solving an already-solved problem, but I don't have the vocabulary even to search for the solution.  What is this problem called, or even what field is this in?  And does anyone have any bright ideas, R libraries, etc.?
Thanks very much.
Answer: One possibility is to generate fractions. You could use the function .rat, hidden in the package MASS, to find rational approximations to the components of a real numeric object.
scores <- c(34.9381, 22.2718, 29.1009)

res <- MASS:::.rat(scores)

This command will return the following list:
$rat
               b0
[1,] 349381 10000
[2,]  67684  3039
[3,] 291009 10000

$x
[1] 34.9381 22.2718 29.1009

You could find the denominators in the second column (b0) of the matrix in $rat:
res$rat[ , "b0"]

Now, you could check which denominators are justified by the possible number of data points.
Comment: That's kind of perfect, I think.  I'll check it out!
Comment: This looks like the right neck of the woods; it tends, however, to merely return fractions denominated by 1000, 10000, etc.  Even passing max.denominator=999, I still get many with a power-of-10 denominator.  Any ideas?
Comment: You could just use `fractions` from the `MASS` package (which is exported, not hidden)
Comment: @mnel The function `fractions` will return the fractions as strings. I suppose its easier to use integers.
Comment: `fractions`, unfortunately, shows the same problem -- in the majority of the cases, it simply takes, e.g., 3.1415 and makes it 31415/10000.

Is anyone aware of a technique for integrating findings from _multiple_ numbers?

These are actually great starting points for me to build a brute-force solution, but I'm also hoping to find out where and whether this specific problem has been dealt with in the past.

Thanks again.


Number of possible solutions to $2 \le |x-1||y+3| \le 5$, where $x$ and $y$ are negative integers

Question:
If $$2 \le |x-1||y+3| \le 5$$ and both $x$ and $y$ are negative integers, find the number of possible combinations of $x$ and $y$ .

Below is my solution approach :-
As $x$ is a negative integer, hence $|x-1|$ in the $2 \le |x-1||y+3| \le 5$ will be come $-(x-1)$ or $(1-x)$ and the main equation will transform into $2 \le (1-x)|y+3| \le 5$.
$1st$ case when $y+3 \ge 0 \Rightarrow y \ge -3 \Rightarrow y \in \{{-3,-2,-1}\} $ as $y$ is a negative integer :
For $y=-3$ we can see that there is no valid solution for $x$ as $|y+3|$ part will become $0$, hence this case is invalid.
For $y=-2$ we get the solution set for $x$ to be $x \in \{{-4,-3,-2,-1}\} $  and total number of solutions possible in this case is $4$.
For $y=-1$ we get the solution set for $x$ to be $x \in \{{-1}\} $ and total number of solutions possible in this case is $1$.
So for this $1st$ case when $y+3 \ge 0$ we have in total 5 solutions.
$2nd$ case when $y+3 \lt 0 \Rightarrow y \lt -3$ and in this case $y$ will have infinite values and I am not able to proceed from here.

The answer for the total number of solutions provided is $10$ and you can see that I've been able to find out the $5$ solutions in my $1st$ case. Can someone please guide or help me about how to proceed in the 2nd case?

Thanks in advance !
Comment: Notice that $|x-1||y+3|$ is an integer between $2$ and $5$, so there are only few possibilities to check.
Comment: Since $x$ is a negative integer, $|x - 1| \geq 2.$  This means that $|y+3|$ must be less than $3$.
Comment: thanks for such quick responses...but can you please direct me in the way of how I was trying to solve this rather than taking a whole new solution approach. If you have new approach...please explain down as answers...thanks!
Comment: In your second case we have $|y+3|=(-y-3)$ and also $1-x>1$ (in fact $1-x\geq 2$),and so by $(1-x)(-y-3) \le 5$ we must have $-y-3 \leq \frac{5}{2}$. This gives you a lower bound for $y$ similarly as in first case.
Comment: @Sil : can you please elaborate your last comment? I understood the part that $1-x \ge 2$ but i did not understood after that. If you kindly elaborate the later part of your comment.
Comment: By definition of absolute value, if $z<0$ then $|z|=-z$, and so $|y+3|=-(y+3)$. Then $5 \geq (1-x)(-y-3) \geq 2(-y-3)$ (because $1-x \geq 2$ and both expressions in brackets are positive), and so by diving by $2$ we get $\frac{5}{2} \geq -y-3$.
Answer: Both $|x-1|$ and $|y+3|$ are non-negative integers. As the product must lie between $2$ and $5$, the only candidates are:
$$(1,2), (1,3), (1,4), (1,5), (2,1), (2,2), (3,1), (4,1), (5,1)$$
However, we can't force $|x-1|=1$ with a negative $x$, so this leaves just five possible solutions:
$$(2,1), (2,2), (3,1), (4,1), (5,1)$$
We can make $|y+3|$ equal $1$ or $2$ twice though, with $|-2
+3|=1,|-4+3|=1$ and similarly with $y=-1,-5$, so each pair can be made two times, once with each $y$, and this gives $10$ solutions.
Comment: Can you please elaborate "We can make $|y+3|$ equal $1$ or $2$ twice though, with $y=-2,-4$ and $y=-1,-5$, so each one is doubled up to give $10$ solutions." ?                                         Thanks !
Comment: @Ganit; is that better?
Answer: The possible values of the product are $2,3,4,5$.
Hence the possible factorizations,
$$1\cdot2,2\cdot1,1\cdot3,3\cdot1,1\cdot4,2\cdot2,4\cdot1,1\cdot5,5\cdot1.$$
But $|x-1|\ge2$, which leaves
$$2\cdot1,3\cdot1,2\cdot2,4\cdot1,5\cdot1,$$
while $|y+3|$ can achieve $1$ and $2$ in two ways.

$$10.$$
Answer: If $x,y$ are integers then $|x-1|$ and $|y+3|$ are non negative integers.
So just rewrite them as $m,n$ and we have $1 \le mn \le 5$.
Those are small and simple numbers.
We can have $nm = 1,2,3,4,5$
But you said $x,y$ are both *negative integers.  So $x \le -1$ and so $x -1 \le -2$ so $|x- 1| \ge 2$.
so we can have:
$nm = 2$ and $|x-1| =2$ and $|y + 3| = 1$ so $x-1= -2$ and $x =-1$ while $|y+3| = 1$ so $y+3 = \pm 1$ so $y = 1-3=-2$ or $y = -1 -3 = -4$.
or
$nm =3$ and $|x-1| = 3$ and $|y+3| = 1$ so $x-1 =-3$ and $x = -2$ while, as above, y=-2, -4$.
or $nm = 4$ and either $|x-1|=2$ and $|y+3|=2$.  Or $|x-1| =4$ and $|y+3| =1$.
If $|x-1|=|y+3|= 2$ then $x = -1$ and $y+3 =\pm 2$ so $y = -1; -5$.
And if $|x-1|=4$ and $|y+3| =1$ then $x-1 = -4$ and $x =-3$ and $y= -2,4$ (as above).
And if $nm = 5$ then $|x-1| = 5$ so $x-1 = -5$ and $x =-4$ and $|y+3| = 1$ and $y=-2,-4$.
So all solutions are.
$(x,y) = \{$
$(-1, -2),(-1, -4), (-2,-2),(-2,-4), (-1,-1),(-1,-5), (-3,-2)(-3,-4), (-4,-2),(-4,-4)$
$\}$.
Comment: Shouldn't there be $2$ in "So just rewrite them as $m,n$ and we have $1 \le mn \le 5$."?
Answer: It is not true that $y$ can take infinitely many numbers.
We have  since $x \le -1$, $|x-1|\ge 2,  $
$$\frac1{|x-1|}\le \frac12$$
we must have
$$|y+3| \le \frac{5}{|x+1|}\le \frac52$$
If $y< -3$, then we have $$-y-3 \le \frac52 $$
$$-\frac{11}2 \le y $$
Hence $-5 \le y < -3$, that is $-5 \le y \le -4$.
For $y=-4=-3-1$, by symmetry, the same $x$ for which $y=-3+1=-2$ satisfies the inequality would work,  there are $4$ of them.
For $y=-5=-3-2$, by symmetry, the same $x$ for which $y=-3+2=-1$ satisfies the inequlaity would work, there is $1$ of them.
Hence in total, there are $10$.
Comment: Can you please explain "We have  since $x \le -1$, $|x-1|\ge 2,$

we must have $$\frac22 \le |y+3|\le \frac52$$" as I am not able to understand this step? Are you dividing the in equality by $|x-1|$?
Comment: I made a msitake earlier, we can conclude that $|y+3| \le \frac{5}{|x+1|} \le \frac52$.


Using netns to force Java application use specify IP

Question: My VPS provider assigned 4 IPv4 to my vps. However, This assigned to single NIC, and VLAN not working(Maybe it is my configuration problem). If I try using VLAN, I can't get external network using VLAN interface.
I want run same Java application on each IP address. This application serving image cache server and notify own IP address to Master server to send HTTP request, and master server get IP from HTTP Request IP.
So, I need to force use specify IP to connect external network for each Java process.
When I tried netns using below configuration, app0_ns works perfectly, but not others. They can ping to 10.200.0.0/16, but can't access to external network.
Here command that I tried to make netns.
My vps using Ubuntu 18.04, and I can change the OS version.
ip netns add app0_ns
ip netns add app1_ns
ip netns add app2_ns
ip netns add app3_ns

ip link add v_app0a type veth peer name v_app0b
ip link add v_app1a type veth peer name v_app1b
ip link add v_app2a type veth peer name v_app2b
ip link add v_app3a type veth peer name v_app3b

ip link set v_app0b netns app0_ns
ip link set v_app1b netns app1_ns
ip link set v_app2b netns app2_ns
ip link set v_app3b netns app3_ns

ip addr add 10.200.0.1/24 dev v_app0a
ip link set v_app0a up
ip addr add 10.200.1.1/24 dev v_app1a
ip link set v_app1a up
ip addr add 10.200.2.1/24 dev v_app2a
ip link set v_app2a up
ip addr add 10.200.3.1/24 dev v_app3a
ip link set v_app3a up

ip netns exec app0_ns ip addr add 10.200.0.2/24 dev v_app0b
ip netns exec app0_ns ip link set v_app0b up
ip netns exec app0_ns ip link set lo up
ip netns exec app0_ns ip route add default via 10.200.0.1

ip netns exec app1_ns ip addr add 10.200.1.2/24 dev v_app1b
ip netns exec app1_ns ip link set v_app1b up
ip netns exec app1_ns ip link set lo up
ip netns exec app1_ns ip route add default via 10.200.1.1

ip netns exec app2_ns ip addr add 10.200.2.2/24 dev v_app2b
ip netns exec app2_ns ip link set v_app2b up
ip netns exec app2_ns ip link set lo up
ip netns exec app2_ns ip route add default via 10.200.2.1

ip netns exec app3_ns ip addr add 10.200.3.2/24 dev v_app3b
ip netns exec app3_ns ip link set v_app3b up
ip netns exec app3_ns ip link set lo up
ip netns exec app3_ns ip route add default via 10.200.3.1

iptables -t nat -A POSTROUTING -s 10.200.0.1/24 -o eth0 -j MASQUERADE
iptables -t nat -A POSTROUTING -s 10.200.1.1/24 -o eth0:1 -j MASQUERADE
iptables -t nat -A POSTROUTING -s 10.200.2.1/24 -o eth0:2 -j MASQUERADE
iptables -t nat -A POSTROUTING -s 10.200.3.1/24 -o eth0:3 -j MASQUERADE

iptables -A FORWARD -i eth0 -o v_app0a -j ACCEPT
iptables -A FORWARD -o eth0 -i v_app0a -j ACCEPT
iptables -A FORWARD -i eth0:1 -o v_app1a -j ACCEPT
iptables -A FORWARD -o eth0:1 -i v_app1a -j ACCEPT
iptables -A FORWARD -i eth0:2 -o v_app2a -j ACCEPT
iptables -A FORWARD -o eth0:2 -i v_app2a -j ACCEPT
iptables -A FORWARD -i eth0:3 -o v_app3a -j ACCEPT
iptables -A FORWARD -o eth0:3 -i v_app3a -j ACCEPT

Here my /etc/network/interfaces.
 auto lo
  iface lo inet loopback

 auto eth0
  iface eth0 inet static
   address [Removed]
   gateway [Removed]
   netmask 255.255.255.0
   dns-nameservers 18.104.22.168 184.108.40.206
   up ip addr add [Removed]/48 dev eth0
   up ip -6 route add [Removed] dev eth0
   up ip -6 route add default via [Removed]

 auto eth0:1
  iface eth0:1 inet static
   address [Removed]
   gateway [Removed]
   netmask 255.255.255.0
   dns-nameservers 22.214.171.124 220.127.116.11

 auto eth0.2
  iface eth0.2 inet static
   address [Removed]
   gateway [Removed]
   netmask 255.255.255.0
   dns-nameservers 184.108.40.206 18.104.22.168
   vlan-raw-device eth0

 auto eth0:3
  iface eth0:3 inet static
   address [Removed]
   gateway [Removed]
   netmask 255.255.255.0
   dns-nameservers 18.104.22.168 220.127.116.11

Here I tried VLAN configuration.
 auto eth0.3
  iface eth0.3 inet static
   address [Removed]
   gateway [Removed]
   netmask 255.255.255.0
   dns-nameservers 188.8.131.52 22.214.171.124
   vlan-raw-device eth0

Answer: It resolved. I used SNAT.
Virtual Interfaces is "Virtual" so It can't resolved as Interface name. I have to using just Physical Interface name.
Here's an example for future reference.
iptables -t nat -A POSTROUTING -s 10.200.0.1/24 -o eth0 -j SNAT --to (eth0 IP)
iptables -t nat -A POSTROUTING -s 10.200.1.1/24 -o eth0 -j SNAT --to (eth0:1 IP)
iptables -t nat -A POSTROUTING -s 10.200.2.1/24 -o eth0 -j SNAT --to (eth0:2 IP)
iptables -t nat -A POSTROUTING -s 10.200.3.1/24 -o eth0 -j SNAT --to (eth0:3 IP)


Can I use Google Places with react-google-maps/api?

Question: I am tiring to use google places to grab some restaurant markers but I am not sure how to combine it with "@react-google-maps/api".
I saw this post: Google map with react-google-maps API
which seem to pass in "places" to the loader but I am unsure of what to do after that like how do I do something like this
var map;
var service;
var infowindow;

function initMap() {
  var sydney = new google.maps.LatLng(-33.867, 151.195);

  infowindow = new google.maps.InfoWindow();

  map = new google.maps.Map(
      document.getElementById('map'), {center: sydney, zoom: 15});

  var request = {
    query: 'Museum of Contemporary Art Australia',
    fields: ['name', 'geometry'],
  };

  var service = new google.maps.places.PlacesService(map);

  service.findPlaceFromQuery(request, function(results, status) {
    if (status === google.maps.places.PlacesServiceStatus.OK) {
      for (var i = 0; i < results.length; i++) {
        createMarker(results[i]);
      }
      map.setCenter(results[0].geometry.location);
    }
  });
}

Comment: The library you are using doesn't implement the Places Service (only Autocomplete and SearchBox apparently).
Comment: Any progress on this?
Answer: The code snippet you provided is using Find Place From Query which is one of the services under the Places Library of Google Maps JavaScript API.
The @react-google-maps/api is a library that was created to provide very simple bindings to Google Maps JavaScript API and as the documentation states, it only have Autocomplete and StandaloneSearchBox components for Places Library.
If you would like to use the Find Place From Query, you can implement it by calling the findPlaceFromQuery() method when the map loads. You will see that in my code snippet below, I call it in the onMapLoad() function. I also use state for center and coordsResults that will hold the array for the findPlaceFromQuery result. I will then use a condition to check the coordsResults state before showing the marker for the result. Here is the sample code and code snippet below:
import React from "react";

import { GoogleMap, Marker, InfoWindow } from "@react-google-maps/api";

let coords = [];

class Map extends React.Component {
  state = {
    center: { lat: -33.867, lng: 151.195 },
    coordsResult: []
  };

  onMapLoad = map => {
    let request = {
      query: "Museum of Contemporary Art Australia",
      fields: ["name", "geometry"]
    };

    let service = new google.maps.places.PlacesService(map);

    service.findPlaceFromQuery(request, (results, status) => {
      if (status === google.maps.places.PlacesServiceStatus.OK) {
        for (var i = 0; i < results.length; i++) {
          coords.push(results[i]);
        }

        this.setState({
          center: results[0].geometry.location,
          coordsResult: coords
        });
      }
    });
  };

  render() {
    return (

        <GoogleMap
          center={this.state.center}
          zoom={13}
          onLoad={map => this.onMapLoad(map)}
          mapContainerStyle={{ height: "400px", width: "800px" }}
        >
          {this.state.coordsResult !== [] &&
            this.state.coordsResult.map(function(results, i) {
              return (
                <Marker key={i} position={results.geometry.location}>
                  <InfoWindow
                options={{ maxWidth: 300 }}>

                      {results.name}

                  </InfoWindow>
                </Marker>
              );
            })}
        </GoogleMap>

    );
  }
}

export default Map;

Comment: Solved by calling `new window.google.maps...` instead
Comment: I'm getting `google is not defined` in the line `let service = new google.maps.places.PlacesService(map);` any ideas?


React - Module not found, For packages inside the installed packages, when requirting express

Question: Hello I tried to install the express package in a react project
But when I import the package inside the app.js using:
const app = require("express");

I get 30 errors all saying
Module not found Error: Can't resolve 'x'

where x are differnt packages like zlib, querystring, path, crypto, fs, stream ....
This is the app.js code when I run it without the require line it works fine
import logo from './logo.svg';
import './App.css';
const app = require("express");

function App() {
  return (

          Edit src/App.js and save to reload.

          Learn React

  );
}

export default App;

And inside my package.json file in my dependencies I do have:     "express": "^4.17.3"
I even tried to create a new blank project for this and I had the same problem
Comment: Express is a framework for Node, not React/FE clients. You can't import it like you're doing. You need to set up your own Express server that React interacts with using endpoints/routes.
Answer: Your bundler (probably Webpack) cannot bundle packages which depend on Node.js APIs.
Express depends on all sorts of things that need Node.js (such as the ability to listen for incoming HTTP requests and use the C library that zlib uses).
You can't run Express inside a browser.


Wavelet analysis of EEG

Question: I want to do a time-frequency analysis of an EEG signal. I found the GSL wavelet function for computing wavelet coefficients. How can I extract actual frequency bands (e.g. 8 - 12 Hz) from that coefficients? The GSL manual says:

For the forward transform, the elements of the original array are replaced by the discrete wavelet transform $f_i \rightarrow w_{j,k}$ in a packed triangular storage layout, where $j$ is the index of the level $j = 0, \ldots, J-1$ and $K$ is the index of the coefficient within each level, $k = 0 ... (2^j)-1$. The total number of levels is $J = \log_2(n)$.
  The output data has the following form, $(s_{-1,0}, d_{0,0}, d_{1,0}, d_{1,1}, d_{2,0}, \ldots, d_{j,k}, \ldots, d_{J-1,2^{J-1}-1})$

If I understand that right an output array data[] contains at position 1 (e.g. data[1]) the amplitude of the frequency band 2^0 = 1 Hz, and
data[2] = 2^1 Hz
data[3] = 2^1 Hz
data[4] = 2^2 Hz

until
data[7] = 2^2 Hz
data[8] = 2^3 Hz

and so on ...
That means I have only the amplitudes for the frequencies 1 Hz, 2 Hz, 4 Hz, 8 Hz, 16 Hz,...
How can I get for example the amplitude of a frequency component oscillating at 5.3 Hz?
How can I get the amplitude of a whole frequency range, e.g. the amplitude of 8 - 13 Hz?
Answer: Two options:

One way to get the amplitude at an arbitrary frequency (say 5.3 Hz) would be to resample the signal at a sampling rate such that the base frequency calculated by the wavelet transform would be 5.3 Hz (instead of 1.0 Hz).
A more appropriate way for a frequency range (say the 8-13 Hz alpha rhythm) is to discard the wavelet transform, filter the signal in this range with a band-pass filter (say a Butterworth filter), apply the Hilbert Transform, and calculate the analytic signal amplitude.

In MATLAB, the latter option would correspond to:
[b a] = butter(2,[8 13]/(sampling_freq/2));
eeg_filtered = filter(b,a,eeg);
eeg_amp = abs(hilbert(eeg_filtered));

Comment: Especially since you are interested in time-frequency analysis, be careful about the filter you use. You might consider a symmetric FIR filter as an alternative to the Butterworth, which has a terribly nonlinear phase response. Another option is to run the data through the BW filter and take the output, reverse it and run it through the filter again. This will remove the phase nonlinearity. It will also sharpen the cutoff frequencies since you've filtered twice. So you may need to adjust for that, too. In either case, you'll need enough data for any transient response to get worked out...
Comment: ...before (and after) the actual data of interest is filtered.

Wavelet analysis of EEG


How to convert STL vector of vector to armadillo mat?

Question: Given vector<vector<double > > A_STL, I want it to get converted into arma::mat A.
Comment: What did you try ? What didn't work ? And why are you insisting on garbling your formatting ?
Comment: Because A_STL is actually a vector of vectors, not just a vector of double
Comment: Yep, saw that and didn't change it. But without `proper formatting`, your template instantiations are getting stripped as malformed html tags.
Answer: One simple way would be to flatten your vector of vector matrix into one dimensional vector. And you can therefore use your mat(std::vector) constructor.
Code example (not tested) :
// Flatten your A_STL into A_flat
std::vector<double> A_flat;
for (auto vec : A_STL) {
  for (auto el : vec) {
    A_flat.push_back(el);
  }
}
// Create your Armadillo matrix A
mat A(A_flat);

Beware of how you order your vector of vector. A_flat should be column major.
Comment: how is the width and height dimensions determined(specified) in the created arma::mat?
Comment: is it possible to provide it in the constructor or it should be applied using the reshape method?
Answer: The following lines should do the job:
template<typename T>
arma::Mat<T> convertNestedStdVectorToArmadilloMatrix(const std::vector<std::vector<T>> &V) {
    arma::Mat<T> A(V.size(), V[0].size());

    for (unsigned_t i{}; i < V.size(); ++i) {
        A.row(i) = arma::conv_to< arma::Row<T> >::from(V[i]);
    }
    return A;
}

Test with:
std::vector<std::vector<float_type>> vec = {{1.0, 2.0, 3.0}, {4.0, 5.0, 6.0}};
arma::Mat<float_type> mat = convertNestedStdVectorToArmadilloMatrix(vec);


Server for virtualization

Question: HP Proliant DL380 G5
I have looked at this server for some good virtualization. I can get the server for around 450usd 2x xenon (X5355) 2 x 72GB HDD 8GB Ram
As my g3 360 and g4 360 and g3 360 are starting to get a bit slow.
I will be running exsi 4.1 or 5? Not that many vms, but a litle bit. Just for a test environment not anything else.
Is that a good way to go or is there any other types in that price range (ebay) to recommend?
Sorry for my English, i'm from norway :)
Kind regards
Comment: Shopping questions, even from Norway, are off topic here and other SE sites.
Answer: The HP ProLiant DL380 G5 server series works well and is fully supported for VMWare use (with ESXi 4.1 and 5/5.1). This comes from experience running the system in production and its place on the VMWare hardware compatibility list (HCL).
The only downside to using this particular platform for virtualization is its limited RAM expandability (8 slots) and the high cost of its RAM.
Comment: WE HAVE THE SAME HARDWARE AND WE DONT HAVE ANY PROBLEM. BUT THEY SHOULD ENABLE __VT ENABLE__ ONLY WANT HE GOOGLE:  how to enable Virtualization Technology (VT) in MOTHERBOARD BIOS?

Server for virtualization


How to get my drum tracks louder for guitar practice , PA ?

Question: How do I get enough volume from my iPad drum tracks to match my guitar amp ? PA ? I have been practicing heavy metal rhythm guitar with drum tracks from my iPad amplified with a blue tooth speaker . It is just not loud enough to get my guitar volume past 2 on my amp . I can play as loud as. I want . I am limited by my blue tooth speaker and want to be able to crank up my guitar amp .
Was thinking of getting a PA and hooking my iPad up to the PA through the headphone jack . All my drum tracks are iPad apps . Is this a good way to go ? What size PA would I need to really get a metal level of volume ?
I enjoy practicing loud . What can I say ?
Answer: A decent PA would do it, and give you the possibility of plugging in microphones also, or other sound sources. If you are trying to go cheap and compact, then a keyboard amp or electronic drum amp would also work, but those are normally designed for a single sound source.
You'll want a lot more watts in your PA or keyboard/drum amp than your guitar amp, because for drum sounds you need headroom and also more low frequency extension, both of which require more power. You should shoot for 200 Watts or more (total across the whole system), depending on what you can afford.
If you want to go the PA route, I'd get a 6 - 12 channel UNpowered mixer and two powered speakers. The advantage in powered speakers is you don't have to take a lot of time matching power amp to speaker cabinets. I'd look for powered speakers with at least a 12" woofer (if not 15") and 100 - 200 Watts each speaker.
For a keyboard or drum amp, I'd look at 12" designs with 200 Watts or so of total power.
Oh also, you'll need a way to get the sound from the iPad into the PA or amp. The cheapest way is find the right cable to go from the headphone jack but I can say from experience it won't sound as good as the best way. The best way is to get an iPad compatible interface (if it's "Core Audio Compliant" it will work even if it doesn't say iPad on it) and an iPad camera connection kit if it's a USB interface.
Answer: It does depend on how loud you mean by loud. For the purpose of practice, anything that makes your ears ring after playing might seem cool now, but take it from someone who can't hear that well anymore and has constant ringing in their ears because of loud music (I think it was a Pantera, or possibly dream theater concert that did it in the mid 90s) I would consider carefully your playing volume. Do the research, hearing damage isn't like the volume going down, it wrecks frequencies so you hear some things well and other poorly.
That was a bit of an aside, but otherwise, I completely agree with Todd's answer, although also, it might be worth taking a look at a powered wedge monitors. Due to the position, you will likely need less volume to hear it well, and you don't need to worry about hooking up mixers to speakers (not that it's very hard, but the wedge would be closer to a guitar amp).
Also, as you can still run your ipad through it, if you pick up an irig or similar, it may also come in handy for running things like amplitube through your ipad in case you have a friend over and want to jam, you can use your amp/wedge set up as a faux guitar amp. Of course, you could also do this through a PA set up too.


Requisições entre Web e CLP Siemens pequeno delay

Question: Esta função Jquery é controlada quando um Switch da minha página é realizado um change
$("#statusM1").change(function () {

        if (statusM1 == 0) {
            url = "index.html";
            name = '"motor"';
            val = 1;
            sdata = escape(name) + '=' + val;
            $.get(url, sdata, function (result) { });
        } else if (statusM1 == 1) {
            url = "index.html";
            name = '"motor"';
            val = 0;
            sdata = escape(name) + '=' + val;
            $.get(url, sdata, function (result) { });
        }
    });

$.ajaxSetup({ cache: false });
    setInterval(function () {
        $.get("IOCounter.html", function (result) {

            statusM1 = result.trim();
            $('#counter').text(statusM1);

            if (statusM1 == 1) {
                $('#statusM1')[0].MaterialSwitch.on();
            } else {
                $('#statusM1')[0].MaterialSwitch.off();
            }

        });
    }, 1000);

setInterval tem a funcionalidade de coletar um dado da página IOCounter.html
O script acima esta funcionando mas percebo que na hora do change há um delay uma pequena confusão no momento do change e a requisição.
$.get(url, sdata, function (result) { });
Explicando um pouco melhor temos o seguinte cenário:
1ª Inicialmente o Switch esta na posição ON,
2ª então ao clicar ele vai para o OFF,
3º e com isto executa a função .change,
4º temos um  intervalo em que a requisição não é feita então o Switch volta para o ON, pois ainda não recebeu o verdadeiro valor do setInterval.
5ª após esta pequena confusão no Switch pega o valor correto da requisição e volta para o OFF
O que tem de ser feito para que amenize este inconveniente ?
Comment: Não use `setInterval` para fazer requisições. Use `setTimeout`.
Comment: Tente fazer desta forma: http://jsfiddle.net/1gL3h7zn/
Comment: @sam é o seguinte como pode acontecer de desligarem ou ligarem o equipamento no local a página tem que atualizar pois senão vira a maior bagunça, entendeu , e mais outra todos os eletricistas uns 15 terão acesso então imagina só a bagunça um liga o outro desliga, entendeu, o porque do setInternal
Comment: @sam como sou novato em JQuery foi o primeiro comando que encontrei na internet, se você tiver sujestão será muito bem vinda.
Comment: Sugeri usar setTimeout porque as requisições serão feitas em fila, uma após a outra. Usando setInterval as requisições serão feitas de forma desorganizada, ou seja, irá fazer uma requisição atrás da outra sem querer saber se a anterior tenha sido processada. Isso pode travar o navegador e até fazer com que o servidor suspenda o acesso por achar que está havendo abuso (se ele tiver essa proteção) ou criar um gargalo. A sugestão que coloquei apenas organiza as requisições, e a página será atualizada da mesma forma.
Comment: @sam funcionou, ai te pergunto qual diferença entre setInterval e setTimeout ? este sistema Web fica hospedado em um CLP Siemens que é uma controladora muito usada em automação Industrial.
Comment: Vamos [continuar esta discussão no chat](https://chat.stackexchange.com/rooms/80258/discussion-between-sam-and-cyberlacs).
Answer: Conforme discutido nos comentários, utilizar requisições Ajax com setInterval não é indicado porque ele é assíncrono ao processamento do Ajax. O retorno do Ajax pode levar milissegundos ou até alguns segundos, logo chamar requisições com um intervalo pré-definido pode criar um gargalo no servidor ou travar o navegador.
O indicado é usar setTimeout após o processamento do Ajax. Desta forma cada requisição será feita de forma ordenada e em fila.
Para isso, coloque o Ajax dentro de uma função e chame-a novamente após o retorno:
function f(){
  $.get("IOCounter.html", function (result) {

      statusM1 = result.trim();
      $('#counter').text(statusM1);

      if (statusM1 == 1) {
          $('#statusM1')[0].MaterialSwitch.on();
      } else {
          $('#statusM1')[0].MaterialSwitch.off();
      }
      // chama novamente a função após 1 segundo, criando um loop
      setTimeout(f, 1000);
  });
}

// chama a função após 1 segundo.
setTimeout(f, 1000);

// Ou, se esse segundo inicial não for necessário
// pode chamar a função sem intervalo com

f();

// removendo a linha setTimeout(f, 1000); acima

Lembrando que a função do $.get só será chamada se o Ajax for bem sucedido. Caso haja algum erro, o setTimeout não será chamado e o loop irá parar. Por isso é melhor chamar o setTimeout no callback .always para garantir que a função será sempre chamada novamente:
function f(){
  $.get("IOCounter.html", function (result) {

      statusM1 = result.trim();
      $('#counter').text(statusM1);

      if (statusM1 == 1) {
          $('#statusM1')[0].MaterialSwitch.on();
      } else {
          $('#statusM1')[0].MaterialSwitch.off();
      }
  })
  .always(function(){
      // chama novamente a função após 1 segundo, criando um loop
      setTimeout(f, 1000);
  });
}