What is the probability that $\pi(x) + x$ is injective?

Question: Let $S$ be a finite group with operator + and $\pi$ be a permutation on $S$.  Then what is the probability that $\pi(x) + x$ is injective over choices of $\pi$?
The concrete instantiation I'm interested in is $S=$GF$(2^n)$ for fixed $n > 0$.  (Computer Scientists call this "xor on $n$-bit strings.")
For $n=1$ we have two permutations, neither of which produce an injection. For $n=2$ we have 24 permutations, 8 of which induce an injection so the probability is 1/3.
Here is an example $\pi$ for $n=2$:
$$\pi(0)=0,\ \pi(1) = z,\ \pi(z)=z+1,\ \pi(z+1)=1.$$
Here notice that $\pi(x) + x$ produces $0$, $z+1$, $1$, and $z$, respectively, which is an injection.
Answer: My laptop has extended your results to $n=3$ and $n=4$ (but $n=5$ is completely out of reach).
For $n=3$ we have $8!=40320$ permutations, of which $384$ induce an injection. $384/40320 = 1/105$.
For $n=4$ we have $16!=20922789888000$ permutations, of which $244744192$ induce an injection. $244744192/20922789888000 = 97/8292375$ in lowest terms, so I don't see a nice pattern here.
Comment: There's one pattern that might help to estimate the probability: The highest power of $2$ that divides the number of permutations which induce an injection seems to be $2^{2^n - 1}$ for $n \ge 2$. I don't have a proof, however.
Answer: There is a name for what you describe: it's called an orthomorphism. If $S$ is the cyclic group of order $n$, then the number of orthomorphisms for $n=1,3,5,...$ is $1, 3, 15, 133, 2025, 37851,...$ (sequence A006717 in OEIS). (If $n$ is even, $S$ has no orthomorphisms.)
You can find lots of links for the case when $S$ is GF$(2^n)$ by googling "orthomorphism of galois field". For instance, here is a short paper which confirms my $244744192$ and goes on to discuss the construction of permutation polynomials.


How to browse VPC website in host machine?

Question: I'm kind of confused with the network adapters in Windows Virtual PC, I was able to browse my SharePoint website inside the Virtual PC, but I wanted to browse the website in my host machine,
I wanted to learn these network setting in few different virtual PC (Windows Virtual PC, Hyper V and VirtualBox).
Answer: You will need to do some reading, here are good places to start with:
How does basic networking work in Hyper-V: http://blogs.technet.com/b/jhoward/archive/2008/06/16/how-does-basic-networking-work-in-hyper-v.aspx
If you understand this, then the same concept apply to all other virtual technologies


Opinions: SQL Statements, do you use table aliases?

Question: One of the guys I work with has the following to say about using SQL aliases, and he just posted the following on reddit.  What do you guys think, to alias or not to alias?
....
So I've always been the odd man out of my with my dev team about how SQL should be written.
I learned in school to use aliases, but I hate them personally. I find it can make the statement unreadable if long. I want to know what tables are joining to what other tables. I don't want to have to search through a 5-10 table join to figure out what "p" means, is that the products table, people, etc...?
Personally I don't find it hard to use a little double click, ctrl+c, ctrl+v. Use the full table name (of course sometimes you have to join to the same table twice which you'll be forced to use aliases in some more bizarre queries.)
Ex. My style
SELECT *
FROM
    People
JOIN
    Orders ON People.PersonID = Orders.PersonID
JOIN
    OrderDetails ON Orders.OrderID = OrderDetails.OrderID
JOIN
    Products ON Products.ProductID = OrderDetails.ProductID
JOIN
    Country ON People.CountryID = Country.CountryID

VS
SELECT *
FROM
    People p
JOIN
    Orders o ON p.PersonID = o.PersonID
JOIN
    OrderDetails od ON o.OrderID = od.OrderID
JOIN
    Products pr ON pr.ProductID = od.ProductID
JOIN
    Country c ON p.CountryID = c.CountryID

Personal preferences yourself? I mean just consider if this query was a larger join and you had a large select statement.
I assume most people use alias as a time saver, do you think it's also more readable? Can you go to your old sql and instantly understand how your joins work?
UPDATE: Specifically I'm trying to argue that shorting the names down to single letters can make the sql statement unreadable. Changing a table from ShoeStackerCrazyProducts down to ShowProducts I think can make sense. Shorting it to sscp on the other hand would make it unreadable. Thoughts?
Comment: If you are asking for opinions, make this question community wiki, so it will not get shut down quickly.
Comment: How about fully qualified names? [server].[db].[owner].[table] - I would rather alias that...
Comment: It's personal preference, to a degree - but with lots of tables and a lots of join statements, **with** aliasses, I believe your T-SQL is much more readable. And yes, I **can** go back to my old SQL and still understand my joins no problem - thanks to using aliasses! :-)
Comment: @Oded: CW doesn't make a poll question acceptable.
Answer: This is subjective, but when your table names get long then aliases are much more readable. Remember that column names will also need qualifiers, so you can quickly end up with long lists of CamelCasedTableNames.WithDelimiters.
Real-world example, taming some legacy tables:
SELECT count(*) as c, a.Attributeid, property as AttributeName,
    a.Subattributeid, SubProperty as SubAttributeName
    FROM prodAttribute a
    INNER JOIN phAttributeDisplayOrder o
        ON a.attributeID = o.AttributeID
    INNER JOIN lstphysicalproperties y
        ON a.attributeid = y.physicalpropertyid
    INNER JOIN (select * from tblsubPhysicalProperties where deleted is null) z
        ON a.attributeid = z.propertyid
            AND a.subAttributeID = z.subpropertynumbering
    GROUP BY o.ranking, a.attributeid, property, a.subattributeid, SubProperty
    ORDER BY o.ranking, a.attributeid, a.subattributeid

That's bad enough without the fully-qualified names.
If I were writing it today, I might avoid the one-character aliases, but in a query this short it's not as important.
Answer: Personally, I always use aliases, even on a single table query. I also make it a habit to use that alias with every column reference, even when the column name is unique and the alias is not strictly required. As long as your aliases are meaningful (e.g., alias Products as pr, not as A), you shouldn't lose much readability.
See also: Brent Ozar's Blog Entry on this topic.
On a related note, I also always include the schema name on every table reference (e.g., dbo.Products vs. Products) even when it's the default schema.
Comment: "...even when the column name is unique..."
This is important for self-documenting code. Do it for your co-worker, or the future you.
Answer: I use SqlPrompt (RedGate) which will do all that copy/paste for you and I still use aliases all the time. What I don't do (and can't stand) is using the alphabet to alias. In other words, the first table I write is 'a', the second 'b' and so forth. For small queries I use the first letter of the table. For longer queries I'll use the whole table name.
Of course, I use schemas so my fully qualified object names tend to be a LOT longer than the example given.
Answer: Alias is better. In the case you have Product and People, just use different abbreviations. Pd for product, pl for people, for example.
Besides, in the case where you have inner queries, aliases are critical.
Answer: Alias are really handy if you need the 3 part name if you are doing logic across multiple databases.  Also, their utility is directly proportional to the length of the DB/schema/table names and the thoughtfulness of the alias.
In my environment we do a lot of work with multiple DBs in the same query, and aliases are invaluable, especially when you have long DB names like:
CustomerNameDataClaimsDetail
CustomerNameDataClaimsHeader
and those DBs have tables like:
ClaimsDetailNew
ClaimsDetailLoad
In that instance it makes a lot of sense to alias CustomerNameDataClaimsDetail.dbo.ClaimsDetailNew to CDN or some such.
Answer: If your tables are named the same, but on different databases, you're forced to alias. This also occurs across identically-named tables but differently named schemas.
SELECT * FROM
DB1.dbo.Table1
JOIN DB2.dbo.Table1 ON DB1.dbo.Table1.field = DB2.dbo.Table1.field

will not work, where
SELECT * FROM
DB1.dbo.Table1 T1
JOIN DB2.dbo.Table1 T2 ON T1.field = T2.field

will work.
Also with a self join you're forced to alias.
Answer: It's more common that SQL IDEs support intellisense:

SQL Server Management Studio 2008 does (but only against 2008+ instances)
Oracle's PLSQL Developer
RedGate's SqlPrompt

...which makes it really easy to work with aliases.
That said, I don't think it is subjective to use table aliases.

Who really wants to re-write the table name (especially three/four name syntax in TSQL) for every column reference that needs to be qualified?  That's just making more work, not less--and it increases the possibility of typos.
Every column reference should be qualified; SELECT * is to be avoided unless actually using all columns.  By having the table alias present in a column reference, it's clear where the column is from and can be relied upon for errors if the column is either altered or disappears from the table.  Nothing like getting an error about "erroneous column 'id' " that you then have to chase down--include the table alias, and you've minimized the amount of work necessary to debug the issue.
Table aliases are required if you want to have multiple instances of the same table in a single query.

Conclusion
The ability to maintain SQL is made that much easier by using table aliases.
Answer: I always use aliases as soon as more than one table is involved.
I think that makes JOINs much more readable, especially because we have quite a few tables with composite keys.
If you always have to type the table names, it's more work and less readable:
select *
from TableWithLongName
inner join AnotherTableWithLongName on TableWithLongName.Column1 = AnotherTableWithLongName.Column1 and TableWithLongName.Column2 = AnotherTableWithLongName.Column2

...than this one:
select *
from TableWithLongName t
inner join AnotherTableWithLongName a on t.Column1 = a.Column1 and t.Column2 = a.Column2

Plus, you wouldn't normally do SELECT * in a real world app, you would specify which columns to select.
If you join two or more tables, you have to prefix the columns with the table names.
Again, aliases to the rescue...because I'd prefer this one:
select t.Column1, t.Column2, a.Column1, a.Column2
from ...

...and not:
select TableWithLongName.Column1, TableWithLongName.Column2, AnotherTableWithLongName.Column1, AnotherTableWithLongName.Column2
from ...

Concerning how to name the aliases:
When only two or three tables are involved, I mostly use single letters as aliases.
If you only have two tables with completely different names, it's not that hard to memorize that "o" means "Orders" and "p" means "Products".
If short aliases are likely to cause confusion (like "p1" for "People" and "p2" for "Products") I use longer aliases, but still not the whole name (something like "peo" and "pro").


What is the probability of three cards drawn containing no Queens, but at least one Ace or one King?

Question: We have a standard $52$-card deck. What is the probability of three cards drawn containing no Queens, but at least one Ace or one King?
The total no of draws: $\binom{52}{3}$
no. of draws without any Queen: $p_1= \binom{48}{3}/\binom{52}{3} = 0.78$.
no. of draws without any A or K: $p_2 = \binom{40}{3}/\binom{52}{3} = 0.45$, so $1-p_2 = 0.55$.
So, will I be correct to conclude, that:
$P(\text{no Q, but at least 1 of A,K}) = p_1(1-p_2)$
??
I have a feeling I am missing something, could someone verify, please?
Thanks
Answer: Let:

$A$ denote an ace
$K$ denote a king
$Z$ denote anything but ace, king or queen

Then add up the number of ways to choose each one of the following combinations:

$\binom{4}{3}\cdot\binom{4}{0}\cdot\binom{40}{0}\implies{AAA}$
$\binom{4}{2}\cdot\binom{4}{1}\cdot\binom{40}{0}\implies{AAK}$
$\binom{4}{2}\cdot\binom{4}{0}\cdot\binom{40}{1}\implies{AAZ}$
$\binom{4}{1}\cdot\binom{4}{2}\cdot\binom{40}{0}\implies{AKK}$
$\binom{4}{1}\cdot\binom{4}{1}\cdot\binom{40}{1}\implies{AKZ}$
$\binom{4}{1}\cdot\binom{4}{0}\cdot\binom{40}{2}\implies{AZZ}$
$\binom{4}{0}\cdot\binom{4}{3}\cdot\binom{40}{0}\implies{KKK}$
$\binom{4}{0}\cdot\binom{4}{2}\cdot\binom{40}{1}\implies{KKZ}$
$\binom{4}{0}\cdot\binom{4}{1}\cdot\binom{40}{2}\implies{KZZ}$

Then divide the result by the total number of ways to choose $3$ out of $52$ cards, which is $\binom{52}{3}$.
Comment: There is no need to distinguish aces and kings in this context.
Comment: @drhab: Do you mean that we can use the same letter in order to denote both, and then choose out of $8$ instead of out of $4$, and get the same result? Or do you mean that there is something wrong with the answer?
Comment: Nothing wrong with the answer, but yes: choose from $8$ in stead of twice from $4$.
Comment: @drhab: Yep, good point. Not sure whether it's worth the effort changing it, as OP hasn't replied to either one of the answers given here (mine and yours).
Comment: The decision is yours of course. If I were you I would not change it. The combination of your answer and my comment on it is also educational. I did not mean to stimulate you in changing.
Answer: The probability of getting no queens is: $$\binom{4}{0}\binom{48}{3}\binom{52}{3}^{-1}=\binom{48}{3}\binom{52}{3}^{-1}$$
The probability of getting no queens, no aces and no kings is: $$\binom{12}{0}\binom{40}{3}\binom{52}{3}^{-1}=\binom{40}{3}\binom{52}{3}^{-1}$$
Consequently the probability of getting no queens but at least one
ace or king is: $$\binom{48}{3}\binom{52}{3}^{-1}-\binom{40}{3}\binom{52}{3}^{-1}=\left[\binom{48}{3}-\binom{40}{3}\right]\binom{52}{3}^{-1}$$


Custom image style conversion - how to read back from a file?

Question: I'm making a custom image style in Drupal 8.
It takes various parameters and passes the image to an external service for processing, and it now needs to read back the processed image from a file.
However, in applyEffect I'm expected to work with the Image $image object passed in.
The site is using the standard GD2 toolkit, which provides a load() method, but alas it's protected (presumably because the Image object that owns it would need updating).
Previously (porting this effect from D7) I was able to create a new Image object from the new image and replace the original object's resource and info properties, thus moving the altered image data into the image object. But this is no longer possible.
To summarise I want to:
public function applyEffect(ImageInterface $image) {
    $image->save('/some/path');
    $new_image_filename = call_some_external_process('/some/path');
    $image->load($new_image_filename); // ← this does not work :-)
    return TRUE;
}

Answer: Here's how I did it.
public function applyEffect(ImageInterface $image) {

    // Save the image and process it externally...
    $some_tempoaray_filename = '/tmp/foo';
    $image->save($some_tempoaray_filename);
    call_some_external_process($some_tempoaray_filename);

    $toolkit = \Drupal::service('image.toolkit.manager')->getDefaultToolkit();
    // Re-call the existing Image object's constructor with the name of the
    // new file.
    $image->__construct($toolkit, $some_tempoaray_filename);
    // Next we have to make sure it loads the file into memory
    // because $image->save() requires it to be loaded, but this
    // happens outside of this function and we want to delete
    // the $some_tempoaray_filename so as not to leave temp files.
    $toolkit->getResource(); // forces a load.
    // Now we can lose our temporary file.
    unlink($some_tempoaray_filename);

    return TRUE;
}


How to compare AUCs using the boot package in R?

Question: I would like to compare AUCs for two treatments using the boot package in R. However, something wrong with my R code and I don't know how to fix it. Can someone please give me a hint? many thanks in advance
require(boot)
#Create Data
set.seed(123)
N = 150
y1 = rnorm(150)
y2 = rnorm(150,1,0.2)
y3 = rnorm(150,2,0.5)
time = rep(1:3, each = 50)
trt = rep(rep(0:1, each = 25), times=3)
Data = data.frame(trt,time,y1,y2,y3)

#Trapezoid Rule
trap.rule = function(x,y) sum(diff(x)*(y[-1]+y[-length(y)]))/2

# Sum y1-y3 for each trt at each time point
SUM = function(data){
     set1 = subset(x = data, data$time==1)
     set2 = subset(x = data, data$time==2)
     set3 = subset(x = data, data$time==3)
     s1 = by(set1[,c("y1","y2","y3")], set1$trt, sum)
     s2 = by(set1[,c("y1","y2","y3")], set2$trt, sum)
     s3 = by(set3[,c("y1","y2","y3")], set3$trt, sum)
     result = matrix(data = c(s1[1],s2[1],s3[1],
                              s1[2],s2[2],s3[2]), ncol=2)
     colnames(result) = c("trt = 0", "trt = 1")
     output = cbind(time = 1:3,result)
     return(output)
}

# Statistic for boot
AREA = function(data,i){
        d = data[i,]
        MQ = SUM(data = d)
        A.0 = trap.rule(x = 1:3, y = MQ[,2])
        A.1 = trap.rule(x = 1:3, y = MQ[,3])
        area = A.1 - A.0
        result = c(A.0, A.1, area)
        return(result)
}

area.boot = boot(data = Data, statistic = AREA, R = 1000)
area.boot

However, there is an error message
Error in tapply(1L:49L, list(`set2$trt` = c(0L, 1L, 1L, 1L, 0L, 1L, 0L,  :
  arguments must have same length

Comment: Hi Pocrastinator, I have a typo in my SUM function (see Daniel's comment). That's why boot can't work with AREA function. thanks.
Comment: The problem is in your function AREA.
Answer: I'm just getting started with R... Shouldn't it be set2 in the s2 assignment:
 s1 = by(set1[,c("y1","y2","y3")], set1$trt, sum)
 s2 = by(set2[,c("y1","y2","y3")], set2$trt, sum)
 s3 = by(set3[,c("y1","y2","y3")], set3$trt, sum)


How to troubleshoot Ubuntu Certbot cron/timer?

Question: lsb_release -a
No LSB modules are available.
Distributor ID: Ubuntu
Description:    Ubuntu 20.04.2 LTS
Release:        20.04
Codename:       focal

and have installed certbot via apt-get
My issue is that it is the second time that certificates expire and the cron(also systemd service) installed by certbot is not working.
I see this file created:
/lib/systemd/system/certbot.timer
[Unit]
Description=Run certbot twice daily

[Timer]
OnCalendar=*-*-* 00,12:00:00
RandomizedDelaySec=43200
Persistent=true

[Install]
WantedBy=timers.target

/lib/systemd/system/certbot.service
[Unit]
Description=Certbot
Documentation=file:///usr/share/doc/python-certbot-doc/html/index.html
Documentation=https://letsencrypt.readthedocs.io/en/latest/
[Service]
Type=oneshot
ExecStart=/usr/bin/certbot -q renew
PrivateTmp=true

/etc/cron.d/certbot
# /etc/cron.d/certbot: crontab entries for the certbot package
#
# Upstream recommends attempting renewal twice a day
#
# Eventually, this will be an opportunity to validate certificates
# haven't been revoked, etc.  Renewal will only occur if expiration
# is within 30 days.
#
# Important Note!  This cronjob will NOT be executed if you are
# running systemd as your init system.  If you are running systemd,
# the cronjob.timer function takes precedence over this cronjob.  For
# more details, see the systemd.timer manpage, or use systemctl show
# certbot.timer.
SHELL=/bin/sh
PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin

0 */12 * * * root test -x /usr/bin/certbot -a \! -d /run/systemd/system && perl -e 'sleep int(rand(43200))' && certbot -q renew

My init system is systemctl:
[[ `systemctl` =~ -\.mount ]] && echo yes || echo no
yes

I see there timer registered:
 systemctl list-timers | grep 'cert'
Fri 2022-03-25 17:36:31 UTC 6h left        Fri 2022-03-25 02:41:57 UTC 8h ago       certbot.timer                certbot.service

I also tried to check timer calls to see if certbot timer was called at midnight one day before:
journalctl  --since "2 days ago" -u motd-news.timer
-- Logs begin at Sun 2021-09-26 19:26:36 UTC, end at Fri 2022-03-25 11:37:03 UTC. --
Mar 25 09:54:16 ip-10-40-2-7 systemd[1]: motd-news.timer: Succeeded.
Mar 25 09:54:16 ip-10-40-2-7 systemd[1]: Stopped Message of the Day.
-- Reboot --
Mar 25 09:54:55 ip-10-40-2-7 systemd[1]: Started Message of the Day.
-- Reboot --
Mar 25 09:59:11 ip-10-40-2-7 systemd[1]: Started Message of the Day.
Mar 25 10:06:38 ip-10-40-2-7 systemd[1]: motd-news.timer: Succeeded.
Mar 25 10:06:38 ip-10-40-2-7 systemd[1]: Stopped Message of the Day.
-- Reboot --
Mar 25 10:08:45 ip-10-40-2-7 systemd[1]: Started Message of the Day.

I don't understand why certbot renew command this cron/timer is never called or is called and something fails (for this I need information where to check the logs).
Answer: This works for me
Your system doesn't use the cron so ignore that, it is systemd.
certbot.timer:
[Unit]
Description=Timer for Certbot Renewal

[Timer]
OnBootSec=300
OnUnitActiveSec=1d

[Install]
WantedBy=timers.target

certbot.service:
[Unit]
Description=Let's Encrypt renewal
Wants=network.target
After=network.target

[Service]
Type=oneshot
ExecStart=/usr/bin/certbot renew --quiet --agree-tos
ExecStartPost=/bin/systemctl reload nginx.service
ExecStartPost=/bin/systemctl reload postfix.service
ExecStartPost=/bin/systemctl reload dovecot.service

I also see you rebooted your computer a couple of times, but you are also looking at motd-news.timer. So you won't see anything about certbot's timer!
Comment: Thanks @Alex so wha should I be looking at in the command journalctl  to see only certbot
Comment: `sudo journalctl -u certbot`
Comment: Thanks so it seems like it runned but failed `Mar 24 11:29:35 ip-10-40-2-7 certbot[1842612]: All renewal attempts failed. The following certs could not be renewed:
` I cannot see anymore information why it failed
Comment: Try `sudo certbot renew` and see what the error message is.
Comment: Also there is a logfile in `/var/log/letsencrypt/` on most systems.


Check if a shared folder is password protected in vb.net

Question: I have a shared folder that placed at a computer act as server.
When I want to access to this shared folder from another computer that act as client, how can I check if the shared folder I want to access is password protected or not.
Answer: try to access it. if you could then you would. if not then a security-exception will arise. that is the part when you need the password.
this is about windows shared i presume. now windows shares are never password protected. a share is protected through permissions to some user accounts. folder > rt.click > property > security. a dot net code runs from the account of the logged-in user. if the user who is running the code has permissions on the folder as well as on the share then the code is allowed to access it. otherwise a security-exception happens.


Descending order of properties of the modulus

Question: I'm just checking to make sure I am right about the following (I won't get into detail as the proofs are long and I start to get confused if I look at them too long)
Is it true that $|z_2|-|z_1| \leq |z_1+z_2| \leq ||z_2|-|z_1|| \leq |z_1| + |z_2|$?
I know most (if not all is right) it is mainly the $||z_2|-|z_1|| $ that is throwing me off.
Thank you
Answer: Actually it's not true. The triangle inequality says $||z_1|-|z_2||\leq |z_1 + z_2|\leq |z_1| +|z_2|.$ Take $z_1 =2$ and $z_2=1$, then you can have a contradiction for the second inequality you claimed above.
Comment: Yes, you are right.
Comment: Thank you. So it doesn't make a difference that it's $||z_2|-|z_1||$ rather than the other way around? The inequality still holds? So it should be $|z_2|-|z_1| \leq ||z_2|-|z_1|| \leq |z_1+z_2| \leq |z_1| + |z_2| ?$
Comment: You are welcome moony.


Image taking too long to load?

Question: EDIT:
After doing a method trace, whenever I switch with the purple square, the graph rises a lot. When I switch with a blue or green circle, it stays low:

Here are the methods of the swap with the purple square:

I have an app which swaps two buttons. There is one red button, when it gets clicked, it picks a random button from the other three, and swaps.
I tried doing this one way by just swapping images. In the onClickListener, I only listened for clicks with buttons with the red button.

Get random image
Make it blank
Look for red button
Give red button background that random image had (swap)
Give random image (which is blank now) red background

If this is confusing...leave it. But:
Whenever I switch images from a larger image to a smaller image, the process takes a much longer time. It is much faster when swapping between two smaller images. How do I fix this. Is there a certain image size which is optimal for android?

Here is the layout code:
https://gist.github.com/anonymous/813883bce89606d2a82e
As you can see in the image, it takes a much (MUCH!) shorter time swapping background images with the blue circle than the purple square. Why...?

Why is the way (where I just change the images and check for a button with a red image) slower based on the image sizes? What image size should I use?
Thanks so much for your time
Comment: It may well be that what you are trying to do is unreasonable for your device, but it may also be that your implementation is needlessly running in circles to do it (your use of random numbers to terminate a loop bears careful examination).  Put lots of logging into your code and capture logcat output in timestamp mode, or else use the DDMS method tracing and profiling tools, and from that figure out what exactly it is doing and specifically what is taking most of the time.
Answer: My first guess would be that you have some big PNGs that take a long time to load.
But, we have nice tools to help us actually find out -- so we don't have to guess!
Do a method trace (available in the CPU tab in Android Studio, or the DDMS view in Eclipse+ADT) while doing the switch, and you should see what is taking time.
Comment: Alright, I will check. This is the first time doing a method trace though
Comment: Then it's a wonderful day, because you'll be learning something new! ;)
Comment: Okay, I think i'm getting somewhere. Whenever I switch with the purple square, the graph rises a lot, and with the green or blue circle, the graph only rises a little. Here is an image: http://snag.gy/iScsy.jpg
Comment: Yep. Now, press the little stopwatch button (left of the graph) and try doing one of the "bad" scenarios. When the image shows up, press the stopwatch again. After that, the trace will be fetched, and you should see a trace showing lots of methods, including how long they took.
Comment: And in there, try to find some long-running methods that may be related to what you're doing.
Comment: Alright, so I did that. It seems that it is already sorted out by the longest time at the top and the shortest time at the bottom. I have no idea what these methods are... Here is a screen shot again: http://i.snag.gy/3abvX.jpg
Comment: Okay, so it's the draw that's taking time. Unfortunately, this trace only shows Java-side stuff, and we'd need an OpenGL trace to see details. It is [available in the Android Studio 2.0 Preview](http://android-developers.blogspot.se/2015/11/android-studio-20-preview.html), or in the latest ADT plugin. However, the reasonable guess is that you have a large bitmap (remember, when unpacked, your image is likely 4*width*height bytes in size) -- and it is taking some time to upload to the GPU.
Answer: I dont have the exact answer for your question but just 2 recommendations:
1) Make sure you scale the image first before drawing.
2) Using RelativeLayout causes your ViewGroup to measure your children twice instead of one. So Make sure that you dont do any that trigger re-layout on click events
3) I would suggest that you put these View in a GridView or GridLayout and then when you need to swap your views, just swap the positions of your view in an data (Array, for example), and call notifyDataSetChanged();
Hope this help
Comment: What do you mean scale the image...? How do I do that? Also, how do I make sure that I don't trigger re-layout click events...? Thanks
Comment: Using BitmapOption class, here is an guide on this http://developer.android.com/training/displaying-bitmaps/load-bitmap.html. If you dont change the size or position of the views then you are not triggering layout.
Comment: What size of image is optimal then?
Comment: Depend on the actual size of the View that you want to display. Usually, you want to scale the image to just a little bigger than your view size.
Comment: Then what do I do if I want my app to be compatible on multiple screen sizes? I have read the android docs...but it is unclear
Comment: Well, you could keep your original image size, store it somewhere (Internal Storage). Just scale it when you need to display. This way if you are on a high resolution device, then image could just be display without scaling.
Comment: What about if I wanted the entire layout to work on different screen sizes? Would I need to create different layouts?
Comment: Yes. Create a different layout. Typically, phone screens can only display 1 column of content, but can be 2 or three on tablet. This link https://www.google.com/design/spec/layout/adaptive-ui.html#adaptive-ui-breakpoints has some detail
Answer: Apparently, the image size can affect the speed. So, what I did was re size my image. I did this in photo shop, but you can do it in paint or you can do it in an image-re sizer website. Just search that up in google, and enter the dimentions 56 x 56. For some reason, those dimensions work best.
Here is one image resizer tool:
http://www.picresize.com/
On this website, just select your image from your computer, and then the next screen will say to resize it:
To do it in paint:

Although the bounty is over, I have just posted this to help people know how to do it. I STILL DON"T KNOW WHY THE IMAGE SIZE MATTERS I would really appreciate it if someone explained why I must fix the image size, although I know how.
Thanks,
NullPointerException

Image taking too long to load?


Plugin doesn't support this project's cordova-android version. While installing cordova-plugin-geofence plugin

Question: C:\My App\test>ionic cordova plugin add cordova-plugin-geofence

cordova plugin add cordova-plugin-geofence --save
  npm WARN optional SKIPPING OPTIONAL DEPENDENCY: email@example.com (node_modules\fsevents):
  npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for firstname.lastname@example.com: wanted
   {"os":"darwin","arch":"any"} (current: {"os":"win32","arch":"x64"})

firstname.lastname@example.com
firstname.lastname@example.com
updated 2 packages in 33.453s

Installing "cordova-plugin-geofence" for android
Installing "cordova-plugin-add-swift-support" for android
Android Studio project detected
Installing "cordova-plugin-compat" for android
Plugin doesn't support this project's cordova-android version. cordova-android: 7.0.0, failed
 version requirement:
      <6.3.0
Skipping 'cordova-plugin-compat' for android
Installing "es6-promise-plugin" for android
Subproject Path: CordovaLib
Subproject Path: app
Adding cordova-plugin-geofence to package.json
Saved plugin info for "cordova-plugin-geofence" to config.xml
Ionic Versions Info :
cli packages: (C:\Users\Shadab\AppData\Roaming\npm\node_modules)
@ionic/cli-utils  : 1.19.2
ionic (Ionic CLI) : 3.20.0

global packages:
cordova (Cordova CLI) : 8.0.0

local packages:
@ionic/app-scripts : 3.1.9
Cordova Platforms  : android 7.0.0
Ionic Framework    : ionic-angular 3.9.2

System:
Node : v8.9.4
npm  : 5.6.0
OS   : Windows 7

Environment Variables:
ANDROID_HOME : C:\Users\Shadab\AppData\Local\Android\sdk;

Misc:
backend : pro

Answer: Run the "cordova platforms" command to see what version of android you have. In my case I was using 6.2.3. What I did is I updated my android version using the "cordova platform update firstname.lastname@example.com"command. After that add the plugins again and you should be good to go.


Dynamically display view block based on based on different view filters

Question: I have a view as a page layout. That view allows the user to choose from a list of tags to filter content.
What I'm trying to do is - when someone selects one of the tags to filter content, a separate view block is displayed, based on the tag they select from the filter list.
Is there a way to do this?
Comment: is the view block already embedded in your view page? or will you be displaying it separately as part of that view page template? or is clicking on the filter redirecting the user to a totally different page?
Comment: I'd be displaying it separately, as part of the view page template.
Answer: We did something similar on our site -- on the left hand side we had a list of lesson plans, and when you clicked one, it used AJAX to dynamically update the lesson pane on the right. Sounds basically like what you want.
Here's the set up:
Make a view with both a block and a page, and configure the block so that the two show up on the same page. (example.com/my-view should show the block on the left side and the page on the right side.)
In the block body, he put the list of lessons alongside the following code in


Taking a derivative of a derivative of a surface.

Question: I'm currently studying by myself Differential Geometry with Kreyszig's book.
I'm starting chapter 4. The 1st section is about the 2nd fundamental form:

As usual, I like to thoroughly go about the reasoning on how we get there. Kreyszig doesn't talk much about it as with other sections, yet I took the challenge to expand the solution by myself. Given the following notation (used in the book):

I want to arrive to the following:

Which is used in the process. I already have most of it:

How do I work out those last two derivatives? I'm thinking a sort of chain rule may be present but I'm not that sure at all. Expanding what I have to arrive at, those 2 terms end up being 4 which are resumed in summation notation.
Thanks for any help you can provide.
Comment: Please write an *informative* title... one that relates to the specific content of your question.
Comment: Couldn't you have contradicted the indices on $x_i $ and $ \dot{u}^i$
Comment: I'm not sure you correctly understand what it is that you are calculating. The surface does not change as the arclength changes. It's all about the curve that is a subset of the surface. You're comparing its acceleration with an arbitrary parametrization to its acceleration with an arclength parametrization.
Comment: @Fernado Garcia Cortez I am glad my answer helped you, but I would echo what David G. Stork said. If you edit the question, then it will be useful to more people :)
Comment: @Buraian I agree, yet I can't come up with a better title. I was also aware that my understanding of what the derivative actually meant was a bit of. Do you have something in mind?
Comment: I am working through a similar book on this, I'll perhaps say more specific comments when I reach the chapters dealing with surfaces. However, I think if you can put exactly what wasn't clear about the derivatives on surface concept into a question, then I can try and attempt the question when I know a bit more.
Answer: Here is what I think, the problematic terms here are:
$$ \dot{u}^i \frac{d}{ds}x_i \tag{1}$$
Now by the chain rule we can write the derivative with $s$ as,
$$ \frac{d}{ds} = \frac{du^j}{ds} \frac{d}{du^j}$$
Hence,
$$ \frac{d}{ds} x_i = \frac{du^j}{ds} \frac{d}{du^j} x_i \tag{2}$$
And, we can also use the fact that:
$$ \frac{d}{du^j} x_i =x_{ij} \tag{3}$$
Putting everything together:
$$ \dot{u}^i \frac{du^j}{ds} x_{ij}$$
Now to finish, I guess that $ \frac{du^j}{ds} = \dot{u}^j$?


Problem with specific permissions

Question: I would like to set a role permission for displaying a field depending on the value of an other field. But I can't find how to do it.
For example, I have a content type Person. If I add a content Person that is a "policeman" (field Job = "Policeman") then his phone number (field Phone) is display only to user that have the role "Officer". But if the person is a "Secretary" then his phone number is display only to user that have the role "Direction".
Does anyone know how to do it ? Is there a module for that ?
Thanks !
Answer: There are 2 modules out there that can do one part of what you're wanting, but not both.

Field Permissions lets you display fields based on role.
Field Formatter Conditions lets you display fields based on the content value of another field.

If your content design is flexible these might help.
However, if you're looking for field display based on both a role and another field's value you might be better off adding a template_preprocess_node() function to template.php to check for rendering logic. For example:
function MYTHEME_preprocess_node(&$variables) {
  global $user;

  $job = isset($variables['node']->field_job[LANGUAGE_NONE][0]['value']) ? $variables['node']->field_job[LANGUAGE_NONE][0]['value'] : '';
  if($job == 'policeman' && !in_array('Officer', $user->roles)) {
    hide($variables['content']['field_phone']);
  }
  //@TODO: Add other role/value checks
}

Comment: [Conditional Fields](https://www.drupal.org/project/conditional_fields) would be another option

Problem with specific permissions


Android - canvas drawing doubts

Question: I am looking at one of the sample applications from Google, which deals with touch drawing using canvas:
http://developer.android.com/resources/samples/ApiDemos/src/com/example/android/apis/graphics/TouchPaint.html
I have a few doubts:

I am not able to understand what's the role of Canvas versus the role
of the bitmap.
In the drawPoint function, I am not able to
understand this code snippet:

mCanvas.drawCircle(x, y, radius, mPaint);
mRect.set((int) (x - radius - 2), (int) (y - radius - 2),
          (int) (x + radius + 2), (int) (y + radius + 2));
invalidate(mRect);

If the circle is already drawn into the canvas above, then what happens in the onDraw function where the following code is given:
canvas.drawBitmap(mBitmap, 0, 0, null);
Answer: Canvas vs Bitmap
A Bitmap is what the name suggests: A normal image as a bitmap. The Canvas class is an editor for bitmaps. You use it to change the bitmap data, it holds all drawing methods. This principle behaves similar to the shared preferences (if you already worked with them), you have a SharedPreferences class that holds the preferences, and an Editor class to change things.
Drawing the circles
This code does something similar to double buffering. drawPoint() basically draws a circle into the mBitmap object¹. But this bitmap object is not yet visible. It exists in the memory. When onDraw() is called, it has a Canvas argument that represents the drawing surface of the view. All that drawBitmap() does here is use the prepared bitmap from the memory and draw it inside the views graphical representation to make it visible.
¹ The used canvas mCanvas is tied to mBitmap inside onSizeChanged()
Comment: In `drawPoint()`, the circle drawing call does not involve any bitmap at all! See: `mCanvas.drawCircle(x, y, radius, mPaint);` How does this work?
Comment: Yes thats what my ¹ point meant. When mBitmap is created with a certain size, mCanvas is assigned to it (line `            newCanvas.setBitmap(newBitmap);` , later on `mBitmap = newBitmap; mCanvas = newCanvas`). From this point on `mCanvas` edits the data inside `mBitmap`. And `mCanvas` is used here, it holds the drawing function `drawCircle()` as described in the first paragraph. That circle gets drawn inside the pixel data that the bitmap holds. :)
Answer:
From the Android SDK:

The Canvas class holds the "draw" calls. To draw something, you need 4 basic components: A Bitmap to hold the pixels, a Canvas to host the draw calls (writing into the bitmap), a drawing primitive (e.g. Rect, Path, text, Bitmap), and a paint (to describe the colors and styles for the drawing).

I'm assuming you're referring to this snippet:
@Override protected void onDraw(Canvas canvas) {
    if (mBitmap != null) {
        canvas.drawBitmap(mBitmap, 0, 0, null);
    }
}

Well it looks like an override of an inherited onDraw method which by default probably 'does nothing', hence the override to actually give it some behaviour, in this case given a non-null Bitmap instance, make the canvas draw it.
Answer: if you go to the developper refference:

drawBitmap(Bitmap bitmap, float left, float top, Paint paint)
Draw the
specified bitmap, with its top/left corner at (x,y), using the
specified paint,    transformed by the current matrix.

Then if you see that mBitmap doesn't exist in the class , thats cause that var comes from the extend from another activity .
Canvas also has a setBitmap(Bitmap bitmap) function . Then the solution is that that paint in canvas if you have set into it a bitmap object.

Android - canvas drawing doubts


Is it possible to add the standard errors of 2 groups together to obtain the standard error of the 2 groups combined

Question: I am trying to recreate the results in this table. The results have been obtained by difference in difference estimation. I can obtain values from all columns except for column 5 and 6.
Column 5 says that it is obtained by subtracting column 1 from column 2, and this is simple to do for the means, however I don't know of a way to add OLS regression standard errors of 2 groups together to give a combined standard error, and I don't know of any other way to estimate the combined standard errors.
Does anyone know if/how this can be done. Or does anyone have any advice on alternative methods for obtaining these values.
Thank you for any help.
Chris
Answer: Let $X_1$ be column 1, $X_2$ be column 2, $X_5$ be column 5.
Then
$$X_5 = X_2 - X_1$$
$$Var(X_5) = Var(X_1) + Var(X_2) -2Cov(X_1,X_2) =[SE(X_1)]^2 + [SE(X_2)]^2 -2Cov(X_1,X_2)$$
And $SE(X_5)=\sqrt{Var(X_5)}$.
So you need to get $Cov(X_1,X_2)$ in order to get $SE(X_5)$.
Or you can prove that $X_1$ and $X_2$ are independent such that $Cov(X_1,X_2) =0$.


Is Convexity necessary to use Gradient descent?

Question: I was reading and I saw that convexity is sufficient for using GD to minimize functions. Would it be also necessary?
Answer: Assuming the global minimum exists, no, as per the statement, convexity is sufficient, not necessary. Without convexity, gradient descent is not guaranteed to find the global optimum, but it might. It'll find a local optimum though, assuming a proper learning rate/policy is applied.


How to specify global markup font-size or other property in Lilypond

Question: Can I do this in Lilypond? I believe it's possible, however I could not find anything in docs about this.
My question is, instead of repeating like this:

g16-\markup {\tiny\underline\typewriter 1/16 }
g8-\markup {\tiny\underline\typewriter 1/8 }
g4-\markup {\tiny\underline\typewriter 1/4}

Is it possible to have those attributes grouped, then used simply where one would need them?
Answer: The straightforward way is to define a markup command:
<code>#(define-markup-command (tut layout props m) (markup?)
  (interpret-markup layout props
   #{ \markup \tiny \underline \typewriter #m #}))

{
  g16-\markup \tut 1/16
  g8-\markup \tut 1/8
  g4-\markup \tut 1/4
}
</code>
There is another already upvoted answer that is quite simpler.  Unfortunately, simpler than LilyPond would permit.
Comment: Here's a link to the LilyPond documentation: http://www.lilypond.org/doc/v2.18/Documentation/extending/new-markup-command-definition
Comment: Defining a function is such a pain for a language based on an functional engine.
Comment: Is there any guide on how to learn to write these?
Answer: There are several solutions to this. Here's another suggestion:
<code>tut = #(define-scheme-function
          (parser location text)
          (string?)
          #{\markup { \tiny \underline \typewriter #text }
          #})

{ g16 -\tut "1/16" }
</code>
Comment: Maybe this could even be put in an include file and re-used for other scores?
Answer: For a relatively simple approach, you can (as of 2.19.80) define a markup command using the syntax
<code>\markup tut = \markup \tiny \underline \typewriter \etc
{ g16-\markup \tut 1/16 }
</code>
Answer: Here is another way to temporarily save typing:
<code>\version "2.19.26"

\markupMap TextScriptEvent.text \markup \tiny \underline \typewriter \etc
{
  g16-"1/16"
  g8-"1/8"
  g4-"1/4"
}
</code>
Answer: For a relatively simple approach, you can define a macro:
tut = \tiny\underline\typewriter
g16-\markup {\tut 1/16 }
Comment: You surely can define a macro, but these two lines of code will almost certainly not work just like this.


Mudar body da aplicação inline ReactJS

Question: Olá, pessoal. Além de mudar o img com o id='pikachu' quando o usuário clicar três vezes no h1PIKACHU eu gostaria de mudar o body da aplicação para a mesma imagem. Alguém poderia me ajudar? O código está assim:
import React, { useState } from "react";

const InfoPokemon = ({ data }) => {
  const [contador, setContador] = useState(0);

  const pokemonImage = contador >= 3 ? `https://raw.githubusercontent.com/PokeAPI/sprites/master/sprites/pokemon/other/dream-world/${data.id}.svg` : 'https://i.imgur.com/ntFjCsD.png'

  return (
    <>
      {
        (!data) ? "" : (
          <>
            {data.name !== 'pikachu' ? (

{data.name}

            ) : (
               setContador((c) => c + 1)}>
PIKACHU

            )}
            {data.name !== 'pikachu' ? (
              <img src={`https://raw.githubusercontent.com/PokeAPI/sprites/master/sprites/pokemon/other/dream-world/${data.id}.svg`} alt="" />

            ) : (

            )}

              {
                data.abilities.map(poke => {
                  return (
                    <>

{poke.ability.name}

                    </>
                  )
                })
              }

              {
                data.stats.map(poke => {
                  return (
                    <>
                      <ProgressBar className="containerP" completed={poke.base_stat} customLabel={poke.stat.name} />
                    </>
                  )
                })
              }

          </>
        )
      }
    </>
  )
}
export default InfoPokemon;

Answer: Da pra fazer isso utilizando um useEffect, que observa o contador, e quando ele passar de 3, muda o background do body, imagino que seja isso:
useEffect(() => {
    if (contador = 3) {
      document.body.style.background = `url(${pokemonImage}) no-repeat`
    }
  }, [contador])

O useEffect, quando contém esse [contador] no final, é como se fosse um observador, que indica que esse código dentro (if(contador>=3){...}) vai rodar toda vez que o contador mudar de valor, então quando você clicar três vezes, ele muda o background do body para o pokemonImage.
Ai o background do body vai depender de como você quer que fique, então eu botei uma url(pokemonImage) e um no-repeat, mas isso é css, então tem que ver como melhor encaixar no seu código.
O código final fica assim :
import React, { useState } from "react";

const InfoPokemon = ({ data }) => {
  const [contador, setContador] = useState(0);

  const pokemonImage = contador >= 3 ? `https://raw.githubusercontent.com/PokeAPI/sprites/master/sprites/pokemon/other/dream-world/${data.id}.svg` : 'https://i.imgur.com/ntFjCsD.png'

  useEffect(() => {
    if (contador = 3) {
      document.body.style.background = `url(${pokemonImage}) no-repeat`
    }
  }, [contador])

  return (
    <>
      {
        (!data) ? "" : (
          <>
            {data.name !== 'pikachu' ? (

 setContador((c) => c + 1)}>{data.name}

            ) : (
               setContador((c) => c + 1)}>
PIKACHU

            )}
            {data.name !== 'pikachu' ? (
              <img src={`https://raw.githubusercontent.com/PokeAPI/sprites/master/sprites/pokemon/other/dream-world/${data.id}.svg`} alt="" />

            ) : (

            )}

              {
                data.abilities.map(poke => {
                  return (
                    <>

{poke.ability.name}

                    </>
                  )
                })
              }

              {
                data.stats.map(poke => {
                  return (
                    <>
                      <ProgressBar className="containerP" completed={poke.base_stat} customLabel={poke.stat.name} />
                    </>
                  )
                })
              }

          </>
        )
      }
    </>
  )
}
export default InfoPokemon;

Mudar body da aplicação inline ReactJS


field_get_items gives me an array of node IDs. Can I filter these by type without using node_load()?

Question: I have an entity reference user field for more than one content type. I need to filter the node IDs by content type without using node_load(). Is it possible?
If not, how badly would it affect performance to send the user ID to a view and filter them there?
Answer: Unless you have a map of those ids -> types somewhere outside the DB to reference, no, it's not possible. You could go directly into the node table yourself, of course, and avoid node_load specifically, but there's no way to do it without a db hit.
It's impossible to say how performant a View would be without knowing how your site is built, server specs, traffic info, and so on. The best thing to do would be to try it and benchmark.
Comment: Thanks. I think I can limit the performance impact enough for it not to be a big issue and if it is, using views results instead should be fine.. The page (statuses/share from the Statuses module) is actually loaded in an iframe by necessity so the rest of the page loads fine.


Which statistical test to use when some residuals are normal and some are non-normal?

Question: I have some response data from an experiment which uses appraisal methods to assign scores based on various attributes. The scores are awarded (in part) from visual observations of biological condition, i.e. the scales are ordinal, and also from quantitative measurements. The results of the visual observations and the mensuration are combined and the final response data is continuous. I have four different appraisal methods which all work in this way, using slightly different criteria and scoring.
The null hypothesis which I am testing is that my treatment has no effect on the score. When I run an ANOVA or linear model and examine the residuals, some are returned as normally distributed and some are not. I intend to publish the paper.
How do I deal with this in my analysis? Is it acceptable to run two types of test (ANOVA and a non-parametric test). I am using R (v 3.4.4) for my analyses.
Here is an example of one response using one way ANOVA.

The SW test shows non-normal residuals
Shapiro-Wilk normality test

    data:  residuals(aov_BURNLEY)
    W = 0.8724, p-value = 8.776e-08

Another example using one way ANOVA.

The SW test shows normally distributed residuals
Shapiro-Wilk normality test

    data:  residuals(aov_CTLA)
    W = 0.98722, p-value = 0.4526

And another example using one way ANOVA.

The SW test shows non-normally distributed residuals
Shapiro-Wilk normality test

    data:  residuals(aov_STEM)
    W = 0.37409, p-value < 2.2e-16

Answer: If you know right off the bat that your data is non-normal you should first look to see if it follows some other distribution. You can use the glm function which allows you to model distributions like binomial and Poisson. Or your data may be multinomial in which case you can use multinom or clm. If you want to go down the non-parametric path you should read up on some statistical computation work like Monte Carlo simulations and Bootstrap sampling.
Anyway the first plot you looked at looks like a gamma distribution which you can use glm(response ~ model, family = Gamma(link = "log"))
Comment: Thanks @Rex. Much of my response values are negative, and so those glm functions won't work. Apologies, I should have made that clear in my description above. Any other suggestions?
Comment: I would suggest a log transformation $log(Y + min(Y) + .01)$ that way you transform the data to positive values, shift the distribution to the right some and hopefully achieve near normality. Also remember to do a back transformation when interpreting results.
Comment: I had a feeling that would be a solution. I'm trying very hard to avoid any transformations to make this easy for the reader to interpret. Basically I'm hoping to find a suitable ANOVA-type test with a post-hoc analysis to test for differences between treatment levels. I could just look for differences between control and treatment though I suppose


Prevent puma from running in locally (ruby on rails)

Question: I'm recently started to use Puma for my production server with nginx, however, when I now try to run my app locally, it tries to run Puma with all my production settings and fails. How can I prevent Puma from running locally?
AFAIK all I've done was added the puma gem to my gemfile, so I don't know how it's accessing my server config (I'm just not too knowledgeable in this area). I have it in my production group:
group :production do
  gem 'pg'
  gem 'rails_12factor'
  gem 'puma'
end

Error:
→ rails s
=> Booting Puma
=> Rails 4.2.6 application starting in development on http://localhost:3000
=> Run `rails server -h` for more startup options
=> Ctrl-C to shutdown server
[8917] Puma starting in cluster mode...
[8917] * Version 3.4.0 (ruby 2.0.0-p645), codename: Owl Bowl Brawl
[8917] * Min threads: 1, max threads: 6
[8917] * Environment: development
[8917] * Process workers: 1
[8917] * Phased restart available
[8917] * Listening on tcp://localhost:3000
[8917] Use Ctrl-C to stop
/rbenv/versions/2.0.0-p645/lib/ruby/gems/2.0.0/gems/puma-3.4.0/lib/puma/runner.rb:103:in `reopen': No such file or directory - /Users/me/mll/shared/log/puma.stdout.log (Errno::ENOENT)

Additionally, though less important to me right now, is it in my benefit to run Puma locally? If so, any tips/resources on how I can do that?
Comment: how're you running it?
Comment: just running `rails s`
Comment: That's weird, I didn't think puma accepted config when using `rails s`
Comment: @Ben did you find a solution for your problem?
Answer: You need to put puma in your production group. Like this:
group :production do
   gem 'puma'
end

That way puma will only be used on production and not development.
Update
Make sure that your bin/rails file looks like this:
#!/usr/bin/env ruby
APP_PATH = File.expand_path('../../config/application', __FILE__)
require_relative '../config/boot'
require 'rails/commands'

Comment: Thanks for the reply - sorry I misspoke in my question - I put it in my production group and I still have the same issue (updated question)
Comment: Did you bundle after putting it in the `production` group?
Comment: yep. I even deleted the repo completely, cloned it again (w/ it already in production group) and re-bundled, same error
Comment: Or make sure that you don't have the gem in the gemfile outside that group. Also did you mess with this line in application.rb? `Bundler.require(*Rails.groups)`
Answer: Having the exact same issue with Ben. I try to use web brick on local while developing and testing, and puma in production.
Gem file is perfectly define as puma only sits in production group. 'bin/rails' and 'config/application' are checked, same as @Răzvan Ciocănel suggested. Still boot with 'puma' on local.
At last, have a look into the 'bundle install' gem list, 'puma' is installed along with other 'production' gem. Run 'bundle install --without production' and now local will boot with web brick as ROR default.
I guess as long as puma is bundle installed, it will be loaded on local unless you config something to force it off. So the solution might be to remove the gem in the bundle list in development and test.
Answer: Rails 3 project (it keeps hanging around longer than expected...)
I changed from unicorn to puma in the production group of my gemfile.
group :production do
  gem 'puma'
end

Then then when trying to run tests, or a dev server (which should have been thin) I got:
C:\Rails Projects\Rep>rails s
Could not find gem 'puma x86-mingw32' in any of the gem sources listed in your Gemfile or available on this machine.
Run `bundle install` to install missing gems.

After poking around a bit (including finding this question) I gave up and decided to go ahead and use puma in dev.  I ran bundle install and tried running server and voila, thin was working again.
Then I realized I still only had it in the production group--I looked back at the bundle install and nothing was installed, puma still isn't installed.  But now that bundle install has been run since the edit to the gemfile, everything works again.
C:\Rails Projects\Rep>rails s
=> Booting Thin
=> Rails 188.8.131.52 application starting in development on http://0.0.0.0:3000

So I guess the 'missing gem' error I wasn't because it was trying to actually run puma but rather some kind of bundler generated error due to unattempted gemfile?  Just putting this out in case it speed things up for anyone in similar circumstances who ends up here.


django: got an unexpected keyword argument while accessing ForeignKey _id-Field in Manager

Question: I have a model which looks like this:
class Mentorship (models.Model):
    mentor = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='mentor_user_id')
    mentee = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='mentee_user_id')

    objects = MentorshipManager()

    def clean(self):
        print(self.mentor_id)  # is set and printed to stdout
        print(self.mentee_id)  # is set and printed to stdout

        if Mentorship.objects.is_mentor(self.mentor_id, self.mentee_id):
            raise ValidationError(_('This user is already a mentor.'))

The manager has a function to check if someone is already a mentor of another user, which is called while clean()ing the instance:
def is_mentor_for_goal(self, mentor_id, mentee_id, personal_goal_id):
    if self.exists(mentor_id=mentor_id, mentee_id=mentee_id):
        return True
    else:
        return False

However I always get an exception while accessing the mentor_id or mentee_id attribute in exists:
Django Version:     1.6.1
Exception Type:     TypeError
Exception Value:    exists() got an unexpected keyword argument 'mentor_id'

Is there a reason why I cannot access the _id field within the manager? I just don't understand why the field is accessible in the (unsaved) instance, but not in the manager.
Comment: Try this : `mentor__id=mentor_id` .
Answer: Oh... man... It should be called
if self.filter(mentor_id=mentor_id, mentee_id=mentee_id).exists()

Thanks for your comments
Answer: A few things mentor__id will only work in queryset methods, not things like print. You should also use pk instead of id, here is how it would work:
class Mentorship(models.Model):
    mentor = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='mentor_user_id')
    mentee = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='mentee_user_id')

    objects = MentorshipManager()

    def clean(self):
        print(self.mentor.pk)  # is set and printed to stdout
        print(self.mentee.pk)  # is set and printed to stdout

        if Mentorship.objects.filter(mentor=self.mentor).exists():
            raise ValidationError(_('This user is already a mentor.'))

def is_mentor_for_goal(self, mentor_id, mentee_id, personal_goal_id):
    return self.exists(mentor__pk=mentor_id, mentee__pk=mentee_id)


Checking for property on the object passed to jquery tmpl

Question: I have a sample data like this:
data = {opt1: 'One', opt2:'Two', opt3:'Three'};

tmplString =
${opt1}

${opt2}
??IF OPT3??

$('#node').append(tmplString, data);

In my tmplString I want to render opt3 only if the passed in data has a property called opt3. If I use {{if opt3}} it throws an error when there is no opt3 in the data. Is there a way I could use something like if(prop in obj).
Answer: I ran into this problem recently and tried the solution provided by idrumgood.  Unfortunately in my case the data may be null or it may be undefined and
typeof null === "object"

so using typeof on the value does not distinguish between null and actual data resulting in an error by jquery templates.  I found that if you scope the variable with the $data template variable you can avoid this problem.  For instance, instead of this:
{{if opt3}}
${opt3}

use this:
{{if $data.opt3}}
${opt3}

Here is a jsfiddle demonstrating this solution
Answer: You should be able to use:
if(typeof opt3 == "string")

Or, if you might have something other than a string in there:
if(typeof opt3 != "undefined")

Comment: You mean: "{{if typeof ${opt3} != 'undefined'}}"  ?
Comment: I'm not familiar with jQuery template syntax, but what I have is plain old js, if that'll work.
Comment: checking the `typeof` will not cause an error to be thrown if the element is undefined.


iOS Reachability is not detecting "No Service" in the device as "NotReachable"

Question: I'm using the Reachability class provided by Apple and I'm listening for the reachabilityChanged: notification:
- (void)reachabilityChanged:(NSNotification *)notification
{
   Reachability *reach = [notification object];

   if ([reach isKindOfClass: [Reachability class]]) {
       NetworkStatus status = [reach currentReachabilityStatus];

       if ((status == ReachableViaWiFi) || (status == ReachableViaWWAN)) {
          // Some operations here
       }
   }
}

When I set flight mode or disable WiFi and cellular data in settings, I get a "NotReachable" status in reachabilityChanged:, but when my device seems to just lose the connectivity temporarily for whatever reason (having communications enabled in settings), the "NotReachable" status seems to not being detected.
I've done some tests with a jammer, and when the device goes to "No Service" in the status bar and reachabilityChanged: is called, I've seen that the NetworkStatus is "ReachableViaWWAN" instead of "NotReachable" as I expected.
I need to detect such "No Service" status in the device, how could I?
Comment: are you plugged in via usb to your computer? Is it sharing the network connection?
Comment: @Fogmeister it is plugged in to see logs in Xcode, but it only has cellular data enabled
Comment: yes. But if your computer is sharing it's Internet connection via usb then the phone will still have connection.
Comment: @Fogmeister I disconnected the device from the computer and I'm still getting a "ReachableViaWWAN" status when the device has "No Service"...
Comment: Did you ever solve this? I am having the same issue.
Answer: Credit goes to this person. This worked for me:
- (BOOL)networkCheck
{
    Reachability *wifiReach = [Reachability reachabilityForInternetConnection];
    NetworkStatus netStatus = [wifiReach currentReachabilityStatus];

    switch (netStatus)
    {
        case NotReachable:
        {
            NSLog(@"%@",@"NETWORKCHECK: Not Connected");
            return false;
            break;
        }
        case ReachableViaWiFi:
        {
            NSLog(@"%@",@"NETWORKCHECK: Connected Via WiFi");
            return true;
            break;
        }
        case ReachableViaWWAN:
        {
            NSLog(@"%@",@"NETWORKCHECK: Connected Via WWAN");
            return true;
            break;
        }
    }
    return false;
 }

And then in the ReachableViaWWAN case:
case ReachableViaWWAN:
{
    NSLog(@"%@",@"NETWORKCHECK: Connected Via WWAN");
    NSData *responseData = [NSURLConnection sendSynchronousRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"www.google.com"]] returningResponse:nil error:nil];
    if (responseData != nil)
    {
        return true;
        break;
    }
    else
    {
        return false;
        break;
    }

}


Will about 10 loose hairs in a violin bow make any difference when I use it?

Question:
It's something like the image above, just less loose hairss. While I was looking at it, I tried playing the violin, and some hairs got loose.
Do I just cut them off or yank them off? This little book that came with it said, "Do not attempt your own repairs. Only an expert musical instrument repairman has the skill and experience to repair the instrument."
Comment: What happens if you tighten the bow a little?
Comment: When was your bow last rehaired?  Do you make sure to completely detension your bow when done playing (every time)?
Comment: Could you post a picture of your bow?
Answer: All the hairs should tighten at about the same rate. That bow looks very slack. If individual hairs break, they can be pulled out or cut off - I've seen concert violinists do this mid concert - usually snatched off.
If all the hairs don't tighten together, it's a job for a techie.
Answer: I would carefully cut them off rather than yank them out.  The latter might loosen still more.  If it keeps happening, you should take it to a reputable repairer and find out what the problem is.


Angular Observable object access

Question: I am current learning and getting used to Angular, and while getting information from an Observable I am unable to get it out of object form.
public rowData$!: Observable<any[]>;

UpdateGrid() {
  this.rowData$ = this.http
    .get<any[]>('http://localhost:8080/data');
    this.rowData$.forEach(value => console.log(value));
}

This console log gives me the proper http response:
(2) [{…}, {…}]
 0: {id: 1, name: 'Bob', sex: 'Male'}
 1: {id: 2, name: 'Susan', sex: 'Female'}
length: 2
[[Prototype]]: Array(0)

My tries of using mapping and other ways of extracting the data have failed, and each time I just get Object object whenever the extraction is displayed in html.
Is there an easy way to pull out the data? Any help is appreciated, I can't seem to find an answer online and the docs give examples that I haven't been able to get working. Thank you.
Comment: How do you display this in your template? Do you use the `| async` pipe? Do you bind the array entries to any html elements or do you just want to print out the array as text? See if `{{ rowData$ | async | json }}` yields any results.
Comment: That did work for printing the http response, thank you. I tried the async pipe on its own without success, so the addition of the json is what did it. The one other issue I am still working on is getting it loaded into an object that I can feed into rows in ag-grid.
Comment: I'm not entirely sure how that object would need to look like, but I'll compile an answer and add a bit of explanation on where you could do that :)
Answer: These are basically two questions in one. How to print the array as a string inside your template (which I suppose you only need for debugging purposes) and how to transform the array before passing it to ag-grid. Let's try to answer these in order.
How to print Observable data on the template
When binding to the content of your HTML using the interpolation syntax ({{ }}), angular calls the toString() method under the hood if the object to be bound is not a primitive. This means, getting an output [object Object] is what the bound object's toString() method returns - and is the default for all objects if not implemented otherwise. For arrays, the implementation is overwritten and usually returns the values inside the array joined by a comma and if the array elements are objects themselves, it calls the toString() function on those. This leads to the behaviour you are observing.
This means you have to either override the toString() method for the inner objects, or stringify the value yourself. Angular provides the | json pipe which does this stringification for you using the JSON.stringify() method under the hood.
Using your data as an example, these are the outputs you'd be seeing:

{{ rowData$ }}

{{ rowData$ | async }}

{{ rowData$ | async | json }}

How to transform the data
Since you did not provide what format you want the data in, I'll show you where you can put transformation logic with observables in general.
Each observable has a .pipe() function which takes operators you can apply to the stream to transform it. The operator you need is the map operator, since you want to transform each received value (in your case: the whole array) into a different value (in your case: a new array containing different looking objects).
import { map } from 'rxjs/operators'; // <-- import the operator

@Component({ /* omitted */ })
export class MyComponent {
  public rowData$!: Observable<any[]>; // digression: Try to avoid any, it removes typesafety

  updateGrid() { // digression: Use lower camel case for method names, it's a convention :)
    this.rowData$ = this.http
      .get<any[]>('http://localhost:8080/data')
      .pipe(
        map(rowData => // <-- use the map operator here, it takes each value and returns a new one
          rowData.map(entry => { // <-- map each object in your array
            // return a new entry in the format you need
          });
        )
      );
  }
}

Comment: Thank you, your answer provided insight on the process that is helpful for me! The issue I was facing ended up not being a problem with the object that I was trying to change the form of. I was working with an ag-grid component that wasn't rendering properly but was taking the data correctly. Due to that, I assumed it was a datatype issue which caused my question of conversion and output, which I was using for debugging. Thank you again for your detailed response!

Angular Observable object access


Android - How to draw an arc based gradient

Question: I am trying to create an arc (variable number of degrees) that gradually goes from one color to another. From example from blue to red:

This is my code:
SweepGradient shader = new SweepGradient(center.x, center.y, resources.getColor(R.color.startColor),resources.getColor(R.color.endColor));
Paint paint = new Paint()
paint.setStrokeWidth(1);
paint.setStrokeCap(Paint.Cap.FILL);
paint.setStyle(Paint.Style.FILL);
paint.setShader(shader);
canvas.drawArc(rectF, startAngle, sweepAngle, true, paint);

But the result is the entire arc is painted with the same color.
Edit:
After more experimenting, I found out that the color spread is determined by the angle of the arc. If I draw an arc with a small angle, only the first color is displayed. The larger the angle, more colors are drawn. If the angle is small it seems that there is no gradient. Here is an example. I am drawing 4 arcs - 90, 180, 270 and 360:
RectF rect1 = new RectF(50, 50, 150, 150);
Paint paint1 = new Paint();
paint1.setStrokeWidth(1);
paint1.setStrokeCap(Paint.Cap.SQUARE);
paint1.setStyle(Paint.Style.FILL);

SweepGradient gradient1 = new SweepGradient(100, 100,
        Color.RED, Color.BLUE);
paint1.setShader(gradient1);

canvas.drawArc(rect1, 0, 90, true, paint1);

RectF rect2 = new RectF(200, 50, 300, 150);
Paint paint2 = new Paint();
paint2.setStrokeWidth(1);
paint2.setStrokeCap(Paint.Cap.SQUARE);
paint2.setStyle(Paint.Style.FILL);

SweepGradient gradient2 = new SweepGradient(250, 100,
        Color.RED, Color.BLUE);
paint2.setShader(gradient2);

canvas.drawArc(rect2, 0, 180, true, paint2);

RectF rect3 = new RectF(50, 200, 150, 300);
Paint paint3 = new Paint();
paint3.setStrokeWidth(1);
paint3.setStrokeCap(Paint.Cap.SQUARE);
paint3.setStyle(Paint.Style.FILL);

SweepGradient gradient3 = new SweepGradient(100, 250,
        Color.RED, Color.BLUE);
paint3.setShader(gradient3);

canvas.drawArc(rect3, 0, 270, true, paint3);

RectF rect4 = new RectF(200, 200, 300, 300);
Paint paint4 = new Paint();
paint4.setStrokeWidth(1);
paint4.setStrokeCap(Paint.Cap.SQUARE);
paint4.setStyle(Paint.Style.FILL);

SweepGradient gradient4 = new SweepGradient(250, 250,
        Color.RED, Color.BLUE);
paint4.setShader(gradient4);

canvas.drawArc(rect4, 0, 360, true, paint4);

And here is the result:

This is surprising because I'd expect the RED to be at the start of the arc, the BLUE at the end and enything between to be spread evenly regardless of angle.
I tried to space the colors manually using the positions parameter but the results were the same:
int[] colors = {Color.RED, Color.BLUE};
float[] positions = {0,1};
SweepGradient gradient = new SweepGradient(100, 100, colors , positions);

Any idea how to solve this?
Answer: The solution for this is to set the position of BLUE. This is done like so:
int[] colors = {Color.RED, Color.BLUE};
float[] positions = {0,1};
SweepGradient gradient = new SweepGradient(100, 100, colors , positions);

The problem here is that when setting the position of BLUE to '1' this does not mean that it will be positioned at the end of the drawn arc, but instead at the end of the circle of which the arc is part of.
To solve this, BLUE position should take into account the number of degrees in the arc. So if I'm drawing an arc with X degrees, position will be set like so:
float[] positions = {0,Xf/360f};

So if X is 90, the gradient will place BLUE at 0.25 of the circle:
Comment: At least on Android 4.2, the solution as given doesn't work.  There is a need to have a value of 1 at the end of the array.

Something like this:

int[] colors = {Color.RED, Color.BLUE, Color.BLUE};
float[] positions = {0, Xf/360f, 1};
Comment: Do you know why the resolution is so bad if the angle is very small? like an arc width of 10 degree means just 3 colors. You can see the steps also in your screenshot in the topleft cake
Answer: To add to Yoav's solution.
On my Galaxy Nexus 4.2 stock Android, the solution given doesn't work.
If the array doesn't contain a 0.0f and 1.0f, it appears to be ignored.
My final solution was:
int[] colors = {Color.RED, Color.BLUE, Color.RED};
float[] positions = {0, Xf/360f, 1};

Answer: five years later, but the right way is make 0.749f with 0.750f of the separate line, simple code is like:
    val colors = intArrayOf(0xffff0000.toInt(), 0xff0000ff.toInt(), 0xffff0000.toInt(), 0xffff0000.toInt())
    val positions = floatArrayOf(0.0f, 0.749f, 0.750f, 1.0f)

Answer: Using SweepGradient, you can pass null for positions (in case you want default gradient) and you can also rotate the gradient by setLocalMatrix
override fun onDraw(canvas: Canvas?) {
    super.onDraw(canvas)
    val centerX = width.toFloat() / 2
    val centerY = height.toFloat() / 2

    val paint = Paint()
    paint.isAntiAlias = true

    val colors = intArrayOf(Color.RED, Color.BLUE)
    val gradient = SweepGradient(centerX, centerY, colors, null) // null position
    val matrix = Matrix()
    matrix.postRotate(270f, centerX, centerY) // rotate
    gradient.setLocalMatrix(matrix)
    paint.shader = gradient

    val radius = 400f
    val oval = RectF(centerX - radius,centerY - radius,centerX + radius,centerY + radius)
    canvas?.drawArc(oval, 0f, 360f, false, paint)
}


How to update ModelState?

Question: This is a controller action that I call with ajax post method:
<code>    [HttpPost]
    public ActionResult Add(Comment comment)
    {
        if (User.Identity.IsAuthenticated)
        {
            comment.Username = User.Identity.Name;
            comment.Email = Membership.GetUser().Email;
        }

        if (ModelState.IsValid)
        {
            this.db.Add(comment);
            return PartialView("Comment", comment);
        }
        else
        {
            //...
        }
    }
</code>
If the user is logged in, submit form doesn't have Username and Email fields, so they don't get passed by ajax call. When action gets called ModelStat.IsValid returns false, because these two properties are required. After I set valid values to properties, how do I trigger model validation to update ModelState?
Answer: You can try calling the built in TryUpdateModel method which returns a boolean so you can check that value.
UPDATE:  Try using TryUpdateModel with exceptions. Use a formcollection instead of Comment into the Action.
<code>[HttpPost]
    public ActionResult Add(FormCollection collection)
    {

        string[] excludedProperties = new string[] { "Username". "Email" };
        var comment = new Comment();
        if (User.Identity.IsAuthenticated)
        {
            comment.Username = User.Identity.Name;
            comment.Email = Membership.GetUser().Email;
        }

        TryUpdateModel<Comment>(comment, "", null, excludedProperties, collection.ToValueProvider());

        if (ModelState.IsValid)
        {
            this.db.Add(comment);
            return PartialView("Comment", comment);
        }
        else
        {
            //...
        }
    }
</code>
Comment: Nope, that's first thing I tried and all other method in a controller: UpdateModel, ValidateModel, TryValidate. None of that works, I get an exception: Model can't be updated/validated or somthing similar.
Comment: In that case why not use a ViewModel? This will encompass all the properties you do pass to the Action and no need to worry about the missing ones.
Comment: I think its not a good idea to use a viewmodel with something that will be server added like a user from the the membership
Answer: You can use a custom model binder to bind the comment's Username and Email properties from User.Identity. Because binding occurs before validation the ModelState will be valid then.
Another option is to implement a custom model validator for the Comment class, that checks the ControllerContext.Controller for a validated user.
By implementing any of these options you can remove the first if check.
Comment: Don't be afraid, those are the cleanest, the "most MVC" solutions. By applying them you will also learn a bit more about the framework you are working with.
Comment: any chance someone could post an example of how you would use the model binder in OP's case?
Comment: I was afraid that it will come to that. Any other solution?
Comment: Yes, I know. I was just hopping to keep it simple. I've implemented custom model binder, that way I kept validation. Thanks for pointing me in right direction.

How to update ModelState?


Singing: Head and Chest Voice, let them come naturally or intentionally?

Question: I am taking Singing lessons, and starting to read about Head Voice and Chest Voice. I was told to sing from the Diaphragm. Does this also mean I should

start singing from the head and chest voice intentionally,
or generally sing from the diaphragm and Naturally let chest and head voice come without thinking about it?

Resource:
https://www.aimm.edu/blog/head-voice-vs-chest-voice
Chest Voice - When you sing using your normal speaking register, or close to it, put your hand on your chest, and you will feel a vibration. If you have good airflow and are not straining, you should develop a warm tone that doesn't waver or crack.
Head Voice - When a singer starts reaching up to those higher notes, they may feel the sound and vibration in their head.
Answer: You are overthinking this.  A carpenter does not ask whether they should let their moves with a circular saw come naturally or intentionally.  Of course an experienced singer will change registers mostly "naturally" but that kind of naturality takes a lot of practice.
The actual "natural" register change is your voice flipping involuntarily.  That kind of naturality is not desired in singing, but "singing through the break", namely staying in pitch and articulation control reflexively while changing registers, is certainly part of the training regimen of singers.  As is reducing the impact/change on tonal quality happening during the break.
A trained singer has a considerable latitude of where to change registers, and having the voice flip unexpectedly with large character change is about as likely as a gymnast falling over spontaneously while walking and breaking a limb.  Does that mean that the singer or the gymnast are singing or walking unnaturally?
No.  It means that they are trained and have better control, anticipation and reflexes.
That's not something you get to choose.  It is a sideeffect of training and practice.
Answer: "Singing from the diaphragm" applies equally to chest voice and head voice. It primarily means that you should use abdominal breathing rather than chest breathing, regardless what register you're in.
Achieving a smooth transition from chest to head voice is an important aspect of learning to sing, and you will probably spend a fair amount of time figuring out which notes to sing in what register, but you should always use proper breathing and try to get power from your abdomen rather than increasing tension in your neck and shoulders.
That said, have you asked your singing instructor? If you don't fully understand what they mean, they will hopefully have a better explanation than we do.
Comment: so are you saying I should go with option 2 in my question, and not think about it, only think about the diaphragm?
Comment: I would suggest to focus on the diaphragm until you have made correct breathing a habit, at which point you can pay attention to the register; and to remind yourself of the diaphragm every time you feel you're struggling with high notes and tensing up. Also, listen to what your instructor is saying. That's what you pay them for.


Retorno do select traz valor anterior - jQuery

Question: Tenho uma tabela #tabela e gostaria que a cada vez que eu faço um filtro pelo select ele some a quantidade que está na coluna 6 eq(5). Com o código abaixo ele está executando, porém ele exibe o valor anterior que eu seleciono. Por exemplo, está exibindo 3 linhas com 5, 5 e 5 em cada uma delas. Quando eu troco o option do select para qualquer outra opção, aí que ele vai me mostrar a soma, 25 no console.
 $('select').on('change', function() {
    var qtd = 0
    $("#tabela tbody tr:not(.filtered)").each(function(){
        qtd += parseInt($(this).find('td').eq(5).html())
    });
    console.log(qtd);
});

Qual evento eu poderia utilizar para que ele calculasse quando troco a seleção do <select>. Eu havia pensado no óbvio, o change.
Sou iniciante eh jQuery, então se o código puder ser escrito de uma melhor forma, fique a vontade para sugerir.
Obrigado.
Comment: O valor do select na verdade não me importa. Eu utilizo ele apenas para filtro, se seleciono opção Teste, ele filtra para 3 linhas na tabela, por exemplo. Eu então conto as linhas filtradas, pela classe .filtered. E assim vou somando a cara linha para saber o total que tenho.
Comment: Se ao mudar o select é efetuado o fltro e ao mesmo tempo chamado o "onchange", vai dar problema porque as duas coisas não vão ser processadas em sincronia.
Comment: É o próprio jQuery que faz, um script que uso a classe tablesorter. Veja nesta imagem https://uploaddeimagens.com.br/imagens/img-jpg--188. Eu quero somar o 50 + 1 quando eu troco o filtro de qualquer select (seta preta). Ele soma, mas ele vai mostrar o 51 só depois q eu trocar o filtro de novo.
Comment: E como eu poderia fazer que isso funcione, é possível?
Comment: O plugin é este http://tablesorter.com/docs/?
Comment: Ainda continua calculando depois que troco de option. =/
Comment: Isso, estão assim os ths: Nº Licença e o table:
Answer: O plugin Tablesorter Filter Widget possui um trigger que é disparado após o fim do filtro.
Então coloque os cálculos dentro do trigger:
$("#tabela").on("filterEnd",function() {
   var qtd = 0
   $("#tabela tbody tr:not(.filtered)").each(function(){
      qtd += parseInt($(this).find('td').eq(5).html())
   });
   console.log(qtd);
});

Coloque após a inicialização do plugin:
$("#tabela").tablesorter();

Comment:

Estes são os scripts que eu chamo na página menu.php e nesta página que tenho o código eu faço um include neste menu.php. Mas em ambas eu não tenho esse $("#tabela").tablesorter();
Comment: @netovgs Seria bom disponibilizar um exemplo de HTML da tabela incluindo os selects pra gente dá uma olhada.
Comment: Coloquei este seu código no fim do meu, e não retornou nada.
Comment: @netovgs Tinha que ver onde é que o plugin é inciado. Não precisa ser exatamente `$("#tabela").tablesorter();`, mas alguma coisa parecida
Comment: @netovgs Troca o "change" por "blur" para ver se funciona. O "blur" vc deve alterar o select e tirar o foco dele.
Comment: Fiz o que vc disse, e já apareceu uma luz rs...ele calcula agora conforme eu tiro o foco do Select. Só que aí tento colocar isso: $("#tabela thead tr td input[type=search]").eq(0).focus() para jogar o foco em um input search do lado e assim ele calcular. Mas quem diz que isso funciona?! Se eu uso somente este código ele seleciona exatamente o objeto, agora se eu coloco o .focus, ele não coloca o foco no input. O código está correto ou tem outra forma para fazer? Seila, um lostfocus depois do blur...está por pouco rsrs. Obrigado.
Comment: Vamos [continuar esta discussão no chat](http://chat.stackexchange.com/rooms/72426/discussion-between-netovgs-and-dvd).
Comment: Alguém com alguma sugestão para ajudar? Talvez como dar um tab após o change do select e assim executar o blur...nem sei se seria o caminho correto. =/
Comment: Agora sim!!! Tem o mesmo resultado que o meu, mas sem dúvidas o seu é muito mais prático e limpo. Muito obrigado @dvd.
Answer: Consegui fazendo da seguinte forma:
$(document).ready(function() {
    var qtd = 0;

    $('select').on('blur', function(e) {
        qtd = 0;
        $("#tabela tbody tr:not(.filtered)").each(function() {
            qtd += parseInt($(this).find('td').eq(5).html());
        });
    });

    $('select').on('change', function() {
        setTimeout (function() {
            $("#tabela thead tr td input[type=search]").eq(0).focus();
            $('#total').html(qtd);
        }, 300);
    });
});

Não sei se esta é a melhor forma para se fazer isso, se está seguindo as boas práticas. Caso alguém tenha uma forma mais correta, por favor compartilhe.
@dvd obrigado por sua ajuda.
Abraços.


Optimization with Lagrangian multiplier

Question: I have a function, fd, which I hope to optimize using an equality constraint.  Here is the function:
fd = 224 * d1 + 84 * d2 + d1 * d2 - 2 * d1^2 - d2^2

and constraint:
3*d1 + d2 = 280

Someone has solved this problem by incorporating the constraint into the function using a Lagrangian multiplier.  The new function Ld.lambda is:
Ld.lambda = 224 * d1 + 84 * d2 + d1 * d2 - 2 * d1^2 - d2^2 + lambda * (280 - 3*d1 - d2)

They used the following R code to obtain the values of d1, d2 and lambda that maximize, I think, the new function, Ld.lambda:
# Lagrangian multiplier method
obj_c <- function(param)
                 {x1     <- param[1]
                  x2     <- param[2]
                  lambda <- param[3]
                  L      <- 224*x1+84*x2+x1*x2-2*x1^2-x2^2+lambda*(280-3*x1-x2)
                  L
         }

# gradient function or partial derivatives of Ld.lambda
grad_c <- function(dec)
                  {x1     <- dec[1]
                   x2     <- dec[2]
                   lambda <- dec[3]
                   g1     <- 224+x2-4*x1-3*lambda
                   g2     <- 84+x1-2*x2-lambda
                   g3     <- 280-3*x1-x2
                   c(g1,g2,g3)
           }

# linear solver to estimate optimality conditions
a <- matrix(data<-c(4,-1,3,-1,2,1,3,1,0),nrow=3,ncol=3,byrow=T)
b <- c(224,84,280)
dec <- solve(a,b)
dec
# [1] 69 73  7

The optimal values are estimated to be:
d1 = 69
d2 = 73
lambda = 7

However, if I attempt a quasi-exhaustive search in R the optimal values appear to be:
d1 = 69
d2 = 73
lambda = -infinity to +infinity

Apparently because:
(280 - 3*d1 - d2) = 0 when d1 = 69 and d2 = 73, in which case the value of lambda is irrelevant.
Here is the R code for the quasi-exhaustive search:
my.data <- expand.grid(x1 = seq(0, 200, 1), x2 = seq(0, 200, 1), x3 = seq(0, 200, 1))
head(my.data)
dim(my.data)

d1     <- my.data[,1]
d2     <- my.data[,2]
lambda <- my.data[,3]

Fd <- 224 * d1 + 84 * d2 + d1 * d2 - 2 * d1^2 - d2^2 + lambda * (280 - 3*d1 - d2)

new.data <- data.frame(Fd = Fd, d1 = d1, d2 = d2, lambda = lambda)
head(new.data)

# Impose constraint
new.data <- new.data[(3 * new.data$d1 + new.data$d2) == 280, ]

# identify values of d1, d2 and lambda that maximize Fd with the constraint
head(new.data[new.data$Fd == max(new.data$Fd),], 10)
tail(new.data[new.data$Fd == max(new.data$Fd),], 10)

Why does the Lagrangian multiplier method estimate the optimal value of lambda = 7 and the quasi-exhaustive search estimate the optimal value of lambda = -infinity to +infinity?
What am I doing incorrectly or misunderstanding?
Answer: Bottom line up front: You should be solving a system of equations involving the Lagrange multiplier, not maximizing it.  Details are below.
Details: The Lagrange multiplier method consists of solving the Karush-Kuhn-Tucker (KKT) conditions for first order optimum, i.e., actually, stationary point. See https://en.wikipedia.org/wiki/Karush%E2%80%93Kuhn%E2%80%93Tucker_conditions . Without looking at 2nd order conditions, you can not determine whether the solution is actually an optimum. In your case, because you have no inequality constraints, the KKT conditions take the simpler form (special case) shown in https://en.wikipedia.org/wiki/Lagrange_multiplier, and are the same for minimization and maximization; so in addition to the possibility of finding a saddle point, you could be finding a local maximum or local minimum.
Note that although your problem falls under the simpler special case described in the 2nd link, the first link provides a much better theoretical explanation as to what is going on, which is needed to understand what is going on in the 2nd link.
However, because your objective function is concave (and sufficiently differentiable) and your constraint is linear, thereby satisfying regularity conditions (constraint qualification), KKT conditions are necessary and sufficient for the solution to be a global maximum. Indeed, your objective function is strictly concave, so in this case, the KKT conditions have a single solution, which is the global maximum.
So I think the first method is solving the KKT conditions, which in your case is (just) a system of linear equations.
If you had any inequality constraints, you would need to use the more general form of KKT conditions shown in the first link, and those aren't necessarily easy to solve.  In practice, many numerical optimizers for constrained optimization set up subproblems to drive toward a solution to the KKT conditions, which in "typical" cases do not admit a closed form or non-iterative solution, although they do in some cases.  See Variance of weighted mean greater than unweighted mean for an example in which KKT conditions involving inequality constraints can be solved in closed form, although I didn't show the details of how i did it.

Optimization with Lagrangian multiplier


If A is 5 * 7 and B is 7 * 5 Prove that BA is singular.

Question: I need to show that if $ A $ and $ B $  are $ 5 \times 7 $ and $ 7 \times 5 $ matrices respectively, then the matrix $ BA $ is singular. Is that correct for $ AB $ as well?
Thanks in advance.
Comment: http://math.stackexchange.com/questions/1870747/invertibility-of-ba/1870775#1870775
I guess we both study in the Open University?
Comment: Do you mean $A$ has dimension $5 \times 7$?
Answer: Hint: What size is $BA$? What can we say about its rank?
Answer: Hint: $ A $ is a linear map $ K^7 \to K^5 $ for some field $ K $. Can it be injective?


A man bought three tables for rs. $2500$, then find the prices of the individual tables?

Question: Problem  A man bought three tables for rs. $2500$. He sell the first at $5  $ % loss, second at $5  $ % profit and the  third at $10$% profit. Find the cost price of each table if on the whole he neither gains nor losses.
Solution
Let cost price of first table be x
Let cost price of second table be y
then cost price of third table $= 2500-(x+y)$
$0.95x +1.05y +1.10  [2500-(x+y)]=2500$
$3x+y =5000$
What next $?$
How can we find the answer $?$
Comment: answer can be  $ 625,625 $and $1250$
Answer: There's not much you can do, the question does not have a unique solution. You can, however, move forward a bit by considering the fact that all prices must be positive (or at least not negative), so that $2500-(x+y)\geq 0$ which yields $5000=3x+y=2x+(x+y)\leq 2x+2500$, so $x\geq 1250$. In addition since $y\geq 0$ you also have $5000=3x+y\geq 3x$ so $x\leq \frac{5000}{3}$. However, it is still true that for every $x$ in that range you still get a solution.
For example: $x=1250, y=1250, z=0$ is a solution where the loss/profit on the first two tables cancel each other and the third one is meaningless, but $x=1500, y=500, z=500$ is also a valid solution, and so is $x=\frac{5000}{3}, y=0, z=\frac{5000}{6}$.
Answer: Let the prices be $x,y,2500-(x+y)=z$ so $x+y+z=2500$ but acc. To condition total loss = total profit so $95x/100=105y/100+110z/100$ . Now just plug in values as per choice as its an open end question one of the answer can be $2000,500,0$ . But that hardly makes sense. Hope it helps you.


Translate View footer

Question: I'm trying to translate a link in footer on my views .
the code is :
<?php
$link = l(t('Click to view all the writing categories'), 'somewhere', array('attributes' => array('class' => array('read-latest'))));
print $link;
?>

The problem is after tranlate it from admin/config/regional/translate .
the output is
 no link and no  tag .
Any idea ?
Comment: Make a var_dump of `$link`. Is there any error in watchdog? Did you try to just print the translated string? Did it work?
Comment: @Paul how can i print the translated string ?
THX anyway
Comment: Instead of `print $link;` try `print t('YOUR UNTRANSLATED TEXT');` first. Does this return the translated text? What's the result?
Answer: by this module String Overrides you can translate strings .
That's it

Translate View footer


Linux RDP/VNC/SSH Client

Question: I use loads of machines daily.  Each uses different connection methods, either remote desktop, VNC or SSH.  My desktop is Linux, it would be nice if I had a tabbed interface for them all so I don't have to remember which is VNC, which is RDP etc.
Does anyone know of any of the following:

A tabbed VNC, remote desktop and SSH client OR
A tabbed VNC AND remote desktop client OR
A tabbed VNC client OR
A tabbed remote desktop client

Bullet points are in priority order, I'd prefer have a client that supports them all to prevent my taskbar becoming cluttered.  It's important that I'm able to detach tabs however, so I can move specific tabs to another monitor.
Comment: What descktop environment do you use (or have available)? KDE/Gnome/etc.?
Comment: I use Gnome, although have all the KDE libs so could use an application for either.
Answer: Grdc looks like one option, though I don't have any experience with it myself.
It supports RDP (Remote Desktop), VNC, and SSH.
Answer: Just for reference, there is the KDE application Krdc but I believe it only supports VNC and RDP, not SSH.  (And actually to be honest, sometimes it hasn't worked for me... not sure what's up with that)

Linux RDP/VNC/SSH Client


Techniques for arranging multiple, complementary compositions

Question: One thing I find mystifying is the art of arranging multiple compositions. I tend to either put pieces together that are jarring, or else they are too similar in tone, and just banally blend together like painting a wall eggshell white, and the moldings ivory.
What secrets are there to the technique of combining multiple scores together so that they complement one another?
Comment: Do you mean selecting pieces for a concert - or a book or recording - and deciding in what order to perform them?
Comment: @MichaelCurtis Well, it could be anything, creating a score for a movie, or a book, or a play, or a concert, or anything.
Answer: Creating a set of music for a concert, theater, or movie all require different approaches. Much of deciding choices is a matter of experience. Choosing pieces for theater and movies is scene dependent and is complicated by requiring pieces that match the mood or action of the scene.
The simplest is probably setting a list for a concert or musical performance.
When choosing piece order, there are a number of things to take into account. These are not all the variables, but some examples:

Key of each piece
Tempo and/or rhythm of each piece
instrumental arrangement
lead vocalist

Key is one of the main considerations. It is probably better to avoid multiple pieces of all the same key/tempo/time all in a row. Keys of pieces can be arranged much like you would put together chord progressions.  If you are transitioning from one major key to another major key, I've found that moving up seems to be an easier transition than moving down. For example, moving from D major to a piece in E major. I avoid downward motion because it seems to "drag" the feeling. Moving to the relative sub dominant or dominant is also effective. Switching to a minor piece is generally pretty easy, especially if going to parallel or relative minor of the previous piece.
Tempo of the pieces is another strong effect. Over the course of the set, smooth changes will be less jarring to the audience. You can, of course, have abrupt changes in tempo for effect.  I generally try to avoid too many slow pieces in a row, and often ramp up the tempo then take a break with a slow piece.
The time of the pieces is also something you want to vary.  A long string of all 4/4 time with the same under-rhythm is going to wear the audience out, although I've found that you can get away with the same rhythm for longer than things like key.
Instrumental and vocal arrangements can be broken up as well. Four pieces in a row with the same soloist or vocalist can create "too much of the same thing" in a set.
Once you have an idea of a set, it is a good idea to put it together and listen to it all the way through, either with recorded examples or a live run through.  Multiple listens will show you where the set bogs down, or sounds too much of the same thing, where the rough transitions are. you can then "tune the set" from there.
Answer: Combining tunes (typically three) into "sets" is common in Celtic (Irish, Scottish, etc) music. These are relatively short pieces, each typically a few minutes long. Part of the joy in playing at sessions comes from which tunes the player selects for the set. While there are no rules for this, most sets keep the same time signature (i.e. 6/8 jigs, or 4/4 reels, etc.) but occasionally a strong break will be heard between one tune and the next (slow air followed by fast reel, or MSR: march/strathspey/reel, for example).
Common techniques include:

changing the key of successive tunes, often in fifths or related majors/minors (e.g. D -> G -> Em or A -> Bdorian -> D)
playing all tunes in the same key
playing tunes with related titles (Hag at the Churn, Hag's Purse, Old Hag You Have Killed Me) or themes (all Whiskey tunes)
Variants of the same tune as different dances: for example, a slow air followed by a reel followed by a jig, all based on the same underlying tune/theme (e.g. Garrett Barry's reel/jig/hornpipe)

If you are not familiar with this genre, have a wee listen on YouTube ;)
Comment: Unless you are playing for dancers, in which case switching from a reel to a jig can make the dancers fall down.
Comment: Yes, the less proficient ones might - but the better ones will enjoy the challenge!