select from normalized tables using external references

Question: I am trying to create a normalized set of tables for my books and then
to select them ordering by either book title or authors.
I want to be able to have 'n' books per author, and 'n' authors per book.
The problem I want to solve is how to display my books and authors
ordered by tile or by lastname,firstname,middlename?
I started with a table like this with some 1441 entries.

create table books(
bookid serial,
title text,
firstname text,
lastname text);

I then created an authors table

create table authors(
authorid serial,
firstname text,
lastname text);

and populated it.
I then created a cross reference table

create table bookAuthor
(
     bookId INTEGER NOT NULL REFERENCES books(bookId),
     authorId INTEGER NOT NULL REFERENCES authors(authorId)
);

and
create unique index bookAuthor_unique_index on bookAuthor(bookId, authorId);

I then populated the bookauthor table with 1441 entries.
I am pretty sure the three tables are populated correctly.  I managed to
do several inserts into the authors table and then insert the correct cross relationshipes into the bookauthor table.
I am now stuck, I can't figure out how to display my books and authors
ordered by title or by authors names.
Am I going down the wrong path to create this ability to create N titles per author and N authors per book.
I did multiple searches for foreign keys, and multiple tables with nothing that seemed to resolve my problem.
I'm in a postgresql 9.x environment.
Answer: A join will be helpful.
select * from bookAuthor
inner join books on bookAuthor.bookId = books.bookid
inner join authors on bookAuthor.authorId = authors.authorid
order by books.title;

Or you can order by authors.lastname, authors.firstname instead.
Comment: ERROR:  argument of JOIN/ON must be type boolean, not type integer
LINE 3: inner join books on bookAuthor.bookId shucks I can't figure out how to format this reply..
Comment: I just edited the query as I forgot to actually join the columns on anything.  Are you running this in an sql editor or via a programming language?  That error you're receiving is foreign to me.
Comment: Test formating response ... `# select *  from bookAuthor inner join books on bookAuthor.bookId inner join authors on bookAuthor.authorId order by books.title ;`  Caused the following error message  `ERROR:  argument of JOIN/ON must be type boolean, not type integer
LINE 1: select *  from bookAuthor inner join books on bookAuthor.boo...
`
Comment: user258812, I was using psql to test your solution.  Thanks for your response.  Hmmm I just tried your updated solution  :)  it seems to be producing an output now.  I tried `select * from bookAuthor
inner join books on bookAuthor.bookId = books.bookid
inner join authors on bookAuthor.authorId = authors.authorid and authors.lastname='Patterson'
order by books.lastname limit 3;
`  that worked.
Comment: Yes!  I found a book by James Patterson with a 2nd author, added the 2nd author to the authors table, and added the cross links to the bookauthor table, then did a select and it got it right !!!!! supercalifradglisticexpidalocious !!!  I have been struggling with this for the better part of a week before posting here. I got both selects to work ( order by title, and order by author ).  Thank you ever so much.  Now on to trying to figure out how to make this work in my PHP code.  And how to prevent adding a duplicate author / misspelled


Testing model fit and running model validation plots for averaged models

Question: I have carried out a model selection process and averaged the models within the top 2 AICcs (using MuMIn in R).  I would like to test the model fit using both the chisq and validation/residual plots.  I'm unsure how to write the code for this, or indeed if it is even possible?
Any help would be appreciated.
Comment: Trying to understand at which step you are having a difficulty... Are you able to do that for other models rather than what `MuMIn` returns (so that it is `MuMin` that is the trouble)? Or are you unable to do that for any model (so that `MuMIn` itself is not the trouble)? What do you mean by *test the model fit using ... chisq*?
Comment: I can do both diagnostics for singular models using MuMIn and other packages.  The issue is how do you run diagnostics on averaged models.
Comment: How is an averaged model different from a simple model so that these tests cannot be readily conducted on it? Is it due to `MuMIn` model output belonging to some "weird" class in `R`, or is there also a conceptual difference? If it is just a "wrong class" problem, have you tried changing the class of the model to one that would fit your needs?
Answer: The issue is that an "averaged" model through MuMIn is actually stored as a list of the input models with a few new attributes. It is not actually the "output" model. Every time you print or summarize the model.avg output, it re-generates the averaged outputs from the list for display. You will need to manually generate the components of the diagnostic plots using predict and then do the math.


Prove that $f(x)=0$ has no repeated roots

Question:
$$\text{If } f(x)=\frac{x^n}{n!}+\frac{x^{n-1}}{(n-1)!}+\cdots+x+ 1\text{, then show that } f(x) = 0\\ \text{ has no repeated roots.}$$

I tried solving this question and I think I have come up with a proper answer. I need some verification.
My solution/attempt
First, we need to prove a theorem.

Theorem 1: If a polynomial function $f(x)$ has a repeated root (say $a$, i.e. $f(a)=0$), then $f'(a)=0$.

Proof:
We assume that $f(x)$ has a degree of $n \geq 2$.
Since $a$ is a factor of $f(x)$, we can write:
$$f(x)=(x-a)^m\cdot h(x) \tag{1}$$
where $2  \leq m \leq n$ and $h(x)$ is a polynomial of degree $n - m$
On differentiating $(1)$, we can write
$$f'(x) = m(x-a)^{m-1}\cdot h(x) + (x-a)^m\cdot h'(x)\tag{2}$$
Plugging in $x=a$, we obtain
$$f'(a)=0+0=0$$
Thus, theorem 1 is true.
Now, from the question, we have
$$f(x)=\frac{x^n}{n!}+\frac{x^{n-1}}{(n-1)!}+\cdots+x+ 1\tag{3}$$
If we plug in $x=0$, we get $f(0)=1 \neq 0$, for any value of $n$. Hence $0$ is not a root of $f(x)$.
On differentiating, we get
$$f'(x)=\frac{x^{n-1}}{(n-1)!}+\frac{x^{n-2}}{(n-2)!}+\cdots+x+ 1\tag{4}$$
From $(3)$ and $(4)$, we obtain
$$f(x)-f'(x)=\frac{x^n}{n!} \tag{5}$$
Suppose $c \neq 0$ is a root of $f(x)$. Then from $(4)$, we have
$$f'(c)=-\frac{c^n}{n!} \neq 0\tag{6}$$
Hence, from theorem 1, we can conclude that $f(x)=0$ has no repeated roots.
Q.E.D.
My question
I am a beginner in this field. Did I do all the steps correctly? Are there any points I need to take care of?
Comment: It's great! I like especially that this avoids induction completely.
Comment: @Astrobleme my mistake, well good job!
Comment: Yes. The technique using the derivative is pretty standard when trying to prove that a polynomial does not have a repeated root.
Comment: Ihf's statement's been taken out of context.
Comment: I think you need to mention why $c = 0$ isn't a possible root, as you handle all cases except this.
Comment: @Mark I did. Right after $(3)$. I said that $f(0)=1 \neq 0$
Answer: Let $e_{n}(x)=\sum_{k=n+1}^{\infty} {x^{k}\over{k!}}$, therefore $f_{n}(x)=e^{x}-e_{n}(x)$. To find repeated roots we must solve $f_{n}(x)=f_{n}^{'}(x)=0$ which means $e_{n}(x)=e_{n}^{'}(x)=e^{x}$. Also differentiating $e_{n}(x)$ gives us $e_{n}^{'}(x)=\sum_{k=n+1}^{\infty} k{x^{k-1}\over{k!}}=\sum_{k=n}^{\infty} {x^{k}\over{k!}}=e_{n-1}(x)$. Therefore we have $e_{n}(x)=e_{n-1}(x)$ to solve, which gives us the only answer x=0 which is incorrect when applying it to $f_{n}(x)=0$, and this is what we needed to prove.
Comment: That's a very interesting method!
Comment: That's kind of you!
Comment: @MostafaAyaz very nice solution!


How do I get the user name of the user profile page that is being visited?

Question: I created a module and I need to use the user name of the user's profile being viewed.
How do I call/get it?
Answer: You can load a user object like this :
<code>$current_user = menu_get_object('user', 1);
$username = $current_user->name;
</code>
Reference of menu_get_object function.
Answer: If it's the user that's currently visiting your website that your looking to display then this code can be used.
<code> global $user;
 print $user->name;
</code>


VSTS build step changes log trails

Question: In VSTS builds, is there a way I can know who have make changes in build steps?
Can I get history builds?
The reason for this is, we have a big team. Many time it happens that someone changes the build step for some reason and we never know who made the changes and why.
Like in git repo, we know which file is changed by who and why (in comments).
Answer:
In VSTS builds, is there a way I can know who have make changes in build steps? Can I get history builds?

The answer is yes. You could check the History of the build definition:

Click on the three horizontal dots and we will get an option compare difference, through which we can know the details of the pipeline modification. If the modifier adds a note when saving the modification, we can also know the reason for the build pipeline modification.

VSTS build step changes log trails


Creating interaction variables - Do we always have to "center" the variables first?

Question: I have a multiple regression model (in R) that looks as follows:

The model attempts to find the relationship between TV advertising and Radio advertising (dollars) on sales. I'd like to also create an interaction variable between TV and Radio. I was reading the following article on how to do this, and the author states that the two variables involved in the interaction must be "centered" first (to avoid multicollinearity) before combining them into an interaction variable. Is this always necessary (especially if I already know the two variables have little correlation)? If this is generally necessary, can the R scale() function be used to standardize each variable?
Comment: Although on a slightly different tack this Q&A might help http://stats.stackexchange.com/questions/65898/why-could-centering-independent-variables-change-the-main-effects-with-moderatio?rq=1
Answer: Regarding your first question, whether centering is always necessary with interaction main effects:
Few things are always necessary. Centering can help if there is multicollinearity, which can occur regardless of the initial (lack of) correlation between the interaction terms. The VIF test can tell you if you need to worry about collinearity if it is greater than (depending on source) 2.5 - 5. In R, after you fitted a model with interaction, just do vif(model.fit). If multicollinearity is a problem, it isn't a problem if it occurs on control variables - it only affects the collinear terms, not the others. Last thing, centering also helps comparing the regular and interaction models, since the meaning of the coefficients remain mostly the same, since 0 is the mean. For more information and examples, see this good post on interaction terms and centering.
Regarding your second question, whether scale() could work instead:
Yes... And not exactly. Sure, scaling coefficients also centers them, but it also removes their meaningful units. No longer for each dollar, but for each increase in a standard deviation in the dollar amount. Not very convenient for interpretative purposes. It is better just to center them by removing the mean from the observations, or like so (actually using the scale() function, but without the standardization, which is what the scale=FALSE does):
CaseStudyData$TV_cntrd <- scale(CaseStudyData$TV, scale = FALSE)


Product of values of the derivative of a polynomial at its roots

Question: Let $K$ be a field and $f(x) \in K[x]$ be irreducible and separable, with distinct roots $\alpha_1, \ldots, \alpha_n$. In my notes for my algebraic number theory class, I see the equality
$$
\prod_{i=1}^n f'(\alpha_i) = \prod_{j \neq i} (\alpha_i - \alpha_j)
$$
where $f'(x)$ denotes the formal derivative. Where does this equality come from?
Comment: Hint: $f(x)$ factors as $(x-\alpha_1)\cdots(x-\alpha_n)$ in the algebraic closure $\bar{K}$.
Answer: As potla wrote,
$f(x)
=\prod_{i=1}^n (x-a_i)
$.
To get $f'(x)$,
use
$\ln f(x)
=\sum_{i=1}^n \ln(x-a_i)
$
so
$\dfrac{f'(x)}{f(x)}
=\sum_{i=1}^n \dfrac1{x-a_i}
$
or
$\begin{array}\\
f'(x)
&=f(x)\sum_{i=1}^n \dfrac1{x-a_i}\\
&=\sum_{i=1}^n \dfrac{f(x)}{x-a_i}\\
&=\sum_{i=1}^n \prod_{j=1, j\ne i}^n(x-a_i)\\
\end{array}
$
Note:
If you don't like the use of $\ln$,
you can prove this by induction on $n$
using the product rule.
Therefore
$f'(a_k)
=\sum_{i=1}^n \prod_{j=1, j\ne i}^n(a_k-a_j)
= \prod_{j=1, j\ne k}^n(a_k-a_j)
$
since all the other terms
(with $k \ne i$) have
$a_k-a_k$.
Therefore
$\prod_{k=1}^n f'(a_k)
= \prod_{k=1}^n \prod_{j=1, j\ne k}^n(a_k-a_j)
$.


How can I limit CloudFront downloads

Question: I'm looking to use Amazon's CloudFront to host some content in the near future. Currently, I'm keeping it very simple and I'm just uploading my content to S3 and then making a distribution available via Cloudfront.
However, because I have a limited budget, I'd like to be able to limit the number of downloads or the money spent on bandwidth. As far as I can see, I can't set any quotas or budgets like you can in Google's App Engine, so I'm looking for another way of doing this.
Has anyone had any experience doing this? One approach I'm thinking of is having to place a webserver with redirects in between, but that kind of defeats the simplicity of CF for me.
Answer: AFAIK, there are no quotas or budgets built-in to CloudFront either. However, you can create private, dynamic signed URLs that will limit access to your distribution. So, you can distribute unique URLs from your site with short lifetimes and when you reach your budget, stop. This is not the intended usage for CloudFront Private Content, but I think it might meet your need.

How can I limit CloudFront downloads


Como utilizar Python integrado com .CSV

Question: Bom dia. Tenho que ler um campo(linha) de um arquivo em .csv e preencher um determinado campo no sistema. Como devo fazer? Exemplo, meu .csv é massa de dados para o preenchimento de um cadastro.
Comment: Relacionado: [Leitura de arquivo CSV e armazenamento dos dados em um vetor](https://pt.stackoverflow.com/questions/201023/leitura-de-arquivo-csv-e-armazenamento-dos-dados-em-um-vetor)
Comment: Também leia [Como ler um arquivo CSV em Python?](https://pt.stackoverflow.com/questions/97269/como-ler-um-arquivo-csv-em-python?rq=1)
Answer: Vc pode fazer de varias formas, mas a mais usual e:
import csv
with open('214385.csv') as f:
   f_csv = csv.reader(f)
   headers = next(f_csv)
   for row in f_csv:
   # Process row
      print(row)

link: https://github.com/weltonvaz/stackoverflow/blob/master/214385.py
Exemplo de arquivo csv:
obs: a primeira linha e de cabeçalho
Symbol,Price,Date,Time,Change,Volume
"AA",39.48,"6/11/2007","9:36am",-0.18,181800
"AIG",71.38,"6/11/2007","9:36am",-0.15,195500
"AXP",62.58,"6/11/2007","9:36am",-0.46,935000
"BA",98.31,"6/11/2007","9:36am",+0.12,104800
"C",53.08,"6/11/2007","9:36am",-0.25,360900
"CAT",78.29,"6/11/2007","9:36am",-0.23,225400

link: https://github.com/weltonvaz/stackoverflow/blob/master/214385.csv
este exemplo foi tirado do livro: Python Cookbook --> http://chimera.labs.oreilly.com/books/1230000000393/ch06.html#_solution_94
Comment: Welton, boa tarde. Obrigado na resposta. Tenho o seguinte codigo:
Click("132356.png")
type("Aqui tenho que colocar as informações do .csv") Como fazer esta arte?
Comment: Não entendi, vc poderia explicar melhor.

Como utilizar Python integrado com .CSV


MySQL Syntax error when trying to reset Joomla password

Question: I'm trying to reset my Joomla admin password by executing the following code in MySQL:
INSERT INTO `jos_users` (`id`,`name`, `username`, `password`, `params`)
VALUES (LAST_INSERT_ID(),'Administrator2', 'admin2',
'd2064d358136996bd22421584a7cb33e:trd7TvKHx6dMeoMmBVxYmg0vuXEA4199', '');

INSERT INTO `jos_user_usergroup_map` (`user_id`,`group_id`)
VALUES (LAST_INSERT_ID(),'8');

When I attempt to execute it, I get the following error:
Failed to execute SQL : SQL INSERT INTO `jos_users` (`id`,`name`, `username`, `password`, `params`) VALUES (LAST_INSERT_ID(),'Administrator2', 'admin2',
'd2064d358136996bd22421584a7cb33e:trd7TvKHx6dMeoMmBVxYmg0vuXEA4199', ''); INSERT INTO
`jos_user_usergroup_map` (`user_id`,`group_id`) VALUES (LAST_INSERT_ID(),'8'); failed :
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'INSERT INTO `jos_user_usergroup_map` (`user_id`,`group_id`) VALUES (LAST_INSERT_' at line 1

Could someone tell me where my Syntax might be wrong? I'm using MySQL version 5.0.95.
Answer: Use back ticks (`) around column name password (password is a reserved work in MySQL) if you are not using. Don't use LAST_INSERT_ID() in the first query as you have not added any record to this table yet. The queries will be
INSERT INTO jos_users (`name`, `username`, `password`, `params`)
VALUES ('Administrator2', 'admin2', 'd2064d358136996bd22421584a7cb33e:trd7TvKHx6dMeoMmBVxYmg0vuXEA4199', '');

INSERT INTO `jos_user_usergroup_map` (`user_id`,`group_id`)
VALUES (LAST_INSERT_ID(),'8');

Make sure you run these queries in the same session.


Produce data extracts using day field for the Friday before the weekend

Question: Using TSQL on SQL Server...
I need to produce extracts that use a pay day column in a database that only holds the day number, for example 26 to produce extracts for the 26th day of the month with a twist if that pay day falls on a weekend then the data for that extract should be extracted the Friday before the weekend.
Has anybody attempted this and able to offer some ways of achieving this through TSQL?
Thanks
Comment: Are you always running this for the current month? Otherwise I cannot see how any logic is expected to guess what month you are running it for.
Comment: Hi, Yes this would be for the current month. The report would run Monday to Friday, any data from the next coupld of days needs to be produced on the Friday gone.
Answer: I'm assuming you have the month and year available too, in which case you can construct a real date, and get the day of week from it as a 1-based number starting at Sunday. So, 6 equals Friday. This will produce 5 for today, as Thursday = 5
SELECT DATEPART(dw, DATEFROMPARTS(2018, 07, 26)) AS [DayOfWeek]

EDIT:
I'll make another assumption, this time that this is somehow possible, like it's always run for the current month. This is a bit dodgy as it all falls apart if it's run too early or too late, but at least it's achievable.
SELECT  DATEPART(dw, DATEFROMPARTS(
    DATEPART(YEAR, GETDATE()),
    DATEPART(MONTH, GETDATE()),
    26)) AS [DayOfWeekThisMonth]

EDIT 2:
OK, with the understanding we are working on this month, we can do this:
DECLARE @PayDayNumber INT = 29; -- Replace this with a SELECT to get your value
SELECT CASE(DATEPART(dw, DATEFROMPARTS(DATEPART(YEAR, GETDATE()), DATEPART(MONTH, GETDATE()), @PayDayNumber)))
            WHEN 1 THEN @PayDayNumber - 2
            WHEN 7 THEN @PayDayNumber - 1
            ELSE @PayDayNumber
            END AS [WeekendSafePayDay]

For this month (August 2018) the 29th will return 29th. You can change DATEPART(MONTH, GETDATE()) for 9 to test September, which will return 28 because 29th September is a Saturday, or change it to 7 to test July, which will return 27 because 29th July is a Sunday.
Comment: Then I don't see how you can possibly achieve this. The 26th July is Thursday, the 26th August is Sunday. Without the month it's impossible to know which it will be
Comment: No, all I have is the pay day field with a two digit number - no other date fields.
Comment: I'm looking to report on "pay days" that fall on the weekend on the Friday before. Could I create my own table with dates?
Comment: Does this logic help?

F = Get Friday's date (day)
M = Using F, set Monday's date (M=F+3)
 Check if UC date is 0,
if true/yes, Set data_flag to "N"
else
    Check if UC date is between F & M
    If true/yes, set flag for pulling the data & use tenaltkey to pull the UC data that fall over the weekend
end
Comment: I've made another edit. Does that give you what you need?
Answer: You have said in today's comment above that you are assuming the current month.
First turn your payday day number into a proper date:
select dateadd(month,((year(getdate())-1900)*12)+month(getdate())-1,payday-1)
  as paydate

and then use a case statement against it:
case datename(weekday,paydate)
  when 'Saturday' then dateadd(day,-1,paydate)
  when 'Sunday' then dateadd(day,-2,paydate)
  else paydate
  end as paydateadjust

(Obviously these will need rewriting into a proper SQL statement. Date formula borrowed from Michael Valentine Jones' super useful SQL Server date function.)


Primary ideals in an Artinial local ring

Question: Let $(A,\mathfrak{m})$ be an Artinian local ring. Is true that the only primary ideals of $A$ are the powers of $\mathfrak{m}$?
I'm not able to prove this or to disprove it by counterexample. Can you help me?
Answer: Any proper ideal in a local Artinian ring is primary, this is because the radical of an ideal is the intersection of the prime ideals containing it, but in an Artinian local ring, there is only one prime ideal, so the radical of each ideal is maximal, hence the ideal is primary.
A different way to see this is to use another characterization of primary ideals:
An ideal $I$ in a ring $A$ is primary iff every zero divisor of $A/I$ is nilpotent. Since quotients of local Artinian rings are again local Artinian, it suffices to show that local Artinian rings have the property that every zero divisor is nilpotent.
We can show even more: every non-unit is contained in the maximal ideal which is nilpotent because the ring is Artinian, so every element is either a unit or nilpotent.
So it suffices to give an example of a local Artinian ring with an ideal that is not the power of a maximal ideal.
Consider $R=K[x,y]/(x^3,x^2y,y^2)$ for a field $K$, this is an Artinian local ring with the unique prime ideal $(x,y)$. We have $$(x,y)^2=(x^2,xy,y^2)=(x^2,xy)$$ $$(x,y)^3=(x^3,x^2y,xy^2,y^3)=0$$ Note that $(xy)$ is not equal to any of those powers of the maximal ideal.


Combination of distributions [reference request]

Question: Consider a random variable $X:\Omega \rightarrow E$ that combines multiple distributions:
$$X(\omega)\sim\begin{cases}
N(0,\sigma^2),\hspace{0.2cm} \text{if $\omega =0$}\\
\text{beta}(0,1), \hspace{0.2cm} \text{if $\omega =1$}
\end{cases}$$
Is there a concept for a  random variable that combines multiple probabilitiy distributions?
A good answer would be of the sort:

Yes these are called [something]-distributions, and are commonly used in sub-field x. A good reference for these is work y.

or

No, these are not useful because of [reasons], and have no formal treatment as far as I know
Answer: The term you are looking for is a mixture distribution.
Mixture distributions get used in situations when:

the observations involve a response to a choice (latent variable models),
the data generating process has multiple possible paths (e.g. one of N machines processes a request and the machines are not identical), or
when there are "structural" reasons to observe certain outcomes.

An example of the latter is that we could measure how much money people have invested. For many people, that amount would be zero while for people who have invested the amount would be a positive real number. The zeros exist and have non-negligible probability because there is a process for someone to opt into investing (probably by having enough money that they can afford to invest).
The Wikipedia page has a little on mixture distributions, but if you really want to read up on mixture modeling, I would read McLachlan and Peel's Finite Mixture Models or Mengersen, Robert, and Titterington's Mixtures: Estimation and Applications.


jQuery - After clicking parent of file input and triggering click event to file input it returns 'too much recursion'

Question: I have this in my jQuery:
$(document).on('click', '.upload-wrap', function(event)
{
    $('[name="uploads[]"]').trigger('click');
});

but it returns 'too much recursion' error! however it doesn't for my other elements like:
$(document).on('click', '.upload-image-wrap', function(event)
{
    $(this).next('[name="image"]').trigger('click');

});

I have used setTimeout either to fix this:
$(document).on('click', '.upload-wrap', function(event)
{
    setTimeout(function() {
        $('[name="uploads[]"]').trigger('click');
    }, 0);
});

But now firefox shows top of the page that 'Firefox prevented this site from opening 99999999 pop-up windows' in which 99999999 is increasing by miliseconds.
How can I fix it?
Thanks
Answer: If a .upload-image-wrap has the '[name="uploads[]"]' attribute, you might use not() to exclude the '[name="uploads[]"]' from triggering the delegated event:
$(document).on('click', '.upload-wrap:not([name="uploads[]"])', () => {
  $('[name="uploads[]"]').trigger('click');
});

Another option would be to check if the event was triggered by a human:
$(document).on('click', '.upload-wrap', (e) => {
  if (e.originalEvent !== undefined) $('[name="uploads[]"]').trigger('click');
});

Comment: Bingo :) Could you please tell me what delegated event is?
Comment: Your listener there is bound to the document, as you can see by the `$(document).on`, but it triggers only when a certain type of child is clicked. This is in comparison to a standard event listener, which, when bound to an element, runs when an event is triggered on that element itself. Eg `$('upload-wrap').on('click', ...` would add the listener to each `upload-wrap`, rather than to the `document`.


Clearing/Emptying office clipboard using C# Interop

Question: I am working on an application which on the click of a button will clear both the system clipboard and the office clipboard.
I have tried System.Windows.Forms.Clipboard.Clear() and the following
static class WinAPI
{
    [System.Runtime.InteropServices.DllImport("user32.dll", SetLastError = true)]
    static extern bool OpenClipboard(System.IntPtr WinHandle);
    [System.Runtime.InteropServices.DllImport("user32.dll", SetLastError = true)]
    static extern bool EmptyClipboard();
    [System.Runtime.InteropServices.DllImport("user32.dll", SetLastError = true)]
    static extern bool CloseClipboard();
    public static void ClearClipboard()
    {
        if (OpenClipboard(System.IntPtr.Zero))
        {
            EmptyClipboard();
            CloseClipboard();
        }
    }
}

Both of them seem clear only the system clipboard. Is there a way to extend this to office clipboard.
Answer: Per this question, the answer appears to be "no, not cleanly":

There has been no VBA support for manipulating the Office clipboard
  after Excel 2000. SendKeys is flaky, but it's the only way.

The "SendKeys" referred to is a "solution" where you send the necessary keystrokes or window messages -- assuming one is running, if not, you'll have to start one. There are also other ways to do that, like AutoIt. Unfortunately, all of these solutions are fragile and prone to break between versions of Office, because they rely on internal details of window names and appearances. Before you do this, make sure you're willing to accept the maintenance burden.
A better approach is probably telling whoever wants this application that it can't be done because Microsoft wants clipboard control to remain with the end user -- or, alternatively, that there already is a button for clearing the clipboard, and it exists in Office (Alt, H, FO shows it in my version). That doesn't always work, but when it does it saves you a ton of work.
Answer: You could copy a single space to the clipboard, if the other methods are troublesome?
Answer: You can try the solution presented here. It's meant for VBA but you can easily convert the code to C#.
Let me know if you need help.


list of parent nodes with a list of child referring nodes

Question: I would like to make a list of all parent nodes and under each parent display a list of child nodes that are referencing parent node. Something like drupal.org modules page, except in my case this is not with taxonomy. Using drupal 6 views 2
<code>example

parent1
-child1
-child2
-child3
more parent1

parent2
-child1a
-child2a
-child3a
more parent2
</code>
I am not able to display it using one view. Can anybody help me with some ideas? Thank you
Answer: probably you're using Node reference, right? If this is your case the solution is quite simple.
1) Create a view with a contextual argument for displaying all the children of a specified parent.
2) Use Display Suite module to attach this view on a custom display mode of parent nodes. With display suite you can pass the current nid to the view argument. You can also use Views Attach module ( https://drupal.org/project/views_attach )
3) create a view with the list of every parent and set to show the customized display created before.
I hope this will help you.
Comment: Another solution is to use modules like Viewfield or Views Field View to attach the first view (child nodes) to the second one (parents). Anyway the basic idea is the same.
Comment: Hi, I need to display such list on one page. Not based on parent argument. All parent nodes with child nodes listed. Or I am not understanding your answer? Hm, the views field view seem like an idea worth exploring. I try that and come back
Comment: The main view (the one created on third step) is a single page with all your parent and child nodes as you asked. The argument are used on the "embedded" views to display child nodes after each parent node.
Comment: Great idea with views field view. Works as you said. Thank you


selenium few WebDrivers one window [JAVA]

Question: I have problem with selenium JAVA.
I have something like this:
WebDriver driver1 = new FirefoxDriver();
WebDriver driver2 = new FirefoxDriver();

How to open driver1 and driver2 in one window and two tabs?
thanks in advance for your help
Answer: Robot r = new Robot();
r.keyPress(KeyEvent.VK_CONTROL);
r.keyPress(KeyEvent.VK_T);
r.keyRelease(KeyEvent.VK_CONTROL);
r.keyRelease(KeyEvent.VK_T);
Comment: Only create one instance of Webdriver
Comment: is a way that make two webdrivers? Or make one webdriver perform different tasks at the same time?
Comment: Yes you can make one webdriver perform 2 task
oDriver.get("http://site2.com");
--Perform operation on this site then
oDriver.findElement(By.cssSelector("body")).sendKeys(Keys.CONTROL +"\t");
--perform operation on 2nd site


Direct Product of Two Rings and 0-divisors

Question: Let $R = Z_4\times Z_3$ be the direct product of $Z_4\times Z_3$. Find all 0-divisors in $R$.
So far, I have these elements as the product of $Z_4\times Z_3$ : $(0,0)$, $(0,1)$, $(0,2)$, $(0,3)$, $(1,0)$, $(1,1)$, $(1,2)$, $(1,3)$, $(2,0)$, $(2,1)$, $(2,2)$, $(2,3)$
I also know that 0-divisors are the result of taking two non-zero elements in a ring and multiplying them yields the additive identity(0), aka $(Z_6, 2\cdot3 = 0)$.
In this case, would the 0-divisors be $(2,2)$ and $(1,3)$ since they are the 0-divisors for $Z_4$ and $Z_3$?
Answer: Notice $Z_{12}\simeq Z_3\times Z_4$ by the Chinese Remainder Theorem.  Maybe it would be easier for you to construct this isomorphism, find the zero divisors in $Z_{12}$, and then see what these elements map to in $Z_3\times Z_4$.
In particular, $2,3,4,6,8,9,10$ are the zero divisors of $Z_{12}$. Their images under the isomorphism are the zero divisors in $Z_3\times Z_4$.
Comment: Hmm, finding the zero divisors in $Z_{12}$ based on elements found in $Z_4$ x $Z_3$?

Won't I need 2*6 or 4*3 as elements?

In this case, (1,2), (2,1), (1,3), (3,1), (2,2) and (2,3) would give me 2, 3, 4, 6 when multiplied together. For example 1*2, 2*1 = 2
Comment: Sit down and work out the isomorphism explicitly.  The CRT *guarantees* these groups are isomorphic, but the obvious map might not be the correct one (hint: try testing $n\mapsto (n\pmod 3, n\pmod 4)$.
Comment: No problem!  Glad I could help out.
Comment: Let me phrase that properly and get back to you..
Answer: Since you've written down all twelve elements from the ring, you can for every element check by hand whether it is a zero divisor.
For example, $(0,1)$ is a zero divisor, because $(0,1)\times(1,0)=(0,0)$ and both $(0,1)$ and $(1,0)$ are nonzero.
On the other hand, $(1,1)$ is not a zero divisor, because $(0,0)$ is the only element which results in $(0,0)$ when multiplied with $(1,1)$.
$(2,2)$ and $(1,3)$ are no zero divisors, do you see why?
Comment: I don't think (0,1) can be a 0-divisor because there is a non-zero element though?

0-divisors are formed from the multiplication of two non-0 elements.
Comment: $(0,1)$ is nonzero, and $(1,0)$ is nonzero, and because they multiply to $(0,0)$, they are zero divisors.


Can't find block

Question: I have created a view in Drupal 8 that produces a block display. The block does not appear on the block layout page or custom block list.
In the block settings, it identifies the "Block category" as "Lists (Views)"  and claims that this is "The category this block will appear under on the blocks placement page." but it isn't there at all.
I wish I had more detail to include here but this seems really straightforward and I don't know what else to add. It simply isn't there. The preview on the block display in views is fine, everything is saved. I just can't find the block to add it to a region.
Answer: Click on the "Place Block" in the desired region and find it from there. More on block in D8 here.
Answer: View block will show up under "Disabled" section,on clicking "Place Block" we can find  block we created using view and specify the region u want to show it.

Can't find block


Singular value decomposition of positive definite matrix

Question:
Let $A$ be a positive definite matrix, and let $A = U \Sigma V^*$ be its singular value decomposition (SVD). Show that $U=V$.

What I have done: $A$ is Hermitian, so $A$ is unitarily diagonalizable, say, $A=WDW^*$ where $D$ consists of the eigenvalues (decreasing order). Also $D=\Sigma$ since $A$ is positive definite. From $A^2=AA^*=UD^2U^*$, and similarly I have $A^2=UD^2U^*=VD^2V^*=WD^2W^*$ so the column vectors of $U,V,W$ corresponds to same eigenvalues of $A^2$. And I'm now stuck. How could I proceed?
Comment: What if you took the square root of $A$ (namely, $W D^{1/2} W^*$) and applied the same reasoning to it.
Comment: @PeterShor Could you explain more details? I'm not sure yet.
Answer: As you already figured out, $A = U D V^*$ gives $A^2 = UD^2 U^* = V D^2 V^*$. Now, since positive Hermitian matrices only have one positive Hermitian square root, $A = UDU^* = UDV^*$, and since $U$ and $D$ are invertible, $U^* = V^*$.
Now, we need to show that positive Hermitian matrices have only one positive Hermitian square root. Suppose that $A$ is Hermitian. Consider the eigenspaces of $A$. Suppose that $Av = \lambda v$. Then $A^2 v = \lambda^2 v$. Since the map $\lambda \rightarrow \lambda^2$ is one-to-one on positive reals, this shows that $A$ and $A^2$ have exactly the same eigenspaces, with an eigenvalue of $\lambda$ in $A$ corresponding to an eigenvalue of $\lambda^2$ in $A^2$. This is enough to uniquely characterize $A$, given $A^2$. (We are implicitly using the fact that the vector space is a direct sum of eigenspaces of $A$. This is true since $A$ is Hermitian.)
Comment: Don't think about eigenvectors; think about eigenspaces. If $A$ has eigenspaces $S_1$, $S_2$, $\ldots$, $S_k$, with eigenvalues $\lambda_1$, $\lambda_2$, $\ldots$, $\lambda_k$, then $A^2$ has the same eigenspaces with eigenvalues $\lambda_1^2$, $\lambda_2^2$, $\ldots$, $\lambda_k^2$. Now, if you have two positive Hermitian matrices $A$ and $B$ with $A^2 =B^2$, they must both be diagonalizable, and have the same eigenspaces with the same eigenvalues. This means they are equal. They have the same eigenspaces because any eigenspace of $A$ (or $B$) is also an eigenspace of $A^2$.
Comment: If you don't like eigenspaces, here's another proof. We know that $A^2 v = \lambda^2 v$. Now, consider the vector $w = Av - \lambda v$. We have $A w = A^2 v - \lambda A v = \lambda^2 v - \lambda A v = -\lambda w$. Since $A$ has only positive eigenvalues, we know $w = 0$.
Comment: Your answer is much better than mine. +1
Comment: If $A$ has basis consisting of eigenvectors $v_i$, then $A^2$ has the same eigenvectors as basis. But conversely, if $A^2v_i=(\lambda_i)^2 v_i$, how can I show that $v_i$ is an eigenvector of $A$? I think you showed only one direction.
Comment: Thanks for great answers. This also helped me. http://math.stackexchange.com/questions/349721/square-root-of-positive-definite-matrix
Answer: Not sure how you could proceed. However, without loss of generality, suppose $\Sigma=(\sigma_1 I_{r_1})\oplus\cdots\oplus(\sigma_k I_{r_k})$ where $\sigma_1,\ldots,\sigma_k$ are distinct. If $A=U\Sigma V^\ast$ is positive definite, then so is $U^\ast AU=\Sigma W$, where $W=V^\ast U$. In particular, $\Sigma W$ is Hermitian and
$$
W^\ast\Sigma^2W = (\Sigma W)^\ast(\Sigma W) = (\Sigma W)(\Sigma W)^\ast = \Sigma^2.
$$
Therefore $W$ must be a block diagonal matrix $W_1\oplus\cdots\oplus W_k$ such that $W_j$ and $I_{r_j}$ have the same size and
$$
A=U\Sigma V^\ast = V(\sigma_1 W_1)\oplus\cdots\oplus(\sigma_k W_k)V^\ast.\tag{1}
$$
Since $A$ is positive definite, its eigenvalues coincide with its singular values (and hence they are positive). Now you may argue from $(1)$ that $W=I$ and hence $U=V$.
Comment: 1. How did you know that $W$ must be a block diagonal matrix? I found it hard by some calculations and writing matrices, but is there easy understanding?
Comment: 2. How can I conclude $W=I$ from (1)? It is neither eigenvalue decomposition nor SVD. I don't know what to do.
Comment: @Gobi 1. If $a\ne b$ and $\pmatrix{a&0\\ 0&b}\pmatrix{x&y\\ z&w}=\pmatrix{x&y\\ z&w}\pmatrix{a&0\\ 0&b}$, can you show that $y=z=0$? The block matrix case is similar. 2. With $W$ being unitary, what are the eigenvalues of $W_j$?
Comment: Since $W$ is unitary, eigenvalues are of absolute value 1. Let $\lambda$ be an eigenvalue of $W$ and $x$ be corresponding eigenvector, denoting $x=\pmatrix{x_1\\ \vdots \\x_k}$ then one of $x_j$ will be nonzero so it is the eigenvector of $W_j$ with eigenvalue $\lambda$. So the eigenvalues of $W$ will be same to the eigenvalues of $W_1,\cdots,W_k$. But what should I do now?
Comment: @Gobi The two sides of equation $(1)$ gives a similarity relation. So, the eigenvalues of $A$ are the eigenvalues of $\sigma_1W_1,\ldots,\sigma_k W_k$.


Android gui controller Unity3D

Question: How do I implement the controllers (joystick) into unity3d? I'm building a very barebones game where the player moves around the x and z axis. I want the joystick to show up on screen.
Answer: What exactly do you want to do? Unity already supports Joystick input: http://docs.unity3d.com/Documentation/ScriptReference/Input.html
You can define custom input methods in the InputManger settings of the editor.

Android gui controller Unity3D


In harmony: key or the flow?

Question: I play ambient music and my approach on creating chord lines is simple, just try to stick on the key and if I want to change the key then make it subtle.
But today I tried to create harmony lines which doesn't have a center key, just using enharmonic chords.
For example Chords: D -> F#m -> A -> C#m -> C#
Notes: DF#A -> F#AC# -> AC#E -> C#EG# -> C#FG#...And so on, it can be written forever. It sound good in my ambient context at least, because my role is to create space and not to show way (from A to B), but I want to know if I do something which has a name or theory behind it.
Can music be written not by functionality (for instance: I-IV-V), but only just the motion of the notes (as my line)?
I searched but I didn't find any written/spoken material about this topic.
It's very interesting and I want to know more about this approach.
Comment: Well, that sort of does have a key. It's just not certain exactly what key it is. It could be D minor or F major or A minor or C major or G minor or Bb major. If you repeat that pattern of a Dm chord and then an F major chord and back and forth, then it will sound like a chord progression in the key of D minor. Aside from all of that, this question is a bit broad. The question really needs a complete explanation of keys and chords and how they work, and that's a lot for a Stack Exchange answer.
Comment: You speak about harmony lines. I assume you play the chords in root position or at least the root tone in the bass.line. But it would be interesting what line you play in the upper voices as soprano and alto ?
Comment: J. S. Bach. He was a classical guy who sort of made writing *contrapuntally*; in coordinated melodies rather than chords. His music still has harmony, but it's laid out horizontally rather than vertically. And he's not the only person to do this, not by a long shot.
Answer: You do not have to analyze music using Roman numeral analysis.
Some music - Impressionism like Debussy - does not fit neatly into Roman numeral analysis.
Two common harmonic devices that often don't fit Roman numeral analysis are:

chromatic mediants
chord planing.

A chromatic mediant example would be like D minor to Bb minor. The Roman numeral analysis would be bvi but the important thing is that isn't one of the usual chords in minor. You can read more about chromatic mediants at Wikipedia.
Chord planing is when you use one chord type and just move it in parallel fashion. In your example C# major to D is a kind of planing, but usually you would have the parallel motion move more than just one step. When the motion involves only two chords by a halfstep as in your example you might describe it as a kind of appoggiatura chord.
Back to your example: D F#m A C#m C#
All but the last C# major fit into the key signature for A major where the first four chords would be A: IV vi I iii.
But then some might think it clever to say it fits into F# minor as F#m: VI i III v V
The problem with both - or any other attempt to label "the key" - is the harmony doesn't do anything to actually confirm a key. Specifically there isn't a cadence.
I think the important thing about the progression is that it moves mostly by ascending thirds. In the tonal major/minor key system that is a weak progression. By "weak" it really means not a strong way to define a clear key. It doesn't mean bad harmony. This kind of harmony can have a very gentle flowing feel that would not be found in music like Haydn's, but would seem to work well with ambient.
You might think of this kind of harmony as anti-cadential because it seems to avoid cadential patterns. But if you consider that a cadence functions to stop the flow of the music, it makes sense to take an anti-cadential direction in ambient music where you want the music to sort of float endlessly.
It may help to think in terms of diatonic harmony versus being in a key. You can select chords from a key signature like A major without formally being in the key of A. You might look into modern modal music or pan-diatonicism to get an idea of how that can work.
I sense you are already on the right track. You don't need to formally define a key. You do not need to approach harmony with only Roman numeral analysis. Try reading up on the modernists of the 20th century like Debussy, Ravel, Bartok, Stravinsky, Hindemith, Poulenc, Milhaud, etc. Stylistically some of that music is brutal and not at all like ambient, but it will give you a whole new set of analytically terminology to use when approaching your own music.
Answer: You're describing chords that are created not by reference to an overarching tonic, but that are created by linear motion and voice leading. In your sample chords, notice that each chord has two tones in common with the prior chord, and the other voice moved by step.
This is a common practice beginning in the nineteenth century. One really common example for music students is Chopin's E-minor Prelude:

By the time you reach the third measure, the chords quit making sense in E minor, and a Roman-numeral analysis is utterly nonsensical. But understanding the chords as byproducts of voice leading and linear motion suddenly clarifies what Chopin is doing.
Answer:
Can music be written not by functionality (for instance: I-IV-V), but only just the motion of the notes (as my line)?

Yes, music can be written in a wide variety of ways, and functional harmony is just one. As Todd Wilcox pointed out in his comment, a full explanation of keys, chords, and the various ways of moving between them is outside the scope of this forum.
What you are doing could be described as a type of "process music" - that is, you are coming up with a process for composition and allowing that process to play out. In your case, you are moving through chords by allowing one voice to move step-wise.
Some other terms you may want to research are "non-functional harmony" and "voice-leading."
Your process also sounds a bit like "Neo-Reimannian Theory," which is very complicated, but this video does a good job of trying to explain it:

Answer:
I play ambient music and my approach on creating chord lines is simple, just try to stick on the key

In some ways, I might think that would be the least promising approach to
creating ambient music!
Using chords diatonic to a key is likely to create typical tensions and resolutions that will grab listeners' attention and give the music a sense of driving forward. Very often, of course, that's what you want - except for when making ambient music!
(I do recognise that there are different styles within ambient, and that statement may be more applicable to some of those subgenres than others - and I don't mean to assume that you've been unsuccessful!)
As you've mentioned "just the motion of the notes", one approach you might want to look at is polyphony - a type of texture arising from simultaneous melodic lines. It's actually an older tradition than that of thinking in terms of block chords.
It's also very common for ambient music to be based more or less around a single chord for a whole piece, perhaps just moving the odd note here and there to create variations on the tonality.
Many ambient pieces use delay and reverb to cause interesting evolving concords and discords which wouldn't be apparent from looking at a score of the 'played' notes.
Another common ambient technique is to explore the line between timbre and harmony, and the way that the motion of the harmonics in a sustained note can create changes in the quality of the sonority produced. Or to put it another way - hold down a couple of notes and muck around with the knobs on the synth!
Comment: I usually skip the third note (making the chord non-minor/major) and use embelishments like the 9th.
And of course I use reverb and delay and pedal point.
Thanks the article, I will dig into it ^^
Comment: @Gery yep, open fifths are great for adding a bit of harmonic complexity without starting to make the harmony seem functional.  Suspended chords (sus2) and static extended chords (like minor ninth) can be great for this too.
Comment: @Gery oh and... have a listen to Tallis' *Spem in alium* for a nice bit of polyphony.
Comment: @Gery and to think there were those who thought polyphony 'evil' (at least according to that Wiki article! :)
Answer: The change of the last 2 chords is the change between the relative chords C#m - C#. The preceding prgogression could be considered as a chain of 4 third related chords round the center of A:
IV - vi - I - iii  - (V)
This is not so usual then the opposite direction:
iii - I  - vi  - IV
If you did continue the principle of third relation
the progression would be:
D -> F#m -> A -> C#m -> E -> G#mb5 -> Bm -> D
Is this what you mean?

In harmony: key or the flow?


Probability $Y>X$

Question: The lifetime $X$ of Machine 1 and the lifetime $Y$ of Machine 2 are independent and have density functions
$f_1(x)=\begin{cases}\frac{x}{2} & 0<x<2\\0 & otherwise \\ \end{cases}$
$f_2(x)=\begin{cases} \frac{2}{y^2} & 1<y<2 \\ 0 & otherwise\\ \end{cases}$
What is the probability that Machine 2 outlives Machine 1?
I tried setting the bounds to the bounds given in the piecewise function (i.e. $0<x<2, 1<y<2$) and I multiplied the two piecewise functions together, then took the integral and I got $1$. I don't believe that is correct, but these bounds were all I could think of. Maybe I messed up. Thank you for helping in advance!
Answer: in order to calculate
$$\mathbb{P}[Y>X]$$
you have to evaluate the purple area below

calculated as a double integral of $f_X(x)f_Y(y)$, due to independence
That is
$$\mathbb{P}[Y>X]=\int_1^2\frac{2}{y^2}\left[\int_0^y \frac{x}{2}dx  \right]dy=\frac{1}{2}$$
Answer: $$
P(Y>X)=\iint_{D}f(x,y)\;dxdy
$$
where $f(x,y)=f_1(x)f_2(y)$ and
$$
D=\color{red}{\{y>x\}}\cap [0,2]\times[1,2].
$$
If you missed the part $\{y>x\}$, the integral would be $1$.

Probability $Y>X$


expected value of least squares parameters

Question: I'm having some trouble with this equation from the least squares model.
$$E[\parallel  \mathcal {\hat {B}}  \parallel ^2] = [E\parallel  \mathcal {\hat {B}}  \parallel] ^2 + trace ( \text {cov} [\mathcal {\hat {B}}])$$
$$ =\parallel  \mathcal {\hat {B}}  \parallel ^2   +  \sigma_{e}^2 trace((X^{T}X)^{-1})$$
We have $\mathcal {\hat {B}}= (X^{T}X)^{-1}X^{T}Y$, so we should have
$$\text {cov} [\mathcal {\hat {B}}]=\text {cov}[(X^{T}X)^{-1}X^{T}(Y)]$$
$$=(X^{T}X)^{-1}X^{T}\text {cov}[Y]  (X^{T}X)^{-1}X^{T}$$
$$=(X^{T}X)^{-1}X^{T}\sigma_{e}^2I(X^{T}X)^{-1}X^{T}$$
$$= \sigma_{e}^2(X^{T}X)^{-1}X^{T}(X^{T}X)^{-1}X^{T}$$
I'm stuck at this point. A little clarity would be appreciated.
Comment: $\text{cov}(AX) = A\, \text{cov}(X)\, A^T$. You have written $\text{cov}(AX) = A\, \text{cov}(X)\, A$, which isn't even conformable. If you fix that you get a nice cancellation. This looks like routine bookwork and should carry the `self-study` tag (which helps notify prospective answers to give hints and guidance rather than just do the whole problem for you).
Answer: The non-random parts should form an outer product when you break them out of the covariance.
$$\begin{align*}
cov(\hat\beta) &= cov[(X^TX)^{-1}X^TY] \\
&= (X^TX)^{-1}X^T cov(Y) ((X^TX)^{-1}X^T)^T \\
&= (X^TX)^{-1}X^T cov(Y) X^{TT} (X^TX)^{-1T} \\
&= (X^TX)^{-1}X^T cov(Y) X (X^TX)^{-1} \quad\text{ (the pseudo-inverse is symmetric)}\\
&= (X^TX)^{-1}X^T \sigma_e^2 I X (X^TX)^{-1} \\
&= \sigma_e^2 (X^TX)^{-1}X^T  X (X^TX)^{-1} \\
&= \sigma_e^2 (X^TX)^{-1}
\end{align*}$$
so
$trace(cov(\hat\beta)) = \sigma_e^2 trace((X^TX)^{-1})$, which is how you get the second equality. The first equality comes from the law of total variance, but it looks like you already understood that part.


Use two versions of the same library

Question: I'm working in a iOS project that includes a static library created by another company.
The library include an old version of AFNeworking and I don't have any source files.
Now i need to use a more recent (and less bugged) version of afneworking, but i cannot include the same class twice in the project (of course) because all the "duplicate symbols".
I understand that it's impossible replacing the version included in the library, but how can i include another version along the old one?
There is a (easy) way to refactor the entire framework before include in my project?
thanks
Comment: i'm sorry but after some try with the trojanfoe solution (it works but is a bit dangerouse and very tricky) i ask my boss to request the original source code
Comment: hey... how u solved this ?? i have same problem.. please guide me
Answer: I'm afraid this isn't easy to do. Very few environments allow you to link against two separate versions of the same framework at the same time, and Xcode / iOS is not one of them.
As I see it, you have three options:
1) Link against their library and use the same version of AFNetworking they use.
2) Link against their library, and manually load the newer version of AFNetworking and pull symbols from it. Be warned: this will get ugly fast and future maintainers will wonder what you were smoking.
3) Get them to update their library.
On a side note, I don't know the circumstances here, but in general they should be providing you with sources. It's a very backwards practice to provide only a static (static!) library and no way to know what it's doing inside. You'll have to sign a software license agreement and whatnot to protect their interests.
Answer: You'll have to repackage the static library to remove the embedded AFNetworking files.
Unpack the library with:
$ ar x libwhatever.a

And re-package it, including all files except the AFNetworking object files:
$ ar cr libwhatever.a file1.o ... fileN.o

You will then have to link your executable with the new AFNetworking static library and hope that there haven't been API changes which will break the code in libwhatever.a.  If there are then I doubt there is much you can do.
Comment: This *may* work, but it's dependent on the ABI not changing between the version they linked against at compilation time and the one you're linking it against now. I wouldn't expect this to work if you're moving by more than a point version.
Comment: This seems dangerous, and there could easily be changes that would make this break.
Comment: Yeah - I mention that.  Worth a try though.
Comment: @MichaelMelanson The **ABI** changing?  That changes, like, never.
Comment: Not sure what you mean. I'm referring to the Application Binary Interface, which can definitely change between two versions of a library even when the API doesn't change. If the new version introduces, removes, or rearranges ivars, for example, then all code that accesses or modifies any ivar in the class may be broken.
Comment: @MichaelMelanson I would consider what I think you are referring to as an API change, not ABI change, which is what I consider to be how the stack is configured etc during a function call.  I mention that an API change will break this solution it in my answer.
Comment: I accepted your answer, i didn't know ar command and it's very usefull. But it seems very dangerous and the library is a fat library :) i'm scared that application can crash at runtime for some missing symbols.
Comment: @TheObjCGuy You shouldn't accept my answer if it didn't answer your question.  However I don't think there is a simple answer to this problem.
Comment: I think it's the right answer but this time i asked to the other company the source code (or a new binary). i'm still waiting ;)
Answer: The best and most proper way of handling this would be to contact the the creator of the static library and get them to resolve the situation. They could resolve it either by updating the embedded version of AFNetworking, removing their dependence on AFNetworking, or adding a prefix for their embedded copy of AFNetworking. The last one is probably a good idea anyway when a third party library embeds a different library, because otherwise it would be impossible to use two libraries simultaneously that both include the same third party library.
You could also refactor the copy of AFNetworking that you include yourself to change the names of classes to have a prefix, although this should be unnecessary, as the static library vendor should have done this themselves already.
Lastly, you could find a different library that accomplishes the same thing as your current one but that doesn't embed AFNetworking.

Use two versions of the same library


Using classes in nodes

Question: I need a little bit of guidance, I made a custom class and im trying to use it in a node but of course it throwing a white screen at me. So my question is how can I go about using a custom class for d7 so I can include the tag in my node via php.
I put this code in the template.tpl.php file and tried using it in my node but it then gave the white screen.
<?php class Colors {

  public function red_form() {
        echo 'color red is here';
  }

    public function blue_form() {
        echo 'color blue is here';
  }

    public function green_form() {
        echo 'color green is here';
  }

    public function purple_form() {
        echo 'color purple is here';
  }

    public function yellow_form() {
        echo 'color yellow is here';
  }
}

$colorforms = new Colors();

?>

and im using this in the node.
Text here here and here.

<?php $colorforms->red_form(); ?>

More text here here and here.

the output im trying to get using the code above is.
Text here here and here.

color red is here

More text here here and here

is there a module or something for this? or anything to that nature, im a little in the dark on this.
Answer: Quick fix: declare the class in template.php but instantiate it in your node template (if you check your php error log you probably had something like "Call to a member function red_form() on a non-object in ..." in it).  Also, I am assuming it's a typo that you had $colorforms and $color_form in your example above.
Comment: yeah it was a typo on my end when posting here, however I did try what you suggested and it is still just the white screen but i dont see any errors
Comment: I'd look in your php error log then to see what is going on then...
Comment: its outputting a Undefined variable error, but if I try my code in static php file it works fine.
Comment: must be something drupal7ish then because I put your class code in my drupal6 template.php and then the `$colorforms=new Colors(); $colorforms->red_form();` in another template and it worked fine.
Comment: Could you try $colorforms->red_form(); in a node and see if it still works for you. I really appreciate it.
Comment: Yes.  I put the class Colors declaration in my template.php and `$colorforms=new Colors; $colorforms->red_form();` in my node.tpl.php file and it echoed out color red is here.
Comment: no no not the node.tpl file, a actual node from a content type, like if your making a post for example.
Comment: huh?  like inside a text field?  if so, you are looking for a filter.  Otherwise, you've lost me or I am having a really bad case of the Mondays.
Comment: lol its cool and yes I mean in the text field.
Comment: If that's what you are doing, I'd say make it easier on yourself and just declare functions, eg, `function my_module_or_theme_name_red_form()` and then the basic php filter will work just fine and dandy.  But running php in there is just sooooo risky that I'd really look into alternative means like writing a custom filter that allows only specific functions to be run.  For example, you could write one that changes [redform] into the output of red_form() pretty easily.  http://drupal.org/project/customfilter will do it if you don't want to write your own.
Comment: i think thats perfect for what im looking for, thank you
Answer: Don't instantiate classes (or do any business logic) in your .tpl.php files: stuff in template files should be in its final, renderable form.
Instead, use a preprocess function in template.php:
// Replace MYTHEME with your theme's short name
function MYTHEME_preprocess_node(&$variables) {
  $variables['colorforms'] = new Color();
}

Then, in node.tpl.php, reference $colorforms1:
<?php $colorforms->red_form(); ?>

As an aside, consider breaking your class into a separate module: doing so would allow you to take advantage of Drupal's autoloader. Create the custom module, place the class in a separate file within the module's directory (let's say, includes/color.php).
In the custom module's .info file, add the following line:
files[] = includes/color.php

If you just want to take advantage of the autoloader and don't need any other custom functionality, just use a placeholder .module file:
<?php

/**
 * @file
 * This file is a placeholder.
 */

Note 1: Also consider not echoing out information in your class, but returning the string, to allow others to decide how to render the output:
public function red_form() {
  return 'color red is here';
}

and, assuming you used the solution mentioned here, use this in node.tpl.php:
<?php print $colorforms->red_form(); ?>

Comment: very true, but alas he wanted to put all of that in a text field and was really looking for a filter instead :)

Using classes in nodes


varnish cache not working for ajax calls

Question: if (req.url ~ "do_ajax.php" && req.request == "GET") {
      return (lookup);
}

I put this line inside the varnish.vcl config, but I get this header in the response header:
no-cache, must-revalidate, max-age=0

I also tried with:
if (req.url ~ "do_ajax.php" && req.request == "GET") {
      return (hash);
}

But varnish fails to restart unless I remove return (hash).
Now, I am wondering if there's a line in the varnish config file that forces all ajax calls to not accept cache, and the second thing I don't understand is why I am getting it in the response header, shouldn't it be the client that sends this in the request header instead? Why is the server returning this?
Answer: As mentioned in one of the other posts you made: you are probably using an outdated version of Varnish. That may explain why the VCL syntax is not working.
Please make sure you're on Varnish 6 or Varnish 7. See https://www.varnish-software.com/developers/downloads/#linux-packages for a list of install procedures depending on the Linux distribution you are using.
I also provided a VCL solution in one of the other posts you made.


drupal 7 error: table blocked_ips not found

Question: I have a running Drupal 7 site and wanted to restore it locally on development computer. But on localhost I keep receiving white screen in Firefox or Internal Server Error code 500 on Chrome.
Debugging shows that Drupal is running line 1895 of bootstrap.inc, which says:
$denied = (bool)db_query("SELECT 1 FROM {blocked_ips} WHERE ip = :ip", array(':ip' => $ip))->fetchField();

And just after this line it jumps to error handler, complaining about missing blocked_ips table. The blocked_ips table is not there on either site, the production site had no problem with it.
How to deal with this?
Answer: The blocked_ips table is created unconditionally by the system module...it should be there in any standard D7 install.
The process goes like this:

drupal_boostrap() calls drupal_bootstrap_page_cache() when in the DRUPAL_BOOTSTRAP_PAGE_CACHE bootstrap phase.
drupal_bootstrap_page_cache() calls drupal_block_denied()
drupal_block_denied() calls drupal_is_denied()
drupal_is_denied() contains the following line of code:
$denied = (bool) db_query("SELECT 1 FROM {blocked_ips} WHERE ip = :ip", array(':ip' => $ip))->fetchField();

So Drupal is expecting that table to exist. The only caveat is that if you have a variable called blocked_ips in the variable table the value from there will be used instead of the database being queried. Maybe you have that variable on the local version, and not on the live, and the issue is being masked by that fact?
If you didn't have any data in that table then it would be safe to copy the schema from an empty Drupal install and just create the table.
However, it might be worth checking the integrity of the rest of your data as it sounds like something's gone wrong either on your local copy or during the migration.
Comment: You're right, the table must be there in **D7** install. The problem was, that I logged to D6 database in phpmyadmin with almost identical name and exported from there into local D7.. sorry for the mess.
Answer: Your local development DB has been damaged. Luckily, this is not your production site. Just download your production database and import it into your development site.
To backup your dtabse you can use several tools: form phpMyAdmin to "drush sql-dump" drush command or the handy module Backup and Migrate. To import you the same tools (but use "drush sql-cli" and pipe the DB content if you use drush, instead of sql-dump, for obvious reasons).
Answer: In your settings.php file you have a blocked_ip index in the $conf array. If you uncomment this you bypass the 'blocked_ip' table query. It's possible that the production site has this change but not your local.
E.g. production settings.php (around line 440):
$conf['blocked_ips'] = array(
  '',
);

The array could also contain a list of IP's.
Your local settings.php:
# $conf['blocked_ips'] = array(
#   'a.b.c.d',
# );

Answer: I have also encountered such kind of situation when cloning my site into my local development server.
When I downloaded sql dump files for each module by module and imported them into my localhost, it did work for me.
Firstly, about white screen, check this answer. Then, Drupal will display errors on the screen.
Then, download sql dump files for each module by module, for example, the block module has 4 modules - block, block_custom, block_node_type, block_role. Export those 4 tables in a sql file and same for other modules. Most likely, tables in the same module have same prefix. Import them all into your localhost each by each including the system and variables tables.
Note that the cache tables should be exported and imported by structure only.


Elementos com Tipo de dados de Data e Hora

Question: Pessoal Gostaria de tirar uma duvida, devemos tratar de forma diferente campos que tem como tipo de dados hora e data digo em relação ao view, por que estou com um problema preciso plotar algumas data e horas em um tabela no meu view porem os campos que não são data e nem hora aparecem numa boa já os campos que tem como tipo hora e data aparecem como Object
<code>public static List<FolhaBean> bindingProperties(List<Folha> folhas) {

        List<FolhaBean> folhasBean = new ArrayList<>();

        folhas.forEach(folha -> {

            FolhaBean folhaBean = new FolhaBean(folha.getIdFolha(), folha.getData(), folha.getEntrada(),
                    folha.getSaidaAlmoco(), folha.getVoltaAlmoco(),folha.getSaida(), folha.getBancoHoraNegativo()
                    , folha.getBancoHoraPositivo(), folha.getVersion(), folha.getNomeUsuario());

            folhasBean.add(folhaBean);
        });

        return folhasBean;
    }
</code>
esse eh o bean que estou usando para trazer as informações
<code>@RequestMapping(value = REDIRECT_PAGE_CARREGAR, method = RequestMethod.GET)
   public ModelAndView showCarregar(Model model, HttpServletRequest request){

        usuarioBean= folhaService.findFetchAll();

        model.addAttribute("usuarioBean", usuarioBean);

        return new ModelAndView(REQUEST_MAPPING_PAGE_CARREGAR);
    }

    @RequestMapping(value = "/carregarDados", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
    public ResponseEntity<List<FolhaBean>> carregar() {

        List<Folha> folhas = folhaService.findFetchAll();

        List<FolhaBean> folhasBean = FolhaBean.bindingProperties(folhas);
        return new ResponseEntity<List<FolhaBean>>(folhasBean, HttpStatus.OK);
    }
</code>
e esse o controller.

o codigo que gera a tabela é esse
id="" data-url="${carregarFolha}" data-content-type="application/json" data-page-size="5" data-locale="pt-BR" data-minimum-count-columns="2" data-show-toggle="true" data-toggle="table" data-click-to-select="true" data-striped="true" data-show-columns="true" data-id-field="id" data-show-refresh="true" data-toolbar="#toolbar" data-query-params="paginar" data-select-item-name="" data-pagination="true" data-pagination-pre-text="Anterior" data-pagination-next-text="Próximo" data-checkbox-header="false" data-search="true" data-response-handler="responseHandler">    id Data Entrada Saida Almoço Volta Almoço Saida Banco Positivo Banco Negativo Usuario Licença
Comment: Pode adicionar o trecho de código problemático?
Comment: Objetos do tipo *Date/Time* costumam requerir a chamada de um método `format` para exibição. Não seria o caso?
Comment: então essa é a minha duvida não sei se precisa de um tratamento diferente
Comment: Como é exibido na sua view? Algo assim: `Tue Apr 11 13:41:42 GMT 2017`?
Comment: entao no momento é apresentado como Object apenas
Comment: não é apresentado nenhuma data nem hora
Comment: Não entendi. Poste uma imagem do problema, de preferencia.
Comment: veja que o id aparece normal mais os campos que sao data e hora fica como object
Comment: Isso parece ser um erro no JavaScript, não no Java. Qual é o código que gera esta tabela?
Comment: eu criei uma ideia de tabela dinamica e não tabela statica
Comment: Rapaz consegui resolver era apenas um problema de conversão agradeço demais a atençao
Answer: Já foi resolvido o problema esta na forma que eu estava acessando o objeto.
Eu estava acessando o objeto de forma direta, porem depois que dei uma olhada no json vi que precisava acessar o objeto e depois os atributos desse mesmo objeto, ex  usuario.nome.


android widget update period milles not working

Question: I am a new android developer trying to code a widget..
The "updatePeriodMillis" parameter tell the widget to call onupdate method after the given duraion but it doesn't happen so for me....
can some one please point my mistake.. here are my files
src/hellowidget.java
package de.thesmile.android.widget;

import android.appwidget.AppWidgetProvider;
import java.util.Random;

import android.appwidget.AppWidgetManager;
import android.content.Context;
import android.content.Intent;
import android.widget.RemoteViews;

public class HelloWidget extends AppWidgetProvider {
    int number =0;

    @Override
    public void onUpdate(Context context, AppWidgetManager appWidgetManager,
            int[] appWidgetIds) {

         number = (new Random().nextInt(100));
        for (int appWidgetId : appWidgetIds) {

            RemoteViews views = new RemoteViews(context.getPackageName(),R.layout.main);
            views.setTextViewText(R.id.TextView01, String.valueOf(number));
            appWidgetManager.updateAppWidget(appWidgetId, views);

        }

    }

}

xml/hello_widget_provider.xml
<?xml version="1.0" encoding="utf-8"?>
<appwidget-provider xmlns:android="http://schemas.android.com/apk/res/android"
android:minWidth="146dip"
android:minHeight="72dip"
android:updatePeriodMillis="1000"
android:initialLayout="@layout/main"
/>

main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:orientation="vertical"

android:layout_gravity="center"
android:layout_height="wrap_content">
<TextView android:text="@+id/TextView01" android:id="@+id/TextView01" android:layout_width="wrap_content" android:layout_height="wrap_content"></TextView><TextView android:padding="10dip" android:layout_marginTop="5dip" android:layout_gravity="center_horizontal|center" android:text="@string/widget_text" android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/widget_textview" android:textColor="@android:color/black"></TextView>

</LinearLayout>

android manifest
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="de.thesmile.android.widget"
android:versionCode="1"
android:versionName="1.0">
<application android:icon="@drawable/icon" android:label="@string/app_name">

<receiver android:name=".HelloWidget" android:label="@string/app_name">
<intent-filter>
<action android:name="android.appwidget.action.APPWIDGET_UPDATE" />
</intent-filter>
<meta-data android:name="android.appwidget.provider"
android:resource="@xml/hello_widget_provider" />
</receiver>
</application>
<uses-sdk android:minSdkVersion="7" />
</manifest>

Answer: The update time for widgets is forced to at least 30mins, to avoid poor programmed widgets to dry battery. Use AlarmManager to overcome this (see this post).
Answer: The updatePeriodMillis attribute defines how often the App Widget framework should request an update from the AppWidgetProvider by calling the onUpdate() callback method. The actual update is not guaranteed to occur exactly on time with this value and we suggest updating as infrequently as possible—perhaps no more than once an hour to conserve the battery.
If, you need to update more frequently (i.e 1 second in your case, which is not at all recommended). To do so, set an alarm with an Intent that your AppWidgetProvider receives, using the  AlarmManager. Set the alarm type to either ELAPSED_REALTIME or RTC, which will only deliver the alarm when the device is awake. Then set updatePeriodMillis to zero ("0").


User input box to pick column to perform action

Question: Okay i am very new to VBA coding.
I am working on a program that finds matches within a column and cuts and pastes them onto a separate sheet. I have working code that does this however i would like to broaden it so that there is an input box where user can pick which column for the program to search through, find matches, and cut and paste these onto sheet 2. Here is what I have, any help would be awesome. I know the code is a little clunky as well so any help cleaning it up would be awesome.
Thanks guys.
 Sub removedup()
Dim y As Integer
Dim x As Integer
Dim z As Integer
Dim unique() As String
ReDim unique(0)
Dim dups() As String
ReDim dups(0)
Dim dupFlag As Boolean
Dim dupCount As Integer
Dim rowcount As Integer
Dim sheet2indexer As Integer
Dim rColumn As Range

    Set rColumn = Application.InputBox("Pick Column", , , , , , , 8)

    MsgBox rColumn.Address

'Pre Sort

Cells.Select
    ActiveWorkbook.Worksheets("Sheet1").Sort.SortFields.Clear
    ActiveWorkbook.Worksheets("Sheet1").Sort.SortFields.Add Key:=Range(rColumn.Column)_
        , SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:=xlSortNormal
    With ActiveWorkbook.Worksheets("Sheet1").Sort
        .SetRange Range("A1:Z20000")
        .Header = xlGuess
        .MatchCase = False
        .Orientation = xlTopToBottom
        .SortMethod = xlPinYin
        .Apply
    End With

'get array of all unique names
dupFlag = False
x = 1
Do While Sheets(1).Cells(x, rColumn.Column).Value <> ""
    For y = 0 To UBound(unique)
        If Sheets(1).Cells(x, "E").Value = unique(y) Then
            dupFlag = True
        End If
    Next y
    If dupFlag = False Then
        ReDim Preserve unique(UBound(unique) + 1)
        unique(UBound(unique)) = Sheets(1).Cells(x, rColumn.Column).Value
    Else
        dupFlag = False
    End If

x = x + 1

Loop

rowcount = x - 1

'unique(1 to unbound(unique)) now contains one of each entry
'check which values are duplicates, and record

dupCount = 0

For y = 1 To UBound(unique)
    x = 1
    Do While Sheets(1).Cells(x, rColumn.Column).Value <> ""
        If unique(y) = Sheets(1).Cells(x, rColumn.Column).Value Then
            dupCount = dupCount + 1
        End If
        x = x + 1
    Loop
    If dupCount > 1 Then
        'unique(y) is found more than once
        ReDim Preserve dups(UBound(dups) + 1)
        dups(UBound(dups)) = unique(y)
    End If
        dupCount = 0
Next y

sheet2indexer = 0
'now we have a list of all duplicate entries, time to start moving rows
For z = rowcount To 1 Step -1
    For y = 1 To UBound(dups)
        If Sheets(1).Cells(z, rColumn.Column).Value = dups(y) Then
            'current row z is a duplicate
            sheet2indexer = sheet2indexer + 1
            Sheets(1).Rows(z).Cut Sheets(2).Rows(sheet2indexer)
            Sheets(1).Rows(z).Delete
        End If
    Next y
Next z

End Sub

Answer: If you want to select a range variable using an InputBox, you can supply the value 8 to its last argument. Then, you can select a Range (or an entire column) upon which to work.
For example:
Sub Test()
    Dim rColumn As Range

    Set rColumn = Application.InputBox("Pick Col", , , , , , , 8)

    MsgBox rColumn.Address
End Sub

Comment: And then for example in my macro above would i replace all of my current "E" s with rColumn?
Comment: @Uriahfb In the `.Cells` method, you can supply either a letter or a number for the column. If the user selected the entire column, the range address would be `E:E`, which doesn't work. Instead, convert it to a number by using `rColumn.Column`. The end result is something similar to: `.Cells(2, rColumn.Column).Value`. Let me know if more assistance is needed.
Comment: Okay so i just changed all of my code over to the rColumn.column but am getting an error saying the reference you typed is not valid or you did not provide a reference where one was required. i tried entering a number and letters and got the same error.@user3561813
Comment: Can you quickly debug to make sure that it's being read correctly? After setting `rColumn`, type a line such as `MsgBox rColumn.Address`. Make sure the message box contains the range you selected ("$E:$E" for example). If this works correctly, can you point to the specific line of code that throws the error?
Comment: It does not seem to be setting rColumn at all, it says the reference typed is not valid and does not give me anything in the message box. I have separated the piece of code u supplied above into its own macro to test it, and am getting the same error.
Comment: For the sake of completeness, can you post the separated piece of code for our review (it might be easiest to edit the original post and supply it in there).
Comment: Okay i updated the original post to where I have it now, when the user input box pops up and you enter a number or a letter into the box it does not accept it, saying reference you typed is not valid or you did not provide a reference where one was required
Comment: Ok, I understand the issue. When you supply type `8` as the last parameter to the `InputBox` function, the code is looking for a range object. You can set that in one of two way. (1) Physically select the cell or column by clicking on the cell or column header while the input box is open, or (2) typing in a valid cell or column reference (such as `E1` for cell `E1` or `E:E` for the entire column). Note, since we are interested in the column number, either of these options will return the same column number.
Comment: Okay we are close now im sure this is a quick fix but i am getting the error method 'range' of object '_global' failed on lines ActiveWorkbook.Worksheets("Sheet1").Sort.SortFields.Add Key:=Range("rColumn.Column") _
        , SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:=xlSortNormal
Comment: `rColumn.Column` returns a number (the column of the range). And we also know that `Range(...)` takes a cell/group of cells. Typing `Range(5)` throws an error. We have to fix this by enforcing some type of business rule that you'd have to define. For example, in this circumstance, you can reference `rColumn` directly. But what if the user only selected one cell. You can take `rColumn.EntireColumn`. What if you don't want the whole column, but only a range... Determine your need, and we can help from there.
Comment: It will always be an entire column that they select. I have changed my user input box to ask them to click on the column they would like to find matches in. After changing it to Range(rColumn.EntireColumn) i am getting the same error.
Comment: That's because `rColumn.EntireColumn` is already a `Range` object, so you don't have to wrap it with `Range()`. Simply type `rColumn.EntireColumn`.
Comment: Actually, since it's always an entire column, it would be a better practice to set the entire column into the `rColumn` variable from the start. Amend the `InputBox` code to read: `Set rColumn = Application.InputBox("Pick Col", , , , , , , 8).EntireColumn` . Now, `rColumn` is a Range object to refers to the entire column. When you need to use the numeric value of the column, you can still use `rColumn.Column`
Comment: No problem. Consider marking the question as answered so that future users know that we have a working solution.
Comment: How would one go about doing that?
Comment: The community standards are pretty well covered here: http://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work


jupyter_client KernelClient gives "ChannelABC() takes no arguments" when starting channels

Question: I'm trying to interact with a running ipython kernel through a python shell, using the jupyter_client package.
I have the kernel running, with a connection file (e.g. "kernel-7772.json") sitting in %APPDATA%\jupyter\runtime.
The code I run is the following:
import jupyter_client
cf = jupyter_client.find_connection_file('7772')
km = jupyter_client.KernelClient(connection_file = cf)
km.load_connection_file()
km.start_channels()

And then I get the error TypeError: ChannelABC() takes no arguments
(full traceback:
File "C:\ProgramData\Anaconda3\lib\site-packages\jupyter_client\client.py", line 101 in start_channels
File "C:\ProgramData\Anaconda3\lib\site-packages\jupyter_client\client.py", line 143 in shell_channel
    socket, self.session, self.ioloop

)
I also tried using BlockingKernelClient, which works completely without issues. However, I would prefer to use the non-blocking KernelClient. Am I doing something wrong? Is there a bug in KernelClient?
My jupyter_client version is 5.3.1 and I'm using python 3.7.3.
Answer: KernelClient is an abstract class. The solution is to use AsyncKernelClient instead.
import jupyter_client
cf = jupyter_client.find_connection_file('7772')
km = jupyter_client.AsyncKernelClient(connection_file = cf)
km.load_connection_file()
km.start_channels()


CSS não obedece a margin-right

Question: Eu simplesmente não percebo porque é que a terceira linha não fica alinhada com o resto do texto.
http://jsfiddle.net/Ra35L/2/
HTML:

CONTACTO

+(351) 968 888 888      +(351) 218 888 888

    firstname.lastname@example.com

    Avenida da República, Torre Soleil

CSS:
#contact {
    width: 50%;
    float: left;
    background-color: #449DCC;
    height: 350px;
}
#contact h1 {
    color:#fff;
    font-size:18
}
#contact p {
    float: right;
    margin-right: 25px;
    font-size: 15px;
    color:#fff;
}
#contact a {
    float: right;
    font-size: 15px;
    color:#fff;
    text-decoration: underline;
}

Comment: todo é resto é para que lado? Esquerda ou direita?
Comment: É tudo encostado à direita
Comment: Eu sugiro evitar ``(s) e espaços dessa maneira... é isto que procura? __http://jsfiddle.net/Ra35L/3/__
Comment: Exactamente, mas porque é que os '' prejudica essas formatações?
Comment: @Miguel, respondí em baixo, mais detalhado do que teria espaço aqui nos comentários.
Comment: Para você ver neh, ninguém consegue colocar um mente pensante no stackoverflow pt
Answer: Você pode usar a propriedade text-align. Exemplo, que simplesmente alinha todo texto na posição que você especificar (direita, esquerda ou centro)
#contact p {
    float: right;
    margin-right: 25px;
    text-align: right;
    font-size: 15px;
    color:#fff;
}

Comment: Obgado, parece-me ser a resposta mais lógica apesar de todas resultarem. http://jsfiddle.net/Ra35L/9/
Answer: Coloque um
texto
 para cada linha

CONTACTO

(351) 967 181 237 (351) 214 569 018

firstname.lastname@example.com

Avenida da República, Torre Soleil

Link: http://jsfiddle.net/Ra35L/5/
Comment: Muito obgado. Porque é que os '' prejudica a formatação?
Comment: Na verdade não prejudica, mas, geralmente a gente faz `` em texto maiores ... tags assim fica organizado com `p`
Answer: Penso que o que pretendes é este resultado:
jsfiddle

CONTACTO

+(351) 967 181 237      +(351) 214 569 018

   email@example.com

Avenida da República, Torre Soleil

.
#contact a {
    float: right;
    font-size: 15px;
    margin-right: 25px;
    color:#fff;
    text-decoration: underline;
}

O que fiz?
Fechei o
 antes do  e abri de novo no fim do ; Coloquei margin-right: 25px; no CSS #contact a para ficar tudo bem alinhado.

CSS não obedece a margin-right


IE opacity :hover sometimes?

Question: I am having a very odd opacity/hover problem in IE. Everything works in FF and Chrome.
Consider this page:
<!DOCTYPE html>

    <title></title>

111

222

333

444

555

666

Here's the problem. The mouse-over is intermittent - you may or may not see a red background and font change in IE (7 or 8). You will always see the cursor change. If I take the background and font-weight out, I still see the cursor change. But if either the background or the font-weight are there, The cursor will still change but the background or font may or may not.
If the opacity is NOT set on #outer, everything works everywhere. Again, FF and Chrome are fine.
What do you think?
UPDATE: This semes to be restricted to IE8. When IE8 is in compatability mode (acting like IE7) all is well!
But, including this tag in header:
<meta id="metaIE8IE7" http-equiv="X-UA-Compatible" content="IE=7" />

does NOT fix it.
Comment: Older versions of IE (can't remember which exact version) doesn't support `:hover` on anything other than anchor, though for this one its probably the `filter` which jQuery use to coax IE into producing something resembling `opacity`. As far as I'm are concerned, the `filter` are voodoo leftover from the olden times...
Comment: :hover is working - the cursor does change. The spooky part is that this is a vastly simplied version of my problem - I do have regions on the 'real' page where :hover works in all respects. I was hoping a solution to this would translate.
Comment: @Yi Jiang: filter are still in use in IE8 to produce opacity. But I agree with you that theyr are MS IE voodoo.
Answer: Had the same problem and found a solution (although my solution was for a:hover not an li:hover and I've not tested)
Basically, make sure element 'has-layout'. For example, display:block, etc. Then reset transparency for that element. -ms-filter: "";
Answer: just got the perfect working combination:
display: block;
zoom: 1;
opacity:0.4; /*for ie9 and other browsers */
filter: alpha(opacity=40); /*for ie older browsers*/

As Bob sayed the 'has-layout' is essential for it to work in ie 8. Here the 'display: block;' does the job.
Answer: More CSS cargo-cult for me! I have no idea, but focing IE8 into IE7 mode fixed the problem. I was wrong about it not working in the question. Still good in other browsers too.

IE opacity :hover sometimes?


Add CSS/JS to particular view?

Question: I'm having trouble understanding how to attach a library to views.  I want my assets to be included in /foo but not in /bar.  I've read through the documentation on this more than once and from my understanding this is achieved by using preprocess, such as:
function my_theme_preprocess_page(&$variables) {
  if($variables['is_front']){
    $variables['#attached']['library'][] = 'my_theme/my_library';
  }
}

I'm new to Drupal so forgive my inherit ignorance, but what does $variables contain?  'is_front' is easy enough, but how do I apply this to views or content types?
Thank you all in advance.
Comment: @Neograph734 Sorry about that, removed the question that was unrelated to the title.
Comment: Usually I attach my assets on twig template. All assets will be included only once. I think this is the best option when you are theming. (for me make more sense put them together, twig template + css/js). Please clarify what you really need accomplish.
Comment: I believe you are asking two questions at the same time. Can you post the second question as a separate question?
Comment: @Vagner I'm just trying to attach assets to a view.  Can you show me how you accomplish this through twig?  I'm not sure what I need to be naming the files.
Comment: @JonCarlyon to see what is the right template is easy see this info about twig debug https://www.drupal.org/node/1906392
Comment: The [Devel](https://www.drupal.org/project/devel) module is very helpful in these situations when you want to see the structure of an array or what value a variable has. It's currently only a dev module for Drupal 8 but could be worth checking out.
Answer: One way to do it via your theme:
Set up your js as a library in your mytheme.libraries.yml file:
library-name:
  js:
    js-file-location/js-file-name.js: {}

Call your library in a preprocess hook in your mytheme.theme file:
/**
 * Implements hook_preprocess_views_view().
 */
function mytheme_preprocess_views_view(&$vars) {
  $vars['#cache']['contexts'][] = 'route';
  if ($vars['view_array']['#name'] == 'view_name') {
    $vars['#attached']['library'][] = 'mytheme/library-name';
  }
}

You'll need to replace these parts with your own actual code:

js-file-location - is it in a folder?
js-file-name - include the extension, I've used .js in this example
library-name - call it whatever you like
mytheme - the machine name of your theme

Note the cache context in this example is set to cache per route.  It's important to know about it but outside the scope of this question.
Source: Adding stylesheets (CSS) and JavaScript (JS) to a Drupal 8 theme
Comment: @ChrisHappy, it's basically how Drupal decides how to set the cache for whatever the context is attached to.  Anything else will have to be a new question because comments is not the place for this =)
Comment: I don't like adding libraries within templates. Templates are for formatting data, adding libraries does not fit this paradigm. While Drupal allows it, I would never do it myself.
Comment: I use this technique, but to identify the view I access the view id, which I find more readable: `$view = $vars['view'] ;  if ($view->id() == 'view_id') $vars['#attached']['library'][] = 'my_theme/library-name' ;`
Comment: Perfect! Could you give me a little more info on the cache context? Tried reading the Docs, but it went way over my head...
Comment: Nice. I've been looking for a solution to adding libraries to paths for a while. This looks to be a good one.
Comment: @Jaypan you can also add libraries within twig templates, and attach them to build arrays, but yeah, if you're altering paths I would guess preprocess is the way to go.
Comment: Don't forget to add to mytheme.info.yml:
`libraries:  - mytheme/library-name`
Comment: @Mattias Axelsson, that is for global themes you want to load on every page. This question/answer is about only loading a library with the element that needs it, in this case a view.
Comment: Ah yes of course, thanks for clearing that out.
Answer:
but what does $variables contain?

A couple of render arrays and some values that be used by twig template. Your best option is check de documentation for each preprocess function to see what are included in $variables. Docs link template_preprocess(&$var) better explanation about preprocess functions and default list of template preprocess functions

but how do I apply this to views or content types?

For me the best option is your twig template file by including this line.
{{ attach_library('my_theme/my-library') }}

No matter how many times this will be 'attached' only one will be downloaded (or aggregate). And only will added if this particular template will be rendered.
More info about Twig debug is here
Comment: This is my new favorite method, it's nice and granular.
Answer: I made a module for that for Drupal 8: Views Attach Library.

The Views Attach Library module is designed to attach multiple
  libraries (JS and CSS) to views by providing just a library name.
How to use?
Installation is as simple as copying the module into your
  modules/contrib directory, then enabling the module.
To add a library to a view follow below steps:

Create or edit view
Find Attach Library section
Click on add library or edit library
Add or edit library name in textfield.
Answer: Using hook_views_pre_render() a library can be attached to a view with JS/CSS.
<?php
/**
 * Implements hook_views_pre_render().
 */
function hook_views_pre_render(ViewExecutable $view) {
  if (isset($view) && ($view->storage->id() == 'test_view')) {
    $view->element['#attached']['library'][] = 'custom/view.lib';
  }
}

Here 'custom/view.lib', custom is the module/theme name and view.lib is the library name.
Answer: As per the documentation of template_preprocess_page():

See the page.html.twig template for the list of variables.

To know if a page is a view, please refer to: hook_preprocess_page(): how to tell a views page?
The content type is available as a property of the $node variable: $variables['node']->type.

Add CSS/JS to particular view?


How can I add a folder outside of my working directory to the Git repository?

Question: I have the directory structure like this:
main
|-- folderA
|-- folderB
      |
      |--- .git

Unfortunately, I decided I need to track files in folderA under the same repository as folderB.
Is there other ways to do this than creating symbolic links  in folderB?
Comment: will you consider executing git init on folder A?
Comment: @Jasonw: That obviously does not satisfy the requirement to track them in the *same* repository, right?
Answer: git mv the contents of folderB (except for the .git directory into a subfolder called folderB
main
|-- folderA
|-- folderB
      |
      |-- folderB
      |--- .git

mv folderA to folderB
main
|
|-- folderB
      |
      |-- folderA
      |-- folderB
      |--- .git

git add and git commit folderA
rename the top level folderB to temp
main
|
|-- temp
      |
      |-- folderA
      |-- folderB
      |--- .git

mv folderA, folderB, and the .git folder to the top level main
main
|
|-- folderA
|-- folderB
|--- .git
|-- temp

delete the temp folder.
Answer: I guess you can make A the main repository which includes B, or if you need some kind of separation which you're not making clear, then you can make A a repository and B a submodule.
Answer: If folderA and folderB are not directly depending on each other, only somehow part of the same project, you could track them as separate branches of the same repository.
Then git-new-workdir is a useful tool to have two working directories for the same repository (but with different branches).
Of course, this is only useful for special cases - in the general case you should better use Abizern's advice to move the folders a bit around.


Como acessar de outro computador a aplicação rodando em localhost

Question: Tenho uma aplicação web feita em ASP.NET MVC 5, e dei um start nela pelo Visual Studio 2013, o endereço da Index page ficou assim na máquina onde está rodando: http://localhost:51144/.
Como faço para outro computador da rede acessar minha aplicação?
Comment: Possível duplicata de [IIS montar server em PC em casa](https://pt.stackoverflow.com/questions/167437/iis-montar-server-em-pc-em-casa)
Comment: Olá, dá uma olhada nesse link aqui tem várias pessoas discutindo sobre o assunto: [Development Server LocalHost](https://stackoverflow.com/questions/1730280/accessing-asp-net-development-server-from-another-pc-on-the-network) Dizem que não é uma boa prática, mas é possível se voce liberar algumas portas.
Answer: Se você tiver o IIS (Internet Information Servces) instalado em sua máquina, você pode hospedar sua aplicação como um site lá. Outros computadores da rede podem acessá-lo usando http://<nome do seu computador>/NomeDoSite.
Para testar se o IIS está instalado abra o browser e acesse http://localhost.

Caso não tenha o IIS instalado, veja como habilitá-lo nesse link: http://msdn.microsoft.com/pt-br/library/ms181052(v=vs.80).aspx
Para saber como criar um site no IIS dê uma olhada nesse link:
http://msdn.microsoft.com/pt-br/library/tcywfea7(v=vs.80).aspx
Outra opção é você publicar sua aplicação diretamente pelo Visual Studio, veja esse artigo com um passo a passo: http://www.dotnetfunda.com/articles/show/2596/learn-iis-host-and-publish-in-mvc5-using-visual-studio-2013-rc


Use power series to solve the initial-value problem: $y''-2xy'-2y=0$ where $y(0)=1$ and $y'(0)=0$.

Question:
Use power series to solve the initial-value problem:
$$y''-2xy'-2y=0; y(0)=1, y'(0)=0$$

How to we solve this in terms of summation sign?
I got this :
$a_{n+2}=2\frac{a_n}{n+2}$
$y(x)=c_0(1-x^2-\frac12x^4)+c_1(x+\frac23x^3+\frac4{15}x^5)$
I dont know what will it be in terms of odd and even summations.
Comment: Welcome to MSE.  You'll get a lot more help, and fewer votes to close, if you show that you have made a real effort to solve the problem yourself.  What are your thoughts?  What have you tried?  How far did you get?  Where are you stuck?  This question is likely to be closed if you don't add more context.  Please respond by **editing the question body.**  Many people browsing questions will vote to close without reading the comments.
Comment: Hint: the answer is $\exp(x^2)$.
Comment: I am getting (-1)^n/n! for even numbers.I dont think I am getting the right series
Answer: $$a_{n+2}=2\frac{a_n}{n+2};\;a_0=1;\;a_1=0$$
$$\begin{cases}
a_{2n+1}=0\\
a_{2n}=\frac{1}{n!}\\
\end{cases}
$$
$$y=\sum _{n=0}^{\infty } \frac{x^{2 n}}{n!}=e^{x^2}$$