How to determine the location of a mark on an object that has changed size?

Question: I apologize up front for the horrible title, I do not have the mathematics vocabulary to eloquently summarize this in a title.
This first picture and question is a lead-up to the actual question. In an attempt to explain it.
You have an object of a known size, you put a mark on it at a certain percentage of it's size. You now increase the size of that object in one specific direction, you know by what percentage that object changed size, at what percentage is that mark currently located?

That's a fairly simple answer. Now knowing the previous question, consider the following:
You have an object of an unknown height. You have a mark that has a known height as a percentage of the height of the object it takes up and a known location on that object as a percentage of the height of that object. You increase the height of the object by an unknown amount. The only thing you now know is the height of the mark as a percentage of the height of the object. How do you find it's location as a percentage of the height of the object?
Edit: The green object ONLY expands down, and the red mark stays in the exact same position relative to the top o the object. The red mark also maintains the exact same size in units, even though that size is unknown.

I hope that made sense. If that is unsolvable, what other variable do I need?
(Additionally, what are appropriate tags for this question?)
Edit: Oddly enough you can intuitively solve this when the numbers are simple. If the red mark is at 50% of the height and the green box increases in size downwards by 100% of it's current size. Then the red mark will be at 75% of it;s height. I'm not sure if this is an intuitive guess that just ends up being correct, or if there is some sort of mathematical backing.
Answer: I assume your mark doesn't change position relative to the upper bound of the expanded object (looks so to me based on your picture).
Let $x$ be the height of the mark, $y$ be the height of the original object, $z$ be the height of the expanded object. We have
$$\frac{x}{y}=50\%=\frac{1}{2}\\
\frac{x}{z}=0.27$$
Divide these two equations:
$$z=\frac{y}{0.54}$$
Now let $y$ be $1$. The center of the mark is at $1-0.65=0.35$. Suppose it does not change, but the height of the object is now $\frac{1}{0.54}$. So the center of the mark is now at
$$1-\frac{0.35}{\frac{1}{0.54}}=1-0.35\cdot 0.54=0.811$$
Comment: Thank you! I'm just writing this down into an equation I can plug values into right now. I am stuck on where you got 0.35, where did that number come from?
Comment: @douglasg14b: Sorry forgot to mention that. I edited the answer.
Comment: This is probably going to sound ridiculous, but now where did the 0.65 come from? If z = y/0.54 (which is the same as z = y* 1.851) this determines the change in size, z is 1.851 times larger than y. Maybe I'm a bit dull, though I'm not quite getting where the 0.65 comes from if y = 1;
Comment: @douglasg14b: It is because you said the center is at $65\%$ of the height.
Comment: Ohhh, I see. Thanks, I was being pretty dull there.
Comment: Thanks KittyL, here is what your help went towards: http://i.imgur.com/YuIK2s3.gif (excuse the typo)
Comment: @douglasg14b: Nice little app. :)
Answer: It depends how the object is expanded.
If it is expanded uniformly by a certain factor then the size of the mark is also expanded by the same factor and its location is unchanged.
If the asparagus analogy is correct, then the length below the mark is fixed and only the length above the mark actually grows. If the object expands by a factor of $z$ (let's take the initial length of the object as our unit length) and our mark's mid-point is at $x$ (with $0$ being the bottom of the object) then the position of the mark after expansion is at $x/z$. If the mark's position is with reference to the top of the object (i.e. $0$ means the midpoint of the mark is at the top of the object) then, its new location is at $1-(1-x)/z$.
Comment: Thank you for the reply.
The marks size in units is always constant (however it's actual size is unknown), the only object that changes in actual size is the green box. Which will always be expanded downwards.
Comment: As a visual analogy, could the object be an asparagus (growing upwards) and the mark an independent plastic label fixed to the ground?


How to Apply Filters in DataView(To hide top 5 rows, to hide last 10 rows)

Question: *Hi I want to hide top 5 rows/top 20/bottom 5...etc. How to filter in DataView. Please someone help me out to resolve this. Thanks in advance. *
Answer: You can use Linq.Check out below linq query.
<code>var result= dataView.ToTable().AsEnumerable().OrderBy(r => r["ID"]).Skip(5).ToList();
</code>
For more information check out following msdn link
http://msdn.microsoft.com/en-us/library/bb669073(v=vs.110).aspx


Evaluate $\iiint_V \sqrt{x^2+y^2+z^2}\, dV$ where $V: x^2 + y^2 + z^2 \leq 2z$

Question:
Evaluate $$I=\iiint_V \sqrt{x^2+y^2+z^2}\, dV\,,$$ where $V: x^2 + y^2 +
z^2 \leq 2z$.

I tried using the cylindrical coordinates to arrive at:
$$I = \int\int_R\int_{z=1-\sqrt{1-r^2}}^{1+\sqrt{1-r^2}}r\cdot\sqrt{r^2+z^2}\,dz\,dr\,d\theta$$ where $R = r \leq 1$
But this is very tough to evaluate. Is there a better way to do this?
Comment: Why not spherical coordinates?
Comment: @NinadMunshi Thank you
Answer: In spherical coordinates we have that
$$x^2+y^2+z^2 \leq 2z \implies \rho \leq 2\cos\phi$$
so let's set up in the integral in this coordinate system. As an added bonus, let's do the angular integral first:
$$I = \int_0^{2\pi} \int_0^2 \int_0^{\cos^{-1}\left(\frac{\rho}{2}\right)} \rho^3\sin\phi \:d\phi \:d\rho \:d\theta  = 2\pi\int_0^2\rho^3-\frac{1}{2}\rho^4\:d\rho = \frac{8\pi}{5}$$


Best way of getting the key after $add

Question: I am using angularFire v 0.5.0
On my returned object I do a $add.
What would be the best way to get the generated key?
It must be something in the succes callback of the $add, because the key will come back asynchrounlusly?
scope.settings = $firebase(ref);

scope.settings.value = {
    vat: {
      inclusive: true
    }
}
            }
scope.settings.$add (scope.settings.value).then( function ( {
  scope.settings.key = ???
});

note: this is not the actual code, this is just to clarify the problem.
The actiual code is inside a factory in the loaded event, and there is a check if there is already a settings object inside the database.
This somewhat strange construct is to make it easyer for consumers of the factory to change the settings. The settings is a singleton. AngularFire does not return a array of objects, but every item is a object in the settings, with its own key.
Answer: $add returns a Firebase ref. Call name() on that ref.
scope.settings.$add(…).name();

See https://github.com/firebase/angularFire/blob/master/angularfire.js#L127.
Answer: from the angularfire docs:

The $add method takes a single argument of any type. It will append this value as a member of a list (ordered in chronological order). This is the equivalent of calling push(value) on a Firebase reference.

from the firebase docs (about push()):

Returns
  A Firebase reference for the generated location.

so, i think the "key" that you want is the return value of the $add.
Answer: Maybe they've changed it in newer versions, now it works like this:
$add() will return a promise. You have to use the callback which runs on success. For example:
var something = $scope.somethings.$add({name: "foo"});
something.then(function(e) {
    console.log(e.name())
});

This allows you to perform different actions based on the outcome of the save/write attempt to Firebase.

Best way of getting the key after $add


Unexpected packet read error ODP.net managed driver on Dev server - works on local IIS

Question: I have code using .Net 4.6, c# and running using
EF6
nuget package :
Oracle.ManagedDataAccess.12.1.24160719
Oracle.ManagedDataAccess.EntityFramework.12.1.2400
Code deployed on local IIS works fine, when deployed on dev server (IIS 7) getting attached ORA-12570: Network Session: Unexpected packet read error. (Note I have deployed on other local iis also, it works )
Comment: have you gone to Oracle website and try to understand when this error occurs?
Comment: no doc found, this error used to come for previous versions, with nuget it does not require any installation. I have added entry in web.config to ignore gac policy and use this version of managed driver
Comment: I googled for it and it returned 45K results. https://asktom.oracle.com/pls/asktom/f?p=100:11:0::::P11_QUESTION_ID:424289000563
Answer: We found that we had below product version in GAC (it has same file version and public token)
Oracle.ManagedDataAccess.dll 220.127.116.1150926 ODAC RELEASE 4
we are using Oracle.ManagedDataAccess.dll 126.96.36.19960624 ODAC RELEASE 4 (nuget package)
When we replaced the dll with the new product version in GAC or removed the dll from GAC - our app start working


Is there any reason to have 2 NICs on a server?

Question: Is there any reason to have 2 NICs on a server BESIDES the following cases?

You need to connect to 2 different physical networks
Redudancy (1 NIC fails, so you use the other)

Are there any other reasons?
Answer: (2a). Load balancing.
(3). Separation of traffic (i.e. you could have a combo web/database server, same network, put all web traffic on one NIC, db traffic on the other, makes it easier to calculate loads for traffic types). This also makes it easier to split the two later on, nobody has to change connection strings.
Answer:
A separate network for backups.
A separate network for console access (these are typically now integrated on the system board for mainstream servers).
Increased throughput (multiple GB networks) bonded together.
Comment: 1x 10 gig is better! ;)
Comment: Bonded NICs is the one we use most. 4 x 1Gb NICs is Champion..
Answer: There's only one other major reason that I can think of, which is similar to redundancy, and that's Trunking, so you could configure traffic to flow over 2x1Gbit ports, giving you 2Gbit of total throughput. Some refer to this as LaCP, linux knows this as mode=4 as described below.
Linux interface bonding modes give a few other options:
mode=0  (balance-rr)
Round-robin policy
mode=1 (active-backup)
Active-backup policy
mode=2  (balance-xor)
XOR policy: Transmit based on [(source MAC address XOR'd with destination MAC address) modulo slave count].
mode=3 (broadcast)
Broadcast policy: transmits everything on all slave interfaces. This mode provides fault tolerance.
mode=4  (802.3ad)
IEEE 802.3ad Dynamic link aggregation. Creates aggregation groups that share the same speed and duplex settings.
mode=5  (balance-tlb)
Adaptive transmit load balancing: channel bonding that does not require any special switch support.
mode=6 (balance-alb)
Adaptive load balancing: includes balance-tlb plus receive load balancing (rlb) for IPV4 traffic, and does not require any special switch support.
Comment: 802.3ad == LACP == Mode 4, they are all the same terminology for the same thing. LACP being the most common term used (which is the control protocol specified in 802.3ad)
Comment: Is the more common term for what you are describing "bonding"? I have not seen this called "Trunking".
Comment: I've heard both Trunking and Bonding; with trunking being the more popular. The only problem with that, vLans have trunking as well, which can get confusing at times (it's bit me before). Different vendors have different names.
Comment: @iPaulo: Windows drivers tend to call it 'teaming' , another word to add to the mix :-)
Comment: I think I mentioned that somewhere in my answer..
Comment: @iPaulo, bonding and trunking are the same thing. People from different areas of the world call it different things, but the terms in this situation are interchangable
Answer: Microsoft clusters require an additional NIC port for heartbeat purposes between nodes.
Comment: Not only Microsoft clusters require this... lots of cluster setups require or at least recommend an additional NIC.
Answer: Similar to #2, multiple NICs is also a requisite for high avaliability. Multiple network interfaces (on the same network, but should really be seperate) will be used to monitor which servers are avaliable (a heartbeat). Also, in the case of VMWare, a 3rd NIC can be used for migrating the active state of a virtual machine without interferring with the amount of bandwidth avaliable to the public interface, or the heartbeat.
Answer: Probably 2 NICs is the minimum required for a server, like other said at least for HA. If you start including console, heartbeat, possibly iSCSI storage... you can easily hit half dozen NICs for a server.
Answer: This might come under "# You need to connect to 2 different physical networks", but if the server was also a router, it would need two NICs.
Answer: I always use 2 NICs in a server for redundancy. More than once over the years I've unplugged the wrong cable (usually caused by rushing too much). It's really nice not to have the server disconnect as a result. I've also suffered failed NICs a couple of times.
As far as I'm concerned, if at all possible a server should have redundant everything. NICs are no exception. On the rare occasion I've also needed traffic isolation I add a second pair for that.
Comment: Add failing cables, connectors, and switches to the mix. In the area of virtual voice switching down time is not acceptible. Not during production, not during maintenance, not ever. Where we can live with a mail server or web server being down for a short time (seconds, minutes) this would kill the service on any voice carying device.
Answer: I have never understood the NIC redundancy argument. Without moving parts they rarely fail ... you don't have 2 motherboards in one server, do you? Best be redundant on the whole server level.
However, I like the "human error" redundancy above when unplugging in error.
Comment: No moving parts? Cables are moving parts, especially when someone's working near them :). Joking aside, it can be a fairly complex path between a NIC and switch (cable -> port replicator -> horizontal cabling -> port replicator -> switch). Any one of those components just might be delicate and fail. Plus, while NIC ports themselves may rarely fail, switches will more often fail. You may need to upgrade the OS on a switch or reload it for some other reason - it's necessary to do so without taking an outage on a whole whack of servers.
Answer: Having one interface dedicated to running snort or some other honeypot or IDS, and the other in your internal network is another good reason to have 2 nic cards. Agreed on the load balancing and trunking ideas as well.


Trying to update node using node_save() produces integrity constraint exception

Question: This is the first time I've tried to do this so I may be missing something really obvious. I'm developing a module which uses hook_node_insert() to catch the creation of a node, and puts the node into Drupal Queue for later treatment by a cron process.
At the end of the process, I want to update a field in the node and save it. I've tried using entity_metadata_wrapper as well as node_save, but in both cases I get an error "PDOException: SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry '3011' for key 'PRIMARY': INSERT INTO {node}....". Apparently, Drupal is unaware that the node exists already despite the fact that $node->nid is set (which is why we get a duplicate entry integrity constraint).
Looking at the node_save() code, it certainly seems to be supposed to check and load the node first if the nid is set (which it is - I've followed this step by step in debug). I must be doing something wrong, but what?
Here is the code from hook_node_insert which queues the node for treatment:
if ($node->type == "sms_message") {
  $queue = DrupalQueue::get('sms_message');
  $node_wrapper = entity_metadata_wrapper('node', $node);
  $node_wrapper->field_queued->set(1);
  drupal_set_message($node_wrapper->label() . ' has been queued');
  $queue->createItem($node);
}

And here is the relevant code from the callback module for hook_cron_queue_info
function sms_textlocal_outgoing($node) {
  global $user;
  $user = user_load(1);
  $node_wrapper = entity_metadata_wrapper('node', $node);
  $message = $node_wrapper->field_sms->value();
  $sms_sent = 0;
// Then we do some processing...
  $node_wrapper->field_sms_sent->set($sms_sent);
  node_save($node);

I've also tried:
$node_wrapper->save();

instead of node_save, but with the same result.
Answer: please see the documentation of the hook
https://api.drupal.org/api/drupal/modules!node!node.api.php/function/hook_node_insert/7
Notice that it says that the hook is invoked (i.e. triggered) by node_save and that means that the data is NOT yet written in the database! so you essentially create an infinite loop.
Try to do something like $node->yourfield['und'][0]['value']= 'yourvalue_here' and DO NOT call node_save again. Also do not use a wrapper because in this case only adds complexity. Notice that if you dont use the wrapper you must provide the langauage (['und']  in my example) the number of the item ([0] ie the first one in my example) and the key of the table that stores the value (['value'] in my example). This is done automatically when you re using an entity wrapper but since your node is not ready yet it is not the best option because you clone the object by value and not by reference and then even if you change it the changes are not reflected in the original one that will be fed into the database.
Comment: I'm not sure you've understood the question. Please note that there are two quite different moments in the process. The first is the implementation of hook_node_insert - this actually works fine. The problem occurs when the cron process is run - by this time the node has been saved ok and I am just trying to change one field value. The node is certainly in the database because I have a NID (in fact my problem is that it is trying to save instead of update)
Answer: In fact, the problem seems to be due to the fact that the node had not been loaded prior to node_save(). It's a bit of a shame -  I had despatched the entire node to the queue in the hopes that the Drupal Queue callback function would just be able to take the node off the queue and update it direct, but apparently not.
So, this worked:
function sms_textlocal_outgoing($node) {
  global $user;
  $user = user_load(1);
  $node_upd = node_load($node->nid);
  $node_wrapper = entity_metadata_wrapper('node', $node_upd);
  $message = $node_wrapper->field_sms->value();
  $sms_sent = 0;
// Then we do some processing...
  $node_wrapper->field_sms_sent->set($sms_sent);
  $node_wrapper->save();


Decimal out of range exception

Question: In my C# application, I am trying to save a decimal price into a SQL Server table. Columns type is decimal with no total digits defined.
Without discount calculations, everything works fine.
But when I run some calculations, I get a final value of 21800, and I get the following error when trying to save it.
"Parameter value '218000/00000000000000' is out of range."

I don't understand where the extra zeros come from! The only thing I know is with myValue.ToString() I get 218000/00000000000000, too!
I understand that the digits after floating point are caused by the calculations. But whatever they do, my value is 21800 when watching it. Why is it trying to save 218000/00000000000000? Why does it care at all about the zeros?
Any ideas why this happens and how to fix it?
Comment: Can you provide a code example?
Comment: In the DB you MUST define a decimal precision. Look up what is defined in your table. My guess is that it is something like `decimal(18,14)`
Comment: @lonic I'm afraid not, those discount calculations are done by a whole other classes, but what matters is that the final value is a decimal.
Comment: @juergen I changed my DB column data type to `decimal (19, 4)` and still get the same error. I think I have to also change my `.edmx`
Answer: There are two ways to store decimal numbers:

Fixed-Point: This is what you have defined in your SQL Server project. You defined decimal (19,4), which means 19 digits total and 4 digits after the decimal point. If you define such a type, then every number always has 4 digits after the decimal point; and also, you cannot store a number with more than 4 digits after the decimal point.  And note, there is no equivalent to fixed point in C#!
Floating Point: These are the types float, double and decimal in C#, and the type float(n)in SQL Server. In floating point, as the names says, you can basically vary the number of digits before and behind the decimal point. (Technically, you have a fixed number of digits, the so-called mantissa, and you can then move the decimal point around with a 2nd number, the exponent)

So now to your project: In your database, you use fixed point, while in C#, you have floating point. Therefore, when you calculate something in C#, and you want to store in to your database, then it is always converted from floating point to fixed point. However, if your number in C# does not fit the decimal numbers in the database, then you get the out of range error.
Comment: But my SQL column type was `Decimal` first, not `decimal (19, 4)`. I suppose it wasn't fixed point then!
Comment: @Yalda `decimal` without parameters is default to `decimal(18,0)`.  https://msdn.microsoft.com/en-us/library/ms187746.aspx
Answer: I had to specify the total digits of my decimal column in the SQL table (I set it as decimal (19, 4)).
Besides, my C# representing field also needed to have the right precision count.
I still don't know about the extra zeros and why SQL care about them. Any explanations is appreciated.

Decimal out of range exception


How can I get the name of a HttpResponseHeader?

Question: I am able to loop through a response.Headers collection and display the value for each header like this.
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(postDest);
//Set up the request with needed properties etc.
HttpWebResponse response = req.GetResponse() as HttpWebResponse;
for(int i= 0; i < response.Headers.Count; i++)
{
      MessageBox.Show(response.Headers[i].ToString());
}

But how can I get the name Field-Name for each ResponseHeader?
Update:
If I do this I am able to get the Field-Name and the Value.
    for (int i = 0; i < response.Headers.Count; i++)
    {
        MessageBox.Show("Field-Name is: " + response.Headers.GetKey(i).ToString() + " Value is: " + response.Headers[i].ToString());
    }

Answer: For completeness, I should point out that you can just call .ToString() on the WebHeaderCollection object itself. (Response.Headers.ToString()). Now I don't really recommend this, since the official MSDN comment on the method says:

This API supports the .NET Framework infrastructure and is not
  intended to be used directly from your code.

However, looking at the code through ILSpy, it's not doing anything wild, just building up a list of name/value lines in a StringBuilder based on the headers. It does exclude any unnamed headers, but I think those are quite rare. And it's interesting that they didn't go to the trouble of slapping an Obsolete compiler attribute on it (maybe to pass their unit tests?)) So it's probably safe to use. But if you are worried about this, I would recommend the solution posted in the question, which uses direct indexing. Note that direct indexing is faster than the method in the accepted answer, since it doesn't rely on a String key or internal Hashtable (not that performance is likely to be a major concern in this area.)
Answer: foreach (HttpWebResponse v in response.Headers)
{
   v.Headers.Keys.ToString();
}

Answer: you can use response.Headers.GetValues(response.Headers.GetKey(i))
Comment: Thanks krakover. You got me headed in the right direction if you want to update your answer to jive with my update I will select it as correct.
Answer: You can just do:
foreach (var key in response.Headers.AllKeys)
{
  Console.WriteLine(response.Headers[key]);
}

Answer: var values = response.Headers.GetValues("Key")

or
 var values = Enumerable.Empty<string>();
 if (response.Headers.TryGetValues("Key", out values))
 {
     // check values
 }


How to add a duplicate library to Eclipse?

Question: One of my projects is a spin-off of another, and they utilize slightly different 'common' libraries.
I want to run them simultaneously, but I can't import the spin-off 'common' library in Maven as the original library is already there.
How to solve this collision?
Answer: Might have to use the Maven Shade plugin.  It effectively lets you use both libraries at the same time, but one (or both) will get a modified package path.  This means you'll have to change the references to one (or both) of them.


Regex - White Space

Question: I have a string coming out as:
 test  styletext

I want to grab just the styletext part which is dynamic and give it some css styles.
Can I use regex to select the whole part after the white space and apply the style? How do I target the part after the white space?
Comment: So you have something like this `` and you want to move that to the ``-tag? Do you have the string in a variable? If so in which language? Like PHP, JSP, ASP?
Comment: I am already getting within span tag - and have some dynamic text after this span end tag which I want to style, want to select this part with regex
Comment: why not style the first span, then override span 'abc' with what you don't want?
Comment: I dont want any styling within span, I just want the styletext to be bold, within my code if I add a class with text bold to style text alone-even the text inside span is becoming bold.
Answer: Try this as a regex:
^/span\s*(.*)

You may need to escape the "\" depending on the language you are using.
The text captured in the group will be the style text.
It "translates" as: starting at the beginning of the string (^) match the text "/span", followed by any number of whitespace characters (\s*), followed by any number of any type of character (.*).  The parenthesis tells it to capture the last part for later use.
Comment: I am doing this in js - so should I do something like this: var test = new RegExp("^/span\s*(.*)"); and test will have the styletext value??
Comment: I don't really know Java, but based on a quick look here: http://docs.oracle.com/javase/6/docs/api/java/util/regex/Pattern.html, it looks like you'd want something like `Pattern p = new Pattern;` and then `var test = p.Matches("^/span\s*(.*)", inputString);`
Comment: I see your pattern has changed in the original question too, so that regex will no longer work.  This should do it: `]*>[^>]*>(.*)`  ("" characters, then ">", then any number of non-">" characters again, then ">", then remember everything after that)

Regex - White Space


Change starting select value in Laravel 5.4

Question: I'm using Laravel 5.4 and i'm trying to make select form with this code:
{{ Form::select('country', App\Countries::all()->pluck('en_title'), old('country', $user->country), array('class' => 'form-control') ) }}

The result that i'm receiving is this:
<select name="country" class="form-control">
     <option value="0">a</option>
     <option value="1">b</option>
     <option value="2">c</option>
     <option value="3">d</option>
     ...
</select>

The problem is that i don't have in the database value 0, so i want to start from value="1" like:
<select name="country" class="form-control">
     <option value="1">a</option>
     <option value="2">b</option>
     <option value="3">c</option>
     <option value="4">d</option>
     ...
</select>

What should i change? I read everything possible, but no one try to do this with the specific function, or this is impossible with this function?
Answer: You can specify the key when you pluck. In your case it'd be
{{ Form::select('country', App\Countries::all()->pluck('en_title', 'id'), old('country', $user->country), array('class' => 'form-control') ) }}

Which would result in an array such as
[1 => 'United Kingdom', 2 => 'United States']

Where the key is the ID of the country.
In addition to the above, you're selecting all then plucking the data you want from the resulting data set. You can use pluck in place of all which builds a select for you and just grabs the relevant fields. For example
App\Countries::pluck('en_title', 'id')

Also, on a side note you should probably create that list of countries in your controller rather than calling your database in your views. It'd simplify the code in your view as well as generally being better practice
// Controller
$countries = \App\Countries::pluck('en_title', 'id');

return view('viewname')->withCountries($countries);

// View

{{ Form::select('country', $countries, old('country', $user->country), ['class' => 'form-control'] ) }}

Comment: i have one more question. How i can use this with another pluck with different database table? For example, i have table with id and country, but i'm pluck-ing the user table where in field country is the id of the country, not the name. How i can pluck them together and show the country name instead of only country id?
Comment: I'm not sure I understand what you're asking. I suggest you ask a new question as you'll be able to better describe what you're trying to do outside of the comments section. I suspect you'll need to create a country relationship on the user model so you use `$user->country->name` but again I'm  not entirely sure that's what you mean.
Comment: Thats correct, and how to use while I'm pluck-ing select form?


normal distribution using Z - finding probability between 2 numbers

Question: I am wanting to find the probability of the following:
SD = 20 Mean = 100
P(85 < X < 117)
i have found the z values for both:
P(X>85) :  X-u/o  = 85-100/20
Z = -0.75  and found the probability for this to be: P(X>85) = 1-P(X<85) = 1-0.2266 = 0.7734
P(X<117) : Z = X-u/o = 117-100/20
Z = 0.85 and the probability = 0.8023
so have the probabilities for both conditions but how do I get P(851 so how would I find this probability?
Answer: To find $P(85<X<117)$ is the same as finding $P(X<117)-P(X<85)$.
Answer: As Joe said,
It is the the probability that X is less than 117 minus the probability that X is less than 85. You can think of it as the area under the curve between these two points.
I hope that helps!


Align embedded Media Images

Question: When I embed an image into CKEditor text I can choose alignment options. When I embed a Media Image I cannot choose alignment, but a Media View. A media View allows me to specify image size (via image style) but not alignment
Embedding an Image does not add the image to the Media Library and it would be nice to only use Media Image embedding so as to manage the site's media library of images.
What is the preferred way of specifying the alignment of embedded Media?
Background
I am switching over to simply using core Media modules in Drupal 8.8. I have ditched what I was previously using:
*  Embed
*  Entity Embed
*  DropzoneJS entity browser widget
*  Entity Browser
*  Entity Browser IEF
Answer: The easiest to resolve (and most likely) issue is:
You are limiting the allowed HTML tags for the text format you're using and you haven't allowed the align (and also caption, if you want captions) attributes for the drupal-entity HTML element. (I'm assuming you do have the Align images and Caption images filters enabled because you said those features were working for non-media embeds. If they're not enabled, enable them.)
Solution:
In the "Limit allowed HTML tags and correct faulty HTML" section (/admin/config/content/formats/manage/MY_FORMAT#edit-filters-filter-html-settings), make sure the drupal-entity has at least the data-align (and data-caption for captions) attributes. E.g. <drupal-entity data-align data-caption data-etc...>.
Comment: Thank you for editing the docs! I moved your paragraph to the middle of the doc where other edits to filter settings are discussed because I missed it initially.

This actually wasn't enough to fix this for me however. Left and right alignment worked, but center did not. Center worked within CKEditor, but not when the page was rendered. In order to get images centered aligned, within the CSS of my theme I had to add `.align-center { text-align: center; }`. I can't explain why this is the case and since this seems to work for everyone else I won't open a bug report.
Comment: Thank you so much for your prompt reply. I am pretty sure you correctly identified the solution to my issue. I'll verify that this is the correct answer tomorrow on my dev site. Thanks to your pointer I found the documentation page that I'd not found before (https://www.drupal.org/docs/8/core/modules/media-library-module/embedding-media-with-ckeditor)
Comment: I then edited the Drupal docs to include the  data-view-mode attribute thus: "Additionally, if you have the "Limit allowed HTML tags and correct faulty HTML" filter enabled, you must ensure that the drupal-media tag also allows the alt, data-align, data-caption, and data-view-mode attributes in order for Alternate text, Align, Caption and Display options, respectively, to be effective in the "Edit media" dialog."

Align embedded Media Images


hook_form_alter multiple Content Type

Question: How I use hook_form_alter with multiple Content Type..
function custom_form_alter(&$form, &$form_state, $form_id) {
  if($form_id == 'register_node_form' || 'session_node_form'){

  if(empty($form['field_event_ref']['und'][0]['nid']['#default_value']))
     {
    $form['field_event_ref']['und'][0]['nid']['#default_value'] = arg(3);
     }
    $form['field_event_ref']['und'][0]['nid']['#disabled'] = True;
     }
  }

I want Here to Get Both Of (Register) and (Session) Content type to be alter..
Answer: The code is incorrect, it should be:
function custom_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'register_node_form' || $form_id == 'session_node_form') {
    // code here that alters forms for both content types
  }
}

The if statement is missing the second $form_id.
Also, I wouldn't name the module custom. If you are doing that as a demonstration purpose, a typical convention is to use mymodule_ in posts.
A more readable way:
function mymodule_form_alter(&$form, &$form_state, $form_id) {
  $content_type_forms = array('register_node_form', 'session_node_form');

  if (in_array($form_id, $content_type_forms)) {
    // code here that alters forms for certain content types
  }
}

Comment: It's Work Great, thanks for your comment.. it help me and improve my skill :)
Answer: You can use hook_form_BASE_FORM_ID_alter
function custom_form_node_form_alter(&$form, &$form_state, $form_id) {
  // Run with all form  content type
}

hook_form_alter multiple Content Type


Windows 10 Run Task On Any Domain User Login and then Delete Task

Question: I have a scenario where I need a non-domain joined Windows 10 to reboot after it gets joined to a domain and there's a logon of a domain user - any domain user, not a specific one. I'd also need this reboot to happen only once after the initial logon on that user.
I've tried to create a scheduled task that runs when any domain user logs in and reboots the device but I can't seem to find a way of setting this domain user part up without the device already being domain joined? Is this even possible?
I'd also like for this to only happen once, so after the reboot (triggered by the logon on a domain user), I don't want the machine to reboot every time someone logs in. To try cover this off, I looked at Task Scheduler's 'Delete Task After' option but that doesn't look like it'd work either since the task will always be scheduled to run (when any domain user logs in).
Does anyone have any experience taking care of something like this? At this point, I'm pretty sure I'm trying to force a square peg into a round hole using Task Scheduler and that using something like PowerShell might be the better option.
Any ideas how I'd go about this?
Thanks in advance
Answer: Does it have to be a scheduled task? Group Policy can be configured for one-and-done type changes, and joining to a domain means that Group Policy will apply.
Taking that a step further, Group Policy can create Scheduled Tasks, too.
Answer: Use a Group Policy with a logon script, and write the script so that it only runs once (f.e. by checking and then setting a Registry key, or a file).


Clear cache tables

Question: I installed a 'test' theme and then uninstalled it. I ran drush cache-rebuild and I also cleared all caches in the Configuration->Performance menu. However when I run drush config-export, to export my configuration from my development environment onto my staging environment, the list of files that get exported still include references to the 'test' theme even though I uninstalled it and cleared my caches.
I looked at my database and in the cachetags table there are rows there that reference the 'test' theme that I uninstalled. I have a feeling these are the ones that get exported during the drush config-export. Is there any way I can clear these?? Because right now I can't carry on with the drush config-import command on my staging environment because I get an error stating that it can't install the 'test' theme because it's not included. And it shouldn't install it because it shouldn't be there.
I've looked around and all documentation points to drush cache-rebuild being used to clear all caches, however in my case it's not doing it.
I'm using Drupal 8 along with Drush 8 all running on Ubuntu.
I was considering doing that but since I'm new to Drupal I was a little concerned that it will cause some other problems if I manually deleted them.
I just removed them and sure enough the config files are gone like they should've been. Everything looks fine so far.
It'd still be nice to know what is the proper way to have a theme removed, uninstalled and completely cleared from the database. And also what caches drush cache-rebuild really clears and what it doesn't.
Comment: I would truncate all cache tables and see what happens.
Comment: You can clear the cachetags table, but it has absolutely nothing to do with config import/export and will not fix whatever problem you have there.
Comment: It does have to do with it and it did fix it. `config-export` creates active configuration files so they can be exported onto another environment. If the current configuration still has reference to a theme that was suppose to be uninstalled, then the files will reflect it ( just like they were doing in my case). So in case anyone runs into this problem, removing the files from the cachetags table did in fact remove them also from the `config-export` files.
Answer: To clear all cache tables run this command in your server terminal.
# Truncate cache tables in MySQL regardless of the active cache backend
echo "SHOW TABLES LIKE 'cache%'" | $(drush sql-connect) | tail -n +2 | xargs -L1 -I% echo "TRUNCATE TABLE %;" | $(drush sql-connect) -v

this will loop through all cache tables and truncate them in one command.
I can't remember the source and where I get this to give credit for the one who wrote it the first time.

Clear cache tables


How to loop through list of objects in Terraform?

Question: I am trying to dynamically fetch list of VMs from azure using external data source and display VM individually.
Below is Powershell script:
<code>$rgroup = [Console]::In.ReadLine()
$json = ConvertFrom-Json $rgroup
$name = $json.rg
$vms=(Get-AzVM -ResourceGroupName $name ).name
foreach ($vm in $vms){
$vmname= $vm |convertTo-json
Write-Output  "{""Name"" : $vmname}"}

Main.tf

variable "resourcegroup" {}
data "external" "test" {
program = ["Powershell.exe", "./vm.ps1"]
query = {
rg = "${var.resourcegroup}"
}}
output "value" {
value = "${data.external.test.result.name}}
</code>
However, I am getting an error:

" command "Powershell.exe"   produced invalid JSON: invalid character
  '{' after top-level value"

Can someone tel me how to loop through list of VMs and display it individually ?
Answer: I have written a terraform module to help with adding ssh keys to gcp metadata. it is not a direct answer to your question but it should help you.
<code>variable "ssh_keys" {
  type = list(object({
    user = string
    key = string
  }))
  default = [
    {
      user = "terraform"
      key = "~/.ssh/google_compute_engine.pub"
    },
    {
      user = "user"
      key = "~/.ssh/id_rsa.pub"
    }
  ]
}
resource "google_compute_project_metadata" "default" {
  metadata = merge(
    {
      ssh-keys = join("\n", [for k,v in var.ssh_keys : "${var.ssh_keys[k].user}:${file("${var.ssh_keys[k].key}")}"])
    }
  )
}
</code>


Python 2 to 3 Error. TypeError: unorderable types: int() <= str()

Question: I have a program that is based on k means algorithm. When I go to run the program on python 2, there are no issues. When I run it on python 3, I get the following errors:
Traceback (most recent call last):
  File "kmeans.py", line 111, in <module>
    main()
  File "kmeans.py", line 13, in main
    clusters = kmeans(points, num_cluster, cutoff)
  File "kmeans.py", line 67, in kmeans
    initial = random.sample(points, k) # generating k random points for initial centroids
  File "/afs/cad/linux/anaconda3/anaconda/pkgs/python-3.5.2-1/lib/python3.5/random.py", line 314, in sample
    if not 0 <= k <= n:
TypeError: unorderable types: int() <= str()

This is the code I have so far, I cant seem to figure out how to fix.
import sys
import math
import random

def main():
    points = readDataFile("datafile.txt")
    print ('Original dataset: \n' + str(points) + '\n')

    # generating clusters
    # num_cluster = 2 # k for default testing value
    num_cluster = input ('Please declare number of clusters k: ') #k
    cutoff = 0.5 # iter cut off
    clusters = kmeans(points, num_cluster, cutoff)

    # Print our clusters
    for i,c in enumerate(clusters):
      print ("Cluster " + str(i) + "\t" + str(c))

# reading in data points from file
def readDataFile(filename):
    points = []
    lines = [line.rstrip('\n') for line in open(filename)]
    for line in lines:
      pieces = line.split(' ')
      points.append(Point([int(pieces[0]), int(pieces[1])]))
    return points

# point class to contain a set of 2d coordinates
class Point:
    def __init__(self, coords):
        self.coords = coords
        self.n = len(coords)

    def __repr__(self):
        return str(self.coords)

# cluster class to define cluster functionality
class Cluster:
    # constructor
    def __init__(self, points):
        self.points = points
        self.n = points[0].n
        self.centroid = self.calculateCentroid()

    # to string method
    def __repr__(self):
        return str(self.points)

    # updates the current loc
    def update(self, points):
        old_centroid = self.centroid
        self.points = points
        self.centroid = self.calculateCentroid()
        shift = getDistance(old_centroid, self.centroid)
        return shift

    # calculates new location of centroid based on mean
    def calculateCentroid(self):
        numPoints = len(self.points) # finding center point
        coords = [p.coords for p in self.points] # list of all coordinates in curr cluster
        unzipped = zip(*coords)
        centroid_coords = [math.fsum(dList)/numPoints for dList in unzipped] # mean for each point
        return Point(centroid_coords)

# kmean algo to cluster data
def kmeans(points, k, cutoff):
    initial = random.sample(points, k) # generating k random points for initial centroids
    clusters = [Cluster([p]) for p in initial] # creating k clusters using generated centroids

    loopCounter = 0 # looping thru data until the clusters stabilize
    while True:
        # list of lists to hold point objects
        lists = [ [] for c in clusters]
        clusterCount = len(clusters)
        loopCounter += 1

        for p in points:
            # dist bw curr to first centroid
            smallest_distance = getDistance(p, clusters[0].centroid)
            clusterIndex = 0

            for i in range(clusterCount - 1):
                # calc point to point diff in distances
                distance = getDistance(p, clusters[i+1].centroid)
                # setting cluster index based on dist
                if distance < smallest_distance:
                    smallest_distance = distance
                    clusterIndex = i+1
            lists[clusterIndex].append(p) # appending point to cluster

        biggest_shift = 0.0 # resetting biggest_shift to zero for curr iteration
        for i in range(clusterCount):
            # calc centroid movement dist
            shift = clusters[i].update(lists[i])
            # keeping track of the largest move from all cluster centroid updates
            biggest_shift = max(biggest_shift, shift)

        # checking if centroids movement is not vast (convergence)
        if biggest_shift < cutoff:
            break
    return clusters

# generates euclidean distance between two points
def getDistance(a, b):
    ret = reduce(lambda x,y: x + pow((a.coords[y]-b.coords[y]), 2),range(a.n),0.0)
    return math.sqrt(ret)

# init
if __name__ == "__main__":
    main()

Also my data.txt file looks like this:
0 0
0 1
1 0
10 10
10 11
11 10
11 11

Any help would greatly be appreciated.
Comment: `input()` returns a string, not an integer.
Answer: num_cluster = input ('Please declare number of clusters k: ') #k
cutoff = 0.5 # iter cut off
clusters = kmeans(points, num_cluster, cutoff)

input returns a string so you need to convert it to an int:
num_cluster = int(input ('Please declare number of clusters k: ')) #k

Comment: Traceback (most recent call last):
  File "kmeans.py", line 111, in
    main()
  File "kmeans.py", line 13, in main
    clusters = kmeans(points, num_cluster, cutoff)
  File "kmeans.py", line 79, in kmeans
    smallest_distance = getDistance(p, clusters[0].centroid)
  File "kmeans.py", line 106, in getDistance
    ret = reduce(lambda x,y: x + pow((a.coords[y]-b.coords[y]), 2),range(a.n),0.0)
NameError: name 'reduce' is not defined
Comment: i got it thanks! Didnt know reduce also got moved to functools


IE8 and below  value work around

Question: I have a slight problem, I am trying to capture the input of two buttons, one yes, one no, into a database but for some reason the database doesn't always show the value of the button clicked, it just shows up blank.
<form  action="refer.php" method="post" id="formID" >

    <input type="image" src="images/yes.jpg"
      alt="submit" value="yes" onclick="this.disabled=true,this.form.submit();"
      />
    <input type="hidden" name="refer" value="yes">

</form>

<form action="thank_you.php" method="post" id="formID" >

    <input type="image" src="images/no.jpg"
      alt="submit" value="no" onclick="this.disabled=true,this.form.submit();"
      />
    <input type="hidden" name="refer" value="no" >

</form>

Here is the code that writes it all to the database
session_start();

$name = $_SESSION['name'];

$tel = $_SESSION['tel'];
$email = $_SESSION['email'];
$refer = $_POST['refer'];
$curDate = date("Y-m-d");

mysql_connect ("host", "user", "pass") or die ('Error: ' . mysql_error());
mysql_select_db ("database");

$query = "INSERT INTO Table (id, name, tel, email, refered, date)
  VALUES('NULL', '".$name."', '".$tel."', '".$email."', '".$refer."', '".$curDate."')";

mysql_query($query) or die (mysql_error());

Apparently anything lower than IE8 will ignore the value attribute of all <input type="image"> form inputs.
How could I get this to work properly in all browsers? jQuery or Javascript maybe?
Comment: Could you show us your code? Something as basic as form fields should work in pretty much all browsers in use today.
Comment: @kielie, the code "this.disabled=true" disables the form button and disabled form fields don't get sent to the server.
Comment: can you elaborate the issue? You might probably show your implementation HTML part.
Comment: Sure, I'll edit the code quickly.
Comment: I don't understand, you're disabling the buttons which would cause them to not be sent to the server AND you don't have a name for the buttons so the server doesn't know what to call them
Comment: @Chris Haas - The idea I think is that the "refer" value gets posted instead.
Comment: @Alohci, sorry, a combination of the title and not enough coffee is confusing me apparently
Comment: @Chris I am not disabling them, they still get written to the database, it just blocks double submits, and I am using the "refer" value instead of the name.
Comment: @kielie FYI: the line where you're building your query could be cleaned up by using variable interpolation, a feature of PHP's double-quote strings.  Instead of ending the string and appending the variable and reopening the string, just embed them right in the string:
`... VALUES('NULL', '$name', '$tel', '$email', '$refer', '$curDate')";`
Answer: The problem is presumably that given a click at co-ordinates (1,2) on:
<input type="image" name="foo" value="bar"/>

IE will pass:
foo.x=1&foo.y=2

where other browsers will pass:
foo=bar&foo.x=1&foo.y=2

So to make image inputs work cross-browser you need to be sniffing for the existence of the name.x parameter and not merely name.
If you need to have two different image buttons, that means they will need to have two separate names instead of relying on different values that might not get parsed:
<input type="image" name="foo.bar"/>
<input type="image" name="foo.bof"/>

And then at the server side check for the existence of parameters foo.bar.x and foo.bof.x.
[edit re: edit]
<input type="image" value="yes"/>

This won't work. Without a name attribute, the image input isn't a successful control, so the value won't be passed, and co-ordinate data may not be passed either.
<input type="hidden" name="refer" value="yes">

Both hidden inputs will be submitted, regardless of which image is clicked. The successfulness of the image input doesn't affect the successfulness of any other hidden element.
$query = "INSERT INTO Table (id, name, tel, email, refered, date) VALUES('NULL', '".$name."', '".$tel."', '".$email."', '".$refer."', '".$curDate."')";

That's some pretty dangerous SQL injection there. You should make friends with mysql_real_escape_string or parameterised queries.
Comment: If its PHP you would look for `$_POST[foo.bar_x]` or maybe `$_POST[foo_bar_x]`. PHP is odd.
Comment: So I would look for something like POST_['foo.bar.x'] ?
Or am I misunderstanding the situation?
Comment: Yes, if an `` is clicked, you'll get a `something.x` parameter with a numeric value in all browsers.
Comment: Thanks David, I had completely forgotten about that. It is indeed a very strange feature. Another victim of the foulness that is register_globals, I suppose. I used names with dots as a signal that I'm hacking the desired value into the name, but yeah, probably best avoid this in PHP and just use eg. `$_POST['actionone_x']` and `$_POST['actiontwo_x']`.
Comment: So if I use $_POST[foo_bar_x]  it should work in all browsers?
Comment: @bobince I'll have a look at the SQl injection, thanx for the heads up!
Answer: Give the inputs different names check for the presence of name.x in the submitted data.
Answer: i noticed that you are disabling your inputs before you submit the form.
you cant do that, if you want to submit the values of those inputs. disabled inputs are not submitted.
what you need to do is copy the value to some hidden inputs first.
Comment: How would I go about doing that?

IE8 and below  value work around


What would "small", "medium," and "large" effect sizes be for mixed effects model in simr?

Question: I'm trying to perform an a-priori power analysis for a mixed effects model using the simr package, but I'm not sure which effect size to choose.
When performing a power analysis for ANOVA I've used Cohen's suggested f values to represent a small, large, and medium effect size (0.1, 0.25, and 0.4). It looks like simr uses slopes as effect sizes, so I'm wondering what would the equivalent small/medium/large effect sizes would be in this case.
My study would have two fixed effects (s and z). S has two factors and z has 3. There would be a random intercept (t) as well.
Thanks for the help!
Comment: Hi @mels! I suggest you think about what "small", "medium", and "large" means in the context of your study. Cohen just made up those values anyway. There's no right answer to this. E.g. in a behaviour change study, maybe a 5% change is large. But in some other context, maybe 50% change is large.
Answer: I have struggled with this same issue, and it is my understanding that it's not possible, or at least it's very difficult to define standardized effect sizes in multilevel models.
See, for instance, this thread and this thread and this discussion and this article:
Rights, J. D., & Sterba, S. K. (2019). Quantifying explained variance in multilevel models: An integrative framework for defining R-squared measures. Psychological Methods, 24(3), 309–338. https://doi.org/10.1037/met0000184
The article focuses on R-squared measures but the reasoning is the same as it is for other effect size measures.

This is indeed problematic when you want to run power/sample size calculations for a mixed model. I have addressed the issue in two ways:

find a previous study (or a couple of studies, if possible) using the same scales as I will be using and use their (unstandardized) effect size as the target effect size in power analysis in simr or

refer to existing simulation studies such as this:

Arend, M. G., & Schäfer, T. (2019). Statistical power in two-level models: A tutorial based on Monte Carlo simulation. Psychological Methods, 24(1), 1–19. https://doi.org/10.1037/met0000195
see also this paper:
Kumle, L., Võ, M.LH. & Draschkow, D. Estimating power in (generalized) linear mixed models: An open introduction and tutorial in R. Behav Res 53, 2528–2543 (2021). https://doi.org/10.3758/s13428-021-01546-0
when determining sample size for my upcoming study and skip my own sample size calculations.

Also, as Alex J said, even with standardized effect sizes, these things are not exact and there are no clear answers. E.g. with multilevel models, even if you had the standardized effect size, you need to decide the size of the random intercept, random slope, their covariance, residual correlation structure - lots of moving parts that can affect the power estimate and for which there are no clear guidelines.

Edited to add: though Westfall et al. (2014) present a way of calculating Cohen's d for a mixed/multilevel model:
Westfall, J., Kenny, D. A., & Judd, C. M. (2014). Statistical power and optimal design in experiments in which samples of participants respond to samples of stimuli. Journal of Experimental Psychology: General, 143(5), 2020
I don't know whether this way is commonly used, I only now found the article.


IP tables modification to allow access to mysql on CENTOS 5 server

Question: CentOS 5.4, with IP tables stopped, I can do it. What's the line I need to add to IPtables so I can keep it on and have remote (domain) access to the mysql databases?
my current table:
# Firewall configuration written by system-config-securitylevel
# Manual customization of this file is not recommended.
*filter
:INPUT ACCEPT [0:0]
:FORWARD ACCEPT [0:0]
:OUTPUT ACCEPT [0:0]
:RH-Firewall-1-INPUT - [0:0]
-A INPUT -j RH-Firewall-1-INPUT
-A FORWARD -j RH-Firewall-1-INPUT
-A RH-Firewall-1-INPUT -i lo -j ACCEPT
-A RH-Firewall-1-INPUT -p icmp --icmp-type any -j ACCEPT
-A RH-Firewall-1-INPUT -p 50 -j ACCEPT
-A RH-Firewall-1-INPUT -p 51 -j ACCEPT
-A RH-Firewall-1-INPUT -p udp --dport 5353 -d 184.108.40.206 -j ACCEPT
-A RH-Firewall-1-INPUT -p udp -m udp --dport 631 -j ACCEPT
-A RH-Firewall-1-INPUT -p tcp -m tcp --dport 631 -j ACCEPT
-A RH-Firewall-1-INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT
-A RH-Firewall-1-INPUT -m state --state NEW -m tcp -p tcp --dport 22 -j ACCEPT
-A RH-Firewall-1-INPUT -m state --state NEW -m tcp -p tcp --dport 80 -j ACCEPT
-A RH-Firewall-1-INPUT -s 10.0.1.1/24 -m state --state NEW -m udp -p udp --dport 137 -j ACCEPT
-A RH-Firewall-1-INPUT -s 10.0.1.1/24 -m state --state NEW -m udp -p udp --dport 138 -j ACCEPT
-A RH-Firewall-1-INPUT -s 10.0.1.1/24 -m state --state NEW -m tcp -p tcp --dport 139 -j ACCEPT
-A RH-Firewall-1-INPUT -s 10.0.1.1/24 -m state --state NEW -m tcp -p tcp --dport 445 -j ACCEPT
-A RH-Firewall-1-INPUT -s 10.0.1.1/24 -m state --state NEW -m udp -p udp --dport 445 -j ACCEPT
-A RH-Firewall-1-INPUT -j REJECT --reject-with icmp-host-prohibited
COMMIT

Answer: Just using "-A" adds the rule to the end of the chain, and as mark suggested, this will put the mysql ACCEPT after the blanket REJECT; no packet will ever get to it.
You can either edit the /etc/sysconfig/iptables file to add the line
-A RH-Firewall-1-INPUT -m state --state NEW -m tcp -p tcp --dport 3306 -j ACCEPT

immediately after the line
-A RH-Firewall-1-INPUT -m state --state NEW -m tcp -p tcp --dport 80 -j ACCEPT

and then restart the iptables service, or you could manually do it with
iptables -I RH-Firewall-1-INPUT 11 -m state --state NEW -m tcp -p tcp --dport 3306 -j ACCEPT

which will put it in the same place, but need to be done after each reboot.
Comment: To avoid having to add the rule after each reboot do `sudo service iptables save`.
Comment: You rock! It worked. I was a bit nervous when you said "but need to be done after each reboot," but I guessed you meant restart. Anyway, it worked after manual edit and service iptables restart. Thanks.
Answer: Try this:
iptables -A INPUT -p tcp --destination-port 3306 -j ACCEPT

Comment: for a specific address ip address: iptables -A INPUT -p tcp --dport 3306 -s IP_ADDRESS -j ACCEPT
Comment: @bindbn: it didn't work. I added my iptables to my original post if it helps. Hmmm, when I enter your command at the prompt and then look at the table, it does not appear to be adding/changing anything???
Comment: The file you have included is /etc/sysconfig/iptables, which configures the firewall at boot (strictly, at iptables service start) time.  It does not change as you add or delete rules from the running firewall.  "iptables -L -n -v" will tell you the state of the current, running firewall.
Answer: Depending on how your firewall is set up currently, you will optionally need the outgoing one and you also may need to fiddle with the order of the rules so that these come before any blanket REJECT or DROP rules you might already have.

# for incoming
iptables -A INPUT -i eth0 -p tcp --dport 3306 -j ACCEPT
# for outgoing
iptables -A OUTPUT -i eth0 -p tcp --sport 3306 -m state --state ESTABLISHED -j ACCEPT
Comment: I edited my original post after seeing your answer. Does that change your response?


SQLite date function doesn't appear in SELECT results

Question: I've just started using SQLite, instead of SQL Server, and it doesn't seem to want to do ORDER BY, MAX() or MIN() on dates.
The Survey_Date column is a text field, so ordering it sorts it from January to December, instead of by the year. If I include date(Survey_Date) in my SELECT statement, it will sort the data by year -- but I can't override the DESC sort, and it doesn't actually display the date.
SELECT Survey_Date FROM Surveys WHERE Loc_ID = 32 ORDER BY Survey_Date;

yields results like:

01/10/2009
01/20/2013
02/05/2010
...

SELECT date(Survey_Date), Survey_Date FROM Surveys WHERE Loc_ID = 32 ORDER BY 1 ASC;

yields results like:

|01/20/2013
|02/05/2010
|01/10/2009
...

It's clearly sorting on the date correctly now, but it doesn't display the formatted date, and doesn't recognize the ASC command.
Can anyone explain what it's doing?
Comment: Are you sure that `date` does not just return `NULL` because it cannot parse your date format? Is it really "clearly sorting correctly"?
Comment: I fixed the issue (for what I need) by adding a Survey_Date LIKE '%2015' to the select and sorting the text Survey_Date field. As long as all the dates were from the same year, the text sort worked fine.
Answer: As already explained at least million times over this site, SQLite does not have date/timestamp type.
So if you want to sort by date, you must store them in format that sorts correctly either numerically, or lexicographically (asciibetically/unicodebetically).
The recommended format is ISO-8601, that is yyyy-mm-dd (yyyy-mm-ddTHH:MM:SS if you want a time too). This is what SQLite has some utility functions to work with, too.
Other possible formats are numeric, either number of seconds since some specific point, e.g. Unix time or number of days, e.g. (Modified) Julian day.

01/10/2009
01/20/2013
02/05/2010

They are strings, so this is correctly sorted.

SELECT date(Survey_Date), Survey_Date FROM Surveys WHERE Loc_ID = 32 ORDER BY 1 ASC;

The date function expects ISO-8601 format. It does not understand what you are giving it and returns NULL. Fully expected.
Sorting by all NULL values effectively does nothing. The rows came out sorted by accident.
Comment: @Thilo, hm, checking documentation, it, at least in the current version, actually should. Updating.
Comment: Or to sum up, garbage in, garbage out!
Comment: Thanks, @Jan Hudec. I was relying on the documentation, which said it would convert text in a recognizable format. Of course, it didn't say what "recognizable" was. ISO-8601. Got it.
Comment: @JenniferDunne, well, "recognizable" depends on the database. SQLite only recognizes ISO-8601 (subset of it; ISO-8601 has variant without separators and with 2-digit year and such and SQLite only accepts the basic variant), and says so in [its official documentation](https://www.sqlite.org/lang_datefunc.html).


Azure blob storage custom domain verification - Azure telling me to create CNAME for non-existent address

Question: I want to assign a custom domain name to my Azure blob storage account.  In the custom domain setup page it says:

You can map a custom subdomain name to your Blob service endpoint. Windows Azure must verify that you are authorized to modify DNS records for the domain. To verify authorization, create a CNAME resource record with your DNS provider that points from [subdomain].yourdomain.com to justanotherxiodec11.blob.core.windows.net or asverify.[subdomain].yourdomain.com to asverify.justanotherxiodec11.blob.core.windows.net.

However, justanotherxiodec11.blob.core.windows.net doesn't resolve at all.  Am I missing something?  (Note: I expected to see *mystorageaccountname*.blob.core.windows.net, not justanotherxiodec11...  I have no idea what justanotherxiodec11 is.)
ps Unrelated - are the IP addresses that are associated with the mystorageaccountname.blob.core.windows.net host names static or dynamic?
Answer: It doesn't need to resolve to anything. Microsoft will check your domain's DNS for that record. If it exists, you've proved you at least have control of the domain's DNS records, and as such have proven enough control of the domain for Microsoft's comfort level.
No one other than Microsoft's "does Howiecamp own example.com?" automated system will ever do anything with that subdomain.
Comment: Wow, totally great point- I am embarrassed I missed that!  But then given that the address they have me point to doesn't resolve, what do I ultimately point my custom domain name to once they verify me?
Comment: @Howiecamp They'll give you a different record for that. This one's only for verification.
Comment: Interesting-I just tried this from old portal and got result I expected: "To verify auth, create CNAME record...that points from [subdomain].yourdomain.com to hcblobstorage.blob.core.windows.net."  `hcblobstorage...` is my actual storage account name and it's resolvable (by defn). I think something was broken w/ the new portal bc in my experience w/ Azure custom domains they've always had me create a cname to a resolvable address, in particular mystorageaccount.blob.core.windows.net.  Regardless I totally agree w/ your point about DNS though-the address doesn't need to be valid to be verified.


2D movement animation for sprites using one sprite sheet with four directions

Question: I'm making a 2D tower defense game for learning purposes, and can't make the enemies(sprites) to face the correct direction when moving.
Heres how the map is built for clarification:
https://i.stack.imgur.com/KjPSS.png
And here is the sprite sheet I'm using to test:
https://i.stack.imgur.com/tdpgk.png
The first sprite at the top left is the frame 0, the next on the right is the frame 1 and so on. As you can see the sprite is already looking to the wrong direction. The map have a start point(the first brown tile on the top) and and end point(the last brown tile in the end), and only the brown tiles are walkable, so with the start point and an end point it will calculate the shortest valid path for the sprites to walk in order to reach the end point.
Said that, every sprite that spawn will have a pre determined path to walk, from that i try to find the direction the sprite is facing by checking the last X or Y position and the X or Y current position, with that i choose which line of the sprite sheet i will use for the walk animation. For example, let's say the sprite is moving south, it should use the sprites at the bottom of the sprite sheet(frames 15 to 19), but it's not working.
This is the animation class I'm using for the enemies:
<code> public class AnimatedSprite : Sprite
    {
        public int Lines { get; set; }
        public int Columns { get; set; }
        protected int currentFrame;
        protected int totalFrames;
        protected int timeSinceLastFrame = 0;
        protected int milisecondsPerFrame = 50;

        public AnimatedSprite(Texture2D texture, int lines, int columns, Vector2 position)
            : base ( texture, position)
        {
            this.texture = texture;
            this.position = position;
            Lines = lines;
            Columns = columns;
            totalFrames = Lines * Columns;
        }

        public override void Update(GameTime gameTime)
        {
            base.Update(gameTime);

           //Here i check if the sprite sheet have more than 1 line because if it have,
           //it must use a different update method.
            if (Lines > 1)
            {
                // Down
                if (lastPostion.Y < position.Y)
                {
                    AnimateDown(gameTime);
                }
                // Up
                if (position.Y < lastPosition.Y)
                {
                    AnimateUp(gameTime);
                }

                // Right
                if (position.X > lastPosition.X)
                {
                    AnimateRight(gameTime);
                }

                // Left
                if (position.X < lastPosition.X)
                {
                    AnimateLeft(gameTime);
                }
            }

            if (Lines == 1) {
            timeSinceLastFrame += gameTime.ElapsedGameTime.Milliseconds;
            if (timeSinceLastFrame > milisecondsPerFrame)
            {
                timeSinceLastFrame -= milisecondsPerFrame;
                currentFrame++;
                if (currentFrame == totalFrames)
                {
                    currentFrame = 0;
                }
            }
        }
           center = new Vector2(position.X + texture.Width / Columns, position.Y + texture.Height / Lines);
        }

        public void AnimateUp(GameTime gameTime)
        {
            timeSinceLastFrame += gameTime.ElapsedGameTime.Milliseconds;
            if (timeSinceLastFrame > milisecondsPerFrame)
            {
                timeSinceLastFrame -= milisecondsPerFrame;
                currentFrame++;
                if (currentFrame > 14)
                    currentFrame = 10;
            }
        }

        public void AnimateDown(GameTime gameTime)
        {
            timeSinceLastFrame += gameTime.ElapsedGameTime.Milliseconds;
            if (timeSinceLastFrame > milisecondsPerFrame)
            {
                timeSinceLastFrame -= milisecondsPerFrame;
                currentFrame++;
                if (currentFrame > 19)
                    currentFrame = 15;
            }
        }

        public void AnimateLeft(GameTime gameTime)
        {
            timeSinceLastFrame += gameTime.ElapsedGameTime.Milliseconds;
                if (timeSinceLastFrame > milisecondsPerFrame)
            {
                timeSinceLastFrame -= milisecondsPerFrame;
                currentFrame++;
                if (currentFrame > 4)
                    currentFrame = 0;
            }
        }

     public void AnimateRight(GameTime gameTime)
        {
            timeSinceLastFrame += gameTime.ElapsedGameTime.Milliseconds;
                if (timeSinceLastFrame > milisecondsPerFrame)
            {
                timeSinceLastFrame -= milisecondsPerFrame;
                currentFrame++;
                if (currentFrame > 9)
                    currentFrame = 5;
            }
        }

        public override void Draw(SpriteBatch spriteBatch)
        {
            int width = texture.Width / Columns;
            int height = texture.Height / Lines;
            int line = (int)((float)currentFrame / (float)Columns);
            int column = currentFrame % Columns;

            Rectangle originRectangle = new Rectangle(width * column, height * line, width, height);
            Rectangle destinationRectangle = new Rectangle((int)position.X, (int)position.Y, width, height);

            spriteBatch.Draw(texture, destinationRectangle, originRectangle, Color.White);
        }
    }
}
</code>
Edit: I made a test in a straight line level(start point at left), it starts facing left (frame 0), but when it reaches the third brown tile, it fixes and face the correct direction:
i.imgur.com/3FsGhuY.png
Edit2: I made a test with straight line levels in all four directions(starting down and going up, start right and going left and vice versa), and in all of them, it starts at frame 0 and when it reaches the third tile it fixes and face the correct direction.
Comment: When/where is `lastPosition` set? If it's done in the base, then you are never actually going to drop into your animate methods because `position` will equal `lastPosition`. What makes me think this is the case is because your screenshots show it is using the first row of frames which I would imagine it would do by default.
Comment: And **what** does not work?
Comment: It walks and change directions, but it looks random, it don't follow the frame order of the sprite sheet also. And i set the last position in the update method of the base class(Sprite).

I made a test level in a straight line:

http://i.imgur.com/3FsGhuY.png

It starts facing left as the frame 0, but when it reaches the third brown tile it fix the position to the right.
Comment: This is wonky... `int line = (int)((float)currentFrame / (float)Columns);` Imagine if you are on frame 9. You would get back `1.8f` and then converted to integer of `2`. Personally, I would turn it in a 2D or jagged array where the first `x` is your animation section and `y` would be your actual frames. So instead of frame 9, it would be something like `frame[line, currentFrame]` where `currentFrame` would be 4 instead.
Comment: @TyCobb The integer truncation yields the correct answer in this case (i.e. the answer is not rounded up from 1.8 to 2) but it's not actually necessary to cast those variables as floats.  Integer division is sufficient.
Comment: @RogerN Maybe I was thinking 0 based. There's still going to be rounding issue though, no? frame 6 / 5 columns would be 1 instead of 2 whereas frame 9 / 5 columns said to be on line 2.
Comment: @TyCobb Rounding is never performed in C# when casting a floating point number to an integer.  You must explicitly call the Math.Round method if you want the number to be rounded.  In this case the fractional part of the number is just ignored.
Comment: @RogerN Ahhh.... I don't think I ever realized that. Good thing I have always relied on Math.Round to be on the safe side. Thanks for that lesson.
Answer: You're not checking whether the current frame is below the minimum value for the desired animation loop; you're only checking it against the maximum value.  Also, there's some repetition in your code that should probably be factored out to make it easier to read and work with.
I would replace all of your AnimateXXXX methods with a single method:
<code>public void AnimateLoop(GameTime gameTime, int loopFirstFrame, int loopLastFrame)
{
    timeSinceLastFrame += gameTime.ElapsedGameTime.Milliseconds;
    if (timeSinceLastFrame > milisecondsPerFrame)
    {
        timeSinceLastFrame -= milisecondsPerFrame;
        currentFrame++;
    }
    if (currentFrame > loopLastFrame || currentFrame < loopFirstFrame)
        currentFrame = loopFirstFrame;
}
</code>
And then call them like this:
<code>// Down
if (lastPostion.Y < position.Y)
    AnimateLoop(gameTime, 15, 19);
// Up
if (position.Y < lastPosition.Y)
    AnimateLoop(gameTime, 10, 14);
// Right
if (lastPosition.X < position.X)
    AnimateLoop(gameTime, 5, 9);
// Left
if (position.X < lastPosition.X)
    AnimateLoop(gameTime, 0, 4);
</code>
Comment: It worked! It looks so simple now, you have no idea how much time i spent trying to solve it by myself. Thanks a lot mister!


Ubuntu: Share/link files uploaded by different sftp users

Question: I have a server that multiple users access via sftp.  They do not have ssh access and they are contained to their home directory by setting the ChrootDirectory /home/%u in the /etc/ssh/sshd_config file.  I want one user to be able to access an entire directory containing files uploaded by another user.  I tried creating a symlink: ln -s /home/user2/files /home/user1/other_files but when user1 logs in, they can see the link but not navigate to it.  If I ssh into the box, I can use the other_files symlink to see the uploaded files, but the sftp users cannot (they get a permisisons error when accessing).
Can I allow these users to share files automatically while still containing them to their home directory?  I know the symlink points to a path outside of their directory, which I believe is causing the permission issue.  I can't manually move the files - the uploads are automatic and occur frequently, so I need user1 to be able to see the files as soon as they're uploaded.  If I recreate the users with the same home directory and adjust the permissions of their respective upload directorys, would that allow user 1 to get the files?  Ideally, user 2 shouldn't have access to any of user 1's files, but if that has to happen, it will still work for me.
Comment: Have you tried a hard link instead of a soft link?
Comment: @ErikA - I need user1 to have access to an entire directory of files, so I can't create a hard link.
Comment: Oh right. Can't hard link to a directory. However, you can use `cp -al` to copy an entire directory tree as hard links.
Comment: @Steven Monai - The `cp -al` works, but only for the files that currently exist. If user 2 uploads another file after the command has been run, it doesn't show in the copied folder for user 1. Is there no way to automatically update the folder as new items are uploaded?
Comment: RedGrittyBrick's answer mentions `inotify`. You could use some technology based on `inotify` (such as, perhaps, `incron`) to monitor changes in specific directories and automate the creation/deletion of hard links between chrooted directories.
Answer: Some random untested ideas:
Have you tried chrooting user2 to a subdirectory of the directory to which user1 is chrooted?
If they don't have SSH logins or use other services, the overlap probably won't cause any problems :-)
Perhaps you can also use the sticky bit to prevent user1 harming user2's chrooting environment?
Finally, if you must continuously duplicate files between two separate chrooted home directories, have a look at inotify. There's also inotify-tools package that looks handy
Comment: +1 for mention of `inotify`.
Comment: I chrooted user2 to a subdirectory of user1 - user2 couldn't access any other files, and user1 had access to everything with the proper permissions. I didn't have to configure inotify.


Stats for Trend data

Question: I have collected data for 3 decades for 5 things. I want to see if there is a change in these five things over the period of three decades. For example if A was 20 out of 80 in decade1, 40 out of 120 in decade 2 and 50 out of 70 in decade 3. now i want to check if the change in A was statistically  significant over the period of 3 decades. do i use chi square, annova or any thing else. i have already made trend analysis diagrams and equations, but dont have a statistical test ! :(
Comment: You might want to clarify: you have five items, with three (count) measurements taken over time? How are these five items related, if at all? (E.g. they are mutually exclusive and collectively exhaustive?)
Comment: @Wayne : these are all types  of news items. for instance , number of political, cultural, etc news . so i have 5 categories of different types of news and and their values for 3 decades
Comment: So the types of news are exclusive, it sounds like. That is no news article is both political and cultural, correct? But the types are not collectively exhaustive: there are other types of news that you don't count. And you have one count for each decade -- three counts total -- for each news type, right?
Comment: @Wayne : yes that's right. types of news are exclusive. And they are collectively exhaustive also because all news items have been put in either of the 5 types depending on the dominant theme. So they are mutually exclusive and collectively exhaustive. and yes i have three counts total for each news type. Now what statistical test do i use to study if there is a significant change in each type of news in three decades?
Answer: I believe you'd use a Pearson's chi-squared contingency table test (of independence) on your 3x5 table. In R the chisq.test does what you want (put the data into a table).
I suspect that the collectively exhaustive part might affect the answer, though. Perhaps now that we know what you have, someone more knowledgeable than I can chime in.
EDIT 3: Upon clarification, it sounds like you want to look at the percentages of Type A over the three decades. This kind of regression is mentioned in another thread. And the bottom line is to do a GLM regression with a pro bit link function.
EDIT 2: I don't know what tests are more powerful than others, but if you did the independence test, above, and you cannot reject independence, that's a sign that there is not a significant trend. If you could reject independence, then the number of articles by type does change significantly through the decades: though that doesn't mean there is a trend to the changes.
Also, you say that you want to look at type A and see if it's trended over the decades. Do you actually want to work with just the count of A, or with the percentage of A type stories? That is, since your types cover all possible news, I'd assume all of the types would increase over time. The question might be, as a percentage of all news, is type A significantly less now than it was 30 years ago.
Last, do you need statistics at all? If you look at stories of type A and see 30, 70, 80, you can say that they have increased over time. Period. You only need statistical tests when uncertainty is involved.
EDIT: What I say above would indicate that the data count types are not independent of the decade. To actually show a trend, you'd use a linear regression. In the case of count data, I believe you'd want to use a generalized linear model (glm in R) with a Poisson link function. Look for the statistical significance (or not) of the slope coefficient.
Though with only 3 data points, a "trend" is going to be hard to prove unless it is very large. (That is, you have low power.)
Comment: thank you. but i cant' run the test of independence because there are no different row and column values. there are just three values i have for each category for 3 different decades. now i want to check if there is a statistically significant difference in these values. i think the chi sq goodness of fit can be used but i am not sure because the total number of news or N in each decade is different.
Comment: @user22089: The rows are your categories and the columns are your decades are they not?
Comment: but decades dont' have values. they are just 1, 2, 3. For e.g if i said out of 100 people , 60  say yes and 40 say no. then i run a chi sq goodness of fit , with 60 and 40 as my observed frequency and 50, 50 as my expected. so i get to find out if thr is significant difference between the responses of yes and no. Test of independence is run if i say how many males and females said yes and no, i.e. association between gender and response. Here in my case i cant' study the association between decade and type of news. i want to see each news separately, did it change in 3 decades?
Comment: No decades don't have values, but neither do your news types. You have a two-dimensional contingency table of counts of news article by type and decade. I was proposing a test of the independence of news type and decade (i.e. has the type of news stayed the same across the decades). You're saying you want to do five tests, one of each type across decades. Sounds to me like you'd have to make some kind of multiple-comparison correction.
Comment: in case i want to do five tests, one of each types across decades, then what is multiple-comparison correction ? :(
Comment: @Wayne -- a good start, but a basic chi-square test of independence wouldn't answer the question of whether there was a trend per se (although with only three time points, plotting or determining trends is pretty limited.)
Comment: @James Stanley : Thank You. If i have more than three time points, say eight, n have made trend analysis plots on a software  called Minitab and have got a trend analysis equation also , that tells me the average increase per unit of time. Now i just want to know if the difference in values at each point of time is statistically significant or not. Isnt' chi sq goodness of fit used to check the same? the only problem is that the total number is different in each decade. like political news 20 out of 80 in decade1, 40 out of 120 in decade 2 and 50 out of 70 in decade 3 and so on.
Comment: @ wayne ( EDIT) I did use linear regression and have a slope coefficient for a trend equation. how do i know the statistical significance thru that ?
Comment: @user22089: That depends on your statistical package, which should indicate a p-value for whether the slope is statistically significantly different from zero. (That is, does the confidence interval of the slope coefficient include zero or not.) But with three data points, I'd be suspicious of any "trend". That's very little data. If you could get data by year, that'd give you 30 data points (per type) which would be a better number with which to calculate a trend.
Comment: @Wayne : Thank you so much. I in fact have a data collected for 8 decades, and thru the systematic collection of sample i have 240 points but i clubbed them into decades and had eight points. Was just trying to understand what stat to use thru the smaller example. Now for instance for a particular type of news,  the trend equation that i got with eight points was Yt = 16.93 + 6.82*t . i have been told to read it as , mean value of news features increased by 6.82 units in time t which stand for a decade. do u think its any good?
Comment: @wayne : and i am using minitab for this part of the study and it dint give a p value ! :(
Comment: @user22089: Edited #2.
Comment: @wayne : Type A was 20 out of 80 in decade1, 40 out of 120 in decade 2 and 50 out of 70 in decade 3. Through percentages i could easily conclude that A increased or decreased over time. But i am not sure if that is going to be enough. so i plotted trend analysis and got trend equations and discussed average increase per decade. I am not sure if this is enough and have been asked to prove any result with a statistical test. Also, i plotted a 3x5 cross tab and attempted the test of independence and got a p value of 0.000. so should i conclude that decades and types of news are associated ?
Comment: @Wayne : I used GLM in spss, put the type of news in dependent and decades in independent .Got a  table of output where Unstandarized Coefficients : B (constant) is 16.929 and Decade 6.821.  i got a plot for same data as in another software with trend equation as   Yt = 16.93+ 6.82*t. I see a similarity in both results. But  when i put decade as independent variable i coded it as 1,2,3,4,5,6,7,8 for eight decades , like 1 =1931-39, 2=1941-49 and so on,  now what if the software assumes them as real numbers while getting the output rather than seeing them as decades.

Stats for Trend data


How to find/download latest drupal version via bash?

Question: I'm trying to pull up the latest Drupal release, and download it via a bash script.
I don't have any idea on how I can do that, except that I found out I can list the files on the FTP server, and get all the filenames containing Drupal, like so:
lynx --dump http://ftp.drupal.org/files/projects/ | awk '/http/{print $2}' | grep drupal-7 > latest.txt

How I can pull the latest version from that list, and download it?
Comment: Some HTTP and FTP clients can download the newest file matching a wildcard if you point them to a directory. IIRC Curl has this functionality.
Comment: You could use `sort` with version sort option i.e. `sort -V`. Assuming you don't want dev, alpha or beta (untested): `lynx --dump http://ftp.drupal.org/files/projects/ | awk '/http/{print $2}' | grep drupal-7 |sort -V |grep -v dev|grep -v alpha|grep -v beta|tail -n 1`
Answer: For all your command line and script needs there is Drush. To download the latest Drupal 7 with it, you simply do
drush pm-download drupal

Answer: This command will do it.
wget  http://ftp.drupal.org/files/projects/$(wget -O- http://drupal.org/project/drupal | egrep -o 'drupal-[0-9\.]+.tar.gz' | sort -V  | tail -1)

Here goes the explanation.
wget -O- http://drupal.org/project/drupal |  # <- Download drupal main download site
    egrep -o 'drupal-[0-9\.]+.tar.gz' | # <- searching drupal-[0-9\.]+.tar.gz pattern
                                        # Also only showing the matched pattern
    sort -V  |  # <- sort it by version number (default sort order is ascending)
    tail -1  | grab the last name which would be highest version

After this we get something like drupal-7.12.tar.gz or drupal-7.12.zip. Then it gets replaced in the final wget invocation.
wget  http://ftp.drupal.org/files/projects/drupal-7.12.tar.gz

Comment: That will fail in many cases unless you are using a version of sort that supports --version-sort (and use that option).
Comment: Yeah. I was experimenting on console. Updated already.
Comment: Actually this one worked, but unfortunately I cant seem to understand the sorting thing with egrep, seems a bit tricky for me. Thanks indeed.
Comment: @AltinUkshini answer is updated with explanation. Check again.
Comment: Aha now I get it. I was confused at 0-9\. now I see that it means from 0 to 9 :) . Thank ou so much again :D
Answer: If GNU grep is available and GET from perl's libwww, you can use the following, but it will fail if the format of their project page ever changes:
wget $(GET http://drupal.org/project/drupal | grep -Po '(?<=tar.gz)')

Comment: Im getting an error at this one:
Comment: grep: Support for the -P option is not compiled into this --disable-perl-regexp binary
wget: missing URL
Usage: wget [OPTION]... [URL]...
Comment: @AltinUkshini What version of Linux are you using that doesn't have -P support for grep?
Answer: The currently accepted answer no longer works after the update to the Drupal website.
This method utilizes the update XML and should hopefully be more reliable.
As stated in other answers, the best option is to use drush, but if that is not an option then this should do:
wget $(wget -O- -q https://updates.drupal.org/release-history/drupal/7.x | grep -oPm1 "(?<=<download_link>)[^<]+" | head -1)

Credit to this stackoverflow answer for the XML extraction: https://stackoverflow.com/a/17333829/2383249
Comment: It downloads all the version. I only want the latest one, how do I do that.
Comment: I just updated the code so that there is a | head -1 after the grep statement so it only retrieves the latest one.
Answer: I know @Shiplu's answer works best for OP, but just to add a comment; sometimes you may find it convenient to ask Apache which is the newest file:
$ wget 'http://ftp.drupal.org/files/projects/?C=M;O=A' -O- | egrep -o 'drupal-[0-9\.]+\.zip' | tail -1
(snip)
drupal-7.12.zip

The above URL was copied from the link labelled as "Last Modified".  See also

http://httpd.apache.org/docs/2.4/en/mod/mod_autoindex.html#query
Comment: Last modified could be a 6.0 or dev version.
Answer: If you can install (and don't mind installing) the nokogiri cli (e.g. sudo apt-get install ruby-nokogiri on ubuntu), you could do the following
nokogiri https://updates.drupal.org/release-history/drupal/7.x -e 'print @doc.at_xpath("//download_link/text()")'

which outputs
https://www.drupal.org/project/drupal/releases/7.50


Sum of $1/[(n + 1)^2] + 1/[(n + 2)^2] + ... + 1/[(2n)^2]$ when n goes to infinity

Question: Could someone please help me understand the steps to solve this problem?
Comment: Wait... so you are interested specifically in $\lim\limits_{n\to\infty}\left(\sum\limits_{k=n+1}^{2n}\frac{1}{k^2}\right)$?  Well... the sum $\sum\limits_{k=1}^\infty \frac{1}{k^2}$ converges... so...
Answer: Hint
$$\frac{1}{(2n)^2}+ \frac{1}{(2n)^2} + … + \frac{1}{(2n)^2} \leq \frac{1}{(n+1)^2} + \frac{1}{(n+2)^2} + … + \frac{1}{(2n)^2} \leq\frac{1}{n^2} + \frac{1}{n^2}+ … + \frac{1}{n^2}$$
Answer: Hint:
$\frac{n}{(2n)^2} \lt s_n \lt \frac{n}{(n+1)^2}$.
Answer: For finite $n$ the sum is $\psi ^{(1)}(n+1)-\psi ^{(1)}(2 n+1)$, where $\psi$ is the polygamma function.  Take the limit:
$$\lim\limits_{n \to \infty} \left( \psi ^{(1)}(n+1)-\psi ^{(1)}(2 n+1) \right) = 0.$$
Comment: I don't think there is any reason to pull out the polygamma function here.  To a beginner student, unnecessary information and notation can do more harm than good and just confuse them.
Comment: The OP has a reputation of 1 and is clearly a beginner. Do you really think your answer has a bat in hell's chance of helping him or her?


Find all complex numbers that satisfies this equation

Question: Find all complex numbers that satisfies this equation
$(z - 6 + i)^3 = -27.$
I found one of them being $ z = 3 - i $
Comment: We usually write $i$ lower case.
Comment: There are three cube roots of $-27$ so there have to be three solutions to this equation.  Do you know how to find the three cube roots?
Comment: Hint: If $\zeta=\frac{1}{2}+\frac{\sqrt{3}}{2}i$, then $\zeta^3=-1$ and $(\zeta^2)^3=-1$.
Comment: Note that $\zeta^2=-\frac{1}{2}+\frac{\sqrt{3}}{2}i$
Comment: If you know how to do that (using long division), you can now factor the polynomial and get a quadratic equation that you should be able to solve.
Comment: @GregoryGrant i just changed it.
Comment: @GregoryGrant not really
Comment: $-27 =\left(3e^{-i\pi/3}\right)^3 =\left(3e^{i\pi/3}\right)^3 =\left(3e^{i\pi}\right)^3$
Answer: Let $z-6+i=\omega$, then your equation change to find the solution of equation $\omega^3=-27$. this equation have the solution's $z_k=3(cos(\frac{\pi+2k\pi}{3})+isin(\frac{\pi+2k\pi}{3}))$ which $k=0,1,2$. Finally: $z=6-i+z_k$, are all solution's.
Answer: Hint:
Set $z-6+i=3u$ and find all complex numbers $u$ that satisfy $u^3=-1$.
Answer: $-27=27e^{{\pi}i+2k\pi}$
$\sqrt[3]{27e^{{\pi}i+2k\pi}}=3e^{\frac{1}{3}\pi i+\frac{2}{3}k\pi}=z-6+i$
$z=3e^{\frac{1}{3}\pi i+\frac{2}{3}k\pi}+6-i, \forall k\in \mathbb{Z}$


Why can't I get the LESS CSS framework working here?

Question: http://jsfiddle.net/xfCE8/3/
I've been trying to get less CSS to work, but with no luck, which is pretty embarrassing seeing as how nobody else has this problem.
Answer: I don't think you can link to the .less file directly from the googlecode site. If I run your jsfiddle with Firebug open I see an error. If I look at the HTTP request made to load the .less file I see the following:
Response Headers
Content-Length  28464
Content-Type    text/x-c; charset=us-ascii
Content-Disposition attachment; filename="style.less"
Accept-Ranges   bytes
Date    Mon, 13 Dec 2010 09:11:05 GMT
Last-Modified   Mon, 13 Dec 2010 09:01:31 GMT
Expires Mon, 20 Dec 2010 09:11:05 GMT
Server  DFE/largefile
Cache-Control   public, max-age=604800
Age 452

The Content-Disposition triggers the browser to prompt to save the file if you visit the URL directly. I think it is also confusing the code which attempts to download the .less file.
Try downloading the file and placing it on a different server which doesn't have any special handling for the .less mimetype...
Comment: You see here that the content-type is "text/x-c", which indicates that jsfiddle ignores the reference in the HTML text box, but uses the reference from "Manage Resources" on the left side. The "Manage Resources" has no option to tell whether the link is js or css, so jsfiddle does not parse it correctly when the extension is `.less` and not `.css`.
Comment: It has nothing to do with jsfiddle. As I show above, the **response** headers from the googlecode site are such that a browser will try to download the file. If you visit http://lesscsss.googlecode.com/files/style.less in your browser you will be prompted to download the file. I suspect these headers are causing the "[Exception... "Component returned failure code: 0x80004005 (NS_ERROR_FAILURE) [nsIXMLHttpRequest.send]"]" in your example. Try hosting the file yourself and see if it helps...
Answer: It might be that the "Manage Resources" loader does not understand what content it should be when the extension on the css is ".less" and not ".css".
I think jsfiddle ignores the references you have in the HTML section: all external references must be added on the left side in either the list of known frameworks, or as a link in the "Manage Resources" section. I would guess this is for security reasons...
Answer: First, in chrome, the js and css makes error and can't be loaded.
So you must host them yourself on your server and I advise you to rename the .less to .css if you don't have access to your apache ini or if you don't know .htaccess.
Second thing, I can't find @brand-color but @brand_color which is different ;) The whole css seems to be different anyway here.
Finally, this css framework doesn't seem to be nice to start with (a lot of test comments, etc... doesn't seem finished to me and I'd use it with caution.)
Answer: Don't know this framework, but I can see that you have an s too much here:
<link rel="stylesheet/less" href="http://lesscsss.googlecode.com/files/style.less" type="text/css" />

it should be
<link rel="stylesheet/less" href="http://lesscss.googlecode.com/files/style.less" type="text/css" />

EDIT: Sorry, was wrong. The two links in your code are diffirent, but they should be. The first one links to lesscss, the second one to lesscsss, and both are right. I am sorry.