Python type hinting for function with keras model

Question: If I create function like this:
def mdl(input_shape):

    model = Sequential()
    model.add(Conv2D(depth=64, kernel_size=(3, 3), input_shape=input_shape, activation='relu'))
    model.add(Dense(32), activation='relu')
    model.add(Dropout(0.3))
    model.add(Dense(32), activation='relu')
    model.add(Dropout(0.3))
    model.add(Dense(16), activation='relu')
    model.add(Dropout(0.3))
    model.add(Dense(1))

    return model

and I care a lot about good programming practices, how should I indicate returning type of the function?
Answer: def mdl(input_shape) -> Sequential:

You probably also want to type the input_shape. I am guessing it is a tuple of ints, so:
def mdl(input_shape: Tuple[int, ...]) -> Sequential:

If you are interested in best practice, you may want to use a better, more semantic function name as well, e.g. build_model.
Comment: @Max — you can use `from keras import Sequential` ([docs](https://keras.io/guides/sequential_model/)) and `from typing import Tuple` ([docs](https://docs.python.org/3/library/typing.html)); for Python 3.9+, you can just use the built-in `tuple` type instead of `Tuple`. See also [this answer](https://stackoverflow.com/a/39458225/3618671) for details.
Comment: How can I import those types? If i try to do this my IDE only tells me ""Sequential" is not defined"


Android: Expandable list not expanded on a screen fully

Question:
This is my App screen on the top there is an expandable listview, and underneath there are buttons having images,

now the problem is the expandable listview expands on specific area not expand itself to show all items as displayed in snap,
I need that, when user click on parent item it expands itself with child items on the front of all button so that the buttons are hidden behind the listview, or when user scrolling the buttons the button goes behind the listview...
just like admob ad that is displayed on the front of every thing here is the snaps of that also

i want to show listview like this, as admob banner
here is my xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/container"
android:layout_width="fill_parent"
android:layout_height="match_parent"
tools:context=".MainActivity"
tools:ignore="MergeRootFrame"
android:background="@drawable/background2">

<ScrollView
    android:layout_height="match_parent"
    android:layout_width="fill_parent"
    android:fillViewport="true"
    android:id="@+id/scrollView"
    android:layout_alignParentTop="true"
    android:layout_alignParentLeft="true">

<LinearLayout
    android:layout_height="fill_parent"
    android:layout_width="fill_parent"
    android:orientation="vertical"
    android:focusable="false"
    android:layout_alignParentTop="true"
    android:layout_alignParentLeft="true">

    <ExpandableListView
        android:id="@+id/listView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        >
    </ExpandableListView>

    <Button

        android:layout_width="match_parent"
        android:layout_height="wrap_content"

        android:id="@+id/button31"
        android:layout_marginTop="8dp"
        android:background="@drawable/anaheim"

        android:width="@dimen/abc_search_view_preferred_width"
        android:height="@dimen/abc_action_button_min_width" />

    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/button"
        android:layout_marginTop="8dp"
        android:background="@drawable/boston"
        android:layout_alignParentTop="true"
        android:layout_alignRight="@+id/scrollView"
        android:width="@dimen/abc_search_view_preferred_width"
        android:height="@dimen/abc_action_button_min_width" />

    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/button11"
        android:layout_marginTop="8dp"
        android:layout_alignTop="@+id/button"
        android:layout_alignParentRight="true"
        android:background="@drawable/buffalo"
        android:width="@dimen/abc_search_view_preferred_width"
        android:height="@dimen/abc_action_button_min_width"/>
 </LinearLayout>

</ScrollView>

</RelativeLayout>

Thanks in advance
Comment: do not put scrollable containter(ExpandableListView) into another scrollable containter(ScrollView)
Comment: i put it outside the scroll view also, but then it will show only the listview items not the button,
Comment: put buttons first into relativelayout (at the **bottom** of it) then put expandablelistview **above** them
Comment: kindly please make your answer by editing my xml code, Thanks its more informative for me then
Answer: <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/container"
android:layout_width="fill_parent"
android:layout_height="match_parent"
tools:context=".MainActivity"
tools:ignore="MergeRootFrame"
android:background="@drawable/background2">

<ScrollView
android:layout_height="match_parent"
android:layout_width="fill_parent"
android:fillViewport="true"
android:id="@+id/scrollView"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true">

<LinearLayout
android:layout_height="fill_parent"
android:layout_width="fill_parent"
android:orientation="vertical"
android:focusable="false"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true">

<Button

    android:layout_width="match_parent"
    android:layout_height="wrap_content"

    android:id="@+id/button31"
    android:layout_marginTop="8dp"
    android:background="@drawable/anaheim"

    android:width="@dimen/abc_search_view_preferred_width"
    android:height="@dimen/abc_action_button_min_width" />

<Button
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:id="@+id/button"
    android:layout_marginTop="8dp"
    android:background="@drawable/boston"
    android:layout_alignParentTop="true"
    android:layout_alignRight="@+id/scrollView"
    android:width="@dimen/abc_search_view_preferred_width"
    android:height="@dimen/abc_action_button_min_width" />

<Button
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:id="@+id/button11"
    android:layout_marginTop="8dp"
    android:layout_alignTop="@+id/button"
    android:layout_alignParentRight="true"
    android:background="@drawable/buffalo"
    android:width="@dimen/abc_search_view_preferred_width"
    android:height="@dimen/abc_action_button_min_width"/>
 </LinearLayout>

</ScrollView>
<ExpandableListView
    android:id="@+id/listView"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    >
</ExpandableListView>
</RelativeLayout>

Thanks to @selvin


When did the NFL start using the Wonderlic test and how is it applied to the draft process?

Question: I recently took a Wonderlic Cognitive Ability Test at a job interview. It consisted of logic, mathematics and grammar. The NFL uses this exam as a part of their draft analysis. I can understand why I was asked to complete the assessment for the sales position I applied for. I'm not certain how it applies as a predictor of a football player's success. When did the NFL implement this assessment and how is it used in the analysis of NFL talent?
Answer:
When did the NFL implement this assessment?

During the 1970s when Tom Landry, coach of the Dallas Cowboys, believed it could be used as a predictor of pro success(1).

How is it used in the analysis of NFL talent/applied to the draft process?

This is used in analysis to measure aptitude. Some positions may evaluate its usefulness  (eg, a quarterback's ability to read defenses on the fly) more than others (eg, a cornerback reacting to a ball thrown or a receiver's movement).
However, studies have shown that there is not a strong correlation between a player's Wonderlic score and his NFL performance(2).  In fact, they present a negative correlation for some positions. Thus, it can be surmised that other factors (team quality, player development, character, coaching, etc.) may have more significance on NFL performance than the Wonderlic score.
For quarterbacks:

Donovan
McNabb
scored a 14 on the Wonderlic and had a nine-year run with the Philadelphia Eagles in which he was
selected to the Pro Bowl six times and played in five NFC
Championship games. McNabb had Andy Reid as coach throughout his time in Philadelphia.
Blaine Gabbert scored a 42 on the Wonderlic and is currently 5-22 as a starting quarterback. Gabbert had been coached by three different coaches during his three seasons with the Jacksonville Jaguars.
Comment: The Dallas Cowboys organization really started the concept behind the player combine where you try to find tests that predict performance.
Answer:
The NFL has used Wonderlic since 1968

Thats according to fox. It's used to measure cognitive intelligence, I'm not an expert in NFL but quarterbacks are essentially the same as playmakers in football (soccer), some playmakers have even been described as quarterbacks. One of the most important attributes for a playmaker is the ability to read and analyse situations and make the best decision in a matter of seconds. The wonderlic test is designed to test these types of attributes so for certain positions it does make sense for teams to test these abilities.

Why would it not be "relevant" to explore a million-dollar employee's
  cognitive intelligence?

I don't think it is any definite measure of success though as some players do play purely from instinct, they may not be even able to describe how or why they make the right decision.
I guess for quarterbacks this test makes sense though as there are a lot of plays to understand and memorise.
There has been a 2009 study by Brian D. Lyons, Brian J. Hoffman, and John W. Michel that found that Wonderlic scores failed to positively and significantly predict future NFL performance for any position (wikipedia)

Scoring too high can be as much of a problem as scoring too low.
  Football coaches want to command the locker room. Being smarter than
  the individual players makes that easier. Having a guy in the locker
  room who may be smarter than every member of the coaching staff can be
  viewed as a problem — or at a minimum as a threat to the egos of the
  men who hope to be able when necessary to outsmart the players,
  especially when trying in some way to manipulate them.
Comment: Just to muddy up the results, there's plenty of evidence that the test is not taken too seriously.  A very low score might mean there is concern about ability to take in the playbook.  The team would then have to investigate this on a case by case basis.


Analysing discrete data from a factorial experimental design

Question: The dependent variable in my data can take on the values 0-7 and is, therefore, a discrete variable. I have data from a number of experiments with one, two, and three-way factorial designs.
The previous literature on my topic has just used ANOVA of analyse this type of data. This seems clearly wrong to me and my data rarely meet the assumptions of ANOVA which suggests all the published research on this topic has used the wrong statistical models.
My issue is that I don't know what the best approach to analysing this data is. What is the most appropriate model for analysing discrete data using a factorial design? I'm using R to analyse the data.
Comment: I guess some form of a generalized linear model might be appropriate but I don't know enough about this form of models.
Answer: Given that prior research has analyzed comparable data using ANOVA, I am assuming that the 8-point scale is at least ordinal. That it is discrete is not problematic. Does this scale measure a latent characteristic that is continuous or is it measuring something that only takes on these eight values? Can you assume, even if only roughly, that there are equal intervals between the levels of the scale? What is your sample size and is the sample size balanced across conditions? Answers to all of these questions effects whether an ANOVA approach is "clearly wrong" as you state or a reasonable approach, even if not strictly ideal.
Recall that given the Central Limit Theorem, as sample size increases, the sampling distribution becomes normal even with data from a population that is non-normally distributed. This also extends to discretized data (hence the ability to use a z-test on proportions given a large sample size -- although with modern computers there is little to no need to do so). A consequence of this is that ANOVA (or OLS regression) will often produce results that are in agreement with more complex models with assumptions that more closely match the data, such as an ordered logistic regression model.
Thus, an ANOVA approach is not "clearly wrong" even if it is not precisely correct. I recommend that you compare the results from an ANOVA model to an ordered logistic regression model. For the ordered logistic regression model, take care in how you parameterize your factors and interactions. I recommend effect coding to get a model that more closely aligns with a simple ANOVA model. If the design isn't balanced, you also need to build the model in stages to simulate a Type II sums-of-squares analysis. If the ordered logistic regression model and ANOVA lead to comparable substantive interpretations, go with the latter as it is easier to interpret and easier for most readers to understand.
Comment: Thank you very much for your response. In the context of my experiments, the data can only take on these values. I'm measuring is the number of references to a piece of target information that people make across 7 questions. So, yes, the intervals between each level of the scale are equal. My group sizes do also differ to some extent (in one experiment they vary between 16-25). If the ordered logistic regression model and ANOVA models lead to comparable interpretations do I need to account for the non-normal residuals, heteroscedastic error variance, and unbalanced groups in some way?
Comment: Given that your DV is a count, why not use a Poison model? That said, unless your residuals and other diagnostic suggest a problem, ANOVA should be fine
Comment: Yes, the residuals are non-normal and heteroscedastic. One thing I considered was using a generalized linear model including a term that allows for unequal variances but this doesn't deal with the non-normal residuals. I will look into Poisson models as well.
Comment: In a Poisson distribution, the variance increases as the count increases. Thus, if your heteroscedasticity is increasing variance within increasing count, then the Poisson model may fix this.
Comment: OK, great I will check this out. Thanks for your help.
Comment: Hi again, I tried the Poisson model but it seems as if there is overdispersion and excess zeros in my data so a zero-inflated model is more appropriate. It looks like the results I get are slightly different from the linear model/ANOVA. There doesn't appear to be a lot of guidance for interpreting the output from these models (particularly when there are interaction terms involved) and I fear that I won't be able to do a good job of this. Do you know if there is a legitimate transformation that I could apply to fit the linear model to my data so that the results are  easier to interpret?
Comment: With zero-inflated count data, there is no transformation that will normalize it (with any transformation, the value with the largest frequency will always be at the far left of the distribution). There is good information on the web, such as the https://stats.idre.ucla.edu website, for interpreting such models. With unbalanced data, the interactions are tricky. Run a model with and without them. Base any interpretation of the main effects from the former and interactions from the latter.
Comment: Great thanks for all this information it's been very helpful. I've been reading up on this a little (serious stats by Thom Baguley) has a chapter on modeling discrete outcomes and this says that an assumption of Poisson models is that counts are independent. I don't think this is the case with my data since each person answers all 7 questions and the count is whether or not they refer to a piece of info on that question. Do you have any suggestions in this instance?
Comment: My understanding is that you have one count (from 0 to 7) for each individual and that the individuals are independent. Is that not the case? I think more details on what you actually did are needed.
Comment: Individuals are independent. They answer 7 questions. For each question, they are scored a 1 if they refer to a piece of target info on that question. Then each participant has a total score which tells me on how many questions they referred to the target info.
Comment: You are right that the responses within an individual are not independent but that is not the issue. What matters is that each count is independent, which it is.


What's about $-\int_0^1\frac{\log(1+x^{10})\log x}{x}dx$?

Question: Playing with Wolfram Alpha and inspired in [1] (I refers it if someone know how relates my problem with some of problems involving the Apéry constant in this reference, but the relation doesn't seem explicit), defining
$$I_n:=-\int_0^1\frac{\log(1+x^{2n})\log x}{x}dx$$
for integers $n\geq 1$, I can calculate, as I am saying with Wolfram Alpha (but I don't know how get the indefinite integrals) $I_1$, $I_2$, $I_3$ and $I_4$. And as a conjecture $$I_8=\frac{6\zeta(3)}{8\cdot 16^2}.$$
Motivation. I would like to do a comparison with the sequence  $I_1$, $I_2$, $I_3$, $I_4$ and $I_8$.

Question. If do you know that this problem was solved in the literature please add a comment: can you evaluate in a closed-form $I_5$? Many thanks.

References:
[1] Walther  Janous , Around's Apéry's constant, J. Ineq. Pure and Appl. Math. 7(1) Art. 35 (2006).
Comment: For instance, if you type *Walther  Janous , Around's Apéry's constant* in Google you find the paper from the European Mathematical Information Service.
Answer: By Taylor series expansion ,
For $0<x<1$ and $n\geq 1$,
$\displaystyle -\ln(1+x^{2n})=\sum_{k=1}^{+\infty} \dfrac{(-1)^kx^{2kn}}{k}$
For $k \geq 0$,
$\displaystyle \int_0^1 x^k\ln x dx=-\dfrac{1}{(k+1)^2}$
(integration by parts)
Therefore,
$\begin{align}
I_n&=\int_0^1 \left(\sum_{k=1}^{+\infty} \dfrac{(-1)^kx^{2kn-1}\ln x}{k}\right) dx\\
&=\sum_{k=1}^{+\infty} \left(\int_0^1 \dfrac{(-1)^kx^{2kn-1}\ln x}{k} dx\right)\\
&=-\sum_{k=1}^{+\infty} \dfrac{(-1)^k}{k(2kn)^2}\\
&=-\dfrac{1}{4n^2}\sum_{k=1}^{+\infty} \dfrac{(-1)^k}{k^3}\\
&=-\dfrac{1}{4n^2}\left(\sum_{k=1}^{+\infty} \dfrac{1}{(2k)^3}-\sum_{k=0}^{+\infty}\dfrac{1}{(2k+1)^3}\right)\\
&=-\dfrac{1}{4n^2}\left(\dfrac{1}{8}\zeta(3)-\left(\zeta(3)-\dfrac{1}{8}\zeta(3)\right)\right)\tag{1}\\
&=-\dfrac{1}{4n^2}\times -\dfrac{3}{4}\zeta(3)\\
&=\boxed{\dfrac{3\zeta(3)}{16n^2}}
\end{align}$
For (1) observe that,
$\begin{align}\sum_{k=0}^{+\infty}\dfrac{1}{(2k+1)^3}&=\sum_{k=1}^{+\infty}\dfrac{1}{k^3}-\sum_{k=1}^{+\infty}\dfrac{1}{(2k)^3}\\
&=\zeta(3)-\dfrac{1}{8}\zeta(3)
\end{align}$
Comment: Many thanks to you and @PaulEnta you are generous and nice. It can encourage to me and young students to read and study your answers.
Comment: In my genuine calculations I tried your approach but I had a mistake a  step.
Answer: Integration by part leads to$$ I_n=-I_n+2n\int_0^1\frac{x^{2n-1}\log^2 x}{1+x^{2n}}\,dx$$
Then $$ I_n=n\int_0^1\frac{x^{2n-1}\log^2 x}{1+x^{2n}}\,dx$$
and Maple integrates:$$I_n=\frac{3\zeta(3)}{16n^2}$$
Comment: Many thanks for your attention, now I am going to do the calculation to see it. I was breaking my head and spirit in my attempt to get the closed-form. Thanks!
Answer: $\newcommand{\bbx}[1]{\,\bbox[8px,border:1px groove navy]{\displaystyle{#1}}\,}
 \newcommand{\braces}[1]{\left\lbrace\,{#1}\,\right\rbrace}
 \newcommand{\bracks}[1]{\left\lbrack\,{#1}\,\right\rbrack}
 \newcommand{\dd}{\mathrm{d}}
 \newcommand{\ds}[1]{\displaystyle{#1}}
 \newcommand{\expo}[1]{\,\mathrm{e}^{#1}\,}
 \newcommand{\ic}{\mathrm{i}}
 \newcommand{\mc}[1]{\mathcal{#1}}
 \newcommand{\mrm}[1]{\mathrm{#1}}
 \newcommand{\pars}[1]{\left(\,{#1}\,\right)}
 \newcommand{\partiald}[3][]{\frac{\partial^{#1} #2}{\partial #3^{#1}}}
 \newcommand{\root}[2][]{\,\sqrt[#1]{\,{#2}\,}\,}
 \newcommand{\totald}[3][]{\frac{\mathrm{d}^{#1} #2}{\mathrm{d} #3^{#1}}}
 \newcommand{\verts}[1]{\left\vert\,{#1}\,\right\vert}$
\begin{align}
&-\int_{0}^{1}{\ln\pars{1 + x^{2n}}\ln\pars{x} \over x}\,\dd x \,\,\,\,\stackrel{x^{2n}\ \mapsto\ x}{=}\,\,
-\,{1 \over 4n^{2}}\int_{0}^{1}{\ln\pars{1 + x}\ln\pars{x} \over x}\,\dd x
\\[5mm]= &\
-\,{1 \over 4n^{2}}\int_{0}^{-1}{\ln\pars{1 - x}\ln\pars{-x} \over x}\,\dd x =
{1 \over 4n^{2}}\int_{0}^{-1}\mrm{Li}_{2}'\pars{x}\ln\pars{-x}\,\dd x =
-\,{1 \over 4n^{2}}\int_{0}^{-1}{\mrm{Li}_{2}\pars{x} \over x}\,\dd x
\\[5mm] = &\
-\,{1 \over 4n^{2}}\int_{0}^{-1}\mrm{Li}_{3}'\pars{x}\,\dd x =
-\,{1 \over 4n^{2}}\,\mrm{Li}_{3}\pars{-1} =
-\,{1 \over 4n^{2}}\sum_{k = 1}^{\infty}{\pars{-1}^{k} \over k^{3}}
\\[5mm] = &\
-\,{1 \over 4n^{2}}\pars{\sum_{k = 1\ \mrm{even}}^{\infty}{1 \over k^{3}} -
\sum_{k = 1\ \mrm{odd}}^{\infty}{1 \over k^{3}}} =
-\,{1 \over 4n^{2}}\pars{2\sum_{k = 1}^{\infty}{1 \over \pars{2k}^{3}} -
\sum_{n = 1}^{\infty}{1 \over n^{3}}} =
\bbx{\ds{{3 \over 16n^{2}}\,\zeta\pars{3}}}
\end{align}
Comment: I've understand all your steps, the change of variables to get $-\int_0^{-1}\frac{\log(1+u)\frac{1}{2n}\log u}{u^{1/(2n)}}\frac{1}{2n}\frac{u^{1/(2n)}}{u}du$, after other change of variables and you are introducing the derivative of the dilogarihtm, after the integration by parts with $\operatorname{Li}_2'(x)\log(-1)|_0^{-1}=0$ and after the direct integration of $\operatorname{Li}_3'(x)$ and final statement. It was very nice, Many thanks.
Comment: @user243301 Yes. You're right. Thanks.


Annotating an existing ggplot2

Question: I ran into problems with annotating to an existing ggplot2 using the
plotname + annotate()

syntax
I was trying to annotate to an existing ggplot using a loop which aims to add text and arrows to a plot. While troubleshooting I discovered that the problem was far more basic than the loop (which is fine) or the basic annotation which also works well. I discovered that trying to annotate to the plot after creating it was generally not working. For example
temp_plot <- ggplot(df, aes(x = var1, y = var2)) +
    geom_point() +
    ggtitle("Title")

is working fine, but
temp_plot <- ggplot(df, aes(x = var1, y = var2)) +
    geom_point()
temp_plot + ggtitle("Title")

is not. The basic plot is drawn. But the title is not added....
Comment: Are you actually running the final line? If you are simply sourcing the entire script, this won't print the plot automatically. Wrap it in `print`. You should also make sure you are saving the modified plot, i.e., the final line should be: `temp_plot <- temp_plot + ggtitle("Title")`.
Comment: Thanks for your quick response. I've been wrapping it in plot to view it. And see it fine... but without the annotation. It makes sense to save the modified plot. So thanks. I'm doing that now. But get an error: Error in `ggplot_add()`:
! Can't add `plot(temp_plot)` to a  object.
Comment: What are you passing as argument to `plot()` or `print()`?  (Use of `print()` is nowadays preferred).  `print( temp_plot + ggtitle("Title") )`
I cannot reproduce the problem. Have you loaded a package that redefines `plot()` or `+`?
Comment: I wasn't aware that print() is now preferred - I continue to learn! I've only really been using R for about 6 weeks, though several hours each day, as I analyse findings from a recently completed research project. Re-saving the plot combined with using print() does seem to have solved the problem. I still do not fully understand the cause as the packages I'm using for this sub-project (psych, dplyr, ggplot2 and moments) are widely used and will not be re-difining plot() or + . The plots are based on prcomp() from the stats package. Thanks for your helpful response.
Answer: Thanks to the help [re-saving the plot and using print(), not plot()] , I was able to create a function for creating several similar PCA plots with varying variables and numbers of variables (see below). Some of the code is idiosyncratic to this particular series of similar plots and I'm sure my code can be improved - but it works for my current needs! A list created with pcomp(), a string of text for the plot title, and a list of variable names are passed to the function:
PCA_plot <- function(temp_pca,title_text,temp_variable_names) {

  # Principal Component Analysis Individual Scores and loadings for plots
  temp_pca_scores <- as.data.frame(temp_pca[["x"]])
  temp_pca_loadings <- as.data.frame(temp_pca[["rotation"]])

  # Proportion of variance for Principle Components 1 and 2
  pov1 <- summary(temp_pca)[[6]][[2]]
  pov1 <- sprintf("%1.1f%%", 100*pov1)
  pov2 <- summary(temp_pca)[[6]][[5]]
  pov2 <- sprintf("%1.1f%%", 100*pov2)

  # Axes labels
  PC1_lab <- paste0("Principle Component 1 (", pov1," of variance)")
  PC2_lab <- paste0("Principle Component 2 (", pov2," of variance)")

  # Note
  str_note <- "NOTE: For clarity,\nthe loadings are plotted\nat five times the scale\nof the individual points"

  temp_plot <- ggplot(temp_pca_scores, aes(x = PC1, y = PC2)) +
    geom_point()

  temp_plot <-  temp_plot +  ggtitle(title_text) +
    xlab(PC1_lab) +
    ylab(PC2_lab)  +
    ylim(-5,5) +
    xlim(-5,5) +
    geom_point(position= "jitter", size= 1.2) +
    annotate("text",x=-4,y=4,label= str_note, size= 3) +
    theme_light()

var_number <- length(temp_pca[["sdev"]])

for(i in 1:var_number) {

  if(i==1){
    keys <- paste0("1. ",temp_variable_names[1])
    }
  else {
    key <- paste0("\n",i,". ",temp_variable_names[i])
    keys <- paste0(keys,key)
    }

  temp_plot <- temp_plot +
    annotate(geom = "segment", x = 0, xend = temp_pca_loadings[i,1]*5, y = 0, yend = temp_pca_loadings[i,2]*5,
             arrow=arrow(length = unit(0.2,"cm"),end = "last", type = "closed")) +
    annotate(geom= "text", x=sum((temp_pca_loadings[i,1]*5),-0.2), y=sum(temp_pca_loadings[i,2]*5,0.1), label=i)
}

temp_plot <- temp_plot +
  annotate(geom= "text", x=0.8, y=-3.7, label=keys, size=3, hjust=0)

  return(temp_plot)

}

Annotating an existing ggplot2


Can I use Kamailio Sip Server to handle 500 calling?

Question: I need a Sip server to build a VIOP server to establish voice call between 500 Android an desktop sip clients.
Can Kamailio handle this or I need an Asterisk server too?
Comment: http://www.kamailio.org/w/features/
Comment: Thanks, I searched a lot but I'm not sure if it's possible. Do you familiar with kamailio?
Answer: Kamailio is only an SIP proxy (call negotiation), you still need a RTP server in order to handle the audio of the calls like Asterisk or FreeSwitch


I try to save in cookie for a period of 1 hour but I get invalid date

Question: I have a token and I want to save it in cookie for only 1 hour.
Here is my code :
        time= 3600 * 1000;
    let expires = new Date();
    expires.setDate(expires + time);
    console.log(expires);
    document.cookie =`${name}=${value};expires=${expires.toUTCString()};path=/`;

When I run it in chrome I see the following:
Invalid Date

For more info I use the following for implementing my function:
How to set a cookie to expire in 1 hour in Javascript?
Can anyone shed light on this? what am I doing wrong?
Comment: You didn't get the time on the `expires` before adding the hour to the time. Then you need to reset the time for `expires`...you skipped a few steps
Comment: @scrappedcola thanks let me give it a try and I will let you know about the result
Answer: This is happening because of the expires+time part. You can't add a date to a number like that.
You could try something like
let expires=new Date(new Date().valueOf()+time);


$Si(x)\leq Si(\pi)$ for every $x>0$

Question: I need to show that $Si(x)\leq Si(\pi)$ for every $x>0$ where $Si(x)=\int_{0}^{x} \frac {\sin (t)}{t} dt$. I see it graphically but i can't prove it.
Thank you!
Comment: Your function is positive over $(0,\pi)$..
Comment: The fundamental theorem of calculus might help you out some.
Answer: As $Si'(x) = \frac{\sin x}{x}$, each local maximum occurs for some values of $x$ for which $\sin x = 0$, i.e., $x = k\pi$ for positive integers $k$, as $x > 0$. When $k$ is odd we have local maxima and when $k$ is even we have local minima. So if we can show that $$Si((2j+1)\pi) \leq Si(\pi) \ \ \ \text{ for all non-negative integers } j$$
we're done. It's probably worth drawing a diagram at this stage to see what we're doing. The proof that follows now is just formalizing a fairly intuitive idea: the area below the $x$-axis over an interval $[(2j+1)\pi, (2j+2)\pi]$ is always of greater magnitude that the area above the axis in the next interval $[(2j+2)\pi, (2j+3)\pi]$.
Let's use induction. The result is trivially true for $j = 0$. For arbitrary non-negative $j$,
$$Si((2j+3)\pi) = \int_0^{(2j+1)\pi} \frac{\sin x}{x} dx + \int_{(2j+1)\pi}^{(2j+3)\pi} \frac{\sin x}{x} dx = Si((2j+1)\pi) + \int_{(2j+1)\pi}^{(2j+3)\pi} \frac{\sin x}{x} dx $$
Now this last integral is negative as
$$\int_{(2j+1)\pi}^{(2j+3)\pi} \frac{\sin x}{x} dx = \int_{(2j+1)\pi}^{(2j+2)\pi} \frac{\sin x}{x} dx +\int_{(2j+2)\pi}^{(2j+3)\pi} \frac{\sin x}{x} dx$$ $$ =  \int_{(2j+1)\pi}^{(2j+2)\pi} \frac{\sin x}{x} dx +\int_{(2j+1)\pi}^{(2j+2)\pi} \frac{\sin (x+\pi)}{(x+\pi)} dx$$
$$ =  \int_{(2j+1)\pi}^{(2j+2)\pi} \frac{\sin x}{x} dx \ - \int_{(2j+1)\pi}^{(2j+2)\pi} \frac{\sin (x)}{(x+\pi)} dx$$
$$ <  \int_{(2j+1)\pi}^{(2j+2)\pi} \frac{\sin x}{x+\pi} dx \ - \int_{(2j+1)\pi}^{(2j+2)\pi} \frac{\sin (x)}{x+\pi} dx \ \ - (*)$$
as for $ x \in [(2j+1)\pi, (2j+2)\pi]$, $\sin x$ is negative and hence $\frac{\sin x}{x} < \frac{\sin x}{x+\pi}$. Finally, the expression (*) is zero.
Hence $Si((2j+3)\pi) < Si((2j+1)\pi)$ for arbitrary $j \geq 0$ and therefore $Si((2j+1)\pi) \leq Si(\pi)$ for all $j \geq 0$.

$Si(x)\leq Si(\pi)$ for every $x>0$


DNS A records Disappearing

Question: So, the situation is as follows. Our production servers are the most important servers being affected but this is happening randomly. I can not build a pattern for servers that are being affected to ones that arent. It seems to be completely random.
We do reboots once a month on our servers. Every time we reboot, random servers will lose their STATIC a record in DNS. It will propagate almost instantly too. We will then have to either manually enter another A record in DNS or do a ipconfig /registerdns and wait 15 minutes or so.
All of our servers are on a VLAN with no DHCP, and they have statically assigned everything. The option on the NIC to enabled registering of the address in DNS is enabled.
We have scavenging, but its every 7 days (of anything older than 7 days) and the cycle was started on a Monday, and we restart on Thursday. What do you think I should do?
Comment: bump. do i need to provide more info?
Answer: Did you disable the "DHCP Client" service on these servers?
The DHCP client service is the service that registers the computer in DNS.
Here is the description of the service:
Registers and updates IP addresses and DNS records for this computer. If this service is stopped, this computer will not receive dynamic IP addresses and DNS updates. If this service is disabled, any services that explicitly depend on it will fail to start.
Comment: Will that make it so it doesn't try to renew its DNS record? Isnt that bad? Ill try it and let you know though
Comment: I just realized you werent telling me to try disabling it, but simply asking if it was already. it was enabled on the servers with and without issues. I just checked a few
Comment: That DHCP client service should be set to 'automatic' if you want machines to update and register their records. If you disable it then the machine won't be able to update or register in DNS automatically. I would not recommend disabling it.
Comment: They are set to auto

DNS A records Disappearing


I2C interface on Tiva

Question: On a Tiva (Texas Instruments Cortex M4F ARM) TM4C129XNCZAD I have a problem with I2C interface. I have enabled both a master on I2C module 4 thru port K and a slave on I2C module 6 thru port B. I have interconnected both I2C modules. Using Texas Instruments driver library I tried to send 1 byte using I2C_MASTER_CMD_SINGLE_SEND command. I spend a lot of time to make it working, but SCK line keeps Low logical level. I followed exactly TivaWare™ Peripheral Driver Library USER'S GUIDE, but the communication doesn't work. Has anybody some experience with it?
There is my code:
#include <stdint.h>
#include <stdbool.h>
#include "inc/hw_i2c.h"
#include "inc/hw_memmap.h"
#include "inc/hw_types.h"
#include "driverlib/gpio.h"
#include "driverlib/i2c.h"
#include "driverlib/pin_map.h"
#include "driverlib/sysctl.h"
#include "inc/tm4c129xnczad.h"

#define SLAVE_ADDRESS 0x3C

void  delay  (void)
{
    volatile uint32_t ui32Loop;
    for(ui32Loop = 0; ui32Loop < 200000; ui32Loop++);
}

volatile  uint32_t  result;

int  main  (void)
{
    SysCtlClockSet(SYSCTL_SYSDIV_1 | SYSCTL_USE_OSC | SYSCTL_OSC_MAIN | SYSCTL_XTAL_16MHZ);
    //
    // Enable the GPIO port that is used for the on-board LED.
    //
    SYSCTL_RCGCGPIO_R = SYSCTL_RCGCGPIO_R3 | SYSCTL_RCGCGPIO_R9 | SYSCTL_RCGCGPIO_R1;
    //
    // Do a dummy read to insert a few cycles after enabling the peripheral.
    //
    result = SYSCTL_RCGCGPIO_R;
    //
    // Enable the GPIO pin for the LED (PD3).  Set the direction as output, and
    // enable the GPIO pin for digital function.
    //
    GPIO_PORTD_AHB_DIR_R = 0x8;
    GPIO_PORTD_AHB_DEN_R = 0x8;
    GPIO_PORTK_DEN_R = 0xC0;        // Enable Port K for I2C module 4

    GPIO_PORTB_AHB_DEN_R = 0xC0;    // Enable Port B for I2C module 6

    SYSCTL_RCGCI2C_R = (1 << 4) | (1 << 6);  // Mode Clock Gating Control for I2C modules 4 and 6
    GPIO_PORTK_AFSEL_R = 0xC0;      // Alternate Function Select PK6, PK7
    GPIO_PORTB_AHB_AFSEL_R = 0xC0;  // Alternate Function Select PB6, PB7
    GPIOPinConfigure(GPIO_PK6_I2C4SCL);
    GPIOPinConfigure(GPIO_PK7_I2C4SDA);
    GPIOPinConfigure(GPIO_PB6_I2C6SCL);
    GPIOPinConfigure(GPIO_PB7_I2C6SDA);

    GPIOPinTypeI2C(GPIO_PORTK_BASE, 7);       // Configurtes SDA
    GPIOPinTypeI2CSCL(GPIO_PORTK_BASE, 6);    // Configurtes SCL
    GPIOPinTypeI2C(GPIO_PORTB_BASE, 7);       // Configurtes SDA
    GPIOPinTypeI2CSCL(GPIO_PORTB_BASE, 6);    // Configurtes SCL

    I2CMasterInitExpClk(I2C4_BASE, SysCtlClockGet(), false);

    I2CSlaveEnable(I2C6_BASE);
    I2CSlaveInit(I2C6_BASE, SLAVE_ADDRESS);
    I2CMasterSlaveAddrSet(I2C4_BASE, SLAVE_ADDRESS, false);
    //
    // Loop forever.
    //
    while(1)
    {
        //
        // Turn on the LED.
        //
        GPIO_PORTD_AHB_DATA_R |= 0x8;

        I2CMasterDataPut(I2C4_BASE, 0x33);
        I2CMasterControl(I2C4_BASE, I2C_MASTER_CMD_SINGLE_SEND);
        //
        // Wait until the slave has received and acknowledged the data.
        //
        while(!(I2CSlaveStatus(I2C6_BASE) & I2C_SLAVE_ACT_RREQ));
        //
        // Read the data from the slave.
        //
        result = I2CSlaveDataGet(I2C6_BASE);
        //
        // Wait until master module is done transferring.
        //
        while(I2CMasterBusy(I2C4_BASE));
        //
        // Delay for a bit.
        //
        delay ();
        //
        // Turn off the LED.
        //
        GPIO_PORTD_AHB_DATA_R &= ~(0x8);
        //
        // Delay for a bit.
        //
        delay ();
    }
}

Comment: Did you put pull-up resistors on the I2C lines? I2C is an open-collector signalling system, so the bus needs pull-up resistors to function. For your test, you can probably enable the GPIO's internal pull-ups if available.
Comment: Also take into account that software accuracy for I2C operating is important very much. I2C is a capricious bus and the devices are too. If you say push wrong address to the BUS and no slave answers then at you master side it is some of error state and it is immediately stuck in somewhere until the status/errors are processed properly. Just be aware of things like that.
Comment: A procedure GPIOPinTypeI2C() switches internal pull up resistor on, but a SDA line is waiting in High level. The problem is according to me on SCL side.
Comment: What about function `GPIOPinTypeI2CSCL`? It is called for the two SCL pins (master/slave). That may explain why SDA is okay, but SCL is not.
Comment: If these functions are polled, then you may not be able to do this the way you would like. The I2C slave may be clock stretching until you call the `I2CSlaveDataGet` function, but your code may be blocked on one of the earlier I2C master calls which are waiting to be able to send. I am not familiar enough with this part's I2C driver to be able to diagnose if that's the issue.
Comment: According to Peripheral Driver Library USER'S GUIDE
GPIOPinTypeI2C
Description:
The I2C pins must be properly configured for the I2C peripheral to function correctly. This function provides the proper configuration for the SDA pin.

GPIOPinTypeI2CSCL
Description:
The I2C pins must be properly configured for the I2C peripheral to function correctly. This
function provides the proper configuration for the SCL pin.
Comment: The procedure get stuck at while(!(I2CSlaveStatus(I2C6_BASE) & I2C_SLAVE_ACT_RREQ)); But you are right with the clock stretching but it is at Low level.
Answer: The problem has been resolved. There were issues:

It is essential to populate external pull ups.
Use GPIOPinTypeI2C() 2nd parameter as a bit field instead of a bit number.
The procedure SysCtlClockSet() is dedicated specially to TM4C123 devices. Instead use g_ui32SysClock = SysCtlClockFreqSet((SYSCTL_OSC_MAIN | SYSCTL_XTAL_25MHZ | SYSCTL_USE_PLL | SYSCTL_CFG_VCO_320), 40000000);
For a Master clock setting do not use SysCtlClockGet() procedure. This is also dedicated to TM4C123 devices. Instead use I2CMasterInitExpClk(I2C4_BASE, g_ui32SysClock, false);

Here is the updated code,
#include <stdint.h>
#include <stdbool.h>
#include "inc/hw_i2c.h"
#include "inc/hw_memmap.h"
#include "inc/hw_types.h"
#include "driverlib/gpio.h"
#include "driverlib/i2c.h"
#include "driverlib/pin_map.h"
#include "driverlib/sysctl.h"
#include "inc/tm4c129xnczad.h"

#define SLAVE_ADDRESS 0x3C

void    delay   (void)
{
  volatile uint32_t ui32Loop;
    for(ui32Loop = 0; ui32Loop < 200; ui32Loop++);
}

volatile uint32_t  result;
    uint32_t    g_ui32SysClock;

int main(void)
{
    g_ui32SysClock = SysCtlClockFreqSet((SYSCTL_OSC_MAIN | SYSCTL_XTAL_25MHZ | SYSCTL_USE_PLL | SYSCTL_CFG_VCO_320), 40000000);
    //
    // Enable the GPIO port that is used for the on-board LED.
    //
    SYSCTL_RCGCGPIO_R = SYSCTL_RCGCGPIO_R3 | SYSCTL_RCGCGPIO_R9 | SYSCTL_RCGCGPIO_R1;
    //
    // Do a dummy read to insert a few cycles after enabling the peripheral.
    //
    result = SYSCTL_RCGCGPIO_R;
    //
    // Enable the GPIO pin for the LED (PD3).  Set the direction as output, and
    // enable the GPIO pin for digital function.
    //
    GPIO_PORTD_AHB_DIR_R = 0x8;
    GPIO_PORTD_AHB_DEN_R = 0x8;

    SYSCTL_RCGCI2C_R = (1 << 4) | (1 << 6); // Mode Clock Gating Control for I2C modules 4 and 6

    GPIOPinConfigure(GPIO_PK6_I2C4SCL);
    GPIOPinConfigure(GPIO_PK7_I2C4SDA);
    GPIOPinConfigure(GPIO_PB6_I2C6SCL);
    GPIOPinConfigure(GPIO_PB7_I2C6SDA);

    GPIOPinTypeI2C(GPIO_PORTK_BASE, (1 << 7));       // Configures SDA
    GPIOPinTypeI2CSCL(GPIO_PORTK_BASE, (1 << 6));    // Configures SCL
    GPIOPinTypeI2C(GPIO_PORTB_BASE, (1 << 7));       // Configures SDA
    GPIOPinTypeI2CSCL(GPIO_PORTB_BASE, (1 << 6));    // Configures SCL

    I2CMasterInitExpClk(I2C4_BASE, g_ui32SysClock, false);

    I2CSlaveEnable(I2C6_BASE);
    I2CSlaveInit(I2C6_BASE, SLAVE_ADDRESS);
    I2CMasterSlaveAddrSet(I2C4_BASE, SLAVE_ADDRESS, false);
    //
    // Loop forever.
    //
    while(1)
    {
        //
        // Turn on the LED.
        //
        GPIO_PORTD_AHB_DATA_R |= 0x8;

        I2CMasterDataPut(I2C4_BASE, 0x33);
        I2CMasterControl(I2C4_BASE, I2C_MASTER_CMD_SINGLE_SEND);
        //
        // Wait until the slave has received and acknowledged the data.
        //
        while(!(I2CSlaveStatus(I2C6_BASE) & I2C_SLAVE_ACT_RREQ));
        //
        // Read the data from the slave.
        //
        result = I2CSlaveDataGet(I2C6_BASE);
        //
        // Wait until master module is done transferring.
        //
        while(I2CMasterBusy(I2C4_BASE));
        //
        // Delay for a bit.
        //
        delay   ();
        //
        // Turn off the LED.
        //
        GPIO_PORTD_AHB_DATA_R &= ~(0x8);
        //
        // Delay for a bit.
        //
        delay   ();
    }
}

Answer: I was able to get I2C working on TIVA Launchpad TM4C123GH6PM. I used the the Tivaware library. I created 3 functions, init and write. Here are the functions.
Initialization
void initI2C0(void)
{
   SysCtlPeripheralEnable(SYSCTL_PERIPH_I2C0);

   //reset I2C module
   SysCtlPeripheralReset(SYSCTL_PERIPH_I2C0);

   //enable GPIO peripheral that contains I2C
   SysCtlPeripheralEnable(SYSCTL_PERIPH_GPIOB);

   // Configure the pin muxing for I2C0 functions on port B2 and B3.
   GPIOPinConfigure(GPIO_PB2_I2C0SCL);
   GPIOPinConfigure(GPIO_PB3_I2C0SDA);

   // Select the I2C function for these pins.
   GPIOPinTypeI2CSCL(GPIO_PORTB_BASE, GPIO_PIN_2);
   GPIOPinTypeI2C(GPIO_PORTB_BASE, GPIO_PIN_3);

   // Enable and initialize the I2C0 master module.  Use the system clock for
   // the I2C0 module.  The last parameter sets the I2C data transfer rate.
   // If false the data rate is set to 100kbps and if true the data rate will
   // be set to 400kbps.
   I2CMasterInitExpClk(I2C0_BASE, SysCtlClockGet(), false);

   //clear I2C FIFOs
   HWREG(I2C0_BASE + I2C_O_FIFOCTL) = 80008000;
}

I2C Write Function
void writeI2C0(uint16_t device_address, uint16_t device_register, uint8_t device_data)
{
   //specify that we want to communicate to device address with an intended write to bus
   I2CMasterSlaveAddrSet(I2C0_BASE, device_address, false);

   //register to be read
   I2CMasterDataPut(I2C0_BASE, device_register);

   //send control byte and register address byte to slave device
   I2CMasterControl(I2C0_BASE, I2C_MASTER_CMD_BURST_SEND_START);

   //wait for MCU to finish transaction
   while(I2CMasterBusy(I2C0_BASE));

   I2CMasterSlaveAddrSet(I2C0_BASE, device_address, true);

   //specify data to be written to the above mentioned device_register
   I2CMasterDataPut(I2C0_BASE, device_data);

   //wait while checking for MCU to complete the transaction
   I2CMasterControl(I2C0_BASE, I2C_MASTER_CMD_BURST_RECEIVE_FINISH);

   //wait for MCU & device to complete transaction
   while(I2CMasterBusy(I2C0_BASE));
}

Complete code for TIVA + I2C can be found here.
Reference

I2C Communication with the TI Tiva TM4C123GXL
Comment: @Parag The code word as it is, why do you want to change the code. The complete code is on github

I2C interface on Tiva


Adding AJAX to will_paginate content showing up on link page that's not supposed to be there

Question: I added ajax_pagination using this wiki https://github.com/ronalchn/ajax_pagination/wiki/Installing
it works but when i click on a link in the news section the slider on top shows up on the show page when its not suppose to be there but when you refresh the page it goes away and is back to normal
does anyone know how to fix this?
heres my view
batnews.html.erb

    Featured Articles

  <% @articles.each do |article| %>

<%= link_to(article.title, article, style: 'color: #4C4C4C;') %>

      <%= link_to image_tag(article.photo, style: 'width: 400px; float: left; margin-right: 20px; margin-top: -10px; height: 260px;'), article %>

            <%= article.date %>

             <%= article.author %>

             <%= link_to article.comments.count, article %> <%= link_to 'comments', article %>

<%= truncate article.content, length: 400 %>

        <%= link_to('Read More', article, style: 'font-size: 12px;') %>

      <% end %>

   <%= ajax_section :id => "recent_news", :render => "recent_news" %>

heres my paritial that im rendering _recent_news.html.erb

      Recent News

     <%= ajax_links :section_id => "recent_news" do %>
   <%= will_paginate @news_all %>

    <% @news_all.each do |news| %>

    <%= link_to image_tag(news.photo.url), news, class: 'pull-left', style: 'margin-right:40px; margin-top: 2px; width: 300px;' %>

    <%= link_to news.title, news %>

   <%= link_to news.date, news, style: 'font-size: 10px; color: black; position: relative; top: 15px;' %>

    <%= link_to   (news.comments.count), news, :style => 'font-size: 8px; color: white; font-weight: bold;    position: absolute; top: 0px; right: 5px;' %>

    <%= truncate news.content, length: 500 %>

    <%= link_to 'Read More...', news, style: 'font-size: 12px !important;' %>

  <% end %>
  <%= will_paginate @news_all %>
  <% end %>

heres my controller
static_pages_controller.rb
def batnews
  @articles = Article.all
  @news_all = News.all
  @news_all = News.paginate(page: params[:page], per_page: 4, :order => 'created_at DESC')
  @comment_count = Comment.count(:id)
  respond_to do |format|
  format.html # index.html.erb
  ajax_respond format, :section_id => "recent_news"
  end
end

here my gems
gem 'rails', '3.2.8'
gem 'bootstrap-sass', '2.0.4'
gem 'bcrypt-ruby', '3.0.1'
gem 'faker', '1.0.1'
gem 'will_paginate', '3.0.3'
gem 'bootstrap-will_paginate', '0.0.6'
gem 'jquery-rails', '2.0.2'
gem 'jquery-ui-rails'
gem "haml", "~> 3.1.7"
gem 'twitter-bootstrap-rails', :git => 'git://github.com/seyhunak/twitter-bootstrap-rails.git'
gem 'activerecord-reputation-system', require: 'reputation_system'
gem "paperclip", :git => "git://github.com/thoughtbot/paperclip.git"
gem 'aws-sdk'
gem 'friendly_id'
gem 'ajax_pagination'
gem "jquery-historyjs"

heres the link to the site where you can see the behavior im talking about http://www.batman-fansite.com/batnews
so if you click on the one of the news in recent_news you will be taken to the show page scroll up and you will notice the slider still being there....hit refresh and the slider will be gone...
How can i fix this problem?
Answer: There's actually a simple explanation for this, your ajax is only replacing the HTML within your
 tag. Since your carousel is not a child of recent_news it's content doesn't get replaced with the newly requested HTML. A simple solution would be to wrap your ajax selection around whatever content that you want to be replaced.
Comment: im sorry your explanation makes sense but how would i implement that?
Comment: i dont want the slider to appear on the next page i only want the content of the article
Comment: Move your featured articles container into ``
Comment: so it should be <%= ajax_links :section_id => "recent_news" do %>  <% my partial for news %> <% end %>
Comment: I'm not sure, you'll have to try it. If that doesn't work then I think you might have to write your own Javascript to make this happen if the ajax_paginiation solution your working doesn't work for your application design.
Comment: tried to move the ajax links around but getting the same results...sigh this is frustrating
Answer: This doesn't directly answer your question, but it could solve your problem:  I tried a lot of different ajax will_paginate solutions and none did what I wanted.  I then went on to use the normal will_paginate gem and wrote a custom link renderer that creates them as ajax based.  The full solution is posted here.
Comment: Thanks for the suggestion but It took me so long to get this thing to work and i almost got it just for this weird bug.....so i want to try to find a solution for this...i might have to go with your own solution and start from scratch


Update slider from PyQt when zooming in/out on a PyQtGraph

Question: I would like to connect the PyQtGraph mouse wheel zoom function to a QSlider widget. So when i zoom in/out on the graph, I would get the range of the viewbox and the slider window should follow in sliding range. The closest example of how I would like it to be can be found in this PyQtGraph example: http://www.pyqtgraph.org/downloads/0.10.0/pyqtgraph-0.10.0-deb/pyqtgraph-0.10.0/examples/crosshair.py
So I would like to connect the following definitions in some way.
def update_plot(self):
    self.axX = self.p6.getAxis('bottom')
    self.xmin = self.axX.range[0]
    self.xmax = self.axX.range[0]
    print(self.axX.range)
    return xmin, xmax

def update_slider(self, xmin, xmax):
    self.size = self.w1.slider.value()
    self.p6.setXRange(self.xmin+self.size,self.xmax+self.size)
    print(self.size)

However, I can't seem to get it to work. I have attached the full code of my example below. Can you help me in any way?
import sys
from PyQt5.QtCore import Qt
from PyQt5.QtWidgets import QApplication, QHBoxLayout, QLabel, QSizePolicy, QSlider, QSpacerItem, \
    QVBoxLayout, QWidget

import pyqtgraph as pg
import numpy as np

class Slider(QWidget):
    def __init__(self, minimum, maximum, parent=None):
        super(Slider, self).__init__(parent=parent)
        self.verticalLayout = QVBoxLayout(self)
        self.label = QLabel(self)
        self.verticalLayout.addWidget(self.label)
        self.horizontalLayout = QHBoxLayout()
        spacerItem = QSpacerItem(0, 20, QSizePolicy.Expanding, QSizePolicy.Minimum)
        self.horizontalLayout.addItem(spacerItem)
        self.slider = QSlider(self)
        self.slider.setOrientation(Qt.Vertical)
        self.horizontalLayout.addWidget(self.slider)
        spacerItem1 = QSpacerItem(0, 20, QSizePolicy.Expanding, QSizePolicy.Minimum)
        self.horizontalLayout.addItem(spacerItem1)
        self.verticalLayout.addLayout(self.horizontalLayout)
        self.resize(self.sizeHint())

        self.minimum = minimum
        self.maximum = maximum
        self.slider.valueChanged.connect(self.setLabelValue)
        self.x = None
        self.setLabelValue(self.slider.value())

    def setLabelValue(self, value):
        self.x = self.minimum + (float(value) / (self.slider.maximum() - self.slider.minimum())) * (
        self.maximum - self.minimum)
        self.label.setText("{0:.4g}".format(self.x))

class Widget(QWidget):
    def __init__(self, parent=None):
        super(Widget, self).__init__(parent=parent)
        self.horizontalLayout = QHBoxLayout(self)

        # plot (p6)
        self.win = pg.GraphicsWindow(title="Basic plotting examples")
        self.horizontalLayout.addWidget(self.win)
        self.p6 = self.win.addPlot(title="My Plot")
        x = np.arange(1e5)
        self.y1 = np.random.randn(x.size)
        self.p6.plot(self.y1, pen="r")
        self.p6.setMouseEnabled(x=True, y=False)
        self.p6.setXRange(0,300)
        self.p6.setLimits(xMin=0, xMax=len(self.y1))

        self.p6.sigRangeChanged.connect(self.update_plot)

        # slider (w1)
        self.w1 = Slider(0, len(self.y1))
        self.horizontalLayout.addWidget(self.w1)
        self.w1.slider.setMinimum(0)
        self.w1.slider.setMaximum(len(self.y1))

        self.w1.slider.valueChanged.connect(self.update_slider)

    def update_plot(self):
        self.axX = self.p6.getAxis('bottom')
        self.xmin = self.axX.range[0]
        self.xmax = self.axX.range[0]
        print(self.axX.range)
        return self.xmin, self.xmax

    def update_slider(self, xmin, xmax):
        self.size = self.w1.slider.value()
        self.p6.setXRange(self.xmin+self.size,self.xmax+self.size)
        print(self.size)

if __name__ == '__main__':
    app = QApplication(sys.argv)
    w = Widget()
    w.show()
    sys.exit(app.exec_())

Answer: First of all, the question you asked first was actually more useful for the StackOverflow "conduct". After the editing you just left what is an useless plain copy/paste from a pyqtgraph example.
Don't do that.
People rarely go through editings, and seeing the current status of your question, they would think that you didn't put any efforts at all in trying to solve your problem (leading them to just ignore your question). I suggest you to undo your editing or, at least, restore the original question example code.

The main problem with your question is that zooming is not linear. From a normal user perspective, each step of a zoom slider should increase or decrease by a zoom factor (pyqtgraph does that, actually).
A slider is usually a linear interface, which means that each of its step should be equally proportional to its previous or next steps.
Simply put, if the "middle step" of the slider equals to the original size of an image and the "next step" equals to a double size, the user expects that the step next to that will result in doubling the size again. The same works backwards too, obviously.
Imagine it as a spinbox, or even a couple of +/- buttons.
    size = 2
    print(size)
Out[1]: 2

    def doZoom(size, step):
        zoomFactor = 2
        if step > 0:
            size *= zoomFactor
        else:
            size /= zoomFactor
        return size

    size = doZoom(size, +1)
    print(size)
Out[2]: 4

    size = doZoom(size, +1)
    print(size)
Out[3]: 8

    size = doZoom(size, -1)
    print(size)
Out[4]: 4

A possible solution is to implement a slider that takes into account all of this.
import sys
from math import log
from PyQt5.QtCore import Qt
from PyQt5.QtWidgets import (QApplication, QLabel, QSlider, QWidget,
    QHBoxLayout, QVBoxLayout)

import pyqtgraph as pg
import numpy as np

class LabelSlider(QWidget):
    def __init__(self, *args, **kwargs):
        super(LabelSlider, self).__init__(*args, **kwargs)
        layout = QVBoxLayout(self)
        # IMPORTANT! QStyles sometimes create *huge* margins (6-10 pixels) around
        # layout contents; we don't really need those in here
        layout.setContentsMargins(0, 0, 0, 0)

        self.label = QLabel()
        layout.addWidget(self.label, alignment=Qt.AlignHCenter)
        # use an arbitrary text for the minimum width to minimize size flickering
        # on value changes
        self.label.setMinimumWidth(self.fontMetrics().width("8.8888e+88"))
        self.label.setAlignment(Qt.AlignCenter)

        layout.addSpacing(10)

        self.slider = QSlider()
        # when adding a QSlider to a QLayout and specifying an alignment, the
        # opposite of the orientation *has* to be omitted to ensure that it's
        # centered in the other direction
        layout.addWidget(self.slider, alignment=Qt.AlignHCenter)
        # set the slider "transparent" for mouse events, so that the user will
        # still see it as enabled but won't be able to interact with it
        self.slider.setAttribute(Qt.WA_TransparentForMouseEvents)

        #set a range high enough to limit rounding errors
        self.slider.setMaximum(100000)

        # expose the basic slider signal/methods for transparency, so that
        # this LabelSlider will have a similar interface to that of a QSlider
        self.value = self.slider.value
        self.valueChanged = self.slider.valueChanged

    def setValue(self, value, xLimit):
        sliderValue = self.slider.maximum() - value * self.slider.maximum()
        self.slider.setValue(sliderValue)

        xLimitMin, xLimitMax = xLimit
        limitRange = xLimitMax - xLimitMin
        floatValue = xLimitMin + (value * limitRange / (limitRange)) * (
            limitRange)
        self.label.setText("{0:.4g}".format(floatValue))
        # ensure that the widget is resized to fit the label contents too;
        # sizeHint will be called afterwards
        self.updateGeometry()

    def sizeHint(self):
        hint = super(LabelSlider, self).sizeHint()
        # adjust the minimum hint width to accomodate the label contents
        if hint.width() < self.label.width():
            hint.setWidth(self.label.width())
        return hint

class Widget(QWidget):
    def __init__(self, parent=None):
        super(Widget, self).__init__(parent=parent)
        self.horizontalLayout = QHBoxLayout(self)

        self.win = pg.GraphicsWindow(title="Basic plotting examples")
        self.horizontalLayout.addWidget(self.win)
        self.p6 = self.win.addPlot(title="My Plot")
        x = np.arange(1e5)
        self.y1 = np.random.randn(x.size)
        self.p6.plot(self.y1, pen="r")
        self.p6.setMouseEnabled(x=True, y=False)
        self.p6.setXRange(0,300)
        # set a minimum x range for the plot
        # this value *HAS* to be > 0
        self.p6.setLimits(xMin=0, xMax=len(self.y1), minXRange=1)

        self.p6.sigRangeChanged.connect(self.update_plot)

        self.slider = LabelSlider()
        self.horizontalLayout.addWidget(self.slider)

    def update_plot(self):
        state = self.p6.getViewBox().state

        # get the limits of the plot's ViewBox
        limits = state["limits"]
        minZoom, maxZoom = xLimit = limits["xLimits"]
        xRangeMin, xRangeMax = limits["xRange"]

        # if the minimum x range is set, use that instead
        if xRangeMin is not None:
            minZoom = xRangeMin
        # ensure that the minimum x range is > 0
        minZoom = max(1, minZoom)
        if xRangeMax is not None:
            maxZoom = xRangeMax
        xMin, xMax = self.p6.getAxis("bottom").range
        diff = xMax - xMin

        # get the possible minimum and maximum values based on the wheel factor
        factor = abs(state["wheelScaleFactor"])
        minimum = log(maxZoom / 100000., factor)
        maximum = log(minZoom / 100000., factor)
        value = log(diff / 100000., factor)

        # adjust the factor to a 0.0-1.0 range according to the possible zoom
        realValue = (value - minimum) / (maximum - minimum)

        # set the slider value according to the above value
        self.slider.setValue(realValue, xLimit)

if __name__ == "__main__":
    app = QApplication(sys.argv)
    w = Widget()
    w.show()
    sys.exit(app.exec_())

Comment: Sorry I am new to both Python and the stackoverflow questioning. I have edited back to the original question and code with some adjustments. Thanks for your help
Comment: You're welcome, glad to be of help... And don't worry, we all make mistakes :-) Just remember for the future, it's always better to provide an example as much complete as possible (while still keeping it *minimal*), including all necessary code to minimize the efforts required to understand and answer; a good question could even require more than one hour to get it right, but it's worth the effort if somebody able to help you realizes that he/she can give an answer without struggling even before doing it.


Menu Hambúrguer Bootstrap

Question: Minha aplicação tem um dashboard com uma coluna lateral esquerda, que é onde fica o menu. Quando essa página é aberta em telas menores a coluna some(isso já acontece), só que eu preciso que no lugar dela o menu Hamburguer apareça para que o usuário possa ter acesso ao menu.
Meu código está assim:

<?php echo strtoupper($_SESSION ['nickUser']) ?>

 Início

 Buscar

 Assistido

 Bate-papo

 Configurações

                        <?php
                        $link = filter_input(INPUT_GET, 'p');
                        include $link . ".php";

                        ?>

O resultado é esse:

E Mobile fica assim:

Tentei buscar essa solução porém nada funcionou.
Obrigado!
Answer: Veja se isso te ajuda:
Codepen
Comment: Então, é bem parecido com um código que eu havia usado, mas não funciona... eu só consigo fazer o botão aparecer se for na div fixa no topo(o que não pode) e mesmo assim quando clico no botão nada acontece

Menu Hambúrguer Bootstrap


NSData datawithcontentsOfURL not working in my project

Question: While I m trying to get data from the URL it returns nil. But the same line works in other projects. I have tested it with by creating new project. My code is here
NSData *imgData=[NSData dataWithContentsOfURL:[NSURL URLWithString:@"http://image.projectnext.eu/RBXF_Icon.jpg"]];
it gets data perfectly in my test project but not working in needed project. Is there any settings to be enabled in my original project?
Comment: I've seen some of the NSURL objects not working properly outside of the main thread.  Is this code running in the mainthread or in a background?
Comment: Actually i was uased in the background process that is in new thread, later seeing that the NSData not working well, I tried in the main thread too it not working. One more thing is whatever variable that I m declaring gets nil within the next line of execution. For example I tried just assigning a value for a string.
NSSTRing *str=@"String added";
While I m trying through debugger. in next line of execution the string value becoming nil. It show str value as "<varaible Invalid". Wat the same happened for the NSData.
Answer: Make sure you have network connectivity -- either WiFI or over the phone network....
Comment: ya network is available. I m testing in simulator. Network connection is good. It works absolutely in my sample project.


How to add series values to date/datetime object?

Question: I have a pandas dataframe like as shown below
df = pd.DataFrame({'login_date':['5/7/2013 09:27:00 AM','09/08/2013 11:21:00 AM','06/06/2014 08:00:00 AM','06/06/2014 05:00:00 AM','','10/11/1990'],
'DURATION':[21,30,200,34,45,np.NaN})

I would like to add DURATION values to the login_date column
The DURATION is represented in Days type
If there is NA in DURATION column, just replace it with 0.
So, I tried the below
df['DURATION'] = df['DURATION'].fillna(0)
df['login_date'] = pd.to_datetime(df['login_date'])
df['DURATION'] = df['DURATION'].astype('Int64')
df['logout_Date'] = df['login_date'] + pd.offsets.DateOffset(days=df['DURATION'])

However, this results in an error as shown below
TypeError: Invalid type <class 'pandas.core.series.Series'>. Must be int or float.

But I have already converted my DURATION column to int64 type.
How to add a column of values to my logout_date column
Answer: Try:
df["logout_date"] = pd.to_datetime(df["login_date"]) + df["DURATION"].fillna(0).apply(lambda x: pd.Timedelta(days=x))
print(df)

Prints:
               login_date  DURATION         logout_date
0    5/7/2013 09:27:00 AM      21.0 2013-05-28 09:27:00
1  09/08/2013 11:21:00 AM      30.0 2013-10-08 11:21:00
2  06/06/2014 08:00:00 AM     200.0 2014-12-23 08:00:00
3  06/06/2014 05:00:00 AM      34.0 2014-07-10 05:00:00
4                              45.0                 NaT
5              10/11/1990       NaN 1990-10-11 00:00:00


cylindrical and rectangular coordinates

Question:
Hi! I am currently working on some online homework and I don't understand what I am doing wrong when solving this problem. I know that the first and third coordinates are correct, but I seem to be having some issues finding the correct second coordinate. I understand that, when converting from rectangular to spherical coordinates, theta is equal to arctan(y/x). So to solve for the second coordinate i set theta equal to arctan((-15sqrt3)/-15) and received an answer of 60 which is equivalent to pi/3 but apparently that is incorrect according to the homework site. If someone can help me understand how to correctly solve for the second coordinate in the problem i would greatly appreciate it.
Comment: Seems right to me; maybe they wanted you to add integer multiples of $2k\pi$?
Comment: @Amzoti I just tried -120 and -2pi/3 and it still says that it is incorrect.
Comment: @Amzoti i just tried that website and it gave me an answer of -155.90515744789 for the second coordinate, but when I then tried that on my online homework it said that that answer was incorrect as well.
Answer: Because $x$ and $y$ are negative, the point is in the 3rd quadrant of the $xy$ plane, so that $\pi \leq \theta \leq \frac{3\pi}{2}$.
So here, $\theta = \pi + \frac{\pi}{3} = \frac{4\pi}{3}$.

cylindrical and rectangular coordinates


how to load custom Field Type into a custom Module (form)

Question: I'm trying to make a set of field type (location field type which contain of: country, City, Address, Google map which store lat & long, etc.) and this 'set' of field i need to load into my custom module (form).
so if i have:
FieldType
<?php

/**
 * @file
 * Contains \Drupal\arm_main\Plugin\Field\FieldType\CustomField.
 */

namespace Drupal\arm_main\Plugin\Field\FieldType;

use Drupal\Core\Field\FieldItemBase;
use Drupal\Core\TypedData\DataDefinition;
use Drupal\Core\Field\FieldStorageDefinitionInterface as StorageDefinition;

/**
 * Plugin implementation of the 'custom' field type.
 *
 * @FieldType(
 *   id = "custom",
 *   label = @Translation("Custom"),
 *   description = @Translation("Stores custom data."),
 *   category = @Translation("My Category"),
 *   default_widget = "custom_default",
 *   default_formatter = "CustomFieldDefaultFormatter"
 * )
 */

class CustomField extends FieldItemBase {

  const COUNTRY_ISO2_MAXLENGTH = 2;

  public static function propertyDefinitions(StorageDefinition $storage) {

    $properties = [];

    $properties['a'] = DataDefinition::create('string')
      ->setLabel(t('Label A'))
      ->setRequired(TRUE);

    $properties['b'] = DataDefinition::create('string')
      ->setLabel(t('Label B'))
      ->setRequired(TRUE);

    $properties['c'] = DataDefinition::create('string')
      ->setLabel(t('Label C'));

    $properties['d'] = DataDefinition::create('float')
      ->setLabel(t('Label D'));

    $properties['e'] = DataDefinition::create('float')
      ->setLabel(t('Label E'));

    $properties['f'] = DataDefinition::create('integer')
      ->setLabel(t('Label F'));

    return $properties;
  }

  public static function schema(StorageDefinition $storage) {

    $columns = [];
    $columns['a'] = [
      'type' => 'varchar',
      'length' => 255,
    ];
    $columns['b'] = [
      'type' => 'varchar',
      'length' => 255,
    ];
    $columns['c'] = [
      'type' => 'text',
      'length' => 255,
    ];

    $columns['d'] = [
      'type' => 'float',
      'size' => 'big',
      'default' => 0.0,
      'not null' => FALSE,
    ];
    $columns['e'] = [
      'type' => 'float',
      'size' => 'big',
      'default' => 0.0,
      'not null' => FALSE,
    ];
    $columns['f'] = [
      'type' => 'int',
      'length' => 10,
      'not null' => FALSE,
    ];

    return [
      'columns' => $columns,
      'indexes' => [],
    ];
  }

  public function isEmpty() {

    $isEmpty =
      empty($this->get('a')->getValue()) &&
      empty($this->get('b')->getValue()) &&
      empty($this->get('c')->getValue()) &&
      empty($this->get('d')->getValue()) &&
      empty($this->get('e')->getValue());

    return $isEmpty;
  }

  /**
   * {@inheritdoc}
   */
  public function getConstraints() {
    $constraint_manager = \Drupal::typedDataManager()->getValidationConstraintManager();
    $constraints = parent::getConstraints();

    $constraints[] = $constraint_manager->create('ComplexData', array(
      'value' => array(
        'Length' => array(
          'max' => static::COUNTRY_ISO2_MAXLENGTH,
          'maxMessage' => t('%name: the country iso-2 code may not be longer than @max characters.', array('%name' => $this->getFieldDefinition()->getLabel(), '@max' => static::COUNTRY_ISO2_MAXLENGTH)),
        )
      ),
    ));
    return $constraints;
  }

} // class

FieldWidget
<?php

/**
 * @file
 * Contains \Drupal\arm_main\Plugin\Field\FieldType\CustomFieldDefaultWidget.
 */

namespace Drupal\arm_main\Plugin\Field\FieldWidget;

use Drupal\Core\Field\FieldItemListInterface;
use Drupal\Core\Field\WidgetBase;
use Drupal\Core\Form\FormStateInterface;

/**
 * Plugin implementation of the 'custom_default' widget.
 *
 * @FieldWidget(
 *   id = "custom_default",
 *   label = @Translation("Custom"),
 *   field_types = {
 *     "custom"
 *   }
 * )
 */
class CustomFieldDefaultWidget extends WidgetBase {

/**
   * {@inheritdoc}
   */
  public static function defaultSettings() {
    return array(
      'size' => 60,
      'placeholder' => '',
    ) + parent::defaultSettings();
  }

  /**
   * {@inheritdoc}
   */
  public function settingsForm(array $form, FormStateInterface $form_state) {
    $element['size'] = array(
      '#type' => 'number',
      '#title' => $this->t('Textfield size'),
      '#default_value' => $this->getSetting('size'),
      '#required' => TRUE,
      '#min' => 1,
    );
    $element['placeholder'] = array(
      '#type' => 'textfield',
      '#title' => t('Placeholder'),
      '#default_value' => $this->getSetting('placeholder'),
      '#description' => t('Text that will be shown inside the field until a value is entered. This hint is usually a sample value or a brief description of the expected format.'),
    );
    return $element;
  }

  /**
   * {@inheritdoc}
   */
  public function settingsSummary() {
    $summary = array();

    $placeholder = $this->getSetting('placeholder');
    if (!empty($placeholder)) {
      $summary[] = t('Placeholder: @placeholder', array('@placeholder' => $placeholder));
    }else {
      $summary[] = t('No placeholder');
    }
    $summary[] = t('Textfield size: @size', array('@size' => $this->getSetting('size')));

    return $summary;
  }

  public function formElement(FieldItemListInterface $items, $delta, Array $element, Array &$form, FormStateInterface $formState) {

    $countries = \Drupal::service('country_manager')->getList();

    $element['a'] = [
        '#type' => 'select',
        '#options' => $countries,
        '#empty_value' => '',
        '#default_value' => (isset($items[$delta]->value) && isset($countries[$items[$delta]->value])) ? $items[$delta]->value : NULL,
        '#description' => t('Description here'),
      ];

    $element['b'] = [
      '#type' => 'textfield',
      '#title' => t('Title B'),
      '#default_value' => isset($items[$delta]->b) ?
          $items[$delta]->b : null,
      '#empty_value' => '',
      '#placeholder' => t('B Here'),
    ];

    $element['c'] = [
      '#type' => 'textfield',
      '#title' => t('Title C'),

      '#default_value' => isset($items[$delta]->c) ?
          $items[$delta]->c : null,

      '#empty_value' => '',
      '#placeholder' => t('C Here'),
    ];

    $element['intro'] = [
      '#type' => 'markup',
      '#markup' => t('some text here...'),
      '#prefix' => '
',
      '#suffix' => '
',
    ];

    $element['d'] = [
      '#title' => t('Title D'),
      '#type' => 'textfield',
      '#default_value' => isset($items[$delta]->d) ? $items[$delta]->d : NULL,
      '#empty_value' => 0,
      '#placeholder' => t('D Here'),
      '#attributes' => array(
        'data-d-delta' => $delta,
        'class' => array('custom-field-watch-change'),
      ),
    ];

    $element['e'] = [
      '#title' => t('Title E'),
      '#type' => 'textfield',
      '#default_value' => isset($items[$delta]->e) ? $items[$delta]->e : NULL,
      '#empty_value' => 0,
      '#placeholder' => t('E Here'),
      '#attributes' => array(
        'data-e-delta' => $delta,
        'class' => array('custom-field-watch-change'),
      ),
    ];

    $element['f'] = [
      '#title' => t('Title F'),
      '#type' => 'textfield',
      '#default_value' => isset($items[$delta]->f) ? $items[$delta]->f : NULL,
      '#empty_value' => 7,
      '#placeholder' => t('F Here'),
      '#attributes' => array(
        'data-f-delta' => $delta,
        'class' => array('custom-field-watch-change'),
      ),
    ];

    $element['open_but'] = [
      '#type' => 'button',
      '#value' => t('Set button Marker'),
      '#attributes' => array(
        'data-delta' => $delta,
        'id' => 'but_setter_' . $delta,
      ),
    ];

    $element['clear_fields'] = [
      '#type' => 'button',
      '#value' => t('Clear Fields'),
      '#attributes' => array(
        'data-delta' => $delta,
        'id' => 'clear_fields_' . $delta,
        'class' => array('custom-field-clear'),
      ),
      '#suffix' => '
',
    ];

    $element['preview'] = [
      '#type' => 'item',
      '#title' => t('Preview'),
      '#markup' => '

',
      '#prefix' => '
',
      '#suffix' => '
',
    ];

    return $element;
  }

} // class

how do i load it into FormBase programmatically in here:
class testCreateForm extends FormBase {

  public function __construct($coreService, $mainService) {      }
  public static function create(ContainerInterface $container) {      }
  public function getFormId() {      }

  public function buildForm(array $form, FormStateInterface $form_state) {
    $form['someSample'] = array(
      '#type' => 'details',
      '#title' => t('Add new things'),
      '#description' => t('desc here'),
      '#open' => TRUE,
    );
    $form['someSample']['test'] = array(
      '#type' => 'textfield',
      '#title' => t('test'),
      '#description' => $this->t('Your test code'),
      '#default_value' => "",
      '#size' => 10,
      '#maxlength' => 8,
      '#required' => TRUE,
    );
    $form['someSample']['custom'] = array( // i did this but not work
      '#type' => 'custom',
      '#title' => t('Custom Title'),
    );
    return $form;
  }

  /**
   * {@inheritdoc}
   */
  public function validateForm(array &$form, FormStateInterface $form_state) {      }

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {

  }

}

Answer: The purpose of a field type is defining a field that is then attached to an entity. Once the field is attached to an entity, its widget will be used for entering the data, and its formatter will be used to show the entered data.
See for example the email field type. It's implemented by the EmailItem class; its default widget is implemented by the EmailDefaultWidget, which in £mailDefaultWidget::formElement() uses the following code.
  $element['value'] = $element + array(
    '#type' => 'email',
    '#default_value' => isset($items[$delta]->value) ? $items[$delta]->value : NULL,
    '#placeholder' => $this->getSetting('placeholder'),
    '#size' => $this->getSetting('size'),
    '#maxlength' => Email::EMAIL_MAX_LENGTH,
  );
  return $element;

With a field type, you will never directly output it in a form. That is only the purpose of its widget.
If you want to just have something to use directly in a form, you need to implement a form input element, which is what Drupal does with the Email class, for example.
As in this case, a widget class for a field type can use the form input element defined from another class.
Comment: Hi @kiamlaluno thanks for your reply, I did try to see your example but fail to understand how it's linked/relate all together :( i have update my question to give my complete fieldType and fieldWidget code and how i implement it. but seems like it didn't work. if you don't mind to en-light me more, very much appreciate.
Comment: You are confusing entity fields (implemented by your first part) with form fields. You don't add an entity field to a form as you are trying to do.
Comment: Thank you for the reply, to make things clearer, I'm trying to make a set of field type (location field type which contain of: country, City, Address, Google map which store lat & long, etc.) and this 'set' of field i need to load into my custom module (form). so now if I understand correctly from you: that my approach is not the right approach to my requirement, as custom field type can't be applied to a form, am I right?
if, so what is the 'right' approach for this requirements?
Answer: i found some tutorial here:
https://docs.acquia.com/articles/drupal-8-creating-elements-theming-elements-and-managing-frontend-libraries
and it works to me, so generally all you need to build is an element class, define your element class, apply it to template then should be done.
if someone interested, i dont mind to write more detailed here
Thanks
Comment: 404 error in given link.


Ajax enabled form stopped working - Ajax callback never called

Question: I have the weird problem that an Ajax enabled form that just worked stopped working - and I have not a clue what is causing this and when it stopped to work. The form itself has no changes for months now and I did not find any code updates which may interfere with this form.
The form is defined in its own form class which extends FormBase. The Ajax functionality is added with the following code in buildForm() method:
<code>$form['form_container']['actions']['submit'] = [
  '#type' => 'submit',
  '#value' => 'Submit',
  '#ajax' => [
    'callback' => '::ajaxResponse'
  ],
  '#attributes' => [
    'class' => ['js-show-throbber']
  ],
  '#weight' => -45,
];
</code>
In the form class the method is defined:
<code>public function ajaxResponse(array $form, FormStateInterface $form_state)
</code>
When I set a breakpoint within this method for XDebug the script never stops, the process within this methods are not running.
There is no info in browser's console, it is not working in any browser and in watchdog of Drupal are no entries. For me it seems that somehow the bridge between browser / JavaScript world and the form PHP class is broken. I use the exact same PHP code for many other forms without any problem.
My question: can anybody give me a hint how exactly the bridge between browser and form class is created when the form gets rendered? How can I find out if there is a problem in the PHP form class or somewhere in JavaScript?
Comment: Can you replicate on a fresh install?
Comment: Can you replicate this when logged in and/or with or without admin role? Is there any custom JS involved? BigPipe or some other caching involved?
Comment: Thank your for your tipps... good ideas, I will check this tomorrow! Clear is: it is happening independently from the role. Cachings are deactivated. Really strange, I am very eager to find out what the problem is here...
Comment: try `'callback' => [get_class($this), 'ajaxResponse'],`
Answer: Ok, this was just a stupid mistake in a another javascript. There the jQuery method .off() was used to remove event listeners which had the effect to remove the Ajax event listener.


Adaptar consultar para criar VIEW que devolve soma da contagem de duas Subqueries

Question: De acordo com a documentação, o MySQL não permite o uso de subqueries no FROM quando a consulta é uma view:

Subqueries cannot be used in the FROM clause of a view.

Que resulta no seguinte erro:

1349: View's SELECT contains a subquery in the FROM clause

A seguinte consulta devolve a soma da contagem dos registos de cada tabela:
SELECT SUM(total)
FROM (
    SELECT COUNT(*) AS total
    FROM tabela1
    WHERE escondido='não'

    UNION ALL

    SELECT COUNT(*) AS total
    FROM tabela2
    WHERE escondido='não'
) t

Assumindo 1000 registos na tabela1 e 500 na tabela2, a consulta devolve 1500.

Com a seguinte alteração à consulta, já é possível criar a view, mas o resultado são duas linhas, cada uma com o total de registos de cada tabela:
SELECT COUNT(*) AS total
FROM tabela1
WHERE escondido='não'

UNION ALL

SELECT COUNT(*) AS total
FROM tabela2
WHERE escondido='não'

Como manter o conceito original da consulta utilizando a mesma numa view ?
Comment: `SELECT Sum(total) FROM View_no_Mysql_que_nao_aceita_subquery` não soluciona seu problema?
Comment: @gmsantos De certa forma deverá resultar, mas a ideia é que a `view` em si devolva o resultado do `SUM()` e não valores para serem processados.
Comment: Sem subquery acho complicado... vou tentar aqui com `outer join`. Por essas e outras estou largando o MySql
Comment: @gmsantos Obrigado pelo apoio, coloquei agora uma resposta com uma solução que vai ao encontro do que procurava... Tenho estado a testar o assunto e desta forma consigo resolver a questão.
Answer: Após alguns testes, eis uma forma de resolver a questão:
SELECT (
    (SELECT COUNT(*) AS total
     FROM tabela1
     WHERE escondido='não')

    +

    (SELECT COUNT(*) AS total
     FROM tabela2
     WHERE escondido='não')
) AS total

Básicamente passei a lógica aplicada no FROM para o SELECT indo ainda ao encontro do pretendido dentro das regras do MySQL.
Answer: Outras duas alternativas seriam:

Utilizar um Sum() fora da view:
SELECT Sum(total) FROM View_no_Mysql_que_nao_aceita_subquery

Criar uma view para a view
CREATE VIEW mysql_precisa_de_gambiarras AS
SELECT Sum(total) FROM View_no_Mysql_que_nao_aceita_subquery

Por fim ficaria:
SELECT * FROM mysql_precisa_de_gambiarras

Comment: +1 pelo nome das views :)
Answer: Você pode executar o seguinte comando SQL:

Ou então você pode adicionar 1 campo na tabela1, chamado countTabela1 e
outra na tabela2, chamado countTabela2 que conterão quantas linhas cada tabela possui.
Depois você fazer é criar uma tabela, chamada countTabela que possua 2 campos:
1º campo: uma chave estrangeira da tabela1, chamado FK_countTabela1;
2º campo: uma chave estrangeira da tabela2, chamado FK_countTabela2;
Só depois realizar o somatório dos 2 campos:
SELECT FK_countTabela1 + FK_countTabela2 AS Total FROM countTabela;


Get paths of files attached to the node from field name

Question: How can I get the paths (URLs) of files attached to the node from field name in Drupal 8?
I tried using Drupal 7's node_load(), but that does not return paths of the files:
$node = \Drupal::routeMatch()->getParameter('node');
$node = node_load($node->id());
var_dump($node);

Comment: This seems to be very similar to what you asking for: http://drupal.stackexchange.com/a/222948/42650
Answer: You can get it like this:
$file_uri = $node->field_machine_name->entity->getFileUri();
If your field allows for more than 1 value, then:
$file_uris = array();
foreach ($node->field_machine_name as $value) {
  if ($value->entity) {
    $file_uris[] = $value->entity->getFileUri();
  }
}


initiate class parameters after initiating two members of class

Question: at first i apologize if its a silly question. I'm new in .net.
I have a mobile class like this:
    public class Mobile
{
    private string region;
    private string number;
    private bool regionIsValid;
    private bool numberContentIsValid;
    private string internationalNumber;

    public string Region
    {
        set { region = value.ToUpper(); ConvertNumber(); }
        get { return region; }
    }
    public string Number
    {
        set { number = value; ConvertNumber(); }
        get { return number; }
    }
    public Interface Reason
    {
        set { reason = value; }
        get { return reason; }
    }
    public bool NumberContentIsValid
    {
        set { numberContentIsValid = value; }
        get { return numberContentIsValid; }
    }
    public string InternationalNumber
    {
        set { internationalNumber = value; }
        get { return internationalNumber; }
    }

    public void ConvertNumber()
    {
        var sw = Stopwatch.StartNew();

        try
        {
            if (Number == null || Region == null || DoesNumberContentValid() == false || NumberContentIsValid == false)
                return;

            var phoneUtil = PhoneNumberUtil.GetInstance();
            var phone = phoneUtil.Parse(Number, Region);
            InternationalNumber = phoneUtil.Format(phone, PhoneNumberFormat.INTERNATIONAL);

            Log.GetLogger().Info(Format.CreateLogMessage("converting mobile number completed successfully.", sw.Elapsed.TotalMilliseconds));
            return;
        }
        catch (Exception ex)
        {
            Log.GetLogger().Error(Format.CreateLogMessage(ex.ToString(), sw.Elapsed.TotalMilliseconds));
            return;
        }

    }
    public bool DoesNumberContentValid()
    {
        var sw = Stopwatch.StartNew();
        var len = new Regex(@"^.{2,20}$"); //length at least 6 characters and maximum of 20
        var digit = new Regex(@"^[0-9]*$"); //a string consisting only of numbers

        if (number.StartsWith(@"+") == true) number = number.Substring(1);
        number = number.Replace(" ", string.Empty);

        try
        {
            if (!len.IsMatch(Number))
            {
                NumberContentIsValid = false;
                Reason = new Interface("G00005");
            }
            else if (!digit.IsMatch(Number))
            {
                NumberContentIsValid = false;
                Reason = new Interface("G00005");
            }
            else if (Region != "IR")
            {
                NumberContentIsValid = false;
                Reason = new Interface("G00005");
            }
            else
            {
                var phoneUtil = PhoneNumberUtil.GetInstance();
                var mobile = phoneUtil.Parse(Number, Region);
                if (phoneUtil.IsValidNumber(mobile) != true)
                {
                    NumberContentIsValid = false;
                    Reason = new Interface("G00005");
                }
                else if (phoneUtil.GetNumberType(mobile).ToString() != "MOBILE")
                {
                    NumberContentIsValid = false;
                    Reason = new Interface("G00005");
                }
                else
                    NumberContentIsValid = true;
            }

            Log.GetLogger().Info(Format.CreateLogMessage("mobile content validation completed successfully.", sw.Elapsed.TotalMilliseconds));
            return true;
        }
        catch (Exception ex)
        {
            Reason = new Interface("G00001", ex.Message);
            Log.GetLogger().Error(Format.CreateLogMessage(ex.ToString(), sw.Elapsed.TotalMilliseconds));
            return false;
        }
    }
}

i want to initiate the internationalNumber if Number and Region both are available. please take look at my convertnumber() method:
        public void ConvertNumber()
    {
        var sw = Stopwatch.StartNew();

        try
        {
            if (Number == null || Region == null || DoesNumberContentValid() == false || NumberContentIsValid == false)
                return;

            var phoneUtil = PhoneNumberUtil.GetInstance();
            var phone = phoneUtil.Parse(Number, Region);
            InternationalNumber = phoneUtil.Format(phone, PhoneNumberFormat.INTERNATIONAL);

            Log.GetLogger().Info(Format.CreateLogMessage("converting mobile number completed successfully.", sw.Elapsed.TotalMilliseconds));
            return;
        }
        catch (Exception ex)
        {
            Log.GetLogger().Error(Format.CreateLogMessage(ex.ToString(), sw.Elapsed.TotalMilliseconds));
            return;
        }

    }

in order to do this i use the Number and Region property setter like this:
public string Region
{
    set { region = value.ToUpper(); ConvertNumber(); }
    get { return region; }
}
public string Number
{
    set { number = value; ConvertNumber(); }
    get { return number; }
}

it works. but it might causes unexpected errors(you realize if take look at my DoesNumberContentValid() method. tips: i have to use the number instead Number)
now i wonder is there better way to do it? (obliviously i cant use class contractor because i cant initiate both parameters at a same time. )
Thank you.
Comment: IS the international number property always in relation to the other two properties? Are you sure you want to allow the user to set the international number property separately?
Comment: Thanks dear @ Maor Veitsman. yes the international number always in relation to the other two properties and i want to et the international number property separately.
Comment: Just to be sure, the InternationalNumber property should have a private setter, right?
Comment: no. it has a public setter.(i can set the InternationalNumber any where in my project.)
Comment: If the international number has been set and both the region and number has been set as well, what is the international number that should be returned?
Comment: no. let me explain it again. number is the user input.(its a mobile number) but i save it in a database in international format. this is my mobile number: 9111111111 and this is my international number: +98 911 111 1111(some how it contain the number value and region)
Answer: Perhaps this will work for you:
public string InternationalNumber
{
    set { internationalNumber = value; }
    get { return internationalNumber ?? CalcInternationalNumber(); }
}

And the function CalcInternationalNumber:
public string CalcInternationalNumber()
{
    var sw = Stopwatch.StartNew();

    try
    {
        if (Number == null || Region == null || DoesNumberContentValid() == false || NumberContentIsValid == false)
            return null;

        var phoneUtil = PhoneNumberUtil.GetInstance();
        var phone = phoneUtil.Parse(Number, Region);
        var intNum = phoneUtil.Format(phone, PhoneNumberFormat.INTERNATIONAL);

        Log.GetLogger().Info(Format.CreateLogMessage("converting mobile number completed successfully.", sw.Elapsed.TotalMilliseconds));
        return intNum;
    }
    catch (Exception ex)
    {
        Log.GetLogger().Error(Format.CreateLogMessage(ex.ToString(), sw.Elapsed.TotalMilliseconds));
        return null;
    }

}

Hope this was what you were looking for.


Timing of arpeggiated chords

Question: Arpeggiated chord [A] can be realized by either playing the first note on time, and the following notes later [B], or starting a bit in advance and playing the last note on time [C].
When each of them should be used? Is it entirely up to the performer, or are there some guidelines or conventions, perhaps depending on the epoch or style? Are there any notation marks that suggest which realization to choose?
Comment: Or you could time it so the second or third note is on time
Comment: @ToddWilcox yes, of course one can imagine various possibilities, but at least to me these two seem the most characteristic. It would make an interesting answer if you could show an example where what you propose is preferred or recommended.
Answer: Great question! My bible (Oxford Companion to Music) shows arps starting on the beat, rather than before it. Then goes on to state arps should not destroy the rhythm of the passage. Somewhat of an oxymoron!
An arp. sigh across one stave means play all those notes arpeggiated. Across both staves means start at the lowest and play through to the highest. And a split arp. sign means play both hands (on piano) simultaneously. Not that that helps, just interesting.
I tend to play arps so that the main note - usually the melody note - gets played in time, thus the arp. comes before the beat. But that's just my style. It will most likely depend on the genre and era, and will be left to the jurisdiction of the player to interpret what the composer wanted.
EDIT: Just retrieved my Elaine Gould's 'Behind Bars', out on loan, which states that 'A chord will be spread before the beat unless the playing style suggests otherwise'.

Timing of arpeggiated chords


php -> MYSQL query can't figure out what is wrong getting error #1064

Question: I am trying to insert some values in the table the query is below:
Insert into
auditlog (
          event,
          desc,
          userid,
          useripaddress,
          audittype
)
VALUES (
         'User Authenticated',
         'Useradminsuccessfully logged in to the system',
         '1',
         '127.0.0.1','1'
)

It gives me the following error:
 #1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'desc,userid,useripaddress,audittype)VALUES ('User Authenticated', 'User admin su' at line 1
However when i run the insert using PHPMYAdmin it does insert a value and the query generated is
INSERT INTO
     `auditlog`(
              `event`,
              `desc`,
              `userid`,
              `useripaddress`,
              `audittype`)
     VALUES (
              'User Authenticated',
              'Useradminsuccessfully logged in to the system',
              '1',
              '127.0.0.1','1'
     )

The only difference i see is the quotes which i dont believe are needed. I don't understand where am i going wrong and am breaking my head now :):)
Comment: possible duplicate of [How can I write SQL for a table that shares the same name as a protected keyword in MySql?](http://stackoverflow.com/questions/10706920/how-can-i-write-sql-for-a-table-that-shares-the-same-name-as-a-protected-keyword)
Answer: The backticks are needed around desc because it is a reserved word.
INSERT INTO auditlog (event, `desc`, userid, useripaddress, audittype)
VALUES (
    'User Authenticated',
    'Useradminsuccessfully logged in to the system',
    '1',
    '127.0.0.1',
    '1'
)

There is also no harm in adding backticks around the other column names if you aren't sure whether or not they are reserved words.
Comment: got it ...thnx...it works now!!! aahh didn't think desc can also be for descending ..i wanted to use short name for description...i just changed the column name to description to avoid any further issues. Thanks!!
Answer: Here is a list of words that are reserved and needs to be backticked: http://dev.mysql.com/doc/refman/5.5/en/reserved-words.html


why Tostring doesnot convert int to string

Question: Consider this code:
Dim a As Integer = 4
Dim c As Integer = 3
Console.WriteLine(a.ToString + c)
Console.ReadLine()

it should return 43 as a is being converted to string but still return 7
Comment: "it should return" - I think you can safely assums it's behaving as expected: presumably the string is converted back to an integer again.  Try the & operator.
Comment: Thanks for ur answer joe well u r right when both r strings then these can be easily concatenated but i want to know when we apply + within an int and string why doesn't it concatenate
Answer: Because you need to convert both operands to string, and/or use the string concatenation operator &.
As it stands, you are evaluating this expression:
"4" + 3

and VB decides to convert the first operand to be an integer to match the second operand. VB will only perform string concatenation with + if both operands are strings. It prefers arithmetic with +.
Some useful links:

http://msdn.microsoft.com/en-us/library/te2585xw.aspx
http://msdn.microsoft.com/en-us/library/9c5t70w2.aspx
http://msdn.microsoft.com/en-us/library/wfx50zyk.aspx

As you can see from these links, the setting of Option Strict plays a role. You clearly have it set to Off but frankly setting it to On would be prudent.
Personally I'd write it like this
a.ToString & c.ToString

The bottom line is that if you know you want to concatenate strings, it is always clearer to use the dedicated string concatenation operator &.
Comment: thanks so u say for concatenation both operand must be string
Comment: but the first link u provided says "The + Operator (Visual Basic) has the primary purpose of adding two numbers. However, it can also concatenate numeric operands with string operands"
Comment: Yes, that is correct. I repeated that in my answer. And by the way, I re-tagged the question since this is not vb6.


Ext.StoreMgr versus Ext.StoreManager?

Question: In ExtJs, what is the difference between Ext.StoreMgr and Ext.StoreManager?
I see both in the code I am working on and am worried we may have mixed versions of ExtJs or something.
Answer: Both are the same.
you can see in documentation Ext.data.StoreManager has 3 alternate names:

ALTERNATE NAMES:
  Ext.StoreManager
  Ext.StoreMgr
  Ext.data.StoreMgr

Ext.StoreMgr versus Ext.StoreManager?


How to fix search result "Access denied You are not authorized to access this page"

Question: How to fix search result "Access denied You are not authorized to access this page"?
Have tried to change permissions and search module configuration, nothing helps...
Comment: What do you mean by fixing it? Do you mean you want to give access to users or you want to display a better error message or what?
Answer: In admin/people/permissions, make sure that the roles that should be allowed to search are checked. Under the Search heading, look for the Use search permission. If anonymous users need this permission, check the box next to Anonymous User.
Next, clear your Drupal cache.
If you use Drush, you can use the following command.
<code>drush cc all
</code>
There are several other ways to clear your cache as well.
Lastly, you can try rebuilding your permissions at admin/reports/status/rebuild.


How to show my activity when the notification shade is pulled down

Question: Is it possible to make my activity to foreground when the notification shade is pulled down?.
My application is a simple VoIP application. My incoming call screen activity is shown behind the notification shade if it is pulled down.  Is there any way to hide the notification shade when my activity starts?.It happens in the case of native GSM calls.
Answer: You can hide notification shade with Java's reflection code.  Otherwise, the only way to detect when notification shade is pulled down is when your app's Activity is in the foreground.  And for that you can override the onWindowFocusChanged method in your Activity.


What does $s^t$ mean in group theory?

Question: For subset $S$ and $T$ of a group, define $ST = \{st|s \in S, t \in T\}$ and $S^T = \{s^t|s \in S, t \in T\}$.
What does $s^t$ mean in this context?
Answer: The notion $s^t$ where $s,t$ are elements of a group denotes the conjugation, and is, as @BabakSorouh mentioned, equal to $t^{-1}st$
Comment: I think $s^t=t^{-1}st$ is the "better" convention: It makes $s^{tu}=(tu)^{-1}stu=u^{-1}t^{-1}stu=u^{-1}s^tu=(s^t)^u$. Compare with $s^{tu}=tus(tu)^{-1}=tusu^{-1}t^{-1}=(s^u)^t$, which is less attractive.
Comment: ...or $tst^{-1}$ depending on convention.
Comment: @HagenvonEitzen: I agree. But some people like superscripts to be contravariant and subscripts to be covariant. I wonder if there's any precedent for writing $s^t=tst^{-1}$ and $s_t=t^{-1}st$...
Comment: @CliveNewstead I thought I had rather seen $^ts$.
Comment: I have never seen $^ts$. I prefer $t^{-1}st$, but I wouldn't say it is more or less prevalent than $tst^{-1}$. It perhaps depends on the area you work in. Recently, writing $tst^{-1}$ makes what I have been doing much, much neater.
Comment: I have seen $s^t=t^{-1}st$ and $^ts=tst^{-1}$ in a paper that makes frequent use of conjugation.
Answer: This symbol denotes conjugation: $s^t=t^{-1}st$ or $tst^{-1}$.
Be careful when you use this that you use a compatible notation with the commutator symbol.  $s^t=t^{-1}st$ should be paired with $[s,t]=s^{-1}t^{-1}st$ and $s^t=tst^{-1}$ with $[s,t]=sts^{-1}t^{-1}$.  The former is much more common, though the latter is seen sometimes too, but you don't want to mix them up or people will be real confused.
You'll also see $S^t$ going around, which means $S^t=\{s^t:s\in S\}$.
Comment: @CliveNewstead Haha, yes, sorry about that.

What does $s^t$ mean in group theory?