Ações independentes em abas

Question: Possuo duas abas e preciso mostrar informações independentes em cada uma das abas. Na primeira aba, consigo mostrar as informações na qual eu preciso. Porém, na segunda aba, preciso referenciar o conteúdo mostrado utilizando outro link. Neste novo link, as informações já estão consolidadas e eu só preciso mostrar na segunda aba. Como posso referenciar este conteúdo em minha segunda aba? Segue abaixo alguns trechos de código.

 ***** CONTEUDO MOSTRADO E IMPLEMENTADO CORRETAMENTE *****

 ***** CONTEUDO QUE DEVE SER MOSTRADO A PARTIR DA REFERENCIA:
 geIndicators.php?rType=STKEXPO&rFilter=PROGRAMADOR&rArea=PCM *****

Comment: Essas abas são janelas diferentes ou estão dentro da mesma página?
Comment: Elas estão na mesma página, Sergio.
Answer: Você terá q usar ajax para pegar o conteudo da outra página:
function openCity(evt, cityName) {
    var i, x, tablinks;
    x = document.getElementsByClassName("city");
    for (i = 0; i < x.length; i++) {
        x[i].style.display = "none";
    }
    tablinks = document.getElementsByClassName("tablink");
    for (i = 0; i < x.length; i++) {
        tablinks[i].className = tablinks[i].className.replace(" w3-gray", "");
    }
    document.getElementById(cityName).style.display = "block";
    evt.currentTarget.className += " w3-gray";

    var xhttp = new XMLHttpRequest();
    xhttp.onreadystatechange = function() {
        if (xhttp.readyState == 4 && xhttp.status == 200) {
            document.getElementById(cityName).innerHTML = xhttp.responseText;
        }
    };
    xhttp.open("GET", "url_arquivo?params", true);
    xhttp.send();
}

Comment: Brito, quando efetuei a troca de abas, o conteúdo da primeira página não era mais mostrado. Então, executei a seguinte alteração:
Comment: var xhttp = new XMLHttpRequest();
                    xhttp.onreadystatechange = function() {
                        if (xhttp.readyState == 4 && xhttp.status == 200) {
                            document.getElementById(cityName).innerHTML = xhttp.responseText;
                        }
                    };

                    if(cityName == "Programador"){
                       xhttp.open("GET", "geIndicators.php?rType=STKEXPO&rFilter=CONSOPROGRAMADOR&rArea=PCM", true);
                       xhttp.send();
                    }
Comment: Porém a página esta sendo duplicada. Aparecem dois cabeçalhos, dois rodapés e etc
Comment: so remover o cabeçalho e o rodape no arquivo da pagina q tu esta tentando carregar na aba. Caso tu entre nesta pagina de outra maneira alem de carregar pela aba tu pode passar um parametro GET pra ocultar o cabeçalho e o rodape ai quando tu for carregar pelo ajax tu passa o parametro na url

Ações independentes em abas


VMWare Workstation 7 vs 6.5 - is it worth upgrading?

Question: We are currently using VMWare Workstation 6.5 for staging and QA purposes(basically to replicate production environment in house). Host OS is Ubuntu 9.04. Guest - Windows 2003 Server.
How is 7.0 lines up against 6.5 in terms of performance and stability? Features such as 3D graphics and etc. are of no interest...
Answer: I too have been wondering this and am downloading 7 to see if there are any performance gains.

3d Graphics support - no use for myself but maybe handy for those wanting to run Vista/7 in its full glory
vSphere and ESXi support is great - can finally test ESXi due to HCL issues with my i7 12Gb Hardware
Automatic Snapshots - maybe handy when you forget to take a snapshot when you just install that component!
Driverless printing - Now this could be handy for testing printing from your application in the testing environment

But like you, I just want to know if it performs better!
Update
It feels like it performs better so there maybe some good reasons to do the upgrade if you feel like your workstation is sluggish when running 6.5.
Have not tested 3d effects or the Unity functions  Unity works well for those that require it
The major improvement is not only VM boot speed but suspend and resume has increased dramatically. I think they have overhauled this entirely with 7.
Overview
For those thinking about upgrading, I would suggest that it feels like it is definately worth it just for the performance and suspend/resume gains.
These tests have been performed on Windows 2003 R2 server & Windows XP. No other guests have been verified.
Answer: I upgraded - XP and 2000 VMs startup is faster.
Haven't tested the 3D support yet - would be nice if I can game on a VM though.


listing all the pages of a custom content type

Question: I would like to know the appropriate way to listing the contents in a single page of type "news". Let me clear it once again, I have a "news" type custom content type.
Now i want to list all the pages of type "news" in a separate(say about us) page and styling them. Prior to this I have created a template file in my custom theme's template directory named as "node-news.tpl.php". Thanks In Advance.
Answer: The views module do that. There's many articles about this question. Take a look on existing answers
Answer: Yes, you can use views module to generate a page to display all node of news content type.

Install a views module
Go to administrator -> structure -> views
Add new view
Add filter content type as "news"
Add fields to views.
Comment: Yes that is quite easy, but i need to list all the pages without using view module and also database query .Can it be possible using some code in template.php or anywhere else??
Comment: You need to create a custom module and can write the custom query in the module.
Answer: generate a View using the view module as mentioned by Satyabrata sahoo. generate a page view for your specific purpose that would be more appropriate.
Answer: Yes You can do it in your template file .
Drupal suggest names for the custom content type template files.
<code> and it is page--node--your_content_type.tpl.php .
</code>
You can see your nodes of type (your_content_type) at here.


How do I find the shortest distance around a circle from one degree value to another, simply by adding or subtracting rotational velocity?

Question: I am trying to create a movement system for a 2D spaceship game using only the arrow keys. So essentially I have a 2d vector and I want to use that to set a rotation for my spaceship. If the ship starts with an angle of 0, and then I press the up arrow the ship should rotate from 0 to 90 degrees or pi/2 from 2pi based on a rotation velocity. This is the code I have that does this.

    private void updateRotation()
    {
        if (Direction.X < 0)
        {
            setRotationValue(MathHelper.ToRadians(180));
        }
        if( Direction.X > 0)
        {
            if(MathHelper.ToDegrees(rotation) < 180)
            {
                setRotationValue(MathHelper.ToRadians(0));
            }
            else
            {
                setRotationValue(MathHelper.ToRadians(360));
            }

        }
        if(Direction.Y < 0)
        {
            setRotationValue(MathHelper.ToRadians(270));
        }
        if(Direction.Y > 0)
        {
            setRotationValue(MathHelper.ToRadians(90));
        }

    }

    private void setRotationValue(float target)
    {
        if (target > rotation)
        {
            rotation += MathHelper.ToRadians(rotationVelocity);
        }
        if (target < rotation)
        {
            rotation -= MathHelper.ToRadians(rotationVelocity);

        }
    }

<
However, my problem arises in a situation where the ship is say facing 45 degrees and I want to rotate to 270 degrees. Well if I press the down key the target rotation is greater then the current rotation so it goes from 45 to 270. This is not the quickest path, as it would be much faster to go from 45 back to 0, then start at 360 and go down to 270. I'm not sure the best way to implement this in code, or if my approach is the right way to do this. I have had a long conversation with chat GPT, which did not give me a solid answer. Any help or direction on how to solve this problem would be much appreciated, especially if this problem is even possible or if I need to look into something like Euler angles or quaternions.
SECOND ATTEMPT TO EXPLAIN: -----------------------------------------
I have an arrow with a starting rotation value of 0 degrees or 2pi, so it is parallel to the x axis. If I tell it to go up, I want it to slowly increment its rotation by some number (I called it rotation velocity before) until its rotation value reaches 90 degrees or pi/2. I have achieved this already with my code.
Now Lets say I have told it to go up but I let go of a key when its at 45 degrees or pi/4. Now I tell the arrow to change its rotation value untill the arrow is facing straight down and is parallel with the Y axis (270 degrees or 3pi/2).
(My Problem):
With the code previous, target rotation value is 270 or 3pi/2, and current rotation value is 45 or pi/4, so it is going to increment the rotation value untill the target value is reached, even though it would be faster to decrement the rotation value back to 0, then set it to 360 or 2pi and continue decrementing to reach 270 or 3pi/2.
So not sure how to determine that that is the faster route mathmatically.
I described values in radians and degrees throughout this as its easier to wrap my head around. By telling the arrow to rotate I mean pressing keys. For example the key mappings are
D or left = 0 degrees or 2pi
W or up = 90 degrees or pi/2
A or right = 180 degrees or pi
S or down = 270 degrees or 3pi/2
While the user is holding a key, the arrow in the example, (or the spaceship in the game I'm trying to make) increments or decrements its rotation value until its rotation value is equal to one of the 4 targets defined in the key mappings above. If the ship is at 90 degrees and the user holds D, the rotation would slowly increment until it reaches 0 degrees or the user lets go of the key.
Answer: I don't fully understand what you want your arrow keys to do, or what you mean by "rotation velocity" in your context, but let me try to restate your goal mathematically:
You have a starting angle $S$, and a desired ending angle $E$, and you want to find an angle $D$, with $-180 \lt D \le +180$, so that $$ E = S + D \mod 360$$
(If that wouldn't solve your problem, please explain further. Also, I'll keep things in degrees, as that's how you've written your question.)
I'll go through the solution in multiple steps, to make it easier to understand, but you certainly can combine equations together in your code if you wish.
First, let's set $$D_0 = E -S$$
And then we'll convert units to "full rotations" $$ d_0 = D_0/360$$
Now, set $$ n = \text{closest_integer_to}(d_0)$$
I'd normally expect this to correspond to a function named round(), but not all computer languages have a "native" round() function that behaves right, especially when handling negative numbers. You should find one where round(-1.7) equals -2, not -1. And when it comes to rounding, there can be a lot of discussion of what will happen with half-integral values, like $3.5$, but we don't care about that here - rounding them either up or down will work for us.
Next, set $$d = d_0 -n$$
Notice that we've modified the amount we rotate by an integral number of full rotations, which doesn't make a difference with angles.
Finally $$ D = 360 * d$$
converting back to degrees to give us the final desired answer.
One nice thing about this is it doesn't matter what range of values your $S$ and $E$ angles are in. If you had been slowly incrementing the value of $S$ and it was currently at, say, $5735$ degrees, you could still use $270$ as your $E$ value and the computed $D$ value would still be between $-180$ and $180$. And of course you can change the two occurences of "$360$" to "$2\pi$" if your angles are kept as radians.
(I gotta confess that I haven't done any 'testing' of this with actual values; it's just what makes sense mathematically. So you might want to run a few test cases after you code it up to make sure I don't have a bug!)
Comment: Hey thank you so much for your response! Finally got around to trying this today, unfortunately it produced the same results as my previous code. I tried to rephrase the question again by editing the original post. If you have some time I would love it if you could take a look and see what you make of it. Just scroll down to the section that says SECOND ATTEMPT TO EXPLAIN. I really appreciated your thorough and step by step approach to solving the problem.
Answer: Throughout the following, I am assuming that all angles are expressed in degrees and that counterclockwise is the positive direction.
Here is my interpretation of the problem:  We have two angles of $\theta$ and $\phi$ expressed in the range from $0$ to $360$, and we want to move along the unit circle from $\theta$ to $\phi$ in the shortest direction, which could be either clockwise or counterclockwise.
Start by computing $\delta = \phi - \theta$.  If $\delta > 180$, subtract $360$ from $\delta$.  If $\delta < -180$, add $360$ to $\delta$.  You now have  $-180 \le \delta \le 180$.  If $\delta > 0$, move counterclockwise $\delta$ degrees; if $\delta < 0$, move clockwise $-\delta$ degrees.
The key is to realize that adding or subtracting $360$ degrees from an angle results in the same angle under a different "name".  By the way, similar computations crop up often in real world problems involving terrestrial longitude.


Movimentar Imagens com Javascript

Question: Gostaria de um exemplo de como poderia movimentar uma imagem HTML usando JavaScript. Por Exemplo a Imagem esta numa posição, ao tocar um botao ele se movimente.Obrigado!
Comment: [Canvas](http://www.w3schools.com/html/html5_canvas.asp) é uma excelente opção para isso. Este [exemplo](http://www.html5canvastutorials.com/advanced/html5-canvas-animation-stage/) bem básico mostra o deslocamento de uma figura.
Answer: Já que não sei se você quer somente um botão para movimentar para somente um lado,tenho um exemplo movimentando aos 4 lados com 4 botões,segue o código :

<title>Demo of changing position of an Image in JavaScript</title>

<input type=button onClick=move_img('up') value='Up'>

<input type=button onClick=move_img('left') value='Left'>
<input type=button onClick=move_img('right') value='right'>

<input type=button onClick=move_img('down') value='down'>

 Return to image move tutorial

Exemplo deste código funcionando : http://www.plus2net.com/javascript_tutorial/image-move-demo.php

OBS : Você também pode caso quiser que a imagem se mova mais ou até menos, mudar na variável step aonde 50 é o quanto ela irá mover.
Comment: Seguindo seu exemplo, coloquei no jsfiddle, assim fica mais fácil de ver os códigos separados https://jsfiddle.net/fb00t8Lq/1/ :)
Comment: @AdemílsonF.Tonato Obrigado amigo,vou colocar também na resposta se você não se importar :)
Comment: Sinta-se a vontade ;)

Movimentar Imagens com Javascript


Why does my Rules Condition about registration code seem to fail?

Question: I'm using the Rules module and the Registration code module and I've tried configuring a rule like so:

Rules Event: upon saving a new user account(event).
Rules Condition: if the registration code used is "123456"(condition).
Rules Action: add a role for a user.

The rules export is as shown below:
{ "rules_give_trial_version" : {
    "LABEL" : "Give trial version",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules", "regcode" ],
    "ON" : { "regcode_used" : [] },
    "IF" : [ { "data_is" : { "data" : [ "regcode" ], "value" : "123456" } } ],
    "DO" : [
      { "user_add_role" : { "account" : [ "user" ], "roles" : { "value" : { "10" : "10" } } } }
    ]
  }
}

However, the Rules Action is not working (nothing works).
Any idea how to get this to work?
Note: The Rules Action works with the event "User has used a registration code" without any Rules Condition (if I temporarily remove that Rules Condition). But I'm badly in need of the condition as we want to check if a user has used a specific code. If yes, that user should be assigned a role.
Comment: "regcode" is a data object, not an integer. Comparing "regcode" to "123456" will never work and the condition will always fail. Instead, treat it like a data object, use the data selector, and you will see you have your choice of data in that object - you can compare regcode:rid, or regcode:created, or regcode:code, or regcode:tags etc. The first step you should do is use the "Show a message on the site" action (with no conditions) to display the value you are trying to compare, so that you're sure you're checking the right thing.
Answer: The typical Rules Condition doesn't seem to work here
Typically when using Rules, you can always give it a try to see if you can add, as a FIRST Rules Condition, a condition like "Entity has field". Or any other variation of a condition that informs the Rules module that you want to test the value of that field in a subsequent rules condition. Without that, Rules has no clue about which data to make available for subsequent processing ...
But, that doesn't seem to work/help for this particular case. For more details on that (if you really want to know why it doesn't work), you may want to look at the active Major task (not bug!) about Make better use of the Entity system ... (from Fago, who has quite a Rules "reputation" ...).
Rules debugging
If that doesn't help, I typically add a (temporary) Rules Action to just "Show a message on the site" (eg to show the value of a field ...). That might result in other unexpected results, to help you further debug it ...
But that doesn't seem to help either (grrrr), so time to move on to Rules debugging, as explained in my answer to "How can I display the value of a variable inside a condition?".
Depending on what the result of that type of debugging is, you may also want to (temporary) enable the Devel module, so that you can (temporary) add a Rules Action like "Display a value".
Try to find (and read) the documentation
Too bad, this module doesn't seem to have a lot of documentation, and the README.txt is not of much help either.
If anything else fails, read the sources
OK, the advantage of open source ... lets go read the sources ...
Aha, I see the regcode.rules.inc (regcode in this filename is the machine name of the Registration code module), so let's see what this module's Rules integration has to offer:

A Rules Event with machine name "regcode_used" and label "User has used a registration code". Fine, that's also what's used in the rule in the question here (nothing new).
A Rules Condition with (a loooong) machine name "regcode_rules_condition_regcode_available" and label "User has used a registration code". Huh??? That's the same label as in the Rules Event, confusing!!! But that Rules Condition is what intrigues me. Time to fabricate a variation of the rule in the question.

Rule prototype (1st attempt)
Have a look at this variation of the Rule in the question (also in Rules export format, use the Rules UI to import it in your own site):
{ "rules_give_trial_version" : {
    "LABEL" : "Give trial version",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "regcode", "rules" ],
    "ON" : { "regcode_used" : [] },
    "IF" : [
      { "regcode_rules_condition_regcode_available" : { "user" : [ "user" ] } },
      { "data_is" : { "data" : [ "regcode" ], "value" : "123456" } }
    ],
    "DO" : [
      { "user_add_role" : { "account" : [ "user" ], "roles" : { "value" : { "10" : "10" } } } }
    ]
  }
}

The only difference in this rule (as compared to the original rule in the question) is the very first (confusing labeled) Rules Condition with machine name regcode_rules_condition_regcode_available.
That additional Rules Condition seems pretty close to the typical Rules Condition as I mentioned in the beginning of my answer (and Fago's issue I mentioned before makes a lot of sense to me now). And since the question states "... badly in need of the condition ...", I thought I'd leave the QA-testing of this variation of the rule in the question to the OPer of the question ...
Too bad, but that 2nd Rules Condition can never work, since the "[regcode]" token is not the token we're looking for (ie something that is a string, and which we want to check if it yes or no matches the registration code we're interested in to assign that special role). Read on for a new (2nd) attempt ...
Rule prototype (2nd attempt)
With some additional eyeballing and experiments, I noticed that within "Rules Actions" (not Rules Conditions!) there is the token [regcode:code], apart from all sorts of other regcode related tokens. So that opens another opportunity to get it to work anyway: let's just grab that [regcode:code] string and pass it on to a (new) Rules Component, in which we're going to do our thing (ie verify the registration code and grant the role if the code is what we want it to be. Below is the adapted rule from the previous attempt, and the (new) Rules Component:
a) Adapted Rule:
{ "rules_grant_a_role_after_using_a_registration_code" : {
    "LABEL" : "Grant a role after using a registration code",
    "PLUGIN" : "reaction rule",
    "ACTIVE" : false,
    "OWNER" : "rules",
    "REQUIRES" : [ "regcode", "rules" ],
    "ON" : { "regcode_used" : [] },
    "IF" : [
      { "regcode_rules_condition_regcode_available" : { "user" : [ "user" ] } }
    ],
    "DO" : [
      { "drupal_message" : { "message" : "Value of token \u0022regcode:code\u0022 is: [regcode:code] and will be used as parm for the subsequent Rules Action, which invokes a Rule Component." } },
      { "component_rules_grant_role_for_specific_regcode" : { "actual_regcode" : "[regcode:code]" } }
    ]
  }
}

b) Rules Component:
{ "rules_grant_role_for_specific_regcode" : {
    "LABEL" : "Grant role for specific regcode",
    "PLUGIN" : "rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "USES VARIABLES" : { "actual_regcode" : { "label" : "Actual Regcode", "type" : "text" } },
    "IF" : [ { "data_is" : { "data" : [ "actual-regcode" ], "value" : "123456" } } ],
    "DO" : [
      { "user_add_role" : {
          "account" : [ "site:current-user" ],
          "roles" : { "value" : { "10" : "10" } }
        }
      },
      { "drupal_message" : { "message" : "Since you used registration code \u0022[actual-regcode:value]\u0022, you have been granted a special role that corresponds to it." } }
    ]
  }
}

Note the 2 extra "Show a message" actions I added (to simplify QA testing).
Curious to hear if with this 2nd attempt it does work, or if you can MAKE it work from here on ...
Comment: Comments are not for extended discussion; this conversation has been [moved to chat](http://chat.stackexchange.com/rooms/48349/discussion-on-answer-by-pierre-vriens-why-does-my-rules-condition-about-registra).
Comment: Thanks for the above. Did you try the rule? I imported it and test. Nothing changes still!
Comment: @primerater01 Did you see the "*I thought I'd leave (at least for now) the QA-testing of this variation of the rule in the question to the OPer of the question ...*"? And what about your new "Rules debugging" results?
Comment: From the Rules debugging, The first condition returns true, while the second condition returns false. Hence, the rules will not run since both conditions are expected to return true for it to work
Comment: @primerater01 : your turn again to verify which results you get with my "2nd attempt" (which is what I added now, together with some edits at the end of the 1st attempt to explain why that could never work (understanding the problem is already part of the solution, right?). Let me know how it turns out ...
Answer: I have thought of and implemented a different way out as explained below.

Event: User has used a registration code
Conditions: User has used a registration code, Data comparison (regcode:tags) = 14, user has field access = "a user field"
Then,
Action: set a data value. i was able to view the registration code used (through token), and set it in a user field automatically.

Note: I have already tagged the particular code with a taxonomy term from the registration code settings interface. This method was adopted because i realized the regcode:tag is readily available almost all the time in the rules config.
Also, 14 above is the taxonomy term id of the term tagged with the code in question.


Percorrer elementos DOM com a função each

Question: Gostaria de um exemlo de como poderia fazer isso usando o Jquery
Answer: Olá , veja um exemplo de como você poderia fazer,

$('#my-list li').each(function(index, element) {
  console.log(index + ' : ' + element.innerHTML);
});

Red

Green

Yellow

Blue

Veja se isso ajuda!


how to restrict access to all .txt file in apache except robots.txt?

Question: I am configuring apache2 on debian and would like to allow only robots.txt to be accessed for searching engines, while other .txt files are restricted, I tried to add the followings to .htaccess but no luck:
<Files robots.txt>
Order Allow,Deny
Allow  from All
</Files>
<Files *.txt>
Order Deny,Allow
Deny from All
</Files>
Can anyone help or give me some hints? I am new comer to apache, thanks a lot.
Answer: Use mod_rewrite
RewriteEngine On
RewriteCond %{REQUEST_URI} !/robots\.txt$ [nocase]
RewriteRule \.txt$  -  [forbidden,last]

First, make sure the rewrite engine in enabled.
Next, use a negated-match (!) to apply a conditional to the RewriteRule that excludes any URI's ending in "/robots.txt"
Lastly, if the URI ends in ".txt" then issue a 403 Forbidden.
EDIT: Don't forget the comparison engine is using regex, so you need to escape special characters (ie, .)
Comment: Thanks! It's worked!! Fully appreciated for your help!!!


Is it possible to login to Drupal with a custom user field, instead of username/pass?

Question: I have two websites - One of them is Drupal 7, and the other is a different site (Site #2). In Site #2, within the user tables, is a field called "customid". Each user on Site #2 has a unique, randomly generated 30 character alphanumeric string within their respective "customid" field.
I can pull the value of the "customid" field for the user on Site #2, and use it as an input value in a form post to the Drupal 7 site.
In the Drupal 7 site, I created a custom user field "customid" as well.
Is it possible to make a form post from Site #2 to Drupal 7 - with the "customid" value as an input, and if it matches the "customid" field in the Drupal user table, log them in, else - redirect to the registration page?
We're essentially bypassing the username/password to log them in - I'm trying to log them in via custom user field.
I searched everywhere, and just couldn't find anything where something like this had been discussed. Thanks anyone for your time and help!
UPDATE:
I've tried implementing W.M.'s solution below, however upon attempting to enable the module, I get the white screen of death. Nothing shows up in the logs for the error.
For my custom module, I have two files:
ra_login.module
ra_login.info
Info file:
name = RA Login
description = Check ID and Login if there is a match, else go to Registration Page.
core = 7.x

; Information added by Drupal.org packaging script on 2013-12-16
version = "7.x-1.0"
core = "7.x"
project = "ra_login"
datestamp = "1387203506"

Module File:
<?php

function ra_login_menu()
{
    $items['authenticate-by'] = array( // or any other custom path you choose
        'title' => 'Login by SSO',
        'access callback' => true, // no point in authenticating at this point in code execution
        'page callback' => 'ra_login_function',
        'type' => MENU_CALLBACK,
        );
    return $items;
}

function ra_login_function($CONTACTID)
{
    // post the data to /authenticate-by as json with a parameter / property named CONTACTID holding the CONTACTID
    $postData = file_get_contents('php://input');

    $Data = json_decode($postData);

    $query = new EntityFieldQuery();
    $query->entityCondition('entity_type', 'user')
        ->propertyCondition('uid', 1, '<>')
        // User number 1 should not be able to log in using this method
        ->fieldCondition('field_contactid', 'value', $Data->CONTACTID, '=')
        ->range(0,1);

    $result = $query->execute();

    if (isset($result['user'])) {
        $uid = array_keys($result['user'])[0];
        $account = user_load($uid);
        global $user;
        $user->uid = $uid;
        $user->name = $account->name;
        $user->timezone = $account->timezone;
        user_login_finalize(); // Log user in
        drupal_goto('/user'); // or any other path to redirect logged in users to
    } else {
        drupal_goto('/user/register');
    }

}

Again, for some reason when I try to enable the module, I get a white screen.
Thanks for anyone who can help!
UPDATE:
I turned on errors in php.ini - now instead of the white screen, it shows me the following error:
Parse error: syntax error, unexpected '[' in C:\inetpub\wwwroot\sites\all\modules\ra_login\ra_login.module on line 31

Line 31 is:
$uid = array_keys($result['user'])[0];

Any help is greatly appreciated!
Comment: Make sure logging & display errors is enabled inside php.ini ..  Make sure display errors is on for all types of errors in Drupal admin pages
Comment: W.M - I modified php.ini to show errors - now instead of the white screen, it shows me the following error:

Parse error: syntax error, unexpected '[' in C:\inetpub\wwwroot\sites\all\modules\ra_login\ra_login.module on line 31

Here is line 31:
$uid = array_keys($result['user'])[0];
Comment: What php version are you running?
Comment: I'm currently running PHP version 5.3.28
Comment: Try to change this: $uid = array_keys($result['user'])[0]; into this: $array_keys = array_keys($result['user']); $uid = $array_keys[0]; .. and report back :)
Comment: That seemed to work - the module successfully enabled! How should I test it? Should I make a form post, where the form action is that custom path, and an input value is the customid? Thanks again for all your help on this!!
Comment: Let us [continue this discussion in chat](http://chat.stackexchange.com/rooms/38400/discussion-between-w-m-and-nickythewrench).
Answer: This is the code you need. In the Drupal site create the following module:
Update:
function my_special_login_menu()
{
    $items['authinticate-by-customerid'] = array( // or any other custom path you choose
        'title' => 'Login by customerid',
        'access callback' => true, // no point in authenticating at this point in code execution
        'page callback' => 'my_special_login_function',
        'type' => MENU_CALLBACK,
        );
    return $items;
}

function my_special_login_function($customerid)
{
    // post the data to /authinticate-by-customerid as json with a parameter / property named customerid holding the customerid
    $postData = file_get_contents('php://input');

    $Data = json_decode($postData);

    $query = new EntityFieldQuery();
    $query->entityCondition('entity_type', 'user')
        ->propertyCondition('uid', 1, '<>')
        // User number 1 should not be able to log in using this method
        ->fieldCondition('field_customerid', 'value', $Data->customerid, '=')
        ->range(0,1);

    $result = $query->execute();

    if (isset($result['user'])) {
        $uid = array_keys($result['user'])[0];
        $account = user_load($uid);
        global $user;
        $user->uid = $uid;
        $user->name = $account->name;
        $user->timezone = $account->timezone;
        user_login_finalize(); // Log user in
        drupal_goto('/user'); // or any other path to redirect logged in users to
    } else {
        drupal_goto('/user/register');
    }

}

For this code to work you need Entity API module and you should serve the site over SSL in order to encrypt the data transferred between the two sites.
Comment: Thanks for your time on this. I created the custom module, however when I try to enable it - I get the white screen of death. Can't find where the bug in the code is. Also - would really love to send the customid via form post to drupal, rather than putting it in a URL to the drupal site. Thank you again for any help you can provide!
Comment: @NickyTheWrench Your module file must start with <?php
Comment: I updated my question above, showing how I implemented your code - if maybe you can take a look, that would be great! Thank you again for your time!
Answer: I have no exact solution for your problem, but get idea how to deal with this,
By implementing following algorithm you can achieve.

Requirement
-In Drupal Site you are saving "customid" this id is refer to "Site #2".
-When you store this "customid" in drupal database you need to update password field also and store this "customid" in password field by drupal encryption format.

Now how to login by "customid"
-From site#2 you are sending "customid" to drupal site, write custom module to catch this customid in to drupal site.
-Now check this "customid" into drupal db and fetch user_name of this related "customid".
-Now you have user_name and password(customid), pass this to the drupal login form post function.
-Drupal will check user_name and password if match user will log in.
Answer: function YOUR_MODULE_page_build(&$page) {
  if(isset($_POST['customid'])){
    $customid=$_POST['customid']; //get your id
    $uid=get_uid_based_on_customid($customid);//you function to identify if someone has customid that customid
    if(empty($uid)){
        //if uid not found send user to login
        drupal_goto('/user');
    }else{
        //if uid found load user, authenticat it and redirect to page
        global $user; //global because is same var as the one drupal uses
        $user = user_load($uid);//set used data for you and drupal
        $login_array = array('name' => $user->name);
        user_login_finalize($login_array);//key function, will record user sessions
        drupal_set_message(t('User loged in!'));
        drupal_goto('/');
    }
  }
}

function get_uid_based_on_customid($customid){

  $query = new EntityFieldQuery();
  $query->entityCondition('entity_type', 'user')
  //->propertyCondition('uid', 1, '<>')
  // User number 1 should not be able to log in using this method because he is always admin, pay attention and uncomment when you go to prod
  ->fieldCondition('field_customid', 'value', $customid, '=')
  ->range(0,1);

  $result = $query->execute();

  if(!empty($result)){
    $data=$result['user'];
    reset($data);
    $first_element=current($data);
    $uid = $first_element->uid;

    return $uid;
  }else{
    return '';
  }

}

Comment: I created a custom module with your code, however when I try to enable it - I get a white screen of death. Thank you for your time!
Comment: have you checked the logs? I would gladly help you if you could provide more details. V.M.'s solution is also correct but the fact you got a white screen on both soutions shows a issue on your side.
Comment: Hey Rotari, The log is not showing any errors, unfortunately. I updated my question above to show how I implemented W.M.'s code within a custom module. Maybe you can take a look and see where I am going wrong? Thank you again for any help you can provide.
Comment: Rotari, I turned on errors - and now instead of the white screen, I get this error from your code:

Parse error: syntax error, unexpected ';' in C:\inetpub\wwwroot\sites\all\modules\ra_login2\ra_login2.module on line 16

Here is line 16: drupal_set_message(t('User loged in!');

Any help is greatly appreciated!
Comment: was just a parenthesis missing

code fully updated and tested(see the original answer)(replace YOUR_MODULE and is ready to go)
Comment: Incredible! Updated the code and it worked instantly. Exactly what I wanted - Thank you again!
Answer: Please review this contrib module:
https://www.drupal.org/project/login_custom_field


gsl_histogram_find gives segmentation fault (c++, gsl)

Question: I'm trying to write a simple program code which reads in a histogram via GSL and then finds me the corresponding bin index for a specific point on the x-axis. The code looks like this:
#include <iostream>
#include <string>
#include <cmath>
#include <fstream>
#include <sstream>

#include <gsl/gsl_histogram.h>

int main() {

        gsl_histogram* h_transform;
        size_t h_Bins = 3;
        h_transform = gsl_histogram_alloc(h_Bins);
        double range[4] = { 1.0, 10.0, 100.0, 1000.0 };
        double bins[3] = {7.0, 0.0011, 9e-02};
        gsl_histogram_set_ranges(h_transform, range, 4);
        for(int i=0; i<h_Bins; i++) {
                h_transform->bin[i] = bins[i];
        }

        for (size_t i=0; i<h_Bins; i++) {
                std::cout << "range[" << i << "] = " << h_transform->range[i] << std::endl;
                std::cout << "bin[" << i << "] = " << h_transform->bin[i] << std::endl;
        }
                std::cout << "range[" << h_range_size << "] = " << h_transform->range[h_range_size] << std::endl;

        size_t* h_index;
        double x = 1.1;
        std::cout << "before find" << std::endl;
        gsl_histogram_find(h_transform, x, h_index);
        std::cout << "after h_find" << std::endl;
        std::cout << "h_index = " << *h_index << std::endl;
        std::cout << "get = " << gsl_histogram_get(h_transform, *h_index) << std::endl;

        return 0;
}

When I then compile this code with
g++ -o gslTest gslTest.cpp -lgsl -lgslcblas -lm

and run it with ./gslTest I get the following output:
range[0] = 1
bin[0] = 7
range[1] = 10
bin[1] = 0.0011
range[2] = 100
bin[2] = 0.09
range[3] = 1000
before find
Segmentation fault (core dumped)

Right now I can't wrap my head around this. I got the same error a few days ago, fixed it and now it reappeared and I can't remember the fix...
Hopefully, some of you might be better at solving this than me!
Thanks in advance!
Comment: What is the prototype for `gsl_histogram_find`?  If the last parameter is a size_t pointer, then that is a problem.
Comment: the prototype is int gsl_histogram_find (const gsl histogram * h , double x , size_t * i )
Comment: Well, my answer gives at least one place in your code that is not correct.
Comment: Yes, it does! Thank you very much!
Answer: One glaring issue is this:
size_t* h_index;
double x = 1.1;
std::cout << "before find" << std::endl;
gsl_histogram_find(h_transform, x, h_index);

Assuming that gsl_histogram_find last parameter is a pointer, then you are sending an uninitialized pointer to that function.  There is absolutely nothing gsl_histogram_find can do with that pointer except check if it is NULL, or dereference it, use it, and thus cause havoc.
What you probably should be doing is this:
size_t h_index;
double x = 1.1;
std::cout << "before find" << std::endl;
gsl_histogram_find(h_transform, x, &h_index);

When a function wants a pointer, it almost always means that the function wants the address of an existing entity.  Please see this answer with respect to passing pointers to functions and what it really means.
Comment: Oh dear lord, you are right! I'm just at the beginning of learning proper c++ coding and this still gets me at times... Thank you very much, that probably spared me another hour or so looking at that code in complete bewilderment!


Modification of Sigmoid function

Question: I need to model my data into a function like shown in the following picture. But how I can do this mathematically?  Is there any similar function to model data that should increase on smaller values fast and converge to 1 relatively slow?
Comment: complementary log-log function might work
Comment: The sigmoid regression allows for more parameters than the usual 2. Four- to Five-parameter logistic regression seems quite common, and would be able to model that behavior.
Answer: Try the Gompertz function
The basic formula is $ y = e^{-e^{-x}} $ and looks like this:
Keep in mind that the growth at the start is doubly exponential, whereas the decay at the end is singly exponential, which may still be too fast for your purposes (being of the same order as a logistic function).

Modification of Sigmoid function


How can I create unique path alias for image styles?

Question: image_style_url returns the public url of an image in the files/styles folder. Is it possible to create alias to that? What I want is the following:
Call image_style_url from the image style and the uri, which gives me typical public url /sites/default/files/style/[style_name]/path/to/image/[image_file_name]. I want to serve simple url like /image/[randomized_number] to the user that will internally alias to the aforementioned public url. This is similar to asking what pathauto module does for /node/[nid], but for image styles.
Note that I do not want custom url to individual images per se, but rather a way to programmatically create unique unpredictable url aliases for image styles.
Comment: Interesting question. I don't have a solution. Perhaps trying to alter the stream wrapper(s) for the styles you want to have unique urls could work?
Comment: Shouldn't url alias work after the actual url is created? altering stream wrappers feels like hacking the core.
Comment: image style urls are provided by the image styles module, and i believe a stream wrapper ... it has nothing todo with aliases so far as i know. you can think of it like a system path (that generates a custom image) -- you have to alter the system path to do this somehow. Offhand I thought maybe streamwrappers would be the way to go -- maybe you can use `hook_menu_alter` ... dunno.
Comment: the problem with using aliases is that you have to boostrap Drupal to serve those images. I think setting up the web server would be a better choice...
Answer: Is a little difficult because image_style_url() uses internally image_style_path() who creates the path /sites/default/files/style/[style_name]/path/to/...
Maybe you can use File (Field) Paths module:

The File (Field) Paths module extends the default functionality of Drupal's core Upload module, the FileField module and many other File Upload modules by adding the ability to use node tokens in destination paths and filenames.
In simple terms, File (Field) Paths allows you to automatically sort and rename your uploaded files using token based replacement patterns to maintain a nice clean filesystem.

If you only want to change the path alias you can use hook_node_insert() or hook_insert()
/**
 * Implements hook_insert().
 */
function mymodule_node_insert($node) {
    // Set the URL alias
    if (empty($node->path['alias'])) {
        $node->path['alias'] = 'image/' . my_random_function();
    }
}

Comment: Destination paths is not the problem. Media (and media browser) module already handles the file organization etc pretty well. The problem is about getting alias to that.
Comment: Please take a look to the new answer.
Comment: This is possibly almost correct, but it works for nodes, not files, I guess.
Answer: My answer below assumes that you want to display the image itself and not an image as the main content on a Drupal page (for this you may use Views module).

I am proposing using the File Entity Paths module. From the module:

It does the same, as Filefield Paths, but focus to the file entity, not to the parent entity...

So you create an alias (let's call it IMAGE_ALIAS) to the file without needing the filename or extension (the MIME type is saved with the file upload) and then you can do these:

Create a symlink to sites/default/files/YOUR_IMAGES_PATH so you end up with www.example.com/IMAGE_ALIAS (more can be found at https://www.drupal.org/node/53705)

Do a rewrite on Drupal root's .htaccess (more can be found at https://www.drupal.org/node/53705)
 RewriteEngine On
 RewriteCond %{REQUEST_FILENAME} !-f
 RewriteCond %{REQUEST_FILENAME} !-d
 RewriteRule ^(.*)$ /sites/%{HTTP_HOST}/files/$1 [L]

Use another folder instead of common sites/default/files eg files (on root).

Use File Aliases module that does all the above.
Comment: The question specifically mentions `image_style_url`. I call this extensively in my theme. Can you please elaborate on how to create alias for styles? Or the alias for the original path will carry over like `/styles/[style-name]/[alias]`?
Comment: About your 4th point, doesn't file alias do this field specific? The alias will be only created when used in an image field, and not for all images?
Comment: No it will not carry over the styles/[style-name]/[alias] for node images but you can also create a symlink to that path. But the custom image path will be the same either for entity file or imagefield.
Answer: Have you tried File Aliases?

The File Aliases module allows you to use token customizable aliases
  for your uploaded files, giving you the ability to keep your file
  system organized as per usual while providing clean looking paths
  (i.e., no more '/sites/default/files/').

I've not tested it nor use it, but it seems to be the right module for your problem.
Comment: Yes, I have tried. That is almost an old (and a buggy) solution to what media and media browser module can do in the first place. This is about creating aliases, not placing files in different (possibly organized) places.
Comment: @RatulSaha In the basic question you are asking about creating Aliases not about saving files on different Folders.
Comment: Yes, creating aliases is the only concern. Saving files etc has already been taken care of by media and media browser, in my case. Creating alias and serving image files by that alias seems not to have any direct solution. File Aliases only provide this for images in a field, not images overall.
Answer: There's a hook for altering the file url when it's being created:

hook_file_url_alter

You should be able to call that hook and then use the path functions to create an alias for a style if it doesn't exist.
https://api.drupal.org/api/drupal/includes%21path.inc/7
Comment: That solves creating the alias. How will visiting the alias lead to actual file?
Comment: @RatulSaha Sorry for the (very, super) late response, but you would use hook_menu to create a new function that loads the path. You can look at the way the core file.module does it.


Quick Proof Verification: Showing Matrix is Nonsingular.

Question: Hello everyone I just want to verify if my proof is correct as I'm very worried that it's not: Thanks so much.
Question:
Let $A$ be a square matrix and let $\lambda$ be a complex number for which $|\lambda| >\|A\|$, where $\|\cdot \|$ denotes some induced matrix norm.  Show that the matrix $\lambda I-A$ is nonsingular and that
$({\lambda I-A})^{-1}= \frac{1}{\lambda}\sum_{k=0}^{\infty}\frac{1}{\lambda^{k}}A^k$
Proof:
Since $\|A\| \geq 0$ and $|\lambda| >\|A\|$ implies $\lambda$ implies $\lambda\neq 0$
$\|\frac{1}{\lambda}A\|<1$
$\sum_{k=0}^{\infty}\frac{1}{\lambda^{k}}A^k$ converges.
Call $C=\frac{1}{\lambda}\sum_{k=0}^{\infty}\frac{1}{\lambda^{k}}A^k$
Now:
$({\lambda I-A})C={\lambda}C-AC
=\sum_{k=0}^{\infty}\frac{1}{\lambda^{k}}A^k
-\sum_{k=0}^{\infty}\frac{1}{\lambda^{k+1}}A^{k+1}=I$.
Obviously I would also have to show that
$C({\lambda I-A})=I$ as well, but it reduces to the same two series subtracted from each other.
The problem I'm having is understanding why the two series subtracted above=Identity.  I know that that they should., I'm just not sure why exactly.  Any help would be much appreciated.  Thank you.
Answer: \begin{align}
&\sum_{k=0}^\infty \frac{1}{\lambda^k}A^k - \sum_{k=0}^\infty \frac{1}{\lambda^{k+1}}A^{k+1}\\
&= \left(I+ \sum_{k=1}^\infty \frac{1}{\lambda^k}A^k\right) - \sum_{l=1}^\infty \frac{1}{\lambda^{l}}A^{l}\\
&=I+\left( \sum_{k=1}^\infty \frac{1}{\lambda^k}A^k- \sum_{l=1}^\infty \frac{1}{\lambda^{l}}A^{l}\right)\\
\\&=I
\end{align}
where I have let $l=k+1$.
Comment: I see. Thank you.  I just worked it out now by myself too.
Answer: $\sum_{k=0}^{\infty}B^k-\sum_{k=0}^{\infty}B^{k+1}=$
$=I+B+B^2+B^3 +...-(B+B^2+B^3+...)=I$.
Answer: $$\sum_{k=0}^\infty\lambda^{-(k+1)}A^{k+1}
=\sum_{k=1}^\infty\lambda^{-k}A^k=-I+\sum_{k=0}^\infty \lambda^{-k}A^k$$
etc. Or
\begin{align}
\sum_{k=0}^\infty \lambda^{-k}A^k-\sum_{k=0}^\infty \lambda^{-(k+1)}A^{k+1}&=
I+\lambda^{-1}A+\lambda^{-2}A^2+\lambda^{-3}A^3+\cdots\\
&{ }-(\lambda^{-1}A+\lambda^{-2}A^2+\lambda^{-3}A^3+\cdots)\\
&=I.
\end{align}
Comment: Thank you.  I see this now! Very helpful


Is there a way to print upto an even result in a for loop?

Question: So I have a for loop that outputs something like "1,2,3, 4, 5,6...". Is there way to stop the loop lets say say at the last even number before the loop ends. So lets say if its "1,2, 3, 4, 5" , the loop stops when its at 4?
Comment: This does not sound like your real question.
Comment: Where is the code you are using?
Comment: This seems like a part of the solution for a larger problem. It will help if you define the original problem that you are trying to solve.
Answer: <code>$n = 5;

$m = $n - ($n % 2); // get the largest even number smaller than $n

for ($i = 1; $i <= $m; $i++)
  echo $i . ' ';
</code>
Answer: <code>$limit = 5;

$limit -= $limit % 2;

for ($i = 0; $i <= $limit; $i++)
{
  // loop body
}
</code>


Extends a class(which implements interface) and implements same interface doesn't require method defination in class?

Question: /Class C has implemented interface A but has not defined go() method is it correct ?/
interface A { void go();}
Class B implements A { void go(){#Some code here}}
Class C extends B implements C {}

Comment: class C extends B implements `C{}` where is `C interface`
Comment: Can we assume that `Class C` should have `implements A`?
Comment: I am getting this in eclipse "Cycle detected: the type C cannot extend/implement itself or one of its own member types"
Answer: It is correct. However, a method in an interface is public abstract even though you don't define it like that.
The implementing class method must be public as well, because you cannot reduce method visibility. So, the method in class B should be public.
Answer: Remember that a C is a B and therefore has the method definition from B. If you really want this to work, you must create an Abstract Base Class for both B and C.
Answer: Yes, C extends B which has implemented go, therefore C inherits this implementation.
Answer: It is correct. Since it has already inherited the method from B. In fact, the implements A for class C is redundant!


Different level of spacing between rows on different lines while converting a csv file to txt file using python

Question: I have to convert a .csv file into .txt file which I did and I have the following code.
text_list = []

csv_file = 'test.csv'
with open(csv_file,"r") as infile:
    for line in infile:
        line = line.split(",", 2)
        text_list.append("\t".join(line))

txt_file = 'test.txt'
with open(txt_file, 'w') as outfile:
    for line in text_list:
        outfile.write(" " + line)
    outfile.close

But the problem is,
CSV file:
phi,Z,T
0,0,0
10.000005,1.2,3000.00
20.000005,2.4,6000.00

Required txt file:
phi        Z    T
0          0    0
10.000005  1.2  3000.00
20.000005  2.4  6000.00

Text file I have with the above mentioned code:
phi    Z    T
0    0    0
10.000005    1.2    3000.00
20.000005    2.4    6000.00

Thank you
Answer: You can use the string method ljust to add spaces to your string so that it has a certain length. Therefore, you read the input file line by line, split each line on commas and append that to text_list, which results in a list of lists with each word of each row.
Then we compute the number of columns num_cols from the length of the first row. Then we calculate the length of the longest word / number in each column with a nested list comprehension. We use this to ljust every word according to the max length of the respective column.
text_list = []

csv_file = 'test.csv'
with open(csv_file,"r") as infile:
    for line in infile:
        line = line.rstrip().split(",", 2)
        text_list.append(line)

num_cols = len(text_list[0])
max_lengths = [max([len(line[i]) for line in text_list]) for i in range(num_cols)]

txt_file = 'test.txt'
with open(txt_file, 'w') as outfile:
    for line in text_list:
        outfile.write('\t'.join([word.ljust(max_lengths[i]) for i, word in enumerate(line)]) + '\n')

Comment: I understand your idea here. But it says  ```AttributeError: '_io.TextIOWrapper' object has no attribute 'split'``` on line, ```for line in infile.split('\n')``` @sunnytown
Comment: My bad, I edited the code, now it should work. Let me know.


How do I repack an existing site into Open Source repo with bundled content and configuration?

Question: I have been tasked to repack an existing live Drupal 7 site, that will go out of commission, to make it available as Open Source on Github so anyone interested may find some use of it.
This will require that the repository comes with a database dump containing an example configuration and content.
What I need to do is to first anonymize the database from usernames/passwords, and also remove any not needed old revisions of existing content to compact the dump.

Is there any best practice strategies for how this can be done as simple as possible, and in the documentation provide a simple step-by-step guide on how to install it using the database dump?

Please note: While a Drupal Distribution would be optimal, in this case the wast amount of extra work, and testing, required is not possible.
Comment: That's what distributions/install profiles are typically used for
Comment: For this use case that is overdoing it, would involve a lot more work and, not the least, testing than it's worth.
Comment: Yeah sorry I skipped over the 2nd to last paragraph somehow which made the question seem different than it is. It's hard to give accurate advice for this at it depends on what you've installed/configured - it might make more sense to start with a question like "what sensitive information should I strip from a core install before distributing a copy of the code and database?" and then trying to work out the same thing for the contrib/custom modules you've got. For something like "old versions of content", that can only really be answered by someone who knows what content can be deleted
Comment: Great point thanks. I will update with that in mind. Just need to think it through a bit first.
Comment: There, hopefully this rewrite makes my task objective clearer.
Answer: You can anonymize some content using drush and the sql-sanitize command found in Drush by default:
https://drushcommands.com/drush-8x/sql/sql-sanitize/
If that doesn't clean up enough of your content to be suitable for Open Source release, you can use the underlying hook drush exposes for this task and implement it for your site as seen in this blog post, https://www.codeenigma.com/support/blog/doing-more-drush-sql-sanitize, found on google. An excerpt of the additional sanitation examples you could do from the blog post are:
/**
* Implements hook_drush_sql_sync_sanitize.
*/
function my_module_drush_sql_sync_sanitize($source) {
  // The query to sanitise field_data_field_profile_linkedin_page
  $linkedin_page_query = "UPDATE field_data_field_profile_linkedin_page SET field_profile_linkedin_page_value = CONCAT('http://uk.linkedin.com/user-name/', FLOOR(100000 + (RAND() * 900000)));";

  // The query to sanitise field_revision_field_profile_linkedin_page
  $linkedin_page_query .= "UPDATE field_revision_field_profile_linkedin_page SET field_profile_linkedin_page_value = CONCAT('http://uk.linkedin.com/user-name/', FLOOR(100000 + (RAND() * 900000)));";

  drush_sql_register_post_sync_op('sanitise_linkedin_page', dt('Sanitise field_profile_linkedin_page'), $linkedin_page_query);

  // The query to sanitise field_data_field_profile_telephone_number
  $telephone_number_query = "UPDATE field_data_field_profile_telephone_number SET field_profile_telephone_number_value = CONCAT('+44', FLOOR(1000000000 + (RAND() * 100000000)));";

  // The query to sanitise field_data_field_profile_telephone_number
  $telephone_number_query .= "UPDATE field_revision_field_profile_telephone_number SET field_profile_telephone_number_value = CONCAT('+44', FLOOR(1000000000 + (RAND() * 100000000)));";

  drush_sql_register_post_sync_op('sanitise_telephone_number', dt('Sanitise field_profile_telephone_number'), $telephone_number_query);

  // The query to sanitise field_data_field_profile_twitter_handle
  $twitter_query = "UPDATE field_data_field_profile_twitter_handle SET field_profile_twitter_handle_value =  SUBSTRING(MD5(RAND()) FROM 1 FOR 8);";

  // The query to sanitise field_revision_field_profile_twitter_handle
  $twitter_query .= "UPDATE field_revision_field_profile_twitter_handle SET field_profile_twitter_handle_value =  SUBSTRING(MD5(RAND()) FROM 1 FOR 8);";

  drush_sql_register_post_sync_op('sanitise_twitter_handle', dt('Sanitise field_profile_twitter_handle'), $twitter_query);
}

If you dont want to attempt to delete revisions manually yourself, in packing the site for git (make a backup first), I would look at the following module: https://www.drupal.org/project/field_sql_norevisions
Once the above steps are done. I would simply provide a drush archive-dump (or the contents thereof) in a GIT repo and instruct users to use Drush and the provided zip (or place the contents of the git repo into a zip) to use drush archive-restore to install the site. The only gotcha with this approach is to assure they use the same database engine on their system as the live site expects (that I can think of).
Comment: Thank you @tenken, your suggestion sounds very much as what I am looking for and will try it when I get started on this in a few days. I'll let know how it turned out.


Need a Intuitive thinking for the proof of Mean value theorem for scalar field

Question: Ok so the proof is laid out on my book but I'm genuinely struggling to have a geometrical/Intuitive thinking to this particular proof. I badly need help with it.
So here is the statement of the proof (PLEASE NOTE THAT $D_u$ in this case implies directional derivative in the direction of the unit vector $u$):
Let $f: S\to \mathbb R$ be a scalar field. Let $a\in S$ and where $S\subseteq \mathbb R^n$
So let $u$ be a unit vector and $u\in\mathbb{R}^n$ and $a + ut \in S$ for all $0\leq t \leq 1.$ Suppose $D_uf(a)$ exists for all $a + ut$ where $0 \leq t \leq 1$ then there exist a $\theta$ such that $0<\theta<1$ and
$$f(a+u)-f(a) = D_uf(z), \text{where }z= a + u\theta$$
Now I'm not gonna write the proof that is written in my book because I fairly understood the steps well. I don't understand where this $z= a + u\theta$ came or what does it even imply or how it looks geometrically.
Comment: Anyone who is more familiar with the formatting in this website is more than welcome to edit my post to make it look more presentable and edit the notation for better understanding. Thank you!
Comment: I've modified your first line of equations. Look up LaTex math symbols if you need help with the rest
Comment: Here's a [MathJax tutorial](https://math.meta.stackexchange.com/questions/5020/mathjax-basic-tutorial-and-quick-reference)
Comment: $a+u\theta$ is just a point on the segment joining $a$ and $a+u$ (if we identify the vectors with heir endpoints.)
Comment: Thank you so much!!!
Answer: Let $f: S\to \mathbb R$ be a scalar field. Let $a\in S$ and where $S\subseteq \mathbb R^n$.

So let $u$ be a unit vector and $u\in\mathbb{R}^n$ and $a + ut \in S$ for all $0\leq t \leq 1.$

$S$ is some region in $\mathbb{R^n}$; $a$ is within $S$ such that all points up to $1$ unit away in the $\arg(u)$ direction are also in $S$. We define $A$ as the segment leading from $a$ to $a+ut$; i.e. $A:=\{ a+ut | t\in[0,1]\}$.

Suppose $D_uf(a)$ exists for all $a + ut$ where $0 \leq t \leq 1$ then there exists a $\theta$ such that $0<\theta<1$ and
$$f(a+u)-f(a) = D_uf(z), \text{where }z= a + u\theta$$

$z$ lies in $A$, as $z=a+u\theta$ for some $\theta\in[0,1]$. So this is saying: for some point on this line $A$, there exists a point $z\in A$ such that the derivative of $S$ at $z$ is equal to the difference of the values of $f$ at the endpoints of $A$; the "mean value" of $f$ on $A$.
This is notated a little confusingly; I'm not a fan of using $t$ and $\theta$ to parametrize the same thing. Also $a,u,z$ seem to have no clear pattern.
Comment: God bless you!!! everything is completely clear now! thank you so much seriously!


Object array in javascript

Question: Very simple question I guess but not sure what's the best approach to achieve this.
I want to create an object of multiple projects. I should do something like this:
var projects = {};
projects.url = "www.example.com";
projects.description = "Project Description";

But how do I use this projects object for more than one project?
Edit: I though about using arrays as some of the answers suggest but is there any way to avoid arrays?
Comment: Why would you want to avoid arrays? Whenever you have *multiple* somethings, arrays/lists/etc are a natural way to hold them.
Comment: @RKour Seriously! Just use an array! They fit your purpose better than objects would.
Comment: Why don't you want to use an array?
Comment: I read somewhere that arrays are more expensive than objects so I was just wondering.
Comment: You are going to the wrong shop if they charge you more for arrays than objects. Actually, arrays are just types of objects, and not going to be the bottleneck in whatever you are developing.
Comment: ok, I'm convinced - Thanks Guys
Comment: @RKour make sure you close the question by checking the green tick across Brad's answer.
Answer: Have an array of project objects.
var projects = [
    {
        url: 'http://www.example.com',
        description: 'Project Description'
    },
    {
        url: 'http://www.example2.com',
        description: 'Project 2'
    }
];

Comment: @RKour, Why would you want to avoid an array?  An array is exactly what you want...
Comment: Thanks Brad - Is there any possibility to avoid arrays?
Answer: Create a project class:
var Project = function() {};

Project.prototype = {
    url: "www.example.com",
    description: "Project Description"
};

Then you can create multiple instances of these objects:
var proj1 = new Project(),
    proj2 = new Project();

Comment: Very good alternative if you must not use arrays (could be a trick question ) but Brad's answer serves my purpose better. +1.
Answer: The best answer, is to use an array, but if you insist on trying to hammer a square peg into a round hole, you can use objects like this...
DISCLAIMER: This code is ugly as your mother in law, don't use it
var projects = {}

projects.project1 = {
  url = "www.example.com";
  description = "Project Description";
}

projects.project2 = {
  url = "www.example2.com";
  description = "Project2 Description";
}

And select like this...
for(i=0;i<2;i++){
  console.log(projects["project"+i].description)
}

EDIT: Some potentially useful code...
The only time I can imagine it being useful to use objects instead of arrays for something like this, is if your projects have unique ID's and you need to look them up a lot out of sequence. There is an advantage in listing the projects, using their ID as the key, so that if you know the ID, you can select the object directly, rather than looping through an array to find the one you want...
projects = {
  projAcHRx:{ ... },
  projFhv5R:{ ... }
}

// select project: projAcHRx
projects.projAcHRx // <~ very simple lookup if you know the ID

Rather than
projects = [
  { id:'projAcHRx',
    ... },
  { id:'projFhv5R',
    ... },
]

// select project: projAcHRx
for(i=projects.length;i;i--){
  if(projects[i] == 'projAcHRx'){
    var selected = projects[i] // <~ hideously complex selection!
  }
}

Comment: Please, don't even suggest this.  Someone will inevitably come by this question in the future and copy and paste it into their project.
Comment: Thanks Billy - I afraid it's not very neat. I'll go with arrays instead!
Comment: Second what Brad said - if you have to put that kind of warning in the front of it, it's not worth sharing.
Comment: I disagree, I think the forum is a place for discussion, so hopefully people will read the comments etc... before copy/pasting. If people are going to drive by and randomly copy/paste code without reading the context, their work is doomed to be sloppy, and not our responsibility to improve. On a related note, I discovered there is a video sharing service (I think vine) which limits you to 6 second videos - what is the world coming to. I used to read books to find out this stuff - not copy/paste without reading a paragraph!

Object array in javascript


Proof Verification: $4x^2+6xy+4y^2>0$ unless both $x$ and $y$ are equal to $0$

Question: This is a problem from Spivak's Calculus 4th ed., Chapter 1, Problem 16(b).

Using the fact that
  $x^2 + 2xy + y^2 = (x + y)^2 > 0$,
  show that $4x^2 + 6xy + 4y^2 >0$ unless $x$ and $y$ are both $0$.

This is my proof:
Firstly, as any non-zero number $a$ satisfies the inequality $a^2>0$ (I have proved that already), $(x+y)^2>0 \Rightarrow 3(x+y)^2$, $x^2>0$ and $y^2>0$
$\therefore 3(x+y)^2+x^2+y^2=4x^2+6xy+4y^2>0$
Does this make sense?
Comment: It makes lot of sense: it is even correct. Nice!
Comment: Cute. Most people would complete the square of $4x^2+6xy$ to obtain $4x^2+6xy+4y^2=(2x+3y/2)^2+7y^2/4,$ or would use the Quadratic Formula to show that  $4x^2+6xy+4y^2=0$ implies both $x= (-6y\pm \sqrt {-28y^2})/8$ and $y=(-6x\pm \sqrt {-28x^2})/8.$
Answer: It is almost correct. The only flaw lies in the fact that you should assume only that $x\neq0$ or $y\neq0$. Therefore, you cannot say that both numbers $x^2$ and $y^2$ are greater than $0$. But you can say that their sum is greater than $0$, and that is quite enough for the proof.
Comment: That really confused me, so maybe I missed something: if $\;x,y\neq0\;$ then *by all means* $\;x^2,\,y^2>0\;$ ...! Of course, I assume all the way $\;x,y\in\Bbb R\;$ .
Comment: What the OP was trying to prove was that if $x\neq0$ **or** $y\neq0$, then $4x^2+6xy+4^2>0$. But **one** of the numbers $x$ and $y$ *can* be equal to $0$.
Comment: Carlos Where did you deduce that "or" from the OP?
Comment: From "unless $x$ and $y$ are both $0$". The opposite of this consists in asserting that $x\neq0$ or $y\neq0$.
Comment: One of them can indeed be equal to $0$.
Answer: More generally,
since
$\begin{array}\\
ax^2+2bxy+ay^2
&=a(x^2+y^2)+b(x^2+2xy+y^2)-b(x^2+y^2)\\
&=(a-b)(x^2+y^2)+b(x+y)^2\\
\end{array}
$
if
$a > b$ then
$ax^2+2bxy+ay^2 \ge 0$
with equality if and only if
$x = y = 0$.
Your case is
$a=4, b=3$.
You can handle the more general case of
$ax^2+2bxy+cy^2$
by looking at how
the quadratic formula
is derived.


dataTables temporarily disable sorting

Question: I have a sortable dataTable filled with data where you can edit the data when you click on it.
Before clicking it looks like this:
<input type='text' value='...' size=3 disabled>

And when clicking:
$('#table1 tbody').on( 'click', 'tr', function ()
{
    var olddata = "";
    olddata = table.cell( this, 3 ).data();
    table.cell( this, 3 ).data( "<input type='text' value='" + olddata + "' size=3 style='background-color:white'>" );
});

However when you click on a row it changes position since it now also contains extra html code , and if this was the active ordering column it ends up at the bottom or top.
I sort using:
var columnSet =
[
    ...
    {title: "Mycolumn", width:"1%", "type": "string"},
    ...
];

So my question is, is it possible to temporarily disable sorting in the whole table when a row is clicked, and then enable again when done editing, or alternatively sort based on  value attribute?
Comment: For datatable, you need to mention whether a particular column should be sortable or not. You can set all the columns to false in case you dont want sorting for any columns. The property name is "aoColumns".
Comment: Yes but i want to be able to sort them, just not when the user clicks to edit a row.
Comment: Its difficult to change the sorting the behavior of the datatable as you will have to reinitialize the datatable. Suggestion would be not to do inline edit and redirect the user to different page or use a bootstrap modal to edit the row if you are using bootstrap.
Answer: Ok I managed to solve this using a small trick
var columnSet =
[
    ...
    {title: "Mycolumn", width:"1%", "type": "html"},
    ...
];

using type: html removes everything between "<" and ">" however this left me with dataTables trying to sort an empty cell since
<input value="...">

only has content between "<" and ">"
I solved this using:
olddata = $(table.cell( row, 5 ).data()).attr("value");
table.cell( row, 5 ).data( "<input type='text' value='" + olddata + "' size=25 style='background-color:white'>
" + olddata + "
" );

The p element will not be seen but datatable can see it and use it for sorting so the row does not change position! This solution was even better than disabling sorting since you can now still sort the table

dataTables temporarily disable sorting


Examples of the Pigeonhole Principle

Question: As most of you might know, the Pigeonhole Principle basically states that

If $n$ items are put into $m$ containers, with $n>m$, then at least one container must contain more than one item

It always surprises me how this trivial - and at the same time powerful - idea might be the key in order to solve extremely complicated math olympiad-problems...
Quick and beautiful solutions are characteristic of pigeonhole problems, which are often a three-part process

Recognize that the problem requires the Pigeonhole Principle
Figure out what the pigeons and what the pigeonholes might be
After applying the pigeonhole principle, there is often more work to be done

I'll illustrate this with an example I've always liked...

(Example-)Problem: Given a $n\times n$ square, prove that if $5$ points are placed randomly inside the square, then two of them are at most $\frac{n}{\sqrt2}$ units apart.

Step 1: This problem can be solved with the Pigeonhole Principle
Step 2: We divide the $n\times n$ square into four $\frac{n}{2}\times\frac{n}{2}$ squares (pigeonholes). Consequently, at least two points (pigeons) are inside the same $\frac{n}{2}\times\frac{n}{2}$ square.
Step 3: The maximal distance between two points in an $\frac{n}{2}\times\frac{n}{2}$ square is the diagonal, which has the length $\frac{n}{\sqrt2}\qquad\square$
Another problem which can be solved with the Pigeonprinciple is the following:

IMO $1972/1$

Prove that from a set of ten distinct two-digit numbers (in the decimal system), it is possible to select two disjoint subsets whose members have the same sum.

At this point, you might have noticed how useful the Pigeonhole Principle can be, if you know how to recognize and use it.

Question: I would like to work on this amazing principle with my students for a week and was, therefore, gathering problems related to the Pigeonhole Principle with beautiful solutions.
  Could you suggest some more?
Comment: Nice question +1
Answer: Here's some list of problems that I know (I don't know references at all)

Choose 51 numbers from $\{1, 2, 3, \dots, 100\}$, then at least two of them are coprime.
Choose 51 numbers from $\{1, 2, 3, \dots, 100\}$, then one of them divides the other one.
For any irrational $x$, there exists infinitely many integers $p, q$ such that $|x-p/q| < 1/q^{2}$. (Dirichlet's approximation theorem)

You can find other examples here.
Answer: How about the division problem?
let $A \subseteq$ $\{1,2,...,2n\}, |A|=n+1$
show that there must be two elements $x, y$ $\in A$ s.t $  x\neq y $ and $x$ divides $y$.
Proof:
Any natural number can be denoted as: $N=2^k * m$, where $m$ is some odd number.
Since there are only $n$ odd numbers at most in $A$, there must be at least two numbers $a, b$ for which the greatest odd divisor $m$ is the same via PHP, hence one of them must divide the other.
Hope it helps!
Answer: Here are a few of my personal favourites:

The Erdos-Szekeres theorem is of course a classical example
Call $S = \{a_1,...,a_{|S|}\} \subset \{1,2,...,n\}$ a Sidon set if all the pairwise sums $a_i+ a_j, i \leq j$ are distinct. Then $|S| = O(n^{1/2})$

The proof is very simple. $S$ is equivalently a Sidon set if the ${|S| \choose 2}$ pairwise differences are distinct. These can only take values from $1$ to $n-1$. So by the pigeonhole principle, ${|S| \choose 2} \leq n-1 \implies |S| = O(n^{1/2})$. (The same proof can be replicated for the pairwise sums, but the differences give a better constant).
The beautiful thing about this proof is that the upper bound is very close to tight - there exist Sidon sets with size close to $n^{1/2}$.

Any prime $p$ not equal to $2$ or $5$ divides infinitely many of the integers, $11, 111, 1111, ...$

By the pigeonhole principle, infinitely many of them are in the same residue class mod $p$, and their pairwise differences are of the form $11...10..0$ Since $p$ is coprime to $10$, $p$ must divide the initial string of $1$'s.
Answer: Here's some relatively challenging problems, where the 'pigeonhole part' isn't always immediately obvious.
Show that for any $x\in\mathbb{Z}^+ $, there exists a Fibonacci Number that is divisible by $x$. (It may be helpful to consider a few cases first, such as $10^{10}$, then to generalize the proof. This is also a generalisation of Sim000's 3rd problem.)
There are $n$ distinct positive integers $a_1,a_2,\dots, a_n$ For any seqeuence $b_1,b_2,\dots, b_n$, where $b_i\in \{-1,0,1\}$ for $1\leq i\leq n$ and  the terms are not all zero, $n^3\nmid a_1b_1+a_2b_2+\dots + a_nb_n$. Find the maximum possible value of $n$.
A student, who has $11$ weeks to prepare for an upcoming Olympiad, decides to sit one practice exam every day. However, due to time constraints, the student cannot sit more than $12$ practice exams in any $7$-day period. Prove that there are consecutive days during which the student sits exactly 21 practice exams.
The prime factorisations of $n+1$ positive integers $x_1,x_2,\dots, x_{n+1}$ only involve $n$ primes $p_1,\dots, p_n$. Prove that there exists a nonempty subset of $\{x_1,\dots, x_{n+1}\}$  whose elements multiply to a perfect square.
Suppose real numbers $x_1,\dots, x_n$ satisfy $\sum x_i^2=1$. Prove for integers $k\geq 2$, there exists integers $y_1,\dots, y_n$ not all zero such that $|y_i|\leq k-1$ for $1\leq i\leq n$ and $$\Biggl |\sum x_iy_i\Biggl| \leq \frac{\sqrt{n}(k-1)}{k^n-1}$$
Answer: There is a series of 3 articles on conception, identification and application of Pigeon-hole Principle See here.
The first article discusses about $k-to-1$ functions and next articles build upon it.
There is an interesting problem about finding minimum number of devotees in a temple, just by seeing the number of footwears outside the entrance.
Please note, I am the author of the blog.
Answer: The  following  problem is stated in Proofs from THE BOOK:

Paul  Erdős     attributes    the following  nice   application of  the  pigeon-hole principle to Andre Vázsonyi and Marta Sved:

Claim. Suppose we are given $n$ integers $a_1,\ldots, a_n$, which need not be distinct. Then there is always a set of consecutive numbers $a_{k+1},a_{k+2},\ldots,a_l$ whose sum   $\sum_{i=k+1}^la_i$ is a multiple of $n$.
Comment: This book is a great source of mathemtical beuty and attraction !! There are some great discussions in this book (in many branchs of mathematics) that I think can attract anyone!
Answer: There are great applications of pigeonhole principle (PHP) in some olympiad problems and some theorems, both in finite and infinite structures. I'll mention three of them here and some hints about solutions. Hope you'll find them useful:
1-Given five lattice points on the plane, we connect any two of them by drawing a line between them. so we draw 10 lines, between these points. Prove that there exist another lattice point on at least one of these lines.(By "lattice point" I mean points of the plane with integer coordinates)
(Hint: integer coordinates can be odd or even, and you are given 5 points! now look at the middle of lines.)
2- for any positive integer n, prove that there exist a multiple of n which its presentation in base 10 has only 0 and 1.
(Hint : consider a sequence 1,11,111,1111,... . look at this sequence modulo n and by PHP find the solution in the form of x-y where x and y are in this sequence.)
3- for any positive integer n, prove there exist a Fibonacci number divisible by $10^n$.
(Hint : again look at the sequence of fibonacci numbers modulo $10^n$ and try to prove that this sequence is a periodic sequence.)

Examples of the Pigeonhole Principle


Como retornar dados em formato JSON de uma WebAPI .net

Question: Estou fazendo uma chamada dentro da API para que me retorne dados de consumidor, porém gostaria de saber como retornar esses dados pro cliente em formato JSON.
Meu controller:
<code>[System.Web.Http.HttpGet]
public async Task<ActionResult> GetConsumidor()
{
  ConsumidorDAO consumidor = new ConsumidorDAO();
  string dadosConsumidor = consumidor.getDados();

  return (dadosConsumidor);
}
</code>
Eu faço uma consulta no banco de dados para trazer alguns dados de um consumidor como nome, sobrenome, etc.
<code>public string getDados()
{
  OracleCommand lOracleCommand = lOracleConnection.CreateCommand();
  String query;
  string nome = "";

  try
  {
    query = "select nome " +
      "from crd.cliente " +
      "where cpf_cgc = 'xxxxxxx'" +
      "  and empresa_origem = '367' ";

    lOracleCommand.CommandText = query;
    OracleDataReader reader = lOracleCommand.ExecuteReader();
    while (reader.Read())
    {
      nome = reader["nome"].ToString();
    }
  }
  catch (Exception lException)
  {
    _status += lException.Message + "\n";
    lOracleCommand.Connection.Close();
  }

  return nome;
}
</code>
Comment: O cliente seria o que exatamente? por exemplo, você iria salvar os dados em um arquivo de texto?
Comment: Eu so retorno os dados em formado JSON com as informaçoes
Answer: JSON é uma representação de objeto no formato Javascript (Javascript Object Notation).
Como você está retornando somente uma string, isso não se encaixa como um objeto, objetos são formados por zero ou mais duplas de chave e valor.
Se você insiste em retornar um JSON, pode fazer um objeto com uma propriedade que tem seu valor como string e serializa-lo no retorno da API, segue um exemplo.
Exemplo:
<code>//outros using
using System.Web.Script.Serialization;

public class ResultadoObjeto
{
    public string Propriedade { get; set; }
}

[System.Web.Http.HttpGet]
public async Task<string> GetConsumidor()
{
   ConsumidorDAO consumidor = new ConsumidorDAO();
   string dadosConsumidor = consumidor.getDados();

   //aqui gero e preencho o objeto
   var resultadoObjeto = new ResultadoObjeto();
   resultadoObjeto.Propriedade = dadosConsumidor;

   //aqui o transformo em JSON e retorno
   string json = new JavaScriptSerializer().Serialize(resultadoObjeto);
   return (json);

}
</code>
Comment: Fiz como no exemplo porém na hora do retorno não é possível de converter  string em System.Web.Mvc.ActionResult @Paz
Comment: modifique o ActionResult para string, editei a resposta para o código que funcionará corretamente


Custom Login JSP page Springboot + SpringSecurity

Question: I'm new in springboot and I'm triying to implement a custom login. It's not working, it always appear the default spring security login. Any help ?
I've been looking for a solution but I can't find anything that fit in my project. Please, any idea? You can see the project here :
download here
<code>@Configuration
@EnableWebSecurity
public class DemoSecurityConfig extends WebSecurityConfigurerAdapter {

    // add a reference to our security data source

    @Autowired
    @Qualifier("securityDataSource")
    private DataSource securityDataSource;

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {

        // use jdbc authentication ... oh yeah!!!
        auth.jdbcAuthentication().dataSource(securityDataSource);

    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {

        http.authorizeRequests()
            .antMatchers("/employees/showForm*").hasAnyRole("MANAGER", "ADMIN")
            .antMatchers("/employees/save*").hasAnyRole("MANAGER", "ADMIN")
            .antMatchers("/employees/delete").hasRole("ADMIN")
            .antMatchers("/employees/**").hasRole("EMPLOYEE")
            .antMatchers("/resources/**").permitAll()
            .and()
            .formLogin()
                .loginPage("/fancy-login")
                .loginProcessingUrl("/authenticateTheUser")
                .permitAll()
            .and()
            .logout().permitAll()
            .and()
            .exceptionHandling().accessDeniedPage("/access-denied");

    }

}
</code>
Thanks!
Answer: Try at first like this:
<code> @Override
  protected void configure(HttpSecurity http) throws Exception {
    http
            .authorizeRequests()
            .anyRequest().authenticated()
            .and()
            .formLogin()
            .loginPage("/fancy-login.html")
            .permitAll();
  }
</code>
put your fancy-login.html to resources/static/fancy-login.html.


Does this equivalence stand?

Question: I'm struggling to verify the following equivalence from Ekeland (p.12):
$$\lambda (\xi \cosh t + \overline \xi \sinh t) = \lambda e^t (\xi + \overline \xi)$$
for $\lambda=\pm 1$ and $\xi \in \mathbb C^n$
Comment: Where are you stuck?  Have you separated $\sinh,\cosh$ into exponential form?
Comment: Thank you @abiessu. So you say it's just $e^t = cosht + sinh t$? It is an alternative form of the exponential I wasn't aware of
Answer: Let $\xi=i$, $\lambda=1$:
$$
\xi\cosh(t)+\bar{\xi}\sinh(t)=i(\cosh(t)-\sinh(t))=ie^{-t}\neq 0
$$
Hence the relation is false.

Does this equivalence stand?


Erro de exceção em Lista dinamica C ++

Question: Estou criando uma lista encadeada em C++ e na condição if (j ->n == x), no método wasVisited que deve checar se um elemento já foi inserido na lista, aparece a seguinte mensagem quando eu compilo:

Exceção lançada: violação de acesso de leitura.
  j era 0xCCCCCC.

Não consigo resolver, alguém pode me ajudar? Estou usando o visualStudio como IDE.
#include "stdafx.h"
#include <iostream>
using namespace std;

class Celula{

public:
    int n;
    Celula* prox;

    Celula() {

        n = -1;
        prox = NULL;

    }//fim Construtor

    Celula(int x) {

        n = x;
        prox = NULL;

    }//fim construotor
};
class Lista {

public:
    Celula* origem;
    Celula* fim;

    Lista() {

        Celula x;
        origem = &x;
        fim = &x;

    }//fim construtor

    void inserir(int x) {

        Celula c(x);

        fim->prox = fim = &c;

    }//fim inserir

    bool wasVisited(int x) {

        bool res = false;
        Celula* j = origem->prox;

        do {

            if (j ->n == x) {

                res = true;

            }//fim if

            else {

                j = j->prox;

            }//fim else

        } while (res == false && j != NULL);//fim do.while

        return res;

    }//fim wasVisited

};

int main()
{
    Lista teste;

    teste.inserir(2);
    teste.wasVisited(2);
    teste.wasVisited(1);
    cin.get();

    return 0;
}

Comment: ele já está sendo iniciado: "Celula* j = origem->prox;"

o erro que está dando é na hora de comparar o valor do elemento do objeto que o ponteiro j aponta com o valor 'x' enviado como parametro.
Answer: O problema está aqui
Celula x;

O valor de x no construtor, é perdido ao sair da função pois é uma variável local. Com isso origem e fim se tornam valores não inicializados gerando acesso á 0xCCCCCC. para resolver isso basta alterar a construção:
Lista() {

   Celula *x = new Celula();
   origem = x;
   fim = x;

}

Comment: Deu certo, teve uns erros a mais, porem tranquilos de resolver, obrigado!
Comment: Que bom que funcionou, bons estudos
Comment: `new` não deveria ser usado em código normal, nunca, apenas quando é realmente a última ferramenta que resta. `std::unique_ptr` e os outros ponteiros inteligentes deveriam ser as primeiras ferramentas a serem consideradas.

Erro de exceção em Lista dinamica C ++


How to show multiple example in swagger documentation?

Question: In my REST API PATCH operation, I am using v3 swagger-annotation:2.0.6
I was trying to add more examples as swagger schema for my patch operation PATCH /users/id.
Request Body:
{
  "operationList": [
    {
      "op": "replace",
      "path": "/username",
      "value": "john1991"
    }
  ]
}

Currently I have following class for request model.
public class UserPatchOp extends PatchOperation {
    @Override
    @Schema(description = "some description", example = "replace", required = true)
    public PatchOperator getOp() {
        return super.getOp();
    }

    @Override
    @Schema(description = "some description", example = "/username", required = true)
    public String getPath() {
        return super.getPath();
    }

    @Override
    @Schema(description = "some description", , example = "john1991", required = true)
    public Object getValue() {
        return super.getValue();
    }
}

In PatchOperation.java
public class PatchOperation {

    /**
     * {@link PatchOperator} operation to be performed
     */
    @Schema(description = "Operation to be performed", required = true)
    @JsonProperty
    @NotNull
    private PatchOperator op;

    @Schema(description = "Path to target where operation will be performed", required = true)
    @JsonProperty
    @Pattern(regexp = "/([/A-Za-z0-9~])*-*", message = "Invalid path. Please follow regex pattern")
    private String path;

    @Schema(description = "Value used by operation")
    @JsonProperty
    private Object value;

    public PatchOperation() {
    }
}

In the swagger document, in UserPatchOp.java I have shown to the end-user that how to replace username.
On swagger, the request bogy comes with this example.

other than username through this patch operation, end-user can update description then path would be /description.
End-user can also update the usergroup from which it belongs to '/usergroups'
So in general,  same way I want to add more example to swagger schema.
But I am not able to do it. Because at one time I can show one example only.
I want to show following multiple operations to the client on swagger page.
{
  "operationList": [
    {
      "op": "replace",
      "path": "/username",
      "value": "john1991"
    },
    {
      "op": "remove",
      "path": "/description"
    },
    {
      "op": "add",
      "path": "/memberships"
      "value":["1224","8907"]
    }
  ]
}

And entry point method is
@PATCH
@Path("users/{id}")
@Consumes({MediaType.APPLICATION_JSON, APPLICATION_JSON_PATCH_JSON})
@ApiResponses(value = {
        @ApiResponse(responseCode = "200", description = MessageConstants.OK, content = @Content(schema = @Schema(implementation = UserInfo.class))),
        @ApiResponse(responseCode = "500", description = MessageConstants.SERVER_ERROR, content = @Content(schema = @Schema(implementation = RestError.class))),
        @ApiResponse(responseCode = "400", description = MessageConstants.BAD_REQUEST, content = @Content(schema = @Schema(implementation = RestError.class))),
        @ApiResponse(responseCode = "401", description = MessageConstants.UNAUTHORIZED, content = @Content(schema = @Schema(implementation = RestError.class))),
        @ApiResponse(responseCode = "404", description = MessageConstants.NOT_FOUND, content = @Content(schema = @Schema(implementation = RestError.class)))})
public Response updatePartialUser(
        @Parameter(description = "User Id", required = true) @PathParam("id") String id,
        @Parameter(description = "User Update Info", required = true) @Valid PatchOperations<UserPatchOperation> operationList) {

Is there any way, I can add multiple examples for getOP, getPath and getValue method? Thank you.
Comment: Yes, because that's how it should be done.
If you want to delete username you should make a method with @ DeleteMapping, for adding username with @ PostMapping, for getting it with @ GetMapping
So in the end you will have 3+ methods with endpoint /username.

Read this article, maybe it will clear some things for you: https://blog.logrocket.com/the-essential-guide-for-designing-a-production-ready-developer-friendly-restful-api/
Comment: @Szprota21 Thank you for your response. I have updated my question accordingly. I have patch operation which is responsible for update the resource which i have it like username, description and usergroup. And I need to show multiple example in swagger schema.
Answer: It is possible to create multiple examples of responses which one method can return but it is possible to do only one example for one response code.
@Operation(description = "Retrieves status of application",
               responses = {
                       @ApiResponse(responseCode = "200",
                                    description = "Everything works fine.",
                                    content = @Content(mediaType = "application/json",
                                                       examples = @ExampleObject(value = "{\n" +
                                                                                "  \"success\" : true,\n" +
                                                                                "  \"message\" : \"OK\"\n" +
                                                                                "}"))),
                       @ApiResponse(responseCode = "500",
                                    description = "Application not working properly",
                                    content = @Content(mediaType = "application/json",
                                                       examples = @ExampleObject(value = "{\n" +
                                                                                "  \"success\" : false,\n" +
                                                                                "  \"message\" : \"Application not working properly\"\n" +
                                                                                "}")))
               })
    @GetMapping("haproxy")
    ResponseEntity<BaseResponse> getHaProxy();

I'm not sure if it's what you want but I don't see other way around.
Keep in mind that swagger documentation should be done in a way that someone will be able connect to your api and do some operations. You don't need to provide too much responses there. That's for OPTIONS rest method is. OPTIONS method is basically a GET which don't need any parameters and in response will return complete informations about what certain method can do and what the request/response will be. Here you have better explanation of that: RESTful API methods; HEAD & OPTIONS
Btw. you should update your dependencies, swagger-annotations is on 2.1.4 now, 2.0.6 is from 2 years ago
EDIT 2020-09-30 About request's body:
It is possible to add multiple requests examples like that:
@Operation(description = "Creates a User",
           requestBody = @io.swagger.v3.oas.annotations.parameters.RequestBody(description = "Request examples",
                                                                               content = @Content(examples = {
                                                                                @ExampleObject(name = "doing weird stuff", value = "http://localhost:7080"),
                                                                                @ExampleObject(name = "doing weirdest stuff", value = "{\n\"test\":\"12\"\n}"),
                                                                               })),
           responses = {
                   @ApiResponse(responseCode = "200",
                                description = "Everything works fine.",
                                content = @Content(mediaType = "application/json",
                                                   schema = @Schema(implementation = UserResponse.class))),
                   @ApiResponse(responseCode = "404",
                                description = "Not found",
                                content = @Content(mediaType = "application/json",
                                                   examples = @ExampleObject(value = "{\"success\":false,\"message\":\"That shop or API version is not accessible yet\",\"httpStatus\":\"NOT_FOUND\"}"))),
                   @ApiResponse(responseCode = "500",
                                description = "Something went wrong",
                                content = @Content(mediaType = "application/json",
                                                   schema = @Schema(implementation = SomeBasicResponse.class)))
           })
@Parameters({
                    @Parameter(in = ParameterIn.HEADER, name = "url",
                               content = @Content(schema = @Schema(type = "string", defaultValue = "localhost:7080")))
            })

@PostMapping
ResponseEntity<UserResponse> createUser(@RequestHeader(name = "login", required = false) String login,
                                              @RequestHeader(name = "password") String password,
                                              @RequestBody UserRequest request);

I hope that's what you are looking for.
Comment: I have updated my question. actually, I am looking for how to put my json example in request body of swagger page.
Comment: I have updated my answers, hope it solves your issue now
Answer: I have added example at entry point with help of schema
@Parameter(description = "Update User", required = true, schema = @Schema (example = "{\n  "
                    + "\"operationList\": [\n    "
                    + "{\n      \"op\": \"replace\",\n      \"path\": \"/username\",\n      \"value\": \"john1991\"\n    },\n    "
                    + "{\n      \"op\": \"replace\",\n      \"path\": \"/description\",\n      \"value\": \"NewDescription\"\n    },\n    "
                    + "{\n      \"op\": \"add\",\n      \"path\": \"/memberships\",\n      "
                    + "\"value\":[\"1234\",\"6789\"]\n    "
                    + "{\n      \"op\": \"remove\",\n      \"path\": \"/privileges\",\n      \"value\":[\"148\",\"155\"]\n    "
                    + "}\n  ]\n}")) @Valid PatchOperations<UserPatchOperation> operationList) throws RestException


Can I remove number from parentheses to some power that contains also infinity if it doesnt have impact on calculating lim?

Question: I have $\displaystyle\lim _{n \rightarrow \infty} \frac{(3 n-1)^2(n+3)^3}{(n+7)^4(n-5)^2}$ and thats how I solve this:
$\displaystyle\lim _{n \rightarrow \infty} \frac{(3 n-1)^2(n+3)^3}{(n+7)^4(n-5)^2}=\left[\frac{\infty}{\infty}\right]=\lim _{n \rightarrow \infty}\frac{9n^2\cdot n^3}{n^4 \cdot n^2}=\lim _{n \rightarrow \infty}\frac{9n^5}{n^6}=\lim _{n \rightarrow \infty}9\cdot \frac{1}{n}=9\cdot 0=0$
I removed the numbers from the brackets that in my opinion have no effect due to the adjacent infinity and I left the brackets with powers for what was left and then I calculated in an obvious way. Is it possible? In theory, the result is correct.
Comment: The punchline is that it is valid and yields correct results, but is often seen as "improper" or "handwavy."  If you need to justify yourself to someone else, it is best to know how to go about it the long way... but for quick and dirty calculations, yes this is exactly what most of us do.
Answer: I would say that your calculation has an error, which by sheer luck was cancelled out. Here's what you wrote:
$$\lim _{n \rightarrow \infty} \frac{(3 n-1)^2(n+3)^3}{(n+7)^4(n-5)^2}=\left[\frac{\infty}{\infty}\right]=\lim _{n \rightarrow \infty}\frac{3n^2\cdot n^3}{n^4 \cdot n^2}=\lim _{n \rightarrow \infty}\frac{3n^5}{n^6} = \cdots = 0
$$
but here's what you should have written:
$$\lim _{n \rightarrow \infty} \frac{(3 n-1)^2(n+3)^3}{(n+7)^4(n-5)^2}=\left[\frac{\infty}{\infty}\right]=\lim _{n \rightarrow \infty}\frac{(3n)^2\cdot n^3}{n^4 \cdot n^2}=\lim _{n \rightarrow \infty}\frac{9n^5}{n^6} = \cdots = 0
$$
The reason this ended up not mattering is that $5 < 6$.
However, with just a tiny change in one of the exponents you would have gotten the wrong answer.
For example, if that $4$ exponent in the denominator were changed to a $3$ then your method would give the answer:
$$\lim _{n \rightarrow \infty} \frac{(3 n-1)^2(n+3)^3}{(n+7)^3(n-5)^2}=\left[\frac{\infty}{\infty}\right]=\lim _{n \rightarrow \infty}\frac{3n^2\cdot n^3}{n^3 \cdot n^2}=\lim _{n \rightarrow \infty}\frac{3n^5}{n^5} = \cdots = 3
$$
whereas the correct answer should be
$$\lim _{n \rightarrow \infty} \frac{(3 n-1)^2(n+3)^3}{(n+7)^3(n-5)^2}=\left[\frac{\infty}{\infty}\right]=\lim _{n \rightarrow \infty}\frac{(3n)^2\cdot n^3}{n^3 \cdot n^2}=\lim _{n \rightarrow \infty}\frac{9n^5}{n^5} = \cdots = 9
$$
Comment: Gosh you are correct, stupid mistake. Thank
Answer: Since $n$ is tending to $\infty$, and the expressions are just polynomials, we only care about the leading terms (i.e. the highest powers) in each polynomial, so the equalities you have  written are all correct, but sometimes it is not as straightforward. For example, it would be wrong to say:
\begin{align*}
\lim_{n\to \infty}\left(\frac{1}{(\frac{1}{n}+1)^2}\right)=\lim_{n\to 0}\left(\frac{1}{(\frac{1}{n})^2}\right)=\lim_{n\to\infty}(n^2)=\infty
\end{align*}
Comment: I think I wouldnt do this in your example cuz $\frac{1}{n}$ would be going to $0$, not infinity so $1$ have impact imo. denominator woulch change to $1$ because $(0+1)^2=1^2=1$ and $\frac{1}{1}=1$ so result is $1$
Comment: My point is that it is safer to work by some rules for how you are allowed to manipulate expressions like these. Your intuition appears to be working well at the moment, but often we can run into unintuitive maths, where not knowing the 'rules' can result in us getting the wrong answer
Comment: I know what you mean, and I agree that these simplifications sometimes fail.