Change postgres password using remote ssh

Question: I'm running a postgres database on a Google Cloud instance that we drop and recreate daily as part of our nightly build.
Currently this is being done manually and I want to automate it.
gcloud compute ssh --zone europe-west2-c postgres@postgresql-dev -- "dropdb mydb"
gcloud compute ssh --zone europe-west2-c postgres@postgresql-dev -- "createdb mydb"
gcloud compute ssh --zone europe-west2-c postgres@postgresql-dev -- "psql postgres -c 'GRANT ALL PRIVILEGES ON DATABASE mydb to myuser;' "

This works fine to drop and recreate the database, the problem comes in when I have to re-setup the password ...
gcloud compute ssh --zone europe-west2-c postgres@postgresql-dev -- "psql postgres -c 'ALTER USER myuser WITH PASSWORD 'passwordhere' ; "

gcloud command is already using the double quotes, psql postgres -c is already using the single quotes, what quotes should I be using to put the password in quotes?
I've tried escaping the quotes, but it doesn't work:
WITH PASSWORD \'passwordhere\'

ERROR:  syntax error at or near "\" LINE 1: ALTER USER myuser WITH
  PASSWORD \passwordhere'

or
WITH PASSWORD \"passwordhere\"

bash: -c: line 0: unexpected EOF while looking for matching `'' bash:
  -c: line 1: syntax error: unexpected end of file

How do I escape those quotes?
Comment: Isn't the problem with `\"` the fact that you don't close the `'`?
Answer: this seems to work:
gcloud compute ssh --zone europe-west2-c postgres@postgresql-dev -- "psql postgres -c 'ALTER USER myuser WITH PASSWORD '\''passwordhere'\'' '; "

-
WITH PASSWORD '\''passwordhere'\''


Java Swing : How to refresh JTable Model from another page button

Question: I have 2 windows one window shown the JTable Model data, when double click the row will pop up a new window to edit the data, once submit how can I refresh the JTable?
Customer.java :
JPanel getJPanel() {
    if (jPanel == null) {

        jPanel = new JPanel();
        jPanel.setLayout(null);
        jPanel.setSize(new Dimension(792, 420));
        jPanel.add(getJScrollPane(), null);
        setUpTableData();
    }
   JScrollPane getJScrollPane() {
    if (jScrollPane == null) {
        jScrollPane = new JScrollPane();
        jScrollPane.setBounds(new Rectangle(20, 166, 759, 241));
        jScrollPane.setViewportView(getJTable());
    }
    return jScrollPane;
}

   JTable getJTable() {
    if (jTable == null) {
        jTable = new JTable();
        jTable.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent e) {
                new ContactEdit(name,email,phoneNo,phoneNo2,id).getJInternalFrame().setVisible(true);
                }
            }
        });
        DefaultTableModel tableModel = (DefaultTableModel) jTable.getModel();
        String[] colName = {"No." ,"Name", "Email","Contact No. 1","Contact No. 2","ID"};
        tableModel.setColumnIdentifiers(colName);
        jTable.getTableHeader().setBackground(Color.WHITE);
        jTable.getTableHeader().setForeground(Color.BLUE);
        Font Tablefont = new Font("DialogInput",Font.BOLD,12);
        jTable.getTableHeader().setFont(Tablefont);

    }
    return jTable;
}
   public void setUpTableData() {
    DefaultTableModel tableModel = (DefaultTableModel) jTable.getModel();
    ArrayList<Address> list = sql.getContactLists();
    int i = 0;
    for (i = 0; i < list.size(); i++) {
        String[] bill = new String[6];
        for (int j = 0; j < 6; j += 6) {
            bill[j] = Integer.toString(i);
            bill[j + 1] = list.get(i).getName();
            bill[j + 2] = list.get(i).getEmail();
            bill[j + 3] = list.get(i).getPhoneNo();
            bill[j + 4] = list.get(i).getPhoneNo2();
            bill[j + 5] = list.get(i).getId();
        }
        tableModel.addRow(bill);
    }
    jTable.setModel(tableModel);
}

Edit.java
private JButton getJButton() {
    if (jButton == null) {
        jButton = new JButton();
        jButton.setBounds(new Rectangle(155, 138, 85, 25));
        jButton.setText("Update");
        jButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent e) {
                Address a = new Address(jTextField1.getText(),jTextField.getText(),jTextField3.getText(),jTextField2.getText(),"");
                                    sql.updateContact(a, Integer.parseInt(getJTextField4().getText()));
                            Customer c = new Customer();
                            c.setUpTableData();
                getJInternalFrame().setVisible(false);
                getJInternalFrame().dispose();
            }
        });
    }
    return jButton;
}

On JPanel Load will call this setUpTableData to retrieve the data from database.
On the edit window, I have added an action listener on the update button to refresh the table, but I don't know how to make the jTable refresh the updated data? The setUpTableData on ActionListener give me Null Pointer.
Answer: One solution would be to give the edit window an instance of he other JPanel. (You can accomplish that by passing the panel in to the constructor of the edit window)  Then you can simply call the setUpTableData() method from inside the ActionListener.
The code to do this may look like the following:
Edit frame constructor
public EditFrame(CustomerListFrame cListFrame, ... other params) {
    this.cListFrame = cListFrame;
}

Update ActionListener
public void actionPerforment(ActionEvent e) {
    cListFrame.setUpTableData(the new data);
}

Comment: `new Edit(MainFrame.this).getJInternalFrame().setVisible(true)`  That will pass the current instance of `MainFrame` into the constructor for `Edit`.
Comment: Hi thanks for your reply, sorry dont quite get what you mean by give an instance of e other JPanel? how to do that? Thank You
Comment: @newbie - my guess is that he means simply that when creating the other JPanel, this one should have a reference (given in parameter, for example) of the main panel, so that it would be able to call your method, from "there".
Comment: So inside the constructor do I need to specify anything?
Comment: When I call the setUptableData() method inside the actionlstener it prompt me error message said NullPointer
Comment: @newbie My guess is that you aren't properly passing an instance of the JPanel into the edit frame.  I am going to edit my answer to include more information
Comment: Hi, for ur example ur CustomerListFrame izzit the jtable window class name?
Comment: @newbie Yes.  THe CustomerListFrame is your class that contains the JTable.
Comment: Thanks again, I tried your method on Edit Frame i create a constructor
 private Customer c = null;
 public Edit (Customer c){ this.c = c; }
but on MainFrame jTable
jTable.addMouseListener(new java.awt.event.MouseAdapter() {
   public void mouseClicked(java.awt.event.MouseEvent e) {
     //here i will visible the editFrame
     new Edit(  ).getJInternalFrame().setVisible(true);
     how do I pass in the class itself?


Linq Query - Order By field(string type - should converted in to int) - for each group

Question: Code:
var groupedList = list.GroupBy(u => u.state)
                                            .OrderBy(grp => StateToOrder(grp.Key))
                                            .Select(grp => grp.ToList())
                                            .ToList();

Above code groups the records and displaying the result. I want a field(rank) which is of type string which should be converted to int and applied to the sorted group state in which, each state group should display the records based on the rank field(ascending order).
In short, I need to add the rank field to the above code for displaying the records in rank(ascending order) for each state group.
I need to order the records based on rank for each group state.
I don't know where and how to add the rank field in the above code. Say for example, rank fields has the values (1, 2,3,....etc.,) which is of type string.
Comment: I think some sample input/output would help here.
Comment: say for example, rank fields has the values (1, 2,3,....etc.,) which is of type string
Comment: I need to order the records based on `rank` for each group `state`
Comment: I don't know where and how to add the rank field in the above code
Comment: try: `OrderBy(grp => grp.rank)`
Comment: @UmairM, After / Before, what line i need to add the `OrderBy(grp => grp.rank)` code ?. Also, `rank` field is in `string` type.
Comment: @StackOverflow why is it a string field? Can't you expose it as an `int`? It sounds like you need an abstraction somewhere that will provide you the fields as you need them.
Comment: @AntP, It is in string type as it is an API service field. We just use that API values in our application.
Comment: Replace your original `OrderBy()` by this one if you dont want to use that. Or if you want to use both then you should use `ThenBy()` with same lambda operation in it after `OrderBy()`.
Comment: @UmairM, ie..`list.GroupBy(u => u.state)
                                            .OrderBy(grp => StateToOrder(grp.Key)).ThenBy(grp => grp.rank).Select(grp => grp.ToList())
                                            .ToList();` Is that correct ? Is that String type properly display records in ascending order ?
Comment: yes it is correct and self explanatory
Comment: @UmairM, After `grp.`, rank is not displayed in the intellisense.
Comment: @StackOverflow `grp` is doesn't have the `rank` properties, `grp` is `IGrouping`, so it has a key and list of elements. Each one of these elements has a 'rank` property. Check my answer below.
Answer: You can order the list in each group by rank :
var groupedList = list.GroupBy(u => u.state)
                      .OrderBy(grp => StateToOrder(grp.Key))
                      .Select(grp =>
                      new
                      {
                          grp.Key,
                          Data = grp.OrderBy(x => String.IsNullOrWhiteSpace(x.rank)
                                                  ? 0 : Convert.ToInt32(x.rank))
                      });

foreach(var g in groupedList)
{
    g.Key; // Key;
    g.Data; // Ordered List for that state
}

If you want to place the record with empty rank at the end, replace
String.IsNullOrWhiteSpace(x.rank) ? 0 : Convert.ToInt32(x.rank)

with
String.IsNullOrWhiteSpace(x.rank) ? Int32.MaxValue : Convert.ToInt32(x.rank)

Comment: I tried your answer and got `Cannot apply indexing with [] to an expression of type 'AnonymousType#1'` error
Comment: @StackOverflow At what line are you having this error ?
Comment: @StackOverflow don't use `g[0]` use `d.Data.ElementAt(0);`
Comment: Ok, I will try it. Actually accessing `count`, i got this error
Comment: @StackOverflow inside the foreach, you can do `g.Data.Count()`
Comment: How to check the `rank` is not empty because, i am getting `input string was not correct` error message in foreach at `count`
Comment: If it is empty, then it can be considered as `0`. Then it will be correct..How to do in that query in the `convert.toint32`?
Comment: @StackOverflow where do you to place the value in the order if it is empty ?
Comment: I am trying with this `Data = grp.OrderBy(x => Convert.ToInt32((x.rank != "" ? x.rank : "0"))) ` ..Lets see..
Comment: Thank You very much..Working fine as expected. Thanks for your time and effort..)


What is the difference between singing piano (dynamics) and how most adults sing softly (with lower volume) when singing eg. lullabies?

Question: Many adults who sing lullabies for children use more of a soft voice with low volume.
What I have been told is that playing an instrument or singing in piano (dynamics) isn't that easy. My experience is that this is true.
My understanding is that when you sing in piano you use a very physical technique. When adults (mostly untrained) sing lullabies it is another technique. It is a less physical technique.
What is the difference between singing piano (dynamics) and how most adults sing softly (with lower volume) when singing eg. lullabies?
Comment: @Tim It's common to move *closer* to the mic for a piano section.  Sure, it technically makes your voice louder, but in modern recordings where everything is the same dynamic, the *tone* matters more than the recorded volume.
Comment: Since most singing these days is done using a mic, and to sing piano simply means moving further from said mic, maybe the question needs a little tweaking.
Answer: It's reasonably easy to just not put much into it and thus sing at a low volume. It's much harder to sing with proper depth of tone and good pitch while also doing so quietly. It's even harder to project your voice enough to be heard in a performance with good tone while also having it come across softly (i.e. piano in dynamic).
It also matters what you're trying to sing - e.g. the top end of your vocal range is much harder to sing quietly than the middle.
I suspect that most lullabies or other things that people tend to sing along to quietly are normally in a small section of roughly the middle of a typical voice range, and that the average person who isn't thinking about it is not being too fussy about their tone or consistency of pitch.


Android - How to tell when a specific view has been rendered?

Question: I have a regular button that I want to display a timer on. So imagine the text of the button changes every second as a countdown timer. However, I need this timer to only start when the button is fully rendered and ready to go on the screen.
Right now I'm starting the timer (which is an AsyncTask) in the onCreateView() of a fragment. This isn't that accurate, because I do some other loading stuff that I have to have. I could potentially move the timer start at the bottom of onCreateView() but even that isn't very accurate either.
I saw that there's a OnGlobalLayoutListener tree observer. But I imagine this when an entire view tree is "about to be" drawn? how do I know exactly when my particular button is rendered and visible to the user?
Comment: i don't want to make too many assumptions when i read the phrase `Callback method to be invoked when the global layout state or the visibility of views within the view tree changes`. what visibility? does any view's visibility change trigger this? how do i know which one? is this accurate? ...etc.
Answer: OnGlobalLayoutListener() is the right place to go. It's guaranteed that it will be called when your button has been layed out ("fully rendered and ready to go on the screen"). For example, in onCreate() you could do:
btn = (Button) findViewById(R.id.bn);
btn.getViewTreeObserver().addOnGlobalLayoutListener(new OnGlobalLayoutListener() {

    @Override
    public void onGlobalLayout() {
        new AsyncTaskTimer.execute();
        // prevent the listener to be called more than once
        btn.getViewTreeObserver().removeOnGlobalLayoutListener(this);
    }
});

Comment: this seems to be what i want. i'll have to test it and then accept it if it works. thanks!
Answer: You could create a custom button then implement onFinishInflate() or when you initialize the custom button, set it's visibility to invisible and implement onWindowVisibilityChanged(int). Then when you set the button to visible you start the timer. You could also have it be a start button, which when pressed starts the timer and changes what's needed to behave as a timer button.
http://developer.android.com/reference/android/view/View.html


Translate the allowed values list of an entity access field?

Question: I have a field of type: Entity access field.
In my allowed values list I have:
public|Public
community|Community

I have all of the core translation modules enabled:

Configuration Translation
Content Translation
Interface Translation
Language

I cannot find where in the administrative interface to translate these. Can they be translated in the interface?
Comment: You can translate the allowed values list in the Field UI. When *Configuration Translation* is enabled you should find a tab "Translate content fields" directly to the right of "Field settings".
Comment: Yes, this is the right place, below there should be the translation of the allowed value list, if it is a list field. But what is an "entity access field? Where did you place the field?
Comment: I have that. The translation options I have are for the label and the help text, nothing for the list values?
Answer: As @4k4 already said in his comment, if you have the Configuration Translation module enabled, you simply go to your-site/en/admin/structure/types/manage/your-content-type/fields and select the list field you want to translate (see screenshot below).


On using the same tokenizer for train and test data

Question: I have used keras.preprocessing text tokenizer to fit on the training data alone, computed the (train) vocab size 'input_dim' and maximum train sequence length 'input_length' before fitting my neural network model with an embedding layer(input_dim, output_dim, input_length).
When I try to process the test data and predict my trained model, I am not sure about the effect of applying the tokenizer fitted on the train data to my test data.
In particular I did not re-compute the input_dim and input_length for test data, and used trainTokenizer.texts_to_sequences() on the test data straightaway. Processing it with the train tokenizer ensures the same input_dim and input_length, such that the test data has a compatible shape when passed to predict function.
However the original test data has greater max sequence length and I wonder if there is information loss in what I have done.

But otherwise I do not think it is statistically appropriate to concatenate the train and test data to fit tokenizer and train model. How should I process my test data such that the dimensions are appropriate for feeding to the model, and simultaneously keep test data 'unseen' in developing the model?
Any clarification is welcomed!
Answer: The point of using a test set is to validate your model on unseen data. To do this, you need to apply exactly the same preprocessing and prediction function to the test set.
If you used different preprocessing and observed differences between train and test metrics, you wouldn't know if the the culprit is preprocessing or the model itself. With different preprocessing, in most cases, you would need to re-train the model on the test set for the new data format, so you could as well don't use the test set, just train on all data and keep your fingers crossed it would work on out-of-sample data.
If there are drastic differences you should rather ask yourself why is it so. Was the split of the data done at random? Which train or test data is the "correct" representation of the real-life data? Maybe you need to collect more, or better, data?
Comment: To confirm, with "exactly the same preprocessing", in this case each of my test sequence will have to be the same length as my train data (because the model is developed based on the train input_length)?
Comment: @siegfried yes. But there are also models for varying-length inputs like RNNs, where it wouldn't matter.
Comment: right rnn layer itself does not care about the sequence length. but when the rnn model has an embedding layer where an argument is input_length (the max sequence length), i guess it will have to be the max sequence length from the train data. test data will have to compromise on max sequence length when predicting?
Comment: @siegfried yes.


R row means on multiple columns by groups (or unique IDs)

Question: I have a data frame like below (20,000 rows by 49 cols). Each row has a unique name (ID), each ID has 3 repeat reads in 3 columns (e.g. D15C D15C.1 D15C.2). The first 4 letters of the colnames ("D15C") are group names. I need to average the columns by the group names (e.g. average D15C, D15C.1 and D15.2 to get D15C), so the final table will be consolidated to 16 columns from 49 columns.
          ID  D04C D04C.1  D08H D08H.1 D08H.2  D15C D15C.1 D15C.2  D15L D15L.1 D15L.2
1 1367452_at 11.11  10.93 11.85  10.94  10.87 10.73  10.62  10.85 10.73  10.77  10.52
2 1367453_at  9.65   9.94  9.78   9.68   9.67  9.86   9.71   9.82  9.74   9.71   9.76
3 1367454_at 10.19  10.36  9.68  10.07  10.08 10.35  10.26  10.32 10.27  10.19  10.47
(… 20000 rows)

I transposed and edited it to the following data frame in order to use aggregate:
      ID 1367452_at 1367453_at 1367454_at ... ...
1   D04C      11.11       9.65      10.19
2   D04C      10.93       9.94      10.36
3   D08H      11.85       9.78       9.68
4   D08H      10.94       9.68      10.07
5   D08H      10.87       9.67      10.08
6   D15C      10.73       9.86      10.35
7   D15C      10.62       9.71      10.26
8   D15C      10.85       9.82      10.32
9   D15L      10.73       9.74      10.27
10  D15L      10.77       9.71      10.19
11  D15L      10.52       9.76      10.47

But, the following aggregate ("agg" is the data frame name) took 370 seconds to complete. The problem is that I have 100's of this kind of tables waiting......
agg <- aggregate(x = agg[, 2:ncol(agg)], by = list(ID = agg$ID), FUN = "mean", na.rm = T)

So I converted it to a data.table and run a data table method.
dt <- as.data.table(agg)
setkey(dt, ID)
dt2 <- dt[,lapply(list(dt[2:ncol(dt)]),mean),by = ID]

but got an error message after a few minutes:
Error: cannot allocate vector of size 144 Kb
In addition: Warning messages:
1: Reached total allocation of 1535Mb: see help(memory.size)
2: Reached total allocation of 1535Mb: see help(memory.size)

Not sure what is wrong. Can't use dt[1:5,1:5] to see the "head" part of dt, and head(dt) returns too many lines that ran through the roof I can't see the "head" either. Don't know what to do now.
I can list the ID's in one column (as in data.frame) or transpose the table and list the ID's in the first row (as in data.table). Either way, is there any faster way to aggregate the data? Very much appreciated!
Comment: First question eh?  Welcome. Do you really mean data.table as in the `data.table` package? If you tried `transpose` and `aggregate` then it's best to provide the exact commands you tried so that people can help. No idea what you mean by 'Data.table method'. There's probably some guidelines for asking good questions on Stack Overflow somewhere (but I can't them quickly). Try the R chat room to ask for advice.
Comment: Sorry it was not clear. I have edited it to provide more details. Hope it's more understandable now.
Comment: Much better, thank you. This made it very quick to answer.
Answer: This :
dt2 <- dt[,lapply(list(dt[2:ncol(dt)]),mean),by = ID]

should be just :
dt2 <- dt[, lapply(.SD,mean), by=ID]

The dt[2:ncol(dt)] was in fact taking a subset of rows.
One quick way to learn data.table syntax is to run example(data.table) at the prompt and work through the examples at the prompt.  If you search that for "# applying through columns by group" you'll find exactly this example.
And to learn .SD, best way is to search ?data.table for the string ".SD" and then also there are some good questions and very detailed answers about .SD in this data.table tag which are returned by a search "[data.table] .SD".
Comment: @user1444754 Glad it works now. Don't forget to vote for my answer and accept it (tick it) please. So that others know it is resolved. On this comment it sounds appropriate for a new question. Best to provide a reprodicible example that a responder can paste into a fresh R session to see what you mean, quickly.
Comment: Thanks Matthew. Your code worked beautifully. I just started to look into .SD and run the examples this morning. By the way, is there any way to handle the data with group (i.e. ID) on the first row (i.e. transposed table)? The reason I ask is that R seems to handle longer [30,000, 3,000], not wider [3,000, 30,000], tables better. for example, it takes 1 second to write.table that is long, but 5 minutes to save the same sized transposed wide table. So I have to always transpose the table before saving, and transpose the table before operating on it. Is this "my" unique problem?


Forecasting with VARs: Merge differenced forecast with original data in levels

Question: I am using R and am trying to figure out how to merge some forecasts I've done via the vars package, back to my original xts data, which is in levels.
In previous work, I would have used only level data and used rbind to merge the old data with the forecasts, e.g.:
series <- rbind(orig, fcst)

However, the new forecasts I have are in differences, and I'm kind of at a loss as to how to merge the differenced data with the original data in levels. Does anyone have any suggestions?
Answer: If you have the last observed value $y_t$ and a foreast for the differenced series $\widehat{\Delta y}_{t+1} = \hat y_{t+1} - y_t $, then clearly the forecast of $y_{t+1}$ is $\hat y_{t+1} := y_t + \widehat{\Delta y}_{t+1}$.
Similarly, $\hat y_{t+2} := y_t + \widehat{\Delta y}_{t+1} + \widehat{\Delta y}_{t+2}$ and so on until $\hat y_{t+h} := y_t + \sum_{i=1}^h \widehat{\Delta y}_{t+i}$.
Thus use cumulative sums of the forecasts for the first differences added to the initial value $y_t$ to obtain forecasts for levels of $y_t$.
The R implementation would be apply(rbind(orig,fcst),2,cumsum).


How to use package adespatial as same as sPCA package in ade4

Question: I used the package adegenet with the function sPCA to understand if there are geographical patterns in my genetic data.
vcf<- read.table("AMZ.012") #samples per line
vcf_m<-as.matrix(vcf)

# Add coordinates of samples
xy <-read.table("CoordAMZ_m.csv", sep=",") #geo coordinates for each sample

The matrix "vcf" have 0 and 1 (1 means that the information is there and 0 means no information) in each line is a different sample, as the following example:
0 1 0 1
1 1 0 1
1 1 0 0

I ran sPCA using adegenet package in R, following the example:
mySpca <- spca(vcf_m, xy, ask=FALSE, type=5, scannf=FALSE)

The result was:
This function is now deprecated. Please use the 'multispati' function in the 'adespatial' package.

I tried to use this new function but I don't have any idea how could I use as the same as implemented in sPCA and get similar results. I am expecting something like in this pdf (http://adegenet.r-forge.r-project.org/files/tutorial-spca.pdf), page 7.
I would be very happy if someone could help me.
Thanks.
Answer: I am not sure if you are still interested but it is very simple. First have a look at the args(multispati) to see what is required.
The first argument required is a multi-variate ordination analysis using dudi in the ade4 package.
I created a dudi.pca.
Then a listw is required.
This is simply a weighted connection network similar to what you use in sPCA but in a different format.
You can use chooseCN just like in your sPCA.
Then convert your myCN to a listw using the nb2listw function.
Hope this helps!
Cheers,
Kat


Seria possível fazer um projeto em html, css, js, e rodar em um nativo como o android?

Question: Gostaria de saber se é possível criar um projeto em html, css e js, e rodar em um nativo. Se possível, qual plataforma usar?(obs. Projeto simples, custos simples:) ).
Comment: Cara se eu construir em html css e js, ja tira o sentido de nativo, sim é possível criar baseado nessas três ferramentas, porem não será um código nativo.
Answer: Sim, existem o que chamamos de aplicativos híbridos. Eles podem ser criados utilizando frameworks como o React Native, o Ionic ou o NativeScript. Alguns como já disseram não fazem muito mais do que criar um WebView e colocar o seu código por cima utilizando as vantagens do Apache Cordova e do PhoneGap para comunicação com as API's do telefone.
Outros, no entanto, tem uma extensa capacidade de "converter" código front-end em código nativo. Fazendo uma espécie de de-para que melhora muito a performance e a usabilidade do aplicativo, mas em contrapartida possuem bem menos recursos do que seus concorrentes "não-tão-nativos"
Answer: Progressive Web Apps. Características:

Confiabilidade: Quando lançado a partir da home screen do usuário, service workers permitem que um aplicativo da Web Progressivo (ou PWA) seja carregado instantaneamente, independentemente do estado da rede.
Rapidez: Os recursos do aplicativo web são armazenados localmente após a primeira carga. PWAs carregam instantaneamente.
Comportamento: PWAs são instaláveis, e podem ser apresentados como ícones da home screen sem a necessidade de instalação a partir da AppStore. Eles também tem permissão de abrir em tela cheia e enviar notificações Push.


Annotating Methods in Delphi?

Question: I have a piece of code that needs some serious documenting and wanted to ask whether a feature similar to C#/.NET's In-code XML-Documentation is available for Embarcadero Delphi.
My aim is to display some sort of information on how to use a specific method correctly in the manner that it'd be highlighted in the Autocompletion in Delphi XE3.
Something like this (C#):
<code>/// <summary>
/// Some useful information helping other developers use this method correctly
/// </summary>
public static void ADocumentedMethod();
</code>
Does Delphi XE3 support something like this?
Thank you for reading.
Comment: @TLama shouldn't really matter, AFAIK the /// XML-doc is available since D2010, all SKUs, althought it seems to be bit buggy...
Comment: @ain, I'm talking about [`Documentation Insight`](http://edn.embarcadero.com/cs/article/41911) where, as far as I remember, were quite big restrictions in cheaper distributions of Delphi, weren't they ?
Comment: Which distribution of Delphi XE3 do you have ? Could you include this information into your question, please ?
Comment: It works in Delphi 2009, too.
Answer: The feature is named XML Documentation Comments and is documented here. It appears to have been modelled closely on the equivalent .net feature so you should be right at home with it.
The documentation contains this example:
<code>/// <summary> Removes the specified item from the collection
/// </summary>
/// <param name="Item">The item to remove
/// </param>
/// <param name="Collection">The group containing the item
/// </param>
/// <remarks>
/// If parameter "Item" is null, an exception is raised.
/// <see cref="EArgumentNilException"/>
/// </remarks>
/// <returns>True if the specified item is successfully removed;
/// otherwise False is returned.
/// </returns>
function RemoveItem(Item: Pointer; Collection: Pointer): Boolean;
begin
  // Non-XML DOC comment
  // ...
end;
</code>
which results in this help insight hint:

And there are various other ways to process and consume the documentation.
Comment: Also this XML documentation should be present in  `interface` section of an unit in order to be displayed in external units.
Comment: This is perfect! Thank you very much! I feel a bit stupid for not having found this though Googling.
Comment: Note, you can also use  for Exceptions. Problem is, the exception name (cref) is not shown in the insight hint. (10.3 Rio).
Comment: Adding to Paul's comment, the link in context https://stackoverflow.com/questions/45995827/delphi-helpinsight-with-summary-in-implementation So, its similar to a line of procedure or function that gets repeated in the interface, implementation.

Annotating Methods in Delphi?


DataGridColumnHeader Style Continued

Question: This question is a sequel of this question: DataGridColumnHeader Style

The above code shows my Style for the DataGridColumnHeader and DataGridColumnHeadersPresenter. The Triggers work how I want them but there are some small things I don't like. There is what I have right now below here.
Image removed.
The problem here is that the first cell has a border on its left. The reason for this is clear because I have this in my code: BorderThickness="1 0 0 0".
Image removed.
The second problem is on the right of the header. If I Hover over a cell, the Trigger colors the cell grey. You can see that the grey overlays the DataGridColumnHeadersPresenter border because these cells are rectangular and the DataGridColumnHeadersPresenter has rounded corners.
Image removed.
I nearly have what I want and that is:

One big border around the entire header with rounded corners.
A 1 px line between every header cell.
Hover effect that stays inside the outer border.
Answer: The solution to my problem was to assign styles in my code behind instead of the xaml itself. Below is the code:
if (gridColumns.Count > 0)
    {
        for (int i = 0; i < gridColumns.Count; i++)
      {
            DataGridTextColumn column = new DataGridTextColumn();
            column.Header = gridColumns[i].ColumnName;
            column.Binding = new Binding(gridColumns[i].ColumnBinding);
            if (i == 0)
                column.HeaderStyle = (Style)this.FindResource("ColumnHeaderStyleLeft");
            else if (i == gridColumns.Count - 1)
                column.HeaderStyle = (Style)this.FindResource("ColumnHeaderStyleRight");
            else
                column.HeaderStyle = (Style)this.FindResource("ColumnHeaderStyleCenter");
            dataGrid.Columns.Add(column);
        }
    }

DataGridColumnHeader Style Continued


Add JS to Commerce Add to Cart form

Question: I'd like to add my own JS functions to the Commerce "add to cart" form when a user makes selections on various product attributes.
When the user clicks through the options available, I need to scan the form using JS for the current values of the radiobuttons/selects.  I need this to happen as soon as the form elements have changed.
edit:
Having some success with the following, however since the form changes every single attribute this makes my javascript function run many, many times.
(function($) {
  Drupal.behaviors.watch = {
    attach: function(context, settings) {
      //look at form values here.
      //this fires after each form element is updated

    }
  }
})(jQuery);

Forgive me if this question sounds a bit lazy, I am reading the documentation, but I've not seen anything yet.
Comment: Are you using the 'context' parameter in your jQuery selectors to limit the scope of your jQuery commands? Please update your code example with some of the actual contents of your attach function.
Comment: repost as an answer, ha.. this was really the clue I needed. just checking the context to make sure it's even defined was enough.
Comment: Glad it was as easy as that!
Answer: When you use Drupal's "attach" behaviors, use the provided context parameter in your jQuery selectors to limit the selector scope to only the part of the page that is being modified by AJAX:
(function($) {
  Drupal.behaviors.watch = {
    attach: function(context, settings) {
      $('.my-input', context).val('foo');
    }
  }
})(jQuery);

Add JS to Commerce Add to Cart form


Android YouTubePlayerView shows black color tint on video

Question: I downloaded YouTubeAndroidPlayer example from the following URL:
https://developers.google.com/youtube/android/player/downloads/
Using the PlayerViewDemoActivity example.
Playing the video on normal screen shows a black tint over the video as shown in the image.(The tint is not because of the stop icon.)

When we press fullscreen button it goes away.

What are the reason for the tint ?How to remove it even when the screen size is normal ?
Answer: I know what a lot of time has passed. But I have found to solution for the same problem. May be it will useful for someone.
You need set in theme for your YouTubePlayerActivity a value:
<code><item name="android:backgroundDimEnabled">false</item>
</code>
For example:
1. Manifest.xml:
<code>        <activity
            android:name=".Activities.YoutubeActivity"
            android:theme="@style/YoutubeDialog"
            android:label="@string/activity_youtube"
            >
        </activity>
</code>

styles.xml:
//< style name="YoutubeDialog" parent="Theme.AppCompat.Light.Dialog.MinWidth" >
<code>    <item name="android:windowMinWidthMajor">100%</item>
    <item name="android:windowMinWidthMinor">100%</item>
    <item name="android:backgroundDimEnabled">false</item>
    <item name="android:windowContentOverlay">@null</item>
    <item name="android:background">@android:color/transparent</item>
</style>
</code>

Hope it help you!


Command Object with generics

Question: I have a controller that has a Command Object that uses generics like so:
@Controller
@RequestMapping(value = "/first")
public class MyFirstController {

    @RequestMapping(value = "/something", method = RequestMethod.POST)
    @ResponseBody
    public ADifferentDTO doSomething(RequestDTO<MyStringObject> requestDTO, HttpServletRequest request,
            HttpServletResponse response) {

            requestDTO.getSomeObject(); // ERROR HERE

            //.. do something
    }
}

However, this does not work. I'm assuming it does not working because of Type Erasure in Java. Is there a way I can have the Command Object use a generic?
Here is what some of the other classes might look like.
public class RequestDTO<T> {

    private T someObject;
    // some other objects here as well that are from a submitted form (not listed)

    public void setSomeObject(T someObject){
        this.someObject = someObject;
    }

    public T getSomeObject(){
        return someObject;
    }
}

public class MyStringObject {
    private String someString;

    public MyStringObject(String someString){
        this.someString = someString;
    }
    // getter and setter
}

public class MyIntegerObject {
    private Integer someInteger;
    private Integer anotherInteger;

    public MyIntegerObject(Integer someInteger, Integer anotherInteger){
        this.someInteger = someInteger;
        this.anotherInteger = anotherInteger;
    }
    // getter and setter
}

The error I get:
java.lang.Object cannot be cast to com.test.MyStringObject
Of course if I change my RequestDTO to only use a MyStringObject it works fine.
public class RequestDTO {

    private MyStringObject someObject;
    // some other objects here as well that are from a submitted form (not listed)

    public void setSomeObject(MyStringObject someObject){
        this.someObject = someObject;
    }

    public MyStringObject getSomeObject(){
        return someObject;
    }
}

Is there a way this can be done?
Comment: How does your controller know how to construct RequestDTO from what whatever passed from the client side?
Comment: If you're looking at a compiler error then type erasure is not involved.
Comment: @LewBloch it's a runtime error
Comment: @MinhKieu It doesn't know how to construct it
Comment: Then what's being passed in is not  a `MyStringObject`.
Answer: You are correct, it is because of type erasure.
Probably the simplest solution is to create a RequestDTO subclasses parameterized with each of your My*Object and use it as a Command Object class.
Given your example:
@SpringBootApplication
public class So44423504Application {

    public static void main(String[] args) {
        SpringApplication.run(So44423504Application.class, args);
    }

    @RestController
    @RequestMapping(value = "/first")
    public static class MyFirstController {

        public static class MyStringRequestDTO extends RequestDTO<MyStringObject> {}

        public static class MyIntegerRequestDTO extends RequestDTO<MyIntegerObject> {}

        @PostMapping(value = "/something")
        public String doSomething(@ModelAttribute MyStringRequestDTO/*MyIntegerRequestDTO*/ requestDTO) throws JsonProcessingException {
            return new ObjectMapper().writeValueAsString(requestDTO);
        }
    }

    public static class RequestDTO<T> {
        private T someObject;
        // getter and setter
    }

    public static class MyStringObject {
        private String someString;

        public MyStringObject() { } // required since another non-default ctor is present.

        public MyStringObject(String someString){
            this.someString = someString;
        }

        // getter and setter
    }

    public static class MyIntegerObject {
        private Integer someInteger;
        private Integer anotherInteger;

        public MyIntegerObject() { } // required since another non-default ctor is present.

        public MyIntegerObject(Integer someInteger, Integer anotherInteger){
            this.someInteger = someInteger;
            this.anotherInteger = anotherInteger;
        }
        // getters and setters
    }
}

Then it works fine:
$ curl -XPOST 'localhost:8080/first/something?someObject.someInteger=23&someObject.anotherInteger=42'
{"someObject":{"someInteger":23,"anotherInteger":42}}%

$ curl -XPOST 'localhost:8080/first/something?someObject.someString=test'
{"someObject":{"someString":"test"}}%

Comment: Wow, I'm a bit surprised it was that easy! Thank you! Quick question, what I don't understand is how a class extending a parameterized class fixes the type erasure problem. So `MyStringRequestDTO` is known to be a MyStringObject even though the  "extends RequestDTO" will not be resolved to a MyStringObject at runtime?
Comment: Well shortly, it is a way for compiler to store a type information within the `.class` file, since we're stated that T = MyStringObject, so it will be available at runtime. Try to run following snippet `System.out.println(MyStringRequestDTO.class.getGenericSuperclass().getTypeName());
System.out.println(new RequestDTO().getClass().getGenericSuperclass().getTypeName());` and you'll see that actual type is present in the output.
Comment: Another way to see what is stored in class files is to use javap command passing classfile to it. For example above it is look like `public class com.stackoverflow.so44423504.MyStringRequestDTO extends com.stackoverflow.so44423504.RequestDTO` all type information is preserved.

Command Object with generics


Como chamar método com o parâmetro array em java?

Question: Estou iniciando em java, tive apenas uma aula. Então estou fazendo uma programa para somar os itens de uma array, e tem que usar metodo. Esse é meu código.
Principal:
package exercicio3e4;

public class Principal {

    public static void main(String[] args) {

        Somar x;
        x= new Somar();
        x.y={1,4,6,8,1};
        x.calcular();

    }

}

Somar:
package exercicio3e4;

public class Somar {

    int[] y;
    void calcular() {
        int i = y.length;
        int total=0;
        while (i >= 0) {
            i--;
            total = total + y[i];
        }
        System.out.println("Soma da array: " + total);
    }

}

Comment: Basta você utilizar `void calcular(int[] x) { ... }` e para chamar `new Somar().calcular( array )`
Answer: Ao puxar o método na sua classe principal você tem que passar os parâmetros necessários para o método trabalhar, esse parâmetros também tem que ser informado no método.
Exemplo:
public class Principal {
    public static void main(String[] args) {
        Somar x;
        x= new Somar();
        int [] y={1,4,6,8,1};
        //passando os dados de y para o método
        x.calcular(y);
    }
}

Classe Somar com o método recebendo os parâmetros
public class Somar {
    //método com parâmetros
    void calcular(int [] a) {
        int total=0;
        //b recebe os valores de []a recebidos no método
        for(int b : a) {
            total = total + b;
        }
        System.out.println("Soma da array: " + total);
    }
}


Set datefirst in where clause

Question: I'm working on a SQLquery, but I have some problems with set datefirst.
Since I'm working in a directquery from PowerBI, I am not able to put SET DATEFIRST 1 in front of my query.
I need the all the data from 1 table, from last week. So for instance:
Now it's thursday, I need all the information from last week (Monday until sunday).
I have this query:
SELECT *
FROM myDB
WHERE CreatedDateTime >= DATEADD(day, -(DATEPART(dw, GETDATE()) + 6), CONVERT(DATE, GETDATE()))
    AND CreatedDateTime <  DATEADD(day, 1 - DATEPART(dw, GETDATE()), CONVERT(DATE, GETDATE()))
    AND Minutes is not null
    AND Minutes > 0
    AND TicketNumber like 'CH%'
    AND User like 'itsn%'
    AND TicketNumber is not null

How can I set the first day of the week to monday within the select?
Comment: I found this codepart on Stack:

declare @MyDate datetime = getdate()
                   select CASE WHEN DATEPART(DW,@MyDate) = 1
                            THEN 7
                          WHEN DATEPART(DW,@MyDate) <= 7
                            THEN DATEPART(DW,@MyDate) - 1
                     END

But can't find a way the get it in my own code
Comment: Looks more like SQL Server than MySQL. Please tag correctly.
Answer: You actually have the right code in your comment (the CASE statement).
To get it into your existing code, just replace your current DATEPART function with the CASE statement. The final query will look something like this.
SELECT *
FROM myDB
WHERE CreatedDateTime >= DATEADD(day, -(CASE WHEN DATEPART(DW, GETDATE()) = 1 THEN 7 ELSE DATEPART(DW, GETDATE()) - 1 END + 6), CONVERT(DATE, GETDATE()))
    AND CreatedDateTime <  DATEADD(day, 1 - CASE WHEN DATEPART(DW, GETDATE()) = 1 THEN 7 ELSE DATEPART(DW, GETDATE()) - 1 END, CONVERT(DATE, GETDATE()))
    AND Minutes is not null
    AND Minutes > 0
    AND TicketNumber like 'CH%'
    AND User like 'itsn%'
    AND TicketNumber is not null

Just as an illustration, here is a quick check of the query. When it is the 22nd (a Sunday), the range is the 9th through the 16th. When the date goes to the 23rd (a Monday), the range moves up to the 16th through the 23rd.
Comment: Wauw @joe, you are great. This works perfect. Thank you very much

Set datefirst in where clause


How to change executable icon from c# code? (not my app icon)

Question: How can I change *.EXEs icons from c# code (not my main app icon but from that app i want to change the icon of another exe).
I eventually would have to change the icons for A LOT of files so I am looking for a fast and good performance way to do it.
I have been googling for 30min but all I found is how to set the icon for the app in VS.
Comment: Bizarre request, some kind of "friendly" malware?
Comment: @Hans: While I have seen malware that does this, there are legitimate uses as well.  I'll actually be doing this soon myself to make executable config files (that can find the actual application by searching a list of paths) with customizable icons.
Comment: No its not a friendly malware, its pretty bad ass. jk
Answer: You need to call the Resources API methods, as described here.
Specifically, you need to call BeginUpdateResource, UpdateResource, and EndUpdateResource.
Comment: Maybe I'm missing something, but the links here point out to a C++ API while the OP question was about C#
Answer: See this.
http://www.angusj.com/resourcehacker/
It is definitely not through C# but its eventually fast and good performance way as you asked.
EDIT
All About Resource Hacker in a Brief Tutorial
Comment: He wants to do it programatically.
Comment: Yep, I need to do it from inside my app, I already use res hacker sometimes, maybe if rh was a console app I could integrate in my code but I bet that would be kinda slow.
Answer: Rather than hacking the resource in the .exe (not very friendly), you could instead create a shortcut to the exe, which will allow you to easily use your own icon in the shortcut. See here for more info on how to do this, using the ShellLink class.
Comment: Thats not what I need, if I have to move the exes+shortcuts that would be a mess.


How to set data (array of objects) from get request in a state hook?

Question: Hi I am getting data using axios in my App component and then showing it on the screen in my SearchResults component.
I currently make my get request (after the user has typed into an input field - in another component) and store all the data in my state searchResults using setSearchResults. Then I pass the data to my SearchResults component as a prop, and use & map through it, and based on some logic I display that correct data on the screen.
I want to know whether it would be more efficient to do my logic directly in my async func rather than in my function in SearchResults component.
I have attempted to do the logic in the async func (can be found below) but my results do not come out correctly. When a I type something in my inputfield, it retrieves data that is not relevant to what the user has typed. Would it be better to leave it as is? Is the reason it's not working because I'm setting my data from my get request incorrectly in my state hook? Any help is appreciated, thank you in advance!
function App() {
    const [keyword, setKeyword] = useState("")
    const [searchResults, setSearchResults] = useState([])

    const getAllData = async () => {
        return await getDataService(keyword)
            .then(({ data }) => {
                // currently I am just doing:
                   setSearchResults(data.list)

                // my attempt below for doing the logic directly here
                //instead of in showSearchResults() in my other component:
                return data.list.map((item) => {
                  if(item.searchterm.includes(keyword.toLowerCase())) {
                    setSearchResults([...searchResults, item])
                }
              })
            })
            .catch((err) => console.log(err))
    }

    return (

            <form className="container">
                <InputField keyword={keyword} setKeyword={setKeyword} getClothesData={getClothesData} />
                <SearchResults keyword={keyword} searchResults={searchResults} />
            </form>

    );
}

const SearchResults = ({ keyword, searchResults }) => {
  const showSearchResults = () => {
    return searchResults.map((item, index) => {
      if (item.searchterm.includes(keyword.toLowerCase()) && keyword.length > 1) {
        return (

               {item.searchterm}

        );
      }
    });
  };
  return
{ keyword ? showSearchResults() : null }
;
}

Comment: firstly you should seperate fetch data and filter data sides. fetch data should be inside useEffect hooks. In addition, you can sperate to states for quick solution.
Answer: Make your server requests within useEffect hook:
The template is like this:
const App = () => {
  const [state, setState] = useState([])

  useEffect(() => {
    axios(url).then(({ data }) => setState(data))
  }, []) // empty array here means that hooks works once

}

Comment: Thank you! I made this change to my code. Appreciate it
Comment: Nice to hear it helped! If you find answers useful you can vote for them - this improves the reputation a bit and makes me happy as well!
Answer: Looks like the logic you're trying to apply is not correct.
return data.list.map((item) => {
  if(item.searchterm.includes(keyword.toLowerCase())) {
    setSearchResults([...searchResults, item])
}

Here, you're mapping over the items in list, and setting the searchResults state again and again. React will make it perhaps a batched update and will not always take the previous state value.
You can avoid that happening by providing functional update in setSearchResults
Take a look at Why React useState with functional update form is needed?
Comment: So do you mean setting it up as: `setSearchResults(searchReslts => [...searchResults, item])` ?
Comment: @critical_maas Yup!
Also, I'd like you to follow other answers shared here. For e.g the answer shared by Tarakumi
Comment: I followed his comment too! Thanks. I tried to do the suggestion with the functional update but I am still getting incorrect results. It displays all the items more than once, when I wanted the results that contain the keyword.


Append Fields to node form by ajax call

Question: I have a node form with some fields, now I want to append some more fields to it on an ajax callback. in the ajax page I have rendered the new form elements with drupal_render function
My problem is that I am not getting the newly built form fields in POST or form_state.
Shall I use AHAH or can I continue with this ajax calls?
$form['country'] = array(
            "#type"=>"select",
            '#title'    =>t('Ship To'),
            '#required' => true ,
            '#options' => $options,
            '#weight' =>10,
            '#attributes' =>  array('id' => $cn_var),
        );
        $form['dyn_cost'] = array(
            "#type"=>"textfield",
            '#title'    =>t('Shipping Cost'),
            '#required' => true ,
            '#size' =>25,
            '#weight' =>11,
            '#id' =>  $co_var,
        );

        print drupal_render($form);
        exit;

This is my ajax form and it is supposed to be appending to the node form.
Comment: Use AHAH. By printing and exiting you're not altering the $form that Drupal knows, and it won't accept data that it's not expecting. In D6 it's not as fun as #ajax in D7, though. Check out an answer I just gave that's very similar, although its syntax applies to D7: http://drupal.stackexchange.com/questions/59224/why-does-form-stateinput-not-correspond-to-the-html-of-the-form-upon-submit/59248#59248
Comment: May be you want to check the AJAX examples in the example module.
Comment: Is there any problem with my current code ?
Comment: @CharlieS why not to post it as an answer?
NikhilM are you still interested in this at all?
Answer: You can use Conditional Fields module to display form fields with certain conditions. No need to use custom ajax calls.

Conditional Fields allows you to manage sets of dependencies between fields. When a field is "dependent", it will only be available for editing and displayed if the state of the "dependee" field matches the right condition.

Append Fields to node form by ajax call


Como setar valores para config's de meu handler nos testes?

Question: Meu handler possui 4 variáveis de configuração:
  config :base_url
  config :details_path
  config :create_path
  config :token

Eu seto eles e meu arquivo lita_config, mas para testar meu handler, eu preciso setar valores para eles em meus specs também, como eu posso fazer isso?
Answer: Arquivos de configurações são circunstanciais. Se em todos os seus testes você for utilizá-los, pode-se criar um aquivo confi.rb, ou mesmo um fixture para ele e fazer um require no seus specs. Caso, for em um teste ou outro, use um let(:config) ou um before :each.
https://relishapp.com/rspec/rspec-core/v/2-2/docs/hooks/before-and-after-hooks
https://relishapp.com/rspec/rspec-rails/docs/file-fixture
https://relishapp.com/rspec/rspec-core/v/3-4/docs/helper-methods/let-and-let
Answer: No rspec para o set das configurações definidas para um Handler do Lita pode ser feita utilizando registry. Por exemplo, no meu caso, meu handler chama dpeauth, para setar essas 3 variáveis de configuração podemos fazer assim:
registry.config.handlers.dpeauth.base_url = 'valor'
registry.config.handlers.dpeauth.details_path = 'valor'
registry.config.handlers.dpeauth.create_path = 'valor'
registry.config.handlers.dpeauth.token = 'valor'


Reset Serial module annually

Question: I'm a newbie to drupal 7 for a year by now. I'm trying to make a unique id field that would increment per node of content type I create.
The computed fields module + serial module is the likeliest method accomplishing my goal, yet I'd like to restart the serial number starting each year, I'm totally lost, please help.
This is the code I've used.
The output: 20150001, 20150002 and so on.
Is there a method to restart the serial num. back to 0001 again when it's a new year?

Computed Code (PHP)
<code>$entity_field[0]['value'] = $entity->field_serial[LANGUAGE_NONE][0]['value'];
</code>
Display Code (PHP)
<code>$display_output = date('Y') . sprintf('%04s', substr(str_pad($entity_field_item['value'], 4, '0', STR_PAD_LEFT), -4, 4));
</code>

This is another method I've found, it works on the D6 website, but turns into a blank on my D7 published contents. It's from a field on D6 using php filter module.
<code><?php
$case_id_query=db_result(db_query("select  max(field_case_id_value) as id  from {content_field_case_id} "));

$case_id = date("Y") . sprintf ( '%04s', substr ( $case_id_query, 4, strlen ( $case_id_query ) - 4 ) + 1 );
return array(
  0 => array('value' =>$case_id),
);
?>
</code>
can I transform the method above to D7?
Answer: I recommend in the future to peruse the Module issue queue. :)
There are a number of patches in the following issue thread, one of which I've used to reset yearly (and actually modified to reset monthly): https://www.drupal.org/node/2168071
Comment: Christian, thank you for your advise! I'll give it try and let you know the outcome.
Comment: It worked!! I've used the developing module version and updated the patch 29 into the revelvent files before installing. Now all I'll need to change is the digits. you've saved my day~ XD
Comment: Fantastic! I'm glad you're making progress! :)

As far as the digits go, how do you intend to make them look vs. how they're currently printed?
Comment: well, I've intended to cut down the digits of the "0"s after the year, which originally looks like "2015**000001**", I've cut down the numbers within the serial.inc file of the patch, resolving a "2015**0001**" as result.

Reset Serial module annually


Dojo dojo.rawXhrPost and dojo.xhrPost

Question: My question is: can we use dojo.xhrPost to post some Json data? More detail:
I have been experimenting with Dojo code to POST JSON data to a RESTful service. It seems to be that the behaviours of dojo.xhrPost and dojo.rawXhrPost are different, or to be more accurate rawXhrPost() works and xhrPost() does not. This is not consistent with my reading of the docs

The original purpose of
  dojo.rawXhrPost was a method that
  could be used to send a raw post body
  to the server. As of 1.3, this
  function is common with
  dojo.xhrPost(). So, for usage of
  dojo.rawXhrPost(), see dojo.xhrPost()

Which implies that xhrPost() is enough. My code looks like this - I've got a "toy" library service that manages Editions of Books. The code wants to POST a new entry,
        var myEdition = {"Edition":{"isbn":"44"}};

        var xhrArgs = {
            url: "http://localhost:8081/LibraryWink/library/editions",
            postData: dojo.toJson(myEdition),
            handleAs: "json",
            headers: { "Content-Type": "application/json"},

            load: function(data) {
                dojo.byId("mainMessageText").innerHTML = "Message posted.";
            },
            error: function(error) {

                dojo.byId("mainMessageText").innerHTML = "Error :" + error;
            }
        };

        var deferred = dojo.rawXhrPost(xhrArgs);

The headers: { "Content-Type": "application/json"} part in necessary so that my JAX-RC service understands that the content is JSON.
What I find is that the code above works perfectly. However if instead I say:
var deferred = dojo.xhrPost(xhrArgs);

No data is transmitted in the POST. I have a TCP/IP monitor in place and can see that there is nothing transmitted.
So, is this a bug, or am I driving xhrPost() incorrectly? Or should I use rawXhrPost()? If the latter, under what circumstances do we use the two flavours of XhrPost?
Answer: As of DOJO 1.4 the this should work:
var myEdition = {"Edition":{"isbn":"44"}};

var xhrArgs = {
    url: "http://localhost:8081/LibraryWink/library/editions",
    postData: dojo.toJson(myEdition),
    handleAs: "json",
    headers: { "Content-Type": "application/json"},
    load: function(data) {
        dojo.byId("mainMessageText").innerHTML = "Message posted.";
    },
    error: function(error) {

        dojo.byId("mainMessageText").innerHTML = "Error :" + error;
    }
};

dojo.xhrPost(xhrArgs);

If you are posting JSON data, the Content-Type header is critical. If you don't add it, the browser will default to 'application/x-www-form-urlencoded' and URL encode your data for you.
You may want to add a charset to the Content-Type header (I do this) but that does not stop it from functioning:
    headers: { "Content-Type": "application/json; charset=utf-8"}

On Firefox 3.6 at least, the charset is automatically added.
As Dom mentions, the HTTP PUT equivalent is dojo.xhrPut. The difference here is that you need to add your request body data as putData instead of postData.
Comment: Thanks, will experiment and report back.
Comment: I think the charset you meant to use is utf-8 not uft-8.
Answer: While using Dojo library from http://ajax.googleapis.com/ajax/libs/dojo/1.3/dojo/dojo.xd.js, I've no issue posting data from a form (data serialized by dojo.formToJson()).
dojo.xhrPut({
    putData: dojo.formToJson("locationInformation"),
    handleAs: "json",
    load: function(response, ioArgs) {
        // ... business logic ...
    },
    error: function(message, ioArgs) { alert(message+"\nurl: "+ioArgs.url); },
    url: "/API/Location"
});

Using Firebug in Firefox, I can see that my request is built as expected:

Among other request headers: Content-Type = application/json; charset=UTF-8
Body of the Put request: {"postalCode":"h8p3r8","countryCode":"CA"}

xhrPost/xhrPut seem to work as rawXhrPost/rawXhrPut...
Comment: Please could you clarify - your code is using xhrPut(), have you also tried it with xhrPost() ?
Comment: xhrPost() and data passed with the "postData" parameter works as xhrPut() and the "putData" parameter...
Answer: One more thing that I would like to add the the answer. When working with AJAX apps, it's also a good idea to set the Accept value to application/json when that's what you're expecting.
headers: { "Content-Type": "application/json", "Accept" : "application/json"}

Dojo dojo.rawXhrPost and dojo.xhrPost


WebSphere MQ SSL in SVRCONN channels in C++ application

Question: We have a C++ application connecting as client to WebSphere MQ using configurable queue manager and queue name. We have been asked to migrate to SSL channels for security reasons. So far we have taken care of configuring Sender and Receiver channels to use SSL.

Do we need to move the SVRCONN channels as well to use SSL?
If yes, how do we provide key-store details in code to connect to channel?

I could not find any option in MQOPEN API to provide.
Answer:
I could not find any option in MQOPEN API to provide.

Its not in MQOPEN but rather MQCONNX API call.  It is far better to use a CCDT (Client Channel Definition Table) file because then your code just needs to issue an MQCONN API call.


Material biconditional and substitution

Question: Does the material biconditional have the substitution property?
As an example, if I was able to derive $A \leftrightarrow B$ during an argument, may I substitute $A$ for $B$ (or vice-versa) in any previous formula?
Answer: Yes. If $\phi(A)$ is some statement with zero or more instances of $A$ as part of it, and $\phi(B)$ the result of substituting any number of those (you don't have to substitute all of them), then if $A \leftrightarrow B$ is true, and $\phi(A)$ is true, then $\phi(B)$ will be true as well.
So yes, if in some proof you have both $A \leftrightarrow B$ and $\phi(A)$, then you can infer $\phi(B)$. Of course, to be able to do this in a purely formal proof requires an explicit inference rule to this effect.
Comment: @MauroALLEGRANZA I thought my two paragraphs kept that neatly distinct: the first paragraph being the meta-theorem, and the second paragraph being about formal proofs.

Material biconditional and substitution


How to check validity of one time login url by Drupal 7 Services module?

Question: I am developing a client side application and using AngularJS for this. I successfully registered a user.
Now my problem is that I cannot find a way to check the validity of one time login url or any end point provided by Services module?
Anybody an idea?
Answer: Note: I have not tried this solution myself, but think it should work.
Some concepts about one time login URL

You cannot just visit the URL (or even request it via a service, or any other request like curl or wget) to check if it is valid. As the name it is for one time use only.
It is valid for 24 hours from time it is generated.

These couple of things need to be taken into consideration while validating the login URL.
The URL where the check (and login) of a user happens is user/reset/%/%/%, where the dynamic arguments are in order : user id, timestamp of the one time login url creation, and the hash of the password.
To implement your solution, I suggest you to create a custom service endpoint and implement the logic which is implemented in user_pass_reset.
You can just skip the part where the function actually logs the user in.
Comment: As AjitS suggested i created custom endpoint for services. I wrote a [blog](http://bit.ly/1Bop985 ) It has all the steps and code.
Comment: Awesome! It is really good that you blogged your entire solution. +1 :-)


Calling a function within a function [Python]

Question: The instructions that I've been given tells me create 2 functions: first one (helloWorld) just has to print a basic string but the second one (helloWorldNTimes) has to call the first one 'n' amount of times. This is what I have so far - I either don't understand the question completely or misinterpreting it.
def helloWorld():
    print('Hello World')

def helloWorldNTimes(n):

def main():
    helloWorldNTimes(7)

main()

Comment: looks like you need to learn what loops are, specifically something called a [for loop](http://www.tutorialspoint.com/python/python_for_loop.htm)
Comment: https://wiki.python.org/moin/ForLoop
Comment: So far so good! Now you just need to think of a looping structure to use in the `helloWorldNTimes` function..
Comment: I warmly suggest you to start with a good tutorial on the Python basics, e.g. the [one](https://docs.python.org/3/tutorial/index.html) available on the Python official site.
Answer: You have to study loops in programming language. Especially for loop.
You have to call function inside a loop. It can be either while or for loop. Then only it can be called n number of times.
Example :
def helloWorld():
    print ("Hello, World!")

for x in range(7):
    helloWorld()

Answer: your 2nd function doesn't do anything... you have to call a loop "n" times to have it done:
def helloWorld():
    print('Hello World')

def helloWorldNTimes(n):
    for x in range(n):
        helloWorld()

def main():
    helloWorldNTimes(7)

main()


Change the format of a date in PHP5

Question: my question is trivial i think, yet i cant figure out how to solve it.
I have a string that contains a date in the following format:
$date=('25/8/1990');

I want to convert it to:
1990-8-25

I tried to do the following:
$newdate=date('Y-m-d',strtotime($date));

But the result i get is
1969-12-31

instead of
1990-8-25.

Thank you
Comment: possible duplicate of [Convert one date format into another in PHP](http://stackoverflow.com/questions/2167916/convert-one-date-format-into-another-in-php)
Comment: Use `DateTime::createFromFormat` to turn date string into DateTime object, then `DateTime::format` to output in desired string format.
Answer: Use DateTime interface. -
<?php

$date = '25/8/1990';

$newDate = new DateTime(str_replace('/', '-', $date));

echo $newDate->format('Y-n-d');

Output
1990-8-25

Comment: `DateTime::createFromFormat('d/n/Y', $date)` would also do it. Rather than the string replace method.
Comment: @nath You have to change the separator in that case also.
Comment: @sgtBOSE No need to change the seperator in that case check my answer
Answer: You can also use DateTime as
$date = '25/8/1990';
$date = DateTime::createFromFormat('d/n/Y', $date);
echo $date->format('Y-n-d');//1990-8-25

Comment: The format he's using is `d/n/Y`, there is no leading 0 on the month.
Answer: Use DateTime::createFromFormat if the original format is consistent:
$date = '25/8/1990';
$date_obj = DateTime::createFromFormat('j/n/Y', $date);
$date = $date_obj->format('Y-n-j');

Answer: Use date_parse_from_format() or strptime(). Auto-guessing month/day order placement is not very sane, so avoid strtotime().
<?php
$strdate='25/8/1990';

$darray=date_parse_from_format("d/m/Y", $strdate);
$newstr=date("Y-m-d", mktime(0, 0, 0, $darray['month'], $darray['day'], $darray['year']));

echo $newstr; //produces 1990-08-25

?>

Change the format of a date in PHP5


generic hql select function given field and param

Question: is this valid HQL?
If not (i assume not since im getting wrong result back). How/can i achieve this generic slect transaction?
String hql = "SELECT * from users Where :searchCriteria = :searchString";
            List q = session.createSQLQuery(hql).addEntity(Users.class)
                    .setParameter("searchField", searchCriteria)
                    .setParameter("searchString", searchString).list();

Answer: Try this hql,
Criteria cr= session.createCriteria(Users.class);
cr.add(Restrictions.eq("searchField", searchCriteria);
cr.add(Restrictions.eq("searchString", searchString);
List<Users> user_data=(List<Users>)cr.list();


I'm having trouble writing a console application to create a simple program to solve a math equation for superannuation

Question: Could some one help me with this?
I've racked my head over an hour and I can't get it to work.
This is in C++ and I've been learning for a little bit but I'm still new...
int main()
{
 double rate, amount,time, S;

    cout << "Insert the time of the super: ";
    cin >> time;

    cout << "Insert the rate (as a decimal, eg 1% AKA 101% = 1.01): ";
    cin >> rate;

    cout << "Insert the amount $: ";
    cin >> amount;

    S =("amount * (rate ^ time - 1)", pow(rate,time));
    cin >> S;

    cout << "The total amount is: " << "S /(rate - 1)" << endl;

    system("PAUSE");
    return 0;
}

i dont get a compile error but i can never get an answer from it
Answer: You "never get a result" because you're setting S to the result of pow with comma operator weirdness then assigning to it again with the line
cin >> S;

which is waiting for you to input another number.
You have two main problems. Here is the updated code with comments on the altered parts:
int main()
{
    double rate, amount,time, S;

    cout << "Insert the time of the super: ";
    cin >> time;

    cout << "Insert the rate (as a decimal, eg 1% AKA 101% = 1.01): ";
    cin >> rate;

    cout << "Insert the amount $: ";
    cin >> amount;

    S = amount * pow(rate, time - 1); // take away the quotes and don't make pow seperate

    cout << "The total amount is: " << (S /(rate - 1)) << endl; // do the calculation and output it

    system("PAUSE");
    return 0;
}

Remember that things inside quotes "like this" are string literals, so "4 * 4" is a string but 4 * 4 (see the absence of quotes) does multiplication which yields the number 16.
Comment: I think that the - 1 is supposed to be grouped as pow(rate, time - 1) rather than pow(rate, time) - 1.  I could be wrong about this, though.
Comment: @template yeah I think you're right, it looks that way, mea culpa.
Answer: I don't think you should assign values to S the way you are doing it. S is declared as double and you are assinging a string to it initially. And when you output the result you are also enclosing the calculation in quotes. You should simply cout << S / (rate-1); // without quotes or cout will simply output the string
Comment: He wasn't assigning a string to it, he was assigning a double because `pow` returns a double and the comma operator "discards" the first expression.


ANTLR4 yet another left recursion

Question: I'm very ashamed to ask...
I wrote a grammar for the language with typecast from int to bool and vice versa.
logic_expr : expr NOT? OR | AND expr
       | expr '|' expr SMALLER | LARGER
       | NUMBER
       | NUMBER_SHORT
       | IDENT
       | LOGIC_DEFINED
       ;
math_expr : expr ADD | SUB expr
      | NUMBER
      | NUMBER_SHORT
      | IDENT
      | LOGIC_FULL
      ;
expr : logic_expr
     | math_expr
     | IDENT
     | LOGIC_DEFINED
     | '(' expr ')'
     ;

But antlr tells me "The following sets of rules are mutually left-recursive [logic_expr, expr, math_expr]"
I cant understand what's wrong in my grammar?
Comment: Maybe, this will help: http://www.youtube.com/watch?v=8JdjkshB7FI
Answer: As of ANTLR 4.2.2, ANTLR 4 does not currently support grammars which contain indirect left recursion. This limitation is addressed by issue #522, which I'm hopeful makes it into ANTLR 4.3.
Since ANTLR 4 already supports direct left recursion, you can solve this problem by inlining your logic_expr and math_expr rules. I also edited 3 broken alternatives by adding parentheses you omitted. I did not remove the ambiguity which was present in the original rules.
expr
       : expr NOT? (OR | AND) expr
       | expr '|' expr (SMALLER | LARGER)
       | NUMBER
       | NUMBER_SHORT
       | IDENT
       | LOGIC_DEFINED
       | expr (ADD | SUB) expr
       | NUMBER
       | NUMBER_SHORT
       | IDENT
       | LOGIC_FULL
       | IDENT
       | LOGIC_DEFINED
       | '(' expr ')'
       ;

ANTLR4 yet another left recursion


cannot save images without saveFileDialog visual basic

Question: ive been working on a screenshot program that upload the image automaticly to an FTP server. but i get an error when i try to use:
PictureBox1.Image.Save("C:\test.bmp", System.Drawing.Imaging.ImageFormat.Bmp)

and i always get the Error:
A generic error occurred in the GDI+
ErrorCode: -2147467259
source- System.Drawing
Full ERROR CODE BELOW (vid = at in english):
    System.Runtime.InteropServices.ExternalException was unhandled
  ErrorCode=-2147467259
  Message="Ett allmänt fel uppstod i GDI+."
  Source="System.Drawing"
  StackTrace:
       vid System.Drawing.Image.Save(String filename, ImageCodecInfo encoder, EncoderParameters encoderParams)
       vid mostlyTesting.Form1.Timer1_Tick(Object sender, EventArgs e) i C:\Users\emil\AppData\Local\Temporary Projects\mostlyTesting\Form1.vb:rad 22
       vid System.Windows.Forms.Timer.OnTick(EventArgs e)
       vid System.Windows.Forms.Timer.TimerNativeWindow.WndProc(Message& m)
       vid System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
       vid System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW(MSG& msg)
       vid System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(Int32 dwComponentID, Int32 reason, Int32 pvLoopData)
       vid System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32 reason, ApplicationContext context)
       vid System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32 reason, ApplicationContext context)
       vid Microsoft.VisualBasic.ApplicationServices.WindowsFormsApplicationBase.OnRun()
       vid Microsoft.VisualBasic.ApplicationServices.WindowsFormsApplicationBase.DoApplicationModel()
       vid Microsoft.VisualBasic.ApplicationServices.WindowsFormsApplicationBase.Run(String[] commandLine)
       vid mostlyTesting.My.MyApplication.Main(String[] Args) i 17d14f5c-a337-4978-8281-53493378c1071.vb:rad 81
       vid System.AppDomain._nExecuteAssembly(Assembly assembly, String[] args)
       vid Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
       vid System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
       vid System.Threading.ThreadHelper.ThreadStart()
  InnerException:

Comment: Try saving to a folder like `C:\Temp` - your app may not have access to the root folder of the boot drive
Comment: The picture in the picture box, is it a `Bitmap` already? If so the error is probably because the `Bitmap` is locked and therefore you can't save it... If so, create a new bitmap with the size of the original bitmap, then you have to copy the original bitmap to the new created bitmap. Finally dispose of the original bitmap and then you can save this new `Bitmap` out to file...
Comment: did not work. stil getting the error.
Comment: @eim64 did you try what I mentioned in my comment?
Answer: I think what you want is this here
Me.PictureBox1.Image.Save(IO.Path.Combine(My.Computer.FileSystem.SpecialDirectories.Desktop, "TestFile.bmp"))

I hope it helps you. Good luck!
Update:
After I saw Plutonix comment, I tried what he said and It's true, When I try to save the image on C:\ (root folder) It gave me the same error as its giving to you. When I tried with a different path, it worked! The only way is to Run as Administrator and It works for C:\
Comment: After Windows XP, the Root directory is not accessible to regular users, so that would be correct to throw an error -- too bad the error is a vague GDI+ one.


Interpreting the residual plot

Question: I'm new to Machine Learning, I have difficulty in interpreting this residual plot(multiple regression) to find out whether the error is random or not(following some pattern). Would you please share your insights on how to interpret residual plots in general?
Thanks
Answer: Well residual plots are a short graphical way to check how your error is distributed. It should be randomly with a mean on all sectors on zero.
In short it's a graphically check for your distribution. Not random errors are easily seen like in following picture 1

So in generell, if you distribution follows a certain pattern, it's not random. In your case it's hard to tell, you have not enough data. It seems fine, but maybe datapoints 2-5 are not random (they all are nearly same level). More simulations would show if there is a pattern.
For other examples and easy explanation check this link, there are a lot of nicely explained sites which try to explain it. For a math orientate attempt, check the paper 1

THE EXAMINATION OF RESIDUAL PLOTS by Zongwu Cai , Chih-ling Tsai ,Xizhi Wu

Interpreting the residual plot


Understanding feature selection in Lasso regression

Question: Given a selection of features, how can I get some insight about why have those features (and not others) been selected? Is there a standard approach?
Answer: The selection of the penalty value in penalized likelihood typically makes use of some form of information criteria such as AIC, BIC etc. Then the optimal value for the penalty term is where the information criteria minimizes. See the example below in R where a linear model is created with 45 zero coefficients and 5 non-zero ones and 500 random samples are generated from this model:
<code>#install.packages('DLASSO')
library(DLASSO)
r = 5      # Total non zero coefficients
zr = 45    # Total zero coefiifients
n = 500    # Total samples
b = c(seq(1, 3, length.out = r), rep(0, zr))
x = matrix(rnorm((r + zr) * n), ncol = r + zr)
y = x %*% b + rnorm(n)
dLasso = dlasso(
    x = x,
    y = y,
    force = FALSE,
    lambda = seq(.05,3,length.out = 100)
)
plot(dLasso,
         label = .1,
         cex = .80,
         all = 1)
cbind(true = b, coef(dLasso))
</code>
The information criteria plots are shown below:

Here is the end result:

and the comparison of the coefficients:
<code>> cbind(true = b, coef(dLasso))
     true coef.AICc coef.GIC coef.BIC coef.GCV
X.1  1.00    0.8426   0.9321   0.9090   0.9090
X.2  1.25    1.0588   1.1304   1.1147   1.1147
X.3  1.50    1.3499   1.4432   1.4231   1.4231
X.4  1.75    1.5568   1.6476   1.6301   1.6301
X.5  2.00    1.7547   1.8440   1.8211   1.8211
X.6  0.00    0.0000   0.0524   0.0076   0.0076
X.7  0.00    0.0000   0.0122   0.0001   0.0001
X.8  0.00    0.0000   0.0000   0.0000   0.0000
X.9  0.00    0.0000   0.0005   0.0000   0.0000
X.10 0.00    0.0000   0.0039   0.0000   0.0000
X.11 0.00    0.0000   0.0000   0.0000   0.0000
X.12 0.00    0.0000  -0.0080  -0.0001  -0.0001
X.13 0.00   -0.0003  -0.0759  -0.0474  -0.0474
X.14 0.00    0.0000  -0.0006   0.0000   0.0000
X.15 0.00    0.0000   0.0397   0.0173   0.0173
X.16 0.00    0.0000   0.0001   0.0000   0.0000
X.17 0.00    0.0000  -0.0037   0.0000   0.0000
X.18 0.00    0.0000  -0.0087  -0.0001  -0.0001
X.19 0.00    0.0000   0.0067   0.0000   0.0000
X.20 0.00    0.0000   0.0010   0.0000   0.0000
X.21 0.00    0.0000  -0.0046   0.0000   0.0000
X.22 0.00    0.0000   0.0196   0.0003   0.0003
X.23 0.00    0.0000   0.0079   0.0001   0.0001
X.24 0.00    0.0000   0.0000   0.0000   0.0000
X.25 0.00    0.0000   0.0113   0.0001   0.0001
X.26 0.00    0.0000  -0.0011   0.0000   0.0000
X.27 0.00    0.0000   0.0076   0.0001   0.0001
X.28 0.00    0.0000  -0.0167  -0.0002  -0.0002
X.29 0.00    0.0000   0.0080   0.0001   0.0001
X.30 0.00    0.0000  -0.0258  -0.0004  -0.0004
X.31 0.00    0.0000   0.0027   0.0000   0.0000
X.32 0.00    0.0000  -0.0207  -0.0003  -0.0003
X.33 0.00    0.0000   0.0011   0.0000   0.0000
X.34 0.00    0.0000  -0.0067  -0.0001  -0.0001
X.35 0.00    0.0000  -0.0009   0.0000   0.0000
X.36 0.00    0.0000   0.0183   0.0003   0.0003
X.37 0.00    0.0000   0.0019   0.0000   0.0000
X.38 0.00    0.0000  -0.0185  -0.0002  -0.0002
X.39 0.00    0.0000  -0.0004   0.0000   0.0000
X.40 0.00    0.0000   0.0501   0.0154   0.0154
X.41 0.00    0.0000  -0.0001   0.0000   0.0000
X.42 0.00    0.0000   0.0017   0.0000   0.0000
X.43 0.00    0.0000  -0.0037   0.0000   0.0000
X.44 0.00    0.0000   0.0001   0.0000   0.0000
X.45 0.00    0.0000   0.0000   0.0000   0.0000
X.46 0.00    0.0000   0.0083   0.0001   0.0001
X.47 0.00    0.0000   0.0000   0.0000   0.0000
X.48 0.00    0.0000   0.0001   0.0000   0.0000
X.49 0.00    0.0000  -0.0017   0.0000   0.0000
X.50 0.00    0.0000   0.0095   0.0001   0.0001
</code>
Comment: I'd recommend adding some explanation to the plots. Your coefficient plot has multiple lines with the same line design. Otherwise a good answer.
Comment: Thanks! I guess I would now ask: how to get some insight about why those features minimize the information criteria, and not others?