To kill particular java application

Question: I am running a set of Java applications through batch files which occasionally need to be killed via console. But in task manager it shows all these applications as java.exe, whereas in the application tab it shows the particular name. I need to get the process id for the application from the application tab, so that I can kill the application based on it. To reiterate, I have only the application name, not other details, and how would I obtain the PID based on this - in vb.net?
Thanks In Advance
Regards
Sathya.M
Comment: Good point. (+1). Completely forgot about jps.
Comment: start class of all java application has same name. but i didn't know about jps. how to do it?
Comment: @Sathya:  http://docs.oracle.com/javase/1.5.0/docs/tooldocs/share/jps.html
Comment: I changed batch files title like start "myexample"  java -jar ... likewise. Then to stop that applications. first i stored all java applications in one array. Then i checked its mainwindowtitle as equal to myexample. Then i kill that process. its working well.
Answer: Take a look on this thread: How can a Java program get its own process ID?
This is not exact duplicate. It answers the question how can application discover PID of itself.
If all applications you are running are yours you can modify your code to read the PID and pass it to other process (e.g. by writing it to file). If the process is not yours you can anyway use JMX to connect to your applications remotely and discovery their PIDs.
Comment: +1 for the java.lang.management package :-)

To kill particular java application


How does including an interaction term change interpretation of two deviation coded predictors

Question: Suppose I am running a regression with two dummy coded dichotomous variables. Unless I am mistaken, the coefficient for IV1 reflects the effect of IV1 only at IV2 = 0.
How does this change when the model also includes the IV1 x IV2 interaction?
Answer:
Unless I am mistaken, the coefficient for IV1 reflects the effect of
  IV1 only at IV2 = 0.

No, the coefficient of IV1 reflects the difference of mean DV associated with change in IV1, holding IV2 constant. IV2 can be 0, and IV2 can be 1, as long as it's held constant, the regression coefficient of IV1 captures the mean difference in DV.
When IV1 = 1, the regression formula is:
$$DV_{IV1 = 1} = \beta_0 + \beta_1 (1) + \beta_2 (IV2)$$
When IV1 = 0, the regression formula is:
$$DV_{IV1 = 0} = \beta_0 + \beta_2 (IV2)$$
The difference is then:
$$DV_{IV1 = 1} - DV_{IV1 = 0} = \beta_0 + \beta_1 (1) + \beta_2 (IV2) - \beta_0 - \beta_2 (IV2)$$
ending with just $\beta_1$. Notice that IV2 can be any number, as long as they are the same number in both scenarios, the IV2 terms are cancelled out.

How does this change when the model also includes the IV1 x IV2
  interaction?

For this, your original statement would be correct: the coefficient for IV1 reflects the difference in mean DV associated with of IV1 when IV2 = 0.
$$DV_{IV1 = 1, IV2 = 0} = \beta_0 + \beta_1 (1) + \beta_2 (0) + \beta_3 (1 \times 0)$$
$$DV_{IV1 = 0, IV2 = 0} = \beta_0 + \beta_1 (0) + \beta_2 (0)+ \beta_3 (0 \times 0)$$
The difference is just $\beta_1$.
When IV2 = 1, then:
$$DV_{IV1 = 1, IV2 = 1} = \beta_0 + \beta_1 (1) + \beta_2 (1) + \beta_3 (1 \times 1)$$
$$DV_{IV1 = 0, IV2 = 1} = \beta_0 + \beta_1 (0) + \beta_2 (1)+ \beta_3 (0 \times 1)$$
the difference became $(\beta_1 + \beta_3)$


How to get data from two related tables?

Question: I am trying to get data from two related tables in a single query.
Tables look like this:
Table 1:
--------------------------
| ID        | username   |
--------------------------
| 1         | user1      |
| 2         | user2      |
| 3         | user3      |
| 4         | user4      |
--------------------------

Table 2:
----------------------------------------------------
| ID        | user_id    | key        | value      |
----------------------------------------------------
| 1         | 1          | key1       | value1     |
| 2         | 1          | key2       | value2     |
| 3         | 2          | key2       | value3     |
| 4         | 3          | key3       | value4     |
| 5         | 4          | key1       | value5     |
| 6         | 4          | key3       | value5     |
----------------------------------------------------

I want to get a result including all rows from Table 1 and key-value pairs from table 2 where key = key1. If the key is not present in Table 1 for a given row from table 1, fill it with NULL. Expected result example:
----------------------------------------------------
| user_id   | username   | key        | value      |
----------------------------------------------------
| 1         | user1      | key1       | value1     |
| 2         | user2      | NULL       | NULL       |
| 3         | user3      | NULL       | NULL       |
| 4         | user4      | key1       | value5     |
----------------------------------------------------

Alternatively - all the rows from Table 1 which don't contain key-value pair for key=key1 in Table 2.
I tried standard SELECT from 2 tables and SELECT from Table 1 with JOIN from Table 2, but all I get is all rows from Table 1 which contain key-value pair with key=key1 in Table 2 and this is exactly the opposite of what I want.
Any suggestions?
Answer: select
      t1.id,
      t1.username,
      t2.key,
      t2.value
   from
      table1 t1
         left join table2 t2
            on t1.id = t2.user_id
           and t2.key = 'key1'

For your "Alternative" to get all that DO NOT have, just add a where clause..
where t2.user_id IS NULL

Answer: Try this:
SELECT t1.username,t2.user_id,t2.key,t2.value FROM table1 as t1 left join table2 as t2 on(t1.id = t2.user_id) and t2.key = 'key'

Answer: Query might look something like this:
SELECT t1.username, t2.key, t2.value FROM table1 AS t1
LEFT OUTER JOIN table2 AS t2 ON t1.id = t2.user_id;

For example, if there is no user_id 3 in table2, then the query (above) will produce:
+----------+------+--------+
| username | key  | value  |
+----------+------+--------+
| user1    | key1 | value1 |
| user1    | key2 | value2 |
| user2    | key2 | value3 |
| user3    | NULL | NULL   |
| user4    | key1 | value5 |
| user4    | key3 | value5 |
+----------+------+--------+

Comment: he was looking for a sample that allowed only a certain key='key1', AND alternatively how to get the INVERSE (only those that didn't).  Did you see my answer...


how to apply rto_min to a certain host in centos?

Question: I want to apply the rto_min of 3 sec or 6 sec to any route from my server to an ip for example 192.168.18.45. How can I do that in centos?
Thanks,
Answer: You can change rto_min for a route with
ip route change [route] dev eth0 rto_min 3s

If you have tried that and you get strange results when you run the command (for example)
ip route change  192.168.254.0/24 dev eth0 rto_min 400ms

and are getting strange results
ip route show 192.168.254.0/24 dev eth0
192.168.254.0/24  scope link  rto_min lock 0.57ms

There is a known bug in the output formatting of the command.


Query tables across multiple databases

Question: All... I need a way to query identical tables across multiple databases. I have roughly 30+ databases and they all have identical tables.
    SELECT
      a.name
      , a.address
      , b.company_id
      , c.part_no
      , c.cost
    FROM accounts a
    JOIN business b on a.whatever = b.whatever
    JOIN crazy c ON b.things = c.things

Something simple like this, but across all databases. The focus isn't joining on multiple databases, that's simple, it's running this across all databases simultaneously. There's got to be a simpler way than creating a long drawn out stored procedure, no?
Answer: CREATE PROC dbo.alldatabasequery
AS

 CREATE TABLE #temp (
 databasename varchar(500),
 name varchar(max),
 address varchar(max),
 company_id varchar(max),
 cost varchar(max)
 )
INSERT INTO #temp
 EXEC sp_MSforeachdb N'IF ''?'' NOT IN ( ''model'',''tempdb'',''master'',''msdb'')
  BEGIN
  SELECT databasename=''?''
    , a.name
    , a.address
    , b.company_id
    , c.part_no
    , c.cost
    FROM ?.dbo.accounts a
    JOIN ?.dbo.business b
    on a.whatever = b.whatever
    JOIN ?.crazy c
    ON b.things = c.things
   END' ;

SELECT   * FROM #temp

GO

EXEC dbo.alldatabasequery

Comment: you can skip some databases like  EXEC sp_MSforeachdb N'IF ''?'' NOT IN ( ''model'',''tempdb'',''master'',''msdb'')
BEGIN
    select ''?''
END'

;
Comment: I have attempted the EXEC sp_MSforeachdb without success previously... while it pulls all data it also pulls data into different result grids, wherein I need them all in one grid.  I will try this though.
Comment: create a temp table  and then insert into it , then select from that temp table
Comment: Ok, how do you insert into a temp table from executing a Stored Proc?
Comment: hi take a luk and let me knw any issues, make sure datatypes are rgt with your system
Comment: Thanks Kumar, but that's the issue, I wrote my script almost identically to yours, but recieved an error 'Incorrect syntax near 'master'.'.  Same with the other tables we excluded in the NOT IN clause.
Comment: ohoo  i forgot to write  ?.crazy   question mark on  crazy table i edited the script may be thats the error
Comment: I'm getting a Msg 102, Level 15, State 1, Line 34
Incorrect syntax near '.'.   I've isolated the issue to the SELECT statement within the EXEC sp_MSforEachDb section.  All other parts work, so I suppose there's in my script, but I can't find it.  I'd post the script but it's a bit lengthy and I've had trouble posting codes in comments.  I think I'm good though.
Comment: post ur script on question section
Comment: The code is too long... I'm unable to post it in this comment.
Comment: try my second answer with cursor
Comment: post your script in ur question section  means  edit ur question and post ur entire script
Comment: Does this copy the values in the temp table or reference them?
Answer: try this one
CREATE TABLE #temp (
 databasename varchar(500),
 name varchar(max),
 address varchar(max),
 company_id varchar(max),
 cost varchar(max)
 )

DECLARE @statement varchar(max)=''

     declare cur cursor FOR
 select name
   from master.dbo.sysdatabases
  where dbid >4

      open cur

 DECLARE @name  VARCHAR(8000)

      fetch next from cur into @name

      while @@fetch_status = 0

      begin

   SET @statement='SELECT databasename='''+@name+''', a.name
    , a.address
    , b.company_id
    , c.part_no
    , c.cost
    FROM '+@name+'.dbo.accounts a
    JOIN '+@name+'.dbo.business b
    on a.whatever = b.whatever
    JOIN '+@name+'.crazy c
    ON b.things = c.things'

  INSERT INTO #temp
  EXEC (@statement)
   fetch next from cur into @name
     end
    close cur
    deallocate cur

SELECT   * FROM #temp

Comment: Dynamic SQL runs pretty efficiently these days, it's not as fast as raw sql, but this is very readable and maintainable. You should ditch the `FETCH`. Just use `SELECT @sql = @sql + 'select * FROM [' name + '].dbo.[Table]' + char(13) FROM sys.databases`. Each record will be appended to the variable. You can also `exec sp_executesql @sql`to fire it instead of just having an sp that generates a script.

Query tables across multiple databases


Exibir valor de um item do objeto utilizando Javascript

Question: Sou iniciante em Javascript, não sei como exibir o valor qtdeEstoque da listaTamanhos. Alguém pode me ajudar?
alert("Tamanho: " + lista.Value + " / Estoque: " + data[i].qtdeEstoque);

listaTamanhos:
id
qtdeEstoque

Controller:
if (HttpContext.Request.IsAjaxRequest())
{
    return Json(new SelectList(
                listaTamanhos,
                "id",
                "id"), JsonRequestBehavior.AllowGet
                );
}

View:
$.getJSON("/produto", { id: id, cor: idSelected }, function (data) {
   $.each(data, function (i, lista) {
      alert("Tamanho: " + lista.Value + " / Estoque: " + data[i].qtdeEstoque);
   });
});

Comment: exibir onde? você ja tem alguma tabela e quer preencher ela? você quer criar um do zero?
Comment: Guilherme, eu gostaria de exibir a qtdeEstoque em uma mensagem JavaScript. Ela está em uma lista, já vem da tabela.
Comment: var listaTamanhos = tamanho.ListarTodosByProduto(id);    Eu não sei como acessar o atributo qtdeEstoque dessa lista em Javascript. Estou retornando via Json return Json(new SelectList(
                listaTamanhos,
                "id",
                "id"), JsonRequestBehavior.AllowGet
                );
Comment: Note que você esta com `(new SelectList(listaTamanhos, "id", "id"), JsonRequestBehavior.AllowGet);` não seria `(new SelectList(listaTamanhos, "id", ` **"qtdeEstoque"** `), JsonRequestBehavior.AllowGet);`?
Comment: Você chegou a debugar e ver se existe `data[i].qtdeEstoque` porque pelo que você disse não.
Comment: não seria, retorno (new SelectList(listaTamanhos, "id", "id"), JsonRequestBehavior.AllowGet), porque vou montar em html um select em html. E o ID é o value que é o mesmo da DESCRIÇÃO. Veja:
--Selecione o tamanho--
35/36
37/38
39/40
</sel
Comment: preciso acessar o primeiro parâmetro do método SelectList(listaTamanhos, "id", "id")....listaTamanhos que tem o atributo qtdeEstoque
Comment: no Visual Studio não sei debugar o código Javascript, somente no Controller e na View códigos C#. Vi em debug que o atributo qtdeEstoque da listaTamanhos está sendo preenchida corretamente no Controller. Falta agora eu acessar no Javascript. Só que preciso naquele código que postei.
Answer: $.getJSON("/produto", { id: id, cor: idSelected }, function (data) {
   $.each(data, function (i, lista) {
      alert("Tamanho: " + lista["id"]+ " / Estoque: " + lista["qtdeEstoque"];
   });
});

Comment: Pedro, fiz assim porém não funcionou. Retorna "undefined"..Agora, fazendo assim alert("Tamanho: " + lista.Value + " / Estoque: " + lista["qtdeEstoque"]); O tamanho retorna correto e o estoque "undefined"
Comment: Passa pra mim ai o json
Comment: var listaTamanhos = tamanho.ListarTodos(id);

if (HttpContext.Request.IsAjaxRequest())
{
    return Json(new SelectList(
                    listaTamanhos,
                    "id",
                    "id"), JsonRequestBehavior.AllowGet
                    );
}


Proper way to restore a default contextmenu for an edit control?

Question: I'm in a situation where I want to decide whether to disable or enable the default edit contextmenu of a subclassed TextBox control, I've written this:
Public Property DisableEditMenu As Boolean = False

'''
''' Raises the <see cref="E:System.Windows.Forms.Control.Enter"/> event.
'''
''' <param name="e">An <see cref="T:System.EventArgs"/> that contains the event data.</param>
Protected Overrides Sub OnEnter(e As EventArgs)

    If Me.DisableEditMenu AndAlso MyBase.ContextMenuStrip Is Nothing Then
        ' Disable Copy/Cut/Paste contextmenu by creating a new empty one.
        MyBase.ContextMenuStrip = New ContextMenuStrip

    ElseIf Not Me.DisableEditMenu Then
        ' Restore default edit contextmenu...

    End If

    MyBase.OnEnter(e)

End Sub

The problem is... how I can restore the default contextmenu?
I've thinked about to solve it in this way, and it works ok, but I'm not sure if I'm being efficient or I'm doing unnecesary things than what i really should do to restore the default menu:
...
ElseIf Not Me.DisableEditMenu Then
    ' Restore default edit contextmenu...
    Using tb As New TextBox
        MyBase.ContextMenuStrip = tb.ContextMenuStrip
    End Using
...

Because .Net Framework Class Library provides a reference for default values, such as default control colors (eg: TextBox.DefaultBackColor), then maybe a default edit contextmenu is contained/referred in some Type that I didn't discovered yet? or to restore it efficientlly is more hard than I imagine?
Answer: To "restore the default contextmenu", set the ContextMenuStrip property to null.
Me.ContextMenuStrip = Nothing

However, there's no need to set the ContextMenu to a new empty instance. All you have to do is to suppress the WM_CONTEXTMENU message. MSDN describes this message as:

Notifies a window that the user clicked the right mouse button (right-clicked) in the window.

Public Class UITextBox
    Inherits TextBox

    Public Property DisableEditMenu As Boolean

    Protected Overrides Sub WndProc(ByRef m As Message)
        If ((m.Msg = WM_CONTEXTMENU) AndAlso Me.DisableEditMenu) Then
            Exit Sub
        Else
            MyBase.WndProc(m)
        End If

    End Sub

    Private Const WM_CONTEXTMENU As Integer = 123

End Class

Comment: Thanks, I know the alternatives, but I use my way on that to avoid unnecessary windows message interception and processing to don't charge the control with much more operations than what it really needs (I'm in some way a performance obsessive but anyways I'm not any expert on performance). I only would like to know the answer of the question that I did, but really thankyou anyways to try to help me!
Comment: But my intention is to restore it after I set to Nothing the contextmenu! :-/, thanks for comment.
Comment: Huh? The default menu will be used if you set the `ContextMenuStrip` property to null. Isn't that what you want?
Comment: yes, i understood bad your last comment I thinked that you mean set it to Nothing to disable it not to re-enable it, sorry was my fault!


How to use nodemailer with claudia-api-builder

Question: I am trying to create a simple REST API I can post an email to, to then email myself. I am using nodemailer and had set it up as an express app and it all worked fine confirming my authentication etc. is fine. I wanted to host it online so I have used claudia.js to create a lambda and API gateway setup but this seems to have broken it.
The Code
const nodemailer = require('nodemailer');
const secrets = require('./secret');
const apiBuilder = require('claudia-api-builder');

api = new apiBuilder();
module.exports = api;

var mailOptions;
var logMsg = "none";

api.post('/email', async (req, res) => {
  mailOptions = {
    from: secrets.email,
    to: secrets.email,
    subject: 'Email From: ' + req.body.senderEmail + ' | ' + req.body.subject,
    text: req.body.content,
  };
  sendMail(mailOptions);
  return logMsg;
})

const transporter = nodemailer.createTransport({
  service: 'gmail',
  auth: {
    user: secrets.email,
    pass: secrets.pwd
  }
});

function sendMail(mailOptions) {
  logMsg="Starting Send Function";
  transporter.sendMail(mailOptions, function (error, info) {
    if (error) {
      logMsg = error;
      return error;
    } else {
      logMsg = "Send Complete";
      return true;
    }
  });
  logMsg="Function finished";
}

When I debug via postman, by posting a raw JSON
{
    "senderEmail": "test2",
    "subject": "test",
    "content":"test"
}

I receive "Function Finished" Which I dont really see how it is possible as surely the if or else should've fired under transporter.sendMail(..., returning from the function. I also don't receive an email which is my end goal
Answer: I had the same problem until I started returning the transporter
return transporter.sendMail(mailOptions)
  .then(info => {
    console.log('email sent: ', info)
    return {'status': 'OK'}
  })
  .catch(err => {
    console.log('email error: ', err)
    return {'status': 'ERROR'}
  })


Auto-renewing google play subscription price increase - effect on existing users?

Question: I have a few auto-renewing subscriptions I wish to increase the price of without affecting existing subscribers. As in, I wanted existing subscribers to continue renewing at their current price, and new subscribers to be shown the new prices.
Example subscription I want to change
However I'm a bit unclear on google's documentation about subscription price increases https://developer.android.com/google/play/billing/subscriptions#price-change
It states Users currently subscribed to auto-renewing plans are not affected by default. Instead, a legacy price cohort is created...
This makes me think that all is good for my case since I think these are auto-renewing subscriptions. But then it goes on to describe in detail how existing customers will be notified and will be presented with the price change, which is confusing
I started digging around and found these posts, all of which state that existing customers will be charged the new price.
Google Play: Keep old subscription price for current subscriptions?
Change price of subscription product in android app
Android Billing: changing the price of a subscription
Some therefore recommend to create a new subscription item for new users and keep the existing subscription unchanged for existing users in order to get the effect I wish above
So which is it? If I change the price of my auto-renewing subscription, will my existing customers remain on the previous price, or will they be notified and presented with the choice of ending the subscription?
Thanks!
Answer: When you change the price, a legacy price cohort will be created and all of your existing subscribers will be placed in that bucket. They will continue to pay the old price unless you explicitly open the Play Developer Console and migrate the legacy price cohort to the new base plan price.
This document outlines the process


Can't access Port 80 from external

Question: I have configuration like this: NETGEAR MODEM > LINKSYS ROUTER > SERVERS
In the modem, I've setup as bridging and all the traffic is controlling by this ROUTER. Prior to this setup, I can access website from external (port 80) plus exchange servers (mail) and https.
But now with this configuration, I can only send/receive using Exhcange servers and access OWA (Outlook web access using port 443) .... and no internal websites from outside.
This is my config for LINKSYS ROUTER
|--------------------------------------------------------------|
| Application | Start | End | Protocol        | IP Address     |
|--------------------------------------------------------------|
| Ms Exchange | 25    | 25  | Both (TCP/UDP)  | 192.168.100.8  |
| Internets   | 80    | 80  | Both (TCP/UDP) | 192.168.100.11 |
| SSL         | 443   | 443 | Both (TCP/UDP)  | 192.168.100.8  |
| Exchange    | 110   | 110 | Both (TCP/UDP)  | 192.168.100.8  |
|--------------------------------------------------------------|

192.168.100.11 is an Ubuntu web server that running the apache which controlling the virtual name (extranet, cms, test) to redirect to the different servers. As you can see, the home internet is only allowing public IP address.
Now I test this schenarion in internal network work nicely. For instance. If I type in extranet.XXX.local it goes to the right applicatios or if I try MS.XXX.local again it goes to the right one.
I also asked to ISP just in case if they are blocking the inbound port 80 for unknown reason. They said no.
So I didn't understand why this happens. I suspect the configuration that I have between MODEM > ROUTER but I couldn't work what it is. I don't have a documentation of previous settings and I don't know if there is a port that I need to open as well.
I am appreciated your comment
Comment: I suggest you close those UDP ports, as they're not required.
Answer: Is the default gateway the same on the ubuntu box and the exchange box?
The *.local will not be addressable from "outside", I assume you are using another domain name externally, will this not play havoc with your virtual hosts? (expecting *.local getting *.corp.com will break functionality, but you should get some response)
Answer: you say you are using virtual servers on apache, none of these will be visible from the outside world unless the virtual server name, is listed on the public dns and has an "a record" pointing at your router.
If you want to access your server using an IP address from the outside world, you must setup the default server on apache.
Comment: More detail would improve your answer.

Can't access Port 80 from external


LEFT JOIN SUBQUERY

Question: Olá, estou com uma pequena dúvida sobre SQL já que não entendo nada sobre isso.Tenho uma tabela onde estou fazendo um select para ver as atualizações com uma subquery e faço um LEFT JOIN qui está o código:
SELECT a.id, a.nome,
(SELECT COUNT(c.id) FROM postagens as c WHERE c.data_cadastro >
b.data_acesso AND c.id_categoria = a.id AND deletado = 0) as atualizacoes
FROM postagens_categorias as a
LEFT JOIN postagens_categorias_view as b ON a.id = b.id_categoria
WHERE a.deletado =0 AND a.id != 3 ORDER BY a.nome DESC

E dá este resultado aqui:

Os dados que eu gostaria seria:
Projetos   25
Estágios   24
Divulgação 21

Acredito que deveria usar um GROUP BY em algum lugar, se eu usar o DISTINCT no começo ele continua duplicando os valores só que no lugar de NULL, 0.
Aqui está a tabela de postagens_categorias:

Postagens_categorias_view:

Postagens:

Como faço essa parte?
Comment: já tentou com distinct e group by na coluna atualizacoes?
Comment: Acredito que tens que fazer com o INNER JOIN.
Comment: Detalhe suas tabelas na pergunta, facilitará o nosso entendimento do problema para dar uma possível resposta. Com o código que você colocou, suponho que seja mais interessante você tirar o subselect e fazer um group by.
Answer: Pelo que eu entendi do seu problema, a solução é a seguinte:
SELECT a.id, a.nome, count(d.id_categoria) as atualizacoes
FROM postagens_categorias as a
    LEFT JOIN (SELECT id_categoria from postagens_categorias_view b
                INNER JOIN postagens c
                    ON c.id_categoria = b.id_categoria
                WHERE c.deletado = 0 AND
                    c.data_cadastro > b.data_acesso
              ) d
        ON a.id = d.id_categoria
WHERE a.deletado = 0 AND
    a.id != 3
GROUP BY a.id, a.nome
ORDER BY a.nome DESC

Comment: Ficou bem perto do que eu queria, o único problema é que esse não retorna nada quando não tem nenhuma atualização, no caso eu preciso que retorne 0, exemplo : Projetos 0, Estágios 24 e Divulgação 0
Comment: Essa informação de atualização fica em `postagens_categorias_view` ou em `postagens`? Na tabela que essa informação estiver, você usará o `left join`. Por isso é interessante você colocar na sua pergunta a definição das tabelas, facilita o entendimento.
Comment: Blz, melhorei ali para o entendimento colocando as outras tabelas faltantes. A ideia é quando tiver postagem nova ela "categoriza" em qual das áreas e separa cada categoria com as suas atualizações.
Comment: Alterei a resposta. Como pode haver `postagens_categorias` sem registro em `postagens_categorias_view`, nem em `postagens` é necessário que seja left join em ambas as junções para que os registros em `postagens_categorias` apareçam. Alterei o `count(*)`, por `count(c.*)`, estou na dúvida se funcionará, por favor faça o teste. Espero que funcione.
Comment: Infelizmente não funcionou, deu essa mensagem:

#1064 - Você tem um erro de sintaxe no seu SQL próximo a '*) as atualizacoes
FROM postagens_categorias as a
    LEFT JOIN postagens_cat' na linha 1
Comment: Você usando left Join e o count(*) dá certo? Aparece a resposta que deseja?
Comment: Aparece mais ou menos a resposta, pois mostra somente as categorias com atualizações e as sem atualizações não aparece.
Comment: Então, @MarcosSchneider conservei com um amigo e ele propôs essa consulta que coloquei na resposta, por favor teste aí.
Comment: A explicação para a outra solução não funcionar está aqui https://stackoverflow.com/a/10949318/9916784 , como eu tinha colocado na cláusula `where` campos que faziam parte da tabela que foi juntada com `left join`, quando vinha `NULL` ele excluía a linha para realizar o count, por isso não aparecia.
Answer: Tente usar Isnull (quando for null substitui zero) se não der certo, coloca CASE
SELECT a.id, a.nome, isnull(count(*),0) atualizacoes
FROM postagens_categorias as a
    LEFT JOIN postagens_categorias_view as b ON a.id = b.id_categoria
    LEFT JOIN postagens as c on c.id_categoria = a.id
WHERE a.deletado = 0 AND
    c.deletado = 0 AND
    a.id != 3 AND
    c.data_cadastro > b.data_acesso
GROUP BY a.id, a.nome
ORDER BY a.nome DESC

Answer: Se o filtro do seu select estiver certo, o código pode ser esse aqui:
SELECT T.ID,
       T.NOME,
       T.ATUALIZACOES
FROM (
SELECT A.ID,
       A.NOME,
       (SELECT COUNT(C.ID)
        FROM   POSTAGENS AS C
        WHERE  C.DATA_CADASTRO > B.DATA_ACESSO
        AND    C.ID_CATEGORIA = A.ID
        AND    DELETADO = 0) AS ATUALIZACOES
FROM   POSTAGENS_CATEGORIAS AS A
LEFT   JOIN POSTAGENS_CATEGORIAS_VIEW AS B
ON     A.ID = B.ID_CATEGORIA
WHERE  A.DELETADO = 0
AND    A.ID != 3
GROUP BY A.ID,
         A.NOME) T
ORDER BY T.NOME DESC

LEFT JOIN SUBQUERY


Apache reverse proxy backend authentication

Question: I've setup apache reverse proxy for my application with ldap authentication.
The problem is that the backend application also requires authentication.
After I entered ldap credentials, it always returns 401 and doesn't prompt for the application authentication.
The backend uses different credentials.
Answer: Assuming that the backend-server uses the very same LDAP authentication as the frontend you might want to have a look env var proxy-chain-auth in docs for mod_proxy_http.
Comment: No. The backend uses different credentials
Comment: Is it a static backend credential? You should provide such details in your question.
Comment: Yes, I did mention that in the question. And yes, it is static credentials


Azure Container App fails to start due to volumeMount config

Question: I'm stuck with an issue I have trying to setup persistent file-storage for a Container App in the Azure cloud. I'm followed this tutorial: https://learn.microsoft.com/en-us/azure/container-apps/storage-mounts-azure-files?tabs=bash
My problem is in "Create the storage mount" point 9: I updated the app.yaml and I run the command to create a new revision. It succeeds in the terminal, but in the Revisions list on the Azure page, the new revision fails to start. It's execution status is "faulty" but it does not provide any details what failed.
Only in the system log, I once got an error message without error code just saying the storagemount failed - no reason given.
This are the parts of my app.yml I edited:
...
  template:
    containers:
    - image: nginx
      name: trendy-app
      resources:
        cpu: 0.5
        ephemeralStorage: 2Gi
        memory: 1Gi
      volumeMounts:
      - volumeName: trendy-file-volume
        mountPath: /var/log/nginx
    initContainers: null
    revisionSuffix: ''
    scale:
      maxReplicas: 1
      minReplicas: 1
      rules: null
    serviceBinds: null
    terminationGracePeriodSeconds: null
    volumes:
    - name: trendy-file-volume
      storageName: trendystoragemount
      storageType: AzureFile
    - name: trendy-app
      storageType: EmptyDir
  workloadProfileName: Consumption
...

When I remove the configuration lines for the volumeMounts, the container starts as expected - just without the mounted storage obviously. When I add it, but use a non-existing name, the az containerapp update command fails with a meaningful error, that the mount does not exist. With the config about, the command runs, but startup of the container fails. So yeah, something is wrong on the config of the storage volume, but I don't know how to find out what.
I checked the names and tried re-running the commands in the tutorial, but did not find my mistake. At this point I'm stuck and need help how I can debug this.
Thank you,
Dahie
Answer: I think your app.yml is incorrect please check the logs, but it should look something like this (for example).
name: nginx-azure-app
location: eastus
resourceGroup: myResourceGroup
containerName: nginx-container
cpu: 0.5
memory: 0.5Gi
instanceCount: 1

services:
- name: nginx-service
  image: nginx
  ports:
    - protocol: TCP
      port: 80
  volumeMounts:
    - name: nginx-volume
      mountPath: /usr/share/nginx/html
    - name: nginx-logs
      mountPath: /var/log/nginx

volumes:
- name: nginx-volume
  storageName: mystorageshare
  storageType: AzureFile
  shareName: myshare
  readOnly: false
  secretName: mystoragesecret
  secretMountPath: /mnt/azure

- name: nginx-logs
  storageName: mystorageshare
  storageType: AzureFile
  shareName: myshare
  readOnly: false
  secretName: mystoragesecret
  secretMountPath: /mnt/azure-logs

secrets:
- name: mystoragesecret
  storageAccount: mystorageaccount
  shareName: myshare
  accessKey: mystorageaccesskey


wxpython : how to open a Dialog directly from the MenuBar

Question: I'm trying to find a method to open a wx.Dialog from a MenuBar without klicking a MenuEntry first.
Example:

class Custom_MenuBar(wx.MenuBar):
    def __init__(self, parent, style=0):
        wx.MenuBar.__init__(self, style)

        # About-Menu
        aboutmenu = wx.Menu()
        about_id = wx.Window.NewControlId()
        aboutmenu.Append(about_id, "&About", "show About-Menu")
        self.Bind(wx.EVT_MENU, self._about, id=about_id)
        self.Append(aboutmenu, "About Menu")

        # Menubar aktivieren
        parent.SetMenuBar(self)

    def _about(self, _event):
        wx.adv.AboutBox(wx.adv.AboutDialogInfo())

This example (with a frame as parent) shows a MenuBar with an entry "About Menu".
Clicking on this entry shows a MenuItem called "About", and finally clicking on "About" opens the AboutBox.
I want to spare clicking onto the MenuItem, instead open the AboutBox directly when activating the "About Menu".
An idea was to derive from wx.Menu, but as wx.Menu does not inherit from wx.Window, I do not find an Id to Bind to.
My question is: what happens from the event point of view when an entry ("About Menu") is clicked in the MenuBar; then opening a Menu? Is there a possibility to interfere there? Any other idea?
PS: using python 3.8.0 and wxPython 4.0.7.post2
Answer: You have options, depending on exactly what you want to achieve.
Using the menu event options you can use the menu's Id or the text if there is no Id ( menu open ).
The following shows the most obvious options.
import wx
import wx.stc
import wx.adv
class MyApp(wx.App):
    def OnInit(self):
        self.frame = MenuFrame(None, title="Menu Dialogue")
        self.SetTopWindow(self.frame)
        self.frame.Show()

        return True

class MenuFrame(wx.Frame):
    def __init__(self, *args, **kwargs):
        super(MenuFrame, self).__init__(*args, **kwargs)

        # Attributes
        self.panel = wx.Panel(self)
        self.txtctrl = wx.stc.StyledTextCtrl(self.panel,
                                   style=wx.TE_MULTILINE)

        # Layout
        sizer = wx.BoxSizer(wx.HORIZONTAL)
        sizer.Add(self.txtctrl, 1, wx.EXPAND)
        self.panel.SetSizer(sizer)
        self.CreateStatusBar() # For output display

        # Setup the Menu
        menu = wx.MenuBar()

        # File Menu
        filem = wx.Menu()
        filem.Append(wx.ID_NEW, "New")
        filem.Append(wx.ID_OPEN, "Open")
        filem.Append(wx.ID_SAVE, "Save")
        filem.Append(wx.ID_SAVEAS, "Save_As")
        menu.Append(filem, "&File")

        # About Menu
        aboutm = wx.Menu()
        self.about_id = wx.NewIdRef()
        aboutm.Append(self.about_id, "&About Info", "Show About-Menu")
        menu.Append(aboutm,"&About")

        self.SetMenuBar(menu)

        # Event Handlers
        self.Bind(wx.EVT_MENU, self.OnMenu)
        self.Bind(wx.EVT_MENU_OPEN, self.OnMenuOpen)
        self.Bind(wx.EVT_MENU_HIGHLIGHT, self.OnMenuHighlight)

    def OnMenu(self, event):
        evt_id = event.GetId()
        if evt_id == self.about_id:
            info = wx.adv.AboutDialogInfo()
            info.SetDescription("Menu Clicked "+str(evt_id)+" selected\n")
            wx.adv.AboutBox(info)

    def OnMenuOpen(self, event):
        evt_id = event.GetId()
        Dlg = False
        if evt_id == 0:
            obj = event.GetMenu()
            if obj.GetTitle() == "&About":
                Dlg = True
        if Dlg:
            info = wx.adv.AboutDialogInfo()
            info.SetDescription("Menu Opened "+str(evt_id)+" selected\n")
            wx.adv.AboutBox(info)

    def OnMenuHighlight(self, event):
        evt_id = event.GetId()
        if evt_id == self.about_id:
            info = wx.adv.AboutDialogInfo()
            info.SetDescription("Menu Highlight "+str(evt_id)+" selected\n")
            wx.adv.AboutBox(info)

if __name__ == "__main__":
    app = MyApp()
    app.MainLoop()

Comment: One small point I don't understand:
when using your example, if you open a menu with a klick, here "File" menu, without selecting an item, and then move the mouse to the menu managed by EVT_MENU_OPEN, here "About", MenuFrame.OnMenuOpen() is called without a further mouse click.
Why that?
Comment: Because the `MenuBar` has focus, when the cursor moves to `About` that menu opens (drops down), firing the `EVT_MENU_OPEN`, where the `if obj.GetTitle() == "&About"` test is applied. I hope that's clear.
Comment: Also, because the menu opens but no specific menu item is yet selected, there is no event `Id` to check against, thus we check the `Title`.
Comment: What had puzzled me was, that one time a click was needed to bring up the dialog, whereas another time the dialog appeared without click.
With tests according to your explanation I understood that the click was necessary to set the focus; once the MenuBar has the focus, EVT_MENU_OPEN is fired whenever the pointer reaches the "sensivity zone" of any Menu entry.
Unfortunately I found rarely any documentation concerning EVT_MENU_OPEN.


git: undo all changes to my local repository and get a copy of upstream repository

Question: I want to undo all my local changes and update my local machine with the code from git repository.
I have tried resetting the local branch by running the following commands:
git checkout
git reset

When I run git checkout on local machine, it says:

Your branch and 'origin/my-dev-environment' have diverged, and have 1
and 26 different commits each, respectively.   (use "git pull" to
merge the remote branch into yours)

If I try git pull, it would complain about conflicts:

CONFLICT (content): Merge conflict in template/myfile.cs Auto-merging
pages/somefile.html

How can I clear all changes from my local repository and just get a copy of upsteam repository?
Answer: This is explained here: Reset local repository branch to be just like remote repository HEAD
git fetch origin
git reset --hard origin/master


Javascript para o Angular

Question: Pessoal sou meio novo no Angular, alguém poderia me ajudar a converter esse código em javascript para angular.

 window.onload = function(){
  var campo1 = document.getElementById("campo1").value;

  if(campo1 == 0.00){
   document.getElementById("icon").style.display = "none";
  } else {
   document.getElementById("icon").style.display = "block";

  }
 }
<input type="checkbox" name="check" id="checkbox" />
<input type="text" id="campo1" value="0.00" />

Comment: Pesquisa sobre controllers. E na página inicial do Angular você já conseguiria resolver essa dúvida.
Answer:
Vincule o valor de campo1 a uma variável no escopo atual;
use este valor como comparação para via ng-if ou ng-show.

Exemplo funcional a seguir:

function SampleController($scope, $filter) {
  $scope.valor = 0.00;
}

      <input type="text" ng-model="valor" />

Comment: Muito Obrigado, Ajudou muito.
Só fiquei com uma duvida, como faço para pegar um valor fixo do value.
Comment: @DiBoa Sempre um prazer ajudar! Eu não entendi direito, poderia elaborar usa pergunta mais um pouco?
Comment: Então amigo, em meu input já vem um valor no value fixo por exemplo value="10".
Comment: @DiBoa o value sempre será sobrescrito pelo valor do modelo vinculado.
Comment: vlw Deu Certo, também consegui usando o ng-show="".
Answer: Normalmente, você define os valores iniciais para o seu formulário no controller. Desta forma você terá um valor inicial definido quando a aplicação começar.
Veja esse exemplo que eu escrevi: https://jsbin.com/halerewuba/1/edit?html,output

<!DOCTYPE html>

    <meta charset="utf-8">
    <title></title>

      <form>

          Nome:
          <input type="text" ng-model="ctrl.nome">

          Idade:
          <input type="number" ng-model="ctrl.idade">

        <button type="submit">Submit</button>
      </form>

Debug:

          {{ctrl}}

Javascript para o Angular


why am I getting an undefined error?

Question: I'm working on a javascript debugging tool, what I need at the moment is to get the line number off the end of a stack trace. So I wrote the following function to get a stack trace, remove the first few lines and then I was going to use indexOf(':') to get the line number. However I keep getting a "Cannot call method 'substring' of undefined" error. OK that should be an easy one to fix, but wait a minute - console.log suggest the file is defined. Can someone explain where I'm going wrong.
code:
var getLine = function () {
    var stack = (new Error('dummy').stack).toString();
    var stackLines = stack.split('\n');
    stackLines = stackLines.filter(function (element) {
        var exclude = [ "Error: dummy", "graph.js" ];
        for (var i = 0; i < exclude.length; i++) {
            if (element.indexOf(exclude[i]) !== -1) {
                return false;
            }
        }
        return true;
    });

    console.log("1 array", stackLines);
    console.log("2 element", stackLines[0]);
    console.log("3 typeof element", typeof (stackLines[0]));
    console.log("4 huh?", stackLines[0].substring(1));
}

output:
1 array [ '    at Object.<anonymous> (E:\\Development\\james\\main.js:52:18)',
  '    at Module._compile (module.js:456:26)' ]
2 element     at Object.<anonymous> (E:\Development\james\main.js:52:18)
3 typeof element string
E:\Development\james\graph.js:47
    console.log("huh?", stackLines[0].substring(1));
                                      ^
TypeError: Cannot call method 'substring' of undefined

the even stanger thing is - if i wrap the console.log statements in a try/catch then it executes without error?
code:
var getLine = function () {
    var stack = (new Error('dummy').stack).toString();
    var stackLines = stack.split('\n');
    stackLines = stackLines.filter(function (element) {
        var exclude = [ "Error: dummy", "graph.js" ];
        for (var i = 0; i < exclude.length; i++) {
            if (element.indexOf(exclude[i]) !== -1) {
                return false;
            }
        }
        return true;
    });
    try {
        console.log("array", stackLines);
        console.log("element", stackLines[0]);
        console.log("typeof element", typeof (stackLines[0]));
        console.log("huh?", stackLines[0].substring(stackLines[0].indexOf(":")));
    } catch (e){
        console.log("error",e);
    }

output:
1 array [ '    at Object.<anonymous> (E:\\Development\\james\\main.js:52:18)',
  '    at Module._compile (module.js:456:26)' ]
2 element     at Object.<anonymous> (E:\Development\james\main.js:52:18)
3 typeof element string
4 huh? :\Development\james\main.js:52:18)

I feel like I'm missing something very very obvious, but I'm not seeing it!
Comment: This works just fine: http://jsfiddle.net/55ym1xmj/2/
Comment: So is this your actual code, or did you tweak some stuff here to make the example smaller? Because otherwise in your "real" code there may be some kind of race condition.
Comment: Which browser are you using. Stack is a non-standard property of Error. see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error/stack
Comment: @Haim — The question is tagged `node.js` so, presumably, no browser at all.
Comment: @JamesG — It would help if you provided sufficient code to reproduce the problem (i.e. test data and a call to your function).
Comment: @vrjdenker - that is the original codein unmodified form.
Comment: @Haim - no browser running in node.js
Comment: @Quentin - trying to isolate the minimum amount of code to reproduce, I didn't realise just calling this function isn't enough to make it fault.
Comment: I still find it very strange that just adding a try/catch fixes the problem especially as the catch is never called - can anyone provide a theoretical answer as to why wrapping something in a try catch would prevent the error occurring?
Answer: OK I got to the bottom of it, as I suspected there was a simple explanation:
The function was being called multiple times, the first time stackLines[0] was defined however one of the later times it was undefined. The confusing part is the error was being thrown before the console.logs were being printed.
So the first time it was called all the log statements would work, but none of them were actually output before it through an error in one of the subsequent calls.
When I ran it with the try catch I missed the error as there was a bunch of output and I was scrolling to the top and only checking the first one.
Thanks for the responses everyone :)

why am I getting an undefined error?


Calculate $1434661\cdot 3785648743-10020304\cdot 54300201$

Question: I'm working in the following chinese's remainder theorem exercise:

Calculate
  $$1434661\cdot 3785648743-10020304\cdot 54300201$$
  You are told that the answer is a positive integer less than $90$. Compute
  the answer ${\mod 10}$ and ${\mod 9}$, then combine to get the answer.

I've planned a system based on the criterion that the answer is less than $90$ with $d = 1434661*3785648743-10020304*54300201$:
$$\begin{cases}d \equiv 9\pmod{10}\\
d \equiv x \pmod{9}\end{cases}$$
But I'm not sure about the system to be correct, any help will be really appreciated.
Comment: *"You are told that the answer is a positive integer less than 90"* – actually, that is not true.
Comment: It is if you compute it mod 90 - noted in the title of the post but not in the actual question.
Comment: As Martin points out the answer is actually $4887018090000019$ which is *not* a positive integer less than 90.  Whoever whatever the answer is, it is a legitimate question to simply ask "what is the positive remainder when you divide the answer by $90$?".
Answer: Well, you were told what to do so ... do it.
$$1434661\equiv 1 \pmod {10};⋅3785648743\equiv 3\pmod{10};$$
$$ 10020304\equiv 4\pmod{10}; ⋅54300201\equiv 1\pmod {10}.$$
So $$1434661⋅3785648743−10020304⋅54300201 \equiv 1\cdot 3-4\cdot 1\equiv -1\equiv 9 \pmod{10}.$$
And using the sum of digits for multiples of $9$ rule:
$$1434661\equiv1+4+3+4+6+6+1 \equiv  25\equiv 2+5 \equiv 7 \pmod {9};$$
$$3785648743\equiv 3+7+8+5+6+4+8+7+4+3\equiv 55 \equiv 5+5$$
$$ \equiv 10 \equiv 1\pmod{9}; $$
$$10020304\equiv1+0+0+2+0+3+0+4\equiv 10 \equiv 1\pmod{9}; $$
$$54300201\equiv 5+4+3+0+0+2+0+1\equiv 15 \equiv 1+5 \equiv 6\pmod {9}.$$
So $$1434661⋅3785648743−10020304⋅54300201 \equiv 7\cdot 1-1\cdot 6\equiv 1 \pmod{9}.$$
So there is a unique $0\le x < 90$ so that  $x \equiv -1 \pmod {10}$ and $x \equiv 1 \pmod {9}$.
$x = 9,19,29, .....,$ or $ 89$ and $x = 1, 10 ,19,28,....., $ or $82,$
so $x = 19$.
So $1434661⋅3785648743−10020304⋅54300201\equiv 19 \pmod {90}.$
Answer: Simple calculations show that $\,\color{#0a0}{d\equiv -1}\pmod{\!10}\, $ and $\,d\equiv\color{#c00} 1\pmod{\!9}\,$ by casting nines, hence
$\,\ 10\mid \color{#0a0}{d\!+\!1}\,\Rightarrow\, d\!+\!1\bmod 90 = 10\left[\dfrac{d+1}{10}\bmod 9\right]$ $ = 10\left[\dfrac{\color{#c00}1+1}{1}\bmod 9\right] = 10[2]\,$ $\Rightarrow\, d = 19$


Properly override template_preprocess_book_navigation function in Drupal 8 Book module

Question: I'm trying to find what is the proper way to override the template_preprocess_book_navigation function from the Drupal 8's core Book module. I want to add only two lines (bolded), but don't know how this should be done in "Drupal 8 way". Should I create a custom module or add something in the mytheme.theme file?
Thank you and be healthy!

function template_preprocess_book_navigation(&$variables) {
  $book_link = $variables['book_link'];

  // Provide extra variables for themers. Not needed by default.
  $variables['book_id'] = $book_link['bid'];
  $variables['book_title'] = $book_link['link_title'];
  $variables['book_url'] = Url::fromRoute('entity.node.canonical', ['node' => $book_link['bid']])->toString();
  $variables['current_depth'] = $book_link['depth'];
  $variables['tree'] = '';

  /** @var \Drupal\book\BookOutline $book_outline */
  $book_outline = \Drupal::service('book.outline');

  if ($book_link['nid']) {
    $variables['tree'] = $book_outline->childrenLinks($book_link);

    $build = [];

    if ($prev = $book_outline->prevLink($book_link)) {
      $prev_href = Url::fromRoute('entity.node.canonical', ['node' => $prev['nid']])->toString();
      $build['#attached']['html_head_link'][][] = [
        'rel' => 'prev',
        'href' => $prev_href,
      ];
      $variables['prev_url'] = $prev_href;
      $variables['prev_title'] = $prev['title'];
    }

    /** @var \Drupal\book\BookManagerInterface $book_manager */
    $book_manager = \Drupal::service('book.manager');
    if ($book_link['pid'] && $parent = $book_manager->loadBookLink($book_link['pid'])) {
      $parent_href = Url::fromRoute('entity.node.canonical', ['node' => $book_link['pid']])->toString();
      $build['#attached']['html_head_link'][][] = [
        'rel' => 'up',
        'href' => $parent_href,
      ];
      $variables['parent_url'] = $parent_href;
      $variables['parent_title'] = $parent['title'];
      $variables['prev_depth'] = $prev['depth'];
    }

    if ($next = $book_outline->nextLink($book_link)) {
      $next_href = Url::fromRoute('entity.node.canonical', ['node' => $next['nid']])->toString();
      $build['#attached']['html_head_link'][][] = [
        'rel' => 'next',
        'href' => $next_href,
      ];
      $variables['next_url'] = $next_href;
      $variables['next_title'] = $next['title'];
      $variables['next_depth'] = $next['depth'];
    }
  }

  if (!empty($build)) {
    \Drupal::service('renderer')->render($build);
  }

  $variables['has_links'] = FALSE;
  // Link variables to filter for values and set state of the flag variable.
  $links = ['prev_url', 'prev_title', 'parent_url', 'parent_title', 'next_url', 'next_title'];
  foreach ($links as $link) {
    if (isset($variables[$link])) {
      // Flag when there is a value.
      $variables['has_links'] = TRUE;
    }
    else {
      // Set empty to prevent notices.
      $variables[$link] = '';
    }
  }
}
Answer: You can put a template_preprocess() function in a custom module or your theme mytheme.theme file.
It depends on what you want to achieve.
If this preprocess function is specific to the theme (for example, the results are used in a theme template), then you should put it in mytheme.theme.
But, if you put the code in mytheme.theme and then change themes, your book navigation will no longer behave as expected.
So, if the preprocess function does general processing that you might want to use in multiple themes, and it doesn't do anything theme-specific, then it's better to put it in a custom module.  (This is probably your use case.)


Coprime factorization of rational matrix over the polynomial ring

Question: Dear esteemed colleagues,
I have a question regarding the coprime factorization of rational matrices over the polynomial ring. Consider the following rational matrix
$$
R(s) = \begin{pmatrix} \frac{1}{s+1} \\ \frac{1}{s+1} \end{pmatrix},
$$
for which I know a right coprime factorization over the polynomial ring, i.e., $R(s) = N_r(s) D_r^{-1} (s) =  \begin{pmatrix} 1 \\ 1 \end{pmatrix} (s+1)^{-1}$. However, I'm interested in a left coprime factorization, i.e., $R(s) = D_\ell^{-1} (s) N_\ell(s)  $. I have found the following factorization
$$
 D_\ell = (s+1) I_2, \quad \quad N_\ell = \begin{pmatrix} 1 \\ 1 \end{pmatrix},
$$
but it is unfortunately not coprime.
Does there exist a leftcoprime factorization over the polynomial ring for this example?
Does a left AND right coprime factorization over the polynomial ring always exist for general non-square rational matrices?
Thanks.
Answer: I think the Smith-McMillan from will lead to a left coprime factorization, but by observation, we could have
$$
\begin{bmatrix}
s+1&s+1\\
1&-1
\end{bmatrix}^{-1}
\begin{bmatrix}2\\0
\end{bmatrix}=
\begin{bmatrix}
\frac{1}{s+1}\\\frac{1}{s+1}
\end{bmatrix}
$$


Characteristic function on metric spaces

Question: Let $(X,d)$ be a Metric Space and $M \subseteq X$.
In what points is the Characteristic Function  $\chi_M(x): X \longrightarrow\mathbb R:=
\begin{cases}
1 & \text{if } x \in M \\[.2cm]
0 & \text{if } x \notin M
\end{cases} \quad$
continuous?
Answer: Hint. If $x$ belongs to the boundary of $M$ then, by definition of boundary, for all integer $n>0$, there is a point $y_n\in B(x,1/n)\cap M$ and
there is a point $z_n\in B(x,1/n)\cap M^c$. Note that $f(y_n)=1$ and $f(z_n)=0$. Moreover $y_n\to x$, $z_n\to x$. What may we conclude?
What happens if $x$ is not in the boundary of $M$, that is if $x$ is in the interior of $M$ or if $x$ is in the interior of $M^c$?
Comment: This helped me alot thank you
Comment: You are welcome!!


UndefinedVariableError when converting .py file includes lines like df.query("foo=@bar") to .pyd file

Question: I've never used Cython but I need to encrypt my source code.
My questions is, how could I convert python files which include lines like df.query("foo=@bar") to Cython.
How to replicate this error:
foo.py
import pandas as pd
bar=1
df=pd.DataFrame([1,2,3,4,5],columns=['test'])
print(df.query("test==@bar"))

setup.py
from distutils.core import setup
from distutils.extension import Extension
from Cython.Distutils import build_ext
ext_modules = [
    Extension("sample_code",  ["foo.py"]),
]

setup(
    name = 'My Program',
    cmdclass = {'build_ext': build_ext},
    ext_modules = ext_modules
)

then, run python setup.py build_ext --inplace
from sample_code import foo

and I got error:pandas.core.computation.ops.UndefinedVariableError: local variable 'bar' is not defined
Comment: That's not surprising.  `query` has to an `eval` (or equivalent`) to translate the string "test==@bar" into something it can execute.  Without getting into the details, that will be hard, if not impossible, to render in compiled code.
Comment: do you import `foo` to other file ? Then you may need `foo.bar`
Comment: always put full error message (starting at word "Traceback") in question (not comment) as text (not screenshot). There are other useful information.
Comment: @hapulj Thanks for your explaination. I appreciate it.
Comment: @furas That would cost ~100 lines lol so I only gave a small demo to replicate this error.
Answer: As @hpaulj says in the comments: @bar isn't going to work because it uses Python introspection mechanisms to look up the dictionary of the caller. Cython doesn't generate the information.
Based on the documentation for DataFrame.Eval you can pass the keyword arguments locals_dict or globals_dict. So you could do either:
df.query("test==@bar", locals_dict={'bar': bar})

or
df.query("test==@bar", locals_dict=locals())

It's worth emphasising that simply putting this in a Cython file offers no performance advantages. The performance will be determined by the performance of Pandas, and the fact that you've compiled the file that calls Pandas makes no difference at all.
It also offers limited "encryption" advantages in your case - the string "test==@bar" will definitely be findable in your compiled Cython file.
Comment: Thanks a lot, David. I appreciate your help and your kindly suggestions. I understand those strings would keep unchanged even in .exe/pyd files. In fact, this simple "encryption" make it easier to write a new program other than decompile mine. And that's all I need.


Avoiding spam filters on my CentOS 5.5 64bit server?

Question: I run a social network on my web server, with about 15,000 members right now. My administration section let's me Mass Email all my users. Currently it uses the built in PHP mail function.
What is the best way to congfigure my server to bypass spam? Can I install anything on the server? Or should I just make the social network use SMTP? The admin panel lets me choose SMTP or built-in mail function.
I'm not to familiar with mailing from servers, as I usually use Aweber for my mailing, but I cannot use Aweber for this as they will not let me just import 15,000 emails.
Let me know, thanks.
Answer: If it were a simple matter of flipping some switches to keep from being classified as spam, spammers wouldn't have any trouble whatsoever getting through spam filters.
The biggest things you can do...
Make sure you are sending actual email. No fake headers, no CC's to dozens of people unrelated to the person you're sending to, etc.
Keep the message simple. No fancy formatting or turning out web pages as email. Anything that smacks of advertising will up your spam scores in most spam filters, and the more prettified the text the more likely it'll trip filter scores.
Configure SPF and make sure your mail server isn't obscured behind multiple routes or anything that can make it look dodgy when being reverse look-upped.
Have instructions for your users so they know what to look for; if they have their own filters this will help with white-listing.
Have an opt-in list so you're not sending emails to these users unless they want it.
Does your social site have its own built-in messaging? It might make sense to encourage people to use the in-system messaging rather than email. Email should at most be an adjunct to the goal of bringing people into the site and using the site.
There's nothing you can really do to prevent being classified for spam except make the messages legit and don't tick off your users; someone may forward it to the wrong places and you'll end up in an RBL. Only send messages to people who want it. Take a note from Facebook's page...their notifications that I opted into are a simple "hello! Here's a message from XYZ, click the link to view the thread!" I don't think there's anything fancy or hidden in the message (but then again I'm also known for forcing simple text and non-rendering html, etc. in my email to reduce the chances of getting more spam through or malicious links. I could just be blocking out extraneous crap. But regardless, my spam filters haven't blocked any notifications from them.)
Answer: I am not sure about the variants of mail transfer methods in your board software, and it will not make a difference in the spam problem (it is about how the mails got transferred to the first SMTP server).
To avoid being classified as spam you "just" have to configure your mail server very well and behave nicely.
Just some quick hints:

Don't send spam. Offer a configuration option about what mails users get and honor this (this is the "behave nicely" part).
Don't be an open relay.
Configure SPF and DKIM. SPF is easy, DKIM is tricky but will be ever more important in the future, I guess.

There are many questions in Server Fault already covering this topics. Search for them, you will find excellent advice.
Answer: Check if your DNS Configuration is right:
Does the host have a valid fully qualified domain name, thus is the helo name correct?
Is the reverse DNS of you server's IP this fqdn?
Many spamsending trojans/personal computers don't have correct dns settings, so spam can be easily determined by broken DNS settings. And it's easy and fast to check these DNS settings, as the mailserver can block mails before even accepting any bytes of the mail itself.
Have a look in to you maillog while sending mail with your server (/var/log/maillog probably), as most servers don't just drop mail, but block spam with a more or less sensible error message, e.g. "550 Mail appeared to be SPAM or forged. Ask your Mail/DNS-Administrator to correct HELO and DNS MX settings or to get removed from DNSBLs;"
Oh yeah, DNSBL. Check if you're listed on any: http://www.dnsbl.info/
If you are - it means someone is using you're server to send out spam - fix this first (that's a topic on it's own).
That's what I would go for first. To get caught by a content scanner you must have f'ed up you're mail header and body really hard - so I don't think that's your problem.
SPF and DKIM are overrated, they don't play a big role for spam detection (but DKIM is promising, so in the long run you should set up DKIM nevertheless).


How would you properly fret G and C on fret 3 of a bass guitar?

Question: Looking at:
1
I have an exercise which requires me to play fret 3 G followed by fret 3 C at a tempo of 130. My natural inclination is to use finger 1 on G and then, without moving finger 1 (leave the tip on G), simply lower the back part onto C and then raise it again when I'm done.
Is this the correct way to accomplish that? I could certainly practice moving the tip of the finger back and forth but that movement seems unnecessary. Are there better alternatives?
Comment: Can you post a pic of the exercise?  The approach would depend on the entire passage.  You certainly can roll the finger from G to C, like a bar, and there are certainly many other approaches.  Why would you be on the 1?  does it start there?  Or could you finger G with 2?
Comment: That pic does not help.  Is this the "exercise"?
Comment: @ggcg not sure to which pic you're referring. The fretboard? That should be the only pick currently in there. Here's a link to the exercise though! https://www.studybass.com/lessons/common-bass-patterns/roots-to-chords/exercises/
Comment: Sounds like a backwards bass pattern! Usually it's C followed by G.
Comment: You ask about fretted strings, but the studybass.com exercise shows open strings. Where is the exercise with C and G?
Comment: @MichaelCurtis It's the third exercise.
Answer: Quite probably, especially with bass, is that what you don't play is as important as what you do play.
Let me explain. It's very easy to make extraneous noises playing bass - other strings vibrating in sympathy, taking a finger off a just played fret, catching a string with the other hand/fingers.
With this in mind, most good players will mute everything they can except the note being played. They'll do this with whatever they can - it could be the plucking hand/fingers, or the fretting fingers. By sliding your finger across, which seems like a tidy move, you're letting one string go to favour the other. That can cause noise, as the string you moved from is now open. You could make sure the string just left is still muted by however much finger you can leave there.
The better way is to control each string with a separate finger. That way, the played string gets pressed onto the fingerboard, while the unplayed one gets muted, by keeping the same finger used for fretting touching that string. On the same fret isn't a problem.
That way, you will 'rock' your two fingers back and forth, alternately pressing and muting. Using two fingers from your plucking hand will mean you'll work up a good pace, and it'll all sound nice and clean. All you are left with is trying to keep a steady pace at whatever tempo is needed.
When the above is sorted, you might like to consider what happens with the open D and G strings. While you play your G note on the bottom string, that top G might start to vibrate - it may well do the same when you play the C note too. So the objective here is to mute those opens as well. Maybe with a couple of spare fingers from right hand, maybe a couple of spare fingers from left. Yours to experiment. Good luck, and clean playing!
Answer: One way to do this is called a "pressure roll", which is demonstrated by Adam Neely in this video (starting at 1:14):

He slides his finger from one note to the next without lifting it.
If you have only one ascending perfect fourth to play, you can flatten your finger and fret the second note with the lower part of the finger, while the tip mutes the first note, as you described.  Note that this will not work with descending perfect fourths or more than one ascending perfect fourth in a row.
You can also use two different fingers to fret the two notes.  I have small hands so this is usually the easiest option for me.  Adam Neely also does this at 2:02 in the above video with his pinky and ring fingers, and then again with his middle and index fingers.
Comment: Thanks man! That was exactly what I was looking for! I'll have to start working on my pressure roll .
Answer: The link you posted in your comment just shows open E and A.  But if I extrapolate I guess you are just moving back and forth on the root of a I --> IV progression.
There is nothing wrong with rolling the index finger.  But it wouldn't hurt to try and practice (slowly) lifting the index and crossing the string.
You have competing interests.  On the one had you want a smooth transition from one note to the other.  But you also want to be able to move and shift positions when needed.
Rolling a finger gets you where you need to be quickly but possible at the cost of (1) being locked in place, and (2) hearing the other note ring (which you need to control).
Lifting a finger can have the disadvantage of causing the open string to ring, especially at fast tempos.  But I prefer this as it leads to clearer articulation of the note, at least for me.
You can manage extemporaneous sounds by a combination of releasing the pressure on the G without completely lifting the finger or laying part of the right hand on that string.  Either way it acts as a mute for the G, or the open E should you choose to change string.
This issue occurs in guitar as well, especially classical where the scraping noise of the string and sympathetic resonance can reek havoc on clean sound.
Unless there is some direction in the exercise that indicates proper technique I'd practice both ways, slowly at first, working your way up to the fast temp.
Another option could be use two fingers, though that might be more work than needed for this simple exercise.  It is a common exercise in classical guitar and upright bass to cross strings at the same fret with different fingers.  Though in my recollection this is more of a control and dexterity building exercise and not the "preferred" way to play notes at the same fret.
Comment: It's the third exercise in the link.
Comment: I see.  I don't like that "TAB", I'm used to fret numbers and they gave letter names?  Is that standard?  It does not change my answer.
Comment: It's called an alpha tab. I'm new to this, but as I understand it this seems to be a bit of a religious war in the bass community . This instructor's course focuses heavily on learning the bass while also working on music theory so there's an added priority on being able to identify a note and its corresponding letter. Subsequently, there's much less emphasis on tabs and a lot more on standard sheet music. With the tabs provided the idea is that new students focus more on the correlation between the fret and the note rather than the fret number
Comment: Well I was trained to sight read and my teachers would have gone to war against any and all tab
Answer: If you are playing simple repetition of those two notes & do not need to be prepared to go anywhere else afterwards, then I'd use the two strongest fingers with best reach to that side of the neck, 2 & 3 (middle & ring). You will probably find that an easier reach than 1st finger, and considerably easier than unnecessarily dancing from string to string with any single finger if you don't have to. Don't make extra work for yourself - that will come later when you have more complex figures… & when your hands are more used to it.
That way you have the firmest fretting, with the best left hand damping of the other note.
If you need to go off elsewhere after a period of such repetition, then you do that in the last cycle by swapping to fingers best placed to set you up for the next line. No need to swap before you need to.
Answer: When you're reading it is effective to roll that finger over, as it maintains your position. When you're playing at a fast tempo it usually saves you time. As you go back and refine a passage you might decide to substitute an adjacent finger (in this case possibly the second finger) to facilitate movement to whatever note comes next. In any case, the technique of rolling the fretting finger over onto the next string is one you will use again and again, trust me.


SQL Group by 2 column

Question: I want to display once in multiple rows with the 2 GROUP_BY
My table is like this
    +----+----------+-------+
    | ID | BRAND |   TYPE    |
    +----+----------+-------+
    |  1 | A     |  Clothes  |
    |  2 | A     |  Hat      |
    |  3 | A     |  Hat      |
    |  4 | A     |  Hat      |
    |  5 | B     |  Jeans    |
    |  6 | B     |  Jeans    |
    |  7 | B     |  Hat      |
    |  8 | C     |  Clothes  |
    |  9 | C     |  Jeans    |
    | 10 | C     |  Jeans    |
    | 11 | C     |  Hat      |
    +----+-------+-----------+

And my query like this
SELECT brand,
       type,
       COUNT(*) AS total
FROM store
GROUP BY brand, type

When I run that query the result is
        -----------------------------
        | BRAND |   TYPE    |  TOTAL |
        -----------------------------
        | A     |  Clothes  |   1    |
        | A     |  Hat      |   3    |
        | B     |  Jeans    |   2    |
        | B     |  Hat      |   1    |
        | C     |  Clothes  |   1    |
        | C     |  Jeans    |   2    |
        | C     |  Hat      |   1    |
        ------------------------------

Thats not the result I expect. I just wanna display once Brand and with the following Type also display once if there are multiple same value.
UPDATE: expect result
        -------------------------------------------
        | BRAND |   TYPE                |  TOTAL |
        -------------------------------------------
        | A     |  Clothes, Hat         |   4    |
        | B     |  Jeans, Hat           |   3    |
        | C     |  Clothes, Jeans, Hat  |   4    |
        -------------------------------------------

Comment: Specify the expected result.
Comment: Italien not possible if you want to show both the columns `brand` and `type`. If you group the column `brand`, what do you expect to be in the `type` column since there are multiple (different) values that are grouped together?
Comment: @jarlh updated question
Comment: If the `type` is integer is it possible?
Answer:
Using Group_Concat function with Distinct clause, you can get all different and unique type(s) in a comma separated string, under a brand group.
Use Sum function to calculate the total

Try the following:
SELECT brand,
       GROUP_CONCAT(DISTINCT type) As type,
       SUM(total) AS total
FROM store
GROUP BY brand

Comment: Edit : Oh here it is! This work fine with my code! Thank you so much
Answer: Your description suggests me to do conditional aggregation :
SELECT brand,
       COUNT(DISTINCT CASE WHEN TYPE = 'Clothes' THEN TYPE END) AS Clothes,
       COUNT(DISTINCT CASE WHEN TYPE = 'Hat' THEN TYPE END) AS Hat,
       COUNT(DISTINCT CASE WHEN TYPE = 'Jeans' THEN TYPE END) AS Jeans
FROM store s
GROUP BY brand;

If you want to one row with multiple types then you can use GROUP_CONCAT :
SELECT brand, GROUP_CONCAT(DISTINCT TYPE) As TYPE, COUNT(total) AS total
FROM store s
GROUP BY brand;

Answer: with this you get olny one type per brand
SELECT brand,
      Max( type) AS  type,
       COUNT(*) AS total
FROM store
GROUP BY brand

SQL Group by 2 column


python: using multiprocessing with a dataframe for geocoding

Question: I am trying to return the zipcode as column in a dataframe. This code works but doesn't create a new column in the dataframe gps.
import geocoder
import multiprocessing as mp
import pandas as pd

google_key = 'key'

def reverse_gecode(coordinates):
    return geocoder.google(coordinates, key = google_key, method = 'reverse').postal

if __name__ == '__main__':
    gps = pd.DataFrame({'lat': [27.950575, 40.6936488],
                        'lon': [-82.4571776, -89.5889864]})  # dataframe mehtod
    gps['gps'] = zip(gps.lat, gps.lon)
    x = list(gps['gps'])
    # multiprocessings
    pool = mp.Pool(processes = (mp.cpu_count() - 1))
    result_latlong = pool.map(reverse_gecode, x)
    pool.close()
    pool.join()

I have tried

gps['zip_code'] = gps.apply(lambda x: pool.map(reverse_gecode,
list(x[2])),
    axis = 1)
gps['zip_code'] = gps.apply(lambda x: pool.map(reverse_gecode, x[2]),
axis = 1)
gps['zip_code'] = gps.apply(lambda x: pool.map(reverse_gecode, [x[0], x[1]]),
axis = 1)

But I just cannot get anything to work. The error I keep getting is

ValueError: ('Unknown location: 27.950575', u'occurred at index 0')
Answer: try is:
import geocoder
import multiprocessing as mp
import pandas as pd

def reverse_gecode(coordinates):
    return geocoder.google(coordinates, method = 'reverse').postal

if __name__ == '__main__':
    gps = pd.DataFrame({'lat': [27.950575, 40.6936488],
                        'lon': [-82.4571776, -89.5889864]})  # dataframe mehtod
    coords = gps[['lat','lon']].astype(str).apply(lambda x: (x[0],x[1]), axis=1).tolist()
    # multiprocessings
    pool = mp.Pool(processes = (mp.cpu_count() - 1))
    gps['zip_code'] = pool.map(reverse_gecode, coords)
    print(gps)
    pool.close()
    pool.join()

PS i've removed key=google_key in the geocoder.google() call, because it didn't work for me
Output:
         lat        lon zip_code
0  27.950575 -82.457178    33602
1  40.693649 -89.588986    61603

Comment: I just checked it - it works properly for Python 3.5.1 and 2.7.11 (pandas: 0.18.0) - what versions do you have?
Comment: @dustin, what is the output of `print gps[['lat','lon']].astype(str).apply(lambda x: (x[0],x[1]), axis=1)`
Comment: and `gps[['lat','lon']].astype(str).apply(lambda x: (x[0],x[1]), axis=1).tolist()`?
Comment: then it must work! what line of code gives you `AttributeError` exception?
Comment: Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/111040/discussion-between-maxu-and-dustin).


Converter XML para array em PHP

Question: Estou a ir buscar nomes de artigos por este link:
[http://api.elsevier.com/content/search/index:SCIDIR?query=heart+attack&apiKey=20d0c7953f56925f725afe204869dadb&xml-decode=true&httpAccept=application%2Fxml][1]

Está-me a devolver o resultado em XML, agora preciso de converter o resultado para dentro de um array. Estou a usar a seguinte função:
$page = file_get_contents("http://api.elsevier.com/content/search/index:SCIDIR?query=heart+attack&apiKey=20d0c7953f56925f725afe204869dadb&xml-decode=true&httpAccept=application%2Fxml");
$xml = simplexml_load_string($page);
$json = json_encode($xml);
$array = json_decode($json,TRUE);
echo "
";
print_r($array);

O problema é que nem todos os campos são passados para o array, por exemplo no title do artigo não passa para o array. Existe outra função que passe os campos todos o XML para o array? Também experimentei do seguinte modo mas o resultado é identico:
$xml   = simplexml_load_string($buffer);
$array = json_decode(json_encode((array) $xml), 1);
$array = array($xml->getName() => $array);

Answer: Para converter corretamente um XML para Array sem a necessidade de usar JSON, pode ser usado o método abaixo para isso.
function xmlToArray($xml, $options = array()) {
    $defaults = array(
        'namespaceSeparator' => ':', // você pode querer que isso seja algo diferente de um cólon
        'attributePrefix' => '@',    // para distinguir entre os nós e os atributos com o mesmo nome
        'alwaysArray' => array(),    // array de tags que devem sempre ser array
        'autoArray' => true,         // só criar arrays para as tags que aparecem mais de uma vez
        'textContent' => '$',        // chave utilizada para o conteúdo do texto de elementos
        'autoText' => true,          // pular chave "textContent" se o nó não tem atributos ou nós filho
        'keySearch' => false,        // pesquisa opcional e substituir na tag e nomes de atributos
        'keyReplace' => false        // substituir valores por valores acima de busca
    );
    $options = array_merge($defaults, $options);
    $namespaces = $xml->getDocNamespaces();
    $namespaces[''] = null; // adiciona namespace base(vazio)

    // Obtém os atributos de todos os namespaces
    $attributesArray = array();
    foreach ($namespaces as $prefix => $namespace) {
        foreach ($xml->attributes($namespace) as $attributeName => $attribute) {
            // Substituir caracteres no nome do atributo
            if ($options['keySearch']) $attributeName =
                    str_replace($options['keySearch'], $options['keyReplace'], $attributeName);
            $attributeKey = $options['attributePrefix']
                    . ($prefix ? $prefix . $options['namespaceSeparator'] : '')
                    . $attributeName;
            $attributesArray[$attributeKey] = (string)$attribute;
        }
    }

    // Obtém nós filhos de todos os namespaces
    $tagsArray = array();
    foreach ($namespaces as $prefix => $namespace) {
        foreach ($xml->children($namespace) as $childXml) {
            // Recursividade em nós filho
            $childArray = xmlToArray($childXml, $options);
            list($childTagName, $childProperties) = each($childArray);

            // Substituir caracteres no nome da tag
            if ($options['keySearch']) $childTagName =
                    str_replace($options['keySearch'], $options['keyReplace'], $childTagName);
            // Adiciona um prefixo namespace, se houver
            if ($prefix) $childTagName = $prefix . $options['namespaceSeparator'] . $childTagName;

            if (!isset($tagsArray[$childTagName])) {
                // Só entra com esta chave
                // Testa se as tags deste tipo deve ser sempre matrizes, não importa a contagem de elementos
                $tagsArray[$childTagName] =
                        in_array($childTagName, $options['alwaysArray']) || !$options['autoArray']
                        ? array($childProperties) : $childProperties;
            } elseif (
                is_array($tagsArray[$childTagName]) && array_keys($tagsArray[$childTagName])
                === range(0, count($tagsArray[$childTagName]) - 1)
            ) {
                $tagsArray[$childTagName][] = $childProperties;
            } else {
                $tagsArray[$childTagName] = array($tagsArray[$childTagName], $childProperties);
            }
        }
    }

    // Obtém o texto do nó
    $textContentArray = array();
    $plainText = trim((string)$xml);
    if ($plainText !== '') $textContentArray[$options['textContent']] = $plainText;

    $propertiesArray = !$options['autoText'] || $attributesArray || $tagsArray || ($plainText === '')
            ? array_merge($attributesArray, $tagsArray, $textContentArray) : $plainText;

    // Retorna o nó como array
    return array(
        $xml->getName() => $propertiesArray
    );
}

Fonte
Exemplo de utilização:
$page = file_get_contents("http://api.elsevier.com/content/search/index:SCIDIR?query=heart+attack&apiKey=20d0c7953f56925f725afe204869dadb&xml-decode=true&httpAccept=application%2Fxml");

$xml = simplexml_load_string($page);
$arrayData = xmlToArray($xml);
echo "
";
print_r($arrayData);

Codepad.viper-7 Demo
Comment: @pc_oc `echo count($arrayData['search-results']);` parece funcionar para mim.
Comment: Obrigado! só estou com problema com esta solução, funciona tudo ok mas como posso contar as entradas do array? estou a tentar usar count($array['search-results']) mas dá o seguinte erro: Cannot use object of type stdClass as array in
Answer: Não aconselharia fazer esta gambiarra com JSON. Na documentação do SimpleXML tem uma exemplo de como criar um array à partir do XML.
function XML2Array($xmlContent, $out = array()){
    $xmlObject = is_object($xmlContent) ? $xmlContent : simplexml_load_string($xmlContent);
    foreach((array) $xmlObject as $index => $node)
        $out[$index] = ( is_object($node) || is_array($node) ) ? XML2Array( $node ) : $node;
    return $out;
}

$page = file_get_contents("http://api.elsevier.com/content/search/index:SCIDIR?query=heart+attack&apiKey=CHAVEAQUI&xml-decode=true&httpAccept=application%2Fxml");
$array = XML2Array($page);

Coloquei no GitHub para referência futura.
Se você ainda tiver problemas, provavelmente tem um problema em outro lugar, talvez um XML mal formado.
Comment: sim, peço desculpa mas tinha um coisa mal no meu codigo, estava a chamar mal a função. Agora coloquei tudo ok, mas continua a dar o mesmo erro do implexml_load_string() expects parameter 1 to be string, array given in
Comment: É um pouco estranho dar esse erro porque não tem função com este nome, tem uma função chamada `simplexml_load_string`. A `file_get_contents` retorna uma *string*, portanto está sendo passado o tipo correto para `XML2Srray` e consequentemente para a `simplexml_load_string`. Consegui fazer o teste controlado http://ideone.com/kmOZIi
Comment: @Maniero o problema desse código é que dentro do foreach você aceita que o $node seja um array (na equação ternária onde você verifica se há a necessidade de recursão) entretanto, na entrada do início da função você apenas verifica se é um objeto. Você pode corrigir esse problema de `simplexml_load_string` basicamente substituindo a condiconal para `is_object($xmlContent) || is_array($xmlContent)`
Answer: Para quem está com problema com a função descontinuada "each" recriei ela para funcionar no código acima.
function legacy_each($array){
    $key = key($array);
    $value = current($array);
    $each = is_null($key) ? false : [
        1        => $value,
        'value'    => $value,
        0        => $key,
        'key'    => $key,
    ];
    next($array);
    return $each;
}

Converter XML para array em PHP


Different SQL result with same query in PHP and MySQL

Question: After a quick search, I haven't find solution of my problem so I post a new one.
So I have to create view in a MySQL database from a Web interface (using PHP).
I use a PEAR framework for the connection with  MySQL(5.0.26)
I have the SQL request :
CREATE VIEW test AS SELECT cswc.code_de_la_copie, cswc.service_de_reference, cswc.libelle_de_la_copie, cswc.direction_de_securite_logique
FROM  pressi_copiesServiceWithCibles cswc LEFT OUTER JOIN pressi_servicesReferenceWithCibles srwc ON cswc.service_de_reference = srwc.code_du_service
WHERE cswc.cible is null
  AND (srwc.cible LIKE '%£DOMAIN£%' OR srwc.cible LIKE '%$DOMAIN$%');

When I execute this request directly on mon local MySQL Database, I obtain a result with 470 lines.
However, when I execute this request in my PHP code, I have a different result (I have 386 line), and I don't know why !
$values['request'] = "SELECT cswc.code_de_la_copie, cswc.service_de_reference, cswc.libelle_de_la_copie, cswc.direction_de_securite_logique
FROM  pressi_copiesServiceWithCibles cswc LEFT OUTER JOIN pressi_servicesReferenceWithCibles srwc ON cswc.service_de_reference = srwc.code_du_service
WHERE cswc.cible is null
  AND (srwc.cible LIKE '%£DOMAIN£%' OR srwc.cible LIKE '%$DOMAIN$%');";

$baseView = "test";

$sqlView = 'CREATE VIEW '.$baseView.' AS '.$values['request'];
$res =& $this->mdb2->query($sqlView);
if (PEAR::isError($res)) {
   return false;
}

Moreover, I have already create 6 views before this one without any problem (same result in PHP and in MySQL)
Thank you for your help
Comment: take out the rows that are not in your php result and then look all columns to find something strange or different between others. Maybe a charset issue
Comment: someone should vote to close this as "too localized". I would, if i could.
Answer: Note that your connection to the database also has a CHARSET and a COLLATION for any string values you include in your query. Although your query looks the same to you in both situations, it must not from the MySQL servers point of view.
Maybe the client CHARSET (and/or COLLATION) differ when you connect via PHP from when you connect via MySQL console.
See the MySQL manual for more information on the client charset and collation.
For comparison, you can use this query:
SHOW VARIABLES LIKE 'character_set%';
SHOW VARIABLES LIKE 'collation%';

Comment: The problem come from the charset, but apparently not between PHP and MySQL but with the text I get from the user. So I use utf8_decode($values['request']) before execute the resquest. And I have uniformized the charset between PHP and MySQL


Android Retrofit - How to read Response From Server

Question: I'm working on android project I received JSON Object
<code>{"t":"Terminal1.mobileWalletPassword","v":"0000"},{"t":"Terminal1.PasswordAdjust","v":"0000"},{"t":"Terminal1.PasswordAuth","v":"0000"}
    {"t":"Terminal1.Acquirer4.Issuer1.BinList1.BinRange61.txtMatchLength","v":"00"},{"t":"Terminal1.Acquirer4.Issuer1.BinList1.BinRange61.txtName","v":"CUP_620220"}
</code>
in my project there are classes like
<code>    public class Terminal {
private String PasswordAuth="";
private String mobileWalletPassword
....
}
</code>
and I have
<code>    public class Acquirer{
.....
    }
</code>
and I have
<code>    public class Issuer{
...
    }

</code>
How I can handle this response
Comment: But the attributes named are `t` and `v` . It seem doesn't related with the model classes
Comment: Please set the valid Json!!
Answer: It is possible to send the full output format of the api .because your file is not valid ! ?
Answer: Your response not possible to cast to your model.


How can I remove default image from image fields?

Question: I need to create an image field with a default value, which must also be nullable on single content entities. Contrary to text fields or entity reference fields, I was unable to remove this default value on single content entities.
E.g. I can create a text field with default value "Lorem ipsum". On node creation, the field is prefilled with that text, but I can also delete that text and the field will stay empty.
But on image fields, there is no button/option to remove the default value at all. I can remove an override image, but not the default one. Even after uploading a non-default image, storing, and then removing that image again, the default value kicks in again.
How can I make the image field "nullable"?
Note that I can not use media entity references, because I must support SVG and those images also must not leak into the reuseable global media pool.
Answer: Actually default image does not cause any data save but it affects image formatter so if it finds no values for image field, then it displays the default image which is set in field settings.
you can check in DB or simply create a content with default image A.png and then go to field settings and change the default image to B.png, and when you display your node you will see that B.png will shown in content.
So if you don't want to see the default image in some cases you can duplicate default image formatter and do whatever you like.
and if you really want to save a data for image field with default value, you can do it by altering node form like below:
<code>function my_module_form_node_article_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {
  foreach (array_keys($form['actions']) as $action) {
    if ($action != 'preview' && isset($form['actions'][$action]['#type']) && $form['actions'][$action]['#type'] === 'submit') {
      array_unshift($form['actions'][$action]['#submit'], 'my_module_test_form_submit');
    }
  }
}

function my_module_test_form_submit(&$form, \Drupal\Core\Form\FormStateInterface $form_state) {
  $image = $form_state->getValue('field_image');
  if (empty($image[0]['fids'])) {
    $form_state->setValue('field_image', $form['field_image']['widget'][0]['#default_image']['fid']);
  }
}
</code>
Comment: Thanks for the hint with the field formatter, this explains a lof of issues I've had. The image field is the only field in core that doesn't store default values in the DB, but computes them in the field formatter. This is why the image isn't nullable and the storage API doesn't return correct  default values. I've filed a [bug report on d.o](https://www.drupal.org/project/drupal/issues/3250680) about this
Comment: I can imagine how exhaustive it is to realize you actually has not saved any values on a field for long time while you thought you did


Adicionar +1d na data atual php

Question: Tenho a seguinte data:
$data = date("Y-d-m H:i:s");

Preciso criar a seguinte data:
$data_expira = date("Y-d-m H:i:s"); // adicionando +24h

Como eu posso adicionar +1d na data atual?
Answer: resultado ideone
A partir do PHP 5.2.0, há uma maneira simples de se trabalhar com datas e horários, com a classe DateTime - retorna um novo objeto DateTime
$date = new DateTime('+1 day');
echo $date->format('Y-m-d H:i:s');

Outra forma: resultado ideone
 $amanha = date("Y-d-m H:i:s", time() + 86400);
 echo $amanha;

Outra forma: resultado ideone
$amanha = date('Y-m-d H:i:s', strtotime('+1 days'));
echo $amanha;

Para horario local use date_default_timezone_set   — configura o fuso horário padrão utilizado por todas as funções de data e hora em um script
Exemplo ideone com  date_default_timezone_set ("America/Sao_Paulo");

Adicionar +1d na data atual php


Obtaining the object the java.lang.Class object for a parameterized type without constructing the class in q_uestion?

Question: I would like to do something like:
Class<List<String>> targetClass = List<String>.class;

but that construct does not compile.
The compiler is ok with the
Class<List<String>> targetClass;

declaration, but the compiler does not like
List<String>.class

Interestingly, the compiler (1.7) allows this:
Class<List<String>> targetClass = (Class<List<String>>) List.class;

but then of course complains about an unsafe cast.
Comment: Everything becomes `List.class` after compiling, doesn't it?
Comment: @biziclop:  True, but why allow Class>, then?
Comment: @marathon: Because the compiler pass that thinks about generics thinks that `List` is a perfectly reasonable subtype, but doesn't want to deceive you into thinking that you're actually getting a `Class` object that is anything other than `List.class` when you ask for a more specific one (which doesn't exist). All generic objects of the same parent type share the same code, including static fields- like the implicit read-only `class` field.
Comment: @marathon Because that's the type of a variable and not a class literal. Of course it could be forbidden with a special rule but why would it? After all, you can obtain a `Class` instance in many other ways too, not just from a class literal.
Comment: It's a "fake" `Class>`.  It behaves exactly as `List.class` does.
Answer: Although it seems like it should be, List<String> is not a class, so you cannot get the class object for that. Generics are only used to check at compile time. They are erased from the compiled bytecode.
So, the best you can do is just,
Class<List> clz = List.class;

From Effective Java, 2nd ed.,

There are two minor exceptions to the rule that you should not use raw
types in new code, both of which stem from the fact that generic type
information is erased at runtime (Item 25). You must use raw types in
class literals. The specification does not permit the use of
parameterized types (though it does permit array types and primitive
types) [JLS, 15.8.2]. In other words,  List.class, String[].class, and
int.class are all legal, but  List<String>.class and List<?>.class are
not
Answer: Parameterized types aren't real types, because Java has an incomplete implementation of generics. This is why you can't actually refer to the parametric type directly in an object if you don't already know what it is- Java doesn't know either, because that information exists only at compile time.
List<T>.class doesn't exist because List<T> is, unfortunately, not actually a "real" type. List is, and List.class is the same class reference you get out of new List<T>().class, for any type T, unfortunately.
All generic objects of the same type share the same code (this is called type erasure), including static members- such as the magic language-sacred read-only field known as .class. The language doesn't have a mechanism to create a different .class for each subtype.


Pinterest SDK: "PDKClient not found", what's wrong?

Question: I'm trying to implement Pinterest SDK into my Swift project. I've followed this install guide: https://developers.pinterest.com/docs/sdks/ios/
I just can't get this line working:
PDKClient.configureSharedInstanceWithAppId("0000")

It keeps on resulting to  Use of unresolved identifier PDKClient
What should I do?
Answer: You need to import the PinterestSDK in the class (I guess AppDelegate, right?).
So, at the top of AppDelegate, add
import PinterestSDK

Then it should find the PDKClient object.
Comment: Facing same issue in objective c. I have tried import in both appdelegat.h & app delegate.m but not worked. Please suggest something


Problem with convergence of functions

Question: I want to prove that:
If f is a continuous function, and ${X_n \to X} $ a.e then ${f(X_n) \to f(X)}$ a.e
Comment: If $X_n(\omega)\to X(\omega)$ for $n\to\infty$ then by continuity $f(X_n(\omega))\to f(X(\omega))$ for $n\to\infty$.
Comment: I think it would be helpful to include the space, sigma-algebra and measure under consideration.
Comment: @Lord_Farin What for?
Comment: Because it seems hard to believe that things can be said about arbitrary measure spaces built on arbitrary topologies. At least some assumptions need to be made. The sigma-algebra may have nothing to do with the topology.
Comment: @Lord_Farin The sigma-algebra and the measure indeed have nothing to do with a topology. Random variables $X$ usually are measurable functions $X:\Omega\to\mathbb R^n$ where $\Omega$ is endowed with some sigma-algebra $\mathcal F$ and $\mathbb R^n$ is endowed with the Borel sigma-algebra $\mathcal B(\mathbb R^n)$. Hence at least the sigma-algebra $\mathcal F$ of the source-set $\Omega$ is irrelevant. Note also that the result holds irrespectively of the probability measure on $(\Omega,\mathcal F)$. (Unrelated: please use @.)
Comment: @did: Confusion arose from me being more into abstract measure theory. The only reference to the fact that we are dealing with probability theory is that there is a tag "probability". Furthermore, your point is disproved by assuming the Borel $\sigma$-algebra, which arguably relies on the Euclidean topology on $\Bbb R$, in which (topological) sense the function is continuous. There's too many gaps of information left for the reader to decide - apparently you had less problems with guessing how to fill these gaps. Even that $X$ is a RV is not mentioned... Gaps gaps gaps.
Comment: @Lord_Farin Agreed. (And I might re-use your *Gaps gaps gaps*, which I like very much. That is, if you don't mind.)
Comment: @did Please go ahead :).
Answer: As Stefan commented, the 'event' (set of $\omega$'s) that $X_n\to X$, is included in the 'event' when $f(X_n)\to f(X)$, just because of continuity.
So (using $\mu$ for the measure now),
$$0 = \mu(X_n \not\to X) \ge \mu(f(X_n)\not\to f(X)) \ge 0$$
Comment: The set $\{X_n\not\to X\}$ need not be measureable.
Comment: @StefanHansen Sorry but this is not true: if $X$ and every $X_n$ are measurable, then $[X_n\to X]$ and $[X_n\not\to X]$ are measurable.
Comment: @did: Yep, that is true. But it is nowhere mentioned that $X$ and $X_n$ are measurable.
Comment: @StefanHansen Hmmm... One can presume that the question is asked about *random variables* $X_n$ and $X$, otherwise I fail to see the point.
Comment: @did: I see your point. It's just that I've been taught that convergence a.e. does not require measurability (i.e. $\{X_n\not\to X\}$ is a, not necessarily measurable, null-set). So I guess my point is that if the OP shares this definition, then he has to be careful when writing $\mu(X_n\not\to X)$.
Comment: @StefanHansen True. But as soon as $X_n$ and $X$ are all measurable, then the set $[X_n\not\to X]$ is "necessarily" measurable. If this point is clear, everything is fine. :-)
Comment: @did: Indeed it is :)

Problem with convergence of functions


arbitrage free price in martingale measures

Question: Consider a one-period market with $S^1_t,\cdots,S^n_t$, with $t=0,1$ the price process of $n$ assets, where $S_1$ is a risk-free asset: $S^1_0=1$,$S^1_1=1+R$. Assumes that this market satisfies the No-Arbitrage hypothesis and let $M$ denote the set of equivalent martingale measure. Note that each $\mathbb{Q} \in M$ can be viewed as a function that assigns a non-negative value $\mathbb{Q}[A]$ to each $A \subset \Omega$.
(a) Show that if $\mathbb{Q}_0$,$\mathbb{Q}_1 \in M$, then for any $0 \leq t \leq 1$, the probability measure $\mathbb{Q}_t$ defined by $$\mathbb{Q}_t[A] = (1-t) \mathbb{Q}_0[A]+ t\mathbb{Q}_1[A]$$ is also in $M$.
(b) Let $C$ be a contingent claim and $\Pi(C)$ denote the set of all arbitrage-free prices of $C$. Prove that $\Pi(C)$  is a point or an interval.
I solved part (a) easily by the linearity of expectations but I can't solve part (b). I actually find it counter intuitive that the arbitrage-free price of a contingent claim can be an interval. Can someone please give a hint on part (b)? Please just a hint!
Comment: (b) doesn't contain any question... But the reason that the arbitrage free price can be an interval is that the market model can be "incomplete", i.e. that there exist contingent claims which are not replicable.
Comment: I need to prove that,I edited my question
Answer: Some hints to (b):
In an incomplete market $\Pi(C)$ is an interval because we put lower and upper bounds on the arbitrage free prices. For example the upper bound on the price of a non-replicable $C$ is
$$
\inf(E_{\mathbb{Q}}[X/(1+R)]:X\geq C, \: X \text{ is replicable})
$$
because if it would trade at a higher price than this, you could do arbitrage by selling $C$ and buying the portfolio replicating $X$.
Comment: then in a complete market its always a single point right?  I understand your reasoning but I still dont see why the upper bound and the lower bound arent equal even in the incomplete market? @user126540
Comment: @Albanian_EAGLE Yes. In an incomplete market its a single point because all claims are replicable, so both the upper and lower limit will be equal to $E_Q[C/(1+R)]$. In an incomplete market $C$ might not replicable, so the upper bound will be the price of the cheapest replicable claim bigger than $C$, while the lower bound will be the most costly replicable claim which is under $C$.