text:
Q: 2 ways to find a Laurent series? A First Course in Complex Analysis by Matthias Beck, Gerald Marchesi, Dennis Pixton, and Lucas Sabalka Exer 8.17,19,36 --> These exercises involve possibility of computing multiple Laurent series.

-

(Q1) For Exer 8.17, do we obtain multiple Laurent series depending on how we rewrite $\frac1{z+1} = \frac1{2+z-1}$?

I did similarly for Exer 8.18, and it seems that that's the point based on Exer 8.32 where I obtained 4 Laurent series (the 4th being convergent on the $\emptyset$!)
For (Q1)

*

*Take out $z-1$
$$\frac1{z+1} = \frac1{2+z-1} = \frac1{(z-1)(\frac{2}{z-1}+1)} \to \ \text{a Laurent series for} \ |z-1| > 2$$

*Take out $2$
$$\frac1{z+1} = \frac1{2+z-1} = \frac1{(2)(1+\frac{z-1}{2})} \to \ \text{a Laurent series for} \ |z-1| < 2$$
-

(Q2) For Exer 8.19, is there only one Laurent series unlike in Exer 8.17,18?

For (Q2)
$$\frac{z-2}{z+1} = 1 + \frac{-3}{z+1} \ \text{only}?$$

(Q3) For Exer 8.36, I came up with 2 Laurent series. Are they both valid?

Rewrite $\frac1{(z^2-4)(z-2)} = \frac1{(z-2)^2(z+2)}$. Rewrite $\frac1{z+2} = \frac1{z-2+4}$:

*

*Take out $z-2$
$$\frac1{z+2} = \frac1{z-2+4} = \frac1{(z-2)(\frac{4}{z-2}+1)} \to \ \text{a Laurent series for} \ |z-2| > 4$$

--> This is not the book's answer, and it doesn't seem to have a $c_{-1}$. It looks like the integral will be 0.

(Q3.1) What's wrong with this Laurent series? I guess something like $C[2,1] \subsetneq \{|z-2| > 4\}$, so it doesn't apply or something.

*Take out $4$

$$\frac1{z+2} = \frac1{z-2+4} = \frac1{(4)(1+\frac{z-2}{4})} \to \ \text{a Laurent series for} \ |z-2| < 4$$
--> This is the book's answer (apart from the region), and it gives the same answer as with Cauchy Integral Formula 5.1 (and later Residue Theorem 9.10) namely $\frac{- \pi i}{8}$

(Q3.2) Book says that for $\frac1{(4)(1+\frac{z-2}{4})}$, the region of convergence is $\color{red}{0 <} |z-2| < 4$. Why $0 <$?

A: Note that isolated singularities of a rational function specify different regions of convergence when expanding the function around a point in a Laurent series. So, for each of these different regions there is a specific representation of $f$ as Laurent series.

Ad Q.1: Yes, we obtain two different Laurent series expansions of $f$ around $z=1$, one for each region of convergence. Since there are simple poles at $z=1$ and $z=-1$ we have to distinguish two regions of convergence when expanding around the pole $z=1$.
  \begin{align*}
D_1:&\quad 0<  |z-1|<2\\
D_2:&\quad |z-1|>2
\end{align*}

*

*The first region $D_1$ is a punctured disc with center $z=1$, radius $2$ and the pole at $z=-1$ at the boundary of the disc.  It admits for the fraction with pole  at $z=1$ a representation as principal part of a Laurent series and for the fraction with pole at $z=-1$ a power series.

*The region $D_2$ contains all points outside the disc with center $z=1$ and radius $2$. It admits for both fractions a representation as principal part of a Laurent series.
Note that in $D_1$ we have to exclude $0$, since $f$ is not defined there.

We have in $D_1$ the representation
\begin{align*}
\frac{1}{(z-1)(z+1)}&=\frac{1}{z-1}\cdot\frac{1}{2+(z-1)}\\
&=\frac{1}{z-1}\cdot\frac{1}{2\left(1+\frac{z-1}{2}\right)}\\
&=\frac{1}{2}\cdot\frac{1}{z-1}\sum_{j=0}^\infty(-1)^j\left(\frac{z-1}{2}\right)^j\\
&=-\sum_{j=-1}^\infty\left(-\frac{1}{2}\right)^j(z-1)^j
\end{align*}
and in $D_2$ we have the representation
\begin{align*}
\frac{1}{(z-1)(z+1)}&=\frac{1}{z-1}\cdot\frac{1}{2+(z-1)}\\
&=\frac{1}{(z-1)^2}\cdot\frac{1}{1+\frac{2}{z-1}}\\
&=\frac{1}{(z-1)^2}\sum_{j=0}^\infty(-1)^j\left(\frac{2}{z-1}\right)^j\\
&=\frac{1}{4}\sum_{j=-\infty}^{-2}\left(-\frac{1}{2}\right)^j(z-1)^j
\end{align*}

Ad Q.2: Yes, there is only one region of convergence, since we have only one simple pole at $z=-1$. The region of convergence is $|z-1|>0$ and the Laurent-series expansion is according to your calculation.
Ad Q.3,Q3.1: We obtain for $|z-2|>4$ the Laurent series expansion
  \begin{align*}
\frac{1}{(z^2-4)(z-2)}&=\frac{1}{(z-2)^2}\cdot\frac{1}{z+2}\\
&=\frac{1}{(z-2)^3}\cdot\frac{1}{1+\frac{4}{z-2}}\\
&=\frac{1}{(z-2)^3}\sum_{j=0}^\infty(-4)^j\frac{1}{(z-2)^j}\tag{1}\\
&=\cdots
\end{align*}
Ad Q.3.2: The function under consideration
  \begin{align*}
\frac{1}{(z^2-4)(z-2)}
\end{align*}
  has a pole at $z=2$. Since this function is not defined at $z=2$ we have to exclude $0$ from the region and get $0<|z-2|<4$.

Hint: This answer with some more detailed considerations might be helpful.


text:
Q: "this" is a global object after using call() I have stored the names of the methods in a list.
var list = ['fn1', 'fn2', 'fn3', 'fn4'];

I select the method using some criteria dynamically. The methods are part of a larger class that are attached using 'prototype
MyObj.prototype.selectfn = function(criteria) {
    var fn = list[sel];
    this[fn].call(this, arg1);
}
MyObj.prototype.fn1 = function(args) { // do something }
MyObj.prototype.fn2 = function(args) { // do something}

And so on. The problem is inside the selected "fn" function, the this variable appears as a global object even though I used call() I read the mozilla docs, but I'm not able to understand why this is so, can someone help out please?
It it helps, my environment is node.js 0.10.12.
Edit : It's a little hard to provide the correct sample code because my code involves callbacks in a lot of places, but I'll try to elucidate.
Assume two files User.js and Helper.js.
User.js
var m, h;
var Helper = require('./Helper');

function init() {
  // to simplify, assume the `this` here refers to `User`
  h = new Helper(this);
}

function doSomething() {
  // pass some criteria string
  h.selectfn(criteria);
}

Helper.js
var Helper = module.exports = function(user) {
  this.user = user;
}

Helper.prototype.selectfn = function(criteria) {
  // based on some criteria string, choose the function name from "list" array
  // here, the string "sel" holds the selected function name
  var fn = list[sel];
  this[fn].call(this.user, arg1);
  // if I print to console, `this.user` is correct over here, but inside the function it shows as undefined
}

Helper.prototype.fn1 = function(args) {
  // Here, I talk to databases, so I have callbacks. Say, on a callback, the user property is to be updated. This is why I want to use `call()` so that the `this` refers to `User` and can be updated.
  // For example, if we want to update the "last-seen" date.
  this.lastseen = new Date();
}

Hope the little example made it clearer.

A: the first parameter of call() is your function context "this"
as example:
var someObject = {
  withAFunction: function(text) { alert('hello ' + text); }
};

var testFunction = function(text) {
   this.withAFunction(text);
};

testFunction.call(someObject, 'world');

A: I tried to review your code:
var list = ['fn1', 'fn2', 'fn3', 'fn4'];

//MyObj is copy of Object?
var MyObj = Object;
//or a preudoclass:
//var MyObj =  function(){};

//inside this function you use sel and arg1 that seems undefined and use like arguments criteria that seems useless

MyObj.prototype.selectfn = function(sel,arg1) {
    var fn = list[sel];
    this[fn].call(this, arg1); // this is MyObj istance.

MyObj.prototype.fn1 = function(args) { console.log("fn1", args);/* do something */ }
MyObj.prototype.fn2 = function(args) { console.log("fn2",args); /* do something */ }

xxx = new MyObj();

xxx.selectfn(1,"ciao");
//call xxx.fn1("ciao");

see the console for response.

redpajama_set_name: RedPajamaStackExchange


text:
Q: SendInput or similar from windows service (session 0) in Windows 8 to login screen As I understand, when we start windows it starts Session 0 which does not connect to any GUI, etc. and runs all windows services. So my task is, after windows was started, emulate windows input for selecting user and login to is session. I know that for sending input from service I should run desktop app and through it send input, show GUI, so on, but how can I do it before any user session was start? (for example I see that TeamViewer can do it)

A: WTSGetActiveConsoleSessionId() will tell you which session is attached to the physical console.
You can then duplicate your security token with DuplicateTokenEx(), change the new token's session with SetTokenInformation() and the TokenSessionId option, and launch a process with CreateProcessAsUser().
The new process should then be running in the right session, but it may also need to attach itself to the right desktop before it can interact with the logon interface.  You can use EnumDesktops() to list the available desktops, and trial and error to determine which one the logon interface runs in.  (Note that this may be different in different versions of Windows.)


text:
Q: Is the AM-GM inequality the only obstruction for getting a specific sum and product? This might be silly, but here it goes.
Let $P,S>0$ be positive real numbers that satisfy $\frac{S}{n} \ge \sqrt[n]{P}$.

Does there exist a sequence of positive real numbers $a_1,\dots,a_n$ such that $S=\sum a_i,P=\prod a_i$?

Clearly, $\frac{S}{n} \ge \sqrt[n]{P}$ is a necessary condition, due to the AM-GM inequality. But is it sufficient?
For $n=2$, the answer is positive, as can be seen by analysing the discriminant of the associated quadratic equation. (In fact, the solvability criterion for the quadratic, namely- the non-negativity of the discriminant, is equivalent to the AM-GM inequality for the sum and the product).
What about $n>3$?

A: If we choose
$$
 (a_1, \ldots, a_{n-1}, a_n) = (a, \ldots, a, \frac{P}{a^{n-1}})
$$
for some $a > 0$ then $\prod a_i = P$ is satisfied, and we need that
$$
 f(a) = \sum a_i = (n-1)a + \frac{P}{a^{n-1}} = S \, .
$$
This equation has a solution because $f$ is continuous on $(0, \infty)$ with
$$
 \min_{a > 0} f(a) =  f(\sqrt[n]P) = n \sqrt[n]P \le S
$$
and
$$
 \lim_{a \to \infty} f(a) = + \infty \, .
$$

Remarks about a possible generalization
The Maclaurin's inequalities state the following: If $a_1, \ldots, a_n$ are positive real numbers, and the "averages" $S_1, \ldots, S_n$ are defined as
$$
 S_k = \frac{1}{\binom n k} \sum_{1 \le i_1 < \ldots < i_k \le n}
 a_{i_1}a_{i_2} \cdots a_{i_k}
$$
then
$$
 S_1 \ge \sqrt{S_2} \ge \sqrt[3]{S_3} \ge \ldots \ge \sqrt[n]{S_n} \, .
$$
In particular,
$$
 \frac 1 n (a_1 + \ldots + a_n) = S_1 \ge \sqrt[n]{S_n} = \sqrt[n]{a_1 \cdots a_n}
$$
so that this is a generalization of the inequality between the geometric and arithmetic means. Therefore a natural generalization of the above question would be:

Let $S_1, \ldots, S_n$ be given positive real numbers with
$$
 S_1 \ge \sqrt{S_2} \ge \sqrt[3]{S_3} \ge \ldots \ge \sqrt[n]{S_n} \, .
$$
Are there positive real numbers $a_1, \ldots, a_n$ such that
$$
 S_k = \frac{1}{\binom n k} \sum_{1 \le i_1 < \ldots < i_k \le n}
 a_{i_1}a_{i_2} \cdots a_{i_k}
$$
for $1 \le k \le n$?

This is equivalent to asking if the polynomial
$$
 p(x) = x^n - \binom n 1 S_1 x^{n-1} + \binom n 2 S_2 x_{n-2} + \ldots + (-1)^n \binom n n S_n
$$
has $n$ positive real zeros.
Unfortunately, this generalization does not hold. The following counterexample is from

*

*SIKLOS, STEPHEN. "Maclaurin's Inequalities: Reflections on a STEP Question." The Mathematical Gazette, vol. 96, no. 537, 2012, pp. 499–507. JSTOR, https://www.jstor.org/stable/24496873.

We choose $n=3$ and
$$
 S_1 = \frac 3 2, \, S_2 = 2, \, S_3 = 1 \, .
$$
The condition on the $S_k$ is satisfied (with strict inequalities), but a simple analysis shows that the polynomial
$$
 p(x) = x^3 - 3 S_1 x^2 + 3 S_2 x - S_3 = x^3 - \frac 9 2 x^2 + 6 x - 1
$$
has one real (positive) zero and two non-real zeros. It is therefore not possible to find real numbers $a_1, a_2, a_3$ such that
$$
 \frac{a_1+a_2+a_3}{3} = S_1, \,  \frac{a_1a_2 + a_1 a_3 + a_2 a_3}{3} = S_2,\,
 a_1 a_2 a_3 = S_3 \, .
$$

A: Let $\mu:=\frac{S}{n},\,\sigma:=P^{1/n}\le\mu$. We seek $a_i$ of AM $\mu$ & GM $\sigma$. Take $a_1=\cdots=a_{n-2}=\sigma$ so we want $a_{n-1}+a_n=n\mu-(n-2)\sigma=n(\mu-\sigma)+2\sigma,\,a_{n-1}a_n=\sigma^2$. This is achievable because it implies$$(a_{n-1}+a_n)^2-4a_{n-1}a_n=(n(\mu-\sigma)+2\sigma)^2-4\sigma^2\ge0.$$Edit: it's been pointed out we need to verify these roots of a quadratic equation are positive. That's easy: their product is positive, as is their sum.


text:
Q: Universal Sentence Encoder TypeError prunded(text) expected Tensor I have downloaded universal sentence encoder 2 to a computer without internet access and unpacked to a destination folder: 'data.'
import tensorflow as tf
import tensorflow_hub as hub

USE_embedder = hub.load(r'data/')

If I then run USE_embedder(['test']) as I normally would, I get the error: TypeError: 'Autotrackable' object is not callable. But following the tensorflow docs, I would think that I could run:
USE_embedder.signatures['default'](['test'])

But I get the TypeError:
TypeError: pruned(text: expected argument #0(zero-based to be a Tensor; got list(['test'])

When I can run this from a networked computer, loading from https://tfhub.dev/google/universal-sentence-encoder/2 rather than the extracted download, I can run something like this just fine. How can I enable the model to embed text as is normally show in the docs (e.g., USE_embedder(['text']) returns a vector).
Using: Python 3.6.7, Tensorflow 2.4.1, Tensorflow_hub 0.11.0

A: It should work when you convert your list to a tensor:
USE_embedder.signatures['default'](tf.constant(['test']))

(tested with TF 2.4.1, tensorflow_hub 0.11.0)


text:
Q: What are valid payment-method-tokens? I'm trying to create a credit card and therefore I need to call paymentMethodNone(). According to the documentation I can

Use PaymentMethod.create() to create a payment method for an existing customer:

// It's not clear what A_PAYMENT_METHOD_TOKEN has to be
Result<PaymentMethodNonce> result = bt.paymentMethodNonce()
                                      .create("A_PAYMENT_METHOD_TOKEN");

String nonceFromTheClient = result.getTarget().getNonce();
Customer customer = customerResult.getTarget();

PaymentMethodRequest paymentMethodRequest = new PaymentMethodRequest()
        .customerId(customer.getId())
        .paymentMethodNonce(nonceFromTheClient);

Result<? extends PaymentMethod> paymentMethodResult = bt.paymentMethod()
                                                        .create(paymentMethodRequest);

PaymentMethod paymentMethod = paymentMethodResult.getTarget();

However, no word about what valid tokens are in the documentation. Neither here nor here - or am I just blind?

A: Full disclosure: I work at Braintree. If you have any further questions, feel free to contact support.
You do not need a payment_method_token to create a PaymentMethod.
To create a credit card, you will need to create a PaymentMethod. First, retrieve the payment_method_nonce from the incoming request. Next, create the PaymentMethod using PaymentMethodRequest.
//payment_method_nonce will be a post parameter in the request
//set nonceFromTheClient to equal payment_method_nonce
PaymentMethodRequest paymentMethodRequest = new PaymentMethodRequest()
            .customerId(customer.getId())
            .paymentMethodNonce(nonceFromTheClient);
Result<? extends PaymentMethod> result = gateway.paymentMethod().create(request);


text:
Q: .bat file for renaming another file without giving the path I have a folder that cointains a .bat file and another folder called Config.
I can't figure out how to rename a file (test.txt) in the folder Config without giving the path to the file.
I want the .bat file to automatically get the parent folder, then go into the Config folder and rename the test.txt into something else.
This is what I've already found to rename a file
ren C:\Users\Admin\Directory\Config\test.txt something.txt

And I guess that what I want should look like this but I can't figure out how.
ren %ConfigDirectory%\test.txt something.txt

Thanks for your time!

A: This should work:
set parentdir=%cd%
ren %parentdir%\test.txt something.txt

The current directory is stored in the variable %cd%, you could use one line (ren %cd%\test.txt something.txt), but using these two always works.
And if you want to add a directory to the path:
set parentdir=%cd%
set dir=%parentdir%\directory
ren %dir%\test.txt something.txt

EDIT: apparently quotations around the directory helps the command work out:
set parentdir=%cd%
ren "%parentdir%\test.txt" something.txt

A: this isn't answer, but i can't commenting on this amazing forum.. huh *a nice rule*
and where are your .bat file?.. his path is..
this path C:\Users\Admin\Directory\Config isn't default path for os windows.. so no one variable, in environment, haven't this value.. and you can't use such variable until you append her:
setx ConfigDirectory C:\Users\Admin\Directory\Config
maximum what you can do until.. %userprofile%\Directory\Config\test.txt
also you can point path until parent dir of the batch file
%~dp0
so if your .bat file is in C:\Users\Admin\Directory that path, until test.txt, will be %~dp0\config


text: Q: Connecting postgres DB with heroku During development, I used postgres DB where I had to pip install psycopg2. Most of my post I updated during the course of development was on postgres DB. Now during deployment, I discovered that a part of the installation when I did heroku push master is installing sqlite. Now my problem is, how can I deploy my postgres DB for development in heroku, knowing that most of my post on development are really important.. thanks


text:
Q: inserting google calender event into my agenda without oath i am creating an agenda system that list and creates events in google calendar API,
i have successfully retrieved using the following code:
var mykey = 'your_api_key'; // typically like Gtg-rtZdsreUr_fLfhgPfgff
var calendarid = 'you_calendar_id'; // will look somewhat like 3ruy234vodf6hf4sdf5sd84f@group.calendar.google.com

$.ajax({
    type: 'GET',
    url: encodeURI('https://www.googleapis.com/calendar/v3/calendars/' + calendarid+ '/events?key=' + mykey),
    dataType: 'json',
    success: function (response) {
        //do whatever you want with each
    },
    error: function (response) {
        //tell that an error has occurred
    }
});

now i need to insert events and everything i can find requires oath and is mostly about saving an event on the users calendar while i just want it saved in my calendar. any advice?

A: You can use a service account => https://developers.google.com/android/management/service-account

*

*Create a Service Account

*Create a Key for your service account (JSON should work)

*Provide access to the required calendar scopes for your service account

*

*Go to https://admin.google.com/

*Go to Security->API Controls -> Domain-wide Delegation

*Add scopes, for example https://www.googleapis.com/auth/calendar, https://www.googleapis.com/auth/calendar.events

*When you call the API use the JSON (JWT => Json Web Token) file to authenticate
In the account where the calendar lives you have to provide permission to edit events from your calendar to the service account.
All the steps and code samples for HTTP/Rest using service account are here https://developers.google.com/identity/protocols/oauth2/service-account#httprest_1


text:
Q: Python cx_Oracle connection DLL error I have configured the Oracle client and try with the below code, But error prompted from the code.
import os
os.chdir("C:\\oreclient_install_dir\\instantclient_12_2")
import cx_Oracle
ORACLE_CONNECT = "user/pass@(DESCRIPTION=(SOURCE_ROUTE=OFF)(ADDRESS_LIST=(ADDRESS=(PROTOCOL=TCP)(HOST=host)(PORT=1521)))(CONNECT_DATA=(SID=sid)(SRVR=DEDICATED)))"
orcl = cx_Oracle.connect(ORACLE_CONNECT)
print("Connected to Oracle: " + orcl.version)

Error :
Python.exe - Entry Point Not Found
The Procedure entry point K32GetModuleBaseNameA could not be located in the dynamic link library KERNEL32.dll
I am using Server 2008 32 bit as client machine and remotely connect to Oracle Data Base 12c Enterprise Edition Release 12.2.0.1.0 - 64bit
Tried both Python 2.7 and 3.6.
Instant client version is "instantclient_12_2"

Appreciate if you can give me a feedback on this.
Thanks,
Tharindu Panagoda


text:
Q: finding records in a table where there is at least one record in a linked table with a date field of no longer than 3 moths from now() We have a project database in MSACCESS with the following tables:
table PROJECTS with of course an ID and project details.
table COMMENTS with an ID, a DATE and a comment text field.
COMMENTS is linked to PROJECTS with a one-many relation. (a project can have multiple comments)
What I want is a query that selects all projects with at least one comment with a date that is less than 3 months old.
I tried an inner join and got the filter right, but I thought that with the distinctrow or distinct I could filter out the doubles, but msaccess won't accept the syntax.
It's a simple task that in any programming environment would be easy to do, but I just can't get it into a single query...
[update]:
I have one little additional question: Only the records with at least one comment show up and we want new projects (with no comments yet) to show up too. I tried adding an
 "OR count(SELECT projectid FROM comments WHERE (( ( comments.commentdate ) BETWEEN Dateadd("m", -3, DATE()) AND DATE()))) =0

A: Since you seems to want distinct Projects but not the associated comment data there are several  of ways to accomplish this.
LEFT Join Distinct
SELECT DISTINCT projects.*
FROM   projects
       LEFT JOIN comments
         ON projects.id = comments.projectid
WHERE  (( ( comments.commentdate ) BETWEEN Dateadd("m", -3, DATE()) AND DATE() )
       ) or comments.projectid is null

LEFT Join With Group by
SELECT projects.id,
   projects.fielda,
   [....]
FROM   projects
       LEFT JOIN comments
         ON projects.id = comments.projectid
WHERE  (( ( comments.commentdate ) BETWEEN Dateadd("m", -3, DATE()) AND DATE() )
       ) or comments.projectid is null
GROUP BY
   projects.id,
   projects.fielda,
   [....]

IN Clause
SELECT *
FROM   projects
WHERE  id IN (SELECT projectid
          FROM   comments
          WHERE  (( ( comments.commentdate ) BETWEEN
                    Dateadd("m", -3, DATE()) AND DATE()
                  )))

Exists Clause
SELECT *
FROM   projects
WHERE  EXISTS (SELECT *
               FROM   comments
               WHERE  ( comments.commentdate ) BETWEEN
                      Dateadd("m", -3, DATE()) AND DATE()
                      AND ( projects.id = comments.projectid ))
     OR NOT EXISTS (SELECT *
               FROM comments
               WHERE projects.id = comments.projectid)

INNER JOIN to an INLINE View With a UNION to a LEFT JOIN
SELECT *
FROM   projects
INNER JOIN  (SELECT DISTINCT projectid
          FROM   comments
          WHERE  (( ( comments.commentdate ) BETWEEN
                    Dateadd("m", -3, DATE()) AND DATE()
                  ))) comment
     ON projects.id = comment.projectid
UNION ALL
SELECT *
FROM projects
     LEFT JOIN comments
     ON projects.id = comment.projectid
WHERE
     comment.projectid is null


text:
Q: Pre-populating Local SSD disk in GCP Kubernetes for readonly multipods usage What is the best way to preload large files into a local PersistentVolume SSD before it gets used by Kubernetes pods?
The goal is to have multiple pods (could be multiple instances of the same pod, or different), share the same local SSD drive in a read-only mode. The drive would need to be initialized somehow with a large dataset.
Google Local SSD docs describes the Running the local volume static provisioner, but that approach only creates a PersistedVolume, but does not initialize it.

A: Basically, you can add an init container to your pod that initializes the SSD: add data, etc.
apiVersion: v1
kind: Pod
metadata:
  name: "test-ssd"
spec:
  initContainers:
  - name: "init"
    image: "ubuntu:14.04"
    command: ["/bin/init_my_ssd.ssh"]
    volumeMounts:
    - mountPath: "/test-ssd/"
      name: "test-ssd:
  containers:
  - name: "shell"
    image: "ubuntu:14.04"
    command: ["/bin/sh", "-c"]
    args: ["echo 'hello world' > /test-ssd/test.txt && sleep 1 && cat /test-ssd/test.txt"]
    volumeMounts:
    - mountPath: "/test-ssd/"
      name: "test-ssd"
  volumes:
  - name: "test-ssd"
    hostPath:
      path: "/mnt/disks/ssd0"
  nodeSelector:
    cloud.google.com/gke-local-ssd: "true"


text:
Q: slideDown a div with anchor click then go to link I want to have a jquery div slide down on a click of a anchor tag, which is working but I want it to animate first and then visit the clicked link. Is this possible?
   $('#portfolio').click(function() {
        $('#bodyG').slideUp('fast');
        });

A: $('#portfolio').click(function(e){
  e.preventDefault();
  var href = $(this).attr('href');
  $('#bodyG').slideUp('fast', function() {
    window.location = href;
  });
});


text:
Q: How to integrate getstat() api webrtc with Jmeter I have to run a load test of around 1 hour using jmeter which needs to be integrated with getstat api webrtc to collect audio and video streaming metrics for this duration.
Any inputs who has worked on similar framework??

A: As per JMeter project main page:

JMeter is not a browser, it works at protocol level. As far as web-services and remote services are concerned, JMeter looks like a browser (or rather, multiple browsers); however JMeter does not perform all the actions supported by browsers. In particular, JMeter does not execute the Javascript found in HTML pages. Nor does it render the HTML pages as a browser does (it's possible to view the response as HTML etc., but the timings are not included in any samples, and only one sample in one thread is ever displayed at a time).

So if by "getstat api" you mean RTCPeerConnection.getStats() function the only way of obtaining it is using WebDriver Sampler which provides JMeter integration with Selenium browser automation framework. You can add another Thread Group which will kick off the real browser, collect WebRTC stats and store them into i.e. Sample Variables property, this way you will be able to add them into .jtl results file


text:
Q: Ruby regexp throws invalid backref number/name error My current code is intended to go through an enormous .csv file and reformat certain dates to an SQL Datetime friendly format. They are currently DDMMYYYY, I want them as YYYYMMDD, and this is the approach I've taken (lifted from a different SO question):
CSV.foreach('file.csv') do |x|
if x[0] == "1"
    x.gsub(/([0-9]{2})-+([0-9]{2})-+([0-9]{4})/,/\3-\2-\1/)

else
end

This throws the error "invalid backref number/name".
Docs tell me I can avoid this by defining the groups with ?<name> and backreferencing them with \k<name>, but all my attempts to do so have ended in failure. Could someone show me how it's supposed to look, or provide an alternate solution?

A: No regex:
str = "DDMMYYYY"
p new_str = str[4..7] << str[2..3] << str[0..1]
#=> "YYYYMMDD"

A: The second parameter for the gsub should be a string, not a regex (see the docs).
Do:
x.gsub(/([0-9]{2})-+([0-9]{2})-+([0-9]{4})/,'\3-\2-\1')

Note that the second parameter uses 'replacement string' instead of /replacement string/.

A: I think it's worth adding that while the above answers are correct they don't address the error that the OP was getting. This error is not an issue with the second parameter being a regular expression. In fact in the above case ruby never actually calls the gsub method as the regular expression in the second parameter won't parse. A backslash followed by any number will cause this error. It's an invalid regular expression.

A: Use ' to delimit your second gsub parameter (the replacement string), instead of /

A: I'd go with Date::strptime and Date#strftime:
dates = %w[12122012 10121012 12032013]
#=> ["12122012", "10121012", "12032013"]

dates.each do |date_str|
  date = Date.strptime(date_str, '%d%m%Y')
  puts date.strftime('%Y %m %d')
end

# 2012 12 12
# 1012 12 10
# 2013 03 12


text:
Q: How to override SSH default identity? Short version: how can I disable/override the default SSH identity file locations ~/.ssh/id_{rsa,dsa} and force SSH to use another one (first)?
Long version:
I'm trying to setup gitolite with ssh key access. From my client I'd like to access the gitolite-admin repository with my default ~/.ssh/id_rsa identity, while I've created a separate identity ~/.ssh/id_rsa_git to access the normal repositories.
Furthermore, I created an SSH alias in ~/.ssh/config:
Host git
    Hostname <servername>
    User gitolite
    ForwardX11 no
    ForwardAgent no
    GSSAPIAuthentication no
    IdentityFile ~/.ssh/id_rsa_git

Now when I try to access the gitolite repository as non-admin user, I get
$ ssh -v git true
OpenSSH_6.0p1 Debian-4, OpenSSL 1.0.1e 11 Feb 2013
debug1: Reading configuration data /home/jaap/.ssh/config
debug1: /home/jaap/.ssh/config line 105: Applying options for git
debug1: Reading configuration data /etc/ssh/ssh_config
debug1: /etc/ssh/ssh_config line 19: Applying options for *
debug1: Connecting to <servername> port 22.
debug1: Connection established.
debug1: identity file /home/jaap/.ssh/id_rsa_git type 1
debug1: Checking blacklist file /usr/share/ssh/blacklist.RSA-2048
debug1: Checking blacklist file /etc/ssh/blacklist.RSA-2048
debug1: identity file /home/jaap/.ssh/id_rsa_git-cert type -1
debug1: identity file /home/jaap/.ssh/id_rsa type 1
debug1: Checking blacklist file /usr/share/ssh/blacklist.RSA-1024
debug1: Checking blacklist file /etc/ssh/blacklist.RSA-1024
debug1: identity file /home/jaap/.ssh/id_rsa-cert type -1
debug1: Remote protocol version 2.0, remote software version OpenSSH_5.5p1 Debian-6+squeeze3
debug1: match: OpenSSH_5.5p1 Debian-6+squeeze3 pat OpenSSH_5*
debug1: Enabling compatibility mode for protocol 2.0
debug1: Local version string SSH-2.0-OpenSSH_6.0p1 Debian-4
debug1: SSH2_MSG_KEXINIT sent
debug1: SSH2_MSG_KEXINIT received
debug1: kex: server->client aes128-ctr hmac-md5 none
debug1: kex: client->server aes128-ctr hmac-md5 none
debug1: SSH2_MSG_KEX_DH_GEX_REQUEST(1024<1024<8192) sent
debug1: expecting SSH2_MSG_KEX_DH_GEX_GROUP
debug1: SSH2_MSG_KEX_DH_GEX_INIT sent
debug1: expecting SSH2_MSG_KEX_DH_GEX_REPLY
debug1: Server host key: RSA <...>
debug1: Host '<servername>' is known and matches the RSA host key.
debug1: Found key in /home/jaap/.ssh/known_hosts:19
debug1: ssh_rsa_verify: signature correct
debug1: SSH2_MSG_NEWKEYS sent
debug1: expecting SSH2_MSG_NEWKEYS
debug1: SSH2_MSG_NEWKEYS received
debug1: Roaming not allowed by server
debug1: SSH2_MSG_SERVICE_REQUEST sent
debug1: SSH2_MSG_SERVICE_ACCEPT received
debug1: Authentications that can continue: publickey
debug1: Next authentication method: publickey
debug1: Offering RSA public key: /home/jaap/.ssh/id_rsa
debug1: Server accepts key: pkalg ssh-rsa blen 149
debug1: Authentication succeeded (publickey).

This shows that my default key ./ssh/id_rsa is offered first and gets accepted. But this key does not provide access to the non-admin repositories, so I want SSH to offer only/first ./ssh/id_rsa_git. How can I do this?
I've tried adding IdentitiesOnly=yes, but that only disables ssh-agent keys. It seems there is no option in ssh configuration (site-wide or per-user) to disable the default identities, but I also cannot find a way to specify their order.

A: There is an SSH Config setting called IdentitiesOnly that defaults to "no". Set it to yes in your config file (globally or for a specific host) and your problem should be solved.
e.g., put this in ~/.ssh/config:
Host your.server.com
    IdentityFile ~/example/your_new.key
    User your_user
    IdentitiesOnly yes

From the Man page for ssh_config:
 IdentitiesOnly
         Specifies that ssh(1) should only use the authentication identity
         files configured in the ssh_config files, even if ssh-agent(1) or a
         PKCS11Provider offers more identities.  The argument to this keyword
         must be ``yes'' or ``no''.  This option is intended for situations
         where ssh-agent offers many different identities.  The default is
         ``no''.

I was having the exact same problem (and getting locked out by fail2ban). This fixed it.

A: I find it best not to store identity files (keys) in the ~/.ssh directory, since it is known to the SSH client, which (as you have noticed) has an annoying tendency to try all identities it finds in this directory, even when you explicitly specify a sole identity file for it to use.
I store all of my identity files in another directory (~/.ssh2) that is not directly known to the SSH client. The only file in ~/.ssh is config, which contains a series of {host -> key-to-use} stanzas.
With this configuration, the only way for the SSH client to find a given identity file is for you to specify it on the command line with -i, or for you to add a stanza naming the identity file in ~/.ssh/config.

A: Not sure why your setup is not working as expected but you can get around it by passing a specific identity to ssh:
ssh -i ./ssh/id_rsa_git git

From the man page:
 -i identity_file
         Selects a file from which the identity (private key) for
         public key authentication is read.  The default is
         ~/.ssh/identity for protocol version 1, and
         ~/.ssh/id_dsa, ~/.ssh/id_ecdsa and ~/.ssh/id_rsa for
         protocol version 2.  Identity files may also be speci‐
         fied on a per-host basis in the configuration file.  It
         is possible to have multiple -i options (and multiple
         identities specified in configuration files).  ssh will
         also try to load certificate information from the file‐
         name obtained by appending -cert.pub to identity file‐
         names.

It might also be because the host is known. Try deleting the relevant line (line 19) from your .ssh/known_hosts file and then connecting again.


text:
Q: How to update a svn project if .svn folders were deleted without losing history I did svn checkout (git svn clone, I don't remember) for a code.google project and start using git instead.
I preserved the original project in the master git branch and I did all my changes in an additional branch named threadSafe. However, I don't have the .svn folders anymore.
Now, I need to update the project and bring the changes from the original project without loosing my changes. So, updating my git master branch from the svn project and then merging the git branches.
Can this be done if I removed the .svn folders? something like svn update
I read in stackoverflow that "You can checkout again at the same location and the svn will version all your files without downloading if there are no new updates." And I tried this, but it didn't work because it got a message saying that there are folders with the same name.
My best shot following @flopo's suggestion was:
1. Checkout the project again using svn to another location.
2. Copy the new checkout over my code, overwriting files.
3. Now that I have the git master branch with the latest revision and the threadSafe git branch with my changes. Merge branches using git.
However, If I do this I lose the history of the svn repository. Becasue I appear as author of all the changes according to git.
Thank you!

A: *

*Checkout the project again using SVN to another location.

*Copy your code over this new checkout, overwriting files.

*Synchronize the code now you have .svn folders.

A: Use the --force option for the checkout.
From the SVN 1.7 checkout documentation:

Prior to version 1.7, Subversion would complain by default if you try
  to check out a directory atop an existing directory which contains
  files or subdirectories that the checkout itself would have created.
  Subversion 1.7 handles this situation differently, allowing the
  checkout to proceed but marking any obstructing objects as tree
  conflicts. Use the --force option to override this safeguard. When
  you check out with the --force option, any unversioned file in the
  checkout target tree which ordinarily would obstruct the checkout will
  still become versioned, but Subversion will preserve its contents
  as-is. If those contents differ from the repository file at that path
  (which was downloaded as part of the checkout), the file will appear
  to have local modifications—the changes required to transform the
  versioned file you checked out into the unversioned file you had
  before checking out—when the checkout completes.

A: Once you have deleted your .svn folders, you cannot do an update, as you don't have the needed information to do that.
I'm afraid you must do a fresh checkout in another dir. You can't do a checkout in a dir with existing files.

A: Checkout your repository in a fresh folder, then copy the root .svn directory into your old root folder. This should work.

A: If you run an svn status command and you see folders or files with "!" in front of them, follow these steps to rectify the issue:
$ svn status
!       foo/
$ svn update foo/
$ git checkout -- foo/
$ svn status

Now your .svn directories should be back, with things properly showing up as modified or deleted when you run svn status.
Important! You'll want to add .svn to your .gitignore file first, if you haven't.

A: Surely, there is a better way for doing this but I could bring the latest updated from the svn repository to my git repository by creating an intermediate respository. Doing it like this I can preserve the history tree from the original project.
(Thank you for all the answers)
//Clone the svn repository using git svn and upload as a new github repository
cd src
git svn clone http://XX.googlecode.com/svn/trunk/model XX_svn
cd XX_svn
git remote add origin git@github.com:account/XX_svn.git
git push -u origin master

//add a new remote into my git project to fetch from XX_svn
cd ../XX
git remote add svnClone git://github.com/account/XX_svn.git
git fetch svnClone
* [new branch]      master     -> svnClone/master

//merge changes as needed: merge the latest changes from the remote project to my master branch (that was an out of data copy of the original project)
git checkout master
git merge svnClone/master

//Now, I have the latest changes from the svn repository in my git master branch --> I  can merge or cherry pick as needed. For example

git checkout thread-safe
git merge master


text:
Q: Problems with Unity shades on android device I am trying to build a simple 3d scene which renders fine on my Window's machine but when I build and run it on my Android tablet all shades are gone.
The scene is pretty simple as it consists of 4 cubes, one ball, 5th cube as the background, a camera and a direction light source.
Are there any tricks to see the same shades from my PC game window on my android device ?

A: The computation of shadows depend on the quality settings. (menu: Edit > Project Settings > Quality)
These settings can be different for all the supported platforms. Check that shadows are enabled on android.


text:
Q: iOS - UILabel Showing auto bottom border I have add one UILabel in one UIView. I have not added any border or shadow to it. But still it showing that.
And Main problem is, Shadow or Border is not updating while orientation change.
Please refer following images:
Portrait Mode Label

Landscape Mode Label

Constraints Of Label:

Constraints of Superview:

I don't want that Shadow or border over there
Thank you

A: Check the background colour of its superviews and try to give clear colour to label.


text:
Q: How do I recover a HFS+ journaled drive? EDIT: I found a quasi-solution that sort of kind of works:
mount -o loop,offset=209739776,rw -t hfsplus /dev/sdc /mnt/mountpoint/

It appears (via "find /mnt/mountpoint/") that all my data is there, but attempts to access some of my data yields an "input/output error".
I had an external 2 or 3 TB (I'm not sure which) USB drive connected
to my Mac (running OS X Snow Leopard) with an HFS+ journaled
filesystem on it.
The drive was working fine, but was a bit slow and occasionally gave
I/O errors, so I backed up my files and ran fsck_hfs on it.
fsck_hfs died while trying to rebuild the B-tree, and the drive won't
mount at all now. Also, I lied about making backups first.
How do I get this drive working again? Given the redundancy of HFS+,
this should be possible no? Other notes:

*

*If I run fsck.hfsplus -df /dev/sdb3 on a Linux box, I get this:

** /dev/sdb3
        Block 1565298166 is not an MDB or Volume Header
** Checking HFS Plus volume.
   Invalid number of allocation blocks
(-1, 0)
        IVChk - volume header total allocation blocks is greater than device size
        volume allocation block count 732533183 device allocation block count 195662271
** Volume check failed.
volume check failed with error 7
        volume type is pure HFS+
        primary MDB is at block 0 0x00
        alternate MDB is at block 0 0x00
        primary VHB is at block 2 0x02
        alternate VHB is at block 1565298166 0x5d4c8df6
        sector size = 512 0x200
        VolumeObject flags = 0x03
        total sectors for volume = 1565298168 0x5d4c8df8
        total sectors for embedded volume = 0 0x00

Using a Perl script and "seek", I can see some of my filenames
  surrounded by information that I assume is telling me where on the
  drive to find my files. If all else fails, I'll pursue recovering
  files this way, but I'd prefer a "cleaner" recovery option.

A: DiskWarrior 4. It will run you $99. I've used DiskWarrior for several years and I'm very pleased with the results.
Data Rescue 3. $99. Similar to DiskWarrior, just an alternative program. Never used it before, but I've heard some good things about it. It's also sold in the Apple Store which gives it a lot of credibility.

A: even if this question is some time ago, for those who read it, I got another solution: Try testdisk, which is a cross-platform disk recovery tool. It helped me very often.
http://www.cgsecurity.org/wiki/TestDisk_Download
Sorry for my bad english.


text:
Q: Protractor - looping through different locators to populate array I'm using protractor and I want to loop through a series of locators(all with different names) to get the text being displayed and then compare that to an array of expected values.
I've come accross examples like below:
var expected = ['expect1', 'expect2', 'expect3'];
var els = element.all(by.css('selector'));
for (var i = 0; i < expected.length; ++i) {
    expect(els.get(i).getText()).toEqual(expected[i]);
}

where you can do a comparison against a locators children, but not from different locators.
How would you adapt something like the one above to loop through a list of locators(like below) and then compare that to a series of values in another array.
const locators = {
    emp: by.id('employmentError'),
    occ: by.id('occupationError'),
    stat: by.id('statError'),
    show: by.id('showError')
};

The comparison part seems easier, it is populating the initial array full of text from various locators I can't get my head around.

A: It looks like you are trying to collect elements that correspond to different types of errors. What if you would get all of them with a unified locator, like:
var errors = $$("[id$=Error]");
expect(errors.getText()).toEqual([
    "Employment Error happened",
    "Some other error"
]);

Here errors would locate the elements with id attributes ending with "Error".

A: Protractor methods return promises. So it's safer to use promises every time because they are asyn operations.
Try the following code:
const locators = {
    emp: element(by.id('employmentError')),
    occ: element(by.id('occupationError')),
    stat: element(by.id('statError')),
    show: element(by.id('showError'))
};
var promises = [], texts = [];
var els = element.all(by.css('selector'));
els.forEach(els, function(el) {
  els.getText().then(function(text) {
    texts.push(text);
  });
});
for (var i in locators) {
  promises.push(locators[i].getText());
}
expect(protractor.promise.all(promises)).to.become(texts);


text:
Q: Binding inside a NSTableCellView I'm using a NSOutlineView view based and i want to bind a NSSlider and a NSTextfield to a NSDictionary key (@""duration"). The dictionary is a property of my NSTableCellView subclass. I'm facing an error when trying to setup the binding :
The error :
*** Terminating app due to uncaught exception 'NSUnknownKeyException', reason: '[<NSApplication 0x100506400> addObserver:<NSTextValueBinder 0x102609a90> forKeyPath:@"info.duration" options:0 context:0x10260c820] was sent to an object that is not KVC-compliant for the "info" property.'

.h:
#import <Cocoa/Cocoa.h>

@interface ObjectFileTableCellView : NSTableCellView {
    NSTextField *_textFieldFilePath;
    NSTextField *_textFieldDesription;
    NSButton *_checkBox;
    NSDictionary* _info;

    NSSlider*  _slider;
    NSTextField* _labelStartTime;
}

@property(retain) IBOutlet NSTextField *textFieldFilePath;
@property(retain) IBOutlet NSTextField *textFieldDescription;
@property(retain) IBOutlet NSTextField *labelStartTime;
@property(retain) IBOutlet NSSlider *slider;
@property(retain) IBOutlet NSButton *checkBox;

@property(retain) NSDictionary* info;

@end

.m :
- (NSView *)outlineView:(NSOutlineView *)outlineView viewForTableColumn:(NSTableColumn *)tableColumn item:(id)item{
    if ([[tableColumn identifier] isEqualToString:@"Files"]) {

        if ([item isKindOfClass:[OMN_Object class]])
        {

//DONE
- (NSView *)outlineView:(NSOutlineView *)outlineView viewForTableColumn:(NSTableColumn *)tableColumn item:(id)item{
    if ([[tableColumn identifier] isEqualToString:@"Files"]) {
    if ([item isKindOfClass:[OMN_Object class]])
    {
        OMN_Object *o = item;

        ObjectFileTableCellView *v = [outlineView makeViewWithIdentifier:@"FileCell" owner:self]; // File'S owner

                hide = NO;
                NSString* d = [o.fileInfoDetails valueForKey:@"duration"];
                [v.slider setMinValue:0];
                [v.slider setMaxValue:[d doubleValue]];

                NSString *val = [NSString stringWithFormat:@"%f", v.slider.doubleValue];
                [v.labelStartTime setStringValue:val];
                [o.fileInfoDetails setValue:val forKey:@"startTime"];
                v.info = o.fileInfoDetails;

    ...

My NSOutlineView view:

NSTableColumn:

NSTextField Binding Setup:

The wanted result :

How to setup the binding to get what i want ?

A: You're attempting to bind info.duration to the cell itself, not the text field, assuming that "File's Owner" is indeed your ObjectFileTableCellView.
Use labelStartTime as the controller key when you configure the binding.
Double-check your bindings configuration for the slider as well; you may have made a similar mistake.

A: As Said before, File's Owner.info.duration Make no sense because File's Owner is kind off class outlineview. The dictionary Info is a property off ObjectFileTableCellView.
I bound programmatically the NSTextfield to info.duration and it work great !


text:
Q: Change Action from Edit to View for product in magento 2 admin panel I have different users with different user roles.
I want to change the Edit option to View only for the users who have not added this product.
see attach image

How can I do that?
Allowing Edit to users who have added the product.
The rest can only view it.


text:
Q: Passing SSL traffic through corporate proxy using nginx I have done some resarch for this matter and there are some unaswered question regarding my issue, however I managed to solve half of what is needed (thanks to people on the site).
Scenerio:
I have Nginx as a reverse proxy in internal corporate network. I need to pass traffic to Internet behind corporate proxy.
Half of the solution:
To achive this, following works fine:
    server {
        listen 80;
        server_name myhost.com;

        location / {
             proxy_set_header Host google.com;
             proxy_pass http://corporateproxy:9999/;
        }
}

However, above solution does not use SSL between corporate proxy and google.com. Do you have any idea how to add SSL to this?
I have tried adding protocol or port to header but it is not working this way.
I cannot modify anything on the corporate proxy. It should work like this: the URL being accessed is with https it will be redirected to https; http to http. Unfortunatelly header that contains only dns name is treated as http request.
Unfortunatelly the simplest solution does not work because nginx does not respect http_proxy settings on RedHat Machine:
    server {
        listen 80;
        server_name myhost.com;

        location / {
             proxy_pass https://google.com/;
        }
}

Any help will be highly appreciated.


text:
Q: A little help with point set topology Can anyone give me an EXAMPLE of adherent point that is not an accumulation point or just opposite.

A: A point $x$ is an adherent point of a set $A$ if every open set containing $x$ contains a point of $A$; Thus, if $x \in A$, $x$ is automatically an adherent point of $A$. However, $x$ is an accumulation point of $A$ if every open set containing $x$ contains a point of $A$ other than $x$. Thus, to find an example of a set $A$ with an adherent point $x$ that isn't an accumulation point of $A$, you want a set $A$ that contains some point $x$ that is contained in an open set that otherwise misses $A$ completely.
A simple example in the real line is to let $A = [0,1] \cup \{3\}$ and $x=3$. $3 \in A$, so $3$ is an adherent point of $A$, but the open interval $(2,4)$ is an open set containing $3$ that does not contain any other point of $A$: $(2,4) \cap A = \{3\}$.
It should be clear from the definitions that every accumulation point of a set is also an adherent point: if every open set containing $x$ contains a point of $A$ different from $x$, then every open set containing $x$ certainly contains a point of $A$!

A: In the real numbers, letting $A=\{0\}$, $0$ is an adherent point of $A$ since every neighborhood of $0$ contains at least one point of $A$, namely $0$; but $0$ is not a limit point of $A$, since no neighborhood of $0$ contains points of $A$ different from $0$.

A: Well you can see the below link for an answer.

*

*http://www.physicsforums.com/archive/index.php/t-473352.html


text:
Q: return value from jquery function
Possible Duplicate:
jQuery ajax return value

I have this jQuery script:
$('#headerSubmit').click(function() {
    var source = $('#header').attr('value');
});

that gets the value attribute of the element and stores it in the source variable.
How do I return the source variable to use in the rest of the script?
Thanks.

A: As you would be setting the source variable after a click, any code that uses that variable should be executed only after such event. Therefore, you should paste your code right after it:
$('#headerSubmit').click(function() {
    var source = $('#header').attr('value');
    // Rest of the code here
});

Otherwise, the variable wouldn't be initialized before a click.
Edit: Note all other answers incite you to declare the variable on global scope. This is useless unless your code executes after a click since the variable would be null.

A: var source;
$('#headerSubmit').click(function() {
    source = $('#header').attr('value');
});

A: Define var source outside of this click script. and use like this :
var source;
$('#headerSubmit').click(function() {
    source = $('#header').attr('value');
});

In this way 'source' will have global scope, and can be used anywhere with the assigned value later on.

A: Declare 'source' as global.
That is..
var source;
//your piece of jquery code
$('#headerSubmit').click(function() {
   source = $('#header').attr('value');
});

A: If you want source to be used in the entire script, declare it outside the function:
var source = null;
$('#headerSubmit').click(function() {
    source = $('#header').attr('value');
});

A: You can return a variable with
 return source;

Sounds like you probably are just trying to call that variable later in the script.  This is a problem with scope.  If you take out the var and just declare
source = $('#header').attr('value');

You will be able to call that variable in other parts of your script.

A: The way you are using it is asynchronous. You are setting a callback which is triggered on the "click" event. To have it available to the rest of the script, you have two options.

*

*use a global variable. (using this is bad sometimes though)
var myGlobalVariable;
$('#headerSubmit').click(function() {
    var myGlobalVariable = $('#header').attr('value');
});

*Call the function that needs this value inside the callback.
function myAnotherFunction(val){
     alert("I received" + val + ". I will update my set of"
          +" variables without putting it as global variable");
}

$('#headerSubmit').click(function() {
    myAnotherFunction($('#header').attr('value'));
});

A: var source;
$('#headerSubmit').click(function() {
    source = $('#header').attr('value');
   return source;
});

A: To declare a variable in the global scope, you must initialize it before you try setting it in a function, otherwise the declaration is only applicable to the local scope.  If you get your scopes wrong then your references will be invalid and you can expose yourself to bigger issues.
In this case, you will be unable to reference the variables value elsewhere in your script as you are intending to do since the variable only exists within your function currently.
Per MDN:

When you declare a variable outside of any function, it is called a
  global variable, because it is available to any other code in the
  current document. When you declare a variable within a function, it is
  called a local variable, because it is available only within that
  function.

var source;
$('#headerSubmit').click(function() {
    source = $('#header').attr('value');
});


text:
Q: How to normalize feature vectors for concatenating I have two different feature vectors of completely different scale, which are to be used as training data for machine learning algorithm.
When I concatenate them,
should I scale and normalize them separately first and then concatenate?
Or should I concatenate them first and scale-normalize them together?

A: This is too broad question and must be answered carefully. What are your features? If you have categorical features, you are better to encode it in one-hot manner and then you may circumvent scaling problems. Also, it depends on a classifier you want to use downstream : SVM will not tolerate badly scaled and uncentered data, but XGBoost will do ( to some degree )
Without much details it is hard to know whether rescaling your data will improve the performance of your algorithms before you apply them. If often can, but not always.
A good tip is to create rescaled copies of your dataset and race them against each other using your test harness and a handful of algorithms you want to spot check. This can quickly highlight the benefits (or lack there of) of rescaling your data with given models, and which rescaling method may be worthy of further investigation.

A: As mentioned above you could train two separate classifiers on both the data. This is useful because say you have more faith in the CNN features than histogram based features then you give that classifier's prediction more weight in the final output. Once you concatenate the features you are unable to use make use of this prior knowledge.
If both features sets are equally informative with similar noise then concatenation should work fine as well.


text:
Q: Jenkins | Use method from an imported java class in a groovy script I want to be able to use a method from a Jenkins plugin via its java class
Just to point out I'm not a developer or a groovy/java expert - happy to learn!
The java class that my method is part of is com.cloudbees.jenkins.plugins.bitbucket.BitbucketSCMNavigator
From this I would like to use the method getRepoOwner()
What I've done is set my import and defined a new call to the class:
import com.cloudbees.jenkins.plugins.bitbucket.BitbucketSCMNavigator

def bbSCMNav = new BitbucketSCMNavigator()

When I run this I get the error below:
org.codehaus.groovy.runtime.metaclass.MethodSelectionException: Could not find which method <init>() to invoke from this list:
  public com.cloudbees.jenkins.plugins.bitbucket.BitbucketSCMNavigator#<init>(java.lang.String)
  public com.cloudbees.jenkins.plugins.bitbucket.BitbucketSCMNavigator#<init>(java.lang.String, java.lang.String, java.lang.String)

I've searched for the error above Could not find which method <init>() to invoke from this list
And I came across this ticket Could not find which method <init>() to invoke from this list on newInstance in groovy closure
Can't say that I entirerly understand the reply if it's helpful to me or not as I say I'm not a developer and groovy and java are relatively new to me but happy to understand if anyone can point me in the right direction with this
The goal of this exercise is to use the method during the run-time of a build to get the output of getRepoOwner() and use that in a variable to construct a URI
This question also seems similar to mine - Calling internal methods of Jenkins plugin (thinBackup)
But I'm not using maven or a pom.xml here
Cheers

A: Quick Answer
This error Could not find which method < init >() is related to a missing constructor.
Almost all internal jenkins class are ready to use in groovy.
In your case, BitbucketSCMNavigator does not have a default constructor. It have a constructor with one String argument.  Check this line
Explanation
I could replicate your error with another internal class  org.jenkinsci.plugins.workflow.cps.CpsGroovyShellFactory:
node {

   stage('internal') {
      org.jenkinsci.plugins.workflow.cps.CpsGroovyShellFactory obj =
      new org.jenkinsci.plugins.workflow.cps.CpsGroovyShellFactory();
   }

}

    hudson.remoting.ProxyException: org.codehaus.groovy.runtime.metaclass.MethodSelectionException: Could not find which method <init>() to invoke from this list:
      private org.jenkinsci.plugins.workflow.cps.CpsGroovyShellFactory#<init>(org.jenkinsci.plugins.workflow.cps.CpsFlowExecution, boolean, java.lang.ClassLoader, java.util.List)

But, reviewing this class CpsFlowExecution I could see that CpsGroovyShellFactory does not have a default constructor. It have a constructor with one argument : CpsGroovyShellFactory(this)
So, If I instance the constructor with one argument, no errors appear.
node {

   stage('internal') {
      org.jenkinsci.plugins.workflow.cps.CpsGroovyShellFactory obj =
      new org.jenkinsci.plugins.workflow.cps.CpsGroovyShellFactory(null);
   }

}


text:
Q: can't get two connecting strings from XML (web.config)             XmlTextReader reader = new XmlTextReader(Window1.cfg.FSAddress);
            bool[] startreading = {false , false};
            while (reader.Read())
            {
                switch (reader.NodeType)
                {
                    case XmlNodeType.Element:    // Узел является элементом.
                        if (startreading[0])
                        {
                            if (reader.Name == "add")
                                if (startreading[1])
                                {
                                    id2.Text = reader.GetAttribute(1);
                                    return;
                                }
                                else
                                {
                                    id1.Text = reader.GetAttribute(1);
                                    startreading[1] = true;
                                    startreading[0] = false;
                                }
                        }
                        else
                        if (reader.Name == "connectionStrings")
                            startreading[0] = true;
                        break;
                    case XmlNodeType.EndElement:
                        if (startreading[1])
                            if (reader.Name == "add")
                                startreading[0] = true;
                        break;
                }
            }

I take first one but ... then happens something strange and I'm missing second

sorry for my english . btw - Im getting it not from web project.

A: You can use ConfigurationManager.ConnectionStrings to read the connection strings from the connection string section of your web.config file.
Or you can use ConfigurationManager.GetSection to get a section from the config file. If it is a predefined section you can cast it to this type, or you can implement your own custom section (see System.Configuration.ConfigurationSection for a sample).
Oh yes ... you have to include the System.Configuration into your references to work with these classes.

A: Why would you use SAX-based approach for reading configuration files? These are usually negligibly small, so loading entire document into an XmlDocument and then traversing it using XPath will be a much better solution.

A: Why try so hard?
Use this:
    ConfigurationManager.ConnectionStrings
Which is a collection of ConnectionStrings
Use ConfigurationManager.ConnectionStrings['nameOfTheConnectionString'].ConnectionString() to access the string itself.
ConfigurationManager lives in the System.Configuration namespace

A: I can't tell what you're trying to do. But maybe XPath will be a lot easier than SAX.


text:
Q: Gridview row back color not changing on text change event Asp.net C# Everybody. I know there are lots of similar question but still I am asking for it because the earlier query doesn't meet my requirement. I have look for it, please don't mark it as duplicate. I am trying to change the row color of the Gridview where txt_Id.Text is equal to the Id of the Gridview row. Below is the code :
protected void lnkSelect_Click(object sender, EventArgs e)
    {
        LinkButton lnkbtn = sender as LinkButton;
        GridViewRow gvrow = lnkbtn.NamingContainer as GridViewRow;
        int Id = Convert.ToInt32(GridView4.DataKeys[gvrow.RowIndex].Value.ToString());
        txt_Id.Text = Id.ToString();

        foreach (GridViewRow row1 in GridView4.Rows)
        {
            if (txt_Id.Text != "")
            {
                if (row1.Cells[1].Text.Equals(txt_Id.Text))
                {
                    row1.BackColor = System.Drawing.Color.Red;
                    row1.ForeColor = System.Drawing.Color.White;
                }
            }

        }


text:
Q: Specifying R1C1 in Excel using Variables in a For...Next Loop I'm trying to run a For Next loop that pulls specific numbers from specific cells in order to calculate total hours for a time card using Excel (it's the best program for what I'm using it for). I cannot, however figure out how to do it because I'm using R1C1 because I'm running the a count for the locations. I am not hidebound to this particular method of doing things, but a variation on it worked in Access (but I can't use Access for this because, reasons).
Attached is the code snippet I'm using.
For Weekday = 11 To 17  'Determine the day of the week by Row Reference (R1C1 format)
    For DayValue = 29 To 34     'Determin time input (Call, Meal In, Meal Out, Wrap, etc.) for day of the week
        WrkTimes(DayValue) = ActiveSheet.Cells.FormulaR1C1 = "R" & (Weekday) & "C" & (DayValue) 'Select the correct time input
    Next DayValue   'Process the next time input
    TotHrs(Weekday) = WrkTimes(34) - WrkTimes(29) - (WrkTimes(31) - WrkTimes(30)) - (WrkTimes(33) - WrkTimes(32))   'Calculate total hours for the day
    ActiveSheet.Cells(Weekday, 37) = TotHrs(Weekday)    'Display total hours for the day in the proper cell

Yes there is a Next command at the bottom of this loop, I just have other non-relevant code between this and the end. I'm getting the error on the DayValue lines

A: My first suggestion is to use
Cells(r, c)

Then you can put in your offsets such as
Cells(r-3, c)

You would just need to store the r and c values, which you've done as Weekday (r) and DayValue (c).

In the case if what you're looking at with the loop:
Cells(Weekday, DayValue).Value

This would give the value in the cell you've referenced.

Edit:
Suggestion from my comment:
Dim i as Long, j as Long, k as Long
For Weekday = 11 To 17
    i = Cells(Weekday, 34).Value 'Should allow you to have an output for each row
    For DayValue = 33 To 29 Step -1 'Saving column 34 outside of the dayvalue loop
        j = i
        k = Cells(Weekday, DayValue).Value
        i = j - k
    Next DayValue
    Cells(Weekday, 37).Value = i
Next Weekday

A: So, to clarify why I kept getting the subscript out of range (after following the suggestions from Scott and Phylogenesis), it turns out that my Weekday(x) was set for 7 when it should have been set at 17.
Thanks for all the help.


text:
Q: mediaplayer gives me null pointer exception I want my code to play a sound file at MAX volume when a button is pressed.  My code works perfectly fine just playing the sound file, but when I throw in originalVolume
int originalVolume = mAudioManager
                        .getStreamVolume(AudioManager.STREAM_MUSIC);
                mAudioManager.setStreamVolume(AudioManager.STREAM_MUSIC,
                        mAudioManager
                                .getStreamMaxVolume(AudioManager.STREAM_MUSIC),
                        0);

My program crashes upon the click of the button.
public class VolumeUp extends Activity {
    TextView text;
    int counter = 0;
    private AudioManager mAudioManager;
    MediaPlayer mediaPlayer = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        text = (TextView) findViewById(R.id.hello);

        text.setOnClickListener(new OnClickListener() {
            public void onClick(View view) {
                int originalVolume = mAudioManager
                        .getStreamVolume(AudioManager.STREAM_MUSIC);
                mAudioManager.setStreamVolume(AudioManager.STREAM_MUSIC,
                        mAudioManager
                                .getStreamMaxVolume(AudioManager.STREAM_MUSIC),
                        0);

                mediaPlayer = MediaPlayer.create(VolumeUp.this,
                        R.raw.policesiren);
                mediaPlayer.setScreenOnWhilePlaying(true);
                mediaPlayer.setLooping(true);// we set the sound to loop.
                mAudioManager.setStreamVolume(AudioManager.STREAM_MUSIC,
                        originalVolume, 0);
                mediaPlayer.start();

            }
        });

    }

A: From code you have shown above, mAudioManager is null all the time. So its obvious why you get NPE.
you forgot this line:
mAudioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);


text:
Q: Banked curve problem in another frame of reference How would you set up Newton's equation of motion for this problem (rolling without slipping in a circular path) using the frame of reference shown in the figure:

A: When setting up free-body diagrams as a precursor to solving a system of Newton's 2nd Law equations, you usually want to choose the reference frame of your system to be aligned with the system's acceleration. In other words, if the acceleration points to the right (as it does in your example), your reference frame needs to have one axis pointing along that direction (i.e. to the right), and the other axis should be perpendicular to it (e.g. up or down).
This convention means that one direction gets all of the acceleration and the other has no acceleration at all. As a result, the forces in one equation (namely, the perpendicular one) sum to zero simplifying the computation considerably.
In this case, that means you must (counter-intuitively) not make your coordinate system parallel and perpendicular to the inclined plane. Consequently, unlike a standard inclined plane problem, the weight vector does not need to be decomposed into components but the normal force vector does.


text:
Q: Depth First Search: Formatting output? If I have the following graph:
  Marisa  Mariah
       \  /
Mary---Maria---Marian---Maryanne
         |
Marley--Marla

How should be Depth First Search function be implemented such that I get the output if "Mary" is my start point ?
Mary
   Maria
       Marisa
       Mariah
       Marian
            Maryanne
       Marla
            Merley

I do realize that the number of spaces equal to depth of the vertex( name ) but I don't how to code that. Following is my function:
void DFS(Graph g, Vertex origin)
{
    stack<Vertex> vertexStack;
    vertexStack.push(origin);
    Vertex currentVertex;
    int currentDepth = 0;

    while( ! vertexStack.empty() )
    {
        currentVertex = vertexStack.top();
        vertexStack.pop();

        if(currentVertex.visited == false)
        {
            cout << currentVertex.name << endl;

            currentVertex.visited = true;
            for(int i = 0; i < currentVertex.adjacencyList.size(); i++)
                vertexStack.push(currentVertex.adjacencyList[i]);
        }

    }
}

Thanks for any help !

A: Just store the node and its depth your stack:
std::stack<std::pair<Vertex, int>> vertexStack;
vertexStack.push(std::make_pair(origin, 0));
// ...
std::pair<Vertex, int> current = vertexStack.top();
Vertex currentVertex = current.first;
int     depth        = current.second;

If you want to get fancy, you can extra the two values using std::tie():
Vertex currentVertex;
int    depth;
std::tie(currentVertex, depth) = vertexStack.top();

With knowing the depth you'd just indent the output appropriately.
The current size of your stack is, BTW, unnecessarily deep! I think for a complete graph it may contain O(N * N) elements (more precisely, (N-1) * (N-2)). The problem is that you push many nodes which may get visited.
Assuming using an implicit stack (i.e., recursion) is out of question (it won't work for large graphs as you may get a stack overflow), the proper way to implement a depth first search would be:

*

*push the current node and edge on the stack

*mark the top node visited and print it, using the stack depth as indentation

*if there is no node

*if the top nodes contains an unvisited node (increment the edge iterator until such a node is found) go to 1.

*otherwise (the edge iterator reached the end) remove the top node and go to 3.

In code this would look something like this:
std::stack<std::pair<Node, int> > stack;

stack.push(std::make_pair(origin, 0));
while (!stack.empty()) {
    std::pair<Node, int>& top = stack.top();
    for (; top.second < top.first.adjacencyList.size(); ++top.second) {
         Node& adjacent = top.first.adjacencyList[top.second];
         if (!adjacent.visited) {
              adjacent.visted = true;
              stack.push(std::make_pair(adjacent, 0));
              print(adjacent, stack.size());
              break;
         }
     }
     if (stack.top().first.adjacencyList.size() == stack.top().second) {
          stack.pop();
     }
 }

A: Let Rep(Tree) be the representation of the tree Tree. Then, Rep(Tree) looks like this:
Root
  <Rep(Subtree rooted at node 1)>
  <Rep(Subtree rooted at node 2)>
               .
               .
               .

So, have your dfs function simply return the representation of the subtree rooted at that node and modify this value accordingly. Alternately, just tell every dfs call to print the representation of the tree rooted at that node but pass it the current depth. Here's an example implementation of the latter approach.
void PrintRep(const Graph& g, Vertex current, int depth)
{
   cout << std::string(' ', 2*depth) << current.name << endl;
   current.visited = true;
   for(int i = 0; i < current.adjacencyList.size(); i++)
      if(current.adjacencyList[i].visited == false)
         PrintRep(g, current.adjacencyList[i], depth+1);
}

You would call this function with with your origin and depth 0 like this:
PrintRep(g, origin, 0);


text:
Q: HTML Multi-Page Form Issues (page is refreshing) I am having a problem with a multi-page form submission.  The problem is that the page is refreshing when I press the next page button.  I believe it is a return true/false problem, but I don't know where the issue is.  Here is the code:
$(document).ready(function () {
        var info = [];
        function showinfo() {
            for (i=0; i<info.length; i++) {
                $('#step3 ul').append(
                    $('<li>' + info[i] + '</li>')
                );
            };
        };
        $('#step1_btn').click(function() {
            $("input").each(function() {
                if (input.type != radio) {
                    info.push(this.name+':'+this.value);
                } else if ($('.radio').is(':checked')) {
                    info.push(this.name+':'+this.value);
                }
            });
            $('#step1').css('display','none');
            $('#step2').css('display','inherit');
            $('#progbar').attr('value',33);
            return false;
        });
        $('#step2_btn').click(function() {
            $("input").each(function() {
                if (input.type != radio) {
                    info.push(this.name+':'+this.value);
                } else if ($('.radio').is(':checked')) {
                    info.push(this.name+':'+this.value);
                }
            });
            $('#step2').css('display','none');
            $('#step3').css('display','inherit');
            $('#progbar').attr('value',66);
            showinfo();
            return false;
        });
    });

Not sure if that is all you need to see.  If you need to see the html as well, I can provide that.  Thanks in advance for any help you all can give.  I can read javascript fairly well when someone else writes it, but for some reason writing it myself ends up in catastrophe every time.

A: try event.preventDefault():
$('#step1_btn').click(function(e) {
   e.preventDefault();
   // your code here
   return false;
});


text:
Q: Get AD/LDAP user information I'm building a Firebase webapp that will be used inside a corporate environment using windows desktops and AD/LDAP. The webapp is hosted in the cloud outside the corporate network. The webapp needs to visualise some of the AD/LDAP user information like username and first name. Can this information be extracted by Firebase?
For clarity I don't need the user to be authenticated.
Regards

A: If I understand correctly your question, yes you can export the users declared in a Firebase project with the CLI authexport command, as a CSV or JSON file. See https://firebase.google.com/docs/cli/auth#authexport


text:
Q: ASP.Net MVC Html.Raw with AntiXSS protection I want to display user content in a java script variable.
As with all user generated content, I want to sanitize it before outputting.
ASP.Net MVC does a great job of this by default:
@{
  var name = "Jón";
}
<script> var name ='@name';</script>

The output for the above is:
Jón

This is great as it protects me from users putting <tags> and <script>evilStuff</script> in their names and playing silly games.
In the above example,I want sanity from evil doers but I don't want to HTML encode UTF8 valid characters that aren't evil.
I want the output to read:
Jón

but I also want the XSS protection that encoding gives me.
Outside of using a white listing framework (ie Microsoft.AntiXSS) is there any built in MVC function that helps here?
UPDATE:
It looks like this appears to achieve something that looks like it does the job:
@{
  var name = "Jón";
}
<script> var name ='@Html.Raw(HttpUtility.JavaScriptStringEncode(name))';

Will this protect against most all XSS attacks?

A: You'd have to write your own encoder or find another 3rd party one. The default encoders in ASP.NET tend to err on the side of being more secure by encoding more than what might necessarily be needed.
Having said that, please don't write your own encoder! Writing correct HTML encoding routines is a very difficult job that is appropriate only for those who have specific advanced security expertise.
My recommendation is to use what's built-in because it is correct, and quite secure. While it might appear to produce less-than-ideal HTML output, you're better safe than sorry.

Now, please note that this code:
@Html.Raw(HttpUtility.JavaScriptStringEncode(name))

Is not correct and is not secure because it is invalid to use a JavaScript encoding routing to render HTML markup.


text:
Q: Area Between Inscribed Circles and Rectangle I was reviewing past exam questions for a math competition known as UIL Calculator Applications when I stumbled across the following question:
A large amount of dough is rolled out and as many circular cookies as possible are cut from the rolled-out dough. The remaining dough is piled together, rerolled and more circular cookies are similarly cut. What percent of the original amount of dough is left over?
Here's my incorrect attempt, if you'd like:
First, I imagined that I was cutting one circle out of a square with side length $x$, with 4 points tangent to the circle. Therefore, the remaining area would be $$x^2-\pi(\frac{x}2)^2$$
Then, I imagined that I was cutting nine circles out of a square with side length $x$, with each circle tangent to the square and/or to adjacent circles. Therefore, the remaining area would be $$x^2-9\pi(\frac{x}6)^2$$ which is the same result as the first scenario.
So the percent of original amount of dough left over after 1 "cut" for any number of circles is $$\frac{x^2(1-\frac{\pi}4)}{x^2}\approx21.46\%$$ and after 2 "cuts" the percent of original amount of dough left over is $$(21.46\%)^2\approx4.61\%$$
According to the answer key, however, the answer rounded to 3 significant digits is $.867\%$ and I'm not sure as to how.

A: A grid of hexagons is more efficient than a grid of squares, using $\frac{\pi}{2\sqrt{3}}$ of the dough instead of $\frac{\pi}{4}$.


text:
Q: Dataframe for Apriori algorithm | Market Basket Analysis in R I will be grateful if somebody could tell me what am I missing in my code. I am trying to find association rules using apriori algorithm (arules package) in R. I am using R-3.2 version for MacOSX.
The problem arises when I am reading the dataset from a csv format into a transactions class object. I am using the following piece of code -
>Transac1 <- read.transactions(file="transactions.csv", format = "basket", sep=";", rm.duplicates=TRUE)

On inspecting the data frame, I am observing that the first element in all the rows is missing.
>inspect(Transac1[1:5])

items
1  {,
Milk}
2  {,
Shoes}
3  {,
Talc}
4  {,
Cable}
5  {,
Shoe Polish, Talc}

I am able to generate association rules in the end, but I think those are not correct (just because of these blank elements). Can anyone understand and tell me what is possibly the reason for this? The file that I use for reading has data in the requisite format for apriori algorithm.
Any leads would be highly appreciated.

A: @user2031612 please write your code when run apriori algorithm in R, because i have meet same problem because, it's my mistake when not set minLen parameter, you should tried put parameter minLen = 2. It will produce rule with no blank elements


text:
Q: I'm unable to install unicode-math package ubuntu 16.04 I've been struggled trying to install the unicode-math package manually since I don't know if there is another way to accomplish it.
So I downloaded the entire package from CTAN.
And I followed the instructions given in this post.
Manually install packages from dtx file on ubuntu
But after doing it and compiling a TeX archive with XeLaTeX, It stills giving the same error and LaTeX indicates that the .sty file is not installed.
So any help is appreciated.
PS. I'm using TexMaker as my TeX editor.
Greetings.


text:
Q: django url tag problem I have problem with url tag. I want to redirect to a function that is in for eg
project_name.forum.views.function. Here is how i try to create url
{% url forum.views.function %}

it gives me this error:
Caught ViewDoesNotExist while rendering: Tried forum in module project_name.forum.views. Error was: 'module' object has no attribute 'forum'

I added this url in urls.py(I can access it directly) What am I doing wrong?

A: The url tag is used to reference named urls. E.g.
url(r'^$',
    login_required(views.user_babies),
    name='babystats_user_babies'),

Then you use {% url babystats_user_babies %} (the url pattern name, not the view name)

A: It sounds more like an incorrectly set up URL conf. You get that error when you specify a view that doesn't exist.
The url tag failing gives you a failure to reverse url with params... message.
What does your URL conf look like? Does project_name.forum.views.forum exist?
I mean, I find it odd you can visit the page at all, but that's the first place I'd look.

A: I have seen this error before with django url reversing stemming from the urlconf being set up with a root like projectname.app.views.view instead of app.views.view, so it chokes on the reverse without the name of the project.
Another common issue would be that the url takes an extra parameter that can be blank, and it needs you to pass an empty string or whatnot.


text:
Q: How can I automatically use values from a higher-lever(master) visualization when creating a lower-level visualization (details) in Spotfire? I have several different store regions in a single table. Let's call them A, B, and C.
Right now, the master visualization shows the regions. When I drill down into a specific region, I can see all of the states within that region. The table that shows the states shows the unit percentage as out of 100%, but I want it to be out of the region's unit percentage.
Below is the region view and the current result I am gettting for the states view.
Current Result
I want to get the states view to look like this:
Desired Result
So esssentially, I want the units in a details visualization to automatically divide by the grand total of units in a master visualization in order to get a wholistic Unit % column.

A: Your details visualization will only contain data from the selection of your master visualization, therefore any calculations in your details visualization can only be based on this data.
However, you could store the value of all units, for all regions, into a property control Sum([Units])and reference it in your details visualization like Sum([Units]) / ${propControl} where here the units would only be for the selected region.


text:
Q: ForbiddenAttributesError on build with nested attribute Edit 1 : This is related to CanCan gem.
This is a nested_attributes issue. On single form the user can create an Account, a User account (as 'owner') and a Team --- all linked to the account.
The form works fine with the Owner-only nested attribute, but once I add the Team nested attributes I get an ActiveModel::ForbiddenAttributesError.
I've researched the build method for nested models, and I think my syntax is correct in my accounts controller -- note the difference between has_one and has_many.
I really hit a wall...
Thanks for any help.
My models are :
class Account < ActiveRecord::Base
  RESTRICTED_SUBDOMAINS = %w(www)
  has_one :owner, class_name: 'User'
  has_many :teams
  validates :owner, presence: true
  validates :name, presence: true
  accepts_nested_attributes_for :owner, :teams

class Team < ActiveRecord::Base
  acts_as_tenant :account
  has_many :users
  belongs_to :account
  validates_inclusion_of :active, :in => [true, false]
  validates :name, presence: true, allow_nil: false
  validates_uniqueness_to_tenant :name

class User < ActiveRecord::Base
  devise :invitable, :database_authenticatable, :registerable,
     :recoverable, :rememberable, :trackable, :validatable
  acts_as_tenant :account
  belongs_to :team
  validates :lastname, presence: true, allow_nil: false
  validates :firstname, presence: true, allow_nil: false
  validates_uniqueness_to_tenant :email

  def self.current_id
    Thread.current_user[:user_id]
  end

My Accounts controller :
Edit 2 : if I comment out load_and_authorize_resourceit works.
class AccountsController < ApplicationController
  skip_before_filter :authenticate_user!, only: [:new, :create]
  #load_and_authorize_resource

  def new
    @account = Account.new
    @account.build_owner
    @account.teams.build
    #@account.teams.build(teams_params)  # tried this
    #@account.teams.build(params[:team])  # tried this
  end

  def create
    @account = Account.new(account_params)
    respond_to do |format|
     if @account.save
       format.html { redirect_to new_user_session_url(subdomain: @account.subdomain) }
     else
       format.html { render action: 'new' }
       format.json { render json: @account.errors, status: :unprocessable_entity }
     end
   end
 end
 Private
  def account_params
    params.require(:account).permit(:subdomain, :name, :logo, :owner_id, :time_zone, :default_language, :publish_to_wall_new_employee, :publish_to_wall_new_document, :publish_to_wall_published_schedule, :publish_to_wall_modified_schedule, teams_attributes: [:id, :name, :account_id], owner_attributes: [:lastname, :firstname, :email, :password, :password_confirmation, :account_id])
    end
 end

In my Teams controller, I have :
private
  def team_params
    params.require(:team).permit(:name, :active, :account_id)
  end

In my Users controller, I have :
private
   def user_params
     params.require(:user).permit(:firstname, :lastname, :email, :account_id, :avatar, :role, :street_address, :zip, :city, :phone, :dob, :pob, :citizenship, :team_id, :contract_time)
   end

My form is quite long, so this is just an excerpt :
 <%= form_for @account, html: {id: 'accounts-new-form'} do |f| %>
    <%= f.fields_for :owner do |o| %>
      <%= o.label :firstname, "Your firstname" %>
      <%= o.text_field :firstname, options = {class: "form-control required", rel: "FirstName"} %>
    <% end %>
    <%= f.label :subdomain, "Choose a subdomain" %>
    <%= f.text_field :subdomain, options = {class: "form-control required", rel: "Subdomain"} %>
    <%= f.fields_for :teams do |t| %>
      <%= t.label :name, "Choose a team name" %>
      <%= t.text_field :name, options = {class: "form-control required", rel: "Team"} %>
    <% end %>
<%= f.submit class: 'btn btn-primary' %>

Below beginning of full error message :
Processing by AccountsController#create as HTML
  Parameters: {"utf8"=>"✓", "authenticity_token"=>"UTdyTCq3hpxR/w23JzJnWYozOLQhxpfOZPLql6b5+m8=", "account"=>{"owner_attributes"=>{"firstname"=>"john", "lastname"=>"Doe", "email"=>"john@test8.com",     "password"=>"[FILTERED]", "password_confirmation"=>"[FILTERED]"}, "name"=>"Test8 Inc", "subdomain"=>"test8", "teams_attributes"=>{"0"=>{"name"=>"Test8-Team-A"}}}, "commit"=>"Create Account"}
  Account Load (0.6ms)  SELECT  "accounts".* FROM "accounts"  WHERE "accounts"."subdomain" IS NULL  ORDER BY "accounts"."id" ASC LIMIT 1
  Account Load (0.4ms)  SELECT  "accounts".* FROM "accounts"  WHERE "accounts"."subdomain" = '' LIMIT 1
Completed 500 Internal Server Error in 10ms

ActiveModel::ForbiddenAttributesError - ActiveModel::ForbiddenAttributesError:
  activemodel (4.1.1) lib/active_model/forbidden_attributes_protection.rb:21:in `sanitize_for_mass_assignment'
  activerecord (4.1.1) lib/active_record/attribute_assignment.rb:24:in `assign_attributes'
  activerecord (4.1.1) lib/active_record/core.rb:452:in `init_attributes'
  activerecord (4.1.1) lib/active_record/core.rb:198:in `initialize'
  activerecord (4.1.1) lib/active_record/inheritance.rb:30:in `new'
  cancan (1.6.10) lib/cancan/controller_resource.rb:85:in `build_resource'
  cancan (1.6.10) lib/cancan/controller_resource.rb:66:in `load_resource_instance'
  cancan (1.6.10) lib/cancan/controller_resource.rb:32:in `load_resource'
  cancan (1.6.10) lib/cancan/controller_resource.rb:25:in `load_and_authorize_resource'
  cancan (1.6.10) lib/cancan/controller_resource.rb:10:in `block in add_before_filter'
  activesupport (4.1.1) lib/active_support/callbacks.rb:440:in `block in make_lambda'
  activesupport (4.1.1) lib/active_support/callbacks.rb:160:in `block in halting'
  activesupport (4.1.1) lib/active_support/callbacks.rb:149:in `block in halting_and_conditional'
  activesupport (4.1.1) lib/active_support/callbacks.rb:166:in `block in halting'
  activesupport (4.1.1) lib/active_support/callbacks.rb:149:in `block in halting_and_conditional'
  activesupport (4.1.1) lib/active_support/callbacks.rb:166:in `block in halting'
  activesupport (4.1.1) lib/active_support/callbacks.rb:166:in `block in halting'
  activesupport (4.1.1) lib/active_support/callbacks.rb:229:in `block in halting'
  activesupport (4.1.1) lib/active_support/callbacks.rb:166:in `block in halting'
  activesupport (4.1.1) lib/active_support/callbacks.rb:86:in `run_callbacks'

Edit 3 : this is my ability.rb :
class Ability
  include CanCan::Ability

  def initialize(user)
     user ||= User.new # guest user (not logged in)
     can :create, Account

     # only owner can read & manage Account details
     can :manage, Account if user.role == "owner"
     cannot :read, Account if user.role == "employee"
     cannot :read, Account if user.role == "manager"

     # owner has full access to User details, manager can create/edit all User details, employee can read/list other User details
     # employee can edit own details except contract information
     can :manage, User if user.role == "owner"
     can :manage, User if user.role == "manager"
     cannot :update, User if user.role == "employee"
     can :update, User, :id => user.id  # a user can only update its own record
     can :avatar, User, :id => user.id  # a user can only edit own photo
     can :address, User, :id => user.id  # a user can only update its own address
     can :view_contract, User, :id => user.id # a user cannot updedit own contract infos
     can :read, User if user.role == "employee"
     can :home, User if user.role == "employee"
  end
end

A: In your fields_for for team:
<%= f.fields_for :teams do |t| %>

Apparently Rails is not generating teams_attributes for parameter, but just team. As you don't whitelist team, you get this error.

A: Your account_params method in AccountController is missing quite a few of the params you're trying to pass through it.  At the very least, :name, team: [:name], :subdomain and commit
Strong params is a pretty major source of confusion so let me try to explain what's actually happening, in the hope that it will help you solve your own problem, which isn't really about the ForbiddenAttributesError, but is about not understanding strong_params.
When you're creating an object based on user input, you can either restrict access at the model level or at the controller level.  In Rails 3, this was at the model level, with attr_accessible, but that had a very notable failure wherein somebody correctly guessed that they had left wide open the permissions to assign administrator privileges.  In Rails 4, this whole architecture was changed to force authorization at the controller level.  That change is what strong_params does.
Now, in every controller, you need to manually whitelist what's allowed through.  You do this with the require and permit methods that you're using in account_params.  You've probably noticed in tutorials and example code that every controller is doing something like mymodel_params.  Then, in your #create and #update methods, you invariably have a line like MyModel.new(mymodel_params) and @mymodel.update_attributes(mymodel_params).
This is the key to understanding strong_params
What's happening here is:

*

*In mymodel_params, you're writing down a list of parameters you want to whitelist.

*strong_params takes in the raw params hash from the browser and whitelists everything you said was safe.  It spits back a copy of your params hash with just the whitelisted params.  It also marks them specially to say "hey guys, it's cool, these are allowed"

*If you're passing anything not whitelisted in your params hash and try to update or create a new record with it, it will complain at you, throwing a ForbiddenAttributeError, just like it did here
So, with all that written down, the problem is that you're trying to build a record without telling Rails that it's all okay.  You can see that in the error message: it writes out a list of params you're passing, starting with account then a hash of owner_attributes, which then has team inside of that.  Compare that with your account_params and you can see a bunch of attributes are missing there and the structure is off.
tl;dr What Tiago said- your form is mis-structured.


text:
Q: Passing parameters into SQLite querys I'm currently trying to query my SQLite database using the following line of code:
public Cursor getExpenses(String username)
    {
        SQLiteDatabase db = this.getWritableDatabase();
        Cursor results = db.rawQuery("SELECT * FROM " + TABLE_EXPENSES + " WHERE username = " + username  , null);
        DatabaseUtils.dumpCursorToString(results);
        return results;
    }

The problem is the parameter username does not get passed into the query and instead I get returned all the data in TABLE_EXPENSES. If I leave out the quotes, I get no such column error. I was thinking of escaping the double quotes on username but apparently after some searching it seems like you can't escape the characters on SQLite? Hence, my question: How do I pass the parameter into the query.


text:
Q: What is the best way to safely process a login using AngularJS I'm new to Angular. I'm developing a simple login form whereby the username typed is compared to a username returned from a JSON query. If a match is found, the login is processed.
I feel the way I'm doing it isn't safe, am I right in thinking that the returned JSON string could be accessed through the browser's console?
I will be adding password check to this as well in the near future, once I understand how to properly go about this.
I would like pointing in the right direction to approach the issue of user login the Angular way.
app.js
angular.module('userApp', ["ngResource"]).

config(['$routeProvider', function($routeProvider) {
    $routeProvider.
        when('/login', {templateUrl: 'partials/login.html',   controller: LoginCtrl}).
        when('/loggedin', {templateUrl: 'partials/user-admin.html', controller: UserCtrl}).
        otherwise({redirectTo: '/login'});
}],[ '$locationProvider', function($locationProvider) {
    $locationProvider.html5Mode = true;
}]).

factory("User", function($resource) {
    return $resource("users/:userId.json", {}, {
        query: {method: "GET", params: {userId: "users"}, isArray: true}
    });
});

controllers.js
function LoginCtrl($scope, $route, $routeParams, $location, User) {
    $scope.users = User.query();
    $scope.loginUser = function() {
        var loggedin = false;
        var totalUsers = $scope.users.length;
        var usernameTyped = $scope.userUsername;

        for( i=0; i < totalUsers; i++ ) {
            if( $scope.users[i].name === usernameTyped ) {
                loggedin = true;
                break;
            }
        }

        if( loggedin === true ) {
            alert("login successful");
            $location.path("/loggedin");
        } else {
            alert("username does not exist")
        }
    }
}

A: Yes, you are right - this is not safe. NEVER do such things:

*

*NEVER store plain passwords in database (like "my_password_123"

*NEVER return any sort of sensitive information to the client and perform secret computations in JavaScript

*NEVER use simple password comparison (providedPassword == stored password) in server or client code

*NEVER use unsecure (http) layer - use safe one (HTTPS) instead

A proper way of doing this is following:

*

*Generate Hashed value of password on store it in DB. Make sure to use a strong hashing algorithm and salted passwords. At the time of writing this reply SHA-256 would be enough, but make sure to check if it's still considered safe.

*Wire SSL certificate to get HTTPS support, that way noone will spy on what user sends to your server

*User enters username+password and sends them to your code on the server. On the server you compute SHA-1 hash and compare it against the stored value in DB. Then you send back the RESULT of authentication to the client and keep the track of it on the server by persistent session.

Please keep in mind that most of this stuff is done by some security frameworks, like Spring Security. I wouldn't recommend doing it all from scratch, as the topic of security is vast and it's easy to make a mistake that can be used by malicious users.


text:
Q: Leaflet - Mouseover, Click and unclick Here is my working example http://members.upcpoczta.pl/w.racek/mapa.html
I would like to achieve is:

*

*Keep highlight on mouseover like it is now,

*When I click on highlighted bicycle route I would like to keep zoom to feature function but when it zooms in to a route I would like to keep highlighting until I click outside selected route or move a map.
Right now it zooms in nicely but when you move mouse highlighting disappears and you don't really know which route you clicked.

A: Ok, kind of hacky but see it as just a demonstration of how to accomplish something like that. Create a variable selected, and store the highlighted feature in there when the click handler gets fired. Now in your mouseout handler you need to check if a selection is made, see if it corresponds with the layer which fired the mouseout, if so, don't remove the highlighted style. Also you would need to write some logic in the click handler that if a selection is already made, it removes the highlight from it.
Code example:
    function highlight (layer) {
        layer.setStyle({
            weight: 5,
            dashArray: ''
        });
        if (!L.Browser.ie && !L.Browser.opera) {
            layer.bringToFront();
        }
    }

    function dehighlight (layer) {
        if (selected === null || selected._leaflet_id !== layer._leaflet_id) {
            geojson.resetStyle(layer);
        }
    }

    // Variable to store selection
    var selected = null;

    function select (layer) {
        // See if there is already a selection
        if (selected !== null) {
            // Store for now
            var previous = selected;
        }
        map.fitBounds(layer.getBounds());
        // Set new selection
        selected = layer;
        // If there was a previous selection
        if (previous) {
            // Dehighlight previous
            dehighlight(previous);
        }
    }

    var geojson = L.geoJson(rower, {
        style: function (feature) {
            return {
                weight: 2,
                opacity: 1,
                color: feature.properties.colour,
                dashArray: 3,
            };
        },
        onEachFeature: function (feature, layer) {
        layer.on({
            'mouseover': function (e) {
                highlight(e.target);
            },
            'mouseout': function (e) {
                dehighlight(e.target);
            },
            'click': function (e) {
              select(e.target);
            }
        });
    }
}).addTo(map);

Here's a working example on Plunker: http://plnkr.co/edit/fdTnA9CyJdJejiPq2q8M?p=preview
You would also need to write handler for map click or moveend or whatever ux you're trying to accomplish and in there check if there's a selection, then remove the highlight of it, but that's rather simple once you grasp the concept.