Push to another view controller taking too much time in iphone

Question: I am having an app in which I am opening initially a grid of images coming from webservice.
I am using DTGridView by danieltull.
Those images are from different categories like Natural, Arts, Paintings etc.
Initially when the app launches, The grid contain images from all the categories.
There is a category button on main screen, clicking on which user will be pushed to another view where different categories are mentioned like Natural, Arts, Paintings etc.
If a user clicks on any of the category he will be again lead to the Grid of images but will contain images only from that selected category.
The problem is that when the user clicks on any of the category then it takes too much time to navigate to the Grid View.
I am taking data from webservice when user clicks on any of the category.
I want to navigate user to the Gridview as soon as he clicks on category and then want to show custom Spinner.
on selecting the category i am doing the below code and calling the method of the gridview.
<code> if ([self isPad])
    {
         vc = [[ViewController alloc]initWithNibName:@"ViewController_iPad" bundle:nil];
    }
 [self.navigationController pushViewController:vc animated:NO];
[vc getCategoryNames];
</code>
Please help me on this.
** Edited **
<code>- (NSInteger)numberOfRowsInGridView:(DTGridView *)gridView
{
    if (countimages % 4 == 0)
    {
        return countimages/4;
    }
    else
    {

        return countimages/4 + 1;

    }

}

- (NSInteger)numberOfColumnsInGridView:(DTGridView *)gridView forRowWithIndex:(NSInteger)index
{
    return 4;
}

- (CGFloat)gridView:(DTGridView *)gridView1 heightForRow:(NSInteger)rowIndex
{
    return gridView1.frame.size.height / 3;
    // return 300;
   // NSLog(@"%f",gridView1.frame.size.height/3);

}

- (CGFloat)gridView:(DTGridView *)gridView1 widthForCellAtRow:(NSInteger)rowIndex column:(NSInteger)columnIndex
{
    return gridView1.frame.size.width / 4;
    //return 300;
  //  NSLog(@"%f",gridView1.frame.size.width/4);
}

- (DTGridViewCell *)gridView:(DTGridView *)gv viewForRow:(NSInteger)rowIndex column:(NSInteger)columnIndex {

    DTGridViewCell *cell = [gv dequeueReusableCellWithIdentifier:@"cell"];

    if (!cell) {
        cell = [[DTGridViewCell alloc] initWithReuseIdentifier:@"cell"];
  UIView* v=[[UIView alloc]init];
    v.frame=CGRectMake(0, 0, gridView.frame.size.width / 4, gridView.frame.size.height / 3);
    [cell addSubview:v];

    imgeIndex = 0;
    imgeIndex = (rowIndex * 4) + columnIndex;

    UIButton *btn = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, gridView.frame.size.width / 4, gridView.frame.size.height / 3)];
    [btn setTag:imgeIndex+1];
    [btn addTarget:self action:@selector(btnPressed:) forControlEvents:UIControlEventTouchUpInside];
    btn.contentMode = UIViewContentModeScaleAspectFit;
 if ([arr_imgurl count] <= imgeIndex)
        {
            btn.imageView.image=[UIImage imageNamed:@"logo_256.png"];
            return cell;
        }
        else
        {
            //NSLog(@"arr %d",[arr_imgurl count]);
            // NSLog(@"imgindex %d",imgeIndex);
            // NSLog(@"array %@",arr_imgurl);
            NSURL *url = [NSURL URLWithString:[arr_imgurl objectAtIndex:imgeIndex]];
            //NSLog(@"%@",url);
            [btn setImageWithURL:url placeholderImage:[UIImage imageNamed:@"logo_256.png"]];

        }
 btn.titleLabel.textColor = [UIColor whiteColor];

    [v addSubview:btn];
    [database close];

    return cell;
}
</code>
Here arr_imgurl contains imagepaths coming from webservice.
Comment: post code when you click on the button and image size u r getting?
Comment: I am using just a simple self.navigationcontroller pushview for this and calling a method of the gridview by making object of that view from this categoryview
Comment: This is probably because it takes time to load the image. Are you using background thread ?
Comment: put some code without code i can't unserstand where problem occur
Comment: Yes, it takes too much time to load the image. No i am not using any thread.
Comment: hey., plz help me...i have the same problemm.
Answer: While navigating never call web services(reason: it will hold navigation till it receives the complete information we can't be sure about server speed all the time). So better navigate and then call service in thread and mean while show Screen with activity indicator on it so that user will think app is loading images.(Make sure images are loading lazily because user will not have patience to wait till all images are loaded). If you need a sample for this i'll code it and give you.
Comment: Welcome @Manthan we are here to help each other
Answer: Most of the chances are that the loading of all the data for the grid in the new view controller takes the time.
There are plenty of different scenarios for this "incorrect" data loading.
It may be the web service loading synchronously in the main thread.
It may be images loading (in the grid delegate) synchronously in the main thread.
Etc.
Please post some code of the grid data initiation and grid delegate to better understand the exact problem.


Probability generating function and expectation

Question: Let $X$ be Poisson random variable with parameter $Y$, where $Y$ is Poisson random variable, with parameter $\mu$. Prove that, $G_{X+Y}(s)=\exp\{\mu (s\exp^{s-1}-1)\}$
I know that, Poisson r.v. generating function is $G(s)=\exp\{\lambda(s-1)\}$. Do I need to calculate joint probability distribution first ($P(Z)$), where $Z=X+Y$?
Answer: Hint: As recalled in the post, $E[s^X\mid Y]=\exp\{Y(s-1)\}$ hence $G_{X+Y}(s)=E[s^Xs^Y]$ is also $G_{X+Y}(s)=E[E[s^X\mid Y]s^Y]=E[\exp\{Y(s-1)\}s^Y]=E[t^Y]$ for $t$= $____$. Furthermore, for every $t$, $E[t^Y]=\exp\{\mu(t-1)\}$ hence $G_{X+Y}(s)=$ $______$.
Answer: Hint: Use that
$$
{\rm E}[s^{X+Y}]=\sum_{y=0}^\infty{\rm E}[s^{X+Y}\mid Y=y]\cdot P(Y=y)=\sum_{y=0}^\infty s^y\cdot {\rm E}[s^X\mid Y=y]\cdot P(Y=y)
$$
along with the fact that $X\mid Y=y\sim \mathrm{po}(y)$.
Comment: No. $s^Y$ is of course a random variable, but $s^Y\cdot 1_{\{Y=y\}}=s^y\cdot 1_{\{Y=y\}}$, i.e. on the set $\{Y=y\}$ we know that $s^Y$ is just $s^y$ which is constant. That is: on the set $\{Y=y\}$ you may treat $Y$ as being constant (constantly equal to $y$ of course).
Comment: Got a question about ${\rm E}[s^{X+Y}]=s^y\cdot {\rm E}[s^X\mid Y=y]$ -- did you use this property: ${\rm E}(XY|G)={\rm E}(X|G)Y$, where ${\rm E}(\cdot|G)$ commutes with multiplication by $G$-measurable variables [5th property](http://isfaserveur.univ-lyon1.fr/~stephane.loisel/prerequis_esp_cond.pdf)?
Comment: I used that: ${\rm E}[s^{X+Y}\mid Y=y]={\rm E}[s^{X+Y}1_{\{Y=y\}}]/P(Y=y)$ and on the set $\{Y=y\}$ we can replace $Y$ by $y$ and "pull out" $s^y$ since it is constant.
Comment: Can I assume that $s^Y$ is constant, because $Y$ has already happened? Sorry for dumb question.
Comment: Understood. Thank you.


SpEL does not parse simple ${spring.profiles.active} expression

Question: I am trying to learn SpEL, but it is showing behaviours that are not what is shown in the tutorials.
I have a method that calls a simple expression below, trying to get the value of ${spring.profiles.active}, but somehow the code keeps failing.
public void testSpel() {
    ExpressionParser parser = new SpelExpressionParser();
    Expression exp = parser.parseExpression("${spring.profiles.active}");
    String result = exp.getValue(String.class);
    log.info(result);
}

I have tried many variations, such as #{${spring.profiles.active}}, #{'${spring.profiles.active}'}, etc. However it always return an SpEL error:
For case of ${spring.profiles.active}:
Caused by: org.springframework.expression.spel.SpelParseException: EL1041E: After parsing a valid expression, there is still more data in the expression: 'lcurly({)'
at org.springframework.expression.spel.standard.InternalSpelExpressionParser.doParseExpression(InternalSpelExpressionParser.java:135) ~[spring-expression-5.1.5.RELEASE.jar:5.1.5.RELEASE]
at org.springframework.expression.spel.standard.SpelExpressionParser.doParseExpression(SpelExpressionParser.java:61) ~[spring-expression-5.1.5.RELEASE.jar:5.1.5.RELEASE]
at org.springframework.expression.spel.standard.SpelExpressionParser.doParseExpression(SpelExpressionParser.java:33) ~[spring-expression-5.1.5.RELEASE.jar:5.1.5.RELEASE]
at org.springframework.expression.common.TemplateAwareExpressionParser.parseExpression(TemplateAwareExpressionParser.java:52) ~[spring-expression-5.1.5.RELEASE.jar:5.1.5.RELEASE]
at org.springframework.expression.common.TemplateAwareExpressionParser.parseExpression(TemplateAwareExpressionParser.java:43) ~[spring-expression-5.1.5.RELEASE.jar:5.1.5.RELEASE]

For cases of #{${spring.profiles.active}}, #{'${spring.profiles.active}'}
Caused by: org.springframework.expression.spel.SpelParseException: Expression [#{'${spring.profiles.active}'}] @1: EL1043E: Unexpected token. Expected 'identifier' but was 'lcurly({)'
at org.springframework.expression.spel.standard.InternalSpelExpressionParser.internalException(InternalSpelExpressionParser.java:1044) ~[spring-expression-5.1.5.RELEASE.jar:5.1.5.RELEASE]
at org.springframework.expression.spel.standard.InternalSpelExpressionParser.eatToken(InternalSpelExpressionParser.java:926) ~[spring-expression-5.1.5.RELEASE.jar:5.1.5.RELEASE]
at org.springframework.expression.spel.standard.InternalSpelExpressionParser.maybeEatFunctionOrVar(InternalSpelExpressionParser.java:423) ~[spring-expression-5.1.5.RELEASE.jar:5.1.5.RELEASE]
at org.springframework.expression.spel.standard.InternalSpelExpressionParser.eatStartNode(InternalSpelExpressionParser.java:512) ~[spring-expression-5.1.5.RELEASE.jar:5.1.5.RELEASE]
at org.springframework.expression.spel.standard.InternalSpelExpressionParser.eatPrimaryExpression(InternalSpelExpressionParser.java:351) ~[spring-expression-5.1.5.RELEASE.jar:5.1.5.RELEASE]
at org.springframework.expression.spel.standard.InternalSpelExpressionParser.eatUnaryExpression(InternalSpelExpressionParser.java:345) ~[spring-expression-5.1.5.RELEASE.jar:5.1.5.RELEASE]
at org.springframework.expression.spel.standard.InternalSpelExpressionParser.eatPowerIncDecExpression(InternalSpelExpressionParser.java:304) ~[spring-expression-5.1.5.RELEASE.jar:5.1.5.RELEASE]
at org.springframework.expression.spel.standard.InternalSpelExpressionParser.eatProductExpression(InternalSpelExpressionParser.java:282) ~[spring-expression-5.1.5.RELEASE.jar:5.1.5.RELEASE]
at org.springframework.expression.spel.standard.InternalSpelExpressionParser.eatSumExpression(InternalSpelExpressionParser.java:264) ~[spring-expression-5.1.5.RELEASE.jar:5.1.5.RELEASE]
at org.springframework.expression.spel.standard.InternalSpelExpressionParser.eatRelationalExpression(InternalSpelExpressionParser.java:218) ~[spring-expression-5.1.5.RELEASE.jar:5.1.5.RELEASE]
at org.springframework.expression.spel.standard.InternalSpelExpressionParser.eatLogicalAndExpression(InternalSpelExpressionParser.java:205) ~[spring-expression-5.1.5.RELEASE.jar:5.1.5.RELEASE]
at org.springframework.expression.spel.standard.InternalSpelExpressionParser.eatLogicalOrExpression(InternalSpelExpressionParser.java:192) ~[spring-expression-5.1.5.RELEASE.jar:5.1.5.RELEASE]
at org.springframework.expression.spel.standard.InternalSpelExpressionParser.eatExpression(InternalSpelExpressionParser.java:153) ~[spring-expression-5.1.5.RELEASE.jar:5.1.5.RELEASE]
at org.springframework.expression.spel.standard.InternalSpelExpressionParser.doParseExpression(InternalSpelExpressionParser.java:131) ~[spring-expression-5.1.5.RELEASE.jar:5.1.5.RELEASE]
at org.springframework.expression.spel.standard.SpelExpressionParser.doParseExpression(SpelExpressionParser.java:61) ~[spring-expression-5.1.5.RELEASE.jar:5.1.5.RELEASE]
at org.springframework.expression.spel.standard.SpelExpressionParser.doParseExpression(SpelExpressionParser.java:33) ~[spring-expression-5.1.5.RELEASE.jar:5.1.5.RELEASE]
at org.springframework.expression.common.TemplateAwareExpressionParser.parseExpression(TemplateAwareExpressionParser.java:52) ~[spring-expression-5.1.5.RELEASE.jar:5.1.5.RELEASE]
at org.springframework.expression.common.TemplateAwareExpressionParser.parseExpression(TemplateAwareExpressionParser.java:43) ~[spring-expression-5.1.5.RELEASE.jar:5.1.5.RELEASE]

Comment: try this way `"#{spring.profiles.active}"`
Answer: You are mixing concerns.
SpEL doesn't resolve property placeholders, a ConfigurableBeanFactory resolves placeholders, SpEL evaluates Spel Expressions.
If you have a SpEL expression that contains a property placeholder, you need to resolve it first.
See here for an example.
private Object resolveExpression(String value) {
    return this.resolver.evaluate(resolve(value), this.expressionContext);
}

private String resolve(String value) {
    if (this.beanFactory != null && this.beanFactory instanceof ConfigurableBeanFactory) {
        return ((ConfigurableBeanFactory) this.beanFactory).resolveEmbeddedValue(value);
    }
    return value;
}

and you will need to quote '...' the property placeholder so SpEL treats it as a literal.


Problem - cylindrical coordinates

Question: A circular membrane in space is about the region $x^2 + y^2 \leqslant a^2$. The maximum $z$ component is $b$. Suppose that $(x, y, z)$ is a point on the membrane. Show that the corresponding point in cylindrical coordinates $(r, \theta, z)$ satisfies the conditions $ 0 \leqslant r \leqslant a, \space 0 \leqslant \theta \leqslant 2\pi, \mid z \mid \leqslant b$.
I understand everything but I just can't prove it...
Answer: The membrane is the following set
$$
M=\{(x,y,z)\;|\; x^2+y^2 \le a^2, -b \le z \le b \}
$$
In cylindrical coordinates, this yields
$$
M=\{(r,\theta,z)\;|\; 0 \le r \le a, 0 \le \theta \le 2\pi, -b \le z \le b \}
$$
So if a point belongs to $M$, the result follows.

Problem - cylindrical coordinates


Program using /etc/network/interfaces?

Question: The file is configured for a static ip ethernet connection. I do not have isc-dhcp-client nor network-manager. So which is the program that actually uses /etc/network/interfaces to make the connection ? Is it the Linux kernel directly ?
/etc/network/interfaces
<code>auto lo
iface lo inet loopback

iface eth0 inet static
    address 192.168.0.190
    netmask 255.255.255.0
    gateway 192.168.0.1
</code>
Comment: What is the *actual* problem you are trying to solve?
Answer: No, it isn't the kernel. /etc/network/interfaces is just a configuration file used by ifup and ifdown, which are scripts run as part of the startup sequence, usually by a service with the word "network" somewhere in it. If you google around for Ubuntu Startup Sequence, you'll find some decent descriptions about how startup works and from there you can figure out exactly what happens for the particular version you are running.
Comment: Once the network is up, which is the program that handles ethernet traffic ?
Comment: @WarrenJackson Once the Ethernet connection is up, and the interface is provisioned with IP information, it is the kernel that handles traffic through the sockets interface.
Answer: Not the kernel, the kernel doesn't read your filesystem.
There are some scripts (for ex /etc/init.d/networking), which process this file and via kernel API calls will raise the devices, configure IP's/route's etc.
Comment: Once the network is up, which is the program that handles ethernet traffic ?
Comment: Kernel handles.

Program using /etc/network/interfaces?


Alternative name for "incidence rate ratio"

Question: I'm using a negative binomial GLM to predict individual level scores on a psychometric test that ranges from 0-27 and presenting the coefficient "incidence rate ratios".
It seems a little strange to use the term "incidence rate ratio" when actually it is a psychometric score ratio. Should I still use the term "incidence rate ratio" in my manuscript for easy recognition/interpretation? If not, is there another, more generic term that is used or should I make up my own domain specific term (e.g. PGSI ratio where PGSI is the psychometric index I am modelling).
Comment: looks like the use comes from `Stata`, e.g. here http://www.ats.ucla.edu/stat/stata/faq/relative_risk.htm and here http://data.princeton.edu/wws509/stata/c4s1.html. But I'm hard pressed to see how the number of "children ever born" can be viewed as an incidence (prevalence - maybe).
Comment: I agree with @EpiGrad's answer. I am wondering where this term cropped up in your situation - did someone publish a paper on the test using this term?
Comment: @Michelle Yep, another paper in the field whose methods we are replicating. I have seen applied glm guides that present this estimate as an IRR regardless of field, which is where the confusion probably stems from.
Answer: I don't think its appropriate to use the term "incidence rate ratio" and your instincts are correct. You're reporting, as far as I can tell, neither an incident event, nor an actual rate, and rather than retain it because "that's what usually comes out of a negative binomial GLM" I think coming up with a new term will add clarity. I know if I hit "IRR" or the like and you weren't reporting incident cases, my first thought would be "The hell...?"
I vote for a domain-specific term, and a one line discussion of how its obtained, ala "obtained by the exponentiation of the beta1 in a negative binomial GLM..."


Como acrescentar mais valores em um matriz numpy?

Question: Estou fazendo um programa em python que usa matrizes, estou usando o numpy para fazê-las, mas está dando o seguinte problema: eu faço a matriz no intuito de guardar vários valores, mas ela guarda apenas um. Eu estava fazendo primeiro uma lista e dps convertendo para array usando np.array(), mas queria fazer de uma outra forma, será que teria como? Segue abaixo meu programa:
import numpy as np                          #
import math                                 #               importando bibliotecas para criação das matrizes e cálculos com
                                            #               números reais, respectivamente.

n1=n2=1                                     #               definindo constantes
pi = math.pi                                #
M = 200
                                            #
gama1 = 2/3                                                        #
b1 = math.sqrt(gama1) / (1+math.sqrt(1-gama1))                     #

gama2 = 2/3                                                        #   definindo os valores de b1 e b2                                               #
b2 = math.sqrt(gama2) / (1+math.sqrt(1-gama2))                     #

for l in range(1,M+1):
  for c in range(1,n1+1):
    w1 = np.array([b1*math.sqrt(1/(pi*(M+1)))*math.sin((l*c*pi)/(M+1))])  # adicionando valor na lista
  for c in range(1,n2+1):
    w2 = np.array([b2*math.sqrt(1/(pi*(M+1)))*math.sin((l*(n1+c)*pi)/(M+1))])  # adicionando valor na lista

no caso as matrizes são w1 e w2, e ao invés de aparecer uma matriz 1x200, mostra uma matrz 1x1
Comment: é pq a cada loop você define a variável novamente. Então no final você fica só com uma lista. Você pode usar `np.append` para apensar a lista a cada loop.
Comment: não entendi como usar essa função, eu usei no programa,mas não deu certo. Poderia dar um exemplo?
Comment: Eu respondi. Mas, por favor, note a quantidade de informação na sua pergunta e no seu código que não se relaciona com a questão. Procure deixar na pergunta apenas o essencial. Veja um guia aqui: https://pt.meta.stackoverflow.com/questions/1186/como-criar-um-exemplo-m%c3%adnimo-completo-e-verific%c3%a1vel
Answer: O problema do seu código é que, a cada vez que o loop passa, ele cria a linha novamente. Por isso você fica com apenas uma linha no final.
Uma matriz é, basicamente, uma lista de listas, então você pode usar o método append para apensar cada linha em cada iteração do loop. Exemplo:
import numpy as np

linha1=[1,0,0]
linha2=[0,1,0]
linha3=[0,0,1]
linhas=[linha1,linha2, linha3]
matriz=[]

for linha in linhas:
    matriz.append(linha)

A variável matriz aqui já é uma matriz, mas para ter acesso a metódos matemáticos para transformação e análise da matriz, recomendo usar np.matrix do numpy:
M=np.matrix(matriz)

print(M)

[[1 0 0]
 [0 1 0]
 [0 0 1]]

Por xemplo, você pode inverter a matriz, usando:
M.I

Que, nesse caso, retorna a própria matriz identidade, como se sabe.


How many type of solution will this integral has?

Question: Integrate $\int \frac{1}{x^3 \sqrt{x^2-1}} dx$
My attempt,
Let $x=\sec u $
I ended up with the answer $\frac{1}{2} (\frac{\sqrt {x^2} \sqrt{x^{2}-1}}{x^3}+\sec^{-1} x)+c$
Comment: Any two solutions differ by a constant.  A candidate answer may be checked by differentiation.  Using that method, you can see that your answer is wrong.
Comment: Sorry for the typo. Now should be okay
Comment: @GEdgar I differentiated the solution given in the problem, and I am finding that it works... The derivative of $ sec^{-1}(x) $ is $ \frac{1}{x\sqrt{x^2-1}} $ and the derivative of $ \frac{\sqrt{x^2-1}}{x^2} $ is $ \frac{2-x^2}{x^3\sqrt{x^2 - 1}} $. Thus, the derivative of $ \frac{\sqrt{x^2-1}}{x^2} + sec^{-1}(x) $ is $  \frac{2-x^2}{x^3\sqrt{x^2 - 1}} + \frac{1}{x\sqrt{x^2-1}} = \frac{x^2 + 2 - x ^2}{x^3\sqrt{x^2-1}} = \frac{2}{x^3\sqrt{x^2-1}} $.
Answer: It looks like you have the right answer. Since this is an indefinite integral, there are infinitely many possible solutions (i.e. $ C $ is a constant that can take any value).
I would also use the same substitution as you, i.e. $ x = sec(\theta) \rightarrow dx = sec(\theta) tan(\theta) d\theta $.
$$ \int \frac{1}{x^3\sqrt{x^2-1}} dx = \int \frac{1}{sec^3(\theta)} \times \frac{1}{\sqrt{sec^2(\theta) - 1}} \times sec(\theta) tan(\theta) d\theta $$
Since $ sec^2(\theta) - 1 = tan^2(\theta) $, we get:
$$ \int \frac{1}{sec^3(\theta)} \times \frac{1}{\sqrt{tan^2(\theta)}} \times sec(\theta) tan(\theta) d\theta = \int \frac{1}{sec^2(\theta)} d\theta = \int cos^2(\theta) d\theta $$
Since $ cos(2\theta) = 2cos^2(\theta) - 1 \rightarrow cos^2(\theta) = \frac{1}{2} (1 + cos(2\theta)) $, we get:
$$ \int cos^2(\theta) d\theta  = \int \frac{1}{2} (1 + cos(2\theta)) d\theta = \frac{1}{2} \big[ \theta + \frac{1}{2}sin(2\theta) \big] + C = \frac{1}{2} \big[ \theta + sin(\theta)cos(\theta) \big] + C $$
Finally, you want to re-write your answer in terms of $x$. To do this, recall that $ sec(\theta) = x $, so $ \theta = sec^{-1}(x)$. To find expressions for $ sin(\theta) $ and $ cos(\theta) $ in terms of $ x $, it helps to draw out a triangle, i.e.

We see that $ sin(\theta) = \frac{Opposite}{Hypothenuse} = \frac{\sqrt{x^2 - 1}}{x} $ and that $ cos(\theta) = \frac{Adjacent}{Hypothenuse} = \frac{1}{x} $. Putting this all together, we get:
$$ \int \frac{1}{x^3\sqrt{x^2-1}} dx = \frac{1}{2} \big[ \theta + sin(\theta)cos(\theta) \big] + C = \frac{1}{2} \big[ sec^{-1}(x) + \frac{\sqrt{x^2-1}}{x^2} \big] + C $$
Answer: Hint:
Let $\sqrt{x^2-1}=u\implies x^2=u^2+1$
$$\int\dfrac{x\ dx}{x^4\sqrt{x^2-1}}=\int\dfrac1{2u}\cdot\dfrac{2u}{(1+u^2)^2}$$
Now integrate by parts
Comment: Can you address the question in the title ?
Answer: Let $x=cosh(u)$ and $dx=sinh(u)du$
Then
$$\int \frac{1}{x^3 \sqrt{x^2-1}} dx  =\int \frac{sinh(u)}{cosh^3(u)sinh(u)}du= \int sech^3(u)du$$
Now you can use the reduction formula for  $\int sech^m(x)dx$


How to create a custom shape that varies in width

Question: In this mockup I have created, I am trying to create a custom arrow shape below each button whenever the mouse hovers over a button on the main navigation. However, the width will vary for each button and I need it to look the same. How would I accomplish this in CSS?
Click Here to see what I am trying to accomplish under 'I'm New' link.
So far, this is what I have in style.css:
.main_nav_inside {
  margin: 0 auto;
  margin-top: -130px;
  position: relative;
  z-index: 1;
}

.main_nav_inside ul {
  list-style-type: none;
  margin: 0;
  float: right;
}

.main_nav_inside ul li {
  display: inline-block;
  float: left;
  font-family: 'Roboto', sans-serif;
  font-size: 20px;
  font-weight: 500;
  text-transform: uppercase;

}

.main_nav_inside ul li a {
  display: block;
  top: 0;
  padding-left: 20px;
  padding-right: 20px;
  padding-top: 50px;
  height: 130px;
  color: #ffffff;
}

.main_nav_inside ul li a:hover {
  padding-bottom: 5px;
  width: 100%;
  background-color: #2F2F2F;
}

.main_nav_inside ul li a:hover:before {
  padding-bottom: 20px;
  width: calc(2% + 30px);
  background-color: #000000;
  content: '';
  position: absolute;
  margin: 0 auto;
  left: inherit;
  margin-left: -20px;
  margin-right: 0;
  top: 120px;
  height: 20px;
  background: #000000;
  -webkit-transform: skew(0deg, 0deg);
  -moz-transform: skew(0deg, -6deg);
  -ms-transform: skew(0deg, -6deg);
  -o-transform: skew(0deg, -6deg);
  transform: skew(0deg, 15deg);
  z-index: -1;
}
.main_nav_inside ul li a:hover:after {
  padding-bottom: 20px;
  width: calc(10% / 2);
  background-color: #000000;
  content: '';
  position: absolute;
  margin: 0 auto;
  right: inherit;
  margin-left: -35px;
  margin-right: 0;
  top: 120px;
  height: 20px;
  background: #000000;
  -webkit-transform: skew(0deg, 0deg);
  -moz-transform: skew(0deg, -6deg);
  -ms-transform: skew(0deg, -6deg);
  -o-transform: skew(0deg, -6deg);
  transform: skew(0deg, -15deg);
  z-index: -1;
}

Here is the HTML for this page as well:

  {% set parents = craft.entries.section('menu').level(1).limit(5) %}

        {% nav parent in parents %}

          {{ parent.getLink() }}
            {% ifchildren %}

{% children %}

            {% endifchildren %}

          {% endnav %}

This website is being built using Craft CMS..not that this matters.
Comment: Welcome to Stack Overflow. Post your HTML as well.
Comment: Please read [How to create a Minimal, Complete, and Verifiable example](https://stackoverflow.com/help/mcve)
Comment: Also, can you show the rest of your CSS, including how you have .main_nav_inside defined? Thanks!
Comment: If you want the arrow to vary in width, do you want to keep the angle the same (e.g. wider element means the tip of the arrow will be further down), or you want to keep the height of the arrow constant (e.g. wider element means a shallower arrow angle)?
Comment: Terry, yes. it would basically stay at the same height. Roughly 30px.
Comment: Anyone have any suggestions? I possibly was thinking this should be done in jQuery to work with the CSS for this header in particular.
Answer: I was able to create the shape using border-top, border-left and border-right. But the bottom tip seems to stay flat and doesn't have a point to it. No matter what numbers you adjust in the border width of top, left or right the tip will stay flat.
.main_nav_inside ul li a:hover:after {
    top: 100%;
    left: 0;
    right: 0;
    content: " ";
    position: absolute;
    border-top: 20px solid #000000;
    border-left: 50px solid rgba(0, 0, 0, 0);
    border-right: 50px solid rgba(0, 0, 0, 0);
}


Estimating the Parameters for $y=\beta_1 e^{\beta_2 x}+\beta_3 z+\epsilon$

Question: I have the model
$$y=\beta_1 e^{\beta_2 x}+\beta_3 z+\epsilon$$
where $z$ is an indicator variable. I need to obtain estimates from linear regression to get initial values for the parameters. Then I can do an iterative search to find the best values for each parameter. However, I am having trouble doing this.
For the model
$$y=\beta_1 e^{\beta_2 x}+\epsilon$$
I can simply take the natural log of both sides and run the regression model
$$log(y)=log(\beta_1)+\beta_2 x+\epsilon$$
to get estimates of $\beta_1$ and $\beta_2$ but
$$y=\beta_1 e^{\beta_2 x}+\beta_3 z+\epsilon$$
doesn't appear to be intrinsically linear.
Any suggestions would be greatly appreciated.
Edit:
The data is as follows
df <- read.table(textConnection(
'x y z log_y
0.5 0.68 0  -0.38566
0.5 1.58 1  0.45742
1.0 0.45 0  -0.79851
1.0 2.66 1  0.97833
2.0 2.50 0  0.91629
2.0 2.04 1  0.71295
4.0 6.19 0  1.82294
4.0 7.85 1  2.06051
8.0 56.10 0 4.02714
8.0 54.20 1 3.99268
9.0 89.80 0 4.49758
9.0 90.20 1 4.50203
10.0 147.70 0 4.99518
10.0 146.30 1 4.98566'), header = TRUE)

When the model is just $y=\beta_1 e^{\beta_2 x}$ I get parameters estimates of 0.753 and 0.533 respectively after transforming the data to be linear. In SAS, I used these as the initial values for the new model and let $\beta_3=0$, arbitrarily. Using the Gaussian-Newton method, I got that the convergence criterion was met so it may be a valid approach. The coefficients I obtained in SAS are as follows:
Comment: Why do you need to creat initial values by linear regression, why don't you use a reasonable values on the iterative nonlinear programming optimization?
Comment: Your use of logarithms is incorrect: $\log (a+b) \neq \log a + \log b$.
Comment: @Remy, (1) is the example data the real data of your problem or did you create it for this question? (2) what is your question, you ask for suggestion, but you do not explain your problem, what is wrong with your current solution? (3) Could you add the 'self-study' tag if this is a homework question.
Comment: That's how I was taught to do it. For the case where we have $log(y)=log(\beta_1)+\beta_2 x$ I got starting values of $.753$ and $.533$. I was thinking maybe to adapt for this model, I could use those same starting values and set $\beta_3 = 0$. SAS shows that this meets the convergence criterion so it may be a valid approach.
Comment: I know that. I'm giving an example of a different model $y=\beta_1 e^{\beta_2 x}$ which is intrinsically linear.
Comment: Please see https://stats.stackexchange.com/questions/160552 for a general approach that will work well here.  A search for [nls](https://stats.stackexchange.com/search?q=nls+exp+score%3A1+closed%3Ano) might prove fruitful.
Comment: @whuber I read through your answer but am having trouble adapting to my current situation where we have $\beta_3 z$ instead of just $\beta_3$. Would it be okay if I included my data and SAS code to my original post? I could do attempt to do it in R if that'd be preferable.
Comment: Data alone ought to be fine, because from those we can determine the quantities that matter, such as the range of $x,$ the range of $y,$ likely values of the parameters, and so on.  For instance, if you expect all the $\beta_2 x$ to be small, then $$y \approx \beta_1 + (\beta_1 \beta_2) x+ \beta_3 z + \epsilon$$ linearizes the problem.
Comment: @whuber I have edited my post.
Comment: Thank you.  A very special structure to your data is apparent: you have a set of repeated measurements for each $x$ in which only $z$ varies.  You can obtain the estimate of $\beta_3$ from this alone--it's the arithmetic mean of the differences--thereby reducing the problem to solving $y-\hat\beta_3 z = \beta_1\exp(\beta_2 x) + \epsilon,$ which is solved in many threads here (including the one I linked to).
Comment: Using your well explained answer on the link you provided, could I replace $c.0$ with the mean of the differences? And for calculating the mean of the differences, would this be a valid line of code: `mean(df$y[df$z==1]-df$y[df$z==0])
[1] 0.2014286`
Comment: So using SAS, I could create a new variable which is $log(y)-0.2014$
Comment: Rather, create a new variable which is $log(y-0.2014)$ and have that as the response?
Comment: It is the data I am given and yes, this is homework. I'm looking for verification that linearizing the model using $log(y-0.2014)=log(\beta_1)+\beta_2 x$ is valid for getting initial values.
Comment: What is the role of $\beta_3$ and $z $ what do they represent and why do you believe they should be in the model?
Comment: Because when $z$ 'occurs' we would expect $y$ to increase. Are you asking for what the variables actually are?
Comment: Yes, what is z and why is it important. Why do you believe that it needs to be incorporated into the model instead of either ignoring it (since its effect is negligible) or modelling the mean (since you have values z=1 and z=0 in pairs).
Comment: And what is your 'problem/question' since you already obtained coefficients with SAS via a nonlinear model.
Comment: Well isn't it possible that I obtained coefficients that aren't ideal by using an invalid procedure to get initial values?
Comment: I'm not given what $x$, $y$, and $z$ represent.
Comment: @Remy, so your question is about the *validity* of the method?
Comment: @MartijnWeterings Correct
Answer: I haven't read the whole comment thread, but this seems to work. I get the following estimates for the betas and $\sigma^2$: $1.1021399, 0.4884926 1.1266743, \exp(0.2739612)$. Notice that there are no linear approximations required (in the sense that you don't need to estimate a substitute model), and no derivatives required like there are in the Gaussian-Newton method.
df <- read.table(textConnection(
  'x y z log_y
0.5 0.68 0  -0.38566
0.5 1.58 1  0.45742
1.0 0.45 0  -0.79851
1.0 2.66 1  0.97833
2.0 2.50 0  0.91629
2.0 2.04 1  0.71295
4.0 6.19 0  1.82294
4.0 7.85 1  2.06051
8.0 56.10 0 4.02714
8.0 54.20 1 3.99268
9.0 89.80 0 4.49758
9.0 90.20 1 4.50203
10.0 147.70 0 4.99518
10.0 146.30 1 4.98566'), header = TRUE)

neg_log_like  <- function(params){
  beta1 <- params[1]; beta2 <- params[2]; beta3 <- params[3]; logSigmaSq <- params[4]
  meanVec <- beta1 * exp(beta2*df$x) + beta3*df$z
  sds <- rep(exp(logSigmaSq/2), length(meanVec))
  -sum(dnorm(df$y, meanVec, sds, log=T))
}

init_guess <- c(1,1,1,0.0)
optim(par = init_guess,
      fn = neg_log_like,
      method = "Nelder-Mead")

Edit: yes, thanks for pointing out the starting value issue. From the question it sounded more like a "how do I do this at all" issue. The log-likelihood is pretty flat in beta3, so you might consider taking this into account. Here's a plot of the profile negative log-likelihood using the other optimized values I obtained (not beta 3) using the following code
beta3s <- seq(-1, 2, .01)
profile_neg_log_like <- sapply(beta3s, function(beta3) neg_log_like(c(1.1021399, 0.4884926, beta3, 0.2739612)))
plot(beta3s, profile_neg_log_like)

$.2$ looks about right.
Also, notice that if you start off with $\beta_3$ at $0$, and scale up the $\beta_3$ values, you even get a negative estimate:
init_guess <- c(1,1,0,0.0)
res <- optim(par = init_guess, fn = neg_log_like,
             method = "Nelder-Mead", control = list(parscale=c(1, 1, 100, 1)))
cat(res$par)
#1.161925 0.4836862 -0.7783124 0.2670566

Comment: It's the right idea, but you have to be careful not to take logs of negative values.  Here's some code based on that other thread. It converges in 6 iterations and gives you p-values for all parameters, too: `b.3 <- mean(subset(df, z==1)$y) - mean(subset(df, z==0)$y);
c.0 <- 0.5 * min(df$y - df$z*b.3);
model.0 <- lm(log(y - c.0 - z*b.3) ~ x, df);
b.1 <- exp(coef(model.0)["(Intercept)"]);
b.2 <- coef(model.0)["x"];
start <- list(b.1=b.1, b.2=b.2, b.3=b.3);
model <- nls(y ~ b.1 * exp(b.2 * x) + b.3*z, data = df, start = start);
summary(model)`
Comment: Interesting that your $\beta_1$ and $\beta_2$ are very close to mine but $\beta_3$ is significantly different.
Comment: If by "linear approximation" you're referring to my comments or answers on another thread, then please be aware that the point is to find a good starting value for an iterative solution.  You avoided this only by starting with an arbitrary guess of the solution--and you could do substantially better.  Most black-box nonlinear optimizers require some reasonable starting value in order to work at all.  Try $(1,1,0,0)$ for instance :-).  @Remy as I indicated in a comment to your question, estimate $\beta_3$ as the mean difference in responses between the two groups.  You'll get about 0.2.
Comment: @whuber Right, that is what I have used as my initial value for $\beta_3$. But would I be correct in estimating $\beta_1$ and $\beta_2$ by modeling $\text{log}(y-0.2014)=\text{log}(\beta_1)+\beta_2 x$
Answer: This needs to be fit like a non-linear regression. You can do it with a ML estimate as proposed by Taylor, or you can use Bayesian MCMC sampling. My estimate using MCMC sampling in JAGS is very similar to your results:
            Mean          SD   P.value       2.5%     97.5% Time-series SE     psrf  psrf CI
b[1]   1.0700276 0.069644097 0.000 ***  0.9413769 1.2183012   0.0029073561 1.006867 1.024380
b[2]   0.4926133 0.006674661 0.000 ***  0.4790468 0.5055502   0.0002762362 1.006998 1.024800
b[3]  -0.1291385 0.490887669 0.388     -1.1131594 0.8441626   0.0080573350 1.001177 1.004308
sigma  1.0310585 0.264173711 0.000 ***  0.6631381 1.6864203   0.0035488911 1.000404 1.000565

The code is here:
df <- read.table(textConnection(
'x y z log_y
0.5 0.68 0  -0.38566
0.5 1.58 1  0.45742
1.0 0.45 0  -0.79851
1.0 2.66 1  0.97833
2.0 2.50 0  0.91629
2.0 2.04 1  0.71295
4.0 6.19 0  1.82294
4.0 7.85 1  2.06051
8.0 56.10 0 4.02714
8.0 54.20 1 3.99268
9.0 89.80 0 4.49758
9.0 90.20 1 4.50203
10.0 147.70 0 4.99518
10.0 146.30 1 4.98566'), header = TRUE)

require(runjags)

do_DIC <- FALSE
fast_model_run <- FALSE
jags_parallel <- FALSE

##########

repeat {

model_file <- paste0(tempdir(), "/tmp_bugs_model.txt")
sink(model_file)
cat("model {

sigma ~ dunif(0, 10)
b[1] ~ dnorm(0, 0.01)
b[2] ~ dnorm(0, 0.01)
b[3] ~ dnorm(0, 0.01)

for (i in 1:n) {
    y_exp[i] <- b[1]*exp(b[2]*x[i]) + b[3]*z[i]
    y[i] ~ dnorm(y_exp[i], 1/sigma^2)
}

}
")
sink()

win.data <- c(df, n = nrow(df))

inits <- function () {
list(
    b = rnorm(3, 0, 1)
)
}

params = c("b", "sigma")
if (do_DIC)
    params <- c(params, "dic", "ped")

#
if (fast_model_run) { # pro porovnavani casu (vic chainu -> stabilnejsi)
ni <- 20000
nt <- 1
nb <- 10000
nc <- 3
adapt <- 0
} else if (1) { # FINALNI pro paper
# ni: 1000 -> .. sec
ni <- 20000
nt <- 10
nb <- 10000
nc <- 3
adapt <- 5000
} else { # klasicky run
ni <- 1000
nt <- 1
nb <- 500
nc <- 3
adapt <- 0
}

# runjags package

#if (!exists("model_info"))
    model_info <- list()

start_time <- Sys.time()
print(start_time)
t1 <- proc.time()
outRJ <- run.jags(model_file, params, win.data, nc, inits,
    method = ifelse(jags_parallel, "rjparallel", runjags.getOption("method")),
    keep.jags.files = FALSE,
      nb * nt, ni - nb, thin = nt, summarise=FALSE, adapt = adapt, modules = "glm",
    silent.jags = !isatty(stdout())) # adapt = 0
        # pri presmerovani do filu nechceme progress bar
t2 <- proc.time()
print(t2 - t1)
end_time <- Sys.time()
print(end_time)

break

}

par(ask = TRUE)
plot(outRJ$mcmc)
s1 <- mcmcsum(outRJ$mcmc)


How do I truncate strings?

Question: For example, I need to truncate the following text.

Drupal is free, flexible, robust and constantly being improved by hundreds of thousands of passionate people from all over the world. Join us!

I have used drupal_substr(), but the result may be "Drupal is free, flexi."
How can I avoid to truncate a word?
Answer: You need to use truncate_utf8() using $wordsafe = TRUE;

$wordsafe Flag to truncate at last space within the upper limit. Defaults to FALSE.

How do I truncate strings?


how display module in popup modal window in joomla 2.5

Question: I have a newsletter subscription module.I want display it in popup window automatically(when user view a page,without any click).
Comment: What have you tried so far? Here at Stackoverflow, we don't do your work for you, we expect you to have atleast tried something yourself.
Answer: Use a modal window. You can make a new custom html module and load javascript to do it.
This is just one solution and probably not the best.


MYSQL insert internal work

Question: Assume I have the following table
create table MyTable
(
    id int unsigned auto_increment primary key,
    data varchar(4) not null
);

Can anybody explain to me the exact steps that MYSQL server internally executes when I insert an entry from a client like this
insert into MyTable (data) values ("ABCD");

For example:
(parse query - check privileges - ........ - etc)
I want to know the exact work that MYSQL server do from the moment I send the query from the client to the moment when the data is stored successfully and every thing is okay.
Edit:
I want to know the steps in the two storage engines : MYISAM - InnoDB
Thanks
Comment: If you want to know this because of pure interest, why don't you read the source code? If there's another reason behind this - why don't you explain the real problem you're having?
Answer: What you are asking for is the source code.
It's here https://github.com/mysql/mysql-server
After some clarifications, here is a (very minimal) idea of what MySQL (or another database) must do beyond storing a value to a file.
A (MySQL) database has to have ACID transactions, and so must make many strong guarantees that a file does not.
It must ensure:

Atomicity
Consistency
Isolation
Durability

Further, in most practical cases it must maintain at least one index, which a file does not.
ACID and index maintenance are the work that is done which takes time beyond appending to a flat file.
Comment: Ah, so you don't want what you asked for, which is "the exact work that MYSQL server do from the moment I send the query from the client to the moment when the data is stored successfully".
Comment: @egyptian_M totally fine. And what you have just asked me is a completely different question and adds important details to what you asked before. A MySQL database has to have ACID transactions, and so must make many strong guarantees that a file does not. Further, it must maintain an index, which file does not. That work takes time. (https://en.wikipedia.org/wiki/ACID)
Comment: @johnsamir - basically you want someone to do work for you for free, is that correct?
Comment: I just want to figure out why inserting data in MYSQL DB takes a relatively long time than inserting this data in a regular binary file . Sorry for incompleteness in my question.
Comment: Okay Thanks , This is a helpful start
Comment: @egyptian_M: Mainly it ensures the data is written to disk (flushed) at every operation, while disk operations will use memory mapped I/O. You can allow a database to do this as well using ```innodb_flush_log_at_trx_commit=0```. Source: http://tqdev.com/2016-trading-durability-for-performance-without-nosql

MYSQL insert internal work


angularjs-how to implement click in angular

Question: I am a newbie in angularjs.
I was stuck on a code and wanted some help.
I am having a controller called watchlist controller in which I am getting the data which is to be displayed in the watchlist.
However I want to display the data only once the watchlist tab is clicked.
This is the Html code :-

      <button class='btn' id="watchList"  ng-click="fetchUserWatchlist()" watchlist-popover ng-controller="WatchlistController">

        My Watchlist

      </button>

My controller(watchlist):-
$scope.fetchUserWatchlist = function(pageno,callback){
        $scope.isLoading = true;
        $rootScope.isrequest = true;
        userAPI.myWatchlist({userid:$rootScope.getUser().userid,pageno:pageno}, function(r) {
            if (_.isNull(r.watchlistdata)) {
                if(typeof callback == 'function'){
                    callback();
                }
                if(pageno == 1){
                    $scope.watchlist = [];
                    $scope.watchlistCount = 0;
                }
                if (!$rootScope.apiCalled && pageno == 1){
                    if(!_.isUndefined($rootScope.watchlistClicked) && $rootScope.watchlistClicked){
                        $rootScope.$broadcast("watchlist::click");
                        imageLoadingIndicator();
                    }
                    $rootScope.apiCalled = true;
                }

                return false;
            }
            if (!_.isUndefined(r.watchlistdata.watchlist)){
                var rawData = [];
                var tempWatchlist = $scope.watchlist;

                if (_.isArray(r.watchlistdata.watchlist))
                    rawData = r.watchlistdata.watchlist;
                else
                    rawData = [r.watchlistdata.watchlist];

                if (pageno == 1) {
                    $scope.watchlistCount = parseInt(rawData[0].totalcount);
                }

                if ($scope.watchlist.length == 0 || ($scope.watchlist.length > 0 && pageno == 1))
                    $scope.watchlist = rawData;
                else
                    _.each(sortByDate(rawData),function(item){
                        if (! _.some(tempWatchlist,function(existingItem){ return existingItem.programmeid == item.programmeid; }))
                        {
                            $scope.watchlist.push(item);
                        }

                    });
                $scope.watchlistPage += 1;

                $timeout(function(){

                    if (!$rootScope.apiCalled && pageno == 1){
                        if(!_.isUndefined($rootScope.watchlistClicked) && $rootScope.watchlistClicked){
                            $rootScope.$broadcast("watchlist::click");
                            imageLoadingIndicator();
                        }
                        $rootScope.apiCalled = true;
                    }

                },1);
                $rootScope.isrequest = false;
                if(typeof callback == 'function'){
                    callback();
                }
            }else
                $rootScope.end = true;
        });

    };

So basically I want to implement ng-click on the controller but here in the above scenario it does not help..The data is called before the button is clicked.
Please help me with this
Comment: What is `watchlist-popover`? Please provide Plunker or something to get a proper answer.
Comment: Directly linked from the main AngularJs website the free codeschool course [**Learn to build an application using Angular.js**](http://campus.codeschool.com/courses/shaping-up-with-angular-js/) It's a great way to get into the basics of AngularJs - Hope this helps.
Answer: ng-click will work using the scope:
ng-click="executeThis()"

will look in the $scope for a variable named 'executeThis'. F.e.:
$scope.executeThis = function(){
    // Do stuff you want
};

So when you click the element that has this ng-click attribute, the executeThis function on the scope will be executed. In this function you should do whatever you want to do. To display something when you click it, you could use the function to set a variable on the scope to true and then use ng-show to display what you want to display.
HTML:

someDiv

JS inside controller:
$scope.varX = false;

So whenever you set this variable to true, your element should be shown.
However, I do suggest following some tutorials since I suspect you don't yet grasp how angular works.. Understanding how the fundamentals of angular work is definitely necessary if you want to develop an app.
Comment: @Tsasken..I have tried to implement ng-click as you said.But it does not help me.Please see my updated code
Comment: Ok, so right now you have "$scope.isLoading = true;" that says you are still loading data. Make sure the variable is initiated as true when the controller is initiated. Then use 'My Watchlist' to hide and show the watchlist..
Comment: Whenever you set isLoading to false, the watchlist should show.. As long as I understood correctly that the watchlist is in the span element..
Comment: @Tsasken..I tried what you said..But the span/button is getting hidden..actually want to display data on click
Comment: Oh, I think I was wrong before, the 'ng-hide="isLoading"' attribute should be on the element containing the data. Not on the span / button.. If it's still not working I suggest you try to create a jsfiddle / plnkr for further troubleshooting..
Comment: @tsasken..Now issue is that the data from the controller is called before the (ng-click)html is loaded..I want to avoid it and call the data on on the click event,It will make my page load faster.
How do I stop a controller from loading data before a click event is fired
Answer: try
<button class='btn' id="watchList" ng-click="myClickFunction()"  watchlist-popover ng-controller="WatchlistController">

The best way to learn (IMHO) is documentation :-)
Comment: @i100..I tried the above code ..But its not working.I want to display the data only when I click on the watchlist button but in my case it is loading the data before click
Comment: I guess your  ng-controller="WatchlistController" should be attached on the parent div not on the button. It does not make sense for me to bind controler with a button... But I might misunderstand the logic... Look here: https://docs.angularjs.org/api/ng/directive/ngController


Pegar os valor que foram alterado no banco e parear com os novos valores

Question: Estou com a seguinte questão. Ao fazer alteração em um determinado cadastro, preciso manter as informações antigas em algum lugar, primeiramente pensei em um esquema de log, mas chegou a hora de pegar os valores antigos, não consegui identificar quais foram os valores que foram alterados. Qual seria uma forma de fazer o seguinte:
TELEFONE_ANTIGO -> NOVO_TELEFONE
EMAIL_ANTIGO -> NOVO_EMAIL

Apenas quando o valor for alterado. Trabalhando com PHP.
Answer: Amigo, acredito que a melhor forma de fazer isso é pelo próprio BD utilizando triggers.
Por exemplo, vamos supor que você a tabela contato abaixo:
|   CONTATO  |
| id_contato |
|  telefone  |
|   email    |

Então você precisa criar uma outra tabela igual a CONTATO para guardar o histórico:
|   CONTATO_HIST  |
| id_contato_HIST |
| id_contato      |
| telefone        |
| email           |

E agora criar um trigger BEFORE UPDATE na tabela contato, assim:
CREATE TRIGGER contato_before_update
BEFORE UPDATE
   ON contato FOR EACH ROW
BEGIN

    INSERT INTO contato_hist(id_contato,telefone,email)
     SELECT * FROM contato where id_contato = NEW.id_contato;

END

Desse forma, antes que aconteça um update na tabela CONTATO vai rodar o código da sua trigger, que esta inserindo na tabela CONTATO_HIST tudo que tem na tabela CONTATO com o mesmo id_contato que você esta fazendo o update (NEW.id_contato).   Se quiser pode adicionar mais campos na sua tabela CONTATO_HIST e gravar o usuário que fez o update, a data, hora, o que você quiser.
Dessa forma esse histórico fica transparente para sua aplicação, não precisa mudar nada no PHP.
Coloquei um exemplo no SQLFIDDLE
Comment: Depois de 1 ano, acredite, isso solucionou o problema hoje. Acabou que não seguimos com essa ideia, mas o cliente acabou voltando nessa tecla hoje, e de lá para cá me familiarizei bem com os `TRIGGER` o que vai facilitar muito essa implementação. Obrigado.


Beethoven Piano Sonata no. 1 in F minor: What are the first 2 chords of the transition?

Question: So, I'm in the middle of orchestrating Beethoven's Piano Sonata no. 1 in F minor and I'm at the transition in the recapitulation of the first movement. In order to fill in that bass register that Beethoven didn't write(because it would be absurd not to if arranging the sonata for an orchestra), I need to know what the harmonies are, otherwise, it's going to sound horribly wrong. However, the first 2 chords, especially the first one is confusing me. I don't know what to call it, I don't know what that harmony on the Gb is supposed to be. With the one in the bar afterwards, I at least know that it's some sort of secondary dominant chord because it spells a diminished triad on C. Here's the passage in question:

And here's my attempt at a harmonic analysis of it:

Already, I know I'm probably wrong on at least the Gb chord and maybe the diminished chord as well.
My intuition is telling me that the diminished chord is probably a secondary vii°7 chord. Specifically, vii°7/iv. Now, I have seen Beethoven use this exact harmonic relation in his other bookend sonata, Piano Sonata no. 32 in C minor Op. 111, which uses 3 different diminished seventh chords in the first movement. So I know it could be vii°7/iv. And I know that the chord after it is V7/iv.
A move from vii°7 to V7 is quite common, as is the other way around, V7 to vii°7, as they both have the same function and have 3 common tones. However, you don't usually see chords like vii°7/iv or especially vii°7/vi. Usually when you see those kinds of harmonies, the composer has modulated and so it's better to view it in terms of the new key. Beethoven is not modulating here, he's staying in F minor. And there's another thing that's making me second guess my vii°7/iv analysis. The root of said chord isn't present at all, there is no A natural in the diminished chord.
That's the less confusing bit. The Gb right before the diminished chord, I just don't know how to analyze it. It looks on the page like maybe a shell voicing of a major seventh chord? But a major seventh in a minor key? On the Neopolitan of said minor key? That seems strange and like it's probably incorrect.
So, what are the first 2 chords of the transition after the F minor arpeggio? Is it in fact bIIM7 and vii°7/iv? Or is the diminished chord not a vii°7/iv because it lacks the root? Or is the GbM7 not really a GbM7?
Answer: Both measures are Eb minor, with the "bass" F being a suspension from the previous measure, resolving in the next. This is consistent with the rest of the analysis: iv/iv leading to V7/iv.
The C that otherwise appears to be part of a rootless diminished chord is not part of the chord at all. Rather, it's an anticipation of the following measure, where it is part of the chord.
Consider that Beethoven follows a similar harmonic plan (using ii/iv rather than iv/iv) at the same transitional point in the opening of the piece, in measures 11 – 14. Measure 11 initially appears to be an F minor chord – the i chord — in second inversion. However, it's actually Bbm7, with the C being a suspension that resolves in measure 12.
Beethoven in these bars in on his way to Eb major. Relative to that key, bars 11 and 12 are ii7/IV, followed by V7/IV and then IV.

(SOURCE: IMSLP, Schenker edition)
Comment: Beethoven in Bars 11-14 is on his way to V of A flat major, not (I of) E flat major. While he only conclusively lands on I of A flat major on Bar 22, that is preceded by a fairly lengthy dominant preparation, rather like its equivalent in the recapitulation, where I similarly cannot support Beethoven moving to C major and must support him moving to V of F minor instead. I'll note that this 1st movement of Beethoven's Piano Sonata No. 1 is in fairly conservative sonata-allegro form, including sticking to home key-relative major in the exposition and home key-home key in the recapitulation.
Comment: @Dekkadeci That's true. Since OP already recognized the arrival on V, I felt it simplified the analytical language to treat it as though we were moving toward the "key of V", which, locally, we are.


Can a basis for an $n$ dimensional vector space consist of $n+1$ basis vectors?

Question: Can a basis for an $n$ dimensional vector space consist of $n+1$ basis vectors?
I read that the set $\{x^3-2,x+x^2,1,x\}$ is a basis for the vector space polynomials of degree $3$ but I'm not exactly convinced.
Comment: Isn't dimension defined to be the cardinality of any basis?
Comment: The polynomials with degree at most $3$ form a space with dimension $4$
Comment: It's a theorem, that if a vector space has a basis of $n$ vectors, then any basis of that space must also have $n$ vectors. This allows the unambiguous definition of $n$ as the "dimension" of that space.
Comment: Polynomials of degree $n$ are *not* a vector space. Only polynomials of degree $\le n$.
Answer: The cardinality of a basis is always equal to the dimension of the space, so a basis of a $n-$dimensional space has exactly $n$ elements.
Note that the space of polynomial of degree $\leq 3$ is a space of dimension $4$ (its canonical basis is $(1, X, X^2, X^3)$).
Answer: A set of $\ n+1\ $ vectors in a $\ n\ $-dimensional vector space is always linear dependent, hence cannot form a base.
Answer: By definiton, an $n$ dimensional vector space $V$ means that any basis of $V$ has cardinality $n$. So, an $n$-dimensional vector space cannot have a basis of cardinality $n+1$.
In your case, the vector space you are looking at has a basis of cardinality $4$ ,i.e., $\{1,x,x^2,x^3\}$ and so all the bases of the vector space of all polynomials of degree $\leq 3$ have cardinality $4$.
To convince you that the set $\{x^{3}-2,x+x^{2},1,x\}$ is indeed a basis, it is sufficient to check that the set is linearly independent.
To show this, let $a_{0}(x^{3}-2)+a_{1}(x+x^{2})+a_{2}(1)+a_{3}x=0$ and prove that the scalars $a_{0}=a_{1}=a_{2}=a_{3}=0$.
PS: I am also assuming that the coefficients of the polynomials are in some ring.
Answer: The problem is to understand what exactly the dimension of a vector space is. I'll recall this result, which is the basis for the notion of dimension:

Let $V$ be a finite-dimensional space. All bases of $V$ have the same number of elements. Furthermore, the following numbers are the same:

The minimal number of elements in a  generating family for $V$.
The maximal number of elements in a linearly independent family of vectors in $V$.
The number of elements in a basis for $V$.


Como imprimir/inserir de uma forma organizada dentro de um arquivo csv uma tupla em Python

Question: Alguém saberia dizer como faço para imprimir uma tupla da seguinte forma:
  amount_of_commits,author
  148, Steve Ellis
  2, Alex Kwiatkowski
  2, Thomas
  1, Dan Forbes
  1, David Parker
  1, John Barker
  1, Thomas Hodges
  1,dependabot[bot]

O retorno que estou recebendo é do comando git shortlog -s -n cujo código encontra-se abaixo:
for token in tokens:
insights = open("repositories_insights/" + token + "_insights.csv", "w")
insights.write("amount_of_commits,author\n")

data = subprocess.Popen(["git", "-C", "github_repos/" + token + "/" + token, "shortlog",  "-s", "-n"], stdout=subprocess.PIPE).communicate()
print(str(data))
insights.write(data)
insights.close()

Quando imprimo o valor tupla data o resultado sai da seguinte forma
(b'   148\tSteve Ellis\n     2\tAlex Kwiatkowski\n     2\tThomas\n     1\tDan Forbes\n     1\tDavid Parker\n     1\tJohn Barker\n     1\tThomas Hodges\n     1\tdependabot[bot]\n', None)

Answer: Segundo a documentação de communicate o retorno é uma tupla contendo a saída padrão e a saída de erros. Além disso, quando não está no modo texto, o retorno é um objeto do tipo bytes (dá para você ver pelo b no início da saída). Além disso, como o comando não deu nenhum erro, o segundo elemento da tupla é None.
Sendo assim, você precisa pegar o primeiro elemento da tupla (que é a saída padrão do comando) e transformá-lo em string, usando o método decode.
Além disso, o comando está retornando os campos separados por um TAB (\t), então basta usar replace para substituí-lo por vírgula:
data = subprocess.Popen(["git", "-C", "github_repos/" + token + "/" + token, "shortlog",  "-s", "-n"], stdout=subprocess.PIPE).communicate()
insights.write(data[0].decode().replace('\t', ', '))

Outra opção é ler o stdout do processo linha a linha:
import subprocess

# atenção, aqui não chama communicate()
data = subprocess.Popen(["git", "-C", "github_repos/" + token + "/" + token, "shortlog",  "-s", "-n"], stdout=subprocess.PIPE)
for s in data.stdout:
    insights.write(s.decode().replace('\t', ', '))

Outra opção é setar o argumento universal_newlines, assim o retorno serão strings em vez de bytes, eliminando a necessidade de chamar decode:
data = subprocess.Popen(["git", "-C", "github_repos/" + token + "/" + token, "shortlog",  "-s", "-n"], stdout=subprocess.PIPE, universal_newlines=True).communicate()
insights.write(data[0].replace('\t', ', '))

Comment: Muito obrigado, ajudou muito :)


How do I explain when to use string and when String

Question:
Possible Duplicate:
What is the difference between String and string

I'm using string for a variable, like this
string myString = "test";

And I'm using String if I want to use some methods(?) of the Class String
String.Format...

I thought this is looking better. Buy some people are doing stuff like
String myString;
string.Format...

Its working. But I don't like this. How can I tell them to stop? Is there "C# rule" for stuff like this? The same thing for int,Int; char,Char; ...
Comment: @canon - Coding standards and consistency are important - for readability if nothing else.
Answer: string is a C# alias to System.String.
If writing C#, you should be using the alias, so string.Format and string myString.
Both end up compiled to the same IL and mean the same thing, but C# has its idioms and using the type alias is part of them - in the same way that you would use int and not System.Int32.
Comment: Yes, this.  Don't use `String` in C# code.  I've seen people that use `String` when referring to static methods of the `String` class, and `string` everywhere else.  I want to hurt those people.
Comment: Why do you say one should be using the alias if writing C#?  Can you link a legit resource from Microsoft saying this is the preferred way?
Comment: @Gromer - Why have an alias then? And you just need to look at any C# example on MSDN to see that only the aliases are used.
Comment: Having an alias doesn't mean one has to use it.  Like I posted, I always use the alias, but I've never heard anyone say you should use them when writing C#.
Comment: @Gromer After saying `using EventMap = Dictionary>;` do you then proceed to use `Dictionary>` in your code, or do you use `EventMap`?
Comment: I've already explained that I use the aliases.  But for types, I see no reason to say one has to use the alias.  Your example is comparing apples and oranges IMO.
Comment: @Gromer I'm not comparing apples and oranges.  `string` is an alias to `System.String`, and `EventMap` is an alias to `System.Collections.Generic.Dictionary>`.  They are both another name for an existing type.  One of them just happens to be imposed on you by the language.
Comment: So then why did Microsoft decide to _not_ use the type aliases in generated entities in EF if it is such a "bad" practice?
Answer: Coding guidelines are an important thing if you are working on bigger projects and ensure that you can easily read code written by any of the developer in your team.
Unfortunately there isn't any official guideline on how you should format your C# code. Microsoft itself encountered the problem while developing the .NET framework and developed an internal set of style guidelines which grew into a full fledged program called StyleCop which has a default rule set with sensible settings.
According to these rules you should always use string instead of String:
string xyz;
string.Format();

The rules is the following:

SA1121 - UseBuiltInTypeAlias - Readability Rules
The code uses one of the basic C# types, but does not use the built-in
  alias for the type.
Rather than using the type name or the fully-qualified type name, the
  built-in aliases for these types should always be used: bool, byte,
  char, decimal, double, short, int, long, object, sbyte, float, string,
  ushort, uint, ulong.

A recommended reading is the history of StyleCop you can find here:
http://stylecop.codeplex.com/wikipage?title=A%20Brief%20History%20of%20CSharp%20Style&referringTitle=Documentation
It explains some of the problems you encounter with different people from different backgrounds working on the same code base and how they developed the rule set.
We recently implemented StyleCop in our own project and although it is a lot of work to really follow all the rules, the resulting code is much more readable. It also has a fairly good ReSharper integration which allows you to do many fixes automatically if you use ReSharper.
Answer: I usually express this as, "If there is an identical primitive type in the language, prefer it." In your specific case, which style to use is a preference rather than something that has major impacts to functionality. What is important is that whatever style is chosen is consistently applied by everyone in your team.


Why are there two database tables to handle taxonomy terms structure

Question: There is a taxonomy_term_data table and there is a taxonomy_term_hierarchy table.  Why are there 2 tables, instead of them being combined?
taxonomy_term_hierachy strucutre

description of table: Stores the hierarchical relationship between
field: tid: 'Primary Key: the taxonomy_term_data.tid of the term'
field: parent: 'Primary Key: The taxonomy_term_data.tid of the term's parent.
0 indicates no parent.'

taxonomy_term_data structure:

description of table: Stores term information.
fields: vid, name, description, format, weight

Question motivation
I am the maintainer of the draggableviews module.  Currently module is using just 1 table.  Going forward, the module's goal is to mimic taxonomy structure.  Tried to search the web for an answer but could not find one.
Comment: A term can have multiple parents. This is easier represented in the taxonomy_term_hierachy strucutre
Comment: @Reynolds, that would make sense, but tid is unqiue (primary key) and the parent field is an integer.  Can you explain this?
Comment: @iStryker Not quite - it's a compound key across tid + parent, not just on tid
Comment: My mistake, I did not see the compound key, thought it was just on tid.
Answer: taxonomy_term_data is the base table for the taxonomy entity type. It holds ID, property and bundle data for that entity type.
taxonomy_term_hierarchy holds the parent/child relationship between taxonomy terms (which of course can be multiple in nature).
You can't store the data for anything more than a one-to-one relationship in the same table, hence the split into two.


Proof of measurability of the sum of extended-real measurable functions

Question: I was reading Rudin's Real and Complex Analysis (3rd ed.), and on page 19 he says: (The key point here is about arithmetic in $[0, \infty]$.)

Observe that the following useful proposition holds: (with arithmetic in $[0, \infty]$)
If $0\le a_1 \le a_2 \le \cdots$, $0\le b_1 \le b_2 \le \cdots$, $a_n \to a$ and $b_n \to b$, then $a_nb_n\to ab$.
If we combine this with Theorems $1.17$ and $1.14$, we see that sums and products of measurable functions into $[0, \infty]$ are measurable.

Theorem 1.14 If $f_n:X\to [-\infty, \infty]$ is measurable, and $g=\sup_n f_n$, then g is measurable.
Theorem 1.17 Let $f:X\to [0, \infty]$ be measurable.  There exist simple measurable funcctions $s_n$ on $X$ s.t. $0\le s_1\le s_2\le \cdots\le f$, and $\forall x\in X: s_n(x)\to f(x)$ as $n\to \infty.$

I am not very sure what he meant.  I list my attempted proof below, and would appreciate it if someone can confirm if it's valid, or point out if I miss his point.

Suppose $f, g:X\to[0, \infty]$ are two measurable functions.  I want to show that $f+g$ is also measurable.  I'd proceed as follows:
First, I state an easily proved proposition similar to the one given above: If $0\le a_1 \le a_2 \le \cdots$, $0\le b_1 \le b_2 \le \cdots$, $a_n \to a$ and $b_n \to b$, then $a_n+b_n\to a+b$.  (Even if $a$ or $b$ takes value of $\infty$.)
Since $f, g$ are measurable, by Theorem 1.17, there must exist simple measurable functions $f_n, g_n$ on $X$ s.t. $0\le f_1 \le f_2 \le \cdots\le f$, and $\forall x\in X:f_n(x)\to f(x).$  Similarly, $0\le g_1 \le g_2 \le \cdots\le g$, and $\forall x\in X: g_n(x)\to g(x).$  (In Rudin's book, simple functions are real functions, not extended-real.) Hence $\forall x\in X:f_n(x)+g_n(x)\to f(x)+g(x)$ by the proposition above.  (Note that $f_n+g_n$ is real, while $f+g$ is extended-real valued.) But $f_n, g_n$ are simple measurable functions, so their sum $f_n+g_n$ must be simple and measurable.  Moreover, $\{f_n+g_n\}$ is a sequence of increasing functions, so $$\lim_{n\to \infty} (f_n+g_n)=\sup_n(f_n+g_n).$$
Since the supremum of a sequence of real measurable functions must be measurable (Theorem 1.14), we conclude that $f+g$ is measurable (even though it's extended-real).
Answer: You are correct!

I have just one comment. Perhaps it will be better to say that
$$
\lim_{n \to \infty} (f_n + g_n) = \limsup_{n \to \infty} (f_n + g_n) \tag{1}
$$
instead of
$$
\lim_{n \to \infty} (f_n + g_n) = \sup_n (f_n + g_n). \tag{2}
$$
This is because for every convergent sequence $\{a_n\}$,
$$
\lim_{n \to \infty} a_n = \limsup_{n \to \infty} a_n,
$$
whereas only if $\{a_n\}$ is a monotonically increasing sequence that is convergent is it true that
 $$
\lim_{n \to \infty} a_n = \sup_{n \geq 1} a_n.
$$
So, using (2) requires a tiny bit more of an explanation than (1).
The measurability of $\limsup_{n \to \infty} (f_n + g_n)$ also follows from Theorem 1.14 (you haven't stated it in full in the question details):

Theorem 1.14. If $f_n : X \to [-\infty,\infty]$ is mesaurable, for $n = 1,2,3,\dots$, and $$g = \sup_{n \geq 1} f_n, \qquad h = \limsup_{n \to \infty} f_n,$$ then $g$ and $h$ are measurable.

For completeness, here's an example of a sequence $\{ a_n \}$ such that $\sup_{n \geq 1} a_n \neq \limsup_{n \to \infty} a_n$: take the sequence given by $a_n = 1/n$. Then the supremum is $1$ whereas the upper limit is $0$.
Comment: For an _increasing_ and bounded sequence, it's well-known that its limit is the supremum, e.g. https://en.wikipedia.org/wiki/Monotone_convergence_theorem.  If the sequence is unbounded and we consider the arithmetic in $[0, \infty]$ as in Rudin's book, it still holds, doesn't it?
Comment: @syeh_106 ah, yes of course. Let me modify my answer. Thanks!


SAS Token Handling for Custom Module Connectivity in Azure IoT Edge

Question: I am connecting a custom module to IoTHub using Azure IoT Edge.

The authentication method for the IoT Edge device is "Symmetric Key."
The package used for connecting to IoTHub is the azure-iot-sdk-c (https://github.com/Azure/azure-iot-sdk-c).
Connection is established using the "IoTHubModuleClient_CreateFromEnvironment" function from the azure-iot-sdk-c.
MQTT is the chosen protocol.
Versions of IoT Edge, edgeHub, and edgeAgent are 1.4.16.

When connecting the custom module to IoTHub and transmitting telemetry, my understanding is as follows:
(1) The custom module generates an SAS token (generated during the execution of the "IoTHubModuleClient_CreateFromEnvironment" function in azure-iot-sdk-c).
(2) The custom module uses the SAS token generated in (1) to connect to edgeHub and passes the SAS token to edgeHub.
(3) The custom module uses the SAS token generated in (1) to transmit telemetry to edgeHub.
(4) edgeHub, using the SAS token passed in (2), transmits telemetry to IoTHub.
I want to confirm whether the SAS token between the custom module and edgeHub is the same as the SAS token between edgeHub and IoTHub or if they are different.
Thank you.
Answer: The SAS token you have mentioned is only used for communication between IoT Edge modules and IoT Edge Hub module. If there are multiple modules on your IoT Edge device, each module gets their own token using the above approach. Note that each of the modules here are connecting to IoT Edge Hub using ModuleClient
IoT Edge Hub on the other hand connects to Azure IoT Hub using DeviceClient. The configuration needed for IoT Edge Hub connection is set up during the Edge device deployment. For instance, notice the section Deploy the IoT Edge device where you could see the device connection string parameter set. This will be used by the IoT Edge runtime and IoT Edge Hub to authenticate and communicate with IoT Hub.
Refer to the documentation Understand the Azure IoT Edge runtime and its architecture to get a better understanding on the architecture and functionality of IoT Edge Hub.


WCF Session Management

Question: I am new to WCF and trying to accomplish a few things in terms of session management:

I would like to get an event on the server when a new session is opened/created.
I would like the ability to either close all open sessions, or get a list of open sessions and close specific ones (on the server, of course).

How would I go about doing this? Google has been surprisingly unhelpful...
Comment: Those requirements aren't satisfied with "just" WCF - you'll need some management tooling, like AppFabric - check out [this blog post](http://weblogs.asp.net/cibrax/archive/2010/02/01/monitoring-your-wcf-services-with-appfabric.aspx) on the topic
Comment: Maybe I should have been more specific, but I am not looking for external monitoring or events. For instance, for req #1 I would like a hook into a new session being created so I can add custom verification code there.
Comment: Do you mean custom authentication or just some initialization code?
Comment: I need both and assuming the authentication/authorization passes, I will like to close all sessions opened by other users (e.g. req #2)
Answer: The answer is going to be a lot of "it depends". Some of the bindings are not session aware. Something like BasicHttpBinding for example doesn't do sessions on its own, but if you enable ASP.net compatability mode you can get ASP.net's session management to work. You will then be able to use Session_Start and Session_End in global.asax to do what you want when sessions are opening or closing.
You should look at the binding you're using and see if it has some kind of session support built in, because some of them do.
If you're doing authentication, you could also imitate a session management system by mapping requests to authenticated users and storing the session record in the database.
I will say that in any case I'm not sure what "closing" a session is going to get you. Unless you're also locking the user out somehow, the next request will just immediately start a new session if the previous one was ended. Maybe if you explain what goal you want to accomplish (and why) we can be of further help.
Answer: I agree with Tridus's answer on this. You can use Session with WCF services by enabling ASP.NET Compatibility Mode.
Check http://msdn.microsoft.com/en-us/library/aa702542.aspx for an initial reading. Keep in mind - Services are supposed to be stateless by principle.

WCF Session Management


How do I automate suppling the network location of the kickstart config file when booting a Redhat variant 7 install iso

Question: When booting a Scientific Linux 7 install iso for example, one could immediately hit tab and add some text to specify the location of the ks.cfg file they would like to use.
I would like to automate this completely so no human intervention is needed.
As a general example I may have a Jenkins job that connects to an HP ILO, inserts an iso, and triggers a reboot.
What I have not found an answer for yet in Googling is how to automatically append something like:
linux ks=http://<location>/ks.cfg

to the end of the config line that appears after you hit tab.
My ideal solution would be to use few to none in regard to third party provisioning tools.
Ultimately I plan on using Jenkins, puppet, pxeboot, etc, but I dont want the solution to be dependent on something like cobbler for example.
Comment: The solution _is_ dependent on your chosen provisioning method, so answering _this_ question won't help you. Providing the command line via PXE has absolutely no relation whatsoever to providing it to a CD/DVD based installation.
Comment: If that is the case, then if I had jenkins connect to ILO, insert a dvd iso, how would I automate the appending of the ks.cfg url?
Comment: Normally I'd modify the ISO image ensuring the correct options are included in the default isolinux boot option. But typically when you'll be retrieving the kickstart file from the network and remote mounting an ISO image you want that ISO to be small and do a network install, not a CD/DVD install.
Comment: Ah, yes this is basically what I was looking for, I found the isolinux.cfg file which contains that line to append. In my case when we move servers from one data center to another, the network team frequently does not get the vlan change request right and network dependent boot iso fail first. I wanted something that was not network dependent upfront which I why I choose a full DVD
Answer: Just to clarify the answer for others:
Create a custom iso:
http://smorgasbork.com/component/content/article/35-linux/151-building-a-custom-centos-7-kickstart-disc-part-1
These directions were sufficient for this part.
In the isolinux folder edit the isolinux.cfg file.
Here it looks like you could add multiple install options as well that look like:
label check
    menu label Test this ^media & install SL 7
    menu default
    kernel vmlinuz
    append initrd=initrd.img inst.stage2=hd:LABEL=SL-7-x86_64 rd.live.check quiet

After the word quiet add:
ks=http://location/to/ks.cfg

What I like about this It appears I could add multiple options for different scenarios perhaps.
I will test this and update the thread
This link contains all the possible ks location options.
https://access.redhat.com/documentation/en-US/Red_Hat_Enterprise_Linux/5/html/Installation_Guide/s1-kickstart2-startinginstall.html


AS3 flash currencyformatter for Flash

Question: I need help in extending the proper string?? to format my numericstepper and/or text display fields to currency formatted. You can download the FLA from CS5 flash FLA HERE. Thanks
 /* start application */
import flash.geom.Matrix;
import flash.display.Bitmap;
import flash.display.BitmapData;
import flash.text.TextField;
import flash.net.URLLoader;
import flash.globalization.CurrencyFormatter;

//comboBox, I populate values displayed to users

    this.comptype.addItem ( { label: "clerical" } );
    this.comptype.addItem ( { label: "concrete" } );
    this.comptype.addItem ( { label: "demolition" } );
    this.comptype.addItem ( { label: "electricians" } );
    this.comptype.addItem ( { label: "excavation" } );
    this.comptype.addItem ( { label: "HVAC/Plumbing" } );
    this.comptype.addItem ( { label: "oil and gas" } );
    this.comptype.addItem ( { label: "road/bridge construction" } );
    this.comptype.addItem ( { label: "roofing" } );
    this.comptype.addItem ( { label: "sewer construction" } );
    this.comptype.addItem ( { label: "truck driving" } );
    this.comptype.addItem ( { label: "warehousing" } );

this.comptype.addEventListener (Event.CHANGE, selectOrder);
function selectOrder (event:Event) : void

    {
        if (this.comptype.selectedItem.label == "clerical") this.orderTotal.text = ("3.00");
        if (this.comptype.selectedItem.label == "concrete") this.orderTotal.text = ("8.00"); //make sure my values match the above values EXACTLY
        if (this.comptype.selectedItem.label == "demolition") this.orderTotal.text = ("10.00"); //make sure my values match the above values EXACTLY
        if (this.comptype.selectedItem.label == "electricians") this.orderTotal.text = ("5.00"); //make sure my values match the above values EXACTLY
        if (this.comptype.selectedItem.label == "excavation") this.orderTotal.text = ("8.00"); //make sure my values match the above values EXACTLY
        if (this.comptype.selectedItem.label == "HVAC/Plumbing") this.orderTotal.text = ("6.00"); //make sure my values match the above values EXACTLY
        if (this.comptype.selectedItem.label == "oil and gas") this.orderTotal.text = ("13.00"); //make sure my values match the above values EXACTLY
        if (this.comptype.selectedItem.label == "road/bridge construction") this.orderTotal.text = ("10.00"); //make sure my values match the above values EXACTLY
        if (this.comptype.selectedItem.label == "roofing") this.orderTotal.text = ("18.00"); //make sure my values match the above values EXACTLY
        if (this.comptype.selectedItem.label == "sewer construction") this.orderTotal.text = ("9.00"); //make sure my values match the above values EXACTLY
        if (this.comptype.selectedItem.label == "truck driving") this.orderTotal.text = ("13.00"); //make sure my values match the above values EXACTLY
        if (this.comptype.selectedItem.label == "warehousing") this.orderTotal.text = ("7.00"); //make sure my values match the above values EXACTLY

    }
this.outline.calcBtn.addEventListener (MouseEvent.CLICK, goCalc);
function goCalc (Event:MouseEvent) : void

            {
        this.outline.annualSavings.text = (this.staffrate.value-(14.15 + parseInt(this.orderTotal.text)))*this.payroll.value;
        //this.outline.docCostMonth.text = (this.timesPerDay.value * 260) / 12 * this.docProcCost.value;
        //this.outline.docCostYear.text = (this.outline.docCostMonth.text *12);
        //this.outline.annualSavings.text = ((this.procAutoSaving.value * this.outline.docCostYear.text) / 100);
        }

var cf:CurrencyFormatter = new CurrencyFormatter( "en_US" );
this.payroll.value = this.payrollOut;
cf.format( this.payrollOut.text );  //??

Answer: Hey there I hope this helps,
myTextField1.text = formatCost(String(4813.134),2,"$",0);// result: $ 4,813.13

The function is pretty simple, we call the function formatCost()
If you just wish to format it to 0 decimals, formatCost(value as string,0)
If you need a currency add that in as the 3rd parameter.
If you need the symbol to appear behind the number, have the position set to 1
So...
formatCost(String(8/35*100),1,"%",1);// will give "22.9 %"

if wanted, you can tack on more to the formula so that the 5th variable could be the spacer, so that you could change it from a "," to a "." (for french) or as a space " "
public function formatCost(v:String,
           decimal_places:int = 2,
           currency_symbol:String = "",
           placement:int = 0){
        v = String(Number(v).toFixed(decimal_places));
        var result:String = new String();
        if(decimal_places == 0){
        }else{
            result = v.substr(-1-decimal_places);
            v = v.substr(0, v.length-1-decimal_places);
        }
        while( v.length > 3 ){
            result = "," + v.substr(-3) + result;
            v = v.substr(0, v.length-3);
        }
        if(v.length > 0){
            if(placement == 0){
                result = currency_symbol + " " + v + result;
            }else if(placement == 1){
                result = v + result + " " + currency_symbol;
            }else{
                result = v + result;
            }
        }
        return result;
    }//closes formatCost

Answer: A better alternative for currency formatting is to use the Adobe class flash.globalization.CurrencyFormatter
public static function getDollars(value:Number):String{

        var targetFormatter:CurrencyFormatter = new CurrencyFormatter("en-US");
        return targetFormatter.format(value, true);

    }

This class is very flexible, allowing to you customize the currency appearance for locale.
Answer: The issue is that you are not paying attention to the variable types.
this.payrollOut -- is a textfield
this.payrollOut.text  -- is the text contained in that textfield
this.payroll.value cannot be assigned a textfield or a text value
So you must convert to the type that it is expecting -- in this case a Number.
this.payroll.value = Number(this.payrollOut.text);

cf.format is expecting a Number value as well, and will return a String.
an example of usage might be :
var payrollAmount:Number = 400;
var payrollCurrencyAmount:String = cf.format(payrollAmount);

There are other issues with the code that I see -- payrollOut has no value - so it's still not going to function as expected, but this solves the immediate problem.

AS3 flash currencyformatter for Flash


Consulta na mesma tabela

Question: Tenho uma tabela movimento que tem o registro do trabalhador e os eventos a ele relacionado,

queria um consulta que retornasse apenas os registros que possuem exatamente os eventos e1,e2 e e3, no caso do exemplo acima os registro seriam o 001 e 003
Comment: Utilize a cláusula WHERE. Um pequeno tutorial: https://www.w3schools.com/sql/sql_where.asp
Comment: Entendo, mas no caso teria que mostrar os trabalhadores que possuem exatamente os três eventos apenas
Answer: Você não especificou qual base de dados está utilizando, mas pode fazer isso de várias maneiras. Usei o Mysql de exemplo e fiz 2 formas para isso:

Usando EXISTS:

select distinct
m.registro
from movimento m
where
exists (select 1 from movimento x where x.registro = m.registro and x.evento = 'e1')
and
exists (select 1 from movimento x where x.registro = m.registro and x.evento = 'e2')
and
exists (select 1 from movimento x where x.registro = m.registro and x.evento = 'e3');

Resultado:

registro
001
003

Usando INSTR e GROUP_CONCAT:

select distinct
m.registro,
GROUP_CONCAT(m.evento) as eventos
from movimento m
group by m.registro
having
INSTR(GROUP_CONCAT(m.evento),'e1') > 0
and
INSTR(GROUP_CONCAT(m.evento),'e2') > 0
and
INSTR(GROUP_CONCAT(m.evento),'e3') > 0;

Resultado:

registro    eventos
001         e1,e2,e3
003         e1,e2,e3

Coloquei no SQLFiddle
Comment: Funcionou amigo, obrigado
Comment: @NaalielCorrêa marque como resposta por favor. Se tiver dúvidas acesse o [Tour] para ver como
Answer: Segue uma alternativa:
SELECT registro FROM trabalhador
WHERE registro IN (SELECT registro FROM trabalhador WHERE evento = 'e1')
AND registro IN (SELECT registro FROM trabalhador WHERE evento = 'e2')
AND registro IN (SELECT registro FROM trabalhador WHERE evento = 'e3')
GROUP BY registro

Abraço.
Comment: Também funcionou amigo, obrigado

Consulta na mesma tabela


Is it correct that a node and it's translations have the same node id?

Question: I just translated a node and I saw that both nodes have the same node id. Since I cant find anything about it: is this correct?
Answer: Yes it's correct because Drupal 8 use Entity Translation (in core) for the translations.
You can more about this in Drupal 8 multilingual tidbits 17: content translation basics

If you already built multilingual sites with Drupal 7 that had content
  translation, you may notice this model is a refined version of the
  Drupal 7 Entity translation module (without awkward modules required
  like Title) rather than the Drupal 7 core content translation module.
  The core module in Drupal 7 keeps different copies of nodes and
  relates them together in a translation set. In Drupal 8 this feature
  is not available, instead you can configure translatability on a field
  (and in some cases subfield) basis. However if you configure all
  fields to be fully translatable, you can essentially reproduce the
  Drupal 7 behavior. Compared to the Drupal 7 core solution with
  different entity identifiers then, Drupal 8 will have the same entity
  identifier but a different language variant.
The biggest advantage of the Drupal 8 solution is you can configure to
  translate as much as needed and not more. With one unified solution to
  translate only some fields or all fields, (contributed) modules only
  need to deal with one system instead of two. With storing translations
  under one entity, modules that don't want or need to deal with
  multilingual scenarios can still consider the entity as one, no need
  for special translation set support. That is way more flexible than
  Drupal 7 and best of all it applies to all kinds of content, not just
  nodes. It is future proof for modules you enable like rules and
  commerce.


Como alterar chave de um array PHP

Question: Estou precisando alterar a chave de uma array
$task=array('Title' => 'Test', 'Description' => 'Description test')

Preciso alterar o nome da key Description
Existe alguma forma?
Estou trabalhando com o framework Laravel
Comment: Respondi mas saliento que isso é básico de PHP.
Answer: Parece simples, mas não é tão trivial assim.
A resposta à sua pergunta é: não é possível. Dito isso você me perguntaria "como não é possível se as outras respostas mostraram como fazer?" e eu responderia "eles mentiram (no mínimo omitiram) para você".
O PHP, por decisão interna, resolveu definir uma estrutura "genérica" para trabalhar com quase todas as outras estruturas de dados, tanto que não é difícil você ler que PHP é orientado a array - quase tudo é array no PHP. Bem como a própria documentação traz:

Um array no PHP é na verdade um mapa ordenado. Um mapa é um tipo que relaciona valores a chaves. Este tipo é otimizado para várias usos diferentes: ele pode ser tratado como um array, uma lista (vetor), hashtable (que é uma implementação de mapa), dicionário, coleção, pilha, fila e provavelmente mais.

Talvez possa ter passado-lhe despercebido, mas a definição começa com o trecho mais importante:

Um array no PHP é na verdade um mapa [...] que relaciona valores a chaves.

E você não consegue alterar a chave de um mapa. O que você consegue é copiar o valor de uma chave, criando uma nova e excluindo a antiga, mas isso não é alterar. Foi isso que a resposta do Lucas Azambuja fez e é a forma mais prática de se obter o resultado desejado. Você conseguiria ainda abstrair isso para uma função:
function array_replace_key(&$arr, $old, $new, $overwrite = true): bool {
    if (isset($arr[$new]) and !$overwrite) {
        return false;
    }

    $arr[$new] = $arr[$old];
    unset($arr[$old]);

    return true;
}

Veja functionando no Repl.it | Ideone
Para "substituir" a chave description por descrição, por exemplo, bastaria fazer array_replace_key($task, 'description', 'descrição'). Caso a chave descrição já existir no array ele será sobrescrito; se esse não for o comportamento desejado, você pode passar o último argumento como falso que o valor existente será mantido inalterado, array_replace_key($task, 'description', 'descrição', false). A função retornará um booleano indicando se houve ou não a "substituição" da chave.
Vale lembrar que como é feita a cópia do valor de uma chave para outra, dependendo do que é esse valor, poderá ter problemas com memória, pois durante a execução da função você terá dois objetos iguais.
A solução com array_merge tende a ser ruim na maioria dos casos, pois além de manter 3 cópias do seu objeto em memória (uma no objeto original, outra no parâmetro da função e a terceira no novo array a ser mesclado), fará uma operação que é diretamente dependente do tamanho do array (no mínimo O(N)). Isso significa que se você possuir um array com milhares de valores, a operação irá demorar mais, mesmo que a intenção seja apenas alterar uma chave.
Quanto à solução utilizando funções definidas pelo Laravel eu não sei avaliar. Não sei se as funções fazem apenas o que prometem e de que forma fazem, mas inicialmente acho desnecessário utilizar funções de um framework para tal. Se existirem vantagens em utilizá-las talvez o Marcos Xavier saberá responder melhor.
Comment: Muito obrigado Anderson, sua resposta foi completa e clara, estou inciando em programação WEB e foi muito bom entender mais sobre esse tipo de manipulação de ARRAY, a explicação sobre memoria foi perfeita... Sempre tinha visto respostas dando essa mesmo função de array, sem a menor explicação, muito obrigado mesmo.
Answer: <?php

$task=array('Title' => 'Test', 'Description' => 'Description test');
$task['NovoNome'] = $task['Description'];
unset($task['Description']);

?>

Answer: No jeito Laravel de fazer. Usei a sintaxe contraída de array $array = ['...']; ( disponível a partir do PHP 5.4 https://secure.php.net/manual/pt_BR/language.types.array.php )
$task = ['Title' => 'Test', 'Description' => 'Description test'];

//remove a chave Description,equivalente a unset($task['Description'])
array_forget($task, 'Description');
dump($task);

$task = array_add($task,'New Description','New description test');
//add no início do array
$task = array_prepend($task,'First Key','First');
dump($task);

Up.
Testado na versão 5.4 e 5.5 do Laravel

Como alterar chave de um array PHP


Easiest way to turn permutations into Sibelius notation

Question: Total dummy (non-programmer) question here.
There are permutations like these, for example:
(n=9, r=2)  {1,2} {1,3} {1,4} {1,5} {1,6} {1,7} {1,8} {1,9} {2,1} {2,3} {2,4}
{2,5} {2,6} {2,7} {2,8} {2,9} {3,1} {3,2} {3,4} {3,5} {3,6} {3,7} {3,8} {3,9}
{4,1} {4,2} {4,3} {4,5} {4,6} {4,7} {4,8} {4,9} {5,1} {5,2} {5,3} {5,4} {5,6}
{5,7} {5,8} {5,9} {6,1} {6,2} {6,3} {6,4} {6,5} {6,7} {6,8} {6,9} {7,1} {7,2}
{7,3} {7,4} {7,5} {7,6} {7,8} {7,9} {8,1} {8,2} {8,3} {8,4} {8,5} {8,6} {8,7}
{8,9} {9,1} {9,2} {9,3} {9,4} {9,5} {9,6} {9,7} {9,8}
So in this case, there is a 2/2 time signature and every note in the braces is a half-note. The Numbers count as:
1=C
2=D
3=E
4=F
5=G
6=A
7=B
8=C (2nd oct.)
9=D (2nd oct.)

Three Questions in one:
1) is there any software that does this instantly? Also, a batch-plugin would come very in handy while using Sibelius 7.5.
2) Does algorithmic-composition take part in notating permutations ("rocket science" scripts??) ? if current algorithm-composition software has it, i may need detailed instructions.
3) Is it necessary for top notch performance software if i want to go above three or four octave reach with notating permutations?
Answer: I am not certain how your {x,y} pairs map to notes; treating them as chords:
echo '{1,2} {1,3} ...' | tr '{},' '<> ' | perl -ple '%p2n=qw/1 c 2 d 3 e 4 f 5 g 6 a 7 b 8 c'\'' 9 d'\''/; s/(\d)/$p2n{$1}'\''/g' | ly-fu --absolute --open --silent -

produces

which appears unsatisfactory, so perhaps instead the {x,y} blocks are subsequent notes over time?
echo '{1,2} {1,3} ...' | tr ',' ' ' | tr -d '{}' | perl -ple '%p2n=qw/1 c 2 d 3 e 4 f 5 g 6 a 7 b 8 c'\'' 9 d'\''/; s/(\d)/$p2n{$1}'\''/g' | ly-fu --absolute --silent --open

However, that's my tool chain, which requires https://github.com/thrig/App-MusicTools and some knowledge of Unix and Perl and Lilypond to be practical. Replicating this for e.g. Sibelius would require learning what scripting capabilities Sibelius has, or what formats it can import, and then (learning how to and then) writing appropriate code to generate suitable data for Sibelius to import. It appears http://www.sibelius.com/download/documentation/pdfs/sibelius710-manuscript-en.pdf is a good starting point for coding within the Sibelius ecosystem.
Comment: If this is what the OP wants, you can easily write a MIDI file from lilypond and import it into Sibelius. For a score as simple as this, there shouldn't be anything "lost in translation" using MIDI.
Comment: There are commercial and freeware plugins for Sibelius, written in the Sibelius proprietary scripting language (called ManuScript), which are for generating compositional ideas. It is possible for you to contact the authors of these plugins and scripts and ask for help. The official Avid list of Sibelius plugins is here: http://www.sibelius.com/download/plugins/index.html
Answer: Well, I don't know the programmatic facilities of Sibelius.  Here is an example LilyPond file:
\version "2.18.0"

#(define (perm lst r)
  (if (zero? r) '(())
   (append-map
    (lambda (x)
     (append-map
      (lambda (old) (if (member x old) '() (list (cons x old))))
      (perm lst (1- r))))
    lst)))

showperm =
#(define-music-function (parser location r notes) (index? ly:music?)
  (make-sequential-music
   (map (lambda (x) (music-clone notes 'elements (ly:music-deep-copy x)))
        (perm (ly:music-property notes 'elements) r))))

{
  \time 2/2
  \showperm 2 <c' d' e' f' g' a' b' c'' d''>2
  \showperm 4 { c'8 e' g' c'' }
  \bar "|."
}

Now the output from that file will look like
Comment: While this seems like it might be what the asker is looking for, it's not clear whether one could change the permutations and have the music automatically change or how this works. Can you add a little bit about the relationship between the permutations given and how this Lilypond file engraves them as notes?
Answer: In all it sounds that this may be a job for the ManuScript language, which has direct (though often clunky & limited) integration with Sibelius. However I understand you mentioned you don't have much programming knowledge - if you don't want to get into the messiness and fairly poor documentation of Manuscript, it may be best for you to just do things by hand (three hours of copying notes from an excel spreadsheet would be a lot faster than >8 hours of learning ManuScript for a non-programmer). If this is a larger scale or more general-purpose project it would certainly be beneficial to learn ManuScript or other non-Sibelius options (others have mentioned Lilypond, Abjad lets you work with Lilypond algorithmically through Python, OpusModus might also be worth looking into.

2) Does algorithmic-composition take part in notating permutations
  ("rocket science" scripts??) ? if current algorithm-composition
  software has it, i may need detailed instructions.

Since you seem to have very specific goals here, it's highly unlikely that any perfectly pre-built solution exists, but once you have a decent knowledge of whatever language you use it shouldn't be very difficult to make your own.

3) Is it necessary for top notch performance software if i want to go
  above three or four octave reach with notating permutations?

Not quite sure what you mean here, could you specify?