Fixed points of the adjunction between locally ringed spaces and rings

Question: There is an adjunction between locally ringed spaces and rings given by $R\mapsto \text{Spec}(R)$ and $X\mapsto \Gamma(X, \mathcal O_X)$.
Is that adjunction idempotent?
Roughly equivalent: Is it true that the canonical morphism $R\to \Gamma(\text{Spec}_R, \mathcal O_{\text{Spec}(R)})$ is always an isomorphism and that the canonical morphism $X\to \text{Spec}(\Gamma(X, \mathcal O_X))$ is an isomorphism if and only if $X$ is an affine scheme?
Answer: Yes.

$R$ and $\Gamma(\text{Spec}(R), \mathcal{O}_{\text{Spec}(R)})$ are canonically isomorphic, see here.
If $X \to \text{Spec}(\Gamma(X,\mathcal{O}_X))$ is an isomorphism, then this same isomorphism witnesses $X$ as an affine scheme (it's $\text{Spec}$ of something).

More categorically, we know that the category of affine schemes is antiequivalent to the category of rings (see here) and this equivalence is given by $\text{Spec}$ and $\Gamma$. Idempotent adjunctions always give rise to an equivalence of categories between the categories of fixed points, and we see that behavior here.

I hope this helps ^_^


dynamically alter attributes of shape defined in xml?

Question: Currently using the following xml code as a background for a button in a program I am making. However, I would like to dynamically alter the background gradient within my code.

<shape xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/buttonshape"
 android:shape="rectangle">
 <gradient android:startColor="#F0F0F0" android:endColor="#A0A0A0"
  android:angle="270" android:id="@+id/buttonGradient"/>
 <corners  android:topLeftRadius="7dp"
  android:topRightRadius="7dp" />
</shape>

At first, I decided the xml should go, and I would just create my own class to handle this. However, I realized there was no good class to extend from. GradientDrawable doesn't have any apparent methods do round the corners. RoundRectShape doesn't have any method to give me a gradient. However, I also don't know of any accessors to gradients/corners within shapedrawable. I think what it comes down to is the fact that I don't understand exactly how this shape is being defined (I pulled it off an example used elsewhere). Every xml view that I define has all of its properties enclosed within the < /> tags. This is different. What are < gradient > and < corners >? I can't find them anywhere in the API/developer tools. And how can I dynamically alter them in my code?
Answer: Seth, you could try using the overloaded constructor of GradientDrawable:
public GradientDrawable (GradientDrawable.Orientation orientation, int[] colors)

This allows you to set the orientation of the gradient, and pass an array of colors of which the gradient will be supplied.
There is a method to set rounded corners:
public void setCornerRadius (float radius)

which you can perform on a GradientDrawable.
I offer this answer, though I have not yet gotten it to work myself :( Perhaps you'll have better luck.
Answer: You could use a little Xpath..
By "dynamically" I don't know in what platform but in C# the below lines might guide you to your solution.
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load("path to xml file");
XmlNodeList gradientNodeList = xmlDoc.SelectNodes("//gradient");
foreach(XmlNode gradient in gradientNodeList){
    string startColor = gradient.Attributes["android:startColor"].Value; //GET
    gradient.Attributes["android:startColor"].Value = "#FFF"; //SET Custom Value
}
//OR Simply
XmlNode xn = xmlDoc.SelectSingleNode("/shape/gradient"); //and same as above

Or, You could use XSLT to transform your input xml to the desired format.
Comment: this android programming (java)
Comment: @Seth: Well, I'm sure something similar can be applied. I've already mentioned this was just as a hint of what could be done and NOT the end solution.
Comment: You won't be able to use Xpath; on Android, the xml resource files are compiled into bytecode, so modifying them after (even if there _is_ an xml file packaged) would have no effect unfortunately.


Javascript Performance: Assign object fields at creation or later?

Question: Does anyone know whether there are any performance trade-offs/advantages to assigning an object's fields at creation rather than later e.g.
var exObj = new exampleObject(name, date);
OR
var exObj = new exampleObject();
exObj.name = "blah";
exObj.date = "blah";
(assuming you've created your class accordingly)
Also, as a side thought, given that JS arrays are stored as objects, am I correct in assuming that there are no performance differences between using one over the other ? (For some reason using an array with a numeric index "feels" faster.)
Cheers
N
Answer: Test it yourself - http://jsperf.com/assign-object-fields-at-creation-or-later
Comment: Many thanks for this - I actually had planned to test it myself if there were no responses but I hadn't used/been aware of jsperf.com before so this simplifies things considerably.  For those who are interested, the latter method is fractionally quicker (at least on FF 3.6.13).


rsync how to include files that are excluded

Question: I'm trying to set up an rsync that excludes all .* files except for .htaccess but unfortunately, this doesn't work:
rsync -avP --exclude=".*" --include="./.htaccess" ./. user@server:/dir

Is it possible to somehow exclude general exclude rules?
Answer: Just reverse the order of your arguments:
rsync -avP --include="./.htaccess" --exclude=".*" ./. user@server:/dir

The first matching pattern wins. For more information, see the FILTER RULES section of the rsync(1) manpage.
Comment: http://linux.die.net/man/1/rsync for reference.
Comment: Unfortunately that didn't work, but dropping the "./" in front of "./.htaccess" did.
Answer: You could do the following
find . -type f -name ".*" |grep -v .htaccess > dotfiles

then use
rsync --avP --exclude-from=dotfiles ./. user@server:/dir


New symbol for an exact sequence

Question: A sequence $A\to B \to C$ is exact if $\operatorname{im} f = \ker g$, where $ f:A\to B$ and $g:B\to C$.
Why is there not a symbol to denote such a sequence?
Which one would you suggest?
Comment: Because nobody thought it necessary.
Comment: I just write $(ex)$ at the beginning/end of the exact row/column..
Comment: I prefer using the words "is exact" after the diagram.  Or "the exact sequence" before the diagram.
Comment: What is f? What is g?
Comment: also please consider using MathJax
Comment: I've said it before, but language is wonderful. You don't have to symbolize everything under the sun.
Comment: See edit. Thanks
Answer: @egreg's comment is totally right — because there's no need in such symbol.
Also, there are at least two reasons to not introduce it. First one is that heavily symbolized mathematical writing is usually unreadable. Second is high probability of  ambiguity in case when diagram is somewhat complicated.
So I would suggest to just write «this sequence is exact at $B$», or that «pair of morphisms $f, g$ is exact» (which is better, in my opinion).
Comment: "...heavily symbolized mathematical writing is usually unreadable."  I would upvote this a dozen times if I could.
Comment: Not to rant, but I HATE seeing arguments written out in logical symbols.  "Oh, the proof is clear.  Just note that $\neg((\nexists x \in P \forall y \in Z \ni x \notin W(\alpha) \vee y) \Rightarrow (J \Leftrightarrow K \wedge Q)$."
Answer: Here are three ideas. I prefer the last one.
Comment: These seem to indicate more about the individual maps themselves and not the sequence as a whole.  At least one is ambiguous (what if we have zigzags?) and the others are already in use for different things.

New symbol for an exact sequence


Django allauth Email confirmation sends only html code

Question: I've setup my django-allauth plugin on Django==1.6.1, everything works fine, but when I try to change the confirmation message to an html one, it sends the HTML but just the code, it doesn't show any style or color, or image, this is my template code:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Confirma tu correo men</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>

Bienvenido a Contratalos.com

Verifica tu correo para que empieces a formar
 parte de nuestra comunidad 3.0
<input type="submit" value="Verificar correo" width="300" height="35" style="color:#ffffff; font-size:23px; background-color:#5ac189; margin-top:45px; width: 288px; height: 45px;">     </input>

Si no deseas seguir recibiendo nuestros correos, puedes editar tus preferencias de notificaciones aqui

 Contratalos.com | Inversiones CTRL Venezuela, RIF : J-404528510 C.A., Caracas - Venezuela

This code is placed on:
myapp/shared/templates/account/email/index.html

And it's included from this .txt file:
  myapp/shared/templates/account/email/email_confirmation_signup_message.txt

Like this:
{% include "account/email/index.html" %}

I leaved the logic almost identical, just changed the include tag to index.html it actually sends it, but on yahoo email I just see the code of the template, but no colors, images, etc...
Anybody can shed some light on this?
Thanks in advance!
Answer: Nevermind
I just changed the .txt extension file to .html
So the file that includes this html is now called:
myapp/shared/templates/account/email/email_confirmation_signup_message.html

Works like a charm, thank you.


What is the Expected Value of a CDF

Question: I am confused about what is means to take the expected value of a CDF.
Let $X$ be a random variable with cdf $F_x(x)$, and assume that $X$ is a continuous random variable. What is $E[F_x(X)]$ and $var(F_x(X))$.
I assume this is similar to just taking the expectation of a function of a random variable, so I get something like this to start out.
$E[F_x(X)] = \int F_x(x)f_x(x)dx$
where $f_x(x)$ is the pdf of $X$, but I am not sure what this even means or where to go next. I understand expected value of a random variable, but what does it mean to take the expected value of a CDF. I am sorry if this has been answered, but I am not able to find help on this anywhere.
Answer: We make the substitution $F_x(u)=t$. Then $f_x(u)du=dt$. Note $t$ ranges from $0$ to $1$
$$E[F_x(X)] = \int_{-\infty}^{\infty} F_x(u)f_x(u)du= \int_0^1 t dt =\frac12$$
Similarly
$$E[F_x(X)^2] = \int_{-\infty}^{\infty} F_x(u)^2f_x(u)du= \int_0^1 t^2 dt =\frac13$$
Hence $Var[F_x(X)]=\frac1{12}$.

What is the Expected Value of a CDF


LetterCase Count Java

Question: I have to read in a file to my project and then read the file line by line to find the percent of upper case and lower case letters. My output should be 4 lines stating the percent of upper and lower for that specific line in the file. This is what I have to far but it doesn't quite work:
    Scanner inFile = new Scanner(new File("file.txt"));

    int upper = 0;
    int lower = 0;
    int total;
    double percentU = 0.0;
    double percentL = 0.0;

    while (inFile.hasNext()) {
        String line = inFile.nextLine();

        for (int x = 0; x < line.length(); x++)
        {
            if (Character.isUpperCase(line.charAt(x)))
            {
                upper++;
            }
            if (Character.isLowerCase(line.charAt(x)))
            {
                lower++;
            }

        total = upper + lower;
        percentU = upper/total;
        percentL = lower/total;

        System.out.println("lowercase: " + String.format("%.2f", percentL) + "\t" + "uppercase: " + String.format("%.2f", percentU));
        }

    }

Comment: What do you mean by it doesn't work? What exactly is the problem?
Comment: Possible duplicate of [Java: dividing 2 ints makes an int?](http://stackoverflow.com/questions/787700/java-dividing-2-ints-makes-an-int)
Comment: @Caitlin Compagnone try solution below
Answer: When you divide an int by another int the result will be also an int. So for example if you divide 30 by 50 the result will be 0 instead of 0.6.
More information:
How to make the division of 2 ints produce a float instead of another int?
Integer division: How do you produce a double?
Division of integers in Java
Comment: Of course! Thank you! Unfortunately for some reason the percentages are coming out incorrectly still. The file input is:
Comment: thisTHIS  AAbbCCDDEE  N  UkJ all on separate lines
Comment: Please add a sample input and an expected result to your question
Answer: I Just change these lines removed if (Character.isLowerCase(line.charAt(x))):
         if (Character.isUpperCase(line.charAt(x))) {
                    upper++;
                }
           if (Character.isLowerCase(line.charAt(x))) {
                    lower++;
                }

To:
            if (Character.isUpperCase(line.charAt(x))) {
                    upper++;
                } else {
                    lower++;
                }

And moved these lines out of while loop:
 total = upper + lower;
    percentU = (float)upper/total;
    percentL = (float)lower/total;
    System.out.println("total: " + total);
    System.out.println("lowercase: " + String.format("%.2f", percentL) + "\t" + "uppercase: " + String.format("%.2f", percentU));

Try this solution it's ok:
 public static void main(String[] args) {
    Scanner inFile = null;
    int upper = 0;
    int lower = 0;
    int total = 0;
    double percentU = 0.0;
    double percentL = 0.0;
    try {
        inFile = new Scanner(new File("C:\\temp\\file.txt"));

        while (inFile.hasNext()) {
            String line = inFile.nextLine();

            for (int x = 0; x < line.length(); x++) {
                if (Character.isUpperCase(line.charAt(x))) {
                    upper++;
                } else {
                    lower++;
                }

            }
        }
        total = upper + lower;
        percentU = (float)upper/total;
        percentL = (float)lower/total;
        System.out.println("total: " + total);
        System.out.println("lowercase: " + String.format("%.2f", percentL) + "\t" + "uppercase: " + String.format("%.2f", percentU));

    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

LetterCase Count Java


XSL percentile function

Question: Is there way how to get 90, 95 or 99 percentile from input values with XSLT 2.0 or 3.0? Below is a code from this question How to print percentile using xsl, but is is not working correctly. This gives me a avarage from two values and not one value which is that wanted percentil.

From this "online calculator" is result 5. https://www.emathhelp.net/calculators/probability-statistics/percentile-calculator/?i=2%2C4%2C3%2C1%2C5&p=90&steps=on

XML
<root>
    <value t="5"></value>
    <value t="1"></value>
    <value t="2"></value>
    <value t="4"></value>
    <value t="3"></value>
</root>

XSL
    <xsl:template match="/">
      <xsl:variable name="thisPercentile">
         <xsl:call-template name="percentiles">
            <xsl:with-param name="responsetimes" select="/root/*/@t" />
            <xsl:with-param name="percentile" select="0.9" />
         </xsl:call-template>
      </xsl:variable>

      <xsl:value-of select="$thisPercentile" />
    </xsl:template>

<xsl:template name="percentiles">
   <xsl:param name="responsetimes" select="." />
   <xsl:param name="percentile" select="." />
   <xsl:variable name="sortedresponsetimes">
        <xsl:for-each select="$responsetimes">
            <xsl:sort data-type="number" />
            <xsl:element name="time">
                <xsl:value-of select="." />
            </xsl:element>
        </xsl:for-each>
   </xsl:variable>
   <xsl:variable name="n" select="count($responsetimes)-1" />
   <xsl:variable name="k" select="floor($percentile*$n)+1" />
   <xsl:variable name="f" select="($percentile*$n+1)-$k" />
   <xsl:variable name="a0" select="$sortedresponsetimes[1]/time[$k]" />
   <xsl:variable name="a1" select="$sortedresponsetimes[1]/time[$k+1]" />
    <xsl:value-of select="$a0 + ( $f * ( $a1 - $a0))" />
</xsl:template>

Ouput after transform

4.6
Answer: In XPath 3.1 making use of the sort function you could implement that algorithm given on the linked page as
  <xsl:function name="mf:percentile" as="xs:decimal">
      <xsl:param name="input-sequence" as="xs:decimal*"/>
      <xsl:param name="p" as="xs:integer"/>
      <xsl:sequence select="let $sorted-input := sort($input-sequence),
                            $i := round($p div 100 * count($sorted-input))
                            return $sorted-input[$i]"/>
  </xsl:function>

in a complete sample as
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    xmlns:xs="http://www.w3.org/2001/XMLSchema"
    xmlns:mf="http://example.com/mf"
    exclude-result-prefixes="xs mf"
    version="3.0">

  <xsl:function name="mf:percentile" as="xs:decimal">
      <xsl:param name="input-sequence" as="xs:decimal*"/>
      <xsl:param name="p" as="xs:integer"/>
      <xsl:sequence select="let $sorted-input := sort($input-sequence),
                            $i := round($p div 100 * count($sorted-input))
                            return $sorted-input[$i]"/>
  </xsl:function>

  <xsl:output method="text"/>

  <xsl:template match="root">
      <xsl:value-of select="mf:percentile(value/@t, 90)"/>
  </xsl:template>

</xsl:stylesheet>

https://xsltfiddle.liberty-development.net/bFukv8u
In XSLT/XPath 2.0 you can use perform-sort and then local XSLT variables in the function:
  <xsl:function name="mf:percentile" as="xs:decimal">
      <xsl:param name="input-sequence" as="xs:decimal*"/>
      <xsl:param name="p" as="xs:integer"/>
      <xsl:variable name="sorted-input" as="xs:decimal*">
          <xsl:perform-sort select="$input-sequence">
              <xsl:sort select="."/>
          </xsl:perform-sort>
      </xsl:variable>
      <xsl:variable name="i" select="round($p div 100 * count($sorted-input))"/>
      <xsl:sequence select="$sorted-input[$i]"/>
  </xsl:function>

http://xsltransform.hikmatu.com/3Nqn5Yc
Comment: Well, if you want to output that value computed from the other document then `` should do.

XSL percentile function


Why setup domain.com as my ADDS domain, the ".com" is disappear?

Question: Recently I setup a test environment for my self-test. On a win2008 I add ADDS role. I type in "domain.com" as the domain name. Everything is fine and installation completed without problem. However I don't get why everywhere the ".com" is missed. On the logon screen it shows "domain/user". When type in "whoami" in cmd it shows "domain/user".
I think it is by purpose but what is the purpose?
Also what if I use domain.net or domain.co.jp as AD domain name?
Thanks.
Answer: The name you're seeing is the NetBIOS (think legacy) name). When you configured the domain, you would have been asked for the domain name (domain.com) and later, the NetBIOS domain name (which you probably left as domain).
The NetBIOS name dates from before Active Directory, and lives to support legacy apps. You can log in using any reasonable form of your logon name:

firstname.lastname@example.com
domain\user
domain.com\User

The same would apply if you named the original DNS domain "example.co.jp", and the corresponding NetBIOS name "example" - you would then be "example\user". You don't have to have matching names either - domain.com.au could have the NetBIOS name "AUS".
Comment: What if I have both domain.com and domain.net in the same forest? Will it lead to conflict?
Comment: That's OK - but they won't be able to have the same NetBIOS (short) name. When you go through the AD Domain Controller Promotion wizard, you'll be told that the domain "DOMAIN" is already in use, and you'll have to choose an alternative NetBIOS domain name for the second domain tree. As I mentioned, the names don't have to match - so you might end up with something like domain.com being "DOMAIN" and domain.net being "NETDOMAIN" or "DOMAIN2". Anything that satisfies the NetBIOS name rules will be fine (15 or fewer letters, numbers, and from memory, one or two of the punctuation characters).
Answer: What you're seeing is the NETBIOS domain name.  What you typed in was the DNS domain name.  The NETBIOS domain name primarily still exists to provide support for legacy systems, but either are valid.

Active Directory domain names are usually the full Domain Name System (DNS) name of the domain. However, for backward compatibility, each domain also has a pre-Windows 2000 name for use by computers running pre-Windows 2000 operating systems. The pre-Windows 2000 domain name can be used to log on to a Windows Server 2003 domain from computers running pre-Windows 2000 operating systems using the DomainName\UserName format. This same format can also be used to log on to a Windows Server 2003 domain from computers running Windows 2000, Windows XP, or servers running Windows Server 2003. Users can also log on to computers running Windows 2000, Windows XP, or servers running Windows Server 2003 using the user principal name (UPN) associated with their user account.

Microsoft has a support KB article about naming conventions, and valid/reserved names in Active Directory, here.
If you want to log in using the DNS domain name, you do so with the below format:
username@DNSdomainname
Where as logging in with the NETBIOS name is done in the following format:
NETBIOSdomainname\username
Regarding using "domain.net" or "domain.co.jp," either are valid DNS domain names for active directory, though, since you didn't name your domain with them, they wouldn't work for you.  If you wanted to try to use those anyway, you could potentially do so, by setting them up as alternate UPN suffixes for your users.


login to obiee and execute SQL using python

Question: I've tried various ways of extracting reports from Oracle Business Intelligence (not hosted locally, version 11g), and the best I've come up with so far is the pyobiee library here, which is pretty good: https://github.com/kazei92/pyobiee.  I've managed to login and extract reports that I've already written, but in an ideal world I would be able to interrogate the SQL directly.  I've tried this using the executeSQL function in pyobiee, but I can only manage to extract a column or two and then it can't do any more.  I think I'm limited by my understanding of the SQL syntax which is not a familiar one (it's more logical, no GROUP BY requirement), and I can't find a decent summary of how to use it.  Where I have found summaries, I've followed them and it doesn't work (https://docs.oracle.com/middleware/12212/biee/BIESQ/toc.htm#BIESQ102).  Please can you advise where I can find a better summary of the logical SQL syntax?  The other possibility is that there is something wrong with the pyobiee library (hasn't been maintained since August).  I would be open to using pyodbc or cx_Oracle instead, but I can't work out how to login using these routes.  Please can you advise?
The reason I'm taking this route is because my organisation has mapping tables that are not held in obiee and there is no prospect of getting them in there.  So I'm working on extracting using python so that I can add the mapping tables in SQL server.
Answer: I advise you to rethink what you are doing. First of all the python is a wrapper around the OBI web services which in itself isn't wrong, but an additional layer of abstraction which hides most of the web services and functionalities. There are way more than three...
Second - the real question is "What exactly are you trying top achieve?". If you simply want data from the OBI server, then you can just as well get that over ODBC. No need for 50 additional technologies in the middle.
As far as LSQL is concerned: Yes, there is a reference: https://docs.oracle.com/middleware/12212/biee/BIESQ/BIESQ.pdf
BUT you will definitely need to know what you want to access since what's governing things is the RPD. A metadata layer. Not a database.
Comment: How would I go about using ODBC to get it?  Bearing in mind that I've stated this is not a locally hosted server
Comment: You need an ODBC connection: https://docs.oracle.com/middleware/12213/biee/BIEIT/odbc_data_source.htm#BIEIT535


How do I prevent a form from being cached for anonymous users?

Question: I have a form that is pre-populated with information specific to an anonymous user's session information. However, the form appears to get cached for all anonymous users by default.
'Internal Dynamic Page Cache' is enabled, 'Internal Page Cache' is not.
How do I disable caching of this form? It should be rebuilt fresh every time it is displayed.
Comment: is it a custom form ??
Answer: To update:
In order to prevent a form from caching at all, you can include the following #cache key in your form:
$form['#cache'] = ['max-age' => 0];

Comment: Doesn't work for anonymous users. See more : https://www.drupal.org/docs/drupal-apis/cache-api/cache-max-age#s-limitations-of-max-age
Comment: Not workin for me on 8.6
Comment: For anonymous users
Comment: You may need to use the Cache Control Override module for this to work properly: https://www.drupal.org/project/cache_control_override
Comment: Did not work for me, the [other answer](https://drupal.stackexchange.com/a/271181/27710) did.
Comment: This doesn't work anymore with Drupal 9. See at https://www.drupal.org/docs/drupal-apis/cache-api/cache-max-age#s-limitations-of-max-age
Answer: In your mymodule.module file, located at the root of your module directory:
/**
 * Workaround to prevent form caching for anonymous users.
 */
function mymodule_form_myregistration_form_alter() {
    \Drupal::service('page_cache_kill_switch')->trigger();
}

/**
 * Workaround to prevent form caching for anonymous users.
 */
function mymodule_form_mylogin_form_alter() {
    \Drupal::service('page_cache_kill_switch')->trigger();
}

This is using Drupal 8's Form Alter
Comment: I have a similar problem (using search api) for anonymous users, and this solved it simply.  Thank you!
Answer: The correct way to do this is with the following line.
$form['#cache']['contexts'][] = 'session';

See also Cache contexts.
At some stage, max-age has stopped working.
Comment: Yay! This works! I originally commented that it wasn't working, but turned out I did something silly; it does work, so thank you very much.
Comment: can someone reference where the documentation for this answer is?
Comment: On https://www.drupal.org/docs/drupal-apis/cache-api/cache-max-age it states: "Unfortunately, max-age does not work for anonymous users", but I can't remember where I found the session cache context
Answer: Some forms generated by Drupal 8(.7.8)'s FAPI crash when cached server side using Drupal 8's cache, and loaded by an anonymous user.
If you clear the server side cache($ drush cr), the anonymous user can then load the form successfully; on refresh it crashes once cached server side and reloaded by the user.
In this case, BrianV's answer ($form['#cache'] = ['max-age' => 0];) solves the issue on Drupal 8.7.8.
I think we're seeing different types of caching issues here, with different solutions that resolve them, and it might be useful to provide a concise accurate description of your situation which caused a form caching issue, an error log(if it produces errors) as well as the solution you used to fix it.
There might be different problems for a straight FAPI form vs. a webform, vs. say a CiviCRM extension form and providing details will help people a lot more than just saying "well this code worked for my situation" without describing the situation in detail.
Providing the exact Drupal minor version you're on is also important.
The stack trace that my situation was producing was (formatted for readability):
TypeError: Argument 1 passed to Drupal\\Core\\Routing\\RequestContext::fromRequest() must be an instance of Symfony\\Component\\HttpFoundation\\Request, null given, called in DRUPAL_ROOT/core/lib/Drupal/Core/Routing/RequestContext.php on line 31 in DRUPAL_ROOT/core/lib/Drupal/Core/Routing/RequestContext.php on line 37
#0 DRUPAL_ROOT/core/lib/Drupal/Core/Routing/RequestContext.php(31): Drupal\\Core\\Routing\\RequestContext->fromRequest(NULL)
#1 [internal function]: Drupal\\Core\\Routing\\RequestContext->fromRequestStack(Object(Symfony\\Component\\HttpFoundation\\RequestStack))
#2 DRUPAL_ROOT/core/lib/Drupal/Component/DependencyInjection/Container.php(329): call_user_func_array(Array, Array)
#3 DRUPAL_ROOT/core/lib/Drupal/Component/DependencyInjection/Container.php(173): Drupal\\Component\\DependencyInjection\\Container->createService(Array, 'router.request_...')
#4 DRUPAL_ROOT/core/lib/Drupal/Component/DependencyInjection/Container.php(487): Drupal\\Component\\DependencyInjection\\Container->get('router.request_...', 3)
#5 DRUPAL_ROOT/core/lib/Drupal/Component/DependencyInjection/Container.php(326): Drupal\\Component\\DependencyInjection\\Container->resolveServicesAndParameters(Array)
#6 DRUPAL_ROOT/core/lib/Drupal/Component/DependencyInjection/Container.php(502): Drupal\\Component\\DependencyInjection\\Container->createService(Array, 'private__zpo0hT...')
#7 DRUPAL_ROOT/core/lib/Drupal/Component/DependencyInjection/Container.php(237): Drupal\\Component\\DependencyInjection\\Container->resolveServicesAndParameters(Array)
#8 DRUPAL_ROOT/core/lib/Drupal/Component/DependencyInjection/Container.php(173): Drupal\\Component\\DependencyInjection\\Container->createService(Array, 'url_generator')
#9 DRUPAL_ROOT/core/lib/Drupal/Component/DependencyInjection/Container.php(487): Drupal\\Component\\DependencyInjection\\Container->get('url_generator', 1)
#10 DRUPAL_ROOT/core/lib/Drupal/Component/DependencyInjection/Container.php(237): Drupal\\Component\\DependencyInjection\\Container->resolveServicesAndParameters(Array)
#11 DRUPAL_ROOT/core/lib/Drupal/Component/DependencyInjection/Container.php(173): Drupal\\Component\\DependencyInjection\\Container->createService(Array, 'link_generator')
#12 DRUPAL_ROOT/core/lib/Drupal/Component/DependencyInjection/Container.php(487): Drupal\\Component\\DependencyInjection\\Container->get('link_generator', 1)
#13 DRUPAL_ROOT/core/lib/Drupal/Component/DependencyInjection/Container.php(237): Drupal\\Component\\DependencyInjection\\Container->resolveServicesAndParameters(Array)
#14 DRUPAL_ROOT/core/lib/Drupal/Component/DependencyInjection/Container.php(173): Drupal\\Component\\DependencyInjection\\Container->createService(Array, 'plugin.manager....')
#15 DRUPAL_ROOT/core/lib/Drupal/Component/DependencyInjection/Container.php(487): Drupal\\Component\\DependencyInjection\\Container->get('plugin.manager....', 1)
#16 DRUPAL_ROOT/core/lib/Drupal/Component/DependencyInjection/Container.php(237): Drupal\\Component\\DependencyInjection\\Container->resolveServicesAndParameters(Array)
#17 DRUPAL_ROOT/core/lib/Drupal/Component/DependencyInjection/Container.php(173): Drupal\\Component\\DependencyInjection\\Container->createService(Array, 'geocoder')
#18 DRUPAL_ROOT/core/lib/Drupal/Component/DependencyInjection/Container.php(487): Drupal\\Component\\DependencyInjection\\Container->get('geocoder', 1)
#19 DRUPAL_ROOT/core/lib/Drupal/Component/DependencyInjection/Container.php(237): Drupal\\Component\\DependencyInjection\\Container->resolveServicesAndParameters(Array)
#20 DRUPAL_ROOT/core/lib/Drupal/Component/DependencyInjection/Container.php(173): Drupal\\Component\\DependencyInjection\\Container->createService(Array, 'nfb.address_ada...')
#21 DRUPAL_ROOT/core/lib/Drupal/Component/DependencyInjection/Container.php(487): Drupal\\Component\\DependencyInjection\\Container->get('nfb.address_ada...', 1)
#22 DRUPAL_ROOT/core/lib/Drupal/Component/DependencyInjection/Container.php(237): Drupal\\Component\\DependencyInjection\\Container->resolveServicesAndParameters(Array)
#23 DRUPAL_ROOT/core/lib/Drupal/Component/DependencyInjection/Container.php(173): Drupal\\Component\\DependencyInjection\\Container->createService(Array, 'nfb_contact_inf...')
#24 DRUPAL_ROOT/core/lib/Drupal/Core/DependencyInjection/DependencySerializationTrait.php(80): Drupal\\Component\\DependencyInjection\\Container->get('nfb_contact_inf...')
#25 [internal function]: Drupal\\Core\\Form\\FormBase->__wakeup()
#26 DRUPAL_ROOT/core/lib/Drupal/Core/Cache/DatabaseBackend.php(167): unserialize('O:31:"Drupal\\\\Co...')
#27 DRUPAL_ROOT/core/lib/Drupal/Core/Cache/DatabaseBackend.php(122): Drupal\\Core\\Cache\\DatabaseBackend->prepareItem(Object(stdClass), false)
#28 DRUPAL_ROOT/core/lib/Drupal/Core/Cache/DatabaseBackend.php(92): Drupal\\Core\\Cache\\DatabaseBackend->getMultiple(Array, false)
#29 DRUPAL_ROOT/core/modules/page_cache/src/StackMiddleware/PageCache.php(306): Drupal\\Core\\Cache\\DatabaseBackend->get('https://dev.nfb...', false)
#30 DRUPAL_ROOT/core/modules/page_cache/src/StackMiddleware/PageCache.php(124): Drupal\\page_cache\\StackMiddleware\\PageCache->get(Object(Symfony\\Component\\HttpFoundation\\Request))
#31 DRUPAL_ROOT/core/modules/page_cache/src/StackMiddleware/PageCache.php(82): Drupal\\page_cache\\StackMiddleware\\PageCache->lookup(Object(Symfony\\Component\\HttpFoundation\\Request), 1, true)
#32 DRUPAL_ROOT/core/modules/ban/src/BanMiddleware.php(50): Drupal\\page_cache\\StackMiddleware\\PageCache->handle(Object(Symfony\\Component\\HttpFoundation\\Request), 1, true)
#33 DRUPAL_ROOT/core/lib/Drupal/Core/StackMiddleware/ReverseProxyMiddleware.php(47): Drupal\\ban\\BanMiddleware->handle(Object(Symfony\\Component\\HttpFoundation\\Request), 1, true)
#34 DRUPAL_ROOT/core/lib/Drupal/Core/StackMiddleware/NegotiationMiddleware.php(52): Drupal\\Core\\StackMiddleware\\ReverseProxyMiddleware->handle(Object(Symfony\\Component\\HttpFoundation\\Request), 1, true)
#35 DRUPAL_ROOT../vendor/stack/builder/src/Stack/StackedHttpKernel.php(23): Drupal\\Core\\StackMiddleware\\NegotiationMiddleware->handle(Object(Symfony\\Component\\HttpFoundation\\Request), 1, true)
#36 DRUPAL_ROOT/core/lib/Drupal/Core/DrupalKernel.php(693): Stack\\StackedHttpKernel->handle(Object(Symfony\\Component\\HttpFoundation\\Request), 1, true)
#37 DRUPAL_ROOT/index.php(19): Drupal\\Core\\DrupalKernel->handle(Object(Symfony\\Component\\HttpFoundation\\Request))
#38 {main}

Answer: In order to prevent a form from caching at all, you can include the following #cache key in your form along with max-age & context attributes:
$form['#cache'] = [
 'max-age' => 0,
  'contexts' => ['session'],
];

Informative Tips: Follow these documentation to know more about context & max-age attributes.


Escaping double quotes in JavaScript

Question: I have this code:
 facetsString += "<input type='checkbox' value=facetList[count].term>  " + facetList[count].term +  " (" + facetList[count].count + ")" + "	";

I'm trying to give each checkbox a unique value facetList[count].term, but I don't know how to escape the double quotes...
Answer: Just put a backslash in front of the double-quotes:
facetsString += "<input type='checkbox' value=\"facetList[count] ... \" />	"

Alternatively, you can wrap the outer in single quotes, and use double quotes for property values:
facetsString += '<input type="checkbox" value="facetList[count] ... " />	'

Answer: You can escape double quotes like this:
"string with \"double qoutes\""

The solution is:
facetsString += "<input type='checkbox' value=\"" + facetList[count].term + "\">  " + facetList[count].term + " (" + facetList[count].count + ")" + "	";

The example provided would write facetList[count].term in the value attribute, and not the actual value of the variable.
Comment: facetsString+="  "+facetList[count].term+  " (" + facetList[count].count + ")" + "";
Comment: value should hav the array item facetList[count].term.. this one is inside a loop...bt im getting the code value="facetList[count].term"

Escaping double quotes in JavaScript


Header and footer not getting loaded when using selector in angular6 project

Question: I am doing project in angular6. I have created header and footer component.
And when I am using selector <app-header> and <app-footer> in app.component.html it will work fine. But If I will use this selectors in other component it won't show header and footer. I have included this components in app.module.ts file.Can anyone please give any suggestion to fix this problem.
login.component.html
<app-header>
<app-footer></app-footer>

I need to display header and footer in login page. But it is not working.
app.module.ts
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';

import { AppRoutingModule } from './app-routing.module';
import { CustomMaterialModule } from './material.module';
import {FormsModule, ReactiveFormsModule} from '@angular/forms';

import { AppComponent } from './app.component';
import { HomeComponent } from './home/home.component';
import { ContactUsComponent } from './contact-us/contact-us.component';
import { AboutUsComponent } from './about-us/about-us.component';
import { LoginComponent } from './login/login.component';
import { UserComponent } from './user/user.component';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { DashboardComponent } from './dashboard/dashboard.component';
import { NotificationComponent } from './notification/notification.component';
import { SendMessageComponent } from './send-message/send-message.component';

import { DashboardRoutingModule } from './dashboard/dashboard-routing.module';
import { NotesComponent } from './notes/notes.component';
import { PopupComponent } from './popup/popup.component';

import { MyDialogComponent } from './my-dialog/my-dialog.component';

import { MatDialogModule,MatButtonModule, MatToolbarModule, MatGridListModule,MatCardModule,MatSidenavModule, MatIconModule, MatListModule } from '@angular/material';
import {MatSelectModule} from '@angular/material/select';
import { LogoutComponent } from './logout/logout.component';
import { MainNavComponent } from './main-nav/main-nav.component';
import { LayoutModule } from '@angular/cdk/layout';
import { FooterComponent } from './footer/footer.component';
import { HeaderComponent } from './header/header.component';

@NgModule({
  declarations: [
    AppComponent,
    HomeComponent,
    ContactUsComponent,
    AboutUsComponent,
    LoginComponent,
    UserComponent,
    DashboardComponent,
    NotificationComponent,
    SendMessageComponent,
    NotesComponent,
    PopupComponent,
    MyDialogComponent,
    LogoutComponent,
    MainNavComponent,
    FooterComponent,
    HeaderComponent
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    CustomMaterialModule,
    FormsModule,
    BrowserAnimationsModule,
    DashboardRoutingModule,
    MatDialogModule,
    MatButtonModule,
    ReactiveFormsModule,
    MatSelectModule,
    LayoutModule,
    MatToolbarModule,
    MatSidenavModule,
    MatIconModule,
    MatListModule,
    MatCardModule,
    MatGridListModule

  ],

  entryComponents: [
  MyDialogComponent
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

Comment: any errors in the console?
Comment: Seems there's a typo at ``. Should be ``
Answer: Make use of Angular Routing for reusing common components like header and footer which are common layout in web application.
Please refer:- https://blog.angularindepth.com/angular-routing-reusing-common-layout-for-pages-from-different-modules-440a23f86b57


External Coupling vs Common Coupling

Question: I've read a lot of definitions, but still don't understand - what is the real difference between External Coupling and Common Coupling? Example, definitions from here:

External Coupling arises when two modules share an externally imposed data format, communication protocols, or device interface.

Common Coupling: Two modules are common coupled if they share information through some global data items.

As I understand, if Class A and Class B both use some outer .txt file this case corresponds External Coupling and Common Coupling. Could someone gives a clear example ?
Answer: The definition of external coupling you are quoting is quite common nowadays, but I don't know where it comes from. As far as I know, the different types of coupling were originally defined by Glen Myers in this book. These concepts were conceived for languages such as Cobol and Fortran, sometimes it is hard to grasp them because they refer to features that are very different or don't exist in modern-day languages.
According to Myers' definition, there is not much difference between external and common coupling, it seems to be just a matter of referring to individual global variables vs. to a whole shared scope containing multiple data: "External coupling is similar to common coupling except that, in external coupling, the references between modules are to individual data items, not to data structures".
Current definitions of external coupling refer not to a global scope but to things that are external to the application itself: databases, hardware, external libraries, etc. As I see it, your example of the .txt file would be external coupling in this sense. Suppose that many classes of your application read .txt files. All those classes are coupled to that specific file format. If for some reason you need to change the type of file, you will need to fix things in different parts of your code.
The way of mitigating this form of coupling is to reduce as much as possible the sites of contact of your app with the external world. Perhaps you can have only one class C read .txt files, and other classes A and B consume the output of that reading. If you need to change the source format, you can change the implementation of C only, and A and B can keep consuming its output as before (as long as C maintains its interface). You can find out more about this by researching the Adapter Pattern and Hexagonal Architecture.

External Coupling vs Common Coupling


How to update a program and a database structure from multiple servers

Question: I am developing an application in .NET (C# and VB.NET) (Framework 4.0) that will use MySQL database (in local or in remote).
I am doing the installation with InnoSetup, of such form that:

I download the archive installer created by InnoSetup (archive .EXE).
I execute the archive and I check if it exists the Framework 4.0. In case that it does not exist, the script downloads the archive for its installation.
After installing the Framework 4.0 I download from an own server the installer of MySQL.
I install my program.

With the first execution of the program I install the database and I enter the necessary data through a SQL script.
I have problems with the updates, because I need:

Have multiple routes to download the updates (multiple URL with Linux/Apache servers), for balance and availability.
Update the archives of the program (.exe, .dll, images,...) and new fields of the database (ALTER TABLE sentences and some INSERT).

I am thinking in develop a own updater, but I don't want write it if I can use some available solution. Could someone recommend me some available solution? I have been consulting the following products, but I have not seen that any of them support or multiple URL or update of the database:

Clickonce.
Netsparkle.
WinSparkle.
WindowsClient Application Updater Component.
WyBuild.

For the update of the database I have found only one solution: Autodbupdater.
Thank you
Answer: NAppUpdate an open-source solution I wrote to address specific needs we had for WinForms and WPF apps. The general idea is to have the greatest flexibility, at the lowest overhead possible. I think it provides exactly the flexibility you need:
It lets you determine what tasks to execute and on what conditions - you make the rules. A support for any updates source (web, BitTorrent, etc) exist, as well as any feed format - whatever is not implemented you can just write for yourself.
Generally all you'll need to do is add NAppUpdate to your project (one small DLL), implement your own IUpdateSource (to be able to download from multiple sources), use the existing FileUpdateTask and roll your own DbUpdateTask to do DB updates.
Cold updates (requiring an application restart) are supported, and done automatically for file operations unless "hot-swap" is specified for the task.
Some more details at http://www.code972.com/blog/2010/08/nappupdate-application-auto-update-framework-for-dotnet/ or via the mailing list at http://groups.google.com/group/nappupdate.
Code is at http://github.com/synhershko/NAppUpdate (Licensed under the Apache 2.0 license)


SQL Error when trying to remove content type field

Question: I was trying to create a new Content Type for my site and I chose a field name ("description") that already used for other content types.
The problem occurred when saving changes as the machine name for the field already exists for the fields in other Content Types but with a different field type. In other Content types I used the default "Long Text" field type but in this case I chose "Read More Field" as it suited better my use case.
I noticed the problem and went back to change the machine name only to discover I had created two fields and one of them had a machine name with the problem I mentioned before.
When trying to remove such field, I went to admin/structure/types/manage/my_custom_content_type/fields and using the UI options selected "Delete".
Then, the admin UI showed me a screen where it displays the changes I'm about to make and when I chose "Accept", my site takes me to a blank page with the message: "The website encountered an unexpected error. Try it again later."
When I check the logs, this is the error message I see:
[06-Nov-2021 03:07:49] WARNING: [pool www] child 2014 said into stderr: "NOTICE: PHP message: Uncaught PHP Exception Drupal\Core\Database\DatabaseExceptionWrapper: "SQLSTATE[42S22]: Column not found: 1054 Unknown column 'field_description_teaser_value' in 'where clause': SELECT 1 AS expression"
[06-Nov-2021 03:07:49] WARNING: [pool www] child 2014 said into stderr: "FROM"
[06-Nov-2021 03:07:49] WARNING: [pool www] child 2014 said into stderr: "{node_revision__field_description} t"
[06-Nov-2021 03:07:49] WARNING: [pool www] child 2014 said into stderr: "WHERE (field_description_teaser_value IS NOT NULL) OR (field_description_teaser_format IS NOT NULL) OR (field_description_hidden_value IS NOT NULL) OR (field_description_hidden_format IS NOT NULL)"
[06-Nov-2021 03:07:49] WARNING: [pool www] child 2014 said into stderr: "LIMIT 1 OFFSET 0; Array"
[06-Nov-2021 03:07:49] WARNING: [pool www] child 2014 said into stderr: "("
[06-Nov-2021 03:07:49] WARNING: [pool www] child 2014 said into stderr: ")"
[06-Nov-2021 03:07:49] WARNING: [pool www] child 2014 said into stderr: "" at /var/www/html/web/core/lib/Drupal/Core/Database/Connection.php line 701"
2021/11/06 03:07:49 [error] 2010#2010: *21776 FastCGI sent in stderr: "PHP message: Uncaught PHP Exception Drupal\Core\Database\DatabaseExceptionWrapper: "SQLSTATE[42S22]: Column not found: 1054 Unknown column 'field_description_teaser_value' in 'where clause': SELECT 1 AS expression
FROM
{node_revision__field_description} t
WHERE (field_description_teaser_value IS NOT NULL) OR (field_description_teaser_format IS NOT NULL) OR (field_description_hidden_value IS NOT NULL) OR (field_description_hidden_format IS NOT NULL)
LIMIT 1 OFFSET 0; Array
(
)
" at /var/www/html/web/core/lib/Drupal/Core/Database/Connection.php line 701" while reading response header from upstream, client: 172.18.0.6, server: , request: "GET /admin/structure/types/manage/my_custom_content_type/fields/node.my_custom_content_type.field_description/storage HTTP/1.1", upstream: "fastcgi://unix:/run/php-fpm.sock:", host: "custom-site.ddev.site", referrer: "https://custom-site.ddev.site/admin/structure/types/manage/my_custom_content_type/fields"

When launching phpmyadmin, none of the column names listed in the where clause exist in node_revision__field_description table as those columns are created for a different field type.
At this point, I couldn't create any content using this Content Type and I would like to remove it and start from scratch by creating a new one with better machine names and trying to avoid those errors.
My question is: is there a safe way to remove the content type by using SQL or drush?
I tried to remove it via the admin interface but it resulted with the same error as when I try to remove the field.
Comment: How did you initially try to remove it?  You should always use the admin UI/config management first.
Comment: @PatrickKenny, thanks for the comment. I updated my question adding some clarifications but the tl;dr would be: to try to remove it, I used the admin UI/config management.
Answer: I managed to solve my problem by manually adding the missing columns to the tables involved using phpmyadmin.
First:

Created a db backup (just in case).

Second, I created a copy of the tables involved and moved such copies to another db maintaining both data and structure:

node_revision__field_description
node__field_description

Once the backup was done, I proceeded creating the missing columns and copied their attributes from similar columns in other tables (created for other Content Types).
Then, I removed the Content Type via the admin UI without any problem.
Lastly, I restored the original copies of the tables to the db, replacing the modified versions of them.
I know this is probably not the best solution for everyone but it worked for me.


How can I create a marquee effect?

Question: I'm creating a marquee effect with CSS3 animation.

#caption {
    position: fixed;
    bottom: 0;
    left: 0;
    font-size: 20px;
    line-height: 30px;
    height:30px;
    width: 100%;
    white-space: nowrap;
    -moz-animation:  caption 50s linear 0s infinite;
    -webkit-animation:  caption 50s linear 0s infinite;
}
@-moz-keyframes caption {
    0% { margin-left:120%; } 100% { margin-left:-4200px; }
}
@-webkit-keyframes caption {
    0% { margin-left:120%; } 100% { margin-left:-4200px; }
}

    The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. the quick brown fox jumps over the lazy dog.

Now I can get the basic marquee effect, but the code is too specific for this demo.
Is there a way to avoid using specific values like margin-left:-4200px;, so that it can adapt text in any length?
Here is a similar demo: http://jsfiddle.net/jonathansampson/XxUXD/ that uses text-indent but still with specific values.
Answer: With a small change of the markup, here's my approach (I've just inserted a span inside the paragraph):

.marquee {
  width: 450px;
  margin: 0 auto;
  overflow: hidden;
  box-sizing: border-box;
}

.marquee span {
  display: inline-block;
  width: max-content;

  padding-left: 100%;
  /* show the marquee just outside the paragraph */
  will-change: transform;
  animation: marquee 15s linear infinite;
}

.marquee span:hover {
  animation-play-state: paused
}

@keyframes marquee {
  0% { transform: translate(0, 0); }
  100% { transform: translate(-100%, 0); }
}

/* Respect user preferences about animations */

@media (prefers-reduced-motion: reduce) {
  .marquee span {
    animation-iteration-count: 1;
    animation-duration: 0.01;
    /* instead of animation: none, so an animationend event is
     * still available, if previously attached.
     */
    width: auto;
    padding-left: 0;
  }
}

       When I had journeyed half of our life's way, I found myself
       within a shadowed forest, for I had lost the path that
       does not stray. – (Dante Alighieri, Divine Comedy.
       1265-1321)

No hardcoded values — dependent on paragraph width  — have been inserted.
The animation applies the CSS3 transform property (use prefixes where needed) so it performs well.
If you need to insert a delay just once at the beginning then also set an animation-delay. If you need instead to insert a small delay at every loop then try to play with an higher padding-left (e.g. 150%)
Comment: This did not work for me when I tried it on my site. I found out that there's an external resource [prefixfree.js](http://leaverou.github.io/prefixfree/prefixfree.js) that's needed. I should have noticed the (1) beside external resources on the jsfiddle page. For those who just copied the above text without going there, you'll need the prefixfree javascript file too.
Comment: @fcalderan It it possible to make the animation without trailing space? I mean the second animation start before the 1st animation is finish so that no blank space between the animation. Thank you.
Comment: Very nice but if the text character gets more or less, the speed changes as well. The more text, the faster text. Is there a solution for it? @fcalderan
Comment: of course, you need to add vendor prefixes where necessary.
Comment: @FabrizioCalderan Thank you, but just wondering.. Is it possible to detect if the text has finished scrolling with some javascript?
Comment: I twisted it a little so that instead of starting on the right, it starts with the first text already positioned left. Small change:
add `.marquee span { animation-delay: -7.5s; }`
Comment: @YasinOkumuş try to increase the animation-duration
Comment: This answer worked, sort of,  If you are experiencing weird behaviour like: Text slows down when fully in view (even with `linear`) or: When using text-indent: -100% the text stops at ~50%. You might have the css tag: `text-align: center` on. It causes weird stuff to happen. Just wanted to add it here in case anyone had problems like I had.
Answer: Based on the previous reply, mainly @fcalderan, this marquee scrolls when hovered, with the advantage that the animation scrolls completely even if the text is shorter than the space within it scrolls, also any text length takes the same amount of time (this may be a pros or a cons) when not hovered the text return in the initial position.
No hardcoded value other than the scroll time, best suited for small scroll spaces

.marquee {
    width: 100%;
    margin: 0 auto;
    white-space: nowrap;
    overflow: hidden;
    box-sizing: border-box;
    display: inline-flex;
}

.marquee span {
    display: flex;
    flex-basis: 100%;
    animation: marquee-reset;
    animation-play-state: paused;
}

.marquee:hover> span {
    animation: marquee 2s linear infinite;
    animation-play-state: running;
}

@keyframes marquee {
    0% {
        transform: translate(0%, 0);
    }
    50% {
        transform: translate(-100%, 0);
    }
    50.001% {
        transform: translate(100%, 0);
    }
    100% {
        transform: translate(0%, 0);
    }
}
@keyframes marquee-reset {
    0% {
        transform: translate(0%, 0);
    }
}

    This is the marquee text (hover the mouse here)

Comment: A tip for future readers: **hover the text in the demo**.
Answer: The accepted answers animation does not work on Safari, I've updated it using translate instead of padding-left which makes for a smoother, bulletproof animation.
Also, the accepted answers demo fiddle has a lot of unnecessary styles.
So I created a simple version if you just want to cut and paste the useful code and not spend 5 mins clearing through the demo.
http://jsfiddle.net/e8ws12pt/

.marquee {
    margin: 0 auto;
    white-space: nowrap;
    overflow: hidden;
    box-sizing: border-box;
    padding: 0;
    height: 16px;
    display: block;
}
.marquee span {
    display: inline-block;
    text-indent: 0;
    overflow: hidden;
    -webkit-transition: 15s;
    transition: 15s;
    -webkit-animation: marquee 15s linear infinite;
    animation: marquee 15s linear infinite;
}

@keyframes marquee {
    0% { transform: translate(100%, 0); -webkit-transform: translateX(100%); }
    100% { transform: translate(-100%, 0); -webkit-transform: translateX(-100%); }
}

Simple CSS Marquee - Lorem ipsum dolor amet tattooed squid microdosing taiyaki cardigan polaroid single-origin coffee iPhone. Edison bulb blue bottle neutra shabby chic. Kitsch affogato you probably haven't heard of them, keytar forage plaid occupy pitchfork. Enamel pin crucifix tilde fingerstache, lomo unicorn chartreuse plaid XOXO yr VHS shabby chic meggings pinterest kickstarter.

Comment: Feels like bullet train :D
Comment: I'm testing on Safari Version 13.1.1 and the accepted answer works fine (OSX Mojave, October 2020)
Comment: Hi, thanks for the heads-up regarding safari, but one question: if you're saying you're cleaning up the extra styles... why adding "padding: 0; height: 16px; and stuff like that? Is it for some browsers to display correctly? Thank you!
Answer: The following should do what you want.
@keyframes marquee {
    from  { text-indent:  100% }
    to    { text-indent: -100% }
}

Comment: No it does not, since the parent width is considered for this: Let it scroll to the end and see that the text disappears before it is scrolled completely out of sight: http://jsfiddle.net/XxUXD/712/
Comment: I just up voted your comments, you're right... nobody told me it runs infinite. ;)

How can I create a marquee effect?


How are these spammers getting through?

Question: So we've been a bit of an indirect target of spammers recently... my company has gotten a lot of complaints from customers that they are getting a lot of spam from our sales people. Normally (considering the nature of sales) I'd just smack the sales staff and move on... but this isn't us!
Some spammer has been sending emails... to OUR customers... using OUR email addresses. doing a quick message trace and sure enough, these emails appear to be coming from our account. At first I thought it was a hacked account or two so I had everyone change their passwords and set 2fa... but the next day, a batch more emails went out. I ran an audit on the affected accounts and there were no failed logins and no attempts to reset passwords (we disabled password reset because of this).
Normally, I'd say this was just normal spoofing... but these emails are passing THROUGH our exchange online account, the message header even shows our dkim and dmarc. As far as I can tell, Microsoft honestly thinks they are coming from US!
I've added the x-originating-ip to the block list under threat-management. hopefully that will help, but it wont take long for the spammers to update their IP and if that happens while I'm off the clock... well our customers get another massive load of spammy spam... I'd add our IP's to the allow list and block all others, but most of our sales staff are working from home with dynamic IPs so that's not really possible right now. How do I fight this?
Comment: Has one of the sales people had their laptop compromised, perhaps?
Comment: I thought that too, nope and nope. even with PCs offline, the emails go out. additionally, the origin ip is in another state. of course it's probable the spam is being sent over a proxy.
Comment: My thinking is that you could use the **message trace** feature in the EAC to trace these spam emails. At the same time, maybe EOP(https://docs.microsoft.com/en-us/microsoft-365/security/office-365-security/outbound-spam-controls?view=o365-worldwide) could help you manage outbound spam?
Comment: I did a message trace, that's how I know the spam is being processed inside our tenant! for all intents and purposes, the sales people are sending those emails. the problem is, I personally went through and cleared their rules, reset their passwords, set 2fa, disabled password resetting, dropped all active connections (force logoff), AND blocked sign in! spam is STILL going out! my next option is to delete those mailboxes and set a flow rule to bulk delete all messages going through them... the problem is our clients use those email addresses. starting over like that would be a dissaster.
Comment: Do these spam emails have the common content or keywords? If so, I think you could try to create a transport rule(e.g. **"If the senders are the two mailboxes, and the subject or body includes some keywords, these emails will be deleted."**)
Comment: Yeah, that was my next attempt. so far there's been nothing to show for it. no emails period after blocking the source IP... either the spammers aren't aware we blocked their IP, or they just moved on to another scam. we'll see.
Comment: If there is any update, you're welcome to post it. Hope everything goes well with you:)
Comment: so far, nothing. like I said, I just blocked their source IP and we haven't seen anything more. I suspect it's just not worth their time to keep trying, but my original concern is still valid. if they change their IP, they could just pick back up again. I'm putting together a plan to set allowed IPs and block everything else. that of course necessitates our users having static IPs or connect over a VPN... blarg.
Comment: Do their PCs have an anti-virus program? Scan and see if there is a malware sending these spam emails.
Answer: My thinking is that you could use the message trace feature in the EAC to trace these spam emails:

At the same time, maybe EOP(https://docs.microsoft.com/en-us/microsoft-365/security/office-365-security/outbound-spam-controls?view=o365-worldwide) could help you manage outbound spam?

How are these spammers getting through?


comments module with infinite scroll

Question: I've added a comment field to my content type. Now I'd like to add infinite scroll to the comments messages, so it shows by default some number of comments and when I click on the load more button, it shows more.
The problem is that the list of comments is coming from the comment module, not a view, so I can't add infinite scroll plugin to the pager. If I create a custom view that shows the comments, it gets complicated because some comments have nested comments and so on. Is there any solution?
Answer: One option is to create a "views block" that shows comments, set it to use views infinite scroll, then add it to the bottom of the page (and disable the page from showing comments the normal way).
Comment: Matt, thanks. setting a new view "as block"that display comments and adding infinite scroll as pager. And render it at the bottom it's easy.Then i'm confused what do you mean **and disable the page from showing comments the normal way** ? how to make the list of comments comming by default from **comment** module related to my custom view ? once a agian i cannot configure that list coming from the comment module, its not even a view.
Comment: Two potential ways I could imagine:

1. You might be able to do it through the drupal UI.  If you go to the content type you're dealing with and "manage display", does it allow you to hide comments?

2. You do it with a theme override. First turn on twig debugging (https://www.drupal.org/docs/8/theming/twig/debugging-twig-templates) then view source of the page to see which twig template is showing comments.    Then, you can override that template by creating a template with the same name in your subtheme. Simply copy the original template over, but remove the part that displays comments.
Comment: There's a 3rd rather dirty way to do it, which is to hide the normal section that shows comments with CSS (display:none).  I wouldn't recommend this way as it's not great for performance but it is a 3rd option.

comments module with infinite scroll


Add a link to a tableselect row

Question: I'm interested in adding a link in a tableselect form row. Utilizing the #options key I can only add columns with strings. I am able to add form elements in the #options array similar to the #rows array.
$rows[$nid] = [
    'edit_link' => [
        'class' => 'edit_link',
        'data' => [
            '#type' => 'link',
            '#url' => Url::fromRoute('group_manager.edit'),
            '#title' => 'test',
        ],
    ],
]

//…

$form['table'] = array(
    '#type' => 'tableselect',
    '#header' => $header,
    '#options' => $rows,
);

Implementing this example as is doesn't render this column in the table, so I assume it has failed somehow.
The 'edit_link' element works if the form is changed to a 'table' instead of 'tableselect'.
Comment: Your code is roughly correct, but there are things you didn't post so I can't say for sure why you're having a problem. Note that classes need to be passed as an array, so that should look like 'class' => ['edit_link']. Also, you only show one column - is that really all your table has? And if the 'group_manager.edit' route needs a parameter (e.g. the group id ?) that needs to be specified in your Url::fromRoute() call ... But as I said, your code is basically correct and should work for a tableselect - I use working code that's very similar to the above. Check your log for errors ...
Answer: I solved my issue.
The links column was not rendered for the tableselect form because I didn't update my $header array with the new element name edit_link.
It appears a table form does not map the element names to the header names, meaning I did not have to update the header array for my link columns to appear.  As long as the element name was in the header array Tableselect would render the column.  I believe this to be the basis of my issue.

Add a link to a tableselect row


Como integrar o React em uma estrutura MVC (PHP)?

Question: Estou aprendendo PHP e me veio uma dúvida: Com o React, nós temos a CLI, que é uma estrutura já pronta para você, com todos os arquivos necessários. No MVC nós construímos uma estrutura separando a view, controller e model em pastas diferentes.
A dúvida é: Na estrutura MVC, eu devo baixar o pacote CLI do React para poder usá-lo, ou apenas copiar a CDN para as views e usá-lo normalmente?
Answer: o ideal seria transformar seu código php em uma API REST. Essa API retornaria apenas os dados em JSON sem view, que serão utilizados no react.
Você teria seu controller baseado em retornos de JSON, exemplo:
<code>public function index() {
  $dados = []; # qualquer dado

  http_response_code(200);
  return json_encode($dados);
}
</code>
No react, você pode usar a biblioteca axios, para fazer as requisições na API - php.


Custom permissions for unpublished content

Question: I'm running in to a problem with my drupal 8 site. I want to give access to unpublished content. I found a solution using a hook.
I want to create a custom module these don't seem to work.
I found this for the unpublished problem:
"View unpublished content" permission for non-author
It looks like a solid solutions for my problems but I can't get them to work. I can enable the modules created, and it doesn't give any errors.
My view_unpub.info.yml file:
name: View Unpublished
type: module
description: 'View Unpublished Content'
package: SVDS
core: 8.x

My view_unpub.module file:
<?php
function view_unpub_permission()
{
    return array(
        'unconditionally view unpublished content' => array(
            'title' => t('Unconditionally View Unpublished Content'),
            'restrict access' => TRUE
        )
    );
}

function view_unpub_node_access($node, $op, $account)
{
// We're only bothered about the 'view' operation at the moment
    if ($op == 'view') {
// If the user has access to our new permission, let 'em at it
        if (user_access('unconditionally view unpublished content', $account)) {
            return NODE_ACCESS_ALLOW;
        }
    }

// For everything else let the system decide.
    return NODE_ACCESS_IGNORE;
}

Comment: `hook_permission` no longer exists in Drupal 8. You need to add a mymodule.permissions.yml file, which is the new way. See: https://www.aram.cz/article/custom-permissions-drupal-8
Comment: thanks for your reply. And for the second problem I'm moving to a new post. I fixed the problem I changed FileInterface to \Drupal\file\FileInterface to get it to work but the is a other problem the came to my notice.

My new post [Image styles deleted on node save](https://drupal.stackexchange.com/questions/240151/image-styles-deleted-on-node-save)
Answer: The code you are showing is not completely ported to Drupal 8. In particular:

hook_permission() is not used anymore from Drupal 8; what you need is describing the module permissions in view_unpub.permissions.yml
user_access() has been removed
Constants like NODE_ACCESS_ALLOW have been removed

As example of hook_node_access() implementation, see node_node_access(), which also shows what replaces user_access() in Drupal 8.
function node_node_access(NodeInterface $node, $op, $account) {
  $type = $node->bundle();
  switch ($op) {
    case 'create':
      return AccessResult::allowedIfHasPermission($account, 'create ' . $type . ' content');
    case 'update':
      if ($account->hasPermission('edit any ' . $type . ' content', $account)) {
        return AccessResult::allowed()->cachePerPermissions();
      }
      else {
        return AccessResult::allowedIf($account->hasPermission('edit own ' . $type . ' content', $account) && $account->id() == $node->getOwnerId())->cachePerPermissions()->cachePerUser()->addCacheableDependency($node);
      }
    case 'delete':
      if ($account->hasPermission('delete any ' . $type . ' content', $account)) {
        return AccessResult::allowed()->cachePerPermissions();
      }
      else {
        return AccessResult::allowedIf($account->hasPermission('delete own ' . $type . ' content', $account) && $account->id() == $node->getOwnerId())->cachePerPermissions()->cachePerUser()->addCacheableDependency($node);
      }
    default:

      // No opinion.
      return AccessResult::neutral();
  }

The rest of the code seems fine, to me. Check all the files you are using, and see if they need any change to make your modules work in Drupal 8.
Comment: Hi there I thought I had i covered but I don't. I created a .permissions.yml file this works great and tried this, but that doesn't work:

`function view_unpub_node_access(\Drupal\node\NodeInterface $node, $op, $account)
{
    switch ($op) {
        case 'view':
            return AccessResult::allowedIfHasPermission($account, 'view all unpublished');
        default:

            // No opinion.
            return AccessResult::neutral();
    }
}`
Comment: Did you add `use Drupal\Core\Access\AccessResult;` as well as all the necessary `use` lines at the beginning of the file?


Crash with "Out of Virtual Memory"

Question: I'm maintaining an existing application and I've encountered a bug when running under some conditions (easily reproducible), where the app fails with message :

Title: "Windows - Out of virtual memory"
Content: "Windows is low in virtual memory..."

Question is: what I need to check first? When is this message happening? Why?
What is stored in this virtual memory in C#, why an out of memory?
Answer: It sounds like you have a memory or resource leak of some kind. Time to crack open a profiler and see what's consuming resources or memory.
Good profilers include
http://www.red-gate.com/products/dotnet-development/ants-performance-profiler
and
http://memprofiler.com/
-- this will attach to your running process and see what's out of control.
In general this kind of issue can be caused by objects that implement IDisposable not being disposed through a call to Dispose(). The memory and resources used by these objects are not managed by the .NET garbage collector so (unlike regular .NET objects) they won't be tidied up by the system automatically.
A profiler will usually tell you if this is an issue.
There are other situations where this can happen, for instance

Allocation of very large blocks of memory, e.g. 40Gb arrays
Very heavily loaded systems that don't have a chance to properly garbage collect can exceed their virtual memory allocation.

Again, a profiler will tell you where the problem is likely to lie.
Comment: Seems to be the only solution, use a profiler. Thanks for the links
Comment: Most profilers have a 30-day free trial... which can be useful!
Answer: Windows uses Virtual Memory for memory management, but the memory being virtual isn't the issue here. What this indicates is that your application allocates a lot of memory - more than available on the system.
Some things that might cause this:

You are using unmanaged code somewhere that fails to release memory.
You allocate enormous blocks of data (e.g. dynamic calculation of an array size that incorrectly allocates 2GB of data).
You keep references to buffers around longer than needed which prevents the garbage collector from reclaiming the memory.

Without knowing more about your application it is impossible to give any more detailed hints.
Comment: I'm new to the app' and have no more informations to provide at the moment.
Answer: Obviously you're application is taking a lot of memory. You can read about virtual memory here: http://blogs.technet.com/b/markrussinovich/archive/2008/11/17/3155406.aspx

Crash with "Out of Virtual Memory"


How did the author make this leap?

Question: In this paper, the authors examine a common differential equation model for the concentration of a drug in the blood.
In the paper, they begin with the following expression
$$ \mu(t)=\frac{D k_{a}}{V\left(k_{a}-k_{e}\right)}\left\{\exp \left(-k_{e} t\right)-\exp \left(k_{a} t\right)\right\} $$
They then collect some terms
$$\mu(t)=D \exp \left(\beta_{0}+\beta_{1} t\right)\left[1-\exp \left\{-\left(k_{a}-k_{e}\right) t\right\}\right]$$
With $\beta_{0}=\log \left\{k_{a} /\left[V\left(k_{a}-k_{e}\right)\right]\right\} \text { and } \beta_{1}=-k_{e}$
And finally make the leap saying that this can be modeled using
$$\mu_{i j}=D_{i} \exp \left(\beta_{0}+\beta_{1} t_{i j}+\beta_{2} / t_{i j}\right)$$
This last part is where they lose me.  I'm certain they make some approximation, but it isn't clear what approximation is made.
Can anyone shed some light onto how that last jump was made?
Answer: With this kind of thing, a good place to start is to expand things out so you can do a clear comparison of them.  On the one hand we have:
$$\mu(t) = D\exp (\beta_0 +\beta_1 t)[1 - \exp \{-(k_a-k_e)t\}] $$
which expands to
$$\mu(t) = D\exp (\beta_0 +\beta_1 t) - D\exp (\beta_0 +\beta_1 t)\exp \{-(k_a -k_e)t\} \tag{1}\label{eqn1}$$
and on the other we have
$$\mu_{ij} = D_i \exp(\beta_0 +\beta_1 t_{ij} +\beta_2/t_{ij}) \tag{2} \label{eqn2} $$
Comparing (\ref{eqn1}) and (\ref{eqn2}) we see that it's likely that $\beta_2 = (k_a-k_e)$ and the minus sign has been associated with the $t$ to obtain $\beta_2/t_{ij}$ in (\ref{eqn2}).
Without knowing more about the problem it's impossible to say why the first term, $D\exp(\beta_0 +\beta_1 t)$ is being ignored.  I followed your link, but all the details are paid-for and I'm not interested enough in this question to spend money to be able to answer it :)  It seems likely that it is either

small relative to the second term, and so can be neglected
being incorporated into the $D_i$ term after time discretization

with the second option being most likely since $D_i$ wouldn't need a subscript if $t$ weren't involved somehow.
Since this is a question about mathematical modelling, it might be worth me noting that a model is of less use if it's not well-explained, so your question would benefit from indicating what $k_a$ and $k_e$ are and explicitly talking about the time discretization in order to help answerers.  $t_{ij}$ suggests a two-dimensional mesh to me, but I'm guessing.  If I knew for certain, then I might be able to explain the $D_i$ term better.

How did the author make this leap?


Drop rows from each group if dates are within a given range

Question: Given a DataFrame like below:
dfx = pd.DataFrame({"ID":["A", "A", "C" ,"B", "B"],
                    "date":["01/01/2014","01/31/2014","01/23/2014","01/01/2014","01/20/2014"]})

I want to remove "duplicates". "duplicates" are defined as those rows where the ID of the rows are the same, but the "date" between them is Less Than 30 days.
The resulting DataFrame upon removal of the "duplicates" is expected appear as:
ID    date
A   01/01/2014
A   01/31/2014
C   01/23/2014
B   01/01/2014

Answer:
Convert date to datetime.
Group date by ID and find difference between consecutive rows
Extract the days component from the timedelta difference and compare it to 30
Filter dfx based on the mask

dfx[~pd.to_datetime(dfx.date).groupby(dfx.ID).diff().dt.days.lt(30)]

  ID        date
0  A  01/01/2014
1  A  01/31/2014
2  C  01/23/2014
3  B  01/01/2014


Characterizing clusters by separate feature vector scores

Question: Say I have a medium amount of dependent variables in a study. These are scores from questionnaires that have been standardized so all are on a scale from 0 to 1.
I have clusters of my patients - determined by another method - and I want to use a method to characterize the patients in each cluster as distinguished from patients in the other clusters. Let's say I have 5 clusters.
Is there a method that anyone knows about that can detect these "threshold relationships" automatically? I worry my results will be complicated and I may not be able to "see" how cluster 1 and cluster 2,3,4,5 differ by their questionnaire scores (or determine if they don't, statistically).
I want a rigorous, non eye-balled approach, if that makes sense. Rules I end up will look like the following characterizations:
<code>Cluster 1: Score1>=0.8, Score2<=0.4, Score3>=0.8, ...
Cluster 2: Score1<=0.2, Score2>=0.6, Score3<=0.2, ...
Cluster 3: Score1>=0.4, Score2<=0.7, Score3<=0.5, ...
</code>
And then a significance value for each cluster against the rest... Could I use a multi-way ANOVA for that?
Answer: Use a decision tree.
You are looking for an interpretable classifier, not a clustering. You already did clustering, and you are using that as classes now.
Comment: I love it - I will definitely look into this!


Zimbra: changing postfix parameters

Question: I would like to change mynetworks Postfix configuration parameter in Zimbra 7 on Debian GNU/Linux 5.0.
I tried the following (as zimbra user):
$ zmlocalconfig -e postfix_mynetworks="127.0.0.0/8 [...]"
$ postconf -e mynetworks="127.0.0.0/8 [...]"
$ zmmtactl reload
$ postfix check
$ postfix reload

However
$ postconf mynetworks

Shows still the old value! Anyone knows why and how to fix this? Thank you in advance
UPDATE After office hours I've even tried
# /etc/init.d/zimbra stop
# /etc/init.d/zimbra start

However the parameter is still not updated.
UPDATE 2
$ zmlocalconfig postfix_mynetworks

Shows the updated value
$ zmmtactl reload
Rewriting configuration files...
postfix/postfix-script: refreshing the Postfix mail system
Stopping saslauthd...done.
Starting saslauthd...done.

But sadly postconf mynetworks still shows the old value. Running again postconf -e sets the value and gets lost at the first postfix reload...
Comment: You can also change this in the Admin Console under Server Settings -> MTA -> MTA Trusted Networks.
Comment: @xeon, thank you, that's a good suggestion, why don't you post it as an answer?
Answer: I found the solution to my own problem. By looking at the file /opt/zimbra/conf/zmmta.cf, I saw the following lines:
if VAR zimbraMtaMyNetworks
    POSTCONF mynetworks VAR zimbraMtaMyNetworks
fi

With zmprov I can check the current settings and change them:
zmprov getServer servername.mydomain | grep zimbraMtaMyNetworks
zmprov modifyServer servername.mydomain zimbraMtaMyNetworks "127.0.0.0/8 [...]"
postfix reload

And the problem is solved. Xeon suggested an alternative and simpler way:

You can also change this in the Admin
  Console under Server Settings -> MTA
  -> MTA Trusted Networks

Zimbra: changing postfix parameters


Usuário com própria página

Question: Eu to fazendo um portal, e para fazer o cadastro precisa de cpf e email. Aí envio um email de confirmação, ele clica no link e a situação dele no meu bd muda. Assim o usuario pode acessar o portal. Só vai ter uma página, e todos os usuários irão usar a mesma página, só que os dados que virão da api serão diferentes de cada um. Como faço pra saber que o usuário que entrou (preciso saber a partir do cpf) é tal pessoa para colocar os dados, e tal.
Página index.php
<?php session_start(); include 'config/conexao.php';
?>
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <title>Lojas Guido | Portal do Cliente - Login</title>

    <link href="https://fonts.googleapis.com/css?family=Lato:300,400,700" rel="stylesheet">

    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" media="all">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
    <link rel="icon" href="img/icon/guido.ico" type="image/x-icon">
    <link href="css/style.css" rel="stylesheet" media="all">

          <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#elementoCollapse1">

          </button>

          Lojas Guido

                Cadastrar

Portal do Cliente

Entrar

                        <form name="formulario" id="formEnvia"  method="POST">

                          <?php
                            include "config/valida.php";
                           ?>

                            CPF*
                            Apenas números

                            <input type="text" id="cpf" name="cpf" class="form-control input-lg" placeholder="000.000.000-00" maxlength="14"
      title="Digite apenas números" required />

                            E-mail*:
                            <input type="email" id="email" name="email" class="form-control input-lg " placeholder="email@example.com" maxlength="50" required/>

                            <button type="submit" name="valida" id="valida" value="valida" onclick="valida_envio()" class="btn btn-primary btn-lg btn-block">

                              Acessar</button>

                                Não possui cadastro?  Cadastre-se

                        </form>

Página valida.php
<?php

require_once "config/conexao.php";

if(isset($_REQUEST['valida'])){
  $var1 = $_REQUEST['cpf'];
  $var2 = $_REQUEST['email'];
$query = "SELECT `leados`.`email`, `leados`.`cpf`, `links_emaos`.`situacao` from `leados` INNER JOIN `links_emaos` ON `leados`.`id` = `links_emaos`.`leado_id` WHERE situacao = '2' AND cpf='$var1' AND email= '$var2'";

         $querySelect = mysqli_query($conn,$query);

         if ($received_token === token()) {

         if(mysqli_num_rows($querySelect) == 0){
           $mensagem = "
CPF ou E-mail incorreto!
";
           printf ($mensagem);
         }else {

           $_SESSION['cpf'] = $var1;
           $_SESSION['email'] = $var2;
         header("Location:postagem.php");
       }
}else {
  $mensagem = "
Você não tem autorização para entrar!
";
  printf ($mensagem);
}
}

Obs.: apaguei os códigos do token
Comment: pelo que me parece você está salvando o cpf e email dele em uma session, você não consegue usar esse valor para indicar à sua api qual é o usuário logado?
Comment: Eu fiz nas 3 páginas que existe do site (já depois de logado)

Mas não sei se isso já faz o api saber o cpf logado
Answer: Passe os dados do usuário presentes na variável SESSION para a página de dashboard do usuário, dentro da página do dashboard, você pode validar os dados efetuando uma nova consulta no banco de dados com os valores capturados na variável de sessão.
Comment: Não tenho essa página dashboard
Comment: dashboard é a página inicial que o usuário vai acessar ao entrar no sistema. É para essa página que você precisará enviar os dados via `SESSION`

Usuário com própria página


Select2 selects the first option automatically with tags = true

Question: I have a select with some options and i want to avoid that the first option is the selected one, so i do the following and after that i initialize the select2:
<select class='form-control form-control-sm'>
  <option value='100294'>Aguacate</option>
  <option value='400172'>Bundle Editable</option>
  <option value='100291'>Bundle no Editable</option>
  <option value='100260'>Camara</option>
</select>
$('select').val([]);

$('select').select2({
    tags:true
});

The problem is that, for some reason when i set the select2 tag options to true, after typing 2 characters, the first value is automatically selected and i don't know why
Fiddle: https://jsfiddle.net/wolfteam20/2pwkLq6j/1/
Any help would be appreciated
Edit: I think this one is a bug in select2
Issue
Answer: I know it's been a while, but there is a workaround for this.
Turns out that if you add an empty <option> to the select tag, and add a placeholder, the issue is fixed.
JSFiddle
Comment: plus 1, Awesome. Just what I needed.


Como retornar o tratamento de dados em Matriz passada como parâmetro para rotinas no VBA/Excel?

Question: Preciso passar matrizes distintas para uma rotina que ordena seus elementos e recebem outros tratamentos, e após isso quero que ela retorne esses valores ordenados e tratados para a matriz original; por exemplo, passei valores fora de ordem e alguns fracionados para a rotina por meio de uma matriz, primeiro os valores fracionados são arredondados e depois ordenados, para então retornarem para a matriz que "alimentou" a rotina desta forma (sem as casas decimais e ordenados).
Primeiro os dados são retirados de uma planilha no Excel e preenchem as matrizes que irei tratar. Estes dados não podem ser alterados, pois trata-se de dados de digitação e devem permanecer na ordem e como foram digitados, de qualquer forma, preciso resolver estes casos somente pelo VBA.
A ideia é ter uma rotina que trate a matriz passada para ela, o que funciona, mas que os valores da matriz original, recebam de volta os valores tratados; isto eu não consegui fazer nem encontrar como fazer.
Pesquisei sobre isso para o VBA, mas o que encontrei só faz referência em usar esses valores da matriz dentro da rotina, porém não devolvendo o resultado para a matriz original.
O exemplo abaixo foi retirado do link:
Noções básicas sobre matrizes do parâmetro
O exemplo funciona para receber e manipular esses valores, porém preciso ter os resultados retornados para a matriz original que no meu caso tratam-se de variáveis dimensionadas, e não somente de dados como mostra este exemplo.
Tem como fazer isso no VBA/Excel?

O exemplo a seguir mostra como você pode definir um procedimento com
  uma matriz de parâmetros.

Sub AnyNumberArgs(strName As String, ParamArray intScores() As Variant)

     Dim intI As Integer

     Debug.Print strName; " Scores"

   ' Use UBound function to determine upper limit of array.
     For intI = 0 To UBound(intScores())

         Debug.Print " "; intScores(intI)

     Next intI

End Sub

Os exemplos a seguir mostram como você pode chamar esse procedimento.

AnyNumberArgs "Jamie", 10, 26, 32, 15, 22, 24, 16

AnyNumberArgs "Kelly", "High", "Low", "Average", "High"

Basicamente os testes que fiz tiveram este formato, no entanto fiz inúmeras tentativas mudando a forma de usar as matrizes, de chamada da função, mudando o tipo de variável declarada na função, etc. Como o básico não funcionou. não tenho o código completo, pois busquei testar primeiro antes de fazer a rotina, já que nunca tinha feito isto antes: Usei função, pois a ideia é que ela "retorne" com os dados tratados e não fiz declarações públicas, pois queria saber se funcionaria desta forma. Portanto, o código abaixo apresenta a estrutura da ideia de como tentar resolver o problema:
Private Sub CommandButton1_Click()

    ...
    ...

    MatrizA() = TrataDepoisRetornaMatriz( MatrizA(), QtdeDeItensDaMatrizA )

    MatrizB() = TrataDepoisRetornaMatriz( MatrizB(), QtdeDeItensDaMatrizB )

    MatrizC() = TrataDepoisRetornaMatriz( MatrizC(), QtdeDeItensDaMatrizC )

    ...
    ...
    ...
End Sub

Private Function TrataDepoisRetornaMatriz( _
      ParamArray Matriz() As Variant, _
           Byval QtdeDeItensDaMatriz As Integer) _
              As Variant
    ...
    ...
    ...

    TrataDepoisRetornaMatriz = Matriz()

End Function

Comment: Leo, não tenho Excel em casa... agora que entendi o que vc não consegue... na segunda te envio uma função retornando os dados... mas se fizer como fez mesmo, vai conseguir, colocando os dados lidos em um array e retornando como função ou colocando um array declarado como global. Veja aqui como fazer http://excelmacromastery.com/Blog/index.php/the-complete-guide-to-using-arrays-in-excel-vba/, desculpe não poder ajudar de maneira completa... mas abandonei windows para desenvolvimento. Na segunda respondeirei sua pergunta e creio que será a contento. Abraço e bom fds
Comment: Oh Leo não tive tempo. Pode postar ai que já deve ter até a rotina de ordenar que teria de fazer aqui, acho que ficará mais completa. Abs e Obrigado pela consideração. Se quiser marque meu comentário com o link como útil à resposta. Abraço
Comment: Quando vc diz que a ordenação da matriz "passada" funciona, porém não consegue retornar para esses valores para a matriz original... essa matriz original seria, ou estariam, em uma planilha/tabela? Pois poderia fazer uma macro simples para ordenar a coluna desejada... se não for isso, acho que não entendi direito... desculpe-me
Comment: Evert, os dados são somente retirados da planilha, não retornam. Um exemplo: as matrizes (vetores) A, B e C pegaram três grupos de dados distintos da planilha. Tem a função/rotina (testei os dois casos), OrdenaDados, que passo como parâmetro um vetor por vez que quero ordenar, informando o vetor (A, B ou C) e a respectiva quantidade de itens para ordenação. São três chamadas da função. Como apresento os dados de A, B e C depois, preciso que eles tenham o resultado da ordenação. É isso.
Comment: Evert, sei que parece estranho eu não ordenar primeiro na planilha, é que eu apresentei o problema simplificado, meu caso é mais complexo e não se trata só de ordenar os dados, eles são tratados também. Se funcionar para esse caso, funcionará também para o que eu preciso, é isso amigo.
Comment: Editei a pergunta para melhor esclarecer.
Comment: onde vc declarou sua matriz? Em um módulo? Ou está tratando como classes? Creio que se tiver a matriz 1 declarada globalmente, não vai precisar de duas... pegue a matriz com os dados, faça as alterações nos valores, dentro da própria função tenha uma matriz temporária e retorne a matriz preenchida como precisa.... Caso ainda não consiga assim, mostre como fez sua implementação, mostre seu código para facilitar a identificação da melhor forma de utilizar. Esse código da microsoft roda ok, mas como foi a sua implementação?
Comment: Eu não coloquei o código pois o que fiz não funcionou de várias formas que tentei, o código é o próprio do formulário, não fiz em módulo separado nem criei uma classe (não trabalhei com classes ainda, mas gostaria). Vou rascunhar uma chamada.
Comment: É que comentou em sua pergunta que funcionou a ordenação... verei hj no trabalho que tenho Excel.
Comment: Oi Evert, eu editei a pergunta, o "exemplo" é que funciona ao receber os dados da matriz, isso eu também consegui, mas retornar os dados após alguma modificação na rotina é que não consegui.
Comment: Evert, obrigado, funcionou perfeitamente e sem declarar a variável como Pública. Aguardo teu exemplo para marcar a resposta e votar. O link é didático, excelente. Valeu!
Comment: Oi Evert, você irá postar a resposta? Se for eu aguardo, senão me avisa que eu posto para não ficar sem resposta.
Comment: Valeu pela dica, abraço!
Answer: A solução é apresentada no código abaixo.
O exemplo do código é simplificado para mostrar com pequenas adaptações ao link    http://excelmacromastery.com/Blog/index.php/the-complete-guide-to-using-arrays-in-excel-vba/ indicado pelo Evert, como fazer funcionar a principal necessidade: "passar dados de uma matriz para uma outra matriz em uma função e ter os resultados desta matriz tratados nesta função retornados para a matriz que a alimentou.
Option Explicit

Private Sub UserForm_Initialize()

    Dim i As Integer

    ' Declare dynamic array - not allocated
    Dim arr() As String

    ' Return new array
    arr = GetArray

    For i = 0 To 5

        MsgBox arr(i)

    Next i

End Sub

Public Function GetArray() As String()

    Dim i As Integer

    ' Create and allocate new array
    Dim arr(0 To 5) As String

    ' Return array

    For i = 0 To 5

        arr(i) = i & " elevado ao quadrado é igual a " & i ^ 2

    Next i

    GetArray = arr

End Function

Claro que da mesma forma podem ser feitos os tratamentos citados na pergunta, como a ordenação de dados, por exemplo, mas a questão não é o tratamento em si, e sim a solução deste problema de transferir e receber valor de matrizes em uma função.


Doubt regarding mutually exclusive events and their complements

Question: Premise: My understanding is that if two events are mutually exclusive, it need not be that they are complementary. However I came across a question that said the following -
If $P(A') = \alpha$ and $P(B') =\beta$ then $P( A\cap B)$ must be ?
The answers is greater than or equal to $1 - \alpha- \beta$. I get the idea, but what if $A$ and $B$ are mutually exclusive - Wouldn't the answer given be wrong then? Because my premise is that disjoint does not mean $\alpha + \beta = 1$, so $1 - \alpha- \beta$ would have a positive value clearly not equal to zero!.
Comment: Are you sure you mean $P(A')$ but $P(B)$? That doesn't seem right for treating $\alpha$ and $\beta$ with the same sign later on.
Comment: If nothing else is specified you can just take $ A $ and $ B $ to be mutually exclusive and then $ P(A\cap B) = 0 $. What you can do with the intersection is to *upper*-bound it by $ \mathrm{min}\left[P(A), P(B)\right] $ (when an event implies the other one), so $ \mathrm{min}\left[1-\alpha, \beta\right] $ (assuming by $ A^\prime $ you mean the complementary of $ A $).
Comment: @HenningMakholm I'm sorry, had made a mistake while typing out the question. I've made the edits now
Answer: The claim you're qouting is either misquoted or wrong. What is right is

If $P(A^\complement)=\alpha$ and $P(B^\complement)=\beta$, then $P(A\cap B)\ge 1-\alpha-\beta$.

(Note that here $\beta$ is the probability of the complement of $B$, not of $B$ itself).
This doesn't contradict the fact that $P(A\cap B)=0$ when $A$ and $B$ are mutually exclusive, because in that case $\alpha+\beta>1$ so the bound from the claim is negative (and therefore trivially satisfied).
Comment: @madhavU: In that case you're right that $1-\alpha-\beta$ is not $0$. But then $1-\alpha-\beta$ is _negative_, and then the probability of $A\cap B$ is certainly _greater than_ this negative number.
Comment: You may be getting confused by the fact that $\alpha$ and $\beta$ are not the probabilities of $A$ and $B$, but of their _complements_. So $1-\alpha-\beta = P(A)+P(B)-1$.
Comment: I did'nt get your last line, could you please explain a bit more ?, what I felt was if A intersection B is 0 and A union B is 1 then we can safely say that 1 -$\alpha$ -$\beta$ = 0, but I don't think this could be the case if A union B is not equal to 1
Comment: Thank you so much I get it now!!


Is there a list of file/image field subtokens?

Question: Token browser does not show the options for file properties. [node:file-field:0:file:url] gets the url, but is there a list of all file options? Or is there a way to check it from sourcecode somehow?
Gathering the list:

[node:field-image:0:file:url]
[node:field-image:0:file:extension]
[node:field-image:0:file:name]
[node:field-image:0:file:size]
[node:field-image:0:file:mime]
The last thing that is still unknown to me is if there is an option to pull image width and height? If I remember correctly that data is in the db.
Comment: Though I would add some context. I am using tokens in metatag module.
Comment: You can create your own custom tokens like [this](https://www.drupal.org/node/1143842). There is also a [module](https://www.drupal.org/project/token_custom) for that
Answer: For file https://www.drupal.org/node/390482#token-file
https://www.drupal.org/project/imagefield_tokens
and
add https://www.drupal.org/project/filefield_paths   add this module
for {The File (Field) Paths module extends the default functionality of Drupal's core File module, Image module and many other File upload modules, by adding the ability to use entity based tokens in destination paths and file names.}
Check this screenshot:
Comment: The last thing that is still unknown to me is if there is an option to pull image width and height? If I remember correctly that data is in the db.
Comment: The question was not about using tokens in field settings. It was about using image field tokens in general.
Answer: Using contrib module
Imagecache Token provides a list of token for image styles, which includes image width and height.

If you want to have those data of original image, you can create an image style original without adding any effect at admin/config/media/image-styles/edit/original

Now you can retrieve the image width and height with:

[node:field_image:original:width]
[node:field_image:original:height]

Downside
All images will be duplicated to the original image style folder.
Comment: It would be perfect if you could get the image data without the duplicate. But I guess this is a legit option.
Comment: @ram4nd Thanks, I think it would be the only way to do that without custom module. Do you feel comfortable on creating custom module? This module is the good starting point. I will look into it today later.