How to convert word text data into html using PHP

Question: I have a html text area where users can add any text. What I want is if a user copies text from his word document or rtf and put into the text area, that text should be formatted into html using html.
I have used php's nl2br function but it just creates new lines. What I want is if there are any headings, bold, bullets in word, then they should be converted into html.
Any help will be of great use.
Thanks
Comment: Good luck. Not even Microsoft can get this one right.
Comment: Any text pasted in a textarea will be plain text. You're looking for the [`contentEditable`](ttps://developer.mozilla.org/en/HTML/Content_Editable) property. See also: https://developer.mozilla.org/en/rich-text_editing_in_mozilla
Answer: Use tinymce. It has a function that do exactly what you are asking. Just to clarify, this is a client-side script. Anyway, your user will always pass through the text area (part of a form), so it can be used and works well.
Comment: @Diodeus Obviously. But the question is that the user will pass through a text area (part of a form) so it can be done client-side.
Comment: This runs on the client. It's not PHP.
Comment: sorry for late reply. the issue with the project is that there is an existing sql server database on which I don't have any control. The users generally paste data through Microsoft Word on a dotnet(C#) developed software which updates the database. In my project I have to fetch that particular data on a PHP website. By default it is not properly formatted. So I wanted it to format that through HTML.
Answer: If you are talking about posting data then use htmlspecialchars to avoid HTML tags
Answer: Look at some of the PHP and Javascript-powered WYSIWYG (what you see is what you get) text editors, such as tinymce. These generally can handle such things, and you can look at the source to get an idea of how it's done.


redirecting in htaccess with advanced method

Question: How can I redirect URLs in .htaccess?
For example, I want to send a login URL to a user's email like this:
http://any.com/login.php?id=eurydmd315&=yeyss31541-Refid=0004599538803325339

When the user is using a mobile device, I would like the user to be redirected
to:
http://mobile.any.com/login.php?id=eurydmd315&=yeyss31541-Refid=0004599538803325339

Comment: Thanks Mr braiam but what am saying is when a user wants to make a direct access to the desktop page  and I want to redirect the user to the mobile page with the same  direct access like this "http://www.anything.com/help.php?Id=blah blah blah " will be redirected to "http://mobile.anything.com/ and it will request the directory from which the user wants to have direct access to (that is the help.php?id=blahblahblah) to be attached to the mobile URL to automatically become something like this "http://mobile.anything.com/help.php?blahblahblah
Comment: Please stop suggesting useless edits to my question. The next time you do it, I'll raise a moderator flag.
Comment: Okay alarm of apology! for you I am backing off from the answer
Answer: This can easily be accomplished by redirecting by detecting mobile browsers (via user-agents), for example android, iphone, and blackberry.
The below can be used:
RewriteEngine On
RewriteBase /

RewriteCond %{HTTP_USER_AGENT} android|avantgo|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge\ |maemo|midp|mmp|opera\ m(ob|in)i|palm(\ os)?|phone|p(ixi|re)\/|plucker|pocket|psp|symbian|treo|up\.(browser|link)|vodafone|wap|windows\ (ce|phone)|xda|xiino [NC,OR]
RewriteCond %{HTTP_USER_AGENT} ^(1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a\ wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r\ |s\ )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1\ u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp(\ i|ip)|hs\-c|ht(c(\-|\ |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac(\ |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt(\ |\/)|klon|kpt\ |kwc\-|kyo(c|k)|le(no|xi)|lg(\ g|\/(k|l|u)|50|54|e\-|e\/|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(di|rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-|\ |o|v)|zz)|mt(50|p1|v\ )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v\ )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-|\ )|webc|whit|wi(g\ |nc|nw)|wmlb|wonu|x700|xda(\-|2|g)|yas\-|your|zeto|zte\-) [NC]
RewriteRule ^$ "http://mobile.any.com [R,L]

Awknowledgement: WordPress' forums


Views taxonomy contextual filter?

Question: I have taxonomy vocabulary called "Groups", with 3 terms. I have two content types that both use a Groups term reference field. These content types are called "Media" and "Links".
When displaying "Media" (node), I have an embedded view that shows "Links". How can I only show "Links" that have the same terms as the actual "Media"?
Is it possible to do with contextual filters?
Comment: @monymirza You don't. Would you mind telliing us how adding a (views) relationship helps in this case exactly ?
Comment: you need to add relation between to types.
Answer:
I have embed view that shows "Links". How can I only show "Links" that
  have the same terms as the actual "Media"?

I'm not sure you used Entity Views Attach module to attach the View or just placing the View as a block.
Whatever it is, you can do it. But if you have EVA, you will be able to set the current node ID argument easily.

Add a new View as Show: Content, Of Type links. Continue and Edit.
Then, in the Views UI, you will see a filter to show only Link nodes are added. Now, add extra fields you want from the Link nodes.
Set configuration as marked in the image below.
Save the View.
Save the View and enjoy!

if you have EVA module, do not set to inherit node ID to the View (it will give wrong results). Send the term ID as argument(s) if possible.
Answer: Yes, you can do this using contextual filters. You need to add a "Content has taxonomy term ID" contextual filter, and set the default value to "Taxonomy term ID from URL" and check "Load default filter from node page, that's good for related taxonomy blocks". now check "Limit terms by vocabulary" and select "Groups" vocabulary.

Views taxonomy contextual filter?


Can I safely run a server with redundant power supplies off of a standard 15 amp outlet?

Question: I purchased a used HP Proliant DL380p Gen 8 off eBay.  It has dual redundant power supplies, both at 750 watts.  Doing the math, I realize that if both PSUs are at peak load, they will pull 12.5 amps on a standard 120 volt circuit.  Given that standard outlets can handle 15 amps, but are technically supposed to only use 80% of that due to electrical code, that would mean an outlet shouldn't supply more than 12 amps of power total.  I also have a mini fridge that uses 0.8 amps plugged in on this circuit.
Additionally, I've read some articles that say the power draw of a server is based on the components inside it rather than the PSU's rated wattage.  In that case, I have 2 Xeon E5-2640 v2 8 core processors (16 cores total, each of the two processors having a TDP of 95 W), 32 gigs of DDR3 ECC ram (8 4 gig sticks), 2 10k SAS hard drives, 2 enterprise class SSD's, and all the standard integrated hardware (optical drive, FlexibleLOM ethernet card, integrated P420i raid controller, ILO controller, integrated graphics card, fans, etc).  I don't have any PCIe cards or additional hardware installed.
Is it safe to plug both PSUs into a standard outlet?  How many watts/amps would the server actually draw at a maximum?
Comment: Go directly to your favorite shopping web site, look up Kill-A-Watt, and buy now.
Answer: For "is this circuit safe" ask an electrician. Seriously, electrical fires are no joke, and some old wiring is terrifying.
Regarding a rough estimate on draw, that's not how redundant power supplies work. Properly sized, each could carry the load of the system if the other failed. For what that load is, make an estimate with component specifications, such as with the HPE Power Advisor tool. That system is closer to 300W. Probably the 460W power supply would be more efficient, oh well.
As you have this hardware, measure yourself. Get metered PDUs, and check what the draw is from each supply.


How to get list of modified objects in Entity Framework 5

Question: I'm binding list of entities to a data grid view like this:
var orders = context.Order.ToList();

BindingList<Order> orderList = new BindingList<Order>(orders);

dataGridView1.DataSource = orderList;

User can edit or add new directly on datagridview. When user click Save button, in order to optimize performance, I want to retrieve list of entities that has been changed/new to perform insert/update. How can I achieve this?
EDIT Define add new row to gridview:
BindinList<Order> orders = (BindingList<Order>)dataGridView1.Datasource;

order.Add(new Order());

EDIT 2 Solve:
BindinList<Order> orders = (BindingList<Order>)dataGridView1.Datasource;

Order order = new Order();

context.Order.Add(order);

order.Add(order);

Answer: List<Object> modifiedOrAddedEntities = context.ChangeTracker.Entries()
 .Where(x => x.State == System.Data.Entity.EntityState.Modified
        || x.State == System.Data.Entity.EntityState.Added)
 .Select(x=>x.Entity).ToList();

When binding EF entities to a DataGridView it is often preferable to create an IBindingList from the DbSet.Local ObservableCollection. This way you get two way databinding and your new entities are automatically added to the context when adding via BindingSource.Add() or IBindingList.Add(). The simplest way to get this working, once properly bound, is to set DataGridView.AllowUserToAddRows to true and new rows the users enter will be new entities Added to the context.
context.Orders.Load();
BindingList<Order> bindingList = context.Orders.Local.ToBindingList();
BindingSource ordersBindingSource = new BindingSource();
ordersBindingSource.DataSource = bindingList;
dataGridView1.DataSource = ordersBindingSource ;

System.Data.Entity must be referenced to use .ToBindingList() and you must be using EF4.1 or greater.
Comment: Thanks for your quick response. Your code can get list of modified entities but it can't get list of new entities. I provide code that use to add new entities. Can you help me to figured out?
Comment: @DoanCuong, see additional answer detail.
Comment: Excuse me, but would you please show me how to implement the `BindingSource.Add()` or `IBingdingList.Add()`? And one more thing, there are no `ToBindingList()` function on `dbset.local`. The only way to do it is using
`var bindingList = new BindingList(context.Orders.Local.ToList());`
Comment: @DoanCuong, answer updated. It can be more complex than I have shown depending on your entity but with some research you should be able to work it out.


Finding guitar technicians

Question: I've often seen advice to locate a good guitar technician or luthier to perform setups and routine maintenance. For example, Ali Maxwell advises, in "How do I set up an electric guitar?":

The first time during your ownership of a guitar that you come to the point where it has to be set up, my suggestion would be to take it to a qualified guitar tech who will set the instrument up for you. If you ask him, he will talk you through what he is doing, so that you know a bit more about it for yourself. He will fix any problems on the action, nut, neck, truss rod, and bridge piece that will be affecting how the instrument sounds/plays/tunes.

But where do I find a helpful guitar expert like this? I looked into this online and found wildly varying opinions about guitar service options. Some people like the convenience of major shops like Guitar Center, but others complain about their expertise or attention to detail. Independent specialists have a lot of fans, but they also have a lot of detractors who claim they're arrogant, difficult to work with, or sometimes downright fraudulent.
So how do I locate guitar technicians, and how do I figure out whether they're helpful and competent? I don't have much experience with hiring technicians in general, and in particular I don't know what to look for specifically in a guitar technician.
Answer: In my experience (all over Scotland) it comes down to one of two ways. Either try them and see how your guitar comes out, or use my preferred option:
Ask the opinion of guitarists you know - ideally ones who play similar guitars/style to you. If a few of them recommend a particular guitar tech and can tell you why, then you should have reasonable assurance that they are competent.
I found my current tech through recommendations, and he is teaching me how to do it myself with my various guitars.
Comment: Thanks! I'm not really in tune with local guitarists, although I do know where to find them – lots of blues bars and cover bands in my area.
Answer: There are no absolute answers to this, and it will depend where one lives in the world.My first move would be to ask a guitar teacher. Some will (including myself) go through the set-up routine as part of a lesson, as it's important that a player has at least some knowledge of his instrument. Next could be a trip to a local music shop, or a local guitar maker (luthier). Asking others who own guitars would be a good move.
It's like finding a good barber, butcher, dentist etc. You don't really know till it's too late ! My first piano tuner made a right pig's ear, but came recommended. It's down to the old adage 'give a man a fish = one meal. Teach him to fish = feed him for life.' Find someone who can show you how to do it for yourself, maybe on an old guitar that actually ends up being so well set up that you love playing it ! Ergo - no money spent later, but potential earnings for you.
Comment: Of course that raises the question of how to find a good guitar teacher. ;) I haven't had much luck in tracking down local music teachers or other guitarists, but it would probably help. Thanks for the advice!

Finding guitar technicians


Mysql process overload cpu

Question: We have this mysql process running and kicking the cpu up to 200%.
Any idea how this could be fixed?

/usr/sbin/mysqld --basedir=/ --datadir=/var/lib/mysql --user=mysql --log-error=/var/lib/mysql/xxxxxxxx.com.err --open-files-limit=48480 --pid-file=/var/lib/mysql/xxxxxxxx.com
Comment: Well you could kill that process and that would solve the problem, but then you wouldn't have a db server running. You need to look into seeing how to observe processes *within* mysql, and see which queries are producing the load.
Comment: @Ash that woosh you heard was the sarcasm flying over your head :-)
Comment: I totally disagree - killing the MySQL process will have many negative knock-on effects, besides I presume this is a production server.  For example any query cache, is totally lost when the new process is started-up (and needs to be re-generated).

Any queries currently running especially insert, update, delete will not complete leaving broken constraints or missing data.
Comment: Well, excuse me for misunderstanding - today I had a running with a data centre whom did exactly the above causing me a ballache running cache queries.
Answer: As EEAA commented:

You need to look into seeing how to observe processes within mysql, and see which queries are producing the load

A good start is to look at long running queries. You can enable the slow query log or do a:
mysqladmin -u root -p --verbose processlist

or:
SHOW FULL PROCESSLIST

from the mysql prompt.
Cheers
Answer: I entirely agree with @HTTP500's answer.
In addition running these commands on the command line you can press the up key and return to continuously run the same query.
I suggest you use the explain command before the statement.  This will definitly diagnose your syntax which I would presume is the problem.

Check all tables have the correct indexes;
Check if a cron is hammering inserts, updates or deletes on an MyISAM table (which as we know has table-level locking);
Answer: When my MySQL server is getting overloaded what I run is mytop; which gives me a complete breakdown of all the queries executing on the server. This is especially useful because it makes it easy to sort by long running queries which are usually the culprit.
However, if you don't have mytop you can do the following:

SHOW FULL PROCESSLIST; will give you a dump of all running queries on the server.
Once you determine the query you can run EXPLAIN EXTENDED on that query.
If it's InnoDB you can run SHOW ENGINE INNODB STATUS to get a full report on the status of InnoDB as well as any errors.
If its a large table make sure the indexes are up to date.

Whatever you do, do not restart the server as it's just going to occur again in the future.

Mysql process overload cpu


error bool(false) when use var_dump($mail->send()); at phpmailer

Question: $mail = new YiiMailer();
$mail->setView('contact');
$mail->setData(array('register' => $model,'user' =>$user));
//$mail->clearLayout();//if layout is already set in config
$mail->setFrom('firstname.lastname@example.com', 'amatra');
$mail->setTo($model->client_email);
$mail->setSubject('Amatra Registration');
$mail->setBody('Thank u for registering, to get server licence activation key ');
$mail->setSmtp('smtp.gmail.com', 465, 'ssl', true, 'email@example.com', 'aconxontheroad');

var_dump($mail->send());
if($mail->send()) {
    return true;
} else {
    return false;
}

I changed port and SMTPSecure but still outputs bool (false),I can't deduce where the error is.
Comment: In order to see errors, you need to do some actual error checking, and make use of PHPMailer's debugging features, which you will find in the docs and examples. This code attempts to send your message twice, once for each time you call `send`.
Comment: CLIENT -> SERVER: EHLO localhost 2018-10-08 00:23:20 CLIENT -> SERVER: AUTH LOGIN 2018-10-08 00:23:20 CLIENT -> SERVER: bGFzdGthZ2FtaTYyQGdtYWlsLmNvbQ== 2018-10-08 00:23:20 CLIENT -> SERVER: a2FnYW1p 2018-10-08 00:23:21 SMTP ERROR: Password command failed: 535-5.7.8 Username and Password not accepted. Learn more at 535 5.7.8 support.google.com/mail/?p=BadCredentials t15-v6sm41674857pfj.7 - gsmtp 2018-10-08 00:23:21 CLIENT -> SERVER: QUIT SMTP Connect() failed
Comment: So read the page that links to, and [read the PHPMailer docs that tell you what to do about it](https://github.com/PHPMailer/PHPMailer/wiki/Troubleshooting#read-the-smtp-transcript). You set `SMTPDebug = 1`, so you can't see all that the server is saying; set it to `2`. It also looks like you're using a very old version of PHPMailer, so you should update.
Comment: i changed SMTPDebug=2
Comment: 2018-10-08 00:49:15 SERVER -> CLIENT: 220 smtp.gmail.com ESMTP z22-v6sm16576242pgk.21 - gsmtp 2018-10-08 00:49:15
Comment: i find it,,if update is wil be solved?
Answer: $mail->SMTPDebug = 1; //optional

You can refer this post to clearly:
Yii, Yiimailer doesn't send the mail (no error shown)
Comment: Set this to 2, not 1. Also this should be a comment as it's not an answer.
Comment: it's runing for chaking error
the erros is
2018-10-08 00:23:20 CLIENT -> SERVER: EHLO localhost 2018-10-08 00:23:20 CLIENT -> SERVER: AUTH LOGIN 2018-10-08 00:23:20 CLIENT -> SERVER: bGFzdGthZ2FtaTYyQGdtYWlsLmNvbQ== 2018-10-08 00:23:20 CLIENT -> SERVER: a2FnYW1p 2018-10-08 00:23:21 SMTP ERROR: Password command failed: 535-5.7.8 Username and Password not accepted. Learn more at 535 5.7.8 https://support.google.com/mail/?p=BadCredentials t15-v6sm41674857pfj.7 - gsmtp 2018-10-08 00:23:21 CLIENT -> SERVER: QUIT SMTP Connect() failed.
Comment: username and password was true,,and i setting gmails to less secure
but still error
Answer: Try the Yii2 Swift mailer.
Yii::$app->mailer->compose('contact/html')
 ->setFrom('firstname.lastname@example.com')
 ->setTo($form->email)
 ->setSubject($form->subject)
 ->send();

https://www.yiiframework.com/extension/yiisoft/yii2-swiftmailer


Totally ramified extension of global field in terms of local field case

Question: Let $K$ be a number field of class number $1$(in other words, it's ring of integers $O_K$ is PID.
Let $p$ be a nonzero prime ideal of $O_K$.
$L/K$ is an extension with $n=[L:K]$, we say that $L$ is totally ramified at $p$ if $p\mathcal{O}_L=q^n$ for some prime $q$ of $L$.
On the other hand, $L_p/K_p$ is tottally ramified if $L$ and $K$ have the same residue field.
Then,  what is the relation between '$L/K$ is totally ramified at $p$' and '$L_p/K_p$ is totally ramified as local field' ?
I think latter does not imply former in general, but if I add some condition (like $[L:K]=[L_p:K_p]$), can't we say something like the latter implies the former ?
Thank you for your help.
Answer: Nothing you're describing depends on the class number. The general situation is as follows (see, for example, Milne's Algebraic Number Theory, Thm. 3.34; Neukirch's Algebraic Number Theory, Prop. I.8.2; or Serre's Local Fields, Prop. I.10).
Let $A$ be a Dedekind domain with field of fractions $K$, let $L$ be a finite separable extension of $K$ with $n = [L : K]$, and let $B$ be the integral closure of $A$ in $L$. Then $B$ is a Dedekind domain. For each prime $P$ of $A$ and each prime $Q$ of $B$ dividing $PB$, let $e_Q$ be the ramification index, i.e., the largest integer such that $Q^{e_Q}$ divides $PB$, and let $f_Q = [B/Q : A/P]$ be the residue degree (also called the inertia degree). Then
$$n = \sum_{Q \mid P} e_Q f_Q.$$
In particular, the following two notions of "totally ramified at $P$" are equivalent:

$PB = Q^n$ for a prime $Q$ of $B$.
There is a unique prime $Q$ of $B$ dividing $PB$, and the residue field $B/Q$ is a degree 1 extension of $A/P$ (i.e. the residue fields are canonically isomorphic).

In the case of an extension of local fields, there's only one prime in total, so the uniqueness part of the second condition is automatic.
Comment: Your answer (+1) implies it, but to be explicit in answering the OP's question, to say that the number field extension $L/K$ is totally ramified at $P$ is equivalent to saying that there is only one prime above $P$ and that the corresponding local extension is totally ramified.
Comment: Is 'to judge [There is only one prime above $P$] ' easier than saying the extension is totally ramified ?


A/B testing and Experiment Length

Question: I have a conceptual question to ask that may come off dumb, but I'm just trying to see if I understand A/B testing properly as I've only studied it but not worked much in practice.
Let's say we are running an A/B test on ads on some mobile app on a homepage. This experiment tests some UI change, and we are concerned with CTR
We calculate the sample size required based off CTR baseline rates, MDE = 1%, alpha = 0.05, and power = 0.8
Let's say we get a sample size required of 1M, and our daily active users (DAU) is 10M. So we conclude we need to allocate ~10% of users to this experiment, and we choose to run it for 28 days because we want to test a 21-day retention metric as well
Now our team says because of constraints, we can only run this experiment for 10 days.

Does this impact sample size calculations?
Does the % of DAU we need to allocate change?

Intuitively, #2 seems like a yes - meaning if we are going to run the test for a shorter length we would want to increase sample size to get the same confidence in our result.
But looking at my inputs for calculating these numbers, the answer seems no? i.e. the sample size will still be 1M, and we still get 10M DAU?
Can someone please point out where I might have faulty logic/poor understanding of A/B testing here?
Comment: Retention is not included in the sample size calculation because it's not part of the test, retention is something which you decided to add as a bonus, and you decided to measure it for 21 days. For ex., if you were only interested in the retention for the next 7 days then you would measure only for 7 days. But the test tells you that you need 1M users to get an estimate of CTR.
Comment: so specifically for CTR - does the % we are allocating for our experiment change if we are shrinking the duration of experiment time? to me our sample size calculation gave us 1M and that does not change, and our DAU does not change, so i dont see why the % of users would change?
Comment: CTR doesn't change if you change the duration of the experiment. As I've mentioned, duration is not included in the estimation of sample size, it is something which you decide to include or not, if you want to test retention as well.
Comment: so there is no impact on what % of users we must allocate to our experiment, if we only have 5 weeks to run vs 1 week to run, if we are only measuring CTR? assuming we have 10x DAU compared to our required sample size?
Comment: What is retention and how do you want to test it (power, significance, etc)? What is MDE? What baseline rates are you assuming?
Answer: a rule of thumb formula for minimum sample size is: $n = \frac{16 * \sigma^2}{\delta^2}$, there are two things that need more clarify:

n is the minimum sample size for each group: if you have an unequal sample size for treat/control group, you can refer here(R - power.prop.test, prop.test, and unequal sample sizes in A/B tests)[https://stats.stackexchange.com/questions/108226/r-power-prop-test-prop-test-and-unequal-sample-sizes-in-a-b-tests]

n is 「unique active users during experiment」not 「daily active users (DAU) * duration days」 for each group

A/B testing and Experiment Length


Batsman runs through stumps and wicketkeeper: out or not, and how?

Question: Is a batsman out when during a second run, they return to the wicketkeeper's end and run through the stumps and wicketkeeper, after the keeper had already removed the bails and continued to hold the ball?
Should the batsman be out Hit Wicket, if they were not given out Run Out?
Answer: If the wicketkeeper cleanly broke the stumps, then the batsman is out - it doesn't matter what happens next add the ball is dead.
Aside: it certainly can't be hit wicket as that explicitly can only happen when playing a stroke or setting of for a first run.
Aside 2: other than in exceptional circumstances, there's no reason a batsman should be running at the wicket - if a batsman did influence the play by doing so, for example by distracting the wicketkeeper, they would be very much at risk of being given out for obstructing the field.


Problem with powers of matrices.

Question: Suppose that the matrix $A$ is as follows:
$$A=\begin{bmatrix}
    -3&4\\
     2&3\end{bmatrix}$$
We need to prove that $A^{2n + 1}=A$.
The way I tackled this problem is as follows:

If $A^{2n + 1} =A$,  then $A^{2n}$ must be the same as the identity matrix $I$.
Thus $(A^2)^n$ must be the same as $I$.
By calculation $A^2=17I$.
Thus the statement can't be proved.

I'm not sure if I'm correct. I believe we have to make use of Cayley Hamilton's Theorem and diagonalization to solve the problem but I can't seem to wrap my head around it. Any help will be appreciated.
Comment: I suspect that a sign is wrong in one of the entries of $A$ (changing any of the four signs results in $\det A=\pm1$ instead of $\det A = -17$)
Comment: Are you sure you did't mistype the signs of one of the entries? As stated the matrix indeed does not have the stated property. But your reasoning is flawed: the matrix $\begin{pmatrix}-1&0\\0&0\end{pmatrix}$ _does_ have the stated property, but fails your point 1. On the other hand, you may check that the property for $n=1$ implies the property for all $n>1$, which simplifies checking it.
Comment: I think Hagen is right. Change for example $2$ to $-2$. You will see that your conclusions are indeed correct and it is provable.
Answer: If one considers the matrix
$$
A=\left[\begin{array}{cc}-3&4s_1\cr2s_2&3\end{array}\right],
$$
where $s_1,s_2 \in \{-1,1\}$ with $s_1s_2=-1$, then the characteristic polynomial $p_A$ of $A$ is given by
$$
p_A(\lambda)=\lambda^2-\text{trace}(A)\lambda+\det(A)=\lambda^2-1.
$$
It follows from Cayley Hamilton's Theorem that $p_A(A)=0$, i.e.
$$
A^2=I.
$$
Hence $A^{2n}=I$ and $A^{2n+1}=A$ for every $n \in \mathbb{Z}$.
Answer: EDIT: As @Hagen states in the comment on the question, that perhaps one of the signs is wrong in the matrix $A$. This working follows if that is true. If not, then this answer can be discarded.
The characteristic polynomial of $A$ is
$$f(\lambda)=\lambda^2-1=(\lambda+1)(\lambda-1).$$
You can show that this matrix is diagonisable (you ahould check this), so that we can write $A=VDV^{-1}$ and $g(A)=Vg(D)V^{-1}$, where here $g(x)=x^{2n+1}$.
Since $D$ is a diagonal matrix with entries of $1$ and $-1$, then $D^{2n+1}=D$ with $n\in\mathbb{Z}$.
Thus,
$$A^{2n+1}=VD^{2n+1}V^{-1}=VDV^{-1}=A$$
when $n$ is an integer.
Answer: The entries of the matrix as given are false. Change the following $(A)_{2,1}$=-2 instead of 2 and it works. Solve simply by induction on $n$, it is very easy then.
Answer: Show $A^3=A$ by direct computation.
Then proceed by induction on $n$:
$$A^{2n+1}= A^{2(n-1)} A^3 = A^{2(n-1)} A = A^{2(n-1)+1} = A$$
No need for Cayley-Hamilton.

Problem with powers of matrices.


Theory of improvisation

Question: I am looking for improvisation theory ressources. I mainly focus on free jazz and improvised music but I am also interested in dance, drama and pictural improvisation.
I want to know if a classification of interactions in an improvisation group already exists.
Every book, talk, thesis, documentary or article are very welcome, do not hesitate to submit your thoughts about this subject.
Comment: Can you add some more criteria, and give us an idea of your current abilities?  As-is I can see you getting a list of vague answers.
Comment: @MatthewRead You are right, I am working on a [graphic vocabulary](http://lab.raphaelbastide.com/images/static/improvisationEN.png) in order to extand the improvisation field for a [graphic performance](http://raphaelbastide.com/#digimp).
Answer: There are theories that apply to more than one of 'improvised music ... dance, drama and pictural improvisation':

rank/order (in jazz or pictures, consider FG/MG/BG too)
strategies/tactics (in dance or drama, consider body/space too)

excerpts from the above links:
"The main ingredients of improvisation ...

Presence and projection are the premises of trust and collaboration.
Commit.
Improvisers are sponges feeding on their surroundings. Listen.
The best ... tend to emerge between - rather than within - people.
Adjust."

"The process can become effortless with practice but without listening there is nothing to adjust to. ... Listening gives them a common space in which to play. Without commitment, there is no one to listen to ... Improvisation requires players to engage fully with each other."
"In any ... combinations ... , some aspects or elements will sound more prominent while others will seem to recede. We use the spatial terms foreground, middleground and background to help us differentiate the various elements ... can constantly change and shift. They do not necessarily have to be fixed."
"A pecking order is the stabilised ranking of individuals in a given social group. The agreement save the time and energy [that] would otherwise be spent on conflicts over access to ressources and privilege. ... The notion is relevant to improvisers on many levels: ... As a person ... As a player ... As a character ... As a storyteller"
Answer: Do you know about "Improvising Jazz" by Jerry Coker ? Also by the same author: "The Complete Method for Improvisation".
Answer: Jamey Aebersold is an acknowledged master teacher in this area.  Read his free handbook:
http://www.jazzbooks.com/mm5/download/FQBK-handbook.pdf
It contains a lot of foundational music theory and suggested listening, and explains his philosophy about jazz, improvisation, and music in general.
Answer: There is another book by John Mehegan titled "Improvising, Jazz Piano". It covers a lot of musical theory but sets an starting point to start improvising.
Answer: On the academic research side of things, the journal Perspectives of New Music1 from time to time publishes articles on improvisation.
A few examples for you to look at and see if they fit what you're looking for or warrant further searching:

Focal Points in Collective Free Improvisation by Clément Canonne
Improvisation, Heterophony, Politics, Composition by Christian Wolff et al.
"Open Work" One Step Further: From John Cage to John Zorn by Oksana Nesterenko
Improvisation as a Creative Dialogue by Oded Ben-Tal and Caroline Wilkins
Forum: Improvisation by Various Authors
Cecil Taylor, Identity Energy, and the Avant-Garde African American Body by Andrew W. Bartlett

1Disclosure: I have professional involvement with the journal.
Answer: Dave Frank is a master teacher of jazz improvisation:
https://davefrankjazz.com
His "Flow, Phrase, Breathe" method has really helped me tap into my own musical creativity. He has over 50 jazz master classes on YouTube.
Answer: "free" and "theory" don't necessarily go well together.
I would echo other comments regarding resources (with the caveat that resource requests are usually not allowed, but the question has not been closed).
Jerry Coker "Improvising Jazz" is an outstanding book.
The Jamey Abersold series has value but it is easy to take the material out of context.  This seems to be where people get the idea of 1 chord = 1 mode and that's the formula for greatness.
With respect to the concept of improv I would cite a quote from Robert Dinero (really a paraphrase).  I was watching an anniversary edition DVD of Taxi Driver and they had old and new interviews with cast members.  In particular Jodi Foster.  She was very young and Di Nero wanted her reactions during filming to be relaxed and authentic.  There was, perhaps, some impov very small deviations from the script here and there and he wanted her to be comfortable going with the flow.  So, they had lunch together every day, went over lines and he'd throw some mistakes in there (intentionally or not).  She attributed the following statement to him "Improv is variation on a theme", you have to know what you are doing so well that you could have created it in your sleep.  It's not second nature, it's first nature.  This is not where Free improv players are usually coming from but the fact is that the great ones have a lifetime of music (or dance or acting chops) behind them.
From the point of view of getting good at improv in music you need to know music and know a variety of musical styles.  Forget "Jazz".  All the great Jazz players drew from Indian classical music (namely Coltrane), Latin music (not Latin Jazz), etc.  I would suggest walking two paths at once (1) study western classical music theory as this is the foundation of "Jazz", and (2) get immersed in a variety of ethnic musical styles that stress free form improv with a simple theme (like Indian Ragas).  You can consider Jazz one of the forms of music to immerse yourself in but what we think of as Jazz didn't exist when those players invented it.  I always like going a step further back in time and ask myself what did they draw inspiration from.

Theory of improvisation


.NET configuration file - Do I need to include it in installer?

Question: I have a C# application MyApp.exe that targets .NET 3.5. In order to support other versions, I used MSDN instructions, and created a config file MyApp.exe.config, with the following content:
<?xml version="1.0"?>
<configuration>
  <startup>
    <supportedRuntime version="v4.0"/>
    <supportedRuntime version="v2.0.50727"/>
  </startup>
</configuration>

My question is what should I do with this file? Do I need to include it in the installer and put near the exe file on the target computer? I couldn't find any instructions about it.
Answer:
Do I need to include it in the installer and put near the exe file on the target computer?

Yes.  This file needs to exist next to the installed exe post-deployment.
Most installers that understand .NET deployment will automatically handle this for you, so it's likely you won't need to "do" anything special (other than verify it got copied across correctly.)
Comment: Thank you! Can you please provide a reference to that? (by the way, I use NSIS installer, which doesn't install this config file automatically)
Comment: @Serg There isn't much other than the main app config reference material: http://msdn.microsoft.com/en-us/library/aa374182(v=vs.85).aspx  The file is read at startup, though, to change the supported runtimes.  If you don't include it, the information won't be available to use on the other system, so you'll get the default binding behavior (which is obviously not what you want)


References on android 2d graphics?

Question: Can someone point me to any good references on android 2d graphics. I have already been at the developer site but not much help. I want to know more on the working on the canvas. Right now I am getting a bit confused.
Comment: Tried searching.Didn't get any good references.
Comment: That still doesn't make this Q&A the appropriate place for this question in my opinion.
Answer: Not quite sure if you want a screen that will just display 2d graphics or one that you will be able to manipulate 2d graphics. if you want to display 2d graphics, just google tutorials, there are loads of them up in great detail like this one. but if you want to manipulate 2d graphics here is a great tutorial
Comment: Gone through all that.I am looking into the working as i mentioned
Comment: so do you want something like this: http://www.android-dev.ro/2011/12/23/androids-2d-canvas-rendering-pipeline/ and http://stackoverflow.com/questions/5762727/how-do-the-pieces-of-androids-2d-canvas-drawing-pipeline-fit-together which explain explain how the 2d canvas rendering pipeline works because still a bit unsure what you mean by 'know more on the working on the canvas'
Comment: Thanks.That goes very deep but really interesting.I am looking forward to more on answers to questions like these http://stackoverflow.com/q/10733883/598714
Comment: id say you would be better of asking a couple of new questions so about specific parts of the Canvas class that you are interested in learning about as just the Canvas class is very broad and there are no real answers or sites that explain the entire Canvas class in detail bar: http://developer.android.com/reference/android/graphics/Canvas.html which you said you have already read

References on android 2d graphics?


Run "git" on remote server with drush alias

Question: I would like to launch git commands, on my production server, from my pc.
The document root of the production application is a clone of the git repository.
On prod, on sites/all/drush/drushrc.php I've add this line:
<?php

// Drush aliases
$options['shell-aliases']['git-status'] = '!git status';

If I login on production and I execute "git status", everything works.
If I try to execute, from my pc "drush @mysite.prod git-status" I obtain:
fatal: Not a git repository (or any of the parent directories): .git
Command git status failed.

Note that if I try to run "drush @mysite.local git-status", works (and my local copy is like the production copy, the document root is the clone of git repository).
What's wrong?
Document root directory declared on my alias is right (other commons drush commands work) and is a checkout of git repository.
Thanks.
Answer: This works just fine for me on both the 6.x and master branches of Drush, and on the 6.2.0 release.  So, your first step would be to try with the latest versions, and see if it works.  If that doesn't fix your problem, try running your command again using the -v flag to get more verbose output.  You will see something like this:
$ drush -v @mysite.prod git-status
Loaded alias @server.xxxxxxxxxxx from file                              [notice]
/home/ga/local/config/drush-aliases/server.aliases.drushrc.php
Loaded alias @mysite.prod from file                                     [notice]
/home/ga/local/config/drush-aliases/mysite.aliases.drushrc.php
Include /home/ga/local/drupal/drush_extensions                          [notice]
Include /home/ga/.drush                                                 [notice]
Calling proc_open(ssh -o PasswordAuthentication=no email@example.com 'cd /srv/www/myserver.com/htdocs && git status');
# On branch master
# Untracked files:
#   (use "git add <file>..." to include in what will be committed)
#
#   ../xxxxx.txt
nothing added to commit but untracked files present (use "git add" to track)
Command dispatch complete                                               [notice]

Try running the command inside of "proc_open(...)" from the shell, and see if it behaves the same way.  Adjust the ssh options until it works right.  Then, set $options['ssh-options'] to adjust.
NOTE:
If you want to do something like this without defining a shell alias, the following should also work:
drush @mysite.prod ssh git status

Comment: But how have you defined the "git-status" command?
Comment: I copied your git-status alias from the question.  I put it into the .drushrc file on my local system; I did not need to define it on the remote system. That probably does not work on Drush 5.x, but it works on Drush 6 and later.
Comment: Now I can't try. I'm using drush 6, asap I'll try it


How to change date format into the comma separated column?

Question: I have comma separated value like 2018-06-20 01:12:53,2018-06-20 01:14:11
But the problem is I need date and time format like day-month-Year H:i when I use DATE_FORMAT(t1.pickup_date_time, "%d-%m-%Y %H:%i")
it could not run because the column(pickup_date_time) has comma separated value.
Your help is appreciated.
Thank you.
Comment: Take some time to think about restructuring your data
Answer: Use SUBSTRING_INDEX first to split the column on the comma. Then use STR_TO_DATE to reformat the date.   If you have issue with the actual code, let me know.


elm-package.json constraints of 'repo_name/package_name' are probably letting too much stuff through

Question: I get this error trying to use a github repository as a dependency using elm-install
Problem in dependency repo_name/package_name 1.0.0

The elm-package.json constraints of 'repo_name/package_name' are probably
letting too much stuff through.

What does this exactly mean?
Answer: (This answer courtesy of @ilias at Elm Slack channel)
It means that Elm couldn't compile the sources for that package in the context of your package.
Imagine for a minute I'm making a package my-fancy-package, and I have a dependency on a package foo/bar. So in my-fancy-package/elm-package.json, I could have a dependency like "foo/bar": "1.0.0 <= v < 2.0.0". Now, perhaps the most recent version of foo/bar while I'm developing my-fancy-package is 1.5.0. And in version 1.5.0, a new function was added that does exactly what I need in my-fancy-package, so I start using that function. The core issue is that there currently is no automated way to test that a package actually works with all the allowed versions of its dependencies. So now my-fancy-package says it depends on foo/bar at any version between 1.0.0 and 2.0.0, while in reality, it really needs to be at least 1.5.0 because I'm using a function from that package.
Now, imagine you're developing an application, and you're using foo/bar at version 1.2.3. According to the semver ranges of my-fancy-package, that means you should be able to use it, but if you were to actually try it, you'd receive this error: my-fancy-package is stating it is compatible with firstname.lastname@example.com while it really needs 1.5.0.
The reason the error message doesn't simply say "it failed to compile" is because all the published packages are compiled before publishing. The most common reason for a package failing to compile in some context is that its dependencies aren't "accurate": they're letting too much stuff through.
In case of elm-install and packages from github, it's harder to say - it could actually be broken package.
Another common cause for this error is a rather silly one - conflicting definitions of infix operators. The associativity and precedence of infix ops can only be defined "globally", so if there are 2 packages that define the same infix operator, that could become a problem
Comment: Notably, in case of elm-install, to get more detailed error info, just put the library in a directory and add the path to the library's `src/` subdir into `"source-directories"` section in `elm-package.json` of the including project (see also: https://discourse.elm-lang.org/t/how-do-i-fork-and-edit-a-third-party-package/1241/2)


definition of image and preimage

Question: Claim: Suppose $f : A \to B$ and $S$ and $T$ are subsets of $A$. Prove that if $S \subseteq T$ then $f(S) \subseteq f(T)$.
Proof. Suppose $f : A \to B$, $S$ and $T$ are subsets of $A$ and $S \subseteq T$. Let $y \in f(S)$. Then there is $x \in S$ such that $y = f(x)$. Since $S \subseteq T$, $x \in T$. So there is $x \in T$ such that $y = f(x)$, and therefore $y \in f(T)$ by definition of image. Since $y$ was an arbitrary element of $f(S)$, we have $f(S) \subseteq f(T)$.
However, I do NOT understand why "Let $y \in f(S)$. Then there is $x \in S$ such that $y = f(x)$" or "there is $x \in T$ such that $y = f(x)$,and therefore $y \in f(T)$ by definition of image" is true? How exactly is the definition of image/preimage applied to those to statements?
Answer: Given a function $f : A \to B$ and a subset $U \subseteq A$, the image $f(U)$ of $U$ is defined by
$$f(U) = \{ f(x) \mid x \in U \} = \{ y \in B \mid y=f(x) \text{ for some } x \in U \}$$
So here you just need to apply the definition. If $y \in f(S)$ then $y=f(x)$ for some $x \in S$; this is just the definition of $f(S)$. Since $S \subseteq T$, it follows that $x \in T$. But then $y=f(x)$ and $x \in T$ so that $y \in f(T)$ again by definition of image.
Sorry if I'm just rewording your problem, but the thing you don't understand really is just the definition of image.
Comment: "But then y=f(x)y=f(x) and x∈Tx∈T so that y∈f(T)y∈f(T) again by definition of image."

Does this mean that y=f(x) and x∈T, moreover T is a subset of A so f:A to B implies that y is an element of B, which fits the full definition. (becuase in the proof, it skipped the part where is mentioned y is an element of B which is part of the definition)

also, f(U)={f(x)∣x∈U}={y∈B∣y=f(x) for some x∈U}, this definition goes both ways right? Thanks for your detailed explanantion.
Comment: or can definition be shortened to this? f(U)={f(x)∣x∈U}={y∈B∣y=f(x) for some x∈U}={y∣y=f(x) for some x∈U} since y being an element of B is implied through y=f(x) for some x∈U anyways

definition of image and preimage


the javascript for dragging and dropping not loading - drupal 7

Question: for some reason when I add new modules the tabledrag.js is not loading.  Tried taking the modules out, clearing cache several times.  Aggregated js as well.
Can anyone help.
Answer: I solved this by installing http://www.drupal.org/project/speedy
it minifies core javascript files


How to explain control variables and interaction effects

Question: I'm a bit stuck on running a GLM between 3 continuous variables in R. I can't make them categorical as it removes the significance. I have two questions.
I'm analysing data on eggs.
I had read that you could control for variables by adding them in using + like so:
m1 <- glm(Volume ~ Altitude + Breadth)

However, I have since been told that saying in my results that

Volume significantly declines as Altitude increases, when controlling for Breadth

isn't a correct statement. Is it? I was told the following:

The language works in that it IS controlling for it by taking it into
  account in the model as a fixed effect, BUT it isn't removing it from
  the analysis entirely as your sentence suggested.

I'm very confused as I have read on this forum people advising to control variables by adding them in like this.
If I can't control for the variable, I can do an interaction. But for this purpose I had been advised to stay away from them as they are so difficult to explain. However if I can't control for Breadth then I don't have much choice.
m1 <- glm(Volume ~ Altitude*Breadth)

How would you explain this interaction? I was going with

For any given breadth, Volume decreases as Altitude increase

but apparently this isn't right either. The model summary is as below
Please let me know if you would like any more information!
Call:
glm(formula = Volume ~ Altitude * Breadth)

Deviance Residuals:
     Min        1Q    Median        3Q       Max
-0.24775  -0.10975  -0.01984   0.06765   0.46698

Coefficients:
                   Estimate Std. Error t value Pr(>|t|)
(Intercept)      -8.5941878  2.2616181  -3.800 0.000461 ***

Altitude          0.0080269  0.0033141   2.422 0.019829 *
Breadth           0.8964839  0.1913092   4.686 2.93e-05 ***
Altitude:Breadth -0.0007117  0.0002800  -2.542 0.014801 *
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

(Dispersion parameter for gaussian family taken to be 0.02604406)

    Null deviance: 3.0980  on 45  degrees of freedom
Residual deviance: 1.0939  on 42  degrees of freedom
AIC: -31.449

Number of Fisher Scoring iterations: 2

Answer: Including an extra predictor in a regression is often described as controlling for it when discussing the coefficient estimates for another predictor of interest, so your first description is unexceptionable & doesn't carry any implication of "removing it from the analysis entirely"—how would you do that? Of course in this case you're assuming it has a linear effect on the response, & no interaction with the predictor of interest; you can check both assumptions.† It might be good advice to concentrate on understanding the mathematical form of the model before worrying over the nuances of verbal descriptions:
$$\operatorname{E} Y = \beta_0 + \beta_1 x_1 + \beta_2 x_2$$
where $\operatorname{E} Y$ is expected volume, $x_1$ altitude, & $x_2$ breadth; $\beta_0$ is the intercept, $\beta_1$ the slope for altitude, & $\beta_2$ the slope for breadth. Experiment with plotting it for different values of the parameters & predictors, & you'll see that $\beta_1$ is the slope of the altitude vs volume plot for any breadth whatsoever.
The model with interaction contains an extra term:
$$\operatorname{E} Y = \beta_0 + \beta_1 x_1 + \beta_2 x_2 + \beta_{12} x_1x_2$$
Now $\beta_1 + \beta_{12}x_2$ is the slope of the altitude vs volume plot; still linear but dependent on the breadth (breadth is said to moderate the effect of altitude on volume). For some breadths volume increases with altitude; for others volume decreases with altitude: the breadth for which volume is a constant function of altitude can be found by solving $\beta_1+\beta_{12}x_2=0$ for $x_2$. If such relationships seem implausible, note they may be outside the range of applicability of the model.
If the interaction term's statistically significant at 1% & the difference in predictions between the two models is practically significant, it'd be silly to use the model without interaction because interaction's "difficult to explain". Plotting altitude vs volume for various different breadths gets the idea across.
† See also posts here & here & the entertaining paper cited by @EMS: Achen (2005), "Let's Put Garbage-Can Regressions and Garbage-Can Probits Where They Belong", Conflict Management and Peace Science, 22, p.327. It's important to realize that stuffing linear terms for "control variables" into a regression model doesn't give you a carte blanche to claim the coefficients for "variables of interest" represent their causal effects on the response.
Comment: Scortchi, thanks so much for the response.

To be honest we have never really been told to focus on the mathematical form of the models. I'm at a much more entry level.

Are you saying I could say that I controlled for it? And that would be right? I could potentially say that for a given breadth, volume decreases with altitude.

I understand I should use interactions when they are available as they explain more of the variance. But I'm afraid I'm still not understanding how I would describe it. Would I just say 'Volume decreases as altitude increases, with the effect moderated by breadth'?
Comment: @restats: Even at entry level, as long as you've covered addition & multiplication you should be able to understand the models - else what's the point in fitting them? Plot them out over relevant predictor values & describe what you see.
Comment: E.g. for breadths below $\frac{-\beta_1}{\beta_{12}}\approx 11.3$, volume *increases* with altitude according to the model with interaction - though this may be far outside the range of breadths you're interested in.
Comment: it's not far outside the range. How did you figure out at which point the relationship changes?
Comment: Well... 8 values out of 48 are less than 11.3...
Comment: @restats: Added explanation to answer.


How to override j_security_check in glassfish?

Question: I'm currently using FORM based authentication in glassfish v2.1 to log users in and it works fine. I want to switch to ProgrammaticLogin and I want to be able to get the initially requested URL (i.e. before redirecting to login page) and use it in my programmatic login code so that the user is redirected back to the requested page after authentication.
I've seen the source code for j_security_check - in my case that's FormAuthenticator (catalina codebase) and it saves the initial request in a SavedRequest object in the session but that session is a StandardSession rather than HttpSession so there's no direct way to access it.
Or should I change the authentication mechanism from FORM to something else?
Thanks!
Answer: Ok, I found the answer. So here it is:
Basically what I was trying to achieve was to implement an openid-based authentication mechanism in glassfish. One way of doing that is to use ProgrammaticLogin but this has a few drawbacks - no easy way of redirecting back to requested URL and programmatic auth means more work for the programmer. So after reading around I found the better way to achieve my goal - Server Authentication Modules or SAMs. This is part of a standard process described in JSR-196 and provides a way for creating pluggable auth modules for glassfish (ie. different than the standard FORM, BASIC etc.). This method allows you to plug new auth modules in the servlet container while keeping your declarative security model.
So all I need to do is write my own custom SAM. Here's a quick how-to:

Implement the ServerAuthModule interface which mostly boils down to the following method:
AuthStatus validateRequest(MessageInfo messageInfo, security.auth.Subject
clientSubject, security.auth.Subject serviceSubject) throws AuthException
Package your SAM in a jar, and place your jar in the glassfish lib directory.
Configure the SAM for use with your application. This is done in 2 steps:

Define your SAM as a message-security-provider in domain.xml.
Bind the SAM for use with your application. You can do this by defining the httpservlet-security-provider attribute in the sun-web-app.xml of your app. Set the value of the attribute to the name you assigned to your SAM in step 1.

For more info read this great tutorial by Ron Monzillo.
UPDATE: There is a simpler and more elegant solution to this problem called AuthenticRoast. This is a Java library written by Aike Sommer which allows you to write your own pluggable authenticators.
Answer: If form authentication is not working for you, I would recommend switching to using a ServletFilter for authentication.  You just get rid of your FORM based auth and add a mapping to the filter for the pages you wanted protected.
Comment: thanks! I've looked at SecurityFilter but then I found a better way to achieve my goal by sticking to the neat declarative security model of glassfish.


How to Apache2 select other proxy on first proxy fail?

Question: Ubuntu Apache2,
I have configured apache2 with reverse proxy,
But if first proxy server(IP-A) is not running then
I want to pass request to other proxy server(IP-B)
How can I able to do this ?
Thanks in advanced,
Answer: You'll create a balancer group, with one member set as a hot spare.
Say 192.0.2.5 is your primary server, and 192.0.2.6 is your secondary, which should only get requests if the primary is down..
<code><Proxy balancer://proxygroup>
  BalancerMember http://192.0.2.5
  BalancerMember http://192.0.2.6 status=+H
</Proxy>
ProxyPass / balancer://proxygroup/
ProxyPassReverse / balancer://proxygroup/
</code>


Webform template suggestion doesn't work

Question: Is there a way to suggest a template in webform 3.x?
I have tried this:
$vars['theme_hook_suggestions'][] = 'webform__form__mywebform';

But it does not work.
Comment: Duplicate of http://drupal.stackexchange.com/questions/81809/using-theme-hook-suggestions-for-webform-confirmation-page.
Answer:
Apply the latest patch from here: https://www.drupal.org/node/1891220
In your theme's template.php, in YOURTHEME_preprocess_webform_form(), add:
$path_parts = explode('/', drupal_get_path_alias());
$path = implode('__', str_replace(array('-', ' ', '+', '.'), '_', $path_parts));
$hook = $vars['theme_hook_original'];
$vars['theme_hook_suggestions'][] = "{$hook}__{$path}";
Answer: To override the template of webform you just need to name it like :
webform-form-[nid].tpl.php

No need to write the code for this.
Comment: Yes, but I want to use name not id. Because devel/stagging/production server. I would like to have naming convention.
Comment: Webform don't have any machine name? How you will differentiate from other webforms?
Comment: I would like to have it webform-form-[my-own-name].tpl.php
Comment: How it will be applied to the specific webform?
Comment: I dont understand you
Comment: Path alias is one possibility that comes to mind. Language, title, whether the current user is logged in, are all available variables that could be used in selecting a template.
Answer: The reason is this part in webform_theme() function:
'webform_form' => array(
      'render element' => 'form',
      'template' => 'templates/webform-form',
      'pattern' => 'webform_form_[0-9]+',
    ),

It will ignore any suggestions if they do not match the pattern. So looks like only webform-form-[nid].tpl.php are working...
What I did (I needed only one special template for some specific webforms), I made a custom numeric suggestion with leading zero (just to be sure it's not NID).
In hook_preprocess_webform_form:
if ($my_custom_conditions) {
 $vars['theme_hook_suggestions'][] = 'webform_form_01';
}

Drupal does not ignore webform-from-01.tpl.php since it matches the pattern and it won't conflict with other webforms, because of leading zero.
Hope it saves anyone's time :)


Setting a URL alias breaks the relative image paths on those pages. Is there a way to fix this?

Question: I set a URL alias for one of my content type pages. So now every 'newsroom' content type is at http://myurl.com/newsroom/name-of-article. That's perfect. But that page also has blocks that contain images and now the paths to those images are broken.
my block contains: scr="sites/default/files/mobile-nav.png">
but the page is trying to find the image at src="NEWSROOM/sites/default/files/mobile_nav.png"
The block that contains the image is on every page of the site because it's the mobile nav.
How do I change my url alias? Or what do I need to do to tell drupal how to find the images correctly while keeping the image path relative?
Answer: src="sites/default/files/mobile-nav.png"> should be src="/sites/default/files/mobile-nav.png">
Please note the additional "/" before "sites." Without the forward slash the image will always be called from wherever you're at on the site so if you were at say site.com/news/ it would look for the images in site.com/news/sites/default.... if you don't have the forward slash before sites.
Answer: You should try to keep your code independent from your base path, so that if later on your install path changes to a subdirectory or another domain, paths will still work. Try this:
<?php global $base_path; ?>
... src="<?php print $base_path; ?>sites/default/files/mobile-nav.png"

$base_path contains the path to the Drupal installation (at least a "/" - see Drupal docs for details). Notice that it must be declared as global before use.


Run method during class destruction

Question: I have an MVVM Project and need to run some methods when th VM is destroyed. I'm trying this:
public class MyClass
{
    public void MyCleanUpmethod(object p)
    {
       // My Clean up proccess here
       ....
    }

    ~ MyClass()
    {
        MyCleanUpmethod(new object());
    }
}

My problem is that ~ MyClass() only runs when close the entire application, I need to run it when MyClass is not used anymore during current procces.
It mean if MyClass is used as Datacontext of a window ~ MyClass() must run when the window closes, if an instance of MyClass is used in other things diferent as Datacontext, ~ MyClass() must run too
How can I do that ?
Answer: You should take a look at the IDisposable interface. Your destructor code then goes into the Dispose method which should be called by your own code. Alternatively you can use a using statement, which takes care of calling Dispose at the end of the scope. For a clean implementation of the dispose pattern take a look at the MSDN article.
Using a finalizer is not appropriate because it is called by the garbage collector, which might be not in time (like in your case).
Comment: I'd also argue that this is worth another question. There has been some problems regarding the finalizer ;) Better create another question for the mvvm stuff.
Comment: Tks. I'm Reading the article now.
Comment: Regarding the call to the dispose method, this [question](http://stackoverflow.com/questions/6983801/how-to-use-disposable-view-models-in-wpf) may help.
Comment: After read the article just one question why if my class implements IDisposble, it doesn't ``Dispose`` Automatically when close my window?
Comment: `Dispose` is not called automatically. Rather, implementing `IDisposable` is a best practice for releasing resources. You're still responsible for calling the method. Maybe this [question](http://stackoverflow.com/questions/502761/disposing-wpf-user-controls) can help you out.
Comment: My problem is how to call Dispose From my ``WPF`` window Before it is closing.
Comment: No, I'm using MVVM pattern, and all the logic resides at VM and don't know how to use ``using`` on ``XAML``
Comment: I think there's some misunderstanding. You wouldn`t use the `using` keyword for this. That was just regarding the dispose pattern itself (which is an important thing to know). In your case, you'd probably just call `Dispose` somewhere. I'm pretty sure this should make it: http://stackoverflow.com/a/13930385/568266 The only difference is that you don't have a user control.
Comment: Just a problem, I need to run something commands against some lists on ``DataContext`` but in this method ``closing``, Datacontext is ``null`` Think must reformule my question. Tks a lot for your help.
Comment: Tks a lot for your help Mathias
Answer: Don't use the destructor for managed code.
instead implement IDisposable:
public class MyClass : IDisposable
{
    public void MyCleanUpmethod(object p)
    {
       // My Clean up proccess here
       ....
    }

    public void Dispose()
    {
        MyCleanUpmethod(new object());
    }
}

and then use the class like this:
using (var cls = new MyClass())
{
 //do stuff with cls
}

Comment: Tks for yur help. but how can I do to use ``using`` into ``XAML``?
Comment: hmm I dont know :) but my guess is that whatever handles the XAML, knows how to dispose objects that implement IDisposable
Comment: ``Dispose()`` Triggers automatically? or must be triggered manually?

Run method during class destruction


Java Script / AJAX email check function integration

Question: I have a form with JS functions for checking empty fields and submit form without refreshing all page, I'm looking for a way to integrate email check function into what I'm having now:
$(function() {
  $('.error').hide();
  $('input.text-input').css({backgroundColor:"#EBEBEB"});
  $('input.text-input').focus(function(){
    $(this).css({backgroundColor:"#EBEBEB"});
  });
  $('input.text-input').blur(function(){
    $(this).css({backgroundColor:"#EBEBEB"});
  });

  $(".button").click(function() {
        // validate and process form
        // first hide any error messages
    $('.error').hide();
        }

      var name = $("input#name").val();
        if (name == "") {
      $("label#name_error").show();
      $("input#name").focus();
      return false;
    }
        var email = $("input#email").val();
        if (email == "") {
      $("label#email_error").show();
      $("input#email").focus();
      return false;
    }
        var phone = $("textarea#phone").val();
        if (phone == "") {
      $("label#phone_error").show();
      $("textarea#phone").focus();
      return false;
    }

        var dataString = 'name='+ name + '&email=' + email + '&phone=' + phone;
        //alert (dataString);return false;

        $.ajax({
      type: "POST",
      url: "process.php",
      data: dataString,
      success: function() {
        $('#contact_form').html("

");
        $('#message').html("
Email sent
")
        .hide()
        .fadeIn(1000, function() {
          $('#message').append("");
        });
      }
     });
    return false;
    });
});
runOnLoad(function(){
  $("input#name").select().focus();
});

Thanks for help.
Comment: What is the "email check function" that you refer to? Your request is unclear
Answer: To check an email, you can use:
var emailReg = /^(("[\w-\s]+")|([\w-]+(?:\.[\w-]+)*)|("[\w-\s]+")([\w-]+(?:\.[\w-]+)*))(@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)|(@\[?((25[0-5]\.|2[0-4][0-9]\.|1[0-9]{2}\.|[0-9]{1,2}\.))((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.){2}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\]?$)/i

function isEmail(email) {
  return emailReg.test(email);
}
//call isEmail wherever you need it

If I may comment further on your code, I would recommend you cache your selectors and reuse them:
var input = $('input.text-input');
input.css({backgroundColor:"#EBEBEB"}).focus(function() //... and so on

Also, if your DOM is correctly structured, you do not have to call your ids with input selectors, it just slows down your implementation because its iterating over every input in the DOM than just getting it directly. That means:
$("label#phone_error") // don't do this
$("#phone_error") // do this

Also, you can use a data object to pass to jquery, so rather than
var dataString = 'name='+ name + '&email=' + email + '&phone=' + phone;

Do this:
$.ajax(yoururl, {data:
  {
    name: name,
    email: email,
    phone: phone
  }, // and so on


skip a line when it has a # character in python?

Question: I would like some help about a problem that I'm facing as a new python programmer. I did a .txt file in c++ where there are some lines starting with # character which mean a comment and I want to skip those lines when I'm reading the file in my python script. How can I do that?
Comment: It looks like you want us to write some code for you. While many users are willing to produce code for a coder in distress, they usually only help when the poster has already tried to solve the problem on their own. A good way to demonstrate this effort is to include the code you've written so far, example input (if there is any), the expected output, and the output you actually get (console output, tracebacks, etc.). The more detail you provide, the more answers you are likely to receive. Check the [FAQ] and [ask].
Comment: `if not line.startswith("#"):`  work with the lines not starts with #
Comment: Which part of this task confuses you? Detecting whether a line starts with a `#` character? Skipping it once you've decided it should be skipped? Something else?
Comment: do you want specifically to "not read" the rest of the line, or do you want to just discard/ignore it?
Comment: you'd better show your effort, for example your code
Comment: Wrote an answer but YES, this question is not a good format for the site, so removed it. We must not encourage help sucking (vampire).
Answer: I think this should help you.
I'll read the whole file and save all lines into a list.
Then I'll iterate over this list looking for the first character in every line.
If the first char is equal to "#", go to the next line.
Otherwise, append this line to a new list called selected_lines.
My code isn't super effective, one-liner or etc... but I think this may help you.
lines = []
selected_lines = []

filepath = "/usr//home/Desktop/myfile.txt"

with open(filepath, "r") as f:
    lines.append(f.readlines())

for line in lines:
    if line[0:1] == "#":
        continue
    else:
        selected_lines.append(line)

Comment: This is easier by iterating over `(line for line in open('myfile.txt') if line[:1] != '#')`. Your code reduced to one line
Comment: replace external parens with sqbraces is: `[line for line in open('myfile.txt') if line[:1] != '#']`. This is called list comprehension. The first stuff i tol you was called generator comprehension.
Comment: I think using `line.startswith('#')` would be more pythonic
Comment: replace external parens with square braces to have the list
Comment: i'm not that good yet with one liners heheh.... but thanks for your hint! what do you mean by "replace external parens with square braces"?
Comment: WARNING: it is not `next` the word you need. it is `pass` or `continue`. However, `next` will not explode being a line, since it just evaluates an expression returning such built in function (that expression is just a value with no use)
Answer: Something like this would work if it's just the beginning character.  If you need it to ignore comments after code, you would need to modify it to if '#' in line: and handle it accordingly.
with open('somefile.txt', 'r') as f:
    for line in f:
        # Use continue so your code doesn't become a nested mess.
        # if this check passes, we can assume line is not a comment.
        if line[0] == '#':
            continue
        # Do stuff with line after checking for the comment.

Comment: Thanks for ur reply. I just put the if and I solved.


É ruim usar o mecanismo padrão de sessão do PHP?

Question: Percebo é que muitos frameworks, como Codeigniter e Laravel 3 e 4 utilizam um mecanismo próprio de armazenamento de sessão. Eles não usam o mecanismo padrão do PHP (Variável $_SESSION e session_start, entre outras coisas).
E quando digo "mecanismo próprio" eu não estou falando de mudar o comportamento da sessão do PHP com a interface SessionHandler ou session_set_save_handler, mas estou falando de trabalhar com um mecanismo para criação da sessão, sem utilizar nenhum dos recursos (já prontos) do PHP.
Gostaria de saber se há algo ruim com o mecanismo padrão de sessão do PHP?
Existe alguma limitação na sessão nativa do PHP, para que os frameworks utilizem outra maneira de implementar sessões?
Comment: Aparentemente gera race conditions no caso do lavarel: https://github.com/laravel/framework/issues/5416#issuecomment-68366445. Lembro de já ter enfrentando problemas similares com native session de php na in-house framework que mantenho no trabalho, mas faz algum tempo e não lembro exatamente o que era e como resolvemos, só que foi chato pra burro.
Comment: Acho que as pessoas reclamam mais da sessão do CI do a do PHP :D.
Comment: Não consigo afirmar categoricamente. Acho que não há problema se souber usar. Acredito que *frameworks* usem de um jeito mais fácil de fazer certo e seja uma camada de abstração que permita modificar no futuro a implementação concreta, além de dar algumas flexibilidades e características adicionais. Que tem limitação, tem, tudo tem. Tudo está limitado ao que aquilo faz. Se precisa de mais, é outra questão.
Comment: É claro, o pessoal do CI dão duas opções: Database e Cookie. Usar cookie como sessão é uma opção muito meia boca. Aí é melhor dar um session_start no meio de um código que não deveria usá-lo
Comment: @bigown interessante. Você respondeu algo parecido com o gmsantos nessa pergunta http://pt.stackoverflow.com/questions/73058/por-que-deveria-usar-filecopy-se-no-php-j%C3%A1-existe-copy
Comment: Não é ruim utilizar a sessão do PHP, o que torna ruim é a forma como alguns programadores à utilizam.
Answer: Como todo recurso é preciso entendê-lo completamente, ler toda documentação e eventualmente procurar informações não documentadas. Algo complexo como este pode ter uma série de detalhes que podem passar desapercebidos. Não vou tentar colocar tudo o que precisa ser verificado, até porque não sou especialista no assunto, e acho que nem cabe, minha intenção não é dar uma resposta definitiva.
O motivo principal de frameworks prover mecanismos próprios para qualquer tecnologia é a abstração do recurso.
Abstração é um dos conceitos mais mal entendidos da computação. Ela sempre existiu antes mesmo de existirem os computadores modernos. A abstração dá mais significado ao que se está fazendo e coloca uma camada em cima do concreto, permitindo que a implementação real seja escondida do usuário daquele recurso.
Uma das maiores vantagens da abstração é que se ela for bem feita pode trocar a implementação sem exigir que os códigos que a usam sejam modificados. Isso é muito importante em diversos cenários. Nem sempre é possível fazer bem feito, por melhor que seja o programador. E nem sempre a complicação da abstração que será necessária vale o esforço.
Então é interessante que estes produtos tenham uma forma que pelo menos não dependa do padrão do PHP.
E como o padrão tem uma implementação relativamente simples e fixa é natural que eles forneçam uma implementação mais poderosa e flexível. Consigo imaginar um monte de coisas que sejam possíveis fazer em uma sessão além do que a implementação padrão fornece. Há vários cenários onde a padrão não atende bem. Embora a maioria dos cenários dispensa qualquer outra solução.
Além de obviamente suprir mais informações, uma melhor integração com banco de dados e distribuição de sessão e transporte e informação de identificação de outra forma e contagem de sessões ativas são alguns exemplos do que pode ser melhorado.
Como foi dito em comentários, o fato de criar uma versão própria, não quer dizer que ficará melhor. Ainda que a intenção desses frameworks seja facilitar o uso dos recursos em relação ao que existe no PHP. Talvez a tentativa de fazer algo melhor tenha deixado complexo demais.
A maioria dos problemas que eu vejo com o uso da sessão padrão tem a ver com o uso errado. Ok, pode ser um pouco difícil fazer certo, mas é obrigação do programador saber fazer isto. E os frameworks terão que escolher entre facilitar ou dar um recurso mais poderoso e flexível. O que eu vejo eles fazerem muito é aplicar as tais das boas práticas, ou seja, eles escolhem o que é bom para você, mesmo que aquilo não seja o melhor sempre.
Pelo tamanho da página da documentação de apenas uma função dá para ter uma ideia de como é complicado usar direito, de forma segura, mas não tem muito o que fazer quando o problema é complexo (ainda que seja um exagero chamá-lo de complexo).

Gostaria de saber se há algo ruim com o mecanismo padrão de sessão do PHP?

Se fosse tão problemático já teria bastante recomendação para não usar, alguém já teria feito um substituto no PHP. É bom ter uma informação aqui, mas o problema não está no recurso, está na pecinha entre o teclado e a cadeira :)
Coloquei no GitHub para referência futura.
Comment: Ótima resposta, como sempre. +1
Answer: Depende. O uso de sessions padrão do PHP não apresenta problemas de forma geral, contudo ele pode ser ruim dependendo de como é utilizado. O save handler padrão usa arquivos, assim em cada request recebido, mesmo com você não usando a sessão em alguns, vai rolar um lock nos arquivos de sessão e uma subsequente leitura deles, isso pode representar um overhead relevante se você tiver uma quantidade realmente grande de requests.
Outro detalhe é que, como eu já disse, fazer um request gera um lock no seu arquivo de sessão (cujo caminho padrão é algo como /var/lib/php/session/sess_$identifier), sendo assim quaisquer requests concorrentes tem que esperar a liberação desse lock para que possam proceder. O lock inicia em session_start() e termina no fim da execução do seu script, ou na chamada de session_write_close(), dessa maneira caso você tenha uma situação em que o cliente faça vários AJAX requests seguidos para o servidor todos esses requests entram em fila esperando o que chegou antes liberar o lock do arquivo de sessão, e isso é realmente ruim. O ideal para minimizar esse problema é sempre usar session_write_close() o mais próximo possível do início da sessão, caso contrário requests concorrentes vão ter que esperar o fim da execução do script que chegou primeiro, o que pode significar uma pancada de operação (ler arquivos, acessar database, processar coisas, etc).
Um outro problema que parece levar várias frameworks a evitarem o uso das sessions padrão de PHP é o fato de que session_start(), assim que invocado, sempre envia o cookie de sessão para o cliente. O problema aqui é relacionado com o descrito no parágrafo anterior, você quer fechar a sessão o mais rápido possível após abrir ela, contudo talvez você queira fazer algo como escrever algo na sessão no fim do seu PHP script e caso já tenha fechado ela vai precisar reabrir. Nessa situação você tem o problema de que provavelmente vai receber um erro similar a Headers already sent pois em HTTP o cabeçalho é sempre enviados antes do conteúdo, e num estágio tardio do seu script é provável que você já tenha terminado de enviar o cabeçalho e começado a mandar conteúdo e a chamada de session_start() vai tentar enviar mais cabeçalho (o cookie).
Por fim nós temos a questão já comentada na resposta do Maniero, que embora tão abstrata que de para você usar ela em 90% das perguntas conceituais de programação (hah é zoeira em, a resposta é boa ;) ), explica bem o fato de que você muitas vezes quer um controle maior que aquele dado por uma implementação nativa, ou quer ter uma acesso a uma abstração diferente, ou quer algo mais flexível, ou ainda quer uma implementação cuja funcionamento seja mais fácil de compreender (que saber o que rola por baixo dos panos, sem "mágica").
Comment: no finzinho tem a nota do conserto: demorou hein, arrumaram nao faz nem um ano. :D  _[2015-08-11 10:36 UTC] firstname.lastname@example.com Time goes by.
I fixed this already. If you have problem, please open new bug report._
Comment: https://bugs.php.net/bug.php?id=38104


Falha com PostAsJsonAsync - WebApi - C#

Question:
Fiz uma WebAPI que pelo Postman eu consigo fazer um CRUD completo, porem criei um Windows Forms C# pelo Visual Studio e estou com alguns problemas.
Consigo dar um get e todos meus dados são buscados perfeitamente, só que aoem ao dar um post, aparentemente da um retorno Ok 200 do methodo Post, mas nada é criado no meu banco.
Esse é meu controle:
public IHttpActionResult Post([FromBody]PROJETO projeto)
{
     var model = new ProjetoCriarEditarViewModel();
     model.CriarProjeto = _projetoBO.CriarProjeto(projeto);

     return Ok(model.CriarProjeto);
}

Esse aqui é o meu método no C#.
private async void button1_Click(object sender, EventArgs e)
{
    using (HttpClient client = new HttpClient())
    {
        client.BaseAddress = new Uri("http://localhost:19832/");

        PROJETO project = new PROJETO();
        project.NOME = textBox1.Text;
        project.DATA_INICIO = dateTimePicker1.Value;
        project.DATA_PREVISTA = dateTimePicker2.Value;
        project.TECNOLOGIA = textBox2.Text;
        project.VALOR = Convert.ToDecimal(textBox3.Text);
        project.STATUS_PROJETO = textBox4.Text;
        project.ID_CLIENTE = Convert.ToInt32(textBox6.Text);

        var resposta = await client.PostAsJsonAsync("/api/projetos/", project);
        bool retorno = await resposta.Content.ReadAsAsync<bool>();
    }
}

Comment: Colocou o atributo [HttpPost] em cima do seu Controller?
Comment: Não coloquei pois ele entende que é um Post pelo nome do método. Então nesse caso nao faz diferença.
Comment: só pra garantir, seu `_projetoBO.CriarProjeto` está dando _commit_ ao fim processo?
Comment: Sim. Eu consigo dar um post pelo postman usando a api e ele cria perfeitamente no banco de dados da minha aplicação. E tambem consigo usar "_projetoBO.CriarProjeto" em toda app.
Comment: @joaop.mr Mas tu testou com o atributo? Fazer o post com o atributo através do código e não do postman?
Comment: Testei por desencargo rs e nada.
Comment: se já debugou? outra coisa o que dentro desse código: CriarProjeto?
Comment: Ja debuguei. Ele retorna o metodo post OK 200. Como se tivesse gravado. Porem não grava.
Comment: CriarProjeto é meu metodo nas regras de negocio que leva pro repositório. Outra coisa, uso o Entity Framework.
Comment: Você tem que debugar o código do repositório!
Comment: Mas eu consigo enviar pelo Postman. E tambem consigo gravar na aplicação. De qualquer forma o farei.
Answer: Vou colocar um exemplo de método que eu utilizo em meus projetos e até hoje nunca me deu dor de cabeça. Está um pouco diferente do seu, creio que talvez estes detalhes façam diferença.
private async Task<bool> PostoToAPIAsync(PROJETO projeto)
{
    HttpClient client = new HttpClient();
    client.BaseAddress = new Uri("http://localhost:19832/api/");
    client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

    // Converte seu objeto para formato Json
    string json = JsonConvert.SerializeObject(projeto);

    // Espera o resultado
    HttpResponseMessage response = await client.PostAsync("projetos", new StringContent(json, Encoding.UTF8, "application/json"));

    // Verifica se o retorno é 200
    if (response.IsSuccessStatusCode)
    {
        return true;
    }

    return false;
}

Perceba que alterei o endereço da sua API e coloquei uma / no final:
http://localhost:19832/api/

E removi a / do método da sua API:
projetos

Além disso, perceba que o método que criei é async, então você deve chamá-lo da seguinte forma:
PROJETO project = new PROJETO();
project.NOME = textBox1.Text;
project.DATA_INICIO = dateTimePicker1.Value;
project.DATA_PREVISTA = dateTimePicker2.Value;
project.TECNOLOGIA = textBox2.Text;
project.VALOR = Convert.ToDecimal(textBox3.Text);
project.STATUS_PROJETO = textBox4.Text;
project.ID_CLIENTE = Convert.ToInt32(textBox6.Text);

if(await PostoToAPIAsync(project))
{
   // Criado com sucesso
}
else
{
   // Erro ao criar
}

Comment: Obrigado pela dica. Fiz exatamente isso amigo. Continuo com o mesmo problema. Ele retorna sucesso mas não grava nada no banco.

Falha com PostAsJsonAsync - WebApi - C#


Do I always have to type package name in Java?

Question: Today I started learning Java.
I saw that package automatic gets included in .Java file.
I was wondering if it always need to be included?
Answer: Yes and no.
It's used to specify the package of the class, read more here.
You could create a class without a package, but your code will look bad..
They exists to avoid conflicts, example between your code and default java package.
If packages doesn't exists, you can't create a class named ArrayList because already exists in Java.
Some IDEs force the fact that, if your .java file is in com/a/b/c folder his package should be com/a/b/c (If i don't remember wrong, IntellIJ IDEA do that)
Answer: Yes and no.
It must be there, but the IDE takes care of it (I don't use Netbeans, but I'd bet that it can do it, too). When moving files between packages, it has to be updated, but again, the IDE does it all.
Answer: Consider specify a common package for all the types within a same project.
In Java is common to start a project with a specific package setting. A package creates a namespace to disambiguate the types that it includes, to play nicelly with other projects that may or may not be in the same classpath. Normally, the package is bound to a URL of the project.
Think of Java packages like C++ namespaces.
A huge project/product written in Java can depend on lots and lots of projects, each described in a different package.
Organizations like Apache have lots of projects, organized under a common package pattern: org.apache.<<name_of_the_project>>.
Consider starting your project with a package named: com.user3552670; or something like your personal site, so persons that will consume your project can relate to the creator.


Get NSManagedObjectId when saving object

Question: How does one retrieve the NSManagedObjectID when saving an object to Core-Data?
I have a series of objects to save to Core-Data and I need to have each ones objectID as I am saving on another thread.
I would then like to pass this array to the main thread and fetch the objects for the array of IDs.
Comment: Can't you just keep the objects you are adding in an array, and then pass that array to the main thread and let that thread iterate through the array and access each object's `objectID` property?
Answer: You can use key value coding which is very convenient:
<code>NSArray *objects; // the objects you are saving
NSArray *objectIDs = [objects valueForKeyPath:@"objectID"];
</code>
However, this does not make too much sense. Why don't you just pass the array of objects right away? You could also retrieve them from the store with a suitable predicate.


Is Cmaj7 in the C major scale different than the Cmaj7 in the C Dorian scale?

Question: I was told that the 7 in Cmaj7 indicates the 7th scale degree.
But here's what's confusing to me: in the C major scale, the 7th scale degree is B. And the interval from the root note of the Cmaj7 chord to the 7th would be a M7.
However, in the C Dorian scale, the 7th scale degree is A#, and the interval from the root note of Cmaj7 to the 7th would be a m7.
So if the number 7 in Cmaj7 really indicates the 7th scale degree, then does that mean Cmaj7 in C major scale is different than Cmaj7 in C Dorian scale?
Comment: Cmaj7 is Cmaj7. There is no Cmaj7 made up from the notes in C Dorian. There will be Bb maj7 and Eb maj7 instead.  There is no A# note in C Dorian. It's Bb.
Answer: CMaj7 always has the notes C E G B regardless of the context around it. In general terms, any major 7th chord contains a root, Major 3rd, Perfect 5th, and Major 7th. It is naturally built in the C major scale by building a chord starting on C in 3rds, but it does not stop you from using it elsewhere even when the notes are not naturally found in the key/scale you are playing. You can play this in any key and it will contain the same notes.
You also seem to be confused with what C Dorian is. C Dorian not only does not have the B, but it also has no E. The notes of the C Dorian scale are as follows:

C D Eb F G A Bb C

If you naturally wanted to build a seventh chord off the root of the scale, it would be Cm7 which contains the notes C, E♭, G, and B♭ or in other terms contain a root, minor 3rd, Perfect 5th, and minor 7th.
Also note: there is no A♯ in C Dorian. The note is B♭ since if you spelled it as A♯ you would have a scale with two As and no Bs. For more information on how notes are named in different contexts, see this question.
Answer: C Ionian is C D E F G A B, whereas C Dorian is C D E♭ F G A B♭. (Note that this last pitch is not A♯, as you wrote.)
When you say that "the 7 in Cmaj7 indicates the 7th scale degree," I have one small adjustment: "the 7 in Cmaj7 indicates the 7th scale degree of the major scale" (hence the maj 7).
So in C Ionian (or C Major), the seventh chord built on C is Cmaj7, because the pitches are C E G B, taken straight from the C-Ionian collection.
But in C Dorian, the chord will be C E♭ G B♭, which creates a Cm7 chord.
In short, I think your confusion lies in the distinction between "Cmaj7" and "the seventh chord built on C." The quality of the seventh chord built on C will not always be maj7; instead, it will change depending on the current key signature.
Answer: Your confusion might arise from a mistaken assumption that the 'maj' in Cmaj7 refers to the 'C'. Actually it refers to the '7'. That is to say, the 7th interval added to the C triad is a major 7th.
By convention, major triads have no suffix, minor triads have a 'm' suffix, and  diminshed has 'dim' or '°'.
For the 7th interval the convention is sort of backwards. Minor 7th intervals are written just as '7' (minor implied, no prefix), and major 7th intervals are written as 'maj7', 'M7', or even just '△' as a shorthand.
Note the upper-case 'M'. If you see Cm7 then that is a C minor triad with a 7th, and because the 7th isn't prefixed with anything (the 'm' belongs to the C) it is a minor 7th interval.
Indeed, there is such a thing as a minor major-7th chord, e.g. C, E♭, G, B, sometimes notated as CmMaj7 although there are many other notations.
Comment: 3rd para. True a '7' without a prefix has a *minor 7th* interval, but the chord produced will either be *minor 7* OR *dominant 7*
Comment: F7 is a dominant 7th even if your intent is not to use it for its dominant function. The feature of a dominant 7th is the tritone between the Major 3rd and the minor 7th makeing it want to resolve the typical dominant-tonic way
Comment: @Tim I'm not entirely sure what you're getting at. I don't think F7 in the key of C major could strictly be called the dominant 7th when it's actually built on the sub-dominant chord (F). If it was being used as a dominant chord then the implied key would be B♭.
Comment: F7 was not mentioned. All I am trying to do is clarify your 3rd para., which comes over (to me) as C7 = Cm7, which it doesn't. It could be phrased a little less ambiguously. Sticking with F7 - any dominant 7 will contain a maj. 3rd and a m7 (b7). whether it's based on a sub-dominant root is immaterial.
Comment: Thanks for the comments. I've edited my answer for clarity.


sql: check for existence of only one specific item for an id, when multiple items may exist

Question: I have a database of locations that can have anywhere from 0 to 27 types of logs available. I'm only interested in the presence of 1 type of log and want to return true or false if that log exists. I tried using CASE WHEN but the problem is my results are showing true or false if the one log exists (which is the desired outcome)and then false for all of the other logs, so I get multiple rows with the same id (which is not what I want).
Sample code:
SELECT
Table1.LocationId
, CASE WHEN Table2.LogId = 8 THEN 'True' ELSE 'False' END AS 'Log8Avail'

Desired result would be:
| LocationID |Log8Avail|
 ----------------------
| 1          | True    |
 ----------------------
| 2          | False   |
 ----------------------
| 3          | True    |
 ----------------------

But what I'm currently getting is:
| LocationId | Log8Avail|
 -----------------------
| 1          | True     |
 -----------------------
| 1          | False    |
 -----------------------
| 1          | False    |
 -----------------------
| 2          | False    |
 -----------------------

My question is, how can I adjust my query so that it only looks for the presence or absence of the specific log I'm interested in?
Comment: Please show your full query.  Where is `Table2.LogId` coming from?  What are your table definitions?  Also, what DBMS are you using?  (MySQL?  SQL Server?  Oracle?  Something else?)
Comment: Sorry about that. I'm new to StackFlow and SQL. Next time I will post full code and specify the DBMS. Thanks for your feedback.
Answer: SELECT
Table1.LocationId
, CASE WHEN (SELECT COUNT(*)
             FROM Table2
             WHERE Table2.LogId = 8)>0 THEN 'True' ELSE 'False'
  END AS 'Log8Avail'

Like this?
Answer: SELECT t1.LocationId,
       CASE WHEN t2.LogID IS NULL
            THEN false
            ELSE TRUE
       END as Log8Avail
FROM Table1 t1
LEFT JOIN Table2 t2
      ON t1.id = t2.id
     AND t2.LogId = 8