How to open a linux directory from browser using php?

Question: i am new to php, and i would like to know how to open a directory using php.
i've tried the following codes, but nothing happened
<code> exec('nautilus /home/');
 exec('sudo nautilus /home/');
 $command='nautilus /home/';
 system($command);
</code>
i am using Centos 6.4
Answer: Try with opendir() php function.
Comment: i need to pop out a window (just like windows explorer) with the contents of directory.
Answer: Try pcmanfm /home it will open a Directory in Linux. or Explorer in Windows


list the top 5 users by time spent watching videos

Question: Table1:
***Publisher*** with following columns:
o    **Publisher_id** ; unique ID for each publisher
o    **Video_id** ; unique ID for each video
o    **Video_duration**; in  minutes for each video

Table2:
***Consumer*** with the following columns:
o    **Video_id** ; unique ID for each video
o    **User_id** ; unique ID for each customer
o    **Dateid** ; the date on which the consumer watched a video

Example:
Publisher_id    Video_id    Video_duration
1   1   2
1   2   3
1   3   2
1   4   5
2   6   2
2   7   2
2   8   20
3   10  2
3   11  3
3   12  3
1   23  100
5   9   8

Video_id    User_id Date_id
1           44      20210615
2           44      20210615
11          33      20210614
6           44      20210612

I think I mostly need to figure out how to sum up the time spent watching videos per user_id and then to corroborate that using a limit 5 select, but I can't figure how to combine these 2 selects
Comment: Please show what you have tried.  Sample data and desired results are also helpful, as is an appropriate database tag.
Comment: I've tried something along these lines (doesn't work, as  sum() is not used correctly) select user_id from consumption_info as c
join publisher_info as p
on c.video_id = p.video_id
order by sum(video_duration);
Answer: I'd try like this:
SELECT SUM(Video_duration)
FROM       Consumer
INNER JOIN Publisher USING (Video_id)
GROUP BY User_id
ORDER BY SUM(Video_duration) DESC
LIMIT 5


is there a way to map the row and column numbers to corresponding numbers in python

Question: Hey so I am trying to map out the first Row and first column with numbers but finding some difficulty here what ever got so far
<code>output = " "
column_count = 0
row_count = 1
for row in range(10):
output = " "
 for column in range(20):
    if (row == 0):
        while column_count <= 20:
            print(column_count, end = " ")
            column_count += 1
    elif (column == 0):
        while row_count <= 10:
            print(row_count)
            row_count += 1
    else:
        output += "x"

print(output)

</code>
this my output
so something like this but mapped out perfectly
Comment: you want to put `X ` inside that rows and column ??
Comment: What kind of output are you expecting?
Answer: From my understanding of your question, you're essentially looking for a grid like you would find for multiplication tables except with 'X' instead of products.
Below is an adaptation of this answer to the question How to print a 10*10 times table as a grid?.
<code># Set Number of Rows and Columns
cols = 21
rows = 11

# Determine width of each column based on largest column
space_fmt = f'{{:>{len(str(cols)) + 1}}}'

# Print Header Row
print(''.join(space_fmt.format(i) for i in range(0, cols)))
# Print Remaining Rows
for y in range(1, rows):
    # Print First Number
    print(space_fmt.format(y), end='')
    # Print Xes
    print(''.join([space_fmt.format('X') for _ in range(1, cols)]))
</code>

An answer with just for loops, no join on list comprehensions
<code># Set Number of Rows and Columns
cols = 21
rows = 11

# Determine width of each column based on largest column
space_fmt = f'{{:>{len(str(cols)) + 1}}}'

# Print Header Row
for i in range(0, cols):
    print(space_fmt.format(i), end='')
print()  # New Line
# Print Remaining Rows
for y in range(1, rows):
    # Print First Number
    print(space_fmt.format(y), end='')
    # Print Xes
    for col in range(1, cols):
        print(space_fmt.format('X'), end='')
    print()  # New Line
</code>


Converting GPS coordinates to X, Y, Z coordinates

Question: So here is the basic problem. I am currently working on a GPS system in C# in Unity 3D (the person that has given us the assignment is making us use this program, so I can't do it in anything else).
Now I've run in to a small problem, basically we are able to request (what we think are decimal) coordinates from an android phone, but now we are trying to convert those coordinates to X, Y, Z coordinates. Preferebly X and Z, because we do not actually need height. However everything we have been finding on the internet so far has been for a conversion to a sphere map where as we just have a basic flat digital map.
If anyone knows how to convert the coordinates we have to the basic X and Z coordinates (so our longitude and latitude) it'd be amazing.
To quickly note I am not sure if the sort of coordinates we have are actual decimal coordinates so this is what they look like:
Latitude: 53.228888 Longitude: 6.5403559
these coordinates should end up on "Wegalaan 3, Groningen, The Netherlands" if you would look them up on a map.
Thanks already!
EDIT: (this is also in the comments)
Sorry if it might be confusing. Honestly I only half understand how all this works, anyways to clear some things up. I am currently working in Unity with a simple 2D map I got from the internet of the city I live in (Groningen, The Netherlands) and I am trying to basically take GPS coordinates I get from my android phone and then show them on that map with a red dot, however to do this I need to be able to move the red dot to the right coordinates on the map. What I am trying to do is convert the GPS coords (lon and lat) to X and Z (Unity3D flat coordinates, may also just be X and Y) so that if I align the map right I get a small GPS system for just my city. If you are curious as to why I am doing this it is simply because a friend of mine and me are trying to build a game using our city and this GPS system as a basis
EDIT2:
except that I'll be honest I have no idea how cartesian coordinates work, but they seem to be what I am looking for yes :P Coordinates on a flat plane and with X,Y coords I mean basically just coordinates I could use in Unity3D on a flat 2D plane which is what I am working in.
EDIT3:
Thanks for the answers, to start. This is not a duplicate, secondly my friend and I already found the stackoverflow topic you sent me, but it seems to not be working for us (maybe we did something wrong). Basically the north and south distance between different places we tested with that formula have worked, however the east west distance between them was way bigger than it should have been. We think it might be because that formula was meant for a spherical earth, but maybe we did something wrong. If someone could explain further that'd be amazing!
EDIT4:
We are sure it can't be our map that is wrong in any way, because we have aligned it with multiple locations. We got the coordinates for these locations and then used this website: http://www.gpscoordinaten.nl/converteer-rd-coordinaten.php to convert it to XY coordinates and then used these XY coordinates to check if our map would align properly. It did, so we are sure there is some problem with the maths we are using and not with our actual map.
EDIT5: Removed many, many grammatical errors. It's way too hot over here to be writing properly right now, so I am very very sorry if any of this makes no sense. just let me know and I'll edit to try and explain what we are trying to do.
EDIT6: Found my own asnwer, it is down in between all the other answers if you wanna see what I did to fix my problem
Comment: possible duplicate of [Converting from longitude\latitude to Cartesian coordinates](http://stackoverflow.com/questions/1185408/converting-from-longitude-latitude-to-cartesian-coordinates)
Comment: I'm not quite sure what you mean by this, but latitude is the horizontal lines and longitude is the vertical ones.  Because of the curve of the Earth, the distance between two lines of longitude goes down as the latitude becomes higher, so if you wanted to think of it as a rectangular grid it doesn't really work.  Usually in geographic software you'll convert from a geographic coordinate system to a projected coordinate system for display.
Comment: Haven´t you already postedt that question earlier today? However: What do you mean with X,Y-coords? Should it be cartesian coordinates? If so which unit do you need? There are many many params which affect such a transformation.
Comment: See here http://stackoverflow.com/a/1185413/363437
Comment: @maniak1982 Sorry if it might be confusing. Honestly I only half understand how all this works, anyways to clear some things up. I am currently working in Unity with a simple 2D map I got from the internet of the city I live in (Groningen, The Netherlands) and I am trying basically take GPS coordinates I get from my android phone and show them on that map with a red dot, however to do this I need to be able to move the red dot to the right coordinates on the map. What I am trying to do is convert the GPS coords (lon and lat) to X and Z so... (continues in my next comment)
Comment: that if I align the map right I got a small GPS system for just my city. If you are curious as to why I am doing this it is simply because a friend of mine and me are trying to build a game using our city and this GPS system as a basis
Comment: Please add this information as edit to your question instead of commenting. Thus it´s way easier to find.
Comment: @HimBromBeere Yeah I did post it earlier as well, but some mean people told me I was an idiot for even asking it and downvoted it. I reported the people and deleted that post to get rid of the hate, then reposted the question in the hope of a serious answer. Please see my answer to maniak to kinda understand what I mean... except that I'll be honest I have no idea how cartesian coordinates work, but they seem to be what I am looking for yes :P Coordinates on a flat plane and with X,Z coords I mean basically just coordinates I could use in Unity3D which is what I am working in.
Comment: @vidstige Thanks for the answer, to start. This is not a duplicate, secondly  my friend and I already found the stackoverflow topic you sent me, but it seems to not be working for us (maybe we did something wrong). Basically the north and south distance between different places we tested with that formula have worked, however the east west distance between them was way bigger than it should have been. We think it might be because that formula was meant for a spherical earth, but maybe we did something wrong. If someone could explain further that'd be amazing!
Comment: You should try to find the projection of the map.  What you're going to need to do is project the latitude and longitude (geographic coordinate system) onto the map, and you won't be able to do that implicitly.  You could try getting the coordinates of the corners of the map, then calculating the coordinates of the GPS position in relation to those points.  It won't be accurate but it will be quick and dirty.
Answer: By now I have found the answer to my own question (actually found it a little while ago already, but totally forgot to post it here)
Basically I made a little formula of my own that multiplied the coordinates with a set number (depending on wether or not it is the x or y axis) that is the difference between two set coordinate points. These two points are the outer points of my map.
Basically by doing this I can get quite accurate measurements I haven't even had a meter difference to my actual position yet.
I know this sounds a bit vague and I don't entirely know how to explain it, but for anyone interested here is the code I use:
<code>void RetrieveGPSData()
{
    currentGPSPosition = Input.location.lastData;
    System.DateTime dateTime = new System.DateTime(1970, 1, 1, 0, 0, 0, 0);
    dateTime = dateTime.AddSeconds(currentGPSPosition.timestamp);

    float z = latToZ (Input.location.lastData.latitude);
    float x = lonToX (Input.location.lastData.longitude);

    this.transform.position = new Vector3 (x, 0f, z);

    gpsString = ("Last Location: " + Input.location.lastData.latitude.ToString () + " " + Input.location.lastData.longitude.ToString () + " " + Input.location.lastData.altitude.ToString () + " " + Input.location.lastData.horizontalAccuracy.ToString () + " " + dateTime.ToShortDateString() +" "+ dateTime.ToShortTimeString());
}

float latToZ (double lat){

    lat = (lat - 53.178469) / 0.00001 * 0.12179047095976932582726898256213;
    double z = lat;

    return (float)z;
}

float lonToX (double lon){

    lon = (lon - 6.503091) / 0.000001 * 0.00728553580298947812081345114627;
    double x = lon;

    return (float)x;
}
</code>
Now for anyone wondering why I took the 53.something and the 6.something off the lon and lat it is because the coordinate of my 0 X and 0 Z point in Unity which corresponds to the bottom left corner of my map, which is one of the two points I talked about that I use for this calculation.
I hope this helps anyone else who might ever be stuck on something similar and if you have any questions feel free to ask them.
-LAKster
Comment: Thanks for your reply, LAKster. :)
My (0,0,0) is right at the center of the earth sphere in my Unity project.
The north pole is at (0, RADIUS_SPHERE, 0). Should I keep those 53. and 6. or what?
Comment: Hey, I'm sorry I am replying now instead of when you posted the question. Honestly I am not sure. By what it looks like you are using an actual sphere instead of a flat map like I am. If you are just using a flat map this is what those numbers mean. The 53. and 6. are the gps coordinates of the real world place on my map that I have at the 0 X and 0 Z point in Unity. Hope this helps :D
Comment: @LAKster I'm using a flat map, how should I know what are the number to use instead of 53.something and 6.something. Since I tried the code you've written in your answer but it gave me a big x and z
Answer: Does the map have mercator projection? Is it a world map?
If so, the top of the map is usually around latitude 85, latitude 0 at the center vertically.
longitude 0 is at greenwich (usually center horizontally), 180/-180 is at the antimeridian/date line, at the left and right edges of the map.
When the latitude is -180, x would be 0, when it's 180, x == width of map.
This link should tell you what you need
Comment: On Mercator-projections latitude +/-90 is not printable as they are inifintely far away
Comment: I'll be honest here. I started working on this last week and only learned half of what I know today. I did stumle on mercator projections, but I have no idea how they work or how exactly they should influence what I am doing. I more or less get that they are just literal flat maps of places, and as far as I know the map I am using is exactly that. We did test the map as well to make sure it would work with coords. I am just having trouble determening the maths to do the conversion to X and Y coords myself
Comment: @HimBrommBeere You are correct. I'll update the answer accordingly.
Comment: Thanks for the link. I'll look at it tomorrow, because currently I am home and just do not feel like working XD Thanks for the answer and I think I might have an idea already, but I'll have to look in to the link you put here to see if I can actually use that idea.


solving this equation using prime numbers

Question: Solve in $\mathbb{Z}$ the following equation:
$3^x$+$3^y$=$738$,
using prime numbers concept and decomposition in prime factors...
I noticed that the above equation is symmetrical to $x$ and $y$, so we can assume $x$ $\leq$ $y$ ... but I can not find a way to solve it. Also, clearly: $738$=$3^2$$*$$2$$*$$41$.
Thanks for your time.
Answer: Note that $3^x+3^y=3^x\cdot(1+3^{y-x})$, so we need $3^x=3^2$and $3^{y-x}=2\cdot 41-1$. (You will note that the complete factorization of $738$ was not needed, only the number of $3$'s).
Answer: Nice answer from Hagen von Eitzen, here is a different method: in base $3$ we have
$$738=[1000100]_3\ ,$$
so the powers are $3^6$ and $3^2$.
Admittedly this does not really use prime factorisation so perhaps it is not actually an answer to the question as posed.
Comment: Great suggestion, David! Even I was looking for a prime factorisation concept, I noted this suggestion.
Comment: Actually, to *obtain* the base 3 representation, you would do exactly that: Divide off factors $3$ as long as you can ...


Drupal multisite: Same theme, different colors

Question: I am looking for an answer to a quite specific theming question:
I have a Drupal multi-site installation. (Well, not yet actually, but I want clarity on my question first before I procees. Just asume that I have one.)
I have a team, called 'Theme', which has various files in the directory /sites/all/themes/Theme. In this folder, there are the .tpl.php files and a few folders like css/ and scripts/.
Then, I have 2 sites, which use the same theme: Theme. These sites are located in /sites/default and /sites/alternative.
What I want to do now is providing a file, colors.css in each sites directory (so /sites/default/colors.css and /sites/alternative/colors.css with something like:
@base: blue;
@light: lightblue;
@dark: darkblue;

This file should be read and these 'variables' should replace the variables in the css files located in /sites/all/themes/Theme/css so that I simply can define the colors in each site, without having to modify or to overwrite bits of the css files located in /sites/all/themes/Theme/css.
I already tried a few things, one which could work but I didn't like enough, so I am looking for a general, good and most important, fast method.
What I already have achieved and what (I think) is very usefull:
function theme_css_alter(&$css) {
    $css['sites/all/themes/Theme/css/colors.css']['data'] = conf_path() . '/colors.css';
}

This function changes the default colors.css provided in /sites/all/themes/Theme/css/colors.css and replaces it with /sites/default/colors.css OR /sites/alternative/colors.css, depending on where you are.
I have already tried the following:

Used PHP to get the correct colors.css file and use PHP-variables all over my CSS-files. This should actually work. But I don't quite like it because you end up with a lot of .php files which are actually .css and a lot of ugly php-syntax in the css files.
I tried the lessphp drupal plugin. This did it's work for replacing the variables but the caveat was this: If I want to include the correct colors.css file, I need to use php. Therefore, my less file needs to have the extension PHP. LESS is build so that you can only 'parse' files with the less extension, so this wouldn't work. I quite liked this though, it used some nice caching which would also be the quickest way. What I could do here is dive into the lessphp library and change the code that says 'only .less files please!' to also accept .less.php files.

So, my questions are:

Does anybody see a different approach that would also work and is fast?
If yes: please elaborate
If no: Which of my previous methods do you fancy and why? What would be the best approach?
Answer: Well, I found out something that is quite useful:
Instead of trying to import the color.less file in each 'basic' theme css file, I do it the other way around: I import all the basic theme css files in colors.less, like this:
@basis: blue;
@donker: black;
@licht: pink;

@import "../all/themes/Theme/css/basic.less";

Then I had to remove all the stylesheet definitions in the .info file and changed the template function to:
$css = drupal_add_css(conf_path() . '/colors.less', array('group' => CSS_THEME, 'weight' => 115, 'browsers' => array('IE' => 1, '!IE' => 1), 'preprocess' => FALSE));

No hassle with php, and it works, is cached when I want it, and fast!


Keep only the last revision of content with multi-version module

Question: We are using Drupal 8 with the multi-version module version 1.0.0-alpha12.
As part of our dev/test workflow, we SQL dump the production database and move it into dev and test environments. Recently this process has been becoming increasingly slow and after some investigation into the composition of the database, I notice we have ~8G of data in the node_revision__body table.
I would therefore like to prune content in the database to keep only the most recent revision when we are working in our dev and test environments.
How can I achieve this with Drupal 8 and the multi-version module? I have come across the Node Revision Delete module, but that has a version for Drupal 7.
Answer: Actually, now (March 30 2018) it has a 8.x version. So this is your module:
Node Revision Delete

The Node Revision Delete module lets you to track and prune old
  revisions of content types.
Features:

Define the max amount of revisions to keep per content type.
Run on Drush, cron run or on a different period (daily, weekly, etc).
Answer: The node revision limit module if you happen to have multilingual sites.
The node revision delete do not work properly with Content Translation.
https://www.drupal.org/project/node_revision_limit


How to use hook_form_search_block_form_alter?

Question: I was referring this page in the process of learning hooks How to Customize the Block Search Form and found following code.
/**
* hook_form_FORM_ID_alter
*/
function YOURTHEME_form_search_block_form_alter(&$form, &$form_state, $form_id) {
    $form['search_block_form']['#title'] = t('Search'); // Change the text on the label element
    $form['search_block_form']['#title_display'] = 'invisible'; // Toggle label visibilty
    $form['search_block_form']['#size'] = 40;  // define size of the textfield
    $form['search_block_form']['#default_value'] = t('Search'); // Set a default value for the textfield
    $form['actions']['submit']['#value'] = t('GO!'); // Change the text on the submit button
    $form['actions']['submit'] = array('#type' => 'image_button', '#src' => base_path() . path_to_theme() . '/images/search-button.png');

    // Add extra attributes to the text box
    $form['search_block_form']['#attributes']['onblur'] = "if (this.value == '') {this.value = 'Search';}";
    $form['search_block_form']['#attributes']['onfocus'] = "if (this.value == 'Search') {this.value = '';}";
    // Prevent user from searching the default text
    $form['#attributes']['onsubmit'] = "if(this.search_block_form.value=='Search'){ alert('Please enter a search'); return false; }";

    // Alternative (HTML5) placeholder attribute instead of using the javascript
    $form['search_block_form']['#attributes']['placeholder'] = t('Search');
}

This code is very helpful and precise to point. For example, if we want to change the placeholder, we need to put following code inside the template.php file and it works.
function YOURTHEME_form_search_block_form_alter(&$form, &$form_state, $form_id) {
    $form['search_block_form']['#attributes']['placeholder'] = t('Search');
}

Now,

From the literature on api.drupal.org, I can get the information that Hook, YOURTHEME_form_FORM_ID_alter(&$form, &$form_state, $form_id), can be used to alter the various parts of forms.
But on that page, there is nowhere a description about any part which all are described in above first code, For example, $form['search_block_form']['#attributes']['placeholder'] = t('Search'); This code is used to change the placeholder. And same way all other like title, #title_display etc...

Why I am asking this, because for hooks all things are already defines and to use them we have to use them as they are provided, So What is the method to connect this all dots, from Hook name to what can we change with that hook.
Precise Question,

To make this question to the point, I what to know from where on api.drupal.org shall I find out, this part $form['search_block_form']['#attributes']['placeholder']? Or how shall I come to know that, if I have to change placeholder I have to use $form['search_block_form']['#attributes']['placeholder'] this code only?
Answer:
So What is the method to connect this all dots, from Hook name to what can we change with that hook.

There isn't one - each hook is different, has different input, different output, different contents, affects different parts of the system, and so on. You have to look for documentation contextual to what you're working with, each time you have something different.
In this case, you're working with a form, which means you should be referring to the Form API. From there it's an easy search to find information about #attributes:

Description: Additional HTML attributes, such as 'class' can be set using this mechanism.
Values: Any HTML attribute not covered by other properties, e.g. class (for control types), enctype (for forms).

It's basically an arbitrary pass-through of the key/value, so
$form['search_block_form']['#attributes']['foo'] = 'bar';

Will get you (e.g.)
<input type="text" foo="bar" />

Comment: It's pretty similar @NoSssweat, there's an article [here](https://www.drupal.org/node/2117411) which goes into a bit more detail
Comment: WOW the form API documentation sure is in-depth, I wish all documentation was like this.
Comment: Is it the same for D8? I don't see a link at top.
Comment: Thanks for explanation, it helped in overall understanding.
Answer:
where on api.drupal.org shall I find out, this part
  $form['search_block_form']['#attributes']['placeholder']?

I don't know, but this is basic PHP. $form is a multidimensional array with keys of search_block_form, #attributes, placeholder, etc...
All I know is that you can use the Devel module to see the structure and what's inside of the array by using dpm($form)
function YOURTHEME_form_search_block_form_alter(&$form, &$form_state, $form_id) {
    dpm($form);
}

Comment: Ok, if we can come to know that tree using Devel module, then Devel module is the answer. I will test and update. Thx
Comment: I realize SE-participants are not allowed to ask for translation help (they should have dictionaries handy). At least that's what I remember from a moderator comment in the past (so unser-unfriendly I think for anybody who did not learn English on their mother's knees ...). But does that also apply to knowing what all the abbreviations mean? If it is relevant to understand the answer, would you mind explaining what IDK means? Here are my guesses: "**I** **D**o **K**now" or otherwise "**I** **D**on't **K**now" ... ***AFAIK***, and ***IMO***, time for ***LOL***, ... ***CU***!
Comment: @CodeNext that is correct. Since it is an HTML Attribute, you would only see it if the form had a placeholder already, but not if the form doesn't have one yet. Which is why the documentation that Clive's answer links to is very important.
Comment: Ok, I understand something. The Devel module is working perfectly fine. but not showing `placeholder`. I was under impression that, the placeholder is something drupal code part, hence it should be somewhere in code. But as I look carefully I realize it is an HTML attribute. Hence, there is not a point to find it in devel. So it is just applying HTML thing. Same way in code in question, onblur, onfocus, onsubmit are Javascript functions. Hence, also not a point to find. Hence remaining part `['search_block_form']['#attributes']` is itself explanatory. Hope I understand correctly?


haproxy and forwarding client IP address to servers

Question: I have a problem with HAproxy.
I use HAproxy as load balancer which distribute incoming http requests to 5 web servers. normally a client request's is forwarded to web servers with loadbalancer's IP. But I need clients IPs or real IPs who request something from web servers. Because we need to log the real client's IPs.
I try to obtain client's IPs on web servers but I can not success up to now. Always I see the load balancer's IP.
I use x-forward-for option but it is not solved the problem. After that I found another option "source 0.0.0.0:80 usesrc clientip" but I got eror while trying to run HAproxy which is about compilation needs with USE_TPROXY option of the HAproxy. I did it, I recompile HAproxy with USE_TPROXY option but does not change anything. what can I do in order to learn real client's IPs.
My linux kernel version is 2.6.32-34 I mean that kernel is support transparent proxy. and I use UBUNTU 10.4 LTS
my config file is here
global
    maxconn 100000
    uid 99
    gid 99
    daemon

defaults
    option forwardfor except 127.0.0.1
    mode    http
    (1)source 0.0.0.0:80 interface hdr_ip(x-forwarded-for,-1)
        (2)source 0.0.0.0:80 usesrc clientip
    contimeout  5000
    clitimeout  50000
    srvtimeout  50000

listen  myWeb 0.0.0.0:80
    mode http
    balance source
    option forwardfor header X-Client
    option http-server-close
    stats enable
    stats refresh 10s
    stats hide-version
    stats scope   .
    stats uri     /lb?stats
    stats realm   LB2\ Statistics
    stats auth admin:xXx

    server  S1 192.168.1.117:80 check inter 2000 fall 3
    server  S2 192.168.1.116:80 check inter 2000 fall 3
    server  S3 192.168.1.118:80 check inter 2000 fall 3

(1)(2) While testing HAproxy I used one of these two lines.
Is somebody help me to learn real IP's of the clients who being request from our servers?
Comment: What you're looking for is called a 'transparent proxy'. iptables is involved somehow, but I'm not sure exactly how.
Comment: by saying transparent proxy I mention that, the proxies which is not modify the http headers while distribute the incoming connections. thus real web page requester client's IP can be sent to the web server. That is the what I understood from transparent proxy.
Answer: I solved this problem. May be it was not a problem from the beginning. I made google search when I faced this problem, and I saw that
option forwardfor

line in order to use in haproxy.cfg file and also other options. I tried those options including recompiling the haproxy... But the real problem related to learning real client's IPs on web servers is not sourced from HAproxy, it is about reading headers by server scripts, in our case this scripting language is PHP.
I try to learn client's IPs by these commands
echo 'Client IP: '.$_SERVER["REMOTE_ADDR"];
echo 'Client IP: '.$_SERVER["HTTP_CLIENT_IP"];

and these commands displays loadbalancer's IP. This is correct but that is not what I am expected. Despite the forwardfor option these commands, gave me loadbalancer's IP
By using forwardfor option we make enable HAproxy to insert the x-forwarded-for header into client's requests sent to our web servers. HAproxy put this field to header but I have ignored this. Today I realized that this is a header field and I have to read this header like this
echo 'Client IP: '.$_SERVER["HTTP_X_FORWARDED_FOR"];

With this command I got the client's IP address not loadbalancer's IP address.
But my offer is in order to get the header data to investigate the other information is getallheaders() function for PHP.
//from php.net http://php.net/manual/en/function.getallheaders.php
foreach (getallheaders() as $name => $value) {
    echo "$name: $value
\n";
}

End of all my last haproxy.cfg file is like below.
global
    maxconn 100000
    uid 99
    gid 99
    daemon

defaults
    option forwardfor except 127.0.0.1
    mode    http
    contimeout  5000
    clitimeout  50000
    srvtimeout  50000

listen  myWeb 0.0.0.0:80
    mode http
    balance source
    option forwardfor
    option http-server-close
    stats enable
    stats refresh 10s
    stats hide-version
    stats scope   .
    stats uri     /lb?stats
    stats realm   LB2\ Statistics
    stats auth admin:passwd

    server  S1 192.168.1.117:80 check inter 2000 fall 3
    server  S2 192.168.1.116:80 check inter 2000 fall 3
    server  S3 192.168.1.118:80 check inter 2000 fall 3

Nevertheless I have many missing things about HAproxy like what is the meaning uid or gid.
Comment: what does this line `option http-server-close` do ?
Answer: If you need the client IP addr on the Apache log you can change your apache conf to log the X-forwarded-for in place the original source (5h)
#LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\"" combined
LogFormat "%{X-Forwarded-For}i %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\"" combined

Comment: Thanks for your answer Marcelo, but we do not need client's IP address on Apache log. we try to learn by our php scripts.
Answer: Just tried @System's solution and it seems that the header name was changed from HTTP_X_FORWARDED_FOR to x-forwarded-for. Probably it's related with HAproxy version, 'cause the answer was written 5 years ago...?
As an example, this is working on production:
String requestIp = httpRequest.getHeader("x-forwarded-for");


Kendo Datasource - Backbone - Changes made to backbone model not syncing in datasource

Question: I have a number of instances where my Kendo Datasource <-> Backbone connection is working as expected, but I have run into a situation that I hope someone knows more about.
When a model or collection is synced from the server, the datasource is also updated and respective Kendo controls are also updated.
However, if you already have a collection loaded, and you loop through that collection, making a change to the models in that collection, it appears that the linked DataSource is not getting the changes.
Example:
I have a collection of "tags" that are displayed as checkbox options. I want to display some of those checkboxes as "checked" based on other data coming from the server (in this case, I am loading a product - and want to display what colors are selected):
this.colors.each(function (me) {
  me.set('selected', '');
  if ( _.findWhere(self.model.get('colors'), {id: me.id} ) ) {
    me.set('selected', 'checked');
  };
})

$('#colors').kendoListView({
  dataSource: this.colors_datasource,
  template: '
<input type="checkbox" value="#: id #" #:selected#> #: name #
'
});

The 'this.colors_datasource' is defined in the initialize method of this backbone view. It is not seeing these changes being made to the backbone models in the collection "this.colors". I presume that this is because the models are not syncing to the server.
If I add the definition between these two blocks of code, it works:
this.colors.each(function (me) {
  me.set('selected', '');
  if ( _.findWhere(self.model.get('colors'), {id: me.id} ) ) {
    me.set('selected', 'checked');
  };
})

this.colors_datasource = new kendo.Backbone.DataSource({
  collection: this.colors
});

$('#colors').kendoListView({
  dataSource: this.colors_datasource,
  template: '
<input type="checkbox" value="#: id #" #:selected#> #: name #
'
});

So, my question: Is this the only solution, or is there a way to tell an already defined DataSource to rebuilt itself?
Thanks - StackOverflow Rocks!
Answer: I'm guessing there is a timing issue. Perhaps, in the case where it's not working, the datasource is being initialized incorrectly?
The code you provided at the bottom is how you should do it. From the docs you can read the kendo.Backbone.DataSource is providing the magic to get the 2-way binding. Without this the kendo ui does not know about the change events coming from the backbone collection. They provide sample code there that's very similar to what you've suggested here.
I also wanted to comment on this line:

I presume that this is because the models are not syncing to the server.

One of the beautiful things about the Backbone.Events system: it does not require a round-trip to the server in order for the UI to keep in sync with changes. As long as you handle the basic collection events add, remove, change, etc. you can keep your interface up to date without talking to your server.
Comment: Thanks for replying. There's no timing issue, I don't think. This is a collection of checkboxes. The collection is fetched/populated elsewhere, and regardless of where I link up the DataSource, it draws out properly. This issue is that later, when I change a model in that collection, the datasource is not seeing that change, and therefore is not triggering a redraw of the Kendo widget.
Comment: Regarding your comment about the events, normally, the DataSource sees these events and reacts as expected. For example, if I were to add a new model to this collection (a new checkbox to the list), this will redraw properly. So while it appears to be reacting to events on the collections, the change event that the model is triggering is not being seen by the datasource.


Show that $1+5^n + 5^{2n} + 5^{3n} + 5^{4n}$ is never prime for n > 0 integer

Question: Show that $1+5^n + 5^{2n} + 5^{3n} + 5^{4n}$ is never prime for n > 0 integer
Trying cases on a computer I can see that the equation is divisible by 11 when $n \neq 5^k$. That's easy to prove if you write the sum as a fraction using the fact that the series is geometric.
Is there a more general way to solve the problem, one which includes a solution for $n=5k$ and doesn't require ansatz?
edit: $ n = 5k$ not $ n = 5^k $
Comment: Will expressing the number is base $5$ help ?
Comment: Is that hint? I thought of that but didn't get anywhere.
Comment: I solved it for $n$ odd, if we can combine that with your result we'd be done.
Comment: Can you show why it $n=5^k$ is needed? I could only show $n=5k$
Comment: @JorgeFernándezHidalgo Got it now. I deleted my comments.
Comment: @JorgeFernándezHidalgo Should be n = 5k
Comment: Oh ok :)${}{}{}{}$
Answer: Case $1:n=2k$
Then our sum is $\frac{5^{10k}-1}{5^{2k}-1}=\frac{(5^{5k}-1)(5^{5k}+1)}{5^{2k}-1}$. Since the denominator is smaller than each of the factors we conclude the number is not prime.
Case $2: n=2k+1$
Let $a=5^{2k+1}$ and notice $1+a+a^2+a^3+a^4=(a^2+3a+1)^2-5a(a+1)^2$.
Since $a=5^{2k+1}$ this is equal to: $(a^2+3a+1)^2-5^{2k+2}(a+1)^2=(a^2+3a+1)^2-(5^{k+1}(a+1))^2$
We recognize this as a difference of squares and obtain:
$((a^2+3a+1)-5^{k+1}(a+1))(a^2+3a+1)+5^{k+1}(a+1))$.
It is very easy to see the first factor is greater than $1$.
Comment: How did you obtain the initial expression in  the second case?


Ionic input, apenas números

Question: No Ionic como faço um campo input receber apenas números ?
Quero um campo de idade e quero garantir que aceite apenas números, proibindo o usuário de digitar letras.
Answer: Você pode usar type="number" no <ion-input>.
<ion-item>
    <ion-input type="number" placeholder="Informe um número"></ion-input>
</ion-item>

Ionic input, apenas números


override 'Edit own content' using taxonomy access

Question: Can I override 'Edit own content' for a particular role and a particular node using taxonomy access? Or better, can I simply switch off Drupal's built-in access content module and solely rely on the settings of TAC (taxonomy access content module)?
What I'm trying to accomplish here is:
a user creates content, the user works on their own content until they think it's ready for moderation upon which they'll set a taxonomy term to 'finished content'. A moderator now comes into play and checks the content of the user. If they decide to approve the content they set a vocabulary term to 'approved content'. This triggers a rule which sets the locking vocabulary of that node to the term 'Locked'. At this point the author should not be able anymore to edit this content.
The problem is that node access permissions still allows the author to edit their own content. How would you tackle such a problem?
Cheers!
Answer: Ok, I've found a way around it. I'm using the Workbench Access module.
This module, which can be used as a stand alone module, allows you to use taxonomy terms as sections you can set on any node and then you need to assign the roles (or particular users) who can update nodes with these terms/sections. In conjunction with the taxonomy access control module I found that you must at least set the global default for that role to 'view'. If you don't, the users of that particular role won't have update AND view access which is not what I wanted. They can see what they've created but they can't change it anymore after they saved it or after a certain taxonomy term has been set, by themselves or automatically through rules.
Hope that helps others as well!
Cheers!


Dynamically adjust argument or filter to views entity reference filter based on value from select list in form

Question: I have a entity reference field that references a taxonomy term from a vocabulary named "fund".  Now I'm needing to add a fiscal year field to the fund terms to allow us to have different budget lines for different fiscal years.  Some of these funds will have the same name, but be from different fiscal years, so I now need to add a fiscal year dropdown list before the autocomplete entity reference field mentioned above.
Say the dropdown has two values FY17 and FY18, I'd like the views entity reference filter view to receive the selected value for fiscal year, and apply that as a filter to the views entity reference filter.  How can I accomplish this?  Alternatively is there a better way to accomplish this?
For example:

I looked at Dynamically change views entity reference filter based on current form value but it doesn't seem like it quite fits what I'm trying to do.  I could be wrong.
Comment: Since the taxonomy field is dependent on the selected year, the solution will need to AJAXify the taxonomy ref view autocomplete field.
Comment: I've done something similar in the past where someone enters Zip Code then the Closest Dealer AJAX's in, where it shows the 3 Closest Dealer based on the zip code. [Example](https://i.stack.imgur.com/ZtGDW.jpg). I utilized a view for the Closest Dealer where I dynamically pass it the Zip. Although, yours will require an extra step for the autocomplete functionality. Maybe I'll have time this weekend to write an answer.
Comment: @NoSssweat that would be really awesome. Since the autocomplete uses Ajax anyway I was hoping it might be a simple matter of grabbing the value of the select and passing it as an argument with the autocomplete Ajax call.
Comment: The problem with that approach is that it would require you to save the node first, because when you're filling out the form Drupal does not know yet the year value until you hit save. So the real question is How can you grab the value of a node field that you're currently filling out and that doesn't exist yet?
Comment: My hope was that one could override the JavaScript function for sending the currently entered search text, to also grab the value from the dom and send it as an argument, but maybe you are saying that argument information cannot be sent along with the Ajax autocomplete request and needs to be prepopulated on the form?
Answer: The simplest answer ended up being to use Entity Reference View Widget which allowed me to build a view for selecting the entity desired.  This was nice because it allowed me to add some additional information and filtering the the approach I was hoping for in my question didn't allow.  Unfortunately, it also moves me further from being able to update this site to Drupal 8 because this module doesn't exist for Drupal 8 because the maintainer decided to let another module that isn't released yet, cover this functionality for Drupal 8.  I would still welcome answers about how to do this in a more forward compatible way.
Comment: I think this feature is in core now. I can simply choose a View with an entity reference display to get the entities from.


7 - Posting www links without http prefix

Question: I have a simple body field that uses an input format with only "Limit allowed HTML tags".
If I enter a link ... say Test
The node will transform the link's href to read http://www.mydomain.com/www.google.com
If I enter Test, it will work as expected.
Is there a reason why not including http:// causes this? Is there a way around it?
I was hoping Pathologic would solve this but it doesn't seem to have.
Thanks!
Answer: The issue is href="www.google.com" really is http://yourdomainandpath/www.google.com just as href="hello.htm" would be as well.
Comment: Ah. This seems to apply at the browser level.


Why is the state in mapStateToProps undefined?

Question: reducers/counter.js
export type counterStateType = {
  +ctr: number,
  +counter: boolean
};

type actionType = {
  +type: string,
  +value: any
};

export default function counter(state: counterStateType = { ctr: 0, counter: true}, action: actionType) {
  console.log("Reducer called with");
  console.log(state);//has valid value ie { ctr: 0, counter: true}
  switch (action.type) {
    case TOGGLE:
      state.counter = !state.counter;
      return state;
    case UPDATE:
      state.ctr = action.value;
      return state;
    default:
      return state;
  }
}

counterPage.js
function mapStateToProps(state) {
  console.log("mapStateToProps called with");
  console.log(state.counter);

  return {
    ctr: state.counter.ctr,//<= undefined
    counter: state.counter.counter
  };
}

function mapDispatchToProps(dispatch) {
  return bindActionCreators(CounterActions, dispatch);
}

export default connect(mapStateToProps, mapDispatchToProps)(Counter);

PS: The above is on router LOCATION_CHANGE
Comment: check what is state.counter
Comment: it was evedent from printing state  itself, but now updated the question for your convinience.
Comment: Your counter was originally true, now it is false in mapStateToProps.  Can you show the code updating the counter object and the reducer updating it.
Comment: solved the issue, the problem was in reducer, here I have omited the state updation swich case of the reducer. but the problem was there.
Answer: The issue was in reducer, I had forgotten about immutablity of redux states. modifying,
  switch (action.type) {
    case TOGGLE:
      state.counter = !state.counter;
      return state;
    case UPDATE:
      state.ctr = action.value;
      return state;
    default:
      return state;
  }

to
  switch (action.type) {
    case TOGGLE:
      return {ctr: state.ctr, counter: !state.counter};
    case UPDATE:
      return {ctr: action.value, counter: state.counter};
    default:
      return state;
  }

solved it.


NextJs Unhandled Runtime Error: Element type is invalid

Question: I was creating an instagram clone from a youtube tutorial which was posted 1 year ago. There are many errors due to nextjs14, I've solved everyone until this error:
Error: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: object.
Check the render method of RootLayout.
The code for GlobalContext.js is
import { globalReducer } from "../reducers/globalReducer";

const initialState = {
    user:{},
    isAuthenticated: false,
    isOnboarded: false,
    isLoading: false,
}

export const GlobalContext = createContext(initialState);
export const GlobalDispatchContext = createContext(null);

const GlobalContextProvider = ({ children }) => {

    const [state, dispatch] = useReducer(globalReducer, initialState)

  return (
    <GlobalContext.Provider value={state}>
      <GlobalDispatchContext.Provider value={dispatch}>
        {children}
      </GlobalDispatchContext.Provider>
    </GlobalContext.Provider>
  );
};

export default GlobalContextProvider;

The code for layout.js is

import "./globals.css";
import GlobalContextProvider from "./state/context/GlobalContext";

export default function RootLayout( Component, pageProps ) {
  return (
    <GlobalContextProvider>
      <Component {...pageProps} />
    </GlobalContextProvider>
  );
}

All the imports and exports are correct as I have checked. Any solution?
I solved that layout.js was not CSR, but after solving it, it showed this error.
Answer: The first props of layout.js is React children and the second is params.
So your layout.js function should be like this:
export default function RootLayout({
  children,
  params,
})

Now, you're using:
<Component {...pageProps} />

Of course you'll get error. Because Component is not a valid React component. Remember, the first props of layout.js is react children not a component.
Check out the official docs for more info
Comment: Its still showing the same error after I fixed the function like this:
```export default function RootLayout({
  children,
  params: { Component, pageProps },
}) {
  return (

  );
}
```
Comment: Of course. what params is ```Component``` ? try to remove `````` with just ```{children}```


Advice on writing for music boxes?

Question: I need to write two different short pieces for music boxes. The main limitations I'm facing are that I have to stay within 2 octaves and I can only(ish) write in the key of C major (or just C, D, E, F, G, A, and B). What should I keep in mind when trying to do this? How could I make a melody more interesting?
So far, I've figured out that since the tempo depends on the player, odd time signatures may not be the best choice. I'm also not sure that writing on anything but C major would suit me. What do you think of that?
Also, since I haven't seen this asked anywhere else, how would you tackle this problem?
Comment: Why would odd time signatures be any more problematic than, say 4/4? What part of the music box is marking bar lines?
Comment: Odd time sigs are fine, you'll just have a hell of a time trying to keep track of everything as you're writing on the paper. As others have said, you've got all the modes to use as well. Last piece of advice: be careful not to put your notes too close together otherwise they won't sound. You can get away with 16th notes if the notes are farther apart; 16th-note scales can't really happen, but you *can* add little ornamentation here and there.
Comment: This is far too broad, since you could write a Gregorian chant or a 2-note rap "beat"
Comment: What's the requirement?  To write something that sounds traditional 'music box' or to stretch the limits of music box composition?
Comment: If this is for a specific music box, please post information, links, etc. to the machine itself.  There are plenty of "music boxes' out there with accidentals included.
Comment: @CarlWitthoft - and what differences would it make either way?
Comment: @Tim nothing, I suppose, other than the simplicity of the composition itself.
Comment: @CarlWitthoft The music box I'm working with is the (make your own) Music Box Kit by Kikkerland.
Comment: where is the music box specific problem? otherwise this is just another 'how do I write a good melody' question
Answer: Keep it simple. I'm especially fond of music boxes. One of my main instruments is a celeste and I play hundreds of these types of songs. So this topic is near and dear to me.
Not sure why everyone's bringing up modes. The majority of music box songs are very simple and are usually in a major scale as music boxes generally depict traditional songs or upbeat songs for children (think "Somewhere Over the Rainbow", "Happy Birthday", etc). So your C major is fine. There's a big list of music box songs you can listen to. Play close attention to the 18 note and 22 note music boxes.
I analyzed the 354 music box songs of the 18 note movements in the link above. 310 were major (87%), 45 were minor (12.7%), 3 were modes and other scales (0.8%), 6 were mixed modes (1.69%). An example of a mixed mode song is "and I love her" by The Beatles.
So you see major is the most used if you want a traditional music box sound. That said, minor melodies and other modes can be very beautiful. One of the reasons why both Harry Potter and Sugar Plum Fairies have that "magical" feel to them is because they're minor on a celeste/bells instrument. Because people are mainly conditioned to hear major on bells (due to kids songs mainly), minor has a unique and mysterious tone to them.
Also worth to note that your typical 18 tine music box movement doesn't "waste" any notes. the comb doesn't have notes that don't appear in the song and more than likely it'll be diatonic. although it can have a non-diatonic tones in there if the song calls for it. Most combs are tuned specifically to a song. so "London Bridge" will have a different comb than "This Old Man", due to repeated notes. See here under "18 note movement information" see how it says "duplicate pitches (teeth) are necessary whenever a note plays again in less than about one second (which happens alot). Most movement combs have between 4 and 10 duplicated teeth, limiting the overall number of different pitches to about 14 or less". Also you can watch a video on this here.
In a music box, usually the melody is emphasized. So start off with the melody, then harmonize it afterwards.
In order to harmonize it properly you may or may not have enough room for full chords in two octaves:
1. Invert chords to make them fit.
2. Play a subset of the chord. So instead of playing 3 notes, you can play 1 note (root of the chord) or two notes (root+fifth,root+third, etc).
3. Try a different key. certain melodies/chords fit better in different keys for two octaves.
Another element of music boxes is to slightly arpeggiate a chord. This can happen on a cadence or when you want to emphasize a chord. But it's very quick, it provides a cute "jumbled" kind of sound. let's say I'm playing a C5 chord. so I'll play a C note, followed by G a few milliseconds afterwards, so they sound like they're together but not quite. you can also do this on full chords. You can see an example if you look at a music box, notice that on cadences and other chords that are emphasized, the dots aren't completely aligned.
Also, if you want to hear what it sounds like on an actual music box, search for "music box maker". they go for under 20 bucks, where you punch custom holes on paper and you crank out through a music box.
Answer: As others have indicated, there are a lot more than just the C major scale note that can be used for music box tunes.Any of the modes of C major will work (except perhaps B Locrian!). The problem lies with the fact that every note coming out is the same volume as every other.
In order to mark out each bar, it's a good idea to have it play two, maybe three notes at the beginning of some bars. Just a series of notes, even in time, won't necessarily start at the beginning, and could easily sound like they're modal even if it's supposed to be in C major. So, with a dyad or chord every so often, the listener will be convinced as to where the tune is at any point.
I agree with David's comment - it doesn't matter whether the music is played slowly or quickly, the time signature it's written in won't affect what's played.
Comment: A fundamental problem for music boxes may be how to convey phrasing in the absence of dynamics; this answer touches on that. To me this seems more important than worrying about restricted scales or modes. +1
Answer: You're not limited to writing in the C major scale.
Well, okay, you can only use the notes of the C major scale. But...
Modes! Modes are basically the notes of a scale, but starting on a different scale degree. In order, the modes you can use are:

C Ionian (C major)
D Dorian
E Phrygian
F Lydian
G mixolydian
A Aeolian (A minor)
B Locrian

All of these use the notes of the C major scale. Melodies in modal music can sound quite interesting and colorful.
Additionally, in general terms, you can simply write in a more classical style for that traditional music box sound. I'll not go into detail, but rest assured this site has plenty of advice on how to do that.
I find it's probably good to include the seventh on your dominant chords if you're going for a traditional music box sound.
Answer: General advice for composers and musicians: play chords, not scales. If tempo is somewhat random, chords are your best friend. There's plenty of chords and beautiful chord progressions on the white keys. Write a song. C, G, Dm7, G, Dm, Cmaj7, Dm6, E7, F, G, C, Dm, F, G, C. There, I wrote it for you.
If you don't know what you're doing or if you need more inspiration, try scales. In addition to D dorian and G mixolydian etc, try various pentatonic scales

A minor pentatonic : A, C, D, E, G
Hirajōshi in A : notes A, B, C, E, F
... same, but tonal center in E : E, F, A, B, C
... same, but tonal center in B : B, C, E, F, A
(whatever the correct name is for this one) : D, E, F, A, B

Hirajōshi is a Japanese scale, look it up if you want to know more.
Comment: In English, I've heard that "Hirajoshi" scale referred to as "Japanese pentatonic minor".
Answer: Start thinking in harmonies:
All music in major C without predominant will fit.
Dorian is o.k. (e.g. "drunken sailor") - aeolian too.
I remember  in the 80ies every second disco hit  had the chord progression am F G em the melody contained many eights  and a few quarter notes). Try this out.
Answer: If I were going to make a scroll for that music box kit, I would first notate the music in a program like MuseScore with an appropriate music box sound select. Only after being satisfied with the music would I transfer it to the punch paper.
The other thing I might do it test the music box with some well know theme and see how it sounds. A Satie Gymnopedie or a Mozart minuet would probably be my choice, but you can pick something you want to emulate.
Beyond that your question seems to be 'how to compose purely diatonic music?' That kind of question is supposed to be too broad for this forum.
Answer: Look up the Simpson's "Orb of Isis" for inspiration. Just write a simple melody, then write a simple "bass" line under it. One thing I noticed is no more than two notes strike simultaneously. Music box music is fun!

Advice on writing for music boxes?


i cant seeem to get this text under this icon

Question: i try to get the green text under the wallet text and icon but i just cant get it to work, also why is the responsiveness so weird here?
https://jsfiddle.net/8dxt0hkj/2/ <-- take a look at the code here
thanks in advance

        Wallet

$35,95

Comment: Hi Yannick. What do you mean when you say the responsiveness is weird? Can you tell us exactly what you see happening that you don't want to have happen, and explain or give an example of what you do want to see? More details will make it easier for us to help you solve the problem.
Comment: Improve code readability
Answer: To put the green text under the wallet text and icon, you will need to change the CSS for wallet_value. You could change display: inline-block; to display: block; to make wallet_value start on the next line (and therefore appear below the wallet text and icon.) This will make the text hug the left edge of the page, though, so if you want the text to line up better you can also add margin-left: 30px;.
I also noticed that in this line:
<input type="text" placeholder="search for..."">

You have an extra " character that might be messing things up. Try changing that line to:
<input type="text" placeholder="search for...">

Edit: It sounds like you want everything inside the header div to be all on one line and change size as needed when the window resizes so that the header always fits on one line. Here is an edited JSFiddle with working code (as close as I can to what I think you're asking how to do.) I used the display: flex option a lot in this, so I recommend checking out this tutorial and/or this documentation if you're not familiar with flex.
I set the header to display: flex;. I also put display: flex; and flex-direction: column; on the wallet div so that it will display one element on top of the other as you asked for. I made the search bar change width dynamically by removing the absolute width and making it have a min-width: 80px; instead, along with width: 100%;. Then, when I set its parent to have flex-grow: 1; the search bar will stretch to fill the remaining space. I also took out some of the large margins that were making things too wide, and I set the min-width of the header as a whole to 700px so it won't get too small when the window resizes. Is that about what you were looking for?
Comment: header will get smaller than 100% width. thanks so much
Comment: I think I see what you might mean - when I resize the result window in your JSFiddle, the search bar jumps down below the top bar when the window is less than 1164px wide, and the wallet text and image also jump up on the same line as the search bar. Is that what you're talking about?
Comment: Did you want the wallet text and icon to stay inside the top header bar all the time? If so, I think I know how you can do that, but I'll need to change my previous answer.
Comment: @YanickPalmers did this answer your question? If it was helpful, please consider accepting it so others can find it more easily. If not, please let me know what you still would like help with.


Checking Answers...

Question: Is it possible to help me to verify my answer to the questions below?

If you shuffle a standard deck of $52$ cards, what is the probability that the top $2$ cards are both "5"?

ANS: $\frac 4{52} \times \frac 3{51} = \frac1{221}$

You roll $2$ dice. You get $\$100$ if at least one of them is $6$, or sum of them is $6$. How much do you think this game is worth?

ANS: $(\frac{11}{36} + \frac5{36}) \times 100 = \frac 49\times 100 = \frac{400}9\approx \$44.44$

A train is approaching a bridge. You are at the $\frac14$ position of the bridge. Running both ways can rescue you (both ways can get you safe, and just before hit by the train). What is the speed ratio between you and the train?

ANS:
Suppose the man has speed of $1$ m/s, train is $x$ m/s,
$\frac{x+4}3=\frac x1$
$x=2$
Comment: Why do you refer to this as "*mental math*"... are you not allowing the use of pen&paper to calculate anything?  Why do you answer the first with a ratio and not the second?  Question 3 seems badly worded as you could get off the bridge long before the train arrives, so there seems to be no upper limit on the speed of the man.
Comment: @JMoravitz, Question #3 assumes that you can just get it off (either running backward or forward) just before you get hit by the train.
Answer:
Your first answer is correct.
At least one 6. Means 6 on one die or 6 on both dice.

Probability = $\frac {1}{6} \times \frac {5}{6} + \frac {5}{6} \times \frac {1}{6} + \frac {1}{6} \times \frac {1}{6}$
$ = \frac {5}{36} + \frac {5}{36} + \frac {1}{36}$
$ = \frac {5+5+1}{36} = \frac {11}{36}$
Sum of numbers is 6. Cases are (1,5) , (2,4), (3,3), (4,2), (5,1).
Probability = $\frac {5}{36}$
Total probability = $\frac {11}{36} \times \frac {5}{36}$
So your answer 2 is also correct.

Question is not enough clear. We have many doubts like how apart train when man start running.
Comment: I guess how aprt train when man start running can be calculated using the problem statement above. Why don't you give it a try?

Checking Answers...


Additional git commits not showing up on initial PR in GitHub

Question: I have a forked branch that was cloned from github.
I pushed a commit to the forked branch and created a PR to merge to the original branch. The PR looked fine.
Problem started when I pushed a second commit to the forked branch, I expected the PR to be auto-updated but the 2nd commit didn't show up. What went wrong?
Answer: I performed the following steps and it worked for me.

Cloned a public repository to my Github account: https://github.com/AnilGithubber/Web-Dev-For-Beginners/ (Ref: Github1)
Forked this cloned repository to my another Github account: https://github.com/AnilKumarVallur/Web-Dev-For-Beginners (Ref: Github2)
Performed changes for rep in Github2, created the PR and not merged yet to Github1
Created another commit from Github2 and the new commit was automatically showing up in Github1

Does your forked repository says it is forked from?
Comment: This issue seems to have resolved itself after sometime. The PR did get updated but there was a significant delay.
Comment: The fork seems to be fine since the initial commit showed up and the PR to merge to the parent branch looked fine as well.


Are there any 2 x 2 matrices A and B that contain real numbers such that $(AB+I_2)^2 = I_2 $ $ $ and that $ AB\neq O_2$?

Question: Are there any 2 x 2 matrices A and B that contain real numbers such that $(AB+I_2)^2 = I_2 $ $ $ and that $ AB\neq O_2$ ?
( There comes another question after it, which is: )
Are there any 3 x 3 non-invertible matrices A and B that contain real numbers such that $(AB+I_3)^3 = I_3 $ $ $ and that $ AB\neq O_3$ ?
I need some hints to solve these two problems. Thank you in advance!
Comment: If you expands $(AB+I_2)^2=I_2$, you will have $(AB)^2+2AB=0$. Did you try this way?
Comment: Using the indication given by Matheus Nunes, take B=I and look for a matrix $A$ whose characteristic polynomial is $\lambda^2+2\lambda$. Do you see why ?
Comment: Yes, this is where I started from. I'll give it one more try.
Comment: Yes, I have just finished it! Thank you very much, now I moved to the second one.
Answer: Perhaps, the simplest example would be
\begin{align}
A\,B&=
\left[\begin{matrix}
-2&0
\\
0&-2
\end{matrix}\right]
\end{align}
and $A,B$ for example,
\begin{align}
A&=
\left[\begin{matrix}
2&0
\\
1&2
\end{matrix}\right]
,\\
B&=
\left[\begin{matrix}
-1&0
\\
\tfrac12&-1
\end{matrix}\right]
.
\end{align}
Comment: thank you, it helped!
Answer: Hint:
Try to find $X$ of size $2\times 2$ or $3\times 3$ not equal to identity matrix such that $X^2 = I_2$ or $X^{3} = I_3$. (since matrix is a linear transformation, then maybe some rotations?)
If there is such $X$ then we want to solve $I + AB = X$, but it is easy: set $B = I$ and $A = X - I$.
Comment: Thank you, I hope I will get around to it this way!


Calling function from another in same object

Question: In the following code, I want pass a reference to the print_season function with parameter "winter" into the function inner_function.
tony = {
    print_season: function (season) {
        console.log(">>season is" + season);
    },

    report: function () {
        console.log(">>report");
        this.inner_object.inner_function(this.print_season("winter"));
    },

    inner_object: {
        inner_function: function(callback) {
            console.log(">>inner_function=" + callback());
        }
    }
}

tony.report();

However, when I do the function is invoked rather than passed and I end up with:
TypeError: callback is not a function
    console.log(">>inner_function=" + callback());

How do I pass the function with specific parameters in this case but to ensure it is not invoked?
Thanks.
Answer: You are not passing a function.
You are actually just passing undefined

You might want print_season to return a callback function:
...

print_season: function (season) {
    // return a callback function
    return function() {
        console.log(">>season is" + season);
    };
},

...

Comment: I think the OP is aware of this: *"However, when I do the function is invoked rather than passed and I end up with: [...]"*. The question is *"How do I pass the function with specific parameters in this case but to ensure it is not invoked?"*
Comment: Ahh ok will make update then :-)
Comment: @FelixKling I made an update.
Answer: You are invoking print_season.
Try something like this.
this.inner_object.inner_function(function() { this.print_season("winter") });

Answer: Try this:
tony = {
print_season: function (season) {
    console.log(">>season is" + season);
},

report: function () {
    console.log(">>report");
    this.inner_object.inner_function(function(){this.print_season("winter")});
},

inner_object: {
    inner_function: function(callback) {
        console.log(">>inner_function=" + callback());
    }
}
}
tony.report();

Or this:
tony = {
print_season: function (season) {
 return function(){
     console.log(">>season is" + season);
 }
},

report: function () {
    console.log(">>report");
    this.inner_object.inner_function(this.print_season("winter"));
},

inner_object: {
    inner_function: function(callback) {
        console.log(">>inner_function=" + callback());
    }
}
}
tony.report();

The goal is to have a function (callback) not something else.


Adding error bands on a radar (spider) chart?

Question: I would like to create a radar chart for my data. However, I would like to add an error band to this chart.
There is a similar topic on StackOverflow. But, it is for R, and I would like to do it in python. (Error bars on a radar plot?)
Similar example:
spider chart
Please, could anyone help me with this subject?
Answer: My example is based on this one from matplotlib. You can get the other supporting functions there and I included how to use them on this example:
<code>   N = 6
theta = radar_factory(N, frame='polygon')

axis = ['1', '2', '3', '4', '5', '6']
val =[0.88, 0.01, 0.03, 0.03, 0.00, 0.06]

fig, ax = plt.subplots(figsize=(9, 9),subplot_kw=dict(projection='radar'))

ax.set_rgrids([0.2, 0.4, 0.6, 0.8])

ax.plot(theta, val, color="b")

arr = np.array(val)
y_err = arr.std() * np.sqrt(1/len(arr) +(arr - arr.mean())**2 / np.sum((arr - arr.mean())**2))
y_est = arr

ax.fill(theta,  y_est + y_err, facecolor=color, alpha=0.25)
ax.fill(theta,  y_est - y_err, facecolor="white", alpha=1)

ax.set_varlabels(axis)

plt.show()
</code>
image example


Does Apache2 run faster if I have more CPU?

Question: I have a cloud server, with:
5120 RAM and 4.6Ghz
My question is: if I add more CPU, (11.5 Ghz) will the load time of the pages be higher?
I mean, is this always gradual? More CPU = faster pageload? And if not, how does it work and how can I learn more about this?
UPDATE:
Symcbean's answer was very clear. But there is still something I don't understand (and what I find on Google, more people don't)
I've tried to put it in a metafore:
Let's say I've got a bucket with water (the bucket with water = the PHP process, with caching etc)
I want to empty the bucket into a funnel. (the end of the funnel = server speed, how bigger the end of the funnel, the faster the water runs through it)
If I have a funnel-end of 0.5 inch, it goes through slow. If I have one of 1 inch it goes faster.
But if the funnel-end is (let's say) 10 inch, it doesn't matter if I have 10 inch or 20 inch, the water goes through it at the same speed.
So with this metafore I mean; how do I know I'm using 100% of the capacity and how do I know that I don't need more...?
PS:
I would really appreciate it if somebody could explain, what the max is, and how this actually works or how I can find this out?
PPS:
this is the output when I run 'top'
<code>top - 23:06:18 up 54 days,  6:08,  1 user,  load average: 0.51, 0.43, 0.47
Tasks: 107 total,   2 running, 105 sleeping,   0 stopped,   0 zombie
Cpu(s): 28.1%us,  1.5%sy,  0.0%ni, 70.2%id,  0.0%wa,  0.0%hi,  0.0%si,  0.2%st
Mem:   4966748k total,  4493968k used,   472780k free,   241436k buffers
Swap:  4194300k total,   123252k used,  4071048k free,  2836028k cached

  PID USER      PR  NI  VIRT  RES  SHR S %CPU %MEM    TIME+  COMMAND
16432 root      20   0 1115m 283m  30m R   95  5.8   1:11.39 php
16422 www-data  20   0  927m  45m  21m S   18  0.9   0:00.53 apache2
20270 mysql     20   0 2327m 330m 5500 S    7  6.8 474:19.11 mysqld
  617 n2        20   0 14268 1140  488 S    1  0.0 182:58.64 n2txd
30212 root      20   0     0    0    0 S    1  0.0  24:50.48 flush-202:1
26848 root      20   0 99424 1108  856 S    0  0.0   2:47.63 sendmail-mta
    1 root      20   0 24188 1556  872 S    0  0.0   0:09.09 init
    2 root      20   0     0    0    0 S    0  0.0   0:00.00 kthreadd
    3 root      20   0     0    0    0 S    0  0.0   0:48.36 ksoftirqd/0
    4 root      20   0     0    0    0 S    0  0.0   1:27.21 kworker/0:0
    5 root      20   0     0    0    0 S    0  0.0   0:00.05 kworker/u:0
    6 root      RT   0     0    0    0 S    0  0.0   0:00.00 migration/0
    7 root      RT   0     0    0    0 S    0  0.0   0:26.69 watchdog/0
    8 root      RT   0     0    0    0 S    0  0.0  21841:40 migration/1
    9 root      20   0     0    0    0 S    0  0.0   0:00.00 kworker/1:0
   10 root      20   0     0    0    0 S    0  0.0   0:56.84 ksoftirqd/1
   11 root      RT   0     0    0    0 S    0  0.0   0:23.78 watchdog/1
   12 root      RT   0     0    0    0 S    0  0.0   0:00.00 migration/2
   13 root      20   0     0    0    0 S    0  0.0   0:00.00 kworker/2:0
   14 root      20   0     0    0    0 S    0  0.0   0:48.05 ksoftirqd/2
   15 root      RT   0     0    0    0 S    0  0.0   0:19.11 watchdog/2
   16 root      RT   0     0    0    0 S    0  0.0   0:00.00 migration/3
   17 root      20   0     0    0    0 S    0  0.0   0:00.00 kworker/3:0
   18 root      20   0     0    0    0 S    0  0.0   0:40.08 ksoftirqd/3
   19 root      RT   0     0    0    0 S    0  0.0   0:19.24 watchdog/3
   20 root       0 -20     0    0    0 S    0  0.0   0:00.00 cpuset
   21 root       0 -20     0    0    0 S    0  0.0   0:00.00 khelper
   22 root      20   0     0    0    0 S    0  0.0   0:00.00 kdevtmpfs
   23 root       0 -20     0    0    0 S    0  0.0   0:00.00 netns
   24 root      20   0     0    0    0 S    0  0.0   0:00.00 kworker/u:1
   25 root      20   0     0    0    0 S    0  0.0   0:00.00 xenwatch
   26 root      20   0     0    0    0 S    0  0.0   0:00.00 xenbus
   27 root      20   0     0    0    0 S    0  0.0   0:22.29 sync_supers
   28 root      20   0     0    0    0 S    0  0.0   0:00.42 bdi-default
   29 root       0 -20     0    0    0 S    0  0.0   0:00.00 kintegrityd
   30 root       0 -20     0    0    0 S    0  0.0   0:00.00 kblockd
   31 root      20   0     0    0    0 S    0  0.0   1:57.23 kworker/2:1
   32 root       0 -20     0    0    0 S    0  0.0   0:00.00 ata_sff
   33 root      20   0     0    0    0 S    0  0.0   0:00.00 khubd
   34 root       0 -20     0    0    0 S    0  0.0   0:00.00 md
   36 root      20   0     0    0    0 S    0  0.0   0:01.45 khungtaskd
   37 root      20   0     0    0    0 S    0  0.0   0:29.28 kswapd0
   38 root      25   5     0    0    0 S    0  0.0   0:00.00 ksmd
   39 root      20   0     0    0    0 S    0  0.0   0:00.00 fsnotify_mark
   40 root      20   0     0    0    0 S    0  0.0   0:00.00 ecryptfs-kthrea
   41 root       0 -20     0    0    0 S    0  0.0   0:00.00 crypto
   49 root       0 -20     0    0    0 S    0  0.0   0:00.00 kthrotld                                                                                50 root      20   0     0    0    0 S    0  0.0   0:00.00 khvcd                                                                                51 root      20   0     0    0    0 S    0  0.0   1:19.07 kworker/3:1                                                                                70 root       0 -20     0    0    0 S    0  0.0   0:00.00 devfreq_wq                                                                                71 root      20   0     0    0    0 S    0  0.0   1:03.05 kworker/0:1                                                                                190 root      20   0     0    0    0 S    0  0.0   1:31.64 kworker/1:1                                                                                193 root      20   0     0    0    0 S    0  0.0   2:52.19 jbd2/xvda1-8
</code>
Answer: Looks like PHP is your CPU bottleneck, not Apache.
You seem to have 4 CPU cores, but the PHP process is only running on one of them; depending on how you have things configured, PHP may not be using all of the available CPU cores for different requests.  At the time the load was in that state, how many requests were being handled?
If PHP's only running a single thread, you need to get it configured to run different requests on different cores to utilize your existing capacity.
If PHP's just executing a single request at that time, and that request is still returning too slowly, then more cores won't help, and you'll need to do some optimization and caching.
Comment: Thanks for the answer! Could you help me maybe by pointing me in the right direction on how to configure php to run on multiple cores (for example, how should it show up when I run 'top')
When I google on this topic, I find a lot, but not an explanation on how to configure PHP.
Comment: I would also like to know how to configure PHP for most efficient usage of multiple cores. Any links would be appreciated. Thanks!
Answer: Not sure where Shane sees 4 cpus in your top output. Certainly there's more than one. However your load average shows that never using more than half of your CPUs. Hence adding more CPUs isn't going to make it any faster.
Page response time is very much removed from PHP execution time. Typically the page load time will be in the region of 6-10 times the length of time to generate the HTML (assuming that the PHP is relatively efficient) - the difference is mostly due to stuff happenning at the network tier and o the browser. Tools like yslow and webpagetest will help with improving front end performance. I'd recommend getting a good book on the topic - like this one. There's a lot of good posts abut web performance here and about MySQL performance here.
Things like top, load average, cpu usage, free, vmstat et al, are good for telling you how your serverside performance is constrained - but as above this should only be a very small part of the story of the page lifecycle. From the snapshot you've provided, the hardware isn't overly taxed (there might be an I/O bottleneck but that's hard to see from these metrics).
If you have reason to suspect that your PHP code is rather slow then start logging and analysing your request data. How long do your PHP requests take to generate? What is your page load time?
One thing that does stand out from the top output you've shown is that there is only a single instance of PHP visible and a single instance of Apache. How is Apache configured? Which MPM? How does it connect to PHP? If you're using CGI, then you should get big improvements by switching to PHP-fpm or mod_php. Are you using an opcode cache?
Your mysqld has clocked up rather a lot of CPU cycles - you might want to start analysing your query log and tuning that. Try running mysqltuner against your instance.
I realise I'm asking a lot of questions here, but the solution to 'how to make my website go faster' would fill a very large book. It would take me about 2 days of work to get a server properly instrumented to capture the data to fully analyse it's performance - and at least 5 days to carry out the analysis - and that's before starting to find solutions to the problems - i.e. you're unlikely to get a specific answer here on Stack Overflow (I'm just trying to point you in the direction of asking the right questions).
Comment: Thanks for this *very clear* answer. But there still is something I don't understand. I've tried to explain it (see the update in the original post) under **update**
Comment: If you want to know the capacity of your server then you need to test it. This is rather complicated since you need to allow for different bandwidth / latency / packet loss on any simulated network connections and for the typical state of the client network stack (CWND, ssthresh) browser cache, along with the processing capacity of the browser (how quickly it can sink the data, generate related requests)


Pyarrow drop a column in a nested structure

Question: I would like to drop columns in my pyarrow table that are null type. Basically NullType columns are columns where all the rows have null data. I would like to drop them since they are not used by me and they cause a conflict when I import them in Spark. Here is an exemple of how I do this right now:
import pyarrow as pa

def drop_na_columns(df):
    null_columns = []
    schema = df.schema
    for (name_, type_) in zip(schema.names, schema.types):
        if type_ == pa.null():
          null_columns.append(name_)
    return df.drop(null_columns)

def create_dataframe(list_dict: dict) -> pa.table:
    fields = set()
    for d in list_dict:
        fields = fields.union(d.keys())
    dataframe = pa.table({f: [row.get(f) for row in list_dict] for f in fields})
    return drop_na_columns(dataframe)

This works fine for most of my use cases but I also have nested structures in my tables and sometimes one column in a nested structure is a null type column.
My question is to know if there is a way to identify the type of every sub-column struct, and then to drop a column in a nested structure. If any of you have an idea or has already tackled this problem I would be delighted to hear about it.
Thanks
Answer: It's reasonalby easy to identify which of your table columns are struct and which fields among these structs are null.
It's a bit harder to remove them though.
Here's an example:
struct_type = pa.struct([
    pa.field('ok', pa.string()),
    pa.field('bad', pa.null())
])

schema = pa.schema([
    pa.field('col1', pa.string()),
    pa.field('col2', struct_type),
])

table = pa.Table.from_arrays(
    [
        ["#0", "#1"],
        [
            ("OK1", None),
            ("OK2", None),
        ]

    ],
    schema=schema
)

You can tell that the second column is a struct by doing:
pa.types.is_struct(table.schema[1].type)
>>> True

And you can iterate through its fields:
[field.name for field in table.schema[1].type]
>>> ['ok', 'bad']

And tell which one are null:
[pa.types.is_null(field.type) for field in table.schema[1].type]
>>> [False, True]

Here's the code to recursively do what you are trying to achieve:
def get_clean_array(array):
    if pa.types.is_struct(array.type):
        if isinstance(array, pa.ChunkedArray):
            array = array.combine_chunks()
        arrays = [
            get_clean_array(array.field(index))
            for index, field in enumerate(array.type)
            if not pa.types.is_null(field.type)
        ]
        names = [
            field.name
            for field in array.type
            if not pa.types.is_null(field.type)
        ]
        return pa.StructArray.from_arrays(arrays, names)
    else:
        return array

def get_clean_table(table):

    return pa.Table.from_pydict({
        field.name: get_clean_array(table[field.name])
        for field in table.schema if not pa.types.is_null(field.type)
    })

Comment: I opened https://issues.apache.org/jira/browse/ARROW-15643 for a feature request to make this "subset a StructArray" easier.


Can't configure a host with another host ip address

Question: I created an Ansible playbook to configure :
- a database server
- a nginx & php server
The database server needs to know the php server ip address to configure database access rights.
The webserver needs to know the database server ip address to configure the database access for the website.
I tried with delegate_facts :
vars:
    Database_server_name: "SVWEB-03"
    Web_server_name: "SVWEB-02"

- name: Web server ip address
  set_fact:
    Web_server_ip: "{{  ansible_default_ipv4.address  }}"
  delegate_to: "{{  Web_server_name  }}"
  delegate_facts: True
  when:
    - "Database_server_name in inventory_hostname"

- name: Database server ip address
  set_fact:
    Database_server_ip: "{{  ansible_default_ipv4.address  }}"
  delegate_to: "{{  Database_server_name  }}"
  delegate_facts: True
  when:
    - "Web_server_name in inventory_hostname"

- debug:
    msg: "{{  Web_server_ip  }}"
  when:
    - "Database_server_name in inventory_hostname"

- debug:
    msg: "{{  Database_server_ip  }}"
  when:
    - "Web_server_name in inventory_hostname"

But I have errors :
TASK [Web server ip address] ***************************************************************************************************
skipping: [SVWEB-02]
ok: [SVWEB-03 -> SVWEB-02]

TASK [Database server ip address] ************************************************************************************************
skipping: [SVWEB-03]
ok: [SVWEB-02 -> SVWEB-03]

TASK [debug] ***************************************************************************************************************
skipping: [SVWEB-02]
fatal: [SVWEB-03]: FAILED! => {"msg": "The task includes an option with an undefined variable. The error was: 'Web_server_ip' is undefined\n\nThe error appears to have been in '/home/murmure/ansible/playbooks/Install_Wordpress_Separate_DB_and_Web.yml': line 64, column 7, but may\nbe elsewhere in the file depending on the exact syntax problem.\n\nThe offending line appears to be:\n\n\n    - debug:\n      ^ here\n"}

TASK [debug] ***************************************************************************************************************
fatal: [SVWEB-02]: FAILED! => {"msg": "The task includes an option with an undefined variable. The error was: 'Database_server_ip' is undefined\n\nThe error appears to have been in '/home/murmure/ansible/playbooks/Install_Wordpress_Separate_DB_and_Web.yml': line 69, column 7, but may\nbe elsewhere in the file depending on the exact syntax problem.\n\nThe offending line appears to be:\n\n\n    - debug:\n      ^ here\n"}

Does someone have an idea about my mistake please ?
Answer: I believe what you need is in hostvars:
- name: Database server ip address
  set_fact:
    Database_server_ip: "{{  hostvars.Database_server_name.ansible_default_ipv4.address  }}"


rake routes fails even when app loads

Question: When running bundle exec rake routes in my app directory I get the following error:
~/Dropbox/code/mcsl2 /master ! ()> bundle exec rake routes
rake aborted!
no such file to load -- app/controllers/api/provider_controller.rb

The file does in fact exist, and the app even loads when running rails s.
Any suggestions on how to track down this error?
EDIT: Here's the relevant part of routes.rb
namespace :api do
  namespace :provider do
    post 'authenticate'
    namespace :customer do
      get '/', :to => 'customer#index'
      post '/', :to => 'customer#create'
      get '/:id', :to => 'customer#show'
    end
  end
end

Comment: Did you check that *app/controllers/api/provider_controller.rb* exists? And if it does, please post route definitions related to this controller.
Comment: @Lukas Stejskal, yep. It's there.
Answer: You need to post your route file to help us out but may be it has to do with the file being called from app/controllers/api/provider_controller.rb as opposed to to app/controllers/provider_controller.rb
The difference is in the extra api folder.
Comment: The file structure does include the API folder. The pathing is correct. Everything works as expected, EXCEPT rake routes.
Answer: Provider is not a namespace, it's a resource, an actual controller. Try this:
namespace :api do
  resources :providers do
    post 'authenticate'
    ...
  end
end

Comment: I would normally agree with you, however, the current way IS working correctly. I.E, requests to /api/provider/authenticate and /api/provider/customer/find work just fine.
Comment: Well, 'rake routes' doesn't work :). And the app should work even after you change it. BTW :customer should be resource (not namespace) as well.
Answer: It turns out that I had an issue with the installation of rails. changing my Gemfile back to 3.0.5 for rails (gem 'rails', '3.0.5') running bundle update && bundle install, then setting the Rails gem back to 3.0.9 (gem 'rails', '3.0.9'), and running bundle update && bundle install again fixed the issue.
Answer: I know this sounds funny but have you tried turning it off and on again.. literally. I use aptana studio 3 for my rails and im come across the odd time where the studio "forgets" where everything is, at one point it even forgot the bash. Either shut it down and open the IDE again or uninstall it and reinstall. Hopes that works
Comment: I have rebooted. I just use TextMate and a console, so there's not much that can get screwed up!

rake routes fails even when app loads


Algebra problem regarding system of logarithmic equations.

Question: The equations are:
$\log_{4}(x)+\log_{4}(y)=5$
$\big(\log_{4}(x)\big)\big(\log_{4}(y)\big)=6$
I attempted to solve this problem by solving the pair of equations for $x$.
For the first equation:
$\Longrightarrow \log_{4}(xy)=5 \Longrightarrow xy=4^{5} \Longrightarrow xy=1024 \Rightarrow x=\dfrac{1024}{y}$
For the second equation:
$\Longrightarrow \log{4}(x)=\dfrac{6}{\log_{4}(y)} \Longrightarrow x=4^{\frac{6}{\log_{4}(y)}}$
Then,
$\Longrightarrow \dfrac{1024}{y}=4^{\frac{6}{\log_{4}(y)}}$
How should I move on from here?
Comment: Hint: First, solve $A+B=5$ and $AB=6$.  Then see how you can apply that to $x$ and $y$.
Answer: Let $u=\log_4(x)$, $v=\log_4(y)$. The equations can be written in $u$ and $v$
$$u+v=5,\ \ uv=6$$
The solutions are $u=2$, $v=3$, or $u=3$, $v=2$. Then you solve for $x$ and $y$
EDIT
As Bernard pointed out, $u$ and $v$ above are generally found as the solutions of the quadratic equation $t^2-5t+6=0$. But in this special case I just solved it by inspection.
Also, for completeness, $\log_4(x)=2$ implies $x=4^2=16$ and $\log_4(y)=3$ implies $y=4^3=64$. So the solutions are $x=16, y=64$ and $x=64, y=16$
Comment: You should write the quadratic equation which has $u$ and $v$ as roots: $t^2-5t+6=0$;
Comment: @Bernard Right, but for this simple case I just solved it by "inspection"
Comment: But how can one be sure there are no other solutions? *A priori*, the solutions are not necessarily integers.
Comment: @Bernard Assuming that i found two numbers with sum $5$ and product $6$, they are THE solution, since the quadratic equation has two solutions (or at most two solutions if only considering reals). Anyway, I updated my answer to reflect your comment.
Comment: You don't get my point: I simply mean a naive reader might not know there's the theory of quadratic  equations behind this stuff, and wonder whether this yields *all* solutions.
Comment: @Bernard I think the edit addresses your concerns. If you think it is still not clear, let me know and I will update it.
Comment: It's perfectly clear now for me!
Answer: We have:
$\log_{4}(x)+\log_{4}(y)=5$
$\Rightarrow \log_{4}(x)=5-\log_{4}(y) \hspace{5 mm}$ (i)
$\big(\log_{4}(x)\big)\big(\log_{4}(y)\big)=6 \hspace{4.25 mm}$ (ii)
Substituting (i) into (ii):
$\Rightarrow \big(5-\log_{4}(y)\big)\big(\log_{4}(y)\big)=6$
$\Rightarrow 5\log_{4}(y)-\big(\log_{4}(y)\big)^{2}=6$
$\Rightarrow \big(\log_{4}(y)\big)^{2}-5\log_{4}(y)+6=0$
$\Rightarrow \log_{4}(y)=\dfrac{-(-5)\pm\sqrt{(-5)^{2}-4(1)(6)}}{2(1)}$
$\Rightarrow \log_{4}(y)=\dfrac{5\pm{1}}{2}$
$\Rightarrow \log_{4}(y)=2,3$
$\Rightarrow y=16,64$
Using (i):
$\Rightarrow \log_{4}(x)=5-\log_{4}(16)$
$\hspace{19.5 mm}=5-2$
$\hspace{19.5 mm}=3$
$\Rightarrow x=64$
or
$\Rightarrow \log_{4}(x)=5-\log_{4}(64)$
$\hspace{19.5 mm}=5-3$
$\hspace{19.5 mm}=2$
$\Rightarrow x=16$
Therefore, the solutions to the system of equations is $x=16$ and $y=64$ or $x=64$ and $y=16$.
Comment: Might be clearer just to factorize the quadratic $\big(\log_{4}(y)\big)^{2}-5\log_{4}(y)+6=0$ rather than use the quadratic equation.


What is $\operatorname{Gal}(\mathbb Q(\zeta_n)/\mathbb Q(\sin(2\pi k/n))$?

Question: Let $\zeta_n$ be the $n$-th primitive root of unity and $4 \mid n$. Consider the field extensions $\mathbb Q \subset \mathbb Q(\sin(2\pi k/n) \subset  \mathbb Q(\zeta_n)$.

What is the degree of the extension $[\mathbb Q(\zeta_n):\mathbb Q(\sin(2\pi k/n)]$?
What is  $\operatorname{Gal}(\mathbb Q(\zeta_n)/\mathbb Q(\sin(2\pi k/n))$?
Comment: I don't think that $\sin(2\pi k/n)$ is always an element of the cyclotomic field? For example, if $n=5$, $k=1$, then $\sin 72^\circ=\cos 18^\circ=\sqrt{2(5+\sqrt5)}/4$, which generates a quartic extension (see e.g. [this table](http://en.wikipedia.org/wiki/Exact_trigonometric_constants)). But the real subfield of $\mathbb{Q}(\zeta_5)$ is $\mathbb{Q}(\sqrt5)$?? OTOH, if $4\mid n$, then $i\in \mathbb{Q}(\zeta_n)$, and we have the obvious way of writing $\sin 2\pi k/n$ in terms of $\zeta_n^k$.
Comment: Duh. The best example showing that the problem is off is the case $n=3$: $\mathbb{Q}(\sin2\pi/3)=\mathbb{Q}(\sqrt3)$ and $\mathbb{Q}(\zeta_3)=\mathbb{Q}(\sqrt{-3})$.
Comment: What is $k{}{}$?
Comment: @JyrkiLahtonen: Perhaps $\cos \frac{2 \pi k}{n}$ is meant, since Galois number fields are always closed under real parts.
Comment: @ZhenLin, that would be my guess as well. But in that case the answer to the question is very easy (and probably covered in most books on Galois theory). Let's just wait for the OP to clarify, whether the typo is about $\sin\leftrightarrow \cos$, or about forgetting the assumption $4\mid n$.
Answer: You should first prove that   $[\mathbb Q(\cos(2\pi /n)):\mathbb Q] =\phi(n)/2$, which is  easy.
Then you should use that $\sin(2\pi k/n)=\cos ((n-4k)\pi/2n)$.
A few calculations necessitating case distinctions will then yield the result:
$$[\mathbb Q(\sin(2\pi /n)):\mathbb Q]=\phi(n)  \quad   \text {if} \;  n  \not \equiv  0 \;( \text {mod} \; 4) $$      $$[\mathbb Q(\sin(2\pi /n)):\mathbb Q]=\phi(n)/2  \quad   \text {if} \;  n  \equiv 0 \;( \text {mod} \; 8)$$  $$[\mathbb Q(\sin(2\pi /n)):\mathbb Q]=\phi(n)/4  \quad   \text {if} \;  n \equiv 4 \;( \text {mod} \; 8)$$ [I have answered your question in the above  form because (as Jyrki  noted) the original question doesn't make sense, since we don't always have  an inclusion $\mathbb Q(\sin(2\pi /n))\subset \mathbb Q(\zeta_n).]$
Comment: @Mohan, if $\gcd(k,n)=1$, then $K=\mathbb{Q}(\cos(2\pi k/n))$ is the real subfield of $L=\mathbb{Q}(\zeta_n)$. Therefore $[L:K]=2$.
Comment: How can we show $[\mathbb Q(\sin(2\pi /n)):\mathbb Q]=\phi(n)/2  \quad   \text {if} \;  n  \equiv 0 \;( \text {mod} \; 8)$ from $\sin(2\pi k/n)=\cos ((n-4k)\pi/2n)$
Answer: Since $e^{ix} = \cos(x) + i \sin(x)$ we have
$$ \sin(x) = \frac{e^{ix} - e^{-ix}}{2i}. $$
Thus $\sin(2 \pi k/n)$ is, unless $n$ is a multiple of $4$, an element of
${\mathbb Q}(\zeta_{4n})$. The degrees of your extensions are basically
measured by the greatest common divisors of $k$ and $n$. There will be
clean formulas for prime values of $n$, or e.g. if $k = 1$.


Erro: Invalid argument supplied for foreach()

Question: estou tendo um problema na exibição da minha lista de recados, está dando esse erro:
Warning: Invalid argument supplied for foreach() in /###/###/###/view/list.php on line 11

No arquivo está assim:

    <?php foreach ($listaRecados as $r): ?>

<?php echo $r->titulo; ?>

<?php echo $r->texto; ?>

          <a href="recado.php?action=excluir&id=<?php echo $r->id; ?>">
          <a href="recado.php?action=curtir&id=<?php echo $r->id; ?>"> <?php echo $r->likes; ?> - <?php echo $r->autor; ?>

    <?php endforeach ?>

A linha 12 é essa: <?php foreach ($listaRecados as $r): ?>
Comment: `$listaRecado` não é um array, verifique seu valor.
Comment: coloca um print_r($listaRecados); e observa o retorno, como o comentário a cima $listaRecados não é um array
Comment: Na verdade ele está puxando o $listaRecado do recado.php, eu sou muito iniciante.
Answer: Verifique sé a Variavel "$listaRecados" que está chamando e exatamente uma Array, utilize a empty() para fazer essa verificação.
 if(!empty($listaRecados)): foreach($listaRecados as $r): endforeach; else: echo "Array Vazio" endif;


Is there a limit to the amount of memory a single thread can access in a dual-processor system?

Question: I'm looking to buy a workstation for data processing using MATLAB.  I'm considering one of two workstations from DELL.  The lower end workstation (3500) has a single processor and 24 GB of memory in 6 DIMMs.  The higher end (7500) will only allow me to select 24 GB of memory (in 12 DIMMs) if I select the dual-processor option.  The difference between the two seems to be that

The Dell Precision T3500 has a three channel memory bus architecture.
The Dell Precision T7500 has a three channel memory bus architecture per processor

Does this mean that each processor gets 12 GB of memory, and a thread on processor A can't see the same memory as processor B?  This seems unlikely, but maybe there is a performance penalty for A to access B's memory?
Answer: You're right that the dual-proc machine has 6 memory channels, 3 per processor. This particular architecture is called NUMA and is very well engineered in the system you're talking about - it'll try to keep a thread's memory 'near' to the core it's running on and will be slightly slower if it has to use memory bound to the other processor's memory channels but I wouldn't worry about it at all, every single box I currently use has this type of system and I'm more than happy with performance.


Features 8.x-3.7 not writable on Window's Ubuntu

Question: 8x-3.7 features, most stable version, but I am having trouble writing to custom module on the UI. My structure is as follow:
 -modules/
    contrib/
       features/
    custom/
       news_blogs/
          config/
             install/
                [code]

when i edit my view, i go to /admin/config/development/features I see that the feature state is  edit. I click the checkbox and click write.
I get error:
Package News/Blogs not written to modules/custom/news_blogs. Error: Failed to create directory /mnt/c/mywebsite/modules/custom/news_blogs/config/install.. and then inside install code is deleted and empty.
I check my logs:
Warning: chmod(): Operation not permitted in Drupal\Core\File\FileSystem->mkdir() (line 226 of /mnt/c/mywebsite/core/lib/Drupal/Core/File/FileSystem.php) #0...
I checked my permissons and it is 777 and my usr is the owner for the directory.
I am unsure what else to check or test to figure out what can be going wrong. Any help is thanked!
Answer: It looks like you are using something like a virtual machine (Vagrant?) with a shared windows file system.  The problem is that Windows permissions don't map well to Linux ones.  That is why the chmod error is happening.
You may need to get your webserver running under the same user you share the file system under, e.g. the vagrant user.
Personally, I have never gotten a stable way to have Features write to a windows share. There always seemed to be a gotcha in the ones that worked.  I've just excepted that I had to download the feature archive, unpack it, and copy it to the site on the Windows side.
But your situation may be different.
Comment: I found this forum very helpful: https://github.com/Microsoft/WSL/issues/81