How to handle ordinal categorical variable as independent variable

Question: I am using a logit model. My dependent variable is binary. However I have an independent variable which is categorical and contains the responses: 1.very good, 2.good, 3.average, 4.poor and 5.very poor. So, it is ordinal ("quantitative categorical"). I am not sure how to handle this in the model. I am using gretl.
[Note from @ttnphns: Although the question says the model is logit (because the dependent is categorical), the crucial issue - ordinal independent variables - is basically alike, be the dependent categorical or quantitative. Therefore the question is equally relevant to, say, linear regression too - as it is to logistic regression or other logit model.]
Comment: My dependent variable takes value 0 and 1, i have 6 independent variable, 3 of them are categorical these variable are like "how do you rate local health services in your area? how do you rate local transportation in your area and how do you rate police services in your area? the responses are very good, good, average, poor and very poor.
Comment: @Tim If the dependent variable is binary, then there is no need for any ordinal regression. The implication is to handle an ordinal predictor using indicator (dummy) variables.
Comment: thanks tim, if i am not mistaken what you say is that i should create dummy for all the categories?? for instance i have five response (very good, good, average, poor and very poor) for one indep varible, so i should create 5 dummies.
Answer: The problem with ordinal independent variable is that since, by definition, the true metric intervals between its levels are not known, no appropriate type relationship - apart from umbrella "monotonic" - can be assumed apriori. We have to do something about it, for example - to "screen or to combine variants" or to "prefer what maximizes something".
If you insist on treating your likert rating IV as ordinal (rather than interval or nominal) I've got a pair of alternatives for you.

Use polynomial contrasts I.e. each such predictor used in
the model enters not only linearly but also quadratically and
cubically. So, not only linear, but more general, monotonic effect can be captured (the linear effect corresponds to the predictor kept as scale/interval and the other two effects tastes it as having nonqual intervals). Additionally, dummies of each predictor could be entered as well, which will test for the nominal/factorial effect. In the end of all that, you know how much your predictor acts as factor, how much as linear covariate, and how much as nonlinear covariate. This option is easy to do in almost any regression (linear, logistic, other generalized-linear models). It will consume dfs, so the sample size should be large enough.
Use optimal scaling regression. This approach transforms monotonically an ordinal predictor into an interval one so as to maximize linear effect on the predictand. CATREG (categorical regression) is an implementation of this idea in SPSS. One problem of your specific case is that you want to do logistic, not linear regression but CATREG is not logit model based. I think this obstacle is relatively minor since your predictand is only 2-category (binary): I mean you might still do CATREG for optimal scaling, then do final logistic regression with the optained transformed scale predictors.
Note also that in simple case of one scale or ordinal DV and one ordinal IV Jonckheere-Terpstra test might be a reasonable analysis instead of regression.

There could be other suggestions, too. The three above are what come to my mind just instantly reading your question.
Let me recommend you also to visit these threads: Associating between nominal and scale or ordinal; Associating between ordinal and scale. They could be helpful despite that they are not about specifially regressions.
But these threads are about regressions, particularly logistic: you must look inside: one, two, three, four, five.
Comment: @kjetilbhalvorsen, Yes it is possible, thank you. This option however is already implied in Pt 2 because one of the methods of optimal scaling for ordinal variables uses spline.
Comment: Another option is to use an aditive model, and represent the ordinal independent variable via a spline.
Comment: (+1) (1) You can also use only the first few polynomial contrasts if you think they're enough. (2) Defining predictors from the response *in the same data set* should come with a health warning. (3) You can also penalize discrepancy between the coefficients of adjacent levels -  see http://stats.stackexchange.com/q/77796/17230.
Comment: @Scortchi, Thank you for the comment. Regarding (2) - yes, in particular, it is of course more reliable to do optimal scaling on on a separate subset of the data on which the final regression will be done. (3) - thanks, too, I'll get myself acquainted with it.
Answer: Just to add to the other excellent answers: A modern way of handling it could be via an additive model, representing the ordinal independent variable via a spline.  If you are quite sure the effect of the variable is monotone, you could restrict to a monotone spline.  (For an example of monotone splines in use, see Looking for function to fit sigmoid-like curve).
In R, if you make the ordinal predictor an "ordered factor" (with for instance the code ord <-  factor(sample(1:5,20,replace=TRUE),ordered=TRUE)   )
then in a linear model it will be represented via orthogonal polynomials.
Comment: It would be nice just a bit expand it, to include a few more details how it will work with ordinal predictors.
Answer: There have been a lot of compromises that handwave the relationship. The default polynomial contrasts are far from ideal, although I'm sure some would vehemently argue this. I have found that stairstep contrasts manage to capture a monotonic, ordered variable's effects quite well.
ordered_factor <- function(fact_var) {
  ord_fact <- factor(fact_var, ordered=TRUE)
  categories <- levels(fact_var)
  n_cat <- length(categories)
  cont <- matrix(0, n_cat, n_cat-1)
  cont[col(cont)<row(cont)] <- 1
  rownames(cont) <- categories
  colnames(cont) <- paste(categories[2:n_cat],
     categories[1:(n_cat-1)],
                          sep=" vs. ")
  contrasts(ord_fact) <- cont
  return(ord_fact)
}

This is from https://aarongullickson.netlify.app/post/better-contrasts-for-ordinal-variables-in-r/
Comment: The R `brms` Bayesian modeling package handles ordinal predictors in the most elegant way, automatically.  This saves degrees of freedom by fully using the ordinal nature of the predictor.


How do I share a PHP variable between multiple pages?

Question: The idea/goal:
I have a username and password inside a text file on my computer. The form on the index page allows the user to sign in with their username and password. The login page is where PHP is used to validate the user entered info with the info which i have on my local text file. Directly after the user entered info match my text file info the user is redirected to a Home page where they're name is displayed with a welcome message.
The Problem:
Everything up until the validation works. The issue is that when i redirect the user to Home.php I can't display their username. How would i display their username after all the validation? Is there anyway i can permanently store their username in a variable that will be accessible across all my pages?
The Index.php page with the form
The login page that validates the form info with the info i have on my local text file
Comment: Sessions or cookies maybe ?
Comment: take a look at $_SESSION http://php.net
Answer: Use $_SESSION -!
session_start();
$_SESSION['username'] = $_POST['username'];

You of course want to filter/sanitize/validate your $_POST data, but that is outside of the scope of this question...
As long as you call session_start(); before you use $_SESSION - the values in the $_SESSION array will persist across pages until the user closes the browser.
If you want to end the session before that, like in a logout button --- use session_destroy()
Comment: Thanks! Worked like a charm! Although what do you mean by filter/validate/sanitize? Does it have to do with MySQL?
Comment: Well, that all depends on what you're doing with the data - if you use the data in a MySQL query, then yes -! While this is a topic that you should research thoroughly, I will give you the synopsis:
Validating your data means - if you expect a string, make sure its a string. If you expect a number, make sure it is a number. `filter_var()` can do this, and 9/10 times, is all you really need.
`filter_var($_POST['username'], FILTER_SANITIZE_STRING)` - on that note, filtering/sanitizing are really one in the same. But it is still a good idea to both sanitize and validate your data --
Comment: To elaborate, you want to validate that your data fits what it should be, and if it doesn't, then break away from the rest of the code (or just make the value `null`) -Furthermore, sanitizing makes sure that no one can sneak in something malicious that might cause trouble - Hackers can be clever, and they will almost always find a way... so it doesn't hurt to be extra cautious-!- And while i'm talking about it, there are sanitizing functions in mysqli/PDO that you should look into and make damn sure you are using with your database - there are lots of articles out there- google is your friend.
Answer: You can start a session and put the form values into the $_SESSION variable, which will be available on all pages.
// On the page where your form is submitted:
session_start();
$_SESSION['name'] = $_POST['name'];

// On the page where the user is redirected:
session_start();
echo $_SESSION['name'];

Note that in reality you would probably want to include some form validation too!
Answer: I agree with @Clément Malet & @Hammerstein. Sessions and/or cookies.
<?php
    // always need this
    session_start();

    // set the value
    $_SESSION['username'] = 'Person';
?>

<?php
    //get session data
    echo $_SESSION['username'];

   // output: Person
?>

Answer:
Start a php session on each page right after the opening php tag:
session_start();

After you determine that the name and password work, and before you do the redirect, add this line:
$_SESSION['name'] = $name;
On any subsequent pages, just echo something like this:
echo "Welcome ".$_SESSION['name'];

Answer: Use session variables
set:
session_start();
$_SESSION['username'] = "user1";

get:
session_start();
$username = $_SESSION['username'];


How to read multiple files with read_csv or lambda

Question: I am reading the same text file twice via read_csv. First time to get a list of keys that match a specific string (MSG) with 'Col6' in that file. This will give me a dataframe with only those entries that match 'Col6'. Then second time I read the same file(again with read_csv) and print some more columns if key1 == key2, which are based on 'Col1'.
I have basically two questions:
1. Can I combine both searches (read_csv) together?
2. Even if I keep the two read_csv separate, how can I read multiple files? Right now I am reading only one file (firstFile.txt), but I would like to replace the file name with '*.txt' so that read_csv operations are performed for all *.txt files in the directory.
Data file looks like following. I want to print all rows with Col1=12345 since Col6 has value 'This is a test'.

Col1  Col2    Col3    Col4    Col5    Col6
-       -       -       -       -       -
54321 544     657     888     4476    -
12345 345     456     789     1011    'This is a test'
54321 644     857     788     736     -
54321 744     687     898     7436    -
12345 365     856     789     1020    -
12345 385     956     689     1043    -
12345 385     556     889     1055    -
65432 444     676     876     4554    -
-     -       -       -       -       -
54321 544     657     888     776     -
12345 345     456     789     1011    -
54321 587     677     856     7076    -
12345 345     456     789     1011    -
65432 444     676     876     455     -
12345 345     456     789     1011    -
65432 447     776     576     4055    -
-     -       -       -       -       -
65432 434     376     576     4155    -

The script that I used is:
import csv
import pandas as pd
import os
import glob

DL_fields1 = ['Col1', 'Col2']
DL_fields2 = ['Col1', 'Col2','Col3', 'Col4', 'Col5', 'Col6']

MSG = 'This is a test'

iter_csv = pd.read_csv('firstFile.txt', chunksize=1000, usecols=DL_fields1, skiprows=1)
df = pd.concat([chunk[chunk['Special_message'] == MSG] for chunk in iter_csv])

for i, row in df.iterrows():
    key1 = df.loc[i, 'Col1']
    j=0
    for line in pd.read_csv('firstFile.txt', chunksize=1, usecols=DL_fields2, skiprows=1, na_values={'a':'Int64'}):
        key2 = line.loc[j,'Col1']
        j = j + 1
        if (key2 == '-'):
            continue
        elif (int(key1) == int(key2)):
            print (line)

Comment: I think you should simply read the entire CSV at the beginning. Use pandas operations to filter out rows you need there after. It does not make much sense to read the same file again, that too line by line.
Comment: I don't get what exactly you're looking for, can you clarify more?
Comment: I want the following output:
12345 345     456     789     1011    'This is a test'
12345 365     856     789     1020    -
12345 345     456     789     1011    -
12345 345     456     789     1011    -
12345 365     856     789     1020    -
12345 385     956     689     1043    -
12345 385     556     889     1055    -
12345 345     456     789     1011    -
Answer: As I understand it, you do not need to read the CSV file twice. You essentially want all the rows where MSG occurs in Col6. You can actually achieve this in one line -
MSG = 'This is a test'
iter_csv = pd.read_csv('firstFile.txt', chunksize=1000, usecols=DL_fields1, skiprows=1)
# this gives you all the rows where MSG occurs in Col6
df = iter_csv.loc[iter_csv['Col6'] == MSG, :]
# this gives you all the rows where 12345 in Col1
df_12345 = df.loc[iter_csv['Col1'] == 12345,]

You can create multiple subsets of the data this way.

To answer the second part of your question, you can loop over all text files like so -
import glob
txt_files = glob.glob("test/*.txt")
for file in txt_files:
    with open(file, 'r') as foo:
        some_df = pd.read_csv(file)

EDIT: This is how you loop over the files and find all keys with Col1=12345 and Col6=MSG-
import glob
from functools import reduce

results_list = []
MSG = 'This is a test'

txt_files = glob.glob("test/*.txt")
for file in txt_files:
    with open(file, 'r') as foo:
        some_df = pd.read_csv(file, chunksize=1000, usecols=DL_fields1, skiprows=1)
        df = iter_csv.loc[iter_csv['Col6'] == MSG, :]
        # results_list is a list of all such dataframes
        results_list.append(df.loc[iter_csv['Col1'] == 12345, ])

# All results in one big dataframe
result_df = reduce(lambda x,y: pd.concat([x,y]), results_list)

Comment: Please feel free to accept this answer if this solution works for you.
Comment: Can the following code that you suggested be put in a loop so that it is executed for multiple files instead of just one file? I mean can I replace "firstFile.txt" with "*.txt"?

    MSG = 'This is a test'
    iter_csv = pd.read_csv('firstFile.txt', chunksize=1000, usecols=DL_fields1, skiprows=1)
    # this gives you all the rows where MSG occurs in Col6
    df = iter_csv.loc[iter_csv['Col6'] == MSG, :]
    # this gives you all the rows where 12345 in Col1
    df_12345 = df.loc[iter_csv['Col1'] == 12345,]


parse data from list dictionary

Question: NameValueList= [
                    {
                        "Name": "Modified Item",
                        "Value": "No"
                    },
                    {
                        "Name": "Style",
                        "Value": "BIG PONY"
                    }
]

how can i get the second data . Output will be like this  'Style':'BIG PONY'
Answer: It is not quite clear to me what you are asking, so here are some options:

You want the output to be a dictionary

NameValueList =  [
                    {
                        "Name": "Modified Item",
                        "Value": "No"
                    },
                    {
                        "Name": "Style",
                        "Value": "BIG PONY"
                    }
]

output = {NameValueList[1].get("Name"):NameValueList[1].get("Value")}
OUT: {'Style': 'BIG PONY'}

You want the output to be a string

output = str(NameValueList[1].get("Name")) + ":" + str((NameValueList[1].get("Value")))
OUT: 'Style:BIG PONY'

Answer: Dictionaries function with key-value pairs, where the first item is the key and the second item is the value. For example, "Name" is the key and "Modified Item" is the value. In the first example, you can iterate over the values in the dictionary at index position 1 in the NameValueList.
for value in NameValueList[1].values():
    print(value)

#output:
#Style
#BIG PONY

In the second example, you can use .get() and pass in the key to get the value of that key. Note: the key you pass in must be of type string.
var = NameValueList[1].get("Name") + ":" + NameValueList[1].get("Value")
print(var)

#output:
#Style:BIG PONY

parse data from list dictionary


Unable to fetch html hidden input values into express app

Question: I'm trying to fetch some hidden form values in post route of my express app,but getting undefined objects in post route,below is some code snippet
const express = require("express")
const app   =   express();

const bodyParser = require('body-parser');
app.use(bodyParser.json());

app.listen(3000, () => {
    console.log('Authentication service started on port 3000');
});

app.get("/link",(req,res)=>{
    let token = 124578
   let link="http://"+req.get('host')+"/postmethod";
    console.log("hyperlink:"+link)
    let formHtmlPostLink="<form method='post' action='"+link+"'>    <input type='hidden' name='bearer' value='"+token+"'> <input type='hidden' name='test' value='test'> <button type='submit' name='submit_param' value='submit_value' class='link-button'>      Reset Password         </button>       </form>"
    res.send(formHtmlPostLink)
})
app.post("/postmethod",(req,res)=>{
    res.send(req.body)//undefined objects
})

Comment: Can you add your frontend code?
Comment: As of now I've not included any front end code,I'm using this html form in nodemailer to send email with link to next post router
Answer: If you are able to submit form to /postmethod, add middleware bodyParser.urlencoded()
app.use(bodyParser.urlencoded());

If form is not being submitted, change link to relative url
  let link = "/postmethod";

Check codesandbox


Python modbus-tk modbus server is merging two requests and hence getting CRC error

Question: I am using modbus-tk library for modbus serial server. All the communication is up and working. There is one instance where master is writing one register and next request is read but modbus-tk is merging the two request and hence getting CRC error
2019-01-31 17:19:59,881 DEBUG   modbus._handle  Thread-2    -->2-16-0-11-0-1-2-0-128-178-123-2-3-0-4-0-1-197-248
2019-01-31 17:19:59,881 ERROR   modbus.handle_request   Thread-2    invalid request: Invalid CRC in request

Actual request should be 2-16-0-11-0-1-2-0-128-178-123 and othe request is 2-3-0-4-0-1-197-248
Any ideas why I am having the issues
For setup, Modbus slave is connected via serial 232 and running two slave instances on single server.
Comment: Can you add delay between two request (delay bet read & write) say 500ms. Sometimes device unable to handle two request. Also let me know is there two different instance of application querying to slave ?
Comment: Adding a delay on master side is not in my hands. Using a device as a master.
Answer: You must create Thread-safe read/write. If you read or write, you cant do it with uncontrolled threads. You need to lock threads when you read or write. I cant explain why, but last time I was working with modbus, I had similar problem. Modbus simply cant handle threads very well. Lock helped a lot, but still most safe it is to do it threadless.
Idea:
import threading

lock = threading.Lock()

def read():
    with lock:
        read....

def write():
    with lock:
        write....


Wildfly Servlet Deployment Error

Question: I'm migrating from JBoss 4.0.4GA to WildFly 8.1.0. During deployment, I'm getting the following error:
server.default-host./.UndertowDeploymentInfoService: org.jboss.msc.service.StartException in service jboss.undertow.deployment.default-server.default-host./.UndertowDeploymentInfoService: Failed to start service
    at org.jboss.msc.service.ServiceControllerImpl$StartTask.run(ServiceControllerImpl.java:1904) [jboss-msc-1.2.2.Final.jar:1.2.2.Final]
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145) [rt.jar:1.7.0_45]
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615) [rt.jar:1.7.0_45]
    at java.lang.Thread.run(Thread.java:744) [rt.jar:1.7.0_45]
Caused by: java.lang.IllegalArgumentException: UT010009: Servlet VxmlServiceServlet of type class com.nexge.commgenie.vxml.VxmlServiceFC does not implement javax.servlet.Servlet
    at io.undertow.servlet.api.ServletInfo.<init>(ServletInfo.java:99)
    at org.wildfly.extension.undertow.deployment.UndertowDeploymentInfoService.createServletConfig(UndertowDeploymentInfoService.java:620)
    at org.wildfly.extension.undertow.deployment.UndertowDeploymentInfoService.start(UndertowDeploymentInfoService.java:245)
    at org.jboss.msc.service.ServiceControllerImpl$StartTask.startService(ServiceControllerImpl.java:1948) [jboss-msc-1.2.2.Final.jar:1.2.2.Final]
    at org.jboss.msc.service.ServiceControllerImpl$StartTask.run(ServiceControllerImpl.java:1881) [jboss-msc-1.2.2.Final.jar:1.2.2.Final]
    ... 3 more

Could anyone please advise on what the issue is?
Thanks & regards, Shankar
Comment: I'm not sure what I did to truncate the beginning of the question, but it should be "HI im moving jboss 4.0.4.GA..."
Comment: Do you have `com.nexge.commgenie.vxml.VxmlServiceFC` in your web.xml declared as a servlet?
Comment: thanks for ur reply Mr James R. Perkins . i was declared in web.xml as below

    VxmlServiceServlet

    com.nexge.commgenie.vxml.VxmlServiceFC

VxmlServiceServlet
/VxmlServletFC
                                                                         OR I need to configure anything in wildfly server to deploy servlet program?
Comment: can you provide snippet?
Answer: The error pretty much states exactly what the issue is. You have a servlet defined that doesn't extend javax.servlet.Servlet. If for whatever reason it is extending javax.servlet.Servlet then the likely issue is you're including some library in your deployment that contains a javax.servlet.Servlet.
Comment: ok thanks Mr james perkins. iwas wrongly added library in wildfly. now its working fine. how can i add my external api jars in wildlfy ? pls help me
Comment: Have a look at how to install a JDBC module http://wildfly.org/news/2014/02/06/GlassFish-to-WildFly-migration/#_jdbc_driver. Installing other modules is the same. Have a look at class loading docs, https://docs.jboss.org/author/display/WFLY8/Class+Loading+in+WildFly, to see how to add them as dependencies.

Wildfly Servlet Deployment Error


Why does this function has this property?

Question: Let $f \in C^1(\Bbb{R}, \Bbb{R})$ and suppose that there exist $C, r \in \Bbb{R}$, with $2 < r < 2^* = 6$, such that
$$
|f(t)| \leq C(1+|t|^{r-1})
$$
Assume also that
$$
\lim_{|t| \to 0}\frac{|f(t)|}{|t|} = 0.
$$
Then, given $\varepsilon > 0$ there is $C_{\varepsilon}$ such that $|f(t)| \leq \varepsilon |t| + C_{\varepsilon}|t|^{r-1}$.
Why is this true?
This is a claim in a text (in Portuguese) I am reading on the method of the Nehari manifold for elliptic equations.
Thanks in advance.
Answer: Since $f(t)/t\to0$ as $t\to0$, for any given $\varepsilon>0$, there exists $\delta>0$ such that
$$
|f(t)|<\varepsilon|t|
\qquad\textrm{whenever}\quad
|t|<\delta.
$$
To proceed further, let
$$
C_\varepsilon=C(1+\delta^{1-r}),
$$
which ensures that
$$
C(1+t^{r-1})\leq C_\varepsilon t^{r-1}
\qquad\textrm{for}\,\,t\geq\delta.
$$
Thus
$$
|f(t)|\leq\varepsilon|t|+C_\varepsilon|t|^{r-1}
\qquad\textrm{for}\,\,t\in\mathbb{R}.
$$
Comment: Got this. Many thanks
Comment: You just need to see that two sides are equal at $t=\delta$, and the derivative of the RHS is larger than that of the LHS, because $C_\varepsilon>C$.
Comment: I messed with the exponents, I apologize. Let me redo my computations


Quantos porcento N item representa no total geral - Consulta

Question: Bom dia, estou criando um relatório da curva ABC porém sou iniciante e ainda estou com algumas dificuldades.
Tenho uma tabela chamada: ITENS.
Com os campos: COD_ITEM, QuantidadeVenda, ValorUnitario, Subtotal, Descricao
Com uma consulta SQL consegui trazer o valor total de vendas:
SELECT SUM(SUBTOTAL) AS SUBTOTAL FROM ITENS
ORDER BY SUBTOTAL

E com outra consulta que não entendi porque não deu certo, traz os campos que pedi porém eles não são "somados" ficando vários registros do mesmo item.
SELECT COD_ITEM, QuantidadeVenda, Descricao, ValorUnitario,
Subtotal FROM ITENS
GROUP BY COD_ITEM, QuantidadeVenda, Descricao, ValorUnitario,
Subtotal

O que precisaria realmente trazer é um select que mostre comparado ao total de vendas quantos % representa cada item
Comment: Informe o BD pois alguns tem ferramentas nativas que facilitam este tipo de consulta.
Comment: Então aqui é o IBExpert
Comment: O firebird, esse é o pra gerenciar éerr
Comment: http://www.devmedia.com.br/forum/tem-como-fazer-isso-no-firebird/59910  ajudou ?
Comment: @WSS: Qual é a versão do Firebird?
Answer: Avalie se o código abaixo atende ao que necessita.
-- código #1
SELECT A.COD_ITEM, A.Subtotal,
       (A.Subtotal / B.Total * 100) as Perc
  from (SELECT COD_ITEM, sum(SUBTOTAL) as Subtotal
          from ITENS
          group by COD_ITEM) as A
       cross join
       (SELECT sum(SUBTOTAL) as Total
          from ITENS) as B;

Ou então:
-- código #2
with A as (
SELECT COD_ITEM, sum(SUBTOTAL) as Subtotal
  from ITENS
  group by COD_ITEM
),
B as (
SELECT sum(SUBTOTAL) as Total
  from ITENS
)
SELECT A.COD_ITEM, A.Subtotal,
       (A.Subtotal / B.Total * 100) as Perc
  from A cross join B;

Comment: Obrigado José, em cima do que me enviou conseguimos outras possibilidades! Grato.


Paragraph view reference?

Question: I am trying to meet the following requirement:
I want to create a node (custom content type) that contains only a paragraph reference.
I have the following paragraphs in my node

Billboard (large image + Caption)
Testmonial (slideshow sentences)
Body
Here i want to display a view that contains news articles (nodes from the custom news content type)
Call to action

But i can't seem to do this properly?
I can create a block display for my view and attach it to the page by path, but then the view is located below my paragraphs, where I want the view to be one of the paragraphs, since there is a call to action that needs to be located below the view.
Anyone ever tried this?
All suggestions welcome!
If you have a solution that does not use paragraphs, I am also happy to hear!
Many thanks in advance
EDIT:
After some additional searching, it seems that for D7, this module seems to be capable of doing this: https://www.drupal.org/project/entityreference_views_formatter more information can be found here: https://www.drupal.org/node/2756315
Still no solution for D8 though...
Answer: Using hook_entity_view, you can insert the view into the field's build array.
<code>function mymodule_entity_view(array &$build, EntityInterface $entity, EntityViewDisplayInterface $display, $view_mode) {

  if ($entity->getEntityType()->id() == 'node' && $entity->bundle() == 'example_content_type' && $view_mode == 'full') {
    $node_id = \Drupal::routeMatch()->getRawParameter('node');
    $index = 0;
    foreach($build['field_paragraph_field'] as $key => $value) {

      if (is_numeric($key) && $value['#paragraph']->bundle() == 'body') {
        $news_view = [
          '#type' => 'view',
          '#name' => 'my_news_feed',
          '#display_id' => 'block_1',
          '#arguments' => [$node_id],
        ];

        array_splice($build['field_paragraph_field'], $index + 1, 0, [$news_view]);

      }
      $index++;
    }
  }

}
</code>
Answer: Check out the Views Reference Field module. This module provides a new field type that allows you to reference a view display similar to an entity reference field. After installing the module create a new paragraph type with a viewsreference field. You now have a paragraph type that displays a view.
Answer: You should be able to acheive this with any module that can add a view as a field. Currently for D8:

Display Suite
Entity views attachment
Viewfield
Display fields
Answer: I did this by adding a paragraph type that is one Entity reference field.
There is a tutorial here:
https://www.mediacurrent.com/blog/drupal-8-how-reference-views-block-display-field/
It works great and takes paragraphs to the next level.

Paragraph view reference?


Syntax error while passing values in alloy script function

Question: I am dispaying the book details from database. I want to get details of a user who has checked out the book on onclick of the button.
My AUI script:
<aui:script>
        function displayUserDetails(userId,userName)
        {
            var details="

"+userId+"	"+userName+"

";
            AUI().use('liferay-util-window','aui-io-deprecated',function(A)
            {
                var dialog=Liferay.Util.Window.getWindow(
                {
                    dialog: {
                            title:'userdetails',
                            bodyContent:details,
                            centered:true,
                            modal: true,
                            width: 500,
                            height: 400
                    }
                 }).render();
            });

        }

        </aui:script>

I am calling the function here
<aui:button name="button9" value="details" id='getMoreInfo_<%=bookId %>' onclick="displayUserDetails(<%=userId %>,<%=un %>);" />

I am getting syntax error that while calling the function on button click (above line)
If i call the function like this...
onclick="displayUserDetails('<%=userId %>','<%=un %>');"

output will be like <%=userId%><%=un%> (in table)
onclick="displayUserDetails(<%=userId %>,<%=un %>);"

Comment: Can you try `onclick='displayUserDetails(<%=userId %>,"<%=un %>");'`
Comment: Hi Pankaj...tried it...Syntax error again...
Answer: Below code is working.....:-)
onClick='<%="displayUserDetails(\'"+userId+"\',\'"+un+"\');"%>'
credits to
Nishikant sapkal   @ http://www.liferay.com/community/forums/-/message_boards/message/27640265


Word wrapping in PhpStorm

Question: How can I enable word wrapping in PhpStorm?
I need to enable it only for some of my files (with extension .txt). Is it possible?
Comment: It's a shame that you can't specifically set it to soft wrap for certain file types. I only ever want to wrap if it's a HTML file, and it would be so much handier if I could set it to do that automatically instead of having to click through the menu each time.
Comment: @Maccath it appears you can do that now. See the "soft-wrap files" setting in PHPStorm.
Answer: For all files (default setting for opened files): Settings/Preferences → Editor → General → Use soft wraps in editor. You can now specify file names/extensions where this option will be enabled by default:

For the currently opened file in the editor: menu → View → Active Editor → Use Soft Wraps (Note: I've assigned custom Ctrl + Alt + R + shortcut for that)

For quite a while (since v2016 or so) you can also access this option via the context menu for the editor gutter area (the area with line numbers on the left side of the editor):

(Note: I have customised this menu quite a bit; by default it has much less items here)

Search Everywhere (Shift 2x times) or menu Help → Find Action... (Ctrl + Shift + A on Windows using the Default keymap) can also be used to quickly change this option (instead of going into Settings/Preferences).
Comment: right click on the left gutter (line numbers area) and choose Soft Wraps. a ver quick way to enable soft wraps per file
Comment: File > Settings > Editor > General > "Use soft wraps in editor"
Comment: phpStorm for Mac v10.0:
**PhpStorm** > Preferences > Editor > Use Soft wraps in Editor (as opposed to under the File menu)
Comment: File > Settings > Editor > Use Soft wraps in Editor.
Comment: @Ryan that option does not seem to exist anymore. Under **General** the option is not there.
Comment: It is there for me, phpStorm v9.0.2 on ubuntu
Comment: I am using PHP Storm on a Mac, 2017.3.4 and for me soft wraps only works in presentation mode.
Comment: @dan No idea unfortunately (Windows user here). As far as I'm aware it works (saw no such tickets/complaints). The only other thing -- it may just not remember the setting when you setup to have only 1 tab opened at a time... so when switching between files it forgets the option...
Comment: Or just tap Left Shift key twice and type "soft wraps" and I will find if for You.
Answer: You have to enable Soft Wraps. Find that option through this path.
Menu View → Active Editor → Use Soft Wraps
Answer: Right click on the line number area and choose:
Soft-Wrap All Files or Soft-Wrap Current File, i.e.:
Answer:
Menu File → Settings → Editor → Use soft wraps in editor: to turn them on for all files by default.

Menu File → Settings → Code Style → General → Wrap when typing reaches right margin
.. but that's different (it will make new line).
Comment: this helped me out.  It was driving me mad with the editor auto wrapping my code when I didnt want it to.  I couldnt find the option but this helped so ty ^^.
Comment: This must be really old, i could not find it
Answer: In addition to Settings -> Editor -> Use soft wraps in editor I recommend Use soft wraps in console and Use custom soft wraps indent with a setting of 4 to make the wraps indented to match the line they started on.
Answer: In PhpStorm 2019.1.3, it is possible to enable soft wrap for some file types only.
Answer: In PhpStorm 2019.1.3, you should add the file type you want to make soft wrapping on.
Go to Settings → Editor → General → Soft-wrap files, and then add any types you want:
Comment: you can actually use **\*.\*** for all type of file and extension.
Answer: You may also want to consider the Wrap to Column plugin, which implements the equivalent to Alt + Q in Emacs and gq in Vim. This may be preferable to having very long lines that are wrapped by the editor.
This plugin can be installed from any IntelliJ IDEA-based IDE by searching for Wrap to Column.
It has the additional benefit that you can choose to wrap only sections of text that you want :-)
Answer: If using PhpStorm 2019 and higher

Menu File → Settings → Editor → General.
There is the 'Soft-wrap files' input under the 'Soft Wraps' Header.

*.md; *.txt; *.rst; .adoc;

Add the file types to this field in which files you want them to be used.

*.md; *.txt; .rst; .adoc;.php;.js
Answer: For word wrapping in PhpStorm 2019.1.3, just follow below steps:
From the top navigation menu:
View → Active Editor → Soft-Wrap
That's it so simple.
Comment: It is not, you have to do it per file.
Answer: WebStorm 10.0.4
For wrapping text/code line by default, but for all types of file:
menu File → Settings → Editor → General → section "Soft Wraps" → checkbox "Use soft wraps in editor".
Comment: But the question is about PhpStorm. Please explain.
Answer: I want to soft-wrap .php files. Putting that in the allowed list still was not working. (For a screenshot, see Mohammed Zayan's answer.)
I entered <code>*.*</code> there, allowing all the files (I am fine with that) and soft wrap worked fine.
Answer: For word wrapping in PhpStorm:

Select File from the menu
From File select Setting
From Setting, select Editor
Select General from Editor
In general, checked Use soft wraps in editor from the Soft wraps section
Comment: Please add some explanation to your answer - is this triggered for all files with the same extension?

Word wrapping in PhpStorm


Ao carregar lista, as mat-select deverão vir já preenchidas

Question: Esse é meu html

                Lista de Aplicabilidades

                    <input type="button" class="btn btn-success" (click)="onCreate()" value="+">

                    Nome
                    Contexto
                    Tipo de Pagamento
                    Tipo de Entrega
                    MarketPlace

                        <input formControlName="id" type="hidden">
                        {{ aplicabilidade.name }}
                        <input formControlName="name" type="text">

                        {{ aplicabilidade.context }}
                        <input formControlName="context" type="text">

                        <input formControlName="id" type="hidden">
                        {{ aplicabilidade.typePaymentDetailsModel }}
                        <input formControlName="typePaymentDetailsModel" type="text">

                        {{ aplicabilidade.typeDeliveryDetailsModels }}

                            <mat-form-field>
                                <mat-select multiple formControlName="typePaymentDetailsModel" placeholder="Tipo de Pagamento" name="payment">
                                    <mat-option  *ngFor="let payment of dataSourcePayment" [value]="payment">
                                    {{payment.name}}
                                    </mat-option>
                                </mat-select>
                            </mat-form-field>

                        {{ aplicabilidade.marketPlace }}
                        <input formControlName="marketPlace" type="text">

                        <fa *ngIf="checkEdit()" name="pencil" (click)="initEditAplicabilidade(aplicabilidade)"></fa>
                        <fa *ngIf="aplicabilidade.edit === true" name="save" (click)="onUpdate()"></fa>

                        <fa *ngIf="checkEdit()" name="times" (click)="onDelete(aplicabilidade)"></fa>
                        <fa *ngIf="aplicabilidade.edit === true" name="ban" (click)="aplicabilidade.edit = null; initDefaultForm();"></fa>

Minha Component
export class ApplicabilityComponent implements OnInit {

  createForm: FormGroup;
  public dataSource: Model.ApplicabilityItem[];
  public dataSourcePayment: Model.TypePaymentItem[];
  public dataSourceDelivery: Model.TypeDeliveryItem[];
  public form:any;

  constructor(private _applicabilityService: ApplicabilityService,
              private builder: FormBuilder,
              private route: Router) {}

  ngOnInit() {
    this.onGet();
    this.initDefaultForm();
  }

  initDefaultForm() {
    this.createForm = this.builder.group({
      id: '',
      name: '',
      context: '',
      typeDeliveryDetailsModels: '',
      typePaymentDetailsModel: '',
      marketPlace: false
    });
  }

  onCreate(){
    this.route.navigate(['create-aplicability']);
  }

  onDelete(aplicabilidade: Model.ApplicabilityItem) {
    debugger;
    if (confirm('Deseja excluir o operador: ' + aplicabilidade.name + '?')) {

      this._applicabilityService
        .delete<any>(aplicabilidade.id)
        .subscribe((res) => {
          this.onGet();
        });
    }
  }

  onGet(){
    this._applicabilityService
      .getAllAplicability<Model.Result<Model.ApplicabilityItem>>()
      .subscribe((data: Model.Result<Model.ApplicabilityItem>) =>{
        this.dataSource = data.itens;
      });

      this._applicabilityService
      .getAllDelivery<Model.Result<Model.TypeDeliveryItem>>()
      .subscribe((data: Model.Result<Model.TypeDeliveryItem>) => {
      this.dataSourceDelivery = data.itens;
    });

    this._applicabilityService
    .getAllPayment<Model.Result<Model.TypePaymentItem>>()
    .subscribe((data: Model.Result<Model.TypePaymentItem>) => {
      this.dataSourcePayment = data.itens;
    });

  }

  initEditAplicabilidade(aplicabilidade: any){
    aplicabilidade.edit = true;
    this.createForm = this.builder.group({
      id: aplicabilidade.id,
      name: aplicabilidade.name,
      context: aplicabilidade.context,
      typeDeliveryDetailsModels: aplicabilidade.typeDeliveryDetailsModels,
      typePaymentDetailsModel: aplicabilidade.typePaymentDetailsModel,
      marketPlace: aplicabilidade.marketPlace
    });
  }

  checkEdit() {
    if (this.dataSource == null || this.dataSource.length == 0) return false;
      return this.dataSource.filter((item: any) => item.edit === true).length == 0;
  }

  onUpdate(){
    let formValue = this.createForm.value;
    this._applicabilityService.update<Model.Result<Model.ApplicabilityItem>>(formValue)
    .subscribe(success =>{
        this.onGet();
      },
        error =>{
      }
    );
  }

}

O que eu é, quando eu clicar em editar(Lápis no Form), ele me abre a tela de edição(Isso está fazendo), mas se eu tenho TypePayment, as mat-select deveriam vir selecionada. Pelo meu código, deveria funcionar, mas não funciona. Não pego erro algum, mas o Dropdown não vem com o(s) item(ns) selecionados.
Minha Model
export interface ApplicabilityItem{
        id: string,
        name: string,
        context: string,
        typePaymentDetailsModel: TypePaymentItem,
        typeDeliveryDetailsModels: TypeDeliveryItem,
        marketPlace: boolean
    }

    export interface TypePaymentItem{
        id: string,
        sgpTypePaymentId: number,
        name: string
    }

    export interface TypeDeliveryItem{
        id: string,
        sgpTypeDeliveryId: number,
        name: string
    }

Pelo POstman, esse é um exemplo de Aplicabilidade com ses tipos complexos:
{
            "id": "3bd8862d-1b15-42fe-9734-426364823ecb",
            "name": "Teste",
            "context": "Texto",
            "typePaymentDetailsModels": [
                {
                    "id": "00dfea8b-4265-42d2-842a-2b854bfcc4dc",
                    "sgpTypePaymentId": 2,
                    "name": "Crédito"
                },
                {
                    "id": "37f0bda4-8661-4339-9c33-3fcbbb2bcd84",
                    "sgpTypePaymentId": 3,
                    "name": "Teste"
                },
                {
                    "id": "200c2e50-468d-46b0-8325-2cb76502c4df",
                    "sgpTypePaymentId": 78,
                    "name": "Novo Teste"
                }
            ],
            "typeDeliveryDetailsModels": [
                {
                    "id": "75c7fdbb-82b7-4e2f-ac03-3696883820f4",
                    "sgpTypeDeliveryId": 1,
                    "name": "Bahia"
                }
            ],
            "marketPlace": true
        }

EDIT1
Conforme o colega Eduardo Vargas me orientou, tentei fazer conforme ele me disse. Fiz assim:
Component
compareValues(c1: Model.ApplicabilityItem, c2: Model.ApplicabilityItem): boolean{
    return c1 && c2 ? c1.id === c2.id : c1 === c2;
  }

Html
<mat-form-field>
   <mat-select multiple [compareWith]="compareValues" formControlName="typePaymentDetailsModel"
       placeholder="Tipo de Pagamento" name="payment" >
       <mat-option  *ngFor="let payment of dataSourcePayment" [value]="payment">
            {{payment.name}}
       </mat-option>
   </mat-select>
</mat-form-field>

e continua a dropdown no edit vindo sem os itens selecionados.
Answer: Voce tem que usar a funcao compareWIth do mat-select
<mat-select multiple formControlName="typePaymentDetailsModel" placeholder="Tipo de Pagamento" name="payment" [compareWith]="comapreValues">
   <mat-option  *ngFor="let payment of dataSourcePayment" [value]="payment">
        {{payment.name}}
   </mat-option>
</mat-select>

Ai no seu componente adicionar a funcao respectiva
compareValues(value1: any, value2: any): boolean {
    return value1.id=== value2.id; //adicione sua logica aqui
}

Comment: Eduardo, uma dúvida. O value1 e value2, o que realmente eu passo ali? O que eu estou comparando?
Comment: Entendi agora, o any seria o meu tipo, que no meu caso seria **Model.ApplicabilityItem**. Vou testar
Comment: Esse é o erro agora: >Error: Uncaught (in promise): Error: Value must be an array in multiple-selection mode.
Comment: C2 está vindo nulo. Pelo que eu entendi, C1 é a minha model que a API me entrega e C2 seria os valores gravados. Na comparação, ele mostraria exatamente o que é comum em C1 e C2, conforme comparação. C2 está null e não sei porque.
Comment: Cara, seu exemplo está correto e vou marcar a sua resposta. Porém, vou abrir outra thread para o erro, já que é outra coisa.


Determinant divisibility by 9

Question: I am having troubles with this homework problem, I tried expanding the determinant using co factor expansion but that didn't help. I know that for a number to be dividable by 9, the sum of its digits have to be a multiple of $9$. If anyone has an idea of what I may have overlooked I would greatly appreciate it.
The question is as follows:
Prove True or False. Let $a, b, c, d, e, f, g, h$ and $i$ be single digits. If the $3$ digit numbers
$abc, def$ and $ghi$ are divisible by $9$ then the determinant
\begin{vmatrix}
g & e & c \\
h & f & a  \\
i & d & b \\
\end{vmatrix}
is divisible by 9.
EDIT: The question was copied exactly as it appeared in my textbook. From what I understand "$abc$" denotes the number with digits $a$, $b$, and $c$. So, if $a = 1$, $b = 2$, and $c = 3$, then $abc$ means the number $123$, not $6$. I hope it's clear enough now.
Comment: I think you may have made a mistake in your determinant. $a$ does not appear in it anywhere.
Comment: Indeed, error is now fixed. Thank you
Answer: Hint $\ {\rm mod}\ 9\!:\ 0\equiv a\!+\!b\!+\!c \equiv d\!+\!e\!+\!f \equiv g\!+\!h\!+\!i\, \Rightarrow\, $ sum of rows $\equiv 0\,\Rightarrow\,$ rows linearly dependent.

Determinant divisibility by 9


curl_multi_getcontent gives me less results

Question: I want to store curl_multi_exec records to a variable but it didn't work out for me after using  CURLOPT_RETURNTRANSFER = TRUE, then I did some research and add curl_multi_getcontent this works fine I mean its record values for the variable but the problem is it only stores few results in the variable.
<code>$ch = curl_init();
    curl_setopt_array($ch, array(
        CURLOPT_URL => $stream_url,
        CURLOPT_ENCODING => "gzip",
        CURLOPT_FOLLOWLOCATION => true,
        CURLOPT_HTTPAUTH => CURLAUTH_BASIC,
        CURLOPT_TIMEOUT => 10,
        CURLOPT_USERPWD => $user.":".$pass,
        CURLOPT_WRITEFUNCTION => "print_out_data",
        //CURLOPT_RETURNTRANSFER => true,
        CURLOPT_VERBOSE => true // uncomment for curl verbosity

    ));

    $running = null;

    $mh = curl_multi_init();
    curl_multi_add_handle($mh, $ch);

    do {
        curl_multi_select($mh, 1);
        curl_multi_exec($mh, $running);
       $content = curl_multi_getcontent($ch);

          $arr = json_decode($content, true);
       // print_r($arr);
          $foo = $arr['id'];
          $bar = $arr['body'];

    } while($running > 0);

    curl_multi_remove_handle($mh, $ch);
    curl_multi_close($ch);
</code>
Answer: Before do{}while() write
<code>$content = array();
</code>
Line
<code>$content = curl_multi_getcontent($ch);
</code>
Replace to
<code>$content[] = curl_multi_getcontent($ch);
</code>
After your loop write
<code>print_r($content);
</code>


Regex Query get a group of string

Question: I just started learning regex on Powershell and I'm trying to resolve the problem below. I have this string $user_access and I want to get the list of users who are part of a group. See my example below.
Here's the $user_access content
$user_access = "
@group1
user1 = read
user2 = readwrite
user3 = read

@group2
user2 = read
user4 = readwrite
user5 = readwrite

@group3
user1 = readwrite
user4 = read
user6 = readwrite
"

I tried to use the pattern below.
$groupSelected = "group2"
$Result = $user_access.Split([Environment]::NewLine) | Select-String -Pattern "^\@$groupSelected"

but here's the only result I'm getting
@group2

Here's the result I want to get
@group2
user2 = read
user4 = readwrite
user5 = readwrite

I hope you guys can help. Thank you so much in advance!
Comment: Don't split lines, and use regex `@group2[^@]+`. You can check regexes [here](https://regex101.com/r/DpfrsD/1)
Answer:
You're providing individual lines to Select-String, which makes the latter report only those lines that match, i.e. you cannot match blocks of lines that way.
You can use the -replace operator to extract a block of lines:
$groupSelected = [regex]::Escape('group2')
$user_access -replace "(?sm)^.*^(@$groupSelected\r?\n.+?)\s*(?:\z|^@.+)$", '$1'

For an explanation of the regex and the ability to experiment with it, see this regex101.com page.
Answer: You can still use Select-String but with a little bit more complex regex and without splitting your input first:
$user_access | Select-String -Pattern "@$groupSelected[^@]+(?=\n|$)" -AllMatches | % { $_.Matches } | % { $_.Value }

Comment: Thanks a lot, @markalex! I'll review and test your pattern.

Regex Query get a group of string


How can I read separate numbers/lines from a .txt and input them to 2 different arrays

Question: I am trying to write a program that reads lines from a .txt and inputs them to 2 different arrays.
So far I have this:
    #include <stdio.h>

    int main() {
        FILE * ifp = fopen("input.txt","r");
        FILE * ofp = fopen ("output.txt", "w");
        int participants = 0, i;
        char name [10];
        float grade [10];
        float perc [10];

        fscanf(ifp, "%d", &participants);

        for (i=1; i<participants; i++) {
             fscanf(ifp, "%s", &name);

             fscanf(ifp, "%f", &grade);

        }

        printf( "%d\n", participants);
        printf( "%s\n", name);
        printf( "%f\n", grade);

        fclose(ifp);
        fclose(ofp);

        return 0;
    }

The txt I'm trying to read is:
    2
    Optimus
    45 90
    30 60
    25 30
    50 70
    Megatron
    5 6
    7 9
    3 4
    8 10

My problem is that it picks up the first 2 lines but stops when it gets to the numbers. I'm trying to get the names into an array and all the numbers, in pairs in a different array. Right now I'm just trying to check to see if I am picking up the numbers in the array but its not picking them all up.
This is the output that I get:
    2
    Optimus
    0.000000

Any ideas?
EDIT
This is my new code after some changes:
    #include <stdio.h>

    int main() {
        FILE * ifp = fopen("input.txt","r");
        FILE * ofp = fopen ("output.txt", "w");
        int participants = 0, i , j;
       char name [10];
        int grade [26];
        float perc [26];

        fscanf(ifp, "%d", &participants);

        for (i=1; i<participants; i++) {
             fscanf(ifp, " %s", name);
             fscanf(ifp, " %d", grade);

        }

        printf( "%d\n", participants);
        printf( "%s\n", name);
        printf( "%d\n", grade[0]);

        fclose(ifp);
        fclose(ofp);

      return 0;
    }

And my new output is :
    2
    Optimus
    45

EDIT 2
What I need to do with those numbers later is divide the first number in a line with the second number in that same line, multiply it by 10, and then have it display "*" according to the number. So it would print out like this:
    Optimus
    +:  *****
    -:  *****
    *:  ********
    /:  *******
    Megatron
    +:  ********
    -:  *******
    *:  *******
    /:  ********

"+" is the first line under a name.
"-" is the second line under that same name.
"*" for the third.
"/" for the fourth.
Answer: This is your main problem:
    printf( "%f\n", grade);

You're trying to print a pointer as a float. You want grade[0].
In this line:
    fscanf(ifp, "%f", &grade);

This will work, but it's not correct. It should be &grade[0] or just plain grade.
Of course in your final version, you'll need to adjust the array subscripts. You'll also need to allocate more arrays for the name - you currently can only store one.
To read in the data you will need to change the program a lot. You could declare grade as grade[10][8] (assuming a maximum of 10 participants), and store each of the 8 integers in the array. A loop like this would process it:
   for (i = 0; i < participants; i++) {
      fscanf(ifp, "%s", name);             // read the name (you need to fix this)
      for (j = 0; j < 8; j++) {
        fscanf(ifp, "%d", &grade[i][j]);   // store each number
      }
   }

Comment: fscanf(ifp, "%f", &grade); is technically correct as well. As &grade == grade.
Comment: @Armin, it's not. &grade is a pointer to an array, _not_ to an element.
Comment: Go try it and check the addresses of &grade and grade, it is the same.
Comment: Ok, so I changed it and now it picks up the first number but stops there. How can I make it so that it continues to pick up the other numbers and when it gets to the name, it adds that to the "name" array.
Comment: @Armin, I'm quite aware of that, but they're not the same type.
Comment: @Drieke - you'll need something a bit more complicated to read the text file. As it stands you read a number, then a word, then you start a loop that isn't going to help. Are there always a sequence of 4 pairs of digits after the word? If so, that makes it a lot easier.
Comment: @Drieke, I've given you a suggestion to help, but this is really for answering specific questions.
Answer: name and grade are arrays - the address of the variable is implicit for an array. So the address operator should not be used for these variables.
fscanf(ifp, "%s", name);
fscanf(ifp, "%f", grade);


Fetch 2 API and show the both result together. (React.JS)

Question: I'm new to react.js, and currently conducting a project in my university. I am facing some problem regarding to Reactjs. Hopefully you guys can guide me to solve this.
So I have an Item Listing API which is gonna display in card component. I also have an API for Item Photo View, which is actually pass the id from Listing API and also will show in card component. So each item has differents image. Therefore, I am gonna call this two API in my react and I will see all the Item in the UI include their images.
This is Listing result from console log.:

Every item have different photo, so I create another API to view the item photo according to their id
Here is my front-end code, how I call the API:
    componentDidMount(){
        // console.log(loginEmail)
          fetch(`http://localhost:9000/api/item/list`,)
          .then((resp)=>{
            resp.json().then((res)=>{
             console.log(res.data);
              this.setState({data: res.data});

            }

            )
          })

          const id = this.state.data.id;

          fetch(`http://localhost:9000/api/item/photo/view/${id}`,)
          .then((resp)=>{
            resp.json().then((res)=>{
             console.log(res);
              this.setState({res});}
            )
          })
        }

Render component:
    render() {
        const data = this.state.data;
        return (
                <>

Item list

                        {
                                Object.keys(data).map((key) =>

                                    {/*  */} //no idea for the this, how to call the image

{ data[key].organisation_name}

asdasdaasd

                                    <button type="button" className="btn btn-primary text-capitalize" >
                                        details
                                    </button>
                                    Item Detail

                                )
                        }

                </>
            );
    }
}

The first Listing API is able to run, and the detail of item are able to show in card. But, I can't get the result of Second API(Item Image View). The image could not shown out, and getting the error of this on my preview

Is there any place I'm wrong? or there is another way that I can get the image from 2nd API and put it in card?
Answer: Put inside of the first API call the second API call:
componentDidMount(){
        // console.log(loginEmail)
          fetch(`http://localhost:9000/api/item/list`,)
          .then((resp)=>{
            resp.json().then((res)=>{
             console.log(res.data);
              this.setState({data: res.data});
              const id = data.id;

              fetch(`http://localhost:9000/api/item/photo/view/${id}`,)
              .then((resp)=>{
                resp.json().then((res)=>{
                console.log(res);
                  this.setState({res});}
                )
              })

            }

            )
          })
        }

Or use async/await syntax to improve the readability.


Meta description to views

Question: Is there a way to add meta description to views in Drupal 8?
Answer: Use the "Metatag Views" sub module that comes with Metatag module. Link https://www.drupal.org/project/metatag

Meta description to views


Reading only two out of three columns with read.csv

Question: I have an ascii dataset which consists of three columns, but only the last two are actual data. Now I want to create a dotchart of the data by using read.csv(file = "result1", sep= " "). R reads all three columns. How do I avoid this?
Comment: I'll leave it here, but please ask future basic R questions on [StackOverflow](http://www.stackoverflow.com).
Comment: Actually, the current consensus seems to be that R questions are now welcome in CV. I can't find the discussion right now, but it's somewhere in http://meta.stats.stackexchange.com/.
Comment: http://stackoverflow.com/questions/5788117/only-read-limited-number-of-columns-in-r
Answer: You can use the colClasses argument to read.csv to select the columns you want.  In this case, you can set colClasses to c("NULL", NA, NA)
read.csv(file="result1", sep=" ", colClasses=c("NULL", NA, NA))

More generally, you can use colClasses to specify the particular types of columns; NA means to use the default approach which is to try and figure out what the column is automatically.  See the help page for read.csv for more details.
Answer: Another option is to read in the whole file, but keep only two of the columns, e.g.:
read.csv(file = "result1", sep = " ")[ ,1:2]

or, using column names, eg. if columns are named 'col1, col2, col3'
read.csv(file = "result1", sep = " ")[ ,c('col1', 'col2')]

Comment: Answer by @Brian takes less time as compared to yours.
Answer: This one takes less time as compared to the provided answers
library(data.table)
fread(file="result1", sep=" ", colClasses=c("NULL", NA, NA))


Drupal 7 CDN Module not altering URLs for themed Pages

Question: I have themed a page on my Drupal 7 website by mentioning the template file as
page--node--.tpl.php
The CSS and Images which are coming on this page are getting picked from the site itself and not from the static url i have configured in CDN.
Other than this page my website is picking CSS JS & Images from CDN
Any suggestions ?
Basic page--node--123.tpl.php
<?php
global $base_url;
$img_actl_path =  "$base_url/".drupal_get_path('theme','theme-name')."/images/v1/";
?>
<img src="<?php print $img_actl_path;?>image1.jpg" width="380" height="197" />

Comment: I created a new template with just image in anchor tag ( code updated in question ). Even this is not picking image from CDN
Answer: The problem is that you are not using the Drupal API.
The CDN module needs to be able to alter the path from your Drupal site to your CDN.  It does this by catching the URL via hook_file_url_alter(), and changing it.
The proper way to to make a URL in this case is with file_create_url().  Something like this should work
function MYTHEME_preprocess_page(&$variables) {
  $path = drupal_get_path('theme', 'MYTHEME');
  $variables['mysrc'] = file_create_url($path . '/images/v1/image1.jpg');
}

And then in your theme you would use
<img src="<?php print $mysrc; ?>" width="380" height="197" />

However, as Mołot suggests, using a proper theme function to make a renderable image would probably be best.


Prove if $T$ is nilpotent, $ST=TS$, and $\dim\operatorname{Nul}T=2$, then $S$ has at most $2$ distinct eigenvalues

Question:
Let $V$ be a finite-dimensional vector space, and let $S,T \in L(V)$ which commute, i.e.
$ST = TS$. Suppose $T$ is nilpotent with $\dim\operatorname{Nul}T = 2$. Prove that $S$ has at most $2$ distinct eigenvalues.

I tried to directly prove this one, but I failed. Then I tried to prove if $S$ has $3$ different eigenvalues, then I want to show $\dim\operatorname{Nul}T \neq 2$, but I also failed.
I doubt that "at most $2$ distinct eigenvalues" is trying to say that the eigenspace of $S$ is at most $2$.  Even though this is not totally right since if $S$ has $2$ distinct eigenvalues, it can also have $2$ to more dimensional eigenspace, but if there are $3$ distinct eigenvalues for $S$, then the eigenspace of it at least has dimension $3$. Thus probably there is something that restricts the dimension of the eigenspace of operator $S$.
Then since $\dim\operatorname{Nul}T=2$, this implies that if the null space of $T$ continues to enlarge, when $T^{n-1}$ is will be the maximum. I don't know whether this is useful. I also don't know how to use $ST=TS$ this given information.
Any help on this? Thanks
Comment: As a starting point, I recommend considering the case where $T$ is a matrix in Jordan form. Consider what the fact that $ST=TS$ tells you about the structure of $S$.
Answer: Hints
\begin{align}
x\in\ker{T}&\Rightarrow TSx=STx=0\\
&\Rightarrow Sx\in\ker{T}\ .
\end{align}
Therefore $\ S(\ker{T})\subseteq\ker{T}\ $. Let $\ \lambda\ $ be an eigenvalue of $\ S\ $ with corresponding eigenvector $\ v\ $. Since $\ T^0v=v\ne0\ $, and $\ T\ $ is nilpotent, there's a smallest natural number $\ k\ $ such that $\ T^kv\ne0\ $. Since
$$
ST^kv=T^kSv=\lambda T^kv\ ,
$$
$\ T^kv\ $ is also an eigenvector of $\ S\ $ corresponding to the eigenvalue $\ \lambda\ $. But $\ T^kv\in\ker T\ $ by the definition of $\ k\ $. Thus every eigenvalue of $\ S\ $ is also an eigenvalue of $\ S_{/\ker T}\in L(\ker T)\ $.  Can you finish it off from here?
Comment: I think your argument is fine, although it wasn't exactly the one I had in mind.  Since $\ S_{/\ker T}\ $ is a linear mapping of the two-dimensional space $\ \ker T\ $ into itself, it can have at most two distinct eigenvalues, and since every eigenvalue of $\ S\ $ is also an eigenvalue of $\ S_{/\ker T}\ $ then the same is also true of $\ S\ $.
Comment: I think I kind of understand what you mean. If $v$ is the eigenvector for $S$, then by the nilpotent property, there exists a integer $k$ such that $T^kv\neq 0$ but $T^{k+1}v=0$. Then now $T^kv$ is also a eigenvector of $S$ with the same eigenvalue. Thus, if $S$ has 3 distinct eigenvalues, with eigenvectors $u,v,w$. Then by the same idea, there exist minimal integers such that $T^au, T^bv, T^cw$ are linearly independent since they have distinct eigenvalues, and they are in the null space of $T$. This contradicts with the fact that $\dim $ null $T$ = 2. Is this right?


How to prove $\sum_{d|n} \mu(d) \sigma(n / d) = n$?

Question: How can I show that for all $n \in \mathbb{N}$;$$\sum_{d \mid n} \mu(d)\sigma(n/d) = n$$
Where $\sigma$ is the divisor function and $\mu$ is the Möbius function.
I am confused because isn't $\sum_{d \mid n}\mu(d)= 1$ if $n=1$ and 0 otherwise?
Comment: What are you confused about?
Answer: The functions you are finding the convolution of are multiplicative. So their convolution is.
Thus you need only verify the equality for prime powers, and the result will follow for all $n$.
If a number $k$ is divisible by a square greater than $1$, then $\mu(k)=0$. So for prime powers the sum is easy to compute.
Remark: If $m$ is the product of $d$ distinct primes, then $\mu(m)=(-1)^d$. If $m$ is divisible by a square $\gt 1$, then $\mu(m)=0$.  For details, google the Möbius function.
Comment: Let $n=p^k$, Then the divisors $d$ of $n$ are $d=1,p,p^2,\dots,p_k$. When $d\ge p^2$, $\mu(d)=0$. So the only interesting terms correspond to $d=1$ and $d=p$. When $d=1$, $\mu(d)=1$ and $\sigma(n/d)=1+p+p^2+\cdots +p^k$. When $d=p$, we hane $\mu(d)=-1$, and $\sigma(n/d)=1+p+\cdots +p^{k-1}$. Subtract. We get almost total cancellation, the result is $p^k=n$.
Comment: $$n=\sum_{k=1}^n \sigma(\gcd(k,n))e^{2\pi i k/n}$$
Comment: @AndreNicolas Could you please write how you verify for prime powers. I did understand why we use only the prime powers, but how do we get n?
Answer: $$\sum_{d \mid n} d = \sigma(n)$$ and so by the Möbius inversion formula, we have that
$$\sum_{d \mid n} \mu(d) \sigma\left(\frac{n}{d}\right) = n$$


vector push_back zero into an empty vector

Question: I encountered the following property of std::vector that I did not know and I was wondering if someone could clarify it for me.
I think this code:
int main()
{
  int i = 5;
  vector<int> vector;
  while(i > 0){
    vector.push_back(i);
    --i;
  }
}

should produce a vector with the following elements:
5, 4, 3, 2, 1

However, when I run the code above what I get is:
5, 4, 3, 2, 0

In order to explore what is going on I printed the vector at each stage and I get the following sequence:

i=5  -- vector (0)
i=4 -- vector(5, 0)
i=3 -- vector(5, 4, 0)
i=2 -- vector(5, 4, 3, 0)
i=1 -- vector(5, 4, 3, 2, 0)

So I think somehow a zero gets push_backed in the first cycle (where 5 should be) which is very strange. If I try a bigger (say n=10) then the last element is modified every time cycle.
I do not understand what's going. My guess is that there is something in the buffer maybe that get's push back before 5 and then this puts the push back and the cycle out of phase. Or is it something else?

Edit:

So as people kindly pointed out -or implied- in the comments the error was in the printing routine that I was used. For the record it was:
void print_vector(std::vector<int> vector){
  cout << string(10, '-') << endl;
  cout << "(";
  for(int i=0; i < vector.size() - 1; ++i){
    cout << vector[i] << ", ";
  }
  cout << vector[vector.size()];
  cout << ")" << endl;

}

And the mistakes comes from the vector[vector.size()] which does weird things when the vector does not have elements I guess.
Comment: `vector[vector.size()]` is always illegal and results in undefined behaviour, as it tries to acces one-past-end element of the vector.
Comment: Can you show us the printing code too? MVCE would be ideal.
Comment: [Works for me](http://ideone.com/lcCxgb) if I add code to print the vector at each stage. Please add the code you use to print it, to make a complete test case.
Comment: This is not the code you're running. See: http://ideone.com/b1qxSV
Comment: I suppose an answer should tell you "where did I go wrong?". Post the complete code and your environment.
Answer: Yes, your error is indeed in the printing code. The
vector[vector.size()]

expression is illegal in C++. Vector contains elements in range [0;vector.size()), and the expression tries to access the non-existent. one-past-end element of the vector, which is undefined behavior.


Count recursive groupings of elements in pairs

Question: For a given set of elements lets say $s=\{A,B,C,D\}$ I want to compute how many unique elements can be obtained converting the initial set in subsets of size two (pairs). Pairs can be made taking two elements or one element and two elements previously grouped, all the elements of the set must be used and the order of the pairs doesn't matter. For example $(((A,B), C), D)$ would be an answer and $((A, B), (C, D))$ another valid one for the previous set. As the order doesn't matter I can use the next formula ($h$ is the length of the set):
$$
\sum\limits_{i=3}^h \binom {i} {2}
$$
This formula can be used as recursively in every step one element is removed and the subsets of size $2$ are computed for the new length. The problem is that when $h >= 4$ it includes duplicates. For example for $h = 5$ it gives $180$ but there are only $105$ unique solutions. For example The solution $( ((A,B), C), (D, E) )$ is counted twice. Is there any way to count the duplicates and therefore express a formula for unique values given the length of the set $(h)$?
Comment: To make sure that we get the problem right: what is the correct answer for h=4 ?
Comment: The correct answer for h=4 is 18 $$\binom {4} {2} * \binom {3} {2}$$. I can enumerate all the answers if it helps
Comment: Mmm I count 12 of the form (A,(B,(C,D))) and 3 of the form ((A,B),(C,D)). What I'm missing?
Comment: Sorry you are right, the formula counts the pairs of the form ((A,B), (C,D)) twice there are 15 uniques and the formula counts 18. I have updated the question to reflect that duplicates start at h=4
Comment: For $h=5$ I get 135...
Comment: ... or rather 105
Comment: Yes it is 105 I didn't count the duplicates correctly from the beginning I will update the numbers. Thanks again
Answer: I didn't get a formula or algorithm, but in case this helps:
Consider all full rooted binary trees with $h$ leaves. Restrict them to the unbalanced ones, such that each right inner node has at least as descendants as its left sibling. Call that set of trees $I_h$. For each tree $i \in I_h$, let $e_i$ be the count of its balanced inner nodes: those nodes that have equal number on descendants on each branch. Then the number we want is given by
$$S(h)=  \sum_{i\in I_h}\frac{h! }{2^{e_i}}$$
For example, for $h=4$ we have two trees (one fully balanced, with $e_1=3$, fully unbalanced with $e_2$=2) so
$$S(4) = \frac{4!}{2^3}+\frac{4!}{2} = 3+12=15$$
For $h=5$ I count three trees and
$$S(5) = \frac{5!}{2^2}+\frac{5!}{2^3}+\frac{5!}{2} = 30 + 15 + 60=105$$
For $h=6$ I get (if didn't miss anything)
$$S(h) = 6! \left(\frac{1}{2^3} +\frac{1}{2^4}
+\frac{1}{2^2}+\frac{1}{2^1}+\frac{1}{2^3}+\frac{1}{2^2}\right)=945$$
Update: Looking for the sequence in OEIS, it seems that the answer is given by A001147
$$S(h) =(2h-3)!! = 1 \times 3 \times 5 \cdots (2h-3)$$
Update: Here's a Java efficient code
<code>public class CountPairings {

    int MAX_H = 20;
    long[][] trees = new long[MAX_H + 1][];

    /**
     * index: amount of internal balanced nodes (from 1), value: how many trees
     */
    public long[] computeTrees(int h) {
        if (trees[h] == null) {
            if (h == 1)
                trees[h] = new long[] { 1, 0 };
            else if (h == 2)
                trees[h] = new long[] { 0, 1 };
            else {
                long[] t = new long[h];
                for (int h1 = 1, h2 = h - 1; h1 <= h2; h1++, h2--) {
                    long[] t1 = computeTrees(h1);
                    long[] t2 = computeTrees(h2);
                    // cartesian product
                    for (int i1 = 0; i1 < t1.length; i1++) {
                        if (t1[i1] == 0)            continue;
                        for (int i2 = 0; i2 < t2.length; i2++) {
                            if (t2[i2] == 0)        continue;
                            int ix = i1 + i2;
                            if (h1 == h2)   ix++;
                            t[ix] += t1[i1] * t2[i2];
                        }
                    }
                }
                trees[h] = t;
            }
        }
        return trees[h];
    }

public long countCombinations(int h) {
    long c = 0, fact = 1, pow2 = 1;
    for (int i = 2; i <= h; i++)
        fact *= i;
    long[] t = computeTrees(h);
    for (int i = 1; i < t.length; i++) {
        pow2 *= 2;
        c += fact * t[i] / pow2;
    }
    return c;
}

    public static void main(String[] args) {
        CountPairings cp = new CountPairings();
        for (int h = 2; h <= 12; h++) {
            long c = cp.countCombinations(h);
            System.out.printf("%2d %d\n", h, c);
        }
    }

}
</code>
Output:
<code> 2 1
 3 3
 4 15
 5 105
 6 945
 7 10395
 8 135135
 9 2027025
10 34459425
11 654729075
12 13749310575
</code>
Comment: Thanks for accepting the answer, but perhaps you'd prefer to un-accept it (there is no hurry) to attract other answers.
Comment: Ok! although your answer is not a formula is a valid answer. Thank you for that! Also the discussion with you helped me to get a deeper understanding of the problem and to code an efficient algorithm to enumerate the unique answers. Thanks!!
Comment: You're welcome. You have an afficient algorithm for arbitrary $h$?
Comment: Yes, basically is based on the original formula I gave but adding tabling to avoid the expansion of the duplicated tuples
Comment: Now you really deserve the best answer! Muchas gracias


Polynomials - Relation of Divisibility

Question: The exercise I am having difficulty solving is the following one :
Suppose $P$ and $Q$ are two polynomials with integer coefficients. Suppose also that for all $(m,n) \in \mathbb{Z}^2$ we have $P(m)-P(n) | Q(m)-Q(n)$. Show that there exists a polynomial $H \in \mathbb{Q}[X]$ such that $Q= H \circ P$.
The issue is that I do not now how to characterize effectively the existence of such a polynomial $H$... I have tried, without success, to use the following result :
if $P,Q$ are two polynomials with integer coefficients such that $P(n)|Q(n)$ for infinitely many integers $n$, then $P$ divides $Q$ within $\mathbb{Q}[x]$.
Does anyone have an idea ?
Answer: Theorem 2.3 in http://www.math.uci.edu/~mfried/paplist-cov/SepVarbsCurves69.pdf might  be helpful:
(Fried-MacRae)   Let $K$ be an arbitrary field, and  let $f(t),g(t),f_1(t)$
and $g_1(t)$ be polynomials in $K[t]$. Then $f_1(x)-g_1(z)$ divides $f(x)-g(z)$ in $K[x,z]$ if and only if there exists a polynomial $F(t)$ in $K[t]$ such that $f(t)=F(f_1(t))$ and  $g(t)=F(g_1(t))$.
Comment: Are you aware of a more elementary proof, since here we are working with fairly simple fields (i.e the rational numbers) ?
Comment: @Marsan. If think you can prove Fried-MacRae's result without Galois Theory. One idea is writing the polynomial $f(x)$ is basis $f_1(x)$. That is,
Comment: write $$f(t)=a_n(t)f_{1}(t)^n+\cdots+a_1(t)f_{1}(t)+a_0(t)$$
where $\deg a_{i}(t)<\deg f_{1}(t)$ for all $i=0,\ldots,n$. Thus, the polynomial $F(T)=a_n(t)T^n+\cdots+a_1(t)T+a_0(t) \in K(t)[T]$ is such that
$F(f_1(t))=f(t)$. Now  find a similar polynomial  $G(T) \in K(t)[T]$  such that
$F(g_1(t))=g(t)$. Then, try to see if  the divisibiity condition  will let you conclude that $F(T), G(T) \in K[T]$ and that they are the same polynomial.

Polynomials - Relation of Divisibility


Using GLMM to explain vegetation change as a function of change in soil parameters

Question: I have a dataset that consists of vegetation datasets (species/abundancy tables) and soil parameters (tested for ten parameters per soil core). Three different rounds of these data are recorded in three different years (2002, 2006, 2018). Dataset is completely balanced.
Experimental setup is as follows:
vegetation transects (blocks) along gradient. Each block consists of 20 plots. Vegetation recorded with ordinal Braun-Blanquet scale.
My total dataset is
3(years)x140 species/abundancy tables
3(years)x450 soil measurements
I want to explain change in vegetation as a function of change in soil parameters with plot nested in block as a random factor to account for spatial autocorrelation. To do so, i want to use a GLMM as follows:
model <- glmer(Vegetation change~soil parameter change + (1|Block/Plot).
My question is:
how do I include change over time (for both response and fixed factor) as a factor?
Is it better to use a distance based value, Bray-Curtis for example, and run two models comparing year 1 and 2, and year 2 and 3? Or do I include all the data at once and give each value a unique coding corresponding with the year?
Answer: I would go for two separate models because the slope would be the same for both comparisons in a unique model, unless you add an interaction term between the soil parameter change and the comparison ID, which would complexify the interpretation of your model.


Procedural dependencies in an OOP application

Question: Despite the number of similar questions, I haven't yet managed to find any such concrete answer (or at least a strongly opinionated individual)
I've (at this time) decided to use "helper" classes, which are simply aggregates of static methods in a class, fittingly named String for example. The class itself has no prospect of being an object instance, and has no reason to.
Now I've noticed many people consider this abuse. I do too, and have only resolved to maintain this approach for the benefits of code organization and (more importantly) auto-loading.
String::keysplode('|', 'apple|banana|coconut', array('a', 'b', 'c'));

Here we have keysplode(). It performs explode() on the given string, with the given delimiter, then calls trim() on each element. The resulting array is passed with the array argument to array_combine(). The result?
array('a' => 'apple', 'b' => 'banana', 'c' => 'coconut');

Great! Fancy! Who cares?
The point is, this function really doesn't belong in a class. Right now it lives at \Package\Common\String::keysplode(), and while that's a nice place for it, I can see how that is considered "abuse".
I have a plethora of these functions, ones that belong in the array_* or  str_* pseudo-namespace, and elsewhere. The further problem is, my "genuine" classes, ones that leverage OOP correctly (or so I believe) use these functions intimately.
The "question", as it were, is where should functions like this go?
When we create functions that extend the "core" functionality of a language, where do we put these functions? Furthermore, how do we manage the dependencies created upon the functions by other parts of an application?
Comment: This might be more appropriate for programmers.stackexchange.com
Comment: This is vastly subjective and completely non-constructive.
Comment: @TomalakGeret'kal -- I beg to differ. This is a surely a common issue experienced by many working with PHP and other languages which were procedural from inception, and have only now began moving towards an OOP paradigm. I understand solutions can be application specific, however certainly someone experienced can shed some insight on common practices or approaches to dealing with such issues.
Comment: @Bracketworks: I never disputed any of that. I said it's subjective and non-constructive, and as such this is not the right place for it.
Comment: @TomalakGeret'kal -- Where would you suggest I seek out such information? It's troubling when you build intuitive parts to an application, but are then stuck simply trying to name and place them.
Comment: @Bracketworks: Some message board perhaps? programmers.SE tends to edge closer to this sort of stuff, too.
Comment: @TomalakGeret'kal -- Fair enough. I concede to the closing votes; however should I vote this question be moved to Programmers, or should I simply delete this one and reword it for that board?
Comment: @Bracketworks: A migration vote is fine. You can always edit it there if required (don't think it would be though)
Answer: Putting library functions into a static class has been a PHP idiom because PHP lacked namespaces and the syntax for static methods is similar to the syntax for accessing package functions in Perl.
Now that PHP has namespaces, the clear answer is to put these methods into namespaces (and no longer static classes). While I think that this will be a slow transition (because so many people are still not on PHP 5.3, and many people are on shared hosts), the adjustment is readily apparent and hopefully framework and library developers accept this new idiom (which is standard for other languages with namespaces like C# and Perl).
<?php

namespace Foo;

function foo () {
    echo 'foo';
}

namespace Bar;

use Foo;

Foo\foo();

Answer: In my opinion developers are developing within an exact language wether is that PHP or anything else. Most of the time a class written in PHP will be used in PHP, so you don't really need to care about core functions. Using them is absolutely a correct way, you only have to take care of those functions' changes.
If you consider using another library's services, that's a whole other thing, but in this case, you don't have to worry about the core functionalities of a language.


send event from asp.net to google calender in web application

Question: I want to send events to my google calendar account from asp.net application
Answer: look at the API
Like Murph said in the comment, link to the guide for .Net API
Comment: i already done with api,added all google.gdata.calender dll then too its not working plz send me whole code
Comment: Which has a specific section for .NET: http://code.google.com/apis/calendar/data/2.0/developers_guide_dotnet.html
Comment: @priti, I never played with google API, I wont spent a few hours to learn something that I'm not to use again.
Comment: @priti we can answer specific questions but there is already sample code in the API docs and we're not going to be able to add anything to that without some more depth to the question
Answer: Have a look at Google API Calendar
http://code.google.com/intl/nl-NL/apis/calendar/
http://code.google.com/intl/nl-NL/apis/calendar/data/2.0/developers_guide_dotnet.html#CreatingSingle
Create single-occurance event
<code>EventEntry entry = new EventEntry();

// Set the title and content of the entry.
entry.Title.Text = "Tennis with Beth";
entry.Content.Content = "Meet for a quick lesson.";

// Set a location for the event.
Where eventLocation = new Where();
eventLocation.ValueString = "South Tennis Courts";
entry.Locations.Add(eventLocation);

When eventTime = new When(DateTime.Now, DateTime.Now.AddHours(2));
entry.Times.Add(eventTime);

Uri postUri = new Uri("http://www.google.com/calendar/feeds/default/private/full");

// Send the request and receive the response:
AtomEntry insertedEntry = service.Insert(postUri, entry);
</code>


Append métodos em uma lista - Python

Question: Eu tentei adcionar 4 métodos numa lista(methodList):
def setVar(self, number):
    self.var = number

methodList = list()

for y in range(4):
    methodList.append(setVar(self, y))

e a função não funciona:
>>> self.var = 0
>>> methodList[1]
>>> print(self.var)
0

se funcionasse seria assim:
>>> self.var = 0
>>> methodList[1]
>>> print(self.var)
1

ai eu printei a função pra ver:
>>> print(methodList[1])
None

Onde eu errei?
Comment: Esse primeiro código, você executou ele somente uma vez, e antes de tentar esse código seguinte no console, certo?
Comment: sim, na verdade foi tudo no código, só to usando as setas pra representar o meu problema, mas não tem erro de ordem nas linhas
Comment: O que exatamente você pretendia fazer, então? No seu loop, cada chamada do método atribui o `var` do objeto `self`, sobrescrevendo o valor anterior. Então, quando você faz `self.var = 0` você sobrescreve ele mais uma vez. Você queria que cada valor fosse pra uma posição da lista? (se sim, ver [a resposta do Cigano](http://pt.stackoverflow.com/a/87797/215)) Ou era alguma outra coisa que pretendia (por exemplo, ao chamar `methodList[1]` de alguma forma que o efeito colateral fosse alterar `self.var`)? Me parece que você tentou fazer uma aplicação parcial de funções, mas não tenho certeza...
Comment: sim, queria tentar aplicar o methodList[1] e chamar o setVar(1), mas não estava conseguindo, o cigano ajudou, obrigado a todos
Comment: Eu não estou entendendo nada (pois se sua lista chama `methodList`, por que ela guarda valores?), mas de todo modo deixei uma resposta assumindo o segundo caso.
Answer: Se o que você quer é fixar alguns argumentos de um método (como sua lista chama methodList, imagino que você queira guardar nela métodos, não valores) você pode usar functools.partial. Nela você estabelece um número fixo de argumentos, e recebe de volta uma "função parcial":
def setVar(self, number):
    self.var = number

methodList = list()

for y in range(4):
    methodList.append(functools.partial(setVar, self, y))

self.var = 0
methodList[1]() # self.var agora deve ser 1

Comment: Muito legal esse `functools`. Não conhecia.
Answer: Sua função não imprime nada. Por isso não retorna nada no print.
Fiz algumas correções:
def setVar(number):
    var = number
    return var

methodList = list()

for y in range(4):
    methodList.append(setVar(y))

print(methodList[1])

Não precisa usar self pro seu exemplo porque você não especificou uma classe.
Veja aqui funcionando.
Comment: estou com um probleminha maior agora, mas é a mesma coisa(quase): self.canvasButtonCommands.append(setMusics(self, genreDirectory[a])) --------- self.canvasButtonCommands[0] não faz nada, porém o código dele ta escrito pra fazer...
Comment: Outro problema merece outra pergunta, certo?
Comment: não posso criar uma pergunta antes de 90 minutos '-', da um help plz, acho que tem haver com o [a]
Comment: Tem certeza de que não faz nada? Já tentou colocar um `print` dentro do método pra conferir?
Comment: já descobri o erro, toda vez que eu faço isso: self.canvasButtonCommands.append(setMusics(self, genreDirectory[a])) ---- ele chama a função, mas era só pra dar append
Comment: Faça o Append sem parâmetros. Use os parâmetros na hora de chamar. Se precisar, use uma estrutura auxiliar com o método e os parâmetros separados.

Append métodos em uma lista - Python


Rust equivalent to Swift extension methods with equal generic parameter constraint?

Question: In Swift, I can add method to a generic type with parameter equality constraint.
extension Optional where Wrapped == String {
    // Available only for `Optional<String>` type.
    func sample1() { ... }
}

How to do this in Rust?

Update
This feature is called Extensions with a Generic Where Clause.
I think this is basically same feature with Rust's impl with where clause without explicit trait.
trait OptionUtil {
    fn sample1(&self);
}

impl<T> OptionUtil for Option<T> where T:std::fmt::Debug {
    fn sample1(&self) {
        println!("{:#?}", self);
    }
}

Is equivalent (without explicit trait) to
extension Optional where Wrapped: DebugDescription {
    func sample1() {
        print("\(self)")
    }
}

Therefore, I thought this Rust code would work, but it doesn't work with an error. (equality constraints are not yet supported in where clauses (see #20041))
impl<T> OptionUtil for Option<T> where T == String {
    fn sample1(&self) {
        println!("{:#?}", self);
    }
}

Comment: Does he? Is figured he just wanted `impl Foo for Option` for some extension trait `Foo`. @Eonil, since not all of us are familiar with Swift, can you describe what this feature does?
Comment: https://doc.rust-lang.org/std/cmp/trait.PartialEq.html and https://doc.rust-lang.org/book/ch10-02-traits.html
Comment: @Stargateur I think `PartialEq`/`Eq` trait is equivalent to `Equatable` protocol in Swift. Which is not what I am asking here.
Comment: oh so you want https://github.com/rust-lang/rfcs/blob/master/text/1210-impl-specialization.md ?
Comment: @mcarton I think what you talked is what I was looking for. It works as I expected. Thanks. Can you convert your comment into an answer? I updated my question BTW.
Comment: @Stargateur I think it's something else though it looks like something highly related.
Answer: You can just implement the trait for the concrete type Option<String>:
impl OptionUtil for Option<String> {
    fn sample1(self: &Self) {
        println!("{:#?}", self);
    }
}

I wrote crate, type_eq, which would let you write something that looks more like your Swift example. But it is identical to implementing the trait for Option<String>:
use type_eq::{Constrain, TypeEq};
use std::fmt::Debug;

trait OptionUtil {
    fn sample1(&self);
}

impl<T> OptionUtil for Option<T>
where
    Constrain: TypeEq<T, String>,
    T: Debug,
{
    fn sample1(&self) {
        println!("{:#?}", self);
    }
}

fn main() {
    let s = Some(String::from("hello"));
    println!("{:?}", s);
}

There are actually very few cases where this crate is useful. Most of the time the simpler code above will work, and is preferred.


Derivative of eigenvectors of a symmetric matrix-valued function

Question: Given a real symmetric $3\times3$ matrix $\mathsf{A}_{ij}$ and its derivative (w.r.t. some parameter, let's call it time) $\dot{\mathsf{A}}_{ij}$, I want to measure/obtain the rotation (rate and direction) of the eigenvectors (the eigenvectors of a real symmetric matrix form an orthonormal matrix). How can this be done?
Edit Since the eigenvectors of a real symmetric matrix are mutually orthogonal, the change of the eigenvectors can only be an overall rotation. An infinitesimal rotation is uniquely determined by the rate $\boldsymbol{\omega}$ such that $\dot{\boldsymbol{x}}=\boldsymbol{\omega}\times\boldsymbol{x}$ for any vector $\boldsymbol{x}$. My question then becomes how to obtain $\boldsymbol{\omega}$.
Comment: Solve for the eigenvalues in terms of the matrix coefficients.  Determine their derivatives wrt time (these expressions will include the derivatives of the matrix components).  Then solve for the eigenvectors in terms of the eigvals and mtx coefficients, and take *their* time derivatives, which will depend on eig.vals, coefficients, and their derivatives, but are just linear equations.  It doesn't sound trivial, but for a 3x3 there are closed form solutions for all of it...
Comment: @MichaelStachowsky There is no simpler way, or over all relation? It seems such a genuine problem.
Comment: Not sure, that's why I put my response as a comment, not an answer.  I doubt it, though.  You'll still need to relate the roots of the polynomial to the coefficients
Answer: We start, as usual, with the equality $Av=\lambda v$ where $v^Tv=1$ and $A$ is a $C^1$ function. It is absolutely necessary that the  considered eigenvalue $\lambda$ is simple - then $\lambda,v$ are $C^1$ function- otherwise, $v$ may be non-continuous.
Proposition. Under the above hypothesis, $\lambda',v'$ are functions of $A,A',\lambda,v$. More precisely,
$\lambda'=v^TA'v,v'=w-(v^Tw)v$ where $w\in(A-\lambda I)^{-1}((v^TA'v)v-A'v)$.
Proof. We obtain $A'v+Av'=\lambda'v+\lambda v',v'^Tv=v^Tv'=0,v^TA=\lambda v^T,v^TAv'=0$.
Moreover, $v^TA'+v'^TA=\lambda'v^T+\lambda v'^T$ implies $v^TA'v=\lambda'$.
$A'v+Av'=(v^TA'v)v+\lambda v'$ implies $(A-\lambda I)v'=(v^TA'v)v-A'v$ and, finally, $v'=w+kv$, where $w\in (A-\lambda I)^{-1}((v^TA'v)v-A'v)$. It remains to calculate $k$; $v^Tv'=v^Tw+kv^Tv$ implies $k=-v^Tw$ and we are done.
Comment: I do not see where is the improvement when you replace $v'$ with $\dot{v}$. On the other hand, I think you are very pretentious. What have you found so far?
Comment: I was on a similar track. What I really want to obtain is the rotation rate $\boldsymbol{\omega}$, where $\dot{\boldsymbol{v}}=\boldsymbol{\omega}\times\boldsymbol{v}$. Can one show that the value obtained for $\boldsymbol{\omega}$ is the same for every eigenvector considered (except when $\boldsymbol{\omega}$ is co-linear with $\boldsymbol{v}$)? Also, what is the meaning of '$\in$' in this context, i.e. how is the singularity of the matrix $(\boldsymbol{\mathsf{A}}-\lambda\boldsymbol{\mathsf{I}})$ dealt with?
Comment: 1.  Choose $\omega=a w \times v$ where $a$ is s.t. $||\omega||=||v'||$. 2. Of course, $\omega$ depends on the considered eigenvalue. 3. Since $v$ is a basis of $\ker(A-\lambda I)$, the result given for $v'$ does not depend on the choice of $w$.
Comment: $\omega$ **must** be the same for all eigenvalues. This is because the change in the eigen system between $A$ and $A+dA$ can only be an (infintesimal) rotation (the eigenvalues of a real symmetric matrix form a orthogonal basis and a rotation is the most general map between such). and a rotation is uniquely determined by $\omega$.
Answer: Suppose that a given (differentiable) matrix-valued function $\mathrm A : \mathbb R \to \mbox{Sym}_n(\mathbb R)$, where $\mbox{Sym}_n(\mathbb R)$ denotes the set of $n \times n$ real symmetric matrices, does have a time-varying spectral decomposition
$$\mathrm A (t) = \mathrm V (t) \, \Lambda (t) \,\mathrm V^\top (t)$$
where the columns of orthogonal matrix $\mathrm V (t)$ and the diagonal entries of diagonal matrix $\Lambda (t)$ at a given $t$ are the (unit) eigenvectors and eigenvalues of $\mathrm A (t)$, respectively.
Differentiating with respect to time, we obtain a nonlinear matrix differential equation in $\rm V$ and $\Lambda$
$$\dot{\mathrm A} (t) = \dot{\mathrm V} (t) \, \Lambda (t) \,\mathrm V^\top (t) + \mathrm V (t) \, \dot\Lambda (t) \,\mathrm V^\top (t) + \mathrm V (t) \, \Lambda (t) \,\dot{\mathrm V}^\top (t)$$
where $\dot{\mathrm A}$ serves as known input. From $\mathrm A (0)$, we obtain initial conditions $\mathrm V (0)$ and $\Lambda (0)$. We have:

$\binom{n+1}{2}$ ordinary differential equations.
$n^2$ (algebraic) quadratic equations (to ensure that $\mathrm V$ stays orthogonal).
$n^2 + n = (n+1) n = 2\binom{n+1}{2}$ functions to determine.

Unfortunately, I do not know how to solve this matrix ODE. In fact, I am not even sure that a time-varying spectral decomposition of a symmetric matrix-valued function is actually legal.
Answer: In order to simplify the algebra, let me first without loss of generality rotate into a coordinate frame where the eigenvectors are the Cartesian basis,
$$
\boldsymbol{\mathsf{A}} =
\begin{pmatrix}
\lambda_1 & 0 & 0 \\ 0 & \lambda_2 & 0 \\ 0 & 0 & \lambda_3 \end{pmatrix},
\quad\text{and}\quad
\dot{\boldsymbol{\mathsf{A}}} =
\begin{pmatrix}
\dot\lambda_1 & a & b \\ a & \dot\lambda_2 & c \\ b & c & \dot\lambda_3 \end{pmatrix}
$$
with some coefficients $a$, $b$, and $c$. The above relation for $\dot{\boldsymbol{\mathsf{A}}}$ follows from loup blanc's $\dot\lambda=\boldsymbol{v}^T\cdot\dot{\boldsymbol{\mathsf{A}}}\cdot\boldsymbol{v}$. We now express the derivatives of the eigenvectors as rotation, i.e. $\dot{\boldsymbol{v}}=\boldsymbol{\omega}\times\boldsymbol{v}$, giving
$$
\dot{\boldsymbol{v}}_1 =
\begin{pmatrix} 0 \\ \omega_z \\ -\omega_y \end{pmatrix},\quad
\dot{\boldsymbol{v}}_2 =
\begin{pmatrix} -\omega_z \\ 0 \\ \omega_x \end{pmatrix},\quad
\dot{\boldsymbol{v}}_3 =
\begin{pmatrix} \omega_y \\ -\omega_x \\ 0 \end{pmatrix}.
$$
Inserting these into loup blanc's relation
$
(\boldsymbol{\mathsf{A}}-\lambda\boldsymbol{\mathsf{1}})\cdot\dot{\boldsymbol{v}} = \dot\lambda \boldsymbol{v} - \dot{\boldsymbol{\mathsf{A}}}\cdot \boldsymbol{v}
$
we see that each eigenvalue determines the components of $\boldsymbol{\omega}$ perpendicular to its eigenvector and that $\dot\lambda$ drops out of the relation. We find
$$
\dot{\boldsymbol{\mathsf{A}}} =
\begin{pmatrix}
\dot\lambda_1 & \omega_z(\lambda_1-\lambda_2) & \omega_y(\lambda_3-\lambda_1) \\
\omega_z(\lambda_1-\lambda_2) & \dot\lambda_2 & \omega_x(\lambda_2-\lambda_3) \\
\omega_y(\lambda_3-\lambda_1) & \omega_x(\lambda_2-\lambda_3) & \dot\lambda_3 \end{pmatrix}.
$$
Finally, generalizing for a general coordinate frame, we have
$$
\boldsymbol{\omega} =
\frac{\boldsymbol{v}_2^T\cdot\dot{\boldsymbol{\mathsf{A}}}\cdot\boldsymbol{v}_3}{\lambda_2-\lambda_3}\boldsymbol{v}_1 +
\frac{\boldsymbol{v}_3^T\cdot\dot{\boldsymbol{\mathsf{A}}}\cdot\boldsymbol{v}_1}{\lambda_3-\lambda_1}\boldsymbol{v}_2 +
\frac{\boldsymbol{v}_1^T\cdot\dot{\boldsymbol{\mathsf{A}}}\cdot\boldsymbol{v}_2}{\lambda_1-\lambda_2}\boldsymbol{v}_3
.
$$
In particular, as pointed out by loup blanc, the derivatives of the eigenvectors, i.e. $\boldsymbol{\omega}$, are only well-defined if the eigenvalues are distinct. However, unlike what loup blanc has claimed in a comment, the values for $\omega_i$ obtained from different eigenvalues agree (this makes sense, since $\dot{\boldsymbol{\mathsf{A}}}$ contains six independent numbers, the same as the number of unknowns $\dot\lambda_i$ and $\boldsymbol{\omega}$).
Answer: The symmetric 3x3 matrix has 3 orthonormal eigenvectors $\boldsymbol{e}_i$ with associated eigenvalues $\lambda_i$ and can be written
$$
\boldsymbol{\mathsf{A}} = \sum_i \lambda_i \boldsymbol{e}_i \otimes \boldsymbol{e}_i,
$$
where $\otimes$ denotes the outer (tensor) product. The triad of eigenvectors rotates as $\dot{\boldsymbol{e}}_i = \boldsymbol{\omega}\times\boldsymbol{e}_i$. Differentiating the above expression for $\boldsymbol{\mathsf{A}}$ we find therefore
$$
\dot{\boldsymbol{\mathsf{A}}} = \sum_i \dot{\lambda}_i \boldsymbol{e}_i \otimes\boldsymbol{e}_i + \sum_{\mathrm{cyclic}} \boldsymbol{\omega}\cdot\boldsymbol{e}_1(\lambda_2-\lambda_3)(\boldsymbol{e}_2 \otimes\boldsymbol{e}_3 + \boldsymbol{e}_3 \otimes\boldsymbol{e}_2).
$$
Multiplying from left and right by $\boldsymbol{e}_i$ and $\boldsymbol{e}_j$ and exploiting their orthonormality, we find
$$
\dot{\lambda}_i = \boldsymbol{e}_i\cdot\dot{\boldsymbol{\mathsf{A}}}\cdot\boldsymbol{e}_i
\qquad\text{and}\qquad
\boldsymbol{\omega} = \sum_{\mathrm{cyclic}} \frac{\boldsymbol{e}_2\cdot\dot{\boldsymbol{\mathsf{A}}}\cdot\boldsymbol{e}_3}{\lambda_2-\lambda_3}\boldsymbol{e}_1.
$$


ASP.NET MVC authentication and credentials

Question: I'm currently working on a simple application in ASP.NET MVC 5. I'm beginner in this. The assignment is about authentication from providers(Facebook, Google, Microsoft) and displaying user credentials from provider on a web page after logging in. I did authentication successfully, but I can't figure out exactly how to get credentials and display them. Any suggestions?
Answer: though this is not exactly an answer, but the post is likely going to be closed. There are some nice resources in the web from which you can find some ideas, please look into the following ones:
https://www.youtube.com/watch?v=WsRyvWvo4EI&list=PL6n9fhu94yhW7yoUOGNOfHurUE6bpOO2b&index=28
https://www.youtube.com/watch?v=kxLxlukWuVg&list=PL6n9fhu94yhW7yoUOGNOfHurUE6bpOO2b&index=29
Comment: Thank you for your answer! :)
Comment: @igortcfc instead of asking at SO why don't you check the code generated by the MVC project template? It *already* contains what you ask, with comments on how to enable each provider. You don't need a video for this