How to generate a list of all valid URLs served by my site

Question: Is there a way to generate a list of all valid URLs that a site will resolve, including redirects?
Specifically, all views, nodes, and redirects (the from and to.)
The list is required for record reasons by a college in another department.
An answer would be especially useful if it didn't require a code change, as it's production site, and a code change would have to go through code review and require a release, but if it's necessary then it's necessary.
Module wise, among many others, xmlsitemap, redirect, path redirect import, pathauto and pathologic are installed. I'm not sure if any of those might be of any use.
As a second question, if there isn't a way of automatically generating all of the URLs in a pleasantly formatted list, then besides manually collecting all of the views URLs and the redirects urls, where else should I be looking?
Answer: There exists a number of website checking tools (aka. robots or spiders) that will crawl a given website and generate a number of reports, including a report of all URLs found on that site by recursively crawling the site from some starting point (crawl foundation page).
Below are links to three such tools that I've used for this purpose:

WebCheck: http://arthurdejong.org/webcheck/
Link Sleuth: http://home.snafu.de/tilman/xenulink.html
DRKSpider: http://www.drk.com.ar/spider.php

Note that these will only report URLs that are reachable from the crawl foundation page. If your site consists of sub-sites that are not reachable from each other, you need to set up more than one crawl foundation.


$(document).ready in ascx page after ajax callback

Question: I'm having a little problem with this setup here I have a list of .ascx files and they all do different tasks in terms of calculations to the controller itself. So on my .aspx page I click on an Ajax.ActionLink() and this will render that specific .ascx file based on the item I clicked. Within that .ascx are 1-3 events that will fire 2 of them are onclick events and 1 is onload. The onclick event(s) are easier to work with in terms of I can hardcode it directly in the controls event like so onclick="$("#toggleMe3").slideToggle("slow");" and the onload must run when the .ascx is loaded i was testing this in a $(document).ready(function(){}); call, this works fine in the .aspx page but as soon as I try adding it into the .aspx page it doesn't load and its ideal that this works but I have no idea why not. In fact nothing in the script tags work if I insert directly into the .ascx page they only work if hardcoded into the control's events, well some of them at least; the onload and onprerender don't fire.
Answer: I've had success using $(document).ready in my partials that get loaded via XHR.  Are the views that you're loading via XHR throwing JavaScript exceptions? Or do they contain malformed HTML?
I typically have my $(document).ready method at the bottom of my partial that I load via Ajax, like...

Comment: Unfortunately this doesn't work for me, I added the script tags to the bottom still no luck. I'm using MicrosoftAjax.js to control the Ajax calls and not the jquery ajax function.
Comment: This works for me, at least in FF3.5 and IE7 on Windows XP. However I do not understand why, as the jQuery documention doesn't handle this case...
Answer: I had a hard time understanding your question...but here it goes.
If you are loading date using AJAX calls, the $(document).ready() event will not fire -- because the page was already loaded.  You are just loading more data now.
If you already know the controls what will apear, pre-load the JavaScript, but instead of just binding using the click event handler, use the live handler.
so
$("#myControl").click(....);

turns into
 $("#myControl").live("click", ....);

Sorry if this isn't what you were looking for.
Comment: if the page is not dynamically loaded, yes.  Otherwise you need the live to preload the event handlers from the aspx.

Otherwise you will have to add some more hooks on the client side to know when the content is loaded, and the call the loaded javascript.
Answer: I had the same problem, after partial postback script specified in $(document).ready was not executed. I found solution here MSDN - PageRequestManager Class
Looks like adding a script like below fixes the issue


How to prove that $E(\frac{\hat{E}^T\hat{E}}{n-q}) = \Sigma$

Question: So quick explanation:
This is a multivariate statistics problem (specifically for multivariate regression). n is, as always, the sample size. q is the number of independent variables. Sigma is the covariance matrix of $e_i$. E is the error matrix. The bold is for vectors. E.g. $\bf{1}$ is a vector of 1's.
Y is the $n$x$p$ matrix of the dependent variables for n observations and p dependent variables $y$.

My skill with this is lacking.
I can get this to,
$$E[Y^T (I-H) Y] = \Sigma$$ but have no clue how to introduce $\Sigma$
OK. But the book offers a hint.
It states that,
$$E(\hat{e}^T\hat{e}) = (n-k)\sigma^2$$
and suggest that this can be solved using another problem in the book so I'll show what was proven in that:
$$E(x^TAx) = E(tr(xx^TA)) = tr(\Sigma A) = \mu^TA\mu$$
$$\sigma^{-2}E(x^TAx) = tr(A) = p-1$$
given that $\mu = \mu \bf{1}$ $\Sigma = \sigma^2 I$ and $A = I -\bf{11^T} p^{-1}$

Let me know if you need anything else. I really want to figure this out but this is very difficult for me. Thank you in advance.
Comment: Please define all notations and the complete model. E.g., what is H? Also provide reference to "the book". The equation $\mu=\mu\mathbf{1}$ sounds wrong.
Answer: Let us define the model as $y = X\beta + u$ where $X$ is $n \times q$ and $u$ is the $n \times 1$ error vector.
First let us consider $\hat{E} = y - \hat{y}$.
This is equal to $\hat{E} = y - \hat{y} = y - X(X^TX)^{-1}X^Ty = (I - P)y$
where $P = X(X^TX)^{-1}X^T$.
Then, we can show trivially that $P$ is a projection matrix i.e. $P^T = P$ and $PP = P$ and this is left to the reader to check.
Then as $y = X\beta + u$ we can say that $\hat{E} = (I-P)(X\beta + u) = X\beta -X(X^TX)X^TX\beta + u - Pu = X\beta - X\beta + (I-P)u = (I-P)u$.
Then, as $P$ is a projection matrix, so is $(I-P)$, hence $(I-P)^T(I-P) = (I-P)(I-P) = (I-P)$.
Then if we consider $\hat{E}^T\hat{E} = u^T(I-P)^T(I-P)u = u^T(I-P)u$ by the above.
Then as $u$ is $n \times 1$, $u^T$ is $1 \times n$ and so $\hat{E}^T\hat{E}$ is a $1 \times 1$ scalar.
Therefore $\hat{E}^T\hat{E} = tr\{\hat{E}^T\hat{E}\} = tr\{u^T(I-P)u\} = tr\{(I-P)uu^T\}.$
Then taking expectations of both sides we have that $E[\hat{E}^T\hat{E}] = E[tr\{(I-P)uu^T\}] = tr\{(I-P)E[uu^T]\}$ as $I-P$ is a constant.
Then as we assume $E[u] = 0$ we know that $E[uu^T] = var[u]$ and as we assume $Var[u] = \sigma_0^2$ we have that $E[uu^T] = \sigma_0^2$.
Hence $E[\hat{E}^T\hat{E}] = tr\{(I-P)E[uu^T]\} = tr\{\sigma_0^2(I-P)\} = \sigma_0^2 tr\{(I-P)\}$.
Then $tr\{(I-P)\} = tr\{I\} - tr\{P\} = n - tr\{X(X^TX)^{-1}X^T\} = n - tr\{(X^TX)^{-1}X^TX\} = n - tr\{I_q\} = n - q$.
Therefore $E[\hat{E}^T\hat{E}] = \sigma_0^2 (n - q)$.
Then $E[\frac{\hat{E}^T\hat{E}}{n-q}] = \frac{\sigma_0^2 (n - q)}{(n-q)} = \sigma_0^2$
Comment: Thank you so much for the detailed response. Although perhaps I wasn't clear with my question (as I wouldn't be able to define $u$ as nx1 since I have p response variables).
So I can't define $\hat{E}$ as you have but I can define one component of the matrix to that. I'm sure the extension to multivariate follows the same procedure.
This will help a lot in solving the multivariate case.

:)
Comment: Oh shoot. I see where the difficulty lays. I can't say that $$\hat{E}^T\hat{E} = tr(\hat{E}^T\hat{E})$$

Hmm...Perhaps taking the expectation will help somehow. I'll give it another go.
Comment: Oh wait..unless we write it as $$E= \begin{pmatrix}
        e_`^T \\
        \vdots \\
        e_n^T \\
        \end{pmatrix}$$
Comment: Wait. Now I'm confused about why you say $I-H$ is a constant.
Comment: I followed your work but need help proving that $var[u] = \sigma^2_0$? I'm not sure how the error matrix is distributed. It's supposed to be nxp.
Comment: There is an $I$ missing in $Var[u] = \sigma_0^2$ since $u$ is a vector.


how to install Crawler-Detect given the instructions?

Question: Sorry in advance if it the questions seems too basic. But I want to know how to install "Crawler-Detect" in my xampp and online server?
The instructions are given in the git link at: https://github.com/JayBizzle/Crawler-Detect
I just don't know how to install them. no one else seem to be having problem with this.
So far I have tried to download the package, place it where my project is, required the class like any regular class in php and run it. this error occured:
Fatal error: Class 'CrawlerDetect' not found in H:\xampp\htdocs\viralagain\theme\crawl.php on line 5
Then installed the composer package and run the command:
  composer require jaybizzle/crawler-detect 1.*
This Error occured:
Fatal error: Class 'Jaybizzle\CrawlerDetect\CrawlerDetect' not found in H:\xampp\htdocs\viralagain\theme\crawl.php on line 5
Then in my composer.js (In The project directory) I added the
"jaybizzle/crawler-detect" :"1.*"
Same error.
Crawl.php:
<?php

require "Jaybizzle/src/CrawlerDetect.php";
use Jaybizzle\CrawlerDetect\CrawlerDetect;

$CrawlerDetect = new CrawlerDetect;

// Check the user agent of the current 'visitor'
if($CrawlerDetect->isCrawler()) {
    // true if crawler user agent detected
    echo "
 [BOT DETECTED]";
}else{
    echo "not a bot";
}

echo $botname = $CrawlerDetect->getMatches();
?>

Comment: What can we tell you that isn't already in the instructions?
Comment: I have installed the composer and run the given command.... but this error keeps coming:

Fatal error: Class 'CrawlerDetect' not found in H:\xampp\htdocs\sitename\theme\crawl.php on line 5

Also on servers where should I run the given command? it doesnt provide any commandline interface.
Comment: I have also included the command in composer.js but same error... may be just run me through the installing procedure, may be I am missing something.......
Comment: Please update your question: include there the steps you have done (in the order you have done them) and the error you get (and when exactly does it rise).
Comment: OK. I will do it..
Comment: Can you post your `crawl.php` file?
Comment: I was trying to use it with simple php... not any framework like Laravel.
I removed all the lines with "use" and put "required" in their places and it kind of worked...
Comment: If you show me your code, i'll try and help you make it better than 'kinda working'....im the author of Crawler Detect by the way :)
Comment: [Question edited]   Wow...didn't expect you to be here. 1st) , great work with this, really amazing. 2nd) I had to require before "use" statements and then remove the code where it gave "undefined variable" errors. Thnx again
Comment: @MarkBeech Kindly let me know if you think its the wrong way to use it....
Answer: I have changed the CrawlerDetect's source and test it.
download it from here:
http://www.parsebazar.com/@files/CrawlerDetect.zip
sample:

require "CrawlerDetect.php";

$CrawlerDetect = new CrawlerDetect;

// Check the user agent of the current 'visitor'
if($CrawlerDetect->isCrawler()) {
    echo 'robot'; // true if crawler user agent detected
} else {
    echo 'visitor';
}


Why does reagent not re-render my reagent-form on a state change

Question: I need to create a form containing a select field where the options depend on the currently available mail accounts. I retrieve these mail accounts in a API request after the page has loaded.
The following function creates the form with the select element.
(defn create-options [mail-accounts]
  (for [m mail-accounts]
    [:option {:key (keyword (str (:id m)))
              :value (:id m)}
     (:name m)]))

(defn render-mail-account-select [mail-accounts]
  (let [form-state (r/atom {})]
    (fn [mail-accounts]
      (let [form [:form.mailing-form.form-horizontal
                  (into [:select.form-control {:field :list :id :mail-account}]
                        (create-options mail-accounts))]]
        (pprint form)
        [bind-fields form form-state]))))

The pprint gives me the following output:
;; Before the mail-accounts are loaded
[:select.form-control {:field :list, :id :mail-account}]

;; After the state update containing the mail accounts
[:select.form-control
 {:field :list, :id :mail-account}
 [:option {:key :24, :value 24} "First mail account name"]
 [:option {:key :25, :value 25} "Second mail account name"]]

My problem is that the select on my page stays empty as if the select does not get re-rendered.
Addendum
I think I forgot to add some code:
I am wrapping this form in a KIOO component where I dereference my state atom.
(defsnippet choose-account-panel "html/static-panel.html" [:div.panel]
  []
  {[:h4.panel-title] (content "3. Mail Account wählen")
   [:div.panel-body] (content [render-mail-account-select (:mail-accounts @state)])})

This component then calls my render-mail-account-select function and should re-render the form properly.
Comment: (Disclaimer: I don't know what I'm talking about) You make a closure over a new reagent atom in the let binding but how can anything update that atom in order to tell the form to update? To my understanding you need to close over atoms defined outside so that it's possible to propagate the changes?
Comment: By closing over the `form-state` atom I can create component local state.
Answer: You need to dereference a Ratom for Reagent to know which functions need to be called again when that Ratom changes. That dereferencing needs to happen within the anonymous function inside render-mail-account-select, or one of the functions that it calls. I can't see any dereferencing happening here?
See the docs here for more details on Reagent's rendering.
Comment: Makes sense as the answer, but how come re-frame doc reference given?
Comment: The re-frame docs have some really good advice on using reagent.
Answer: As already pointed out, your render function must reference something in your state atom in order to know when it needs to be re-rendered. However, if you also want your displayed form to have a 'default' value selected, you also need to set your state atom.
The bind-fields call will associate your form with the state atom. If there is nothing in the state atom, the form will be 'blank' i.e. none of the elements selected. If this is what you want, then that should be fine. However, if you want a value selected, then you should put that value in the atom. For example, if you wanted the first item to be already selected, then put :24 into the state atom i.e.
(swap! form-state assoc :mail-account :24)

Note that I'm not sure your option definition is correct. The docs seem to indicate that you only need the :key attribute with the value (as a keyword) in that attribute. I've not looked at the source to confirm this, but none of the examples use a :value attribute as well.
If you do the swap at the beginning of your render function, then the state atom will have been referenced and your component should re-render each time it is called with new arguments. When I say 'render function', in this case, I mean the anonymous function, not the outer one which creates the state atom.
Comment: What is a 'gind-fields call'? I can't find anything even like the word 'gind' in the question. I'll delete this comment later (, which I'm guessing means don't put a comment below this one or I won't be able to - not sure)


Moved Site - Can't find original CSS for look other than in the ADVAGG

Question: I've inherited a drupal 7(I'm a beginner) site that had ADVagg installed. I added a stanza in my nginx config to take care of those files. What I'm running into is that there is a button on the original site that has a style which only exists in an aggregate file.  I can't find it in any other file in the enitre site. The docroot was zipped and sent to me. I'm just a little miffed as to why the site I've unpacked doesn't have the same styles as the one online currently.
I've disabled the ADVAGG as well with no change.
<code>###
    ### advagg_css and advagg_js support
    ###
    location ~* files/advagg_(?:css|js)/ {
      gzip_static on;
      access_log  off;
      expires     max;
      add_header  ETag "";
      add_header  Cache-Control "max-age=31449600, no-transform, public";
      try_files   $uri @rewrite;
    }
</code>
Answer: AdvAgg is used to improve the standard Drupal Core aggregation.
Just disabling AdvAgg won't disable aggregation.
You will need to disable CSS aggregation under the Performance settings, then flush caches, and you should be able to inspect the button CSS again.


Encrypting a file using a private key and public key

Question: I am a developer with very little experience of encryption.  I am trying to learn more about Encryption and specifically SSL in my spare time.
Say a trusted company has a file (notepad) that contains a load of personal and confidential information.  Say I wanted to ask them to send this information to a me to analyze.  How would I do this?
My research is telling me that I would have to:
1) Create a self signed certificate
2) Generate the public and private key
3) Issue the public key to the trusted company and keep the private key
4) Ask the company to encrypt the information using the public key and then send it to me
5) Decrypt the file using the private key
Is that correct? How would I do this?
Should the certificate be signed by a Certificate Authority in this case as I would manually be issuing the public key to the trusted company (they know it comes from me).
As I said I am relatively new to this subject.
Comment: SSL/TLS is not used to encrypt files. It is used to establish encrypted connections. If you really want to encrypt files for storage, then you can't do this with SSL/TLS. It seems you just simply mean public-key-encryption. If so, then yes, that is a way to do it.
Comment: Note that the size of the data you can encrypt with RSA is limited to less than the key size. Since the reference is to  SSL note that the data is encrypted with a symmetric key such as AES and that key is encrypted with asymmetric encryption such as RSA. This is sometimes called hybrid encryption.
Comment: @Zaph, thanks for your comment.  However, I do not want to be an "expert".  I am just trying to grasp the basics.
Answer: SSL is a protocol for encrypting network connections.  It's not really relevant for manually encrypting and decrypting files.  (It's also insecure and deprecated; TLS should be used instead.)
If you want to manually encrypt and decrypt files, yes, you could use a self-signed certificate and just give the public key to the company that'll send the file.  However, you have to make sure to give them the public key in a way that can't be intercepted — such as physically handing it over on a flash drive, not emailing it — or you're vulnerable to a man-in-the-middle attack: someone could intercept the public key and give the company a different one instead.  (If that happened, the company would unknowingly be encrypting the file for the attacker to decrypt, and the attacker would then re-encrypt the file with the real public key and send it along to you.)
If you're doing this manually and you deliver the public key in a secure way, you don't need to involve a certificate authority.  The purpose of a certificate authority is to vouch for the authenticity of a certificate when it's delivered over an insecure channel.  For example, when you visit stackoverflow.com, your browser gets a certificate (with a public key) from the web server.  Since this certificate wasn't personally given to you by SO staff, how do you know that the web server is the real stackoverflow.com, not a man-in-the-middle attacker intercepting your connection in order to hijack your account?  The website's certificate is signed by a certificate authority — DigiCert, currently — that says DigiCert has verified that it's real.  Your browser is configured to trust that signature from DigiCert, because the browser developers have verified that the company is trustworthy.
PGP and GPG are good tools for securely exchanging encrypted files.  They use a "web-of-trust" model based on securely exchanging certificates, rather than relying on a certificate authority.


Derivation of expressoin for hazard function (another aspect)

Question: I'm now learning the very basics of survival analysis.
Firstly, the probability function is introduced:
$$f(t)=\frac{dF(t)}{dt}=-\frac{dS(t)}{dt}$$
Where $S(t)=1-F(t)$.
We are then introduced to the hazard function:
$$h(t)=\frac{f(t)}{S(t)}$$
Subsequently, we are told that combining the previous two expressions yield:
$$h(t)=-\frac{d}{dt}log S(t)$$
How do I justify this last step, shouldn't it be something like:
$$h(t)=\frac{-\frac{dS(t)}{dt}}{S(t)}$$
??
Comment: Indeed. But these expressions are equivalent ! (review the chain rule).
Comment: This had nothing whatsoeve to do with [tag:division-algebras]. Do you pick your tags randomly rather than study what they mean?
Answer: Simply evaluate the derivative to obtain:
$$h(t) = -\frac{d}{dt}\log(S(t)) = -\frac{1}{S(t)}\frac{dS}{dt} = \frac{f(t)}{S(t)}$$
Comment: What confuses me is the log I think, how did "that" find its way into our equation?
Comment: @Magnus I suppose that whoever wrote that wants to use the integral of the hazard function somewhere, so it was convenient to express $h(t)$ as a derivative. To see where the $\log$ comes from, just integrate your expression for $h$ (which was $-\frac{1}{S(t)} \frac{dS}{dt}$). You remember that $\int \frac{1}{u}\frac{du}{dt}\;dt = \log(u)$, right?
Comment: .....no that rule is new to me. Does it have a name?
Comment: @Magnus I don't believe it has a name. See [this](https://math.stackexchange.com/questions/206032/what-is-the-integral-of-1-x). Or [this](https://math.stackexchange.com/questions/2071721/integration-of-frac1x-from-first-principles), if you are interested in where it came from.
Answer: From your first equation
$$
\frac{{\rm d}S}{{\rm d}t} = -\frac{{\rm d}F}{{\rm d}t} = -f(t) \tag{1}
$$
So that
$$
h(t) = -\frac{{\rm d}}{{\rm d}t} \log S(t) = -\frac{1}{S(t)}\frac{{\rm d} S}{{\rm d} t} =  -\frac{1}{S(t)}[-f(t)]
$$


doctrine 2, how to remove many to many associations?

Question: How do you unlink a relation from a many-to-many table without deleting anything?
I have tried:
$getProject = $this->_helper->getDocRepo('Entities\Project')->findOneBy(array('id' => $projectId));
$getCat = $this->_doctrine->getReference('\Entities\Projectcat', $catId);

$getProject->getCategory()->removeElement($getCat);
$this->em->flush();

my Projectcat entity:
/**
 * @ManyToMany(targetEntity="\Entities\Projectcat", cascade={"persist", "remove"})
 * @JoinColumn(name="id", referencedColumnName="id")
 */
protected $getCategory;

Comment: anyone know?  i teied everything.. i can delete the project and it will also delete from the many to many table but this time, i just want to unlink them. i need them to exist but not associated with a category..
Answer: A rather old post but wanted to provide a way to ensure the association was removed from the ORM Entity side of doctrine, rather than of having to manually execute each Entity's collection removeElement and to expand on the answer by @Rene Terstegen.
The issue is that Doctrine does not "auto-magically" tie together the associations, you can however update the entity's Add/Remove methods to do so.
https://gist.github.com/Ocramius/3121916
The below example is based on the OP's project/category schema.
It assumes that the table project_category is the ManyToMany relationship table, and the project and category tables use the primary key id.
class Project
{

    /**
     * @ORM\ManyToMany(targetEntity="Category", inversedBy="projects")
     * @ORM\JoinTable(
     *  name="project_category",
     *  joinColumns={
     *      @ORM\JoinColumn(name="project", referencedColumnName="id")
     *  },
     *  inverseJoinColumns={
     *      @ORM\JoinColumn(name="category", referencedColumnName="id")
     *  }
     * )
     */
    protected $categories;

    public function __construct()
    {
        $this->categories = new ArrayCollection();
    }

    /**
     * @param Category $category
     */
    public function removeCategory(Category $category)
    {
        if (!$this->categories->contains($category)) {
            return;
        }
        $this->categories->removeElement($category);
        $category->removeProject($this);
    }
}

class Category
{
    /**
     * @ORM\ManyToMany(targetEntity="Project", mappedBy="categories")
     */
    protected $projects;

    public function __construct()
    {
        $this->projects = new ArrayCollection();
    }

    /**
     * @param Project $project
     */
    public function removeProject(Project $project)
    {
        if (!$this->projects->contains($project)) {
            return;
        }
        $this->projects->removeElement($project);
        $project->removeCategory($this);
    }
}

Then all you need to do is to call the removeCategory or removeProject method, instead of both. The same can be applied for addCategory and addProject methods as well.
$project = $em->find('Entities\Project', $projectId);
$category = $em->getReference('Entities\Category', $categoryId);
$project->removeCategory($category);
$em->flush();

Answer: Your information is a bit limited. Some extra information about the database scheme and Project would be nice. But to give it a try.
You have to remove it from both sides of the relationship. You removed it from the category, but you should also remove it from the project.
// Remove Category from Project
$Project->Category->removeElement($Category);
// Remove Project from Category
$Category->Project->removeElement($Project);

Good luck!
Answer: An old post, but the answer above helped me, but it may help to expand it a little bit, I have a project that can have many categories (and categories than can have many projects), so this code gets me all of them:
$project->getCategories();

If I wanted to delete all of the categories for a project, I simply do this:
 foreach ($project->getCategories() as $category) {
    $project->getCategories()->removeElement($category);
 }

The issue with the original question was that I believe Doctrine wants you to pass in the category that is referenced by the project, not just a reference to the category that you grabbed independently using this code:
$getCat = $this->_doctrine->getReference('\Entities\Projectcat', $catId);

Hopefully that makes sense. I know I'm messing up the terminology slightly.
Comment: The entity class should not care if the associated entity or reference was used. http://doctrine-orm.readthedocs.org/en/latest/reference/advanced-configuration.html#reference-proxies The proxy reference object should be transparent.


How do I add a Font Awesome icon to file input field

Question: I have a file input button, instead of browse I want to show Font Awesome upload icon there but whatever I tried nothing gave me result.
Here is what I've tried:

.select-wrapper {
  background: url(http://s10.postimg.org/4rc0fv8jt/camera.png) no-repeat;
  background-size: cover;
  display: block;
  position: relative;
  width: 33px;
  height: 26px;
}
#image_src {
  width: 26px;
  height: 26px;
  margin-right: 100px;
  opacity: 0;
  filter: alpha(opacity=0); /* IE 5-7 */
}

    <input type="file" name="image_src" id="image_src" />

By above code I only get a picture instead of browse button, but I want to use Font Awesome icon.
Comment: Like this? http://stackoverflow.com/a/30858367/483779
Comment: Make sure to add it on the container not the input field itself.
Comment: @JacobGray i've tried adding class of icon in input type class
Comment: @Pangloss I tried but none result came
Comment: In this case; `span.select-wrapper:before { font-family:'FontAwesome'; content: '\icondata'; }`
Comment: @SagarSingh Are you using bootstrap?
Comment: @Tricky12 yes I'm using Bootstrap
Answer: You could hide file input with display: none and create custom button or in this case font-awesome icon that will trigger input. Also you can use span to display input's value that will change on input value change.

$("i").click(function () {
  $("input[type='file']").trigger('click');
});

$('input[type="file"]').on('change', function() {
  var val = $(this).val();
  $(this).siblings('span').text(val);
})
.element {
  display: inline-flex;
  align-items: center;
}
i.fa-camera {
  margin: 10px;
  cursor: pointer;
  font-size: 30px;
}
i:hover {
  opacity: 0.6;
}
input {
  display: none;
}
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.5.0/css/font-awesome.min.css" rel="stylesheet"/>

  No file selected
  <input type="file" name="" id="">

Answer: Since you are using Bootstrap - if you are open to using a small plug-in, there is one that will do what you want. The plug-in is Bootstrap Filestyle - http://markusslima.github.io/bootstrap-filestyle/.
All you have to do is add a few attributes to your input and download/include the plug-in's JS after Bootstrap's JS.
<input type="file" class="filestyle" name="image_src" id="image_src" data-input="false" data-iconName="fa fa-upload" data-buttonText="Upload File" />

Your font-awesome icon class will go in data-iconName and your verbiage will go in data-buttonText.
Additionally, you can add or remove the text input portion with data-input. True to show it and false (as in the demo below) to hide it.
Working Demo Here
Comment: Works great - but note that this requires version >= 1.2 of filestyle
Answer: There's another way you can handle this scenario using just CSS and FontAwesome.  If you go to FontAwesome's website and look at the examples, I'm going to use "fa fa-asterisk" for this example, you will notice once you click the icon and it takes you to the page, it will give you a UNICODE value for the fontawesome icon.  For example the UNICODE value for asterisk is "f069".
This being the case, you can use the "after or before" pseudo class in your CSS like so:
[input]#img_src::before {
font-family: 'FontAwesome';
content: '\f069'
}

This will place a fontawesome asterisk BEFORE (in this case) any input button text. If you want the button to only show the icon, simply don't enter any input text and just use the pseudo classes to handle the distribution of the fontawesome icons using only CSS.
Hope this helps.
Answer:

.select-wrapper {
  background: url(http://s10.postimg.org/4rc0fv8jt/camera.png) no-repeat;
  background-size: cover;
  display: block;
  position: relative;
  width: 33px;
  height: 26px;
}
#image_src {
  width: 26px;
  height: 26px;
  margin-right: 100px;
  opacity: 0;
  filter: alpha(opacity=0); /* IE 5-7 */
}

    <input type="file" name="image_src" id="image_src" />

.select-wrapper {
  background: url(http://s10.postimg.org/4rc0fv8jt/camera.png) no-repeat;
  background-size: cover;
  display: block;
  position: relative;
  width: 33px;
  height: 26px;
}
#image_src {
  width: 26px;
  height: 26px;
  margin-right: 100px;
  opacity: 0;
  filter: alpha(opacity=0); /* IE 5-7 */
}

    <input type="file" name="image_src" id="image_src" />

Comment: can anyone tell how to add more custom choose files image buttons with js ?


VPN server that allows NATIVE Vista VPN client to connect...?

Question: I'm looking for a VPN server solution that allows clients to use the native Windows Vista VPN client.  Main reason is cost, since I am in a startup with little funds and not having to spend $50 per client for software, as well as not having to install any more software, is very appealing to me.
The only thing this will function is the VPN server.  I already have a firewall solution, so this is of no importance to me.  From what I understand, Vista's client will not connect on an IPSec VPN connection, which is what my firewall provides.
Edit:
I do not want to expose SQL Server externally, this is the main reason I want VPN.  Is this something Windows Server 2003 could handle?  Regardless, it would be cheaper finding a smaller hardware firewall solution I would think.
Answer: The native VPN client in Vista can connect to any VPN server that supports PPTP, L2TP, or SSTP.
So yes, VPN in Server 2003 will work as long as you enable one of the protocols listed above. This guide can get you started.
Answer: Just set up a Windows 2003 server. In the Routing and Remote Access component, you can enable it as a PPTP VPN endpoint.
In your firewall, you will need to open ports TCP 1723, and GRE (Generic Routing Encapsulation) protocol.
If you do not enable GRE, you will get to the "Verifying username and password..." step but never the "Registering your computer on the network" step - that's how you know. :)
Hope that helps... works great once set up.
Answer: Windows Server 2003 can certainly handle it, just install RRAS.  PPTP is easy to implement, and a good choice if there's low security risk/compliance threshold.  However, L2TP is more secure and a better choice if security is any kind of an issue.  You'll need to open UDP ports 500, 4500 (for NAT traversal), and 1701 on your firewall to allow access, and port forward these to the 2003 box.  SQL will still be available only to the internal network and those connected via VPN.  Certificates can be a pain, but if you have a relatively small number of clients you can create an offline CA to produce certificates for the server and each client.  We used OpenSSL (Shining Light's Windows implementation is great) and installed ActivePerl just because the CA.pl syntax in OpenSSL is muuuuuuuuuch more friendly (both free downloads).  You can import the certificates in each windows server/client with the certificates snap-in in mmc.
Answer: Seems to me like you need a Windows Server. Microsoft recently introduced something called Windows Server 2008 Foundation which might suit you. WSF is purchased pre-installed by an OEM and requires no CALs, but is limited to 15 users.
But, what do you need the VPN for? Might a Small Business Server be a better solution with it's Remote Web Workplace?
Comment: I do not want to expose SQL Server externally, this is the main reason I want VPN. Is this something Windows Server 2003 could handle? Regardless, it would be cheaper finding a smaller hardware firewall solution I would think.
Answer: Ended up going with a Cisco PIX 501.  I'll deal with 3rd party VPN software at this point.


Cross validation: cross_val_score function from scikit-learn arguments

Question: According to the DOC of scikit-learn

sklearn.model_selection.cross_val_score(estimator, X, y=None,
groups=None, scoring=None, cv=None, n_jobs=1, verbose=0,
fit_params=None, pre_dispatch='2*n_jobs')

X and y

X : array-like The data to fit. Can be for example a list, or an
array.
y : array-like, optional, default: None The target variable to
try to predict in the case of supervised learning.

I am wondering whether [X,y] is X_train and y_train or [X,y] should be the whole dataset. In some of the notebooks from kaggle some people use the whole dataset and some others X_train and y_train.
To my knowledge, cross validation just evaluate the model and shows whether or not you overfit/underfit your data (it does not actually train the model). Then, in my view the most data you have the better will be the performance, so I would use the whole dataset.
What do you think?
Comment: It is up to you. In some cases, people do their whole data analysis - including cross validation - on the train set, and only in the end use the test set.
Answer: Model performance is dependent on way the data is split and sometimes model does not have ability to generalize.
So that's why we need the cross validation.
Cross-validation is a vital step in evaluating a model. It maximizes the amount of data that is used to train the model, as during the course of training, the model is not only trained, but also tested on all of the available data.

I am wondering whether [X,y] is X_train and y_train or [X,y] should be
  the whole dataset.

[X, y] should be the whole dataset because internally cross validation spliting the data into training data and test data.
Suppose you use cross validation with 5 folds (cv = 5).
We begin by splitting the dataset into five groups or folds. Then we hold out the first fold as a test set, fit out model on the remaining four folds, predict on the test set and compute the metric of interest.
Next, we hold out the second fold as out test set, fit on the remaining data, predict on the test set and compute the metric of interest.

By default, scikit-learn's cross_val_score() function uses R^2 score as the metric of choice for regression.
R^2 score is called coefficient of determination.
Comment: `cross_val_score` uses the `score()` method of supplied estimator as default. And for regressor estimators, `score()` calculates the R_squared value. Hence `cross_val_score()` gives out this.


how to properly generate String list for a .bat file?

Question: Im trying to make a list of strings like this:
{https://pastebin.com/5azvnN8L}
with the part labeled num1 , num2 , exedra, going all the way to 100
but I found this to be a difficult task copy and pasting and editing the num area .
So I was wondering if there was a way to do this automatically with a command in cmd or an application accessible to windows10
sorry for the pastebin link i had trouble with the code embedding thing on stack overflow posting
Comment: you mean each line will have `num` and the url? Will the url be same on each line?
Answer: You can use a for /L loop to iterate over a range of numbers to dynamically build your variables, but you'll need to enable delayed expansion first so that you get a different random number each time.
@echo off
setlocal enabledelayedexpansion
for /L %%A in (1,1,100) do set /a num%%A=!RANDOM!%%%dig%+1

or if you want the actual set commands themselves to be in a new file, you don't need delayed expansion and can just do
for /L %%A in (1,1,100) do >>file.txt echo set /a num%%A=%%RANDOM%% %%%% %%dig%%+1

You need to double up the %s to escape them.
Comment: @swapclick please read, [What should I do when someone answers my question?](https://stackoverflow.com/help/someone-answers)


making vsftpd listen on a specific hostname

Question: Is there a way to restrict which hostname(s) vsftpd listens to? I know it can be limited to listening on a particular IP and it fcan be limited by remote ip/hostname, but I wonder if listening only on a specific subdomain or something like that is possible? I'm on Ubuntu.
Answer: As the FTP protocol does not specifically include the server hostname in requests, this is probably not possible.
Comment: +1 The FTP protocol has no equivalent to HTTP's `Host:` header.
Comment: FTP now has a `HOST` command; see [RFC 7151](https://tools.ietf.org/html/rfc7151).


Nested groups in Angular2 forms?

Question: I'm using the reactive forms module in Angular 2 to create a form with several nested groups.
My 'trust' form has an array of contacts at
<FormArray>this.newTrustForm.controls['contact']

One of the fields in the 'contact' group is an array of 'email' groups and I tried finding it here, but alas, no. Where would I then find it?
<FormArray>this.newTrustForm.controls['contact'].controls['email']

I setup my form with the following.
constructor(private _fb: FormBuilder) { }

ngOnInit() {
  this.newTrustForm = this._fb.group({
    ...
    contact: this._fb.array([]),
    ...
  });
}

I then add 'contact' groups with the following.
initContact() {
  return this._fb.group({
    ...
    email: this._fb.array([]),
    ...
  });
}

And then I have initContactEmail setup in the same way.
Comment: you should show us how you are creating these groups.
Comment: @Fals See edits. TIA.
Comment: I'm not seeing you iterating through every contact to create the email group. if you're are nesting, you should do this. Take a look at the last example from the oficial site: https://angular.io/docs/ts/latest/guide/reactive-forms.html#!#form-array
Answer: You have specify the index of contact:
<FormArray>this.newTrustForm.controls['contact'][INDEX]['controls']['email']

Or (more readable):
this.newTrustForm.get(`contact.${INDEX}.email`) as FormArray;

Also, as a suggestion, since contact and email are arrays, you could named them in plural: contacts and emails.

Nested groups in Angular2 forms?


Subconsulta com MIN E MAX juntos

Question: Como consigo trazer uma coluna junto com min() e max()....isso é possível ?
select Name, Size from Production.Product where Size in (select MIN(Size), MAX(Size) from Production.Product)
Answer: Segue uma sugestão utilizando uma CTE com as funções Min e Max, para utilização posterior em um Join:
with CTE_M as
(
  select MIN(Size) as SizeMin, MAX(Size) as SizeMax
  from Production.Product
)

select p.Name, p.Size
from Production.Product as p
inner join CTE_M as c
  on
    p.Size = c.SizeMin or
    p.Size = c.SizeMax

E uma outra sugestão utilizando uma CTE com a função Row_Number para classificar as linhas e obter o menor e o maior valor:
with CTE_RN as
(
  select
    Name,
    Size,
    row_number() over(order by Size) as RN_Asc,
    row_number() over(order by Size desc) as RN_Desc
  from Production.Product
)

select Name, Size
from CTE_RN
where RN_Asc = 1 or RN_Desc = 1

Espero que ajude
Answer: Meia hora de estudo depois , eu mesmo consegui responder..não sei se é possível colocar os dois juntos em uma subquery mas usei essa sintaxe:
select Name, Size from Production.Product where Size in (Select MAX(Size) FROM Production.Product)
union all
select Name, Size from Production.Product where Size in (Select MIN(Size) FROM Production.Product)

Subconsulta com MIN E MAX juntos


How to give id of every fragment in and use it Tab Fragment android

Question: I build app that provide custom add and remove tabs from TABFragment. now i want to give id of every tab which i created custom. and get the id of where i am exactly. I also used tab.getPosition but it give me where am i exactly. For example i created five page. now when i am 4th tab and then i want to 5th tab id 5th page progress under background. Please give me best suggestion and any regards.Thank you
my Add button code.
btNewtab.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

            actionBar.addTab(actionBar.newTab().setText("New Tabs")
                    .setTabListener(HomeActivity.this));  //Adding new tab

             COUNT_TAB+=1;  //Add tab for counting

            mAdapter.notifyDataSetChanged();
        }
    });

Answer: You can identify the individual tabs by Tag easily. just set the tag for each tab and perform action on your basis. i.e
 COUNT_TAB+=1;//put this line before so that you can use it as tag
   actionBar.addTab(actionBar.newTab().setText("New Tabs")
                    .setTabListener(HomeActivity.this).setTag(COUNT_TAB));

//If you want to set the selected tab initially different from default  then set true or false to indicate which tab should be selected. you can change the position of the added tab also  by setting the position. Below is the code i.e.
 actionBar.addTab(actionBar.newTab().setText("TAB1").setTag("tab1")
  .setTabListener(this),0,false);
 actionBar.addTab(actionBar.newTab().setText("TAB2").setTag("tab2")
  .setTabListener(this),1,true);
 actionBar.addTab(actionBar.newTab().setText("TAB3").setTag("tab3")
  .setTabListener(this),2,false);

//To handle the click event of the tabs you have to override the onTabSelected() method
  i have put some sample code hope it will help you.
@Override
    public void onTabSelected(ActionBar.Tab tab,
            FragmentTransaction fragmentTransaction) {
        if (tab.getTag().equals("tab1")) {
            // When the given tab is selected, show the tab contents in the
            // container view.
            Fragment fragment = new DummySectionFragment();
            Bundle args = new Bundle();
            args.putInt("myvalues", 1);
            fragment.setArguments(args);
            getFragmentManager().beginTransaction()
                    .replace(R.id.container, fragment).commit();
        } else if (tab.getTag().equals("tab2")) {
            Toast.makeText(this, "two clicked", Toast.LENGTH_LONG).show();
        } else if (tab.getTag().equals("tab3")) {
            Toast.makeText(this, "three clicked", Toast.LENGTH_LONG).show();
        }
    }

Comment: I have modified the code.please check it.I hope it will help you.
Comment: thanks for your replay. This work for give tag, Now how i can get Tag from tab ? and when i have three tab and my currunt position is 2nd tab and my code need get under third tab progress. how to do it.I hope you understand my engish is not good. Thanks again
Comment: how to initialize tab to get current tab position?
Comment: Thanks for your replay, Now please suggest me how to i remove permanently fragment tab.When i remove tab and after then create new then previous deleted tab show me again.Please help me about this. Thanks a lot men.


Is every $\mathcal{O}_X$-module homomorphism $\mathcal{O}_X^{\oplus n} \to \mathcal{O}_X^{\oplus m}$ given by a matrix?

Question: For $A$ a ring, we know any linear map from $A^{\oplus n} \to A^{\oplus m}$ is given by a $m \times n$ matrix. For $(X,\mathcal{O}_X)$ a locally ringed space (or scheme), is every $\mathcal{O}_X$-module homomorphism $\mathcal{O}_X^{\oplus n} \to \mathcal{O}_X^{\oplus m}$ given by a matrix with coefficients in $\Gamma(X,\mathcal{O}_X)$?
Comment: @SergioDaSilva $\mathscr{O}_X$-module means (abelian) sheaf with an $\mathcal{O}_X$-action. This is standard terminology.
Comment: $\mathcal{O}_X^{\oplus n}$ is a sheaf and not itself a module.  However, for each open $U\subset X$, $\mathcal{O}_X^{\oplus n}(U)$ is an $\mathcal{O}_X(U)$-module. Since the map when restricted to $U$ is a map between free modules, you can indeed encode the information about the map in a matrix.
Comment: I'm not quite sure of the answer, butI think it should be false, as there could be more homomorphims of sheaves rather than matrices with coefficients in the global sections. For example, have you thought about what happens if you pick $X=\mathbb P^1$ over a field? Because in that case the global sections are the constants, but $\mathbb P^1$ itself has many automorphisms...
Comment: In general, for an object $A$ of an abelian category, we have $\mathrm{Hom}(A^n,A^m) \cong M_{m \times n}(\mathrm{End}(A))$. Now apply this to $A=\mathcal{O}_X$.
Answer: Yes, and the reason is basically the same as for rings: on any ringed space $(X, \mathscr{O}_X)$, the $\mathscr{O}_X$-module $\mathscr{O}_X$ represents the global sections functor on the category of $\mathscr{O}_X$-modules. In other words, there's a natural isomorphism $\mathrm{Hom}(\mathscr{O}_X, \mathscr{F}) \to \Gamma(X, \mathscr{F})$ of abelian groups, given by mapping $\phi \in \mathrm{Hom}(\mathscr{O}_X, \mathscr{F})$ to the image of 1 under $\phi$ on the map $\Gamma(X, \mathscr{O}_X) \to \Gamma(X, \mathscr{F})$ induced by $\phi$ on global sections. I think proving this fact is not too difficult an exercise, but I can provide more details if you let me know.
Having proved this, we have isomorphisms
$\mathrm{Hom}(\mathscr{O}_X^{\oplus n}, \mathscr{F}) \to \mathrm{Hom}(\mathscr{O}_X, \mathscr{F})^{\oplus n} \to \Gamma(X, \mathscr{F})^{\oplus n}$.
The first isomorphism is a consequence of the universal property of direct sums. The second one is obtained by taking a direct sum of isomorphism that we established earlier. If you chase through it, this composite isomorphism is given by mapping $\phi \in \mathrm{Hom}(\mathscr{O}_X^{\oplus n}, \mathscr{F})$ to $(\phi(e_1), \dotsc, \phi(e_n))$, where $e_i$ is the standard basis vector of $\Gamma(X, \mathscr{O}_X^{\oplus n}) = \Gamma(X, \mathscr{O}_X)^{\oplus n}$ and $\phi(e_i)$ is its image under the map induced by $\phi$ on global sections.
Now taking $\mathscr{F} = \mathscr{O}_X^{\oplus m}$ gives you what you want.
Answer: I'll answer the $m  =n =1$ case and the rest follows because finite direct sums are the same as the corresponding finite direct sum of presheaves of $\mathcal{O}_X$-modules (Lemma 3.2 of modules, Stacks Project). Now for any $U \subseteq X$, consider the diagram
$$\begin{array}{ccc} \mathcal{O}_X(X) & \stackrel{f(X)}{\longrightarrow} & \mathcal{O}_X(X) \\
\downarrow && \downarrow \\
\mathcal{O}_X(U) &\stackrel{f(U)}{\longrightarrow}& \mathcal{O}_X(U)\end{array}$$
Now I claim everything is completely determined by the image of $1 \in \mathcal{O}_X(X)$ under $f(X)$. Indeed, the point is that the restriction $\mathcal{O}_X(X) \to \mathcal{O}_X(U)$ is a ring homomorphism and so $1$ is sent to $1$. Now $f(U)$ being an $\mathcal{O}_X(U)$-module homomorphism implies it is completely determined by the image of $1$. It follows by commutivity of the diagram that $$f(U)(1) = f(X)(1)|_U$$
and so
$$\operatorname{Hom}_{\mathcal{O}_X}(\mathcal{O}_X,\mathcal{O}_X) = \Gamma(X,\mathcal{O}_X)$$
as desired.


ansible vca_vapp AttributeError: 'NoneType' object has no attribute 'startswith'

Question: When using vca_vapp in Ansible against VCloud, I get the error "AttributeError: 'NoneType' object has no attribute 'startswith'" when using the example.
<code>TASK [vca_vapp vm_name=myvm3 username={{ username }}
template_name=Ubuntu Server 12.04 LTS (amd6420150127)
vapp_name=myapp instance_id={{ instanceid }} state=present
operation=poweron password={{ admin_pass }} vdc_name=VDC2] ***
An exception occurred during task execution. To see the full
traceback, use -vvv. The error was: AttributeError: 'NoneType'
object has no attribute 'startswith' fatal: [localhost]: FAILED!
=> {"changed": false, "failed": true, "parsed": false}
</code>
Answer: Solution: you need to set the (undocumented) 'host' variable. For example:
<code>   - vca_vapp:
       host: 'https://vca.vmware.com'
       vapp_name: myapp
       vm_name: myvm
       state: present
       operation: poweron
       instance_id: "{{ instanceid }}"
</code>
See this pull request: https://github.com/ansible/ansible-modules-extras/pull/1355


What portion of tension reduction in a racket happens through play?

Question: Basically, I'm curious whether a racket that's sitting idle will lose tension as quickly as one which is being regularly played with.
The concrete sport in question is badminton, though I suspect that the same answer holds true for tennis, squash and so on.
Answer: No, an idle racket will not lose tension as quickly. Any impact sustained by a string-bed will reduce its tension. A more intense impact will reduce the tension more. Thus, the effect in badminton is weaker than in tennis, but still existent.


Acionar um botão pelo teclado

Question: Olá,
dentro do sistema que estou desenvolvendo o usuário pode alterar um cadastro que está no banco de dados. Gostaria de saber como posso fazer para que ao invés de o usuário conseguir salvar as alterações apenas clicando no botão "alterar" ele consiga fazer isso pelo atalho "ctrl+s" no teclado.
Obrigado.
Answer: Use Javascript.

Primeiro reconheça qual será o comando que você deseja utilizar.
Depois, defina uma function que irá inserir este atalho.
Por fim, chame a função desejada.

Neste exemplo: Atalho: (Alt + 'a')
document.onkeyup=function(e){
  var e = e || window.event; // for IE to cover IEs window event-object
  if(e.altKey && e.which == 65) {
    //Chama sua função JS aqui
  }
}

Neste site você pode pegar qual o código para cada tecla desejada.
Answer: Funciona também em Mac:

document.addEventListener("keydown", function(e){
 if (e.keyCode == 83 && (navigator.platform.match("Mac") ? e.metaKey : e.ctrlKey)){
  e.preventDefault();
  alert("CTRL+S pressionado!");
 }
}, false);
Clique aqui e Pressione CTRL+S (para teste)

Acionar um botão pelo teclado


How do find if a control is a listbox using jquery?

Question: I have a dynamic aspx pages where asp.net controls will be enabled and disabled.
I am checking what kind of controls are present so that i can validate.
i can check wether a controls is a checkbox or radiobutton but how can i check if it is a listbox.
i am trying this but not working any help
  if (control.is('input[type="radio"]')) {
                         alert("radiobuttonlist");
                     }

  if (control.is('input[type="option"]')) {
                         alert("listbox");
                     }

the listbox one is not working how to check if there is a control listbox type
Comment: `option` is not an input element type. Your selector should probably just be `option` or `select`.
Answer: you can try
control.is('select[multiple]')

Answer: It could be because you're looking for
control.is('input[type="option"]')

Input elements don't have this kind of type.
Maybe you could look for
control.is("option")

Elements
Here you go
fiddle
Since you are selecting all the inputs in your $().each because the select is not an input it was not selected by jQuery I changed a little bit the .each() and I evaluated to search it the current object was a select.
Comment: In your code control.is('input[type="radio"]') evaluates to true? right, the thing here is that an input cannot be of type "option". Could you add some code of the example html that you want to check if it exist to see if I can help you
Comment: I added a fiddle with some changes.
Comment: can you post the link to your fiddle..i don't see any change in my fiddle


After updating I got these error messages

Question: After updating my Drupal 8 test site from 8.3.7 to 8.4.0, I got these error messages:

Mismatched entity and/or field definitions
  The following changes were detected in the entity type and field definitions.
Webform submission

The Sprache field needs to be updated.

Absatz

The Veröffentlicht field needs to be updated.
The Behavior settings field needs to be updated.

What do I have to do? I don't know how and where I should update these fields. Should I update any database table, or is there another workaround?
Answer: Try on terminal this command

drush entity-updates

Or if you have Devel module installed, you can also use the "Execute PHP Code" page at http;//example.com/devel/php

try {
  \Drupal::entityDefinitionUpdateManager()->applyUpdates();
}
catch (EntityStorageException $e) {
  print_r($e);
}


Prove that a squared number is an equivalence relation of $-1\pmod{p}$

Question:
Prove that a squared number is an equivalence relation of $-1\pmod{p}$.

Lets assume that $p$ is a prime number which satisfies:
$$p \,\equiv\, 1 \pmod{4}.$$
How can one find a natural number $n$, which yields:
$$n^2 \,\equiv\, -1 \pmod{p}\;?$$
Comment: Do you know Gauss integers?
Comment: @Berci yes sir, please keep on ...
Comment: Note that if you already have $u,v$ such that $u^2+v^2=p$, then it's easy to find $n\equiv-1\pmod p$
Answer: First find a small non-residue, call it $c.$ When $p \equiv 5 \pmod 8$  we may choose $c=2.$ When $p \equiv 2 \pmod 3$  we may choose $c=3.$  Otherwise, one may just check small numbers in order, checking $(c|p)$  by quadratic reciprocity until we find $(c|p) = -1.$  Tests have been done on this, the first non-residue $c$ is typically tiny.
Then find
$$  n \equiv c^{\frac{p-1}{4} } \pmod p .   $$
When $p$  is large, we use the powermod algorithm. The result is that
$$ x^2 \equiv -1 \pmod p $$
first non-residue for small primes $1 \pmod 4$
=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
<code>    5    2
   13    2
   17    3
   29    2
   37    2
   41    3
   53    2
   61    2
   73    5
   89    3
   97    5
  101    2
  109    2
  113    3
  137    3
  149    2
  157    2
  173    2
  181    2
  193    5
  197    2
  229    2
  233    3
  241    7
</code>
=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
Comment: Could you elaborate how did you get $c^\frac{p-1}{4}$ ? why did you divide $p - 1$ by 4?


GAE, memcache before DB update

Question: I have some troubles with memcache and GAE DB operations.
if i update memcache rigth after DB operations, x.put(), for example, my memcache function  often return old value. If i use sleep(), cache more often correct, but this is not right, in my opinion
sleep(0.2)
data = Picture.all().order('-created').fetch(300)
memcache.set('pictures_all', data)

What i need to do, to get correct memcache?
ANSWER:
Need to use parent with query, all Picture entities must have same parent, then you get strong consistant results
data = Picture.all().order('-created').ancestor(main_key()).fetch(300)
memcache.set('pictures_all', data)

Answer: If you have the data, just update one entry in the memcache, no need to retrieve all from memcache. Something like
data.put()
memcache.set(key, data)

Comment: not really good in my case. Is there a way to wait, before DB is updated, and after get a correct values?
Comment: why is it not really good? If you only update one entity, why do you need to fetch all the data? It will be more efficient to update one entry in your memcache to reflect the changes
Comment: its prototype, i just need correct caching on update, its enough at this time, without complexity. When i will be behind of appspot quotes, i definitely use your more advanced way of caching, thanks
Answer: config = db.create_config(deadline=10, read_policy=db.STRONG_CONSISTENCY)
data = Picture.all().order('-created').fetch(300, config=config)
memcache.set('pictures_all', data)

I guess, this is solution.
EDIT: No, this is dont work
Comment: Don't you want it the other way?
https://developers.google.com/appengine/docs/python/datastore/queryclass#Query_fetch

read_policy
Read policy specifying desired level of data consistency:
STRONG_CONSISTENCY
Guarantees the freshest results, but limited to a single entity group.
EVENTUAL_CONSISTENCY
Can span multiple entity groups, but may occasionally return stale results.
Answer: You're on the right track that the problem is with eventual consistency.
Using STRONG_CONSISTENCY does solve the problem, but it'll give you scalability problems down the road - ones that will be difficult to resolve.
The solution for this is, annoyingly, more complex than it should be.  I'm also not sure whether there's really a bulletproof solution given the eventual consistency behavior.
pseudocode should look something like this:
all_pictures = memcache.get('pictures_all')
if not all_pictures:
    all_pictures = convert_to_list(Picture.all().order('-created').fetch(300))
if not newdata in all_pictures:
    add_to_list_in_proper_order(all_pictures, newdata)
memcache.set('pictures_all', all_pictures)

Answer: Great.
I had the same problem and the solution was exactly what asker gave: the use of ancestors
To read:
data = Picture.all().order('-created').ancestor(main_key()).fetch(300)

To save:
pic = Picture(parent=main_key(), ...)
pic.put()

Comment: But depends on if Pictures are or aren't more readed than writed, I said that because with the use of ancestors, only 1 write per second is allowed to all the ancestor group.

GAE, memcache before DB update


Grabbing rows from MySql where current date is in between start date and end date (Check if current date lies between start date and end date)

Question: I'm trying to select from the database to get the "campaigns" that dates fall into the month. So far i've been successful in grabbing rows that starts or ends inside the current month. What I need to do now is select rows that start in one month and ends a few months down the line ( EG: It's the 3rd month in the year, and there's a "campaign" that runs from the 1st month until the 5th. other example There is a "campaign" that runs from 2012 until 2013 )
I'm hoping there is some way to select via MySql all rows in which a capaign may run. If not should I grab all data in the database and only show the ones that run via the current month.
I have already made a function that displays all the days inbetween each date inside an array, which is called "dateRange". I've also created another which shows how many days the campaign runs for called "runTime".
Select all (Obviously)
$result = mysql_query("SELECT * FROM campaign");

Select Starting This Month
$result = mysql_query("SELECT * FROM campaign WHERE YEAR( START ) = YEAR( CURDATE( ) ) AND MONTH( START ) = MONTH( CURDATE( ) )");

Select Ending This Month
$result = mysql_query("SELECT * FROM campaign WHERE YEAR( END ) = YEAR( CURDATE( ) ) AND MONTH( END ) = MONTH( CURDATE( ) ) LIMIT 0 , 30");

Code sample
while($row = mysql_fetch_array($result))
{
$dateArray = dateRange($row['start'], $row['end']);

echo "
" . $row['campname'] . "
 Start " . $row['start'] . "
 End " . $row['end'];
echo runTime($row['start'], $row['end']);
print_r($dateArray);
}

In regards to the dates, MySql database only holds start date and end date of the campaign.
Answer: to detect overlap of date/times, you can do something like this:
//range of dates to get overlap. means if any row in the database has
//a day in its start/end range that falls between these days
$startDate = '2012-06-01';
$endDate = '2012-06-30';

$sql = "SELECT *
    FROM campaign
    WHERE
        `start` < '$endDate'
        AND `end` > '$startDate'";

that will find any row from campaign that has any day that falls between the $startDate and $endDate. This also works for all occurrences of campaign...:

starts before $startDate and ends before $endDate (end date between date range)
starts after $startDate and ends before $endDate  (both start and end between date range)
starts before $startDate and ends after $endDate (start and end encompass date range)
starts after $startDate and ends after $endDate  (start date between date range)

Also, this query as it stands is has $startDate and $endDate as exclusive. Meaning that if something starts on 31-May (based on the example dates above) and ends on 1-Jun, it would not be included. If you want the dates to be inclusive, you can change the > and < to be >= and <= to include the start and end date.
Comment: That was perfect and exactly what I was hoping for! Thank you so much.


Trocando Value Object no banco de dados

Question: Estou lendo o livro de DDD (Eric Evans) que diz as implementações de Value Object são imutáveis e se quiser mudá-lo, você terá que criar um outro. Em exemplos mais comuns onde tem uma classe Pessoa e outra classe Endereco, você recriar o endereço ao invés de alterar o objeto, isto funciona ok.
E li também https://cargotracker.java.net/ e https://gojko.net/2009/09/30/ddd-and-relational-databases-the-value-object-dilemma/. Mas eu tenho algo um pouco diferente que surgiram dúvidas.
Eu estou trabalhando num sistema de billing, e contém 4 tabelas
Pessoa - campos: idPessoa, Nome -> <<Entity>>
Celular - campos: idCelular, Numero -> <<Entity>>
Vigencia - campos: idVigencia, idPessoa, idCelular, dataInicio, dataFim -> <<Value Object ou Entity????>>

A tabela Pessoa seria o cadastro de funcionário da empresa, suponhamos que tenha em torno de 10 mil registros
A tabela Celular são dados de todos celulares que a empresa possui, suponhamos uns 3 mil registros
A tabela Vigencia é a associativa de Pessoa X Celular, exemplo, o "Joao" está com o celular "11 91234-5678" na data inicial "01-01-2016" e a data final ficaria nula significando que ainda este celular está com ele, e este registro teria um "idVigencia" 1, que não é relativo ao negócio.
Agora que estamos no dia 20/08/2016, ficamos sabendo que o "João" não é mais dono deste celular, e agora é a Maria. Então na tabela de "Vigencia" atualizaria a "data final" da vigencia do "João" para "31-07-2016" e criaria outro registro para a "Maria" com a "data inicia" em "01-08-2016", assim diz que o celular "trocou" de dono
Ligacao - campos: idLigacao, idVigencia, etc... -> <<Value Object>>

Na tabela de ligações, temos ligações do mes 05, 06, 07 e 08 de 2016, onde este celular está com o João, então a FK do campo idVigencia da tabela de Ligação será o numero 1 neste caso, só que com a mudança da "Vigencia" do "João" o mês 08/2016 estaria com a FK errada e deveria ser reprocessada.
Sendo assim, a "Vigencia" seria um Value Object ? (que também é minha duvida, pois poderia talvez ser um Entity, porém não vejo uma identidade no "idVigencia", talvez no conjunto de campos)
Caso for um <> a vigencia seria imutável e ao atualizar o "João" colocando a "data final" para "31-07-2016", teria que descartar o objeto e criá-lo novamente, só que entra no problema em relação a FK "idVigencia" da tabela de "Ligação"
Qual a melhor maneira de implementar isso com DDD?
Comment: Existe relação entre `idPeriodo` e `idVingencia`, é isso?
Comment: Vale lembrar que a abordagem, ou mesmo a arquitetura em si, deve servir a necessidade do seu projeto, e não o contrário. Você tem um fluxograma tipo "guardanapo de restaurante"? Comece simples, faça as ferramentas trabalharem pra você ;-)
Comment: @MarcoAurelio Obrigado pela resposta. Acredito que faltou dados na pergunta. Colocarei numa resposta abaixo para ficar mais clara as informações, toda ajuda é bem vinda, peguei esse problema como exemplo mesmo
Comment: Conforme mencionado, um Value Object não se altera. E, ao contrário do que também está mencionado na pergunta, não há como "mudá-lo". Se, em algum cenário, algum valor deve mudar, e tal mudança é natural, então isto indica que não se trata de um Value Object.
Answer: É um típico problema de se criar Value Object estruturados em bases relacionais. Começa-se a criar ID para o VO, por necessidade, mesmo sabendo que um VO não possui ID por definição.
Para realmente ajudar a resolver seu problema, eu precisaria conhecer mais do negócio. Mas o pouco que você passou, vou arriscar o seguinte:

Caso seja removido o idPeriodo - que eu imagino que seja o FK para Vigência, seu problema está resolvido

E, para relacionar as ligações com a vigência, poderá usar apenas as datas. Assim fica-se livre para manter as datas ou qualquer outra propriedade de Vigência, sem precisar recriar todas as ligações.
Para pesquisar as ligações em uma vigência, pode-se usar o idCelular mais das datas. Acredito que será performático o suficiente.
Comment: alterei a pergunta colocando mais detalhes sobre o negócio, a data da ligação acredito que com o volume extremamente alto, poderá ter impacto em performance :( . Espero ter conseguido melhorar minha pergunta acima que editei
Answer: DDD é para o domínio, tabelas é para a persistência
O seu modelo OO rico provavelmente possui a classe Pessoa, Vigência e Telefone. Acredito que em Vigência há uma referência para Pessoa e outra para Telefone, além dos demais atributos. Quando se trata de um Value Object os atributos não podem ser alterados (pois isto é da natureza de um Value Object), o que não é o caso com Vigência. Então, Vigência não é um Value Object, pois você pode estender a data final, o que é natural para uma vigência, mas não faz sentido em um Value Object.
Quando se pensa em um Value Object V com o atributo x com um dado valor, se houver possibilidade de x possuir ou assumir outro valor diferente daquele de V, então se trata de outro objeto, não é o mesmo.
Por fim, DDD visa refletir com fidelidade um domínio, enquanto tabelas tem como foco a persistência, o que são tópicos distintos e, muitas vezes, conflitantes. Persistir um modelo OO rico, em geral, usando o modelo relacional, introduz vários desafios. A incompatibilidade entre estes modelos é conhecida por impedance mismatch (https://en.wikipedia.org/wiki/Object-relational_impedance_mismatch). Se você evitar os desafios, provavelmente está abrindo mão do modelo OO, porque seu banco relacional não irá deixar de ser relacional.

Trocando Value Object no banco de dados


After logout if browser back button press then it go back last screen

Question: Hello I am developing a solution in MVC in first time so I am facing a big issue,
When I logout from my application(mvc razor web application) it displays login page, but if i  press browser back button it displays last screen, i don't want this, i want if i press back button it still display same login page.
here is my code for logout
public ActionResult Logout()
    {
        Session.Clear();
        Session.Abandon();
        Session.RemoveAll();

        FormsAuthentication.SignOut();

        this.Response.Cache.SetExpires(DateTime.UtcNow.AddMinutes(-1));
        this.Response.Cache.SetCacheability(HttpCacheability.NoCache);
        this.Response.Cache.SetNoStore();

        return RedirectToAction("Login");
    }

Comment: There is no reason to call Clear AND Abandon together. Pick one or the other otherwise you could have some behavioural issues in the future such as firing off Session specific events unexpectedly.
Comment: you say when you press the back button on the browser and it displays the last screen, what is the last screen and where is the logout being called from? surely the last screen would be a logout page thus nothing really to see?
Comment: Use the System.Web.Mvc.OutputCache attribute to decorate your controller or its actions.
Answer: I had this problem a while ago, disabling the cache for the entire application solved my problem, just add these line to the Global.asax.cs file
        protected void Application_BeginRequest()
        {
            Response.Cache.SetCacheability(HttpCacheability.NoCache);
            Response.Cache.SetExpires(DateTime.UtcNow.AddHours(-1));
            Response.Cache.SetNoStore();
        }

Hope this helps.
Comment: its a bad solution to disable cache of pages for the entire application meaning even more hits to your server to execute the action again. the solution here should be an isolated one, not across the whole application.
Comment: AthibaN's solution is the best. Thank you, sir.
Comment: Does this mean you can't cache _anything_ in the whole application?
Comment: nope, but when you hit back, your control hit your Action instead of loading the previously visited page directly.
Comment: disabling the back button is just a workaround and i hope you're aware that decorating all the actions or controllers with `NoCache` is almost same as mine !
Comment: @Ahmed ilyas i agree with you, server gets more hits, but it works as expected, care for a better solution ?
Comment: Definitely not disabling it across the application for a start :) hehe. As for a better solution - im working on it. there are so many things to consider unfortunately so its a challenge to pick the best practice and right solution for the scenario (as simple as it may seem). Remember, different browsers act differently too so that's another factor.
Comment: solution by Murali should be ok, alternatively http://stackoverflow.com/questions/12948156/asp-net-mvc-how-to-disable-automatic-caching-option
Comment: Solution provided by AthibaN and Murali are considrable, my priority is to restrict go back after logout. Thanks both of you.
Answer: You need to add the cache META Tag for all the last page you visited
So add this for all the pages, by making a CustomAttribute like [NoCache] and decorate
public class NoCacheAttribute : ActionFilterAttribute
{
    public override void OnResultExecuting(ResultExecutingContext filterContext)
    {
        filterContext.HttpContext.Response.Cache.SetExpires(DateTime.UtcNow.AddDays(-1));
        filterContext.HttpContext.Response.Cache.SetValidUntilExpires(false);
        filterContext.HttpContext.Response.Cache.SetCacheability(HttpCacheability.NoCache);
        filterContext.HttpContext.Response.Cache.SetNoStore();

        base.OnResultExecuting(filterContext);
    }
}

public class AccountController : Controller
{
    [NoCache]
    public ActionResult Logout()
    {
        return View();
    }
}

Or try it with javascript on the page like

Comment: but will this disable the cache for all the action methods ?
Comment: @Murali Murugesan The [nocache] is not getting fired when i use it above the logout but it is when i use it above the controller class
Answer: Easiest way for a MVC 5 Application is:
[OutputCache(NoStore = true, Duration = 0, VaryByParam = "None")]

Above each of the Controller Methods you don't want to Cache. Or if you are using .Core the following works:
[ResponseCache(Location = ResponseCacheLocation.None, NoStore = true)]

Have a nice day!
Answer: protected void Application_BeginRequest()
        {
            Response.Buffer = true;
            Response.ExpiresAbsolute = DateTime.Now.AddDays(-1d);
            Response.Expires = -1500;
            Response.CacheControl = "no-cache";
            Response.Cache.SetNoStore();
        }

Add [Authorize] filter on each controller

Answer:   protected void Application_BeginRequest()
    {
        Response.Cache.SetCacheability(HttpCacheability.NoCache);
        Response.Cache.SetExpires(DateTime.UtcNow.AddHours(-1));
        Response.Cache.SetNoStore();
        string emailAddress = null;
        var cookie =Request.Cookies[FormsAuthentication.FormsCookieName];
        // Nothing to do if no cookie
        if (cookie != null)
        {
            // Decrypt the cookie
            var data = FormsAuthentication.Decrypt(cookie.Value);
            // Nothing to do if null
            if (data != null)
            {
                // Deserialize the custom data we stored in the cookie
                var o = JsonConvert.DeserializeObject<FormsAuthenticationTicketData>(data.UserData);

                // Nothing to do if null
                if (o != null)
                    emailAddress = o.EmailAddress;
            }
        }
        SetupAutoFac(emailAddress);
    }

Answer: you can use onClick event of javascript to prevent browser back.
for example:
Logout

Hope this will help you, Happy Coding!
Answer:
Open your views.py file in your Django application.

Import the cache_control decorator.

Apply the @cache_control decorator to the view rendering the
protected page.

    from django.views.decorators.cache import cache_control

    @cache_control(no_cache=True, must_revalidate=True, no_store=True)
    def protected_view(request):
        # Your view logic here


Jtree removeFromParent() creates whitespace

Question: I am creating a JTree for a project of mine, and the names for some of the nodes dynamically change, and I'm updating the tree using this function:
public void updateTree() {
    for (Sprite spr : sprites) {
        spr.getMyNode().removeFromParent();
    }
    treeModel.reload();
}

However, when I call this, a row of whitespace shows up like this:
Foo
    Child

Foo2

Answer: I fixed it, I was experimenting and scrolling through the method list of JTree and found tree.updateUI()
and that fixed it.


What is the correct way to organise and separate functions in a Controller into their own files?

Question: Here is my test.routing.yml:
test.alpha:
  path: '/test/alpha'
  defaults:
    _controller: Drupal\test\Controller\TestController::testAlpha
    _title: 'Alpha'
  requirements:
    _permission: 'access content'

test.bravo:
  path: '/test/bravo'
  defaults:
    _controller: Drupal\test\Controller\TestController::testBravo
    _title: 'Bravo'
  requirements:
    _permission: 'access content'

sitelog.charlie:
  path: '/test/charlie'
  defaults:
    _controller: Drupal\test\Controller\TestController::testCharlie
    _title: 'Charlie'
  requirements:
    _permission: 'access content'

Here is my Controller: TestController.php:
namespace Drupal\test\Controller;

class TestController {
  public function testAlpha() {
    return array(
      '#type' => 'markup',
      '#markup' => 'Hello, World!',
    );
  }
  public function testBravo() {
    return array(
      '#type' => 'markup',
      '#markup' => 'Hello, World!',
    );
  }
  public function testCharlie() {
    return array(
      '#type' => 'markup',
      '#markup' => 'Hello, World!',
    );
  }
}

My Controller file is set to grow. I will be adding many more functions, and adding hundreds of lines of code to all of those functions.
What is the correct way of organising and separating out those functions into their own files, in a Drupal 8 project?
In Drupal 7 we used .inc files to keep files from getting too large. Sometimes a common.inc would be used to group reusable functions.
What I like about React is that functionality is broken up into separate components, into separate files. I prefer lots of files, containing a small amount of code, organised into folders.
I'd like to bring this same approach into my Drupal 8 projects, but follow the correct PHP standards/Drupal best practice. My goal being to improve: the readability of my code, ease of finding my code, and possibly, the organisation of reusable code.
Answer: There are a few things that you can do.

As already suggested by Jaypan, you can have as many controllers as you like, grouped by whatever makes sense for you. You can also have a base classes/hierarchy and re-use code through that
You can define services and also static classes/methods to extract re-usable logic (or also not-reusable logic). I'd say that's the 1:1 replacement for functions in include files. Services are defined in a yourmodule.services.yml and you can use dependency injection to make each service self-contained with explicit dependencies to other systems, so that you can also write (unit) test for that code.
You can also use Traits, a relatively new PHP feature that basically allows you to put a few methods into a separate file and include it in one or several classes where you can use them internally as if they were defined on that class. Kind of like a base class except that you're not limited to a single trait, you can have as many as you want.
Answer: You're doing it correctly the way you are doing it. If you really want to split it into multiple files for readability, then you can create multiple controllers, grouping them by type. For example, I'll often have a PageController and an AjaxController in a module, putting anything that returns an AjaxResponse into the AjaxController, and anything that returns a render array into the PageController.
This isn't required, but it will keep your files shorter and more readable. That said, for controllers, the search function in any IDE makes it pretty easy to find whichever callback you need in a flash.
Comment: To be clear about a controller: A controller responds to a request from a route. It generates the page output. It goes in mymodule/src/Controller/ because Drupal 8 supports PSR-4. Correct? Can it then, or should it then,  contain more than just the return of a render array?
Comment: For the most part you're right, but render arrays are only one type of response that can be returned. HtmlResponse, JsonResponse, AjaxResponse, and even the Symfony class Response can all be returned as well. And I haven't tested yet, but if it's the same as D7, a simple string or integer may also be returned (though note that returning an integer caused unexpected results in D7).
Comment: Is it to be regarded as the 'C' of 'MVC'? The 'view' being, most likely, a Twig template, and the 'Model' being all the other code? Is that the concept underlying the 'controller' file?
Comment: You can think of it that way, though I'm not entirely sure that D8 follows the MVC model. D7 didn't.


Gateway/Router - Multiple Public IPs on Virtual WAN Interfaces Through Single WAN Interface/Port

Question: I am looking to setup a router with multiple public WAN/IP interfaces that can be routed across a single physical WAN interface/port. I realize it would be necessary to have different MAC addresses on each interface for full layer 2 compatibility, but this could be achieved via MAC cloning, randomizing the MAC, or using some sort of virtual MAC assigning (Similar  to VMware Virtual LANs and Interfaces).
I'm pretty sure this is possible, as I've seen very similar setups for server environments with Linux network configs and only using a single physical NIC, but can anyone confirm this is possible or have a solution or basic explanation of why or why not this might work?
If so, is it possible with something like DD-WRT specifically? This is what I'm currently running on my Asus RT-N66U. OpenWRT seems much more similar to traditional Linux network configuration, but unfortunately isn't supported on my router. DD-WRT however works great, but network configuration is done through NVRAM variables - which isn't documented well, especially with network configuration specifically and interfacing.
I eventually will have some IPTables configuration to route separate subnets(maybe VLANs, but I would prefer to keep everything open and accessible, but limited to specific subnets) to each individual WAN interface.
What I don't want to have to do is configure multiple LAN ports to be used as WAN ports and setup a "dual" WAN connection and then just bridge them physically with a switch to connect to my single physical WAN connection to my ISP.
Here's a good example of what I'm looking to do, just with an actual network router rather than a server with a single NIC.
Edit:
ISP provides internet via RADIUS/MAC authenticated DHCP connections. They also provide static IP blocks. Both options are available to me and work in any configuration. My main question here is how to setup virtual interfaces with a router. Preferably with DD-WRT, as that's what I'm currently using
Comment: This doesn't make much sense. If you have multiple ISPs, you need to have multiple physical interfaces. If you just have multiple IP addresses from a single ISP, you can just add them all to a single interface.
Comment: @MichaelHampton when using WAN dialups like PPPoE it is rather easy to have a single WAN interface on the router to dial up different ISPs (possibly even over a number of modems interconnected by a switch). But you would not need different MACs, IPs or any other voodoo for this - just the ability to perform more than one PPPoE dialup. I agree that the question is rather vague in this respect.
Comment: @MichaelHampton Many ISPs assign addresses via dhcp and you just can't do that for multiple addresses if you only have one MAC.  Virtualization is the answer to this problem.
Comment: @IronSavior Precisely! I multiple options for connecting to my ISP. In this specific situation, I'm using DHCP and static IP's provided by my ISP. For Layer 2 communications to work correctly across a WAN, multiple IP's can't ARP to the same MAC - or at least they're not supposed to. WAN and LAN have different limitations.
Answer: This is not only possible, but also common.  My preferred method is to employ some sort of hypervisor to host discrete units of function each within their own virtual machine.  Using this sort of technology will allow you to provision the ideal configurations in virtualized resources as well as keeping them somewhat isolated from each other.  For example, you could very easily have a machine with a single physical NIC that hosts a gateway device that has been endowed with as many virtual nics as is convenient for your application.
As a testament to how easy this is, I happen to use Xen on a Intel Atom "netbook"-type computer to host a half-dozen individual VM's that provide network services at home.  I know SF doesn't like to hear about home solutions--I only offer this as an anecdote, Xen is a mature production-ready hypervisor and I promise you that it is up to this task.  This one physical NIC masquerades as many different devices and it also does VLAN tagging where appropriate.
If you want something a little lighter weight, you can also provision "macvlan" interfaces in Linux, but I've found the documentation to be hard to come by.  I've made it work, but it was a lot more messy than going with Xen and provisioning VM's that behave as if they have many interfaces (or whatever hypervisor you may prefer because vmware is just as capable on the right hardware.  I used Xen with the Atom CPU, but I've done the same with vmware with hardware that was more purpose-built for virtualization).
Comment: This is very interesting and good to know! I've built similar setups like this, but only with hyper-v, VMware, and some Linux configuration's. However, in this circumstance, I'm looking to do this with my gateway/router. I just can't seem to make it work. I think it's mostly because of NVRAM network configuration instead of the traditional Linux network interface files and ifconfig in combination with IPTable for firewall/routing.


why does preprocessed test data change with change of calibration data in PLS-DA?

Question: Why does preprocessed test data change when calibration dataset (and model based on that data) changes? I have spectral, normalized datasets, the preprocessing was 1. derivative + autoscale.
For example: I have 2 datasets: 100 samples with 400 variables each as calibration data; 20 samples for test data. preprocessing as above, data was cross-validated as well. the model for PLS-DA was calculated using pls toolbox in matlab. when I plot preprocessed test data I get different results compared to situation when I used e.g. half of those calibration-set samples to create a model. and I can't plot preprocessed test data without calculating the model. how is it connected?
I also tried to put my 20-sample test data as calibration data just to create model, and the preprocessed data plot was also different from plots obtained before.
Answer: It has nothing to do with PLS-DA, it is related to autoscaling spesifically. While taking derivative (or smoothing) is applied per spectrum, the autoscaling does the following:

Calculate the mean of each variable using all calibration set
samples
Subtract this mean from from each variable on both calibration and
validation set
Calculate standard deviation (STD) for of each variable using
all calibration set samples
Divide each variable by this STD on both calibration and validation
set

Therefore, if your calibration set changes, the mean to be subtracted changes. Same happens with STD too.
Comment: Now it's understantable for me, thank you. I have one more question to ask - is it reasonable to use the same preprocessing method as above but in opposite order (which is to use autoscale first and then 1. derivative)?


MySQL query with/without table specific reference

Question: In Joomla 2.5.14, when I create a query to MySQL using PHP, like:
$query = "SELECT id FROM xmb9d_content WHERE state=1" ;

It all works fine, but if I don't want a specific reference to the database prefix (xmb9d_) and use:
$query = "SELECT id FROM #__content WHERE state=1" ;

The query isn't executed. Is this the right way of building the query or what is wrong with this code?
Comment: You're not showing how you execute the SQL query, that would be helpful, the "#__" is replaced by Joomla when you use Joomla's database methods.
Answer: You need to use the database prefix and also stick to Joomla 2.5 coding standards. There shouldn't be any problems with the prefix, providing your query is correct.
This is how it should look:
$db = JFactory::getDbo();

$query = $db->getQuery(true);
$query->select('id')
 ->from('#__content')
 ->where('state = 1');

$db->setQuery($query);

$results = $db->loadObjectList();

Comment: Yes, that's the idea: to comply with J2.5 standards, keep the code clean and easy to maintain although I'm not at all familiar with it yet. Thanks for your help!
Comment: There is good documentation for Joomla now. Have a look around on there and on Stackoverflow to find good examples ;)
Answer: xmb9d_content is the name of the table by replacing it with #__content you are attempting to run the query on a table that doesn't exist (i assume) so it wont work.
What is the issue with the prefix? I don't understand how it could cause you an problems
Comment: This is a Joomla-specific notation. `#__` is automatically replaced by a predefined table prefix which allows several installations to use the same DB, with different prefixes.


Programmatically add button to block

Question: 7 - How do I programmatically create a button, place it in a block, 'weight it' and then make it visible to certain pages?
Code I've tried:
function openid_connect_block_info() {
  $blocks['openid_connect_login'] = array(
      'info' => t('Login Using PixelPin'),
      'cache' => DRUPAL_CACHE_PER_ROLE | DRUPAL_CACHE_PER_PAGE,
      'region' => 'content',
      'pages' => 'user/',
  );

  $blocks['openid_connect_register'] = array(
      'info' => t('Register Using PixelPin'),
      'cache' => DRUPAL_CACHE_PER_ROLE | DRUPAL_CACHE_PER_PAGE,
      'region' => 'content',
      'pages' => '/user/register',
  );
  return $blocks;
}

This code creates the button but doesn't put it under the content block and doesn't make it only visible on the specified pages.
Answer: Why not render in a tpl so you can control the look of it?
I see you already used hook_block_info() so you can complete this using hook_block_view() with a custom callback function to use hook_theme()
Here is a complete example of it:
function openid_connect_block_info() {
  $blocks['openid_connect_login'] = array(
      'info' => t('Login Using PixelPin'),
      'cache' => DRUPAL_CACHE_PER_ROLE | DRUPAL_CACHE_PER_PAGE,
      'region' => 'content',
      'pages' => 'user/',
  );

  return $blocks;
}

then:
function openid_connect_block_view($delta = '') {
  $block = array();
  switch ($delta) {
    case 'openid_connect_login':
      $block['content'] = openid_connect_login();
      break;
  return $block;
}

then:
function openid_connect_login() {
  return theme('openid_connect_login_tpl', array('data' => NULL));
}

last thing here:
    function openid_connect_theme($existing, $type, $theme, $path) {
      return array(
        'openid_connect_login_tpl' => array(
          'variables' => array('data' => NULL),
          'template' => 'openid-connect-login',
          'path' => drupal_get_path('module', 'openid_connect') . '/theme',
        ),
);
}

create your file inside you module under the name we gave openid-connect-login.tpl.php and put it in a folder I named theme ..
I hope I understood it right and was helpful for you issue ..
Comment: So do i put openid_connect_theme in it's own file under the theme folder?
Comment: the openid_connect_theme() function should still be in the module file ,, but tpl file (openid-connect-login.tpl.php) should be in the theme folder yes

Programmatically add button to block


Message "current thread is in sleep,wait or join state" - locking?

Question: I have encountered (for me) very strange problem. In my app, when pressing start button, all threads are activated, when pressing stop button, all threads are aborted and all collections are cleared.
This is all happen at the main thread, while other procceses have their own threads or are running via threadpool. However, today I replaced ReaderWriterLock with ReaderWriterLockSlim and rarely, when I press "STOP" button the app will freeze. With Break all I can see the coed is stuck on the line this.someobject.TryEnterWriteLock(-1) and when I display details, the variables are all filled with this message:
"Cannot .... because current thread is in sleep,wait or join state"
I dont understand it - its the main application thread. I do not expect direct answer rather than advice what should I look for, this message I have never seen before.
Thank you!
Comment: Please post some code samples.
Answer: Do not be confused by the message - it is there because the debugger cannot access the values - your main thread is locked. Why it is locked - there is no saying without the code.
BTW did you try to look at other threads in your app?
Comment: But...I have NO locks in the main thread. The methods are ran from different threads and thats why I am asking about the message related to current thread.


Is it possible to have an example at endpoint level that populates all parameter's values in openapi spec?

Question: I know that we can have examples in the drop down menu for each parameter in the openapi spec. This requires to select each example for each parameter.

I was wondering if it is possible to have a drop down menu for the endpoint that we can select the example and that example has the values for all parameters in that endpoint.
Answer: This is not supported - neither by the OpenAPI Specification nor in Swagger UI. Here's an existing feature request in the OpenAPI Specification repository:
https://github.com/OAI/OpenAPI-Specification/issues/1673


How to host a Wordpress site on multiple servers due to geographical siteload issues?

Question: Wordpress website is currently hosted in the US, this is where 40% of our target audience is. The rest of visitors are coming form Middle east, Australia, Russia, China, Singapore, UK, Switzerland, Kazakstan... all over the map.
With all caching in place (not CDN) it still barely loads in Asia / Oceania and has speed issues in Europe.
Can I simply setup multiple servers and create multiple A records that point to different servers in different regions and assume that a visitor from Australia will be served form australian server?
Any tips?
Comment: Have you measured how slow the website is, and what the cause is? Without details you're likely to just get random performance advice. My top tip is CDN. Caching & DB are good to look at after that.
Answer: The problems with geographically distributing WordPress, as you'll see, all revolve around the MySQL database.
There are basically two ways to architect this:
Read replicas
In this architecture, you run your LAMP frontend with WordPress in several geographic locations, each of which has a read-only replica (slave) of the master MySQL database. You will need to use something like MySQL Proxy to direct write operations back to the master, as WordPress doesn't natively support using a different database connection for reads versus writes.
The big problem with this setup is that if your master goes down, you can't make changes (e.g. no new posts or comments). So the master should probably be clustered or otherwise protected (e.g. using Amazon RDS Multi-AZ). Database writes are also delayed slightly due to network latency between the LAMP frontend and the remote MySQL master.
Multi-master
In this architecture, you run your LAMP frontend with WordPress in several geographic locations, each of which has a multi-master replicated database, using something like MariaDB Galera or an equivalent MySQL solution (if you can find one). You need to have at least three masters if you go this route.
As there's no single point of failure, it really doesn't matter if one master goes down (so long as they don't ALL go down at the same time; that situation requires manual intervention to recover).
The problem with this is that writes take much longer, as they have to be replicated to all of the multiple masters. So people may notice a few seconds' delay when doing anything that writes to the DB, such as commenting or writing a new post. In practice, this delay isn't that significant, as users already expect delays when they submit information in these contexts.

If you have three or more geographic locations you're going to deploy to, I'd go ahead and spend the effort to go multi-master. If you only have two locations, you can get by with a read replica and proxy for now.
Comment: On that note, be prepared for *slow* shell access overseas. I had a server in Japan through AWS (because I could, mostly) and the delay was a good 1-2 seconds.
Comment: Ok, so If we take one of these roads what do we do with the DNS? How do I get the Australian audience to the Australian server, and US audience to the US server? - that's the main question.
Do we just point multiple A records to different servers?
Answer: I'm assuming since this question has been tagged amazon-web-services that your Wordpress site is running on Amazon AWS EC2 instances. If so, you can use Amazon's Route53 product to serve geographic DNS records. You can find an in depth tutorial here. There are other DNS providers that support geographic DNS records such as Dyn but note that it will be a premium feature which you'll need to pay for.
Comment: This is helpful, we are contemplating staying on Amazon or getting a dedicated SSD server for the US, but putting Asia on Amazon. I'll definitely look into Route 53
Answer:
Can I simply setup multiple servers and create multiple A records that point to different servers in different regions and assume that a visitor from Australia will be served form australian server?

no, it not possible. In such case it would be something like round robin. In your case CDN would be the best choice, imho.


How to down-weight older data in time series regression

Question: In a regression fit of vectors varying with time $t$
$\qquad y \sim [x_t\ x_{t-1}\ x_{t-2}\ ...] \cdot [c_t\ c_{t-1}\ c_{t-2} \ ...] $ ,
how can one down-weight the older $x_t$ to model "older is less relevant" (than the regression gives) ?
Say that rows in data matrix $X$ are observables (stocks, market segments ...)
and columns are times.
Correct me,
Weighted least squares
weights rows; how does one weight columns, times ?
Added:
Down-weighting older data in time series looks complex, much more so than
linear least squares with i.i.d. errors in rows (observations) --
just divide through by $\sigma_i$; or
classification  with i.i.d. errors in columns (e.g. features) --
just centre each column.
Can anyone say either

yes, I downweight time series; here are some examples on the web
no: down-weighting time series is complex, not for novices.

(http://AndrewGelman.com/2005/06/21/timeseries_regr  discussed this question 10 years ago,
mentioning Kalman filters and hierarchical Bayes, but with no examples.)
Answer: A common method is to use an exponentially weighted cost function:
$$ \sum_i \lambda^{i} e(t-i)^2 $$
where $e(t)$ is the residual error, and $\lambda$ is the forgetting rate. If $\lambda=1$, you get back least squares regression.
You can use recursive least squares (RLS) to find a solution efficiently.
Comment: Thanks; if you could point to an example, I'll accept. Also on RLS, wouldn't nonlinear least squares aka LevMar be simpler, and fast enough ?
Comment: What kind of example? There are tons of papers using RLS. You want a reference? Also, why nonlinear LS and Levenberg-Marquardt? This cost function is quadratic, and RLS is very simple to implement.
Comment: A runnable example on the web, preferably with real data; python would be nice. Sure there are lots of papers, but is the method ever used in practice ? Also off-the-shelf and stable [scipy.leastsq](http://docs.scipy.org/doc/scipy/reference/tutorial/optimize.html#least-square-fitting-leastsq) is simple.