What are the advantages to DHCP server running on Windows Server 2003 R2 vs pfsense router?

Question: I am taking over responsibility for the network at a small medical practice.  I understand how the network is configured, but I want to know more about the why.
The network currently is Cisco modem -> pfsense router -> Windows Server 2003 R2
In this configuration, what are the advantages to having the DHCP server be on the windows machine?  There are only 10 clients on the network.
Answer: Assuming that you have Active Directory in place, the Windows clients would need to have the Windows server be listed as their DNS server.  The router may not be able to do this.
This is needed because Active Directory works very heavily off of DNS for finding things like domain controllers, etc within the domain.
Comment: pfSense's DHCPd can update MS DNS if you have security on the zone disabled. MS DHCPd is needed for secure updates if the clients do not support secure updates.
Answer: As a Windows Admin, I think it's just cleaner.  As mrdenny said, you can occasionally get issues where the router won't handle certain DHCP options or hand those options out in a way Windows likes.  I prefer having my DNS and DHCP handled by one of my Domain Controllers because it's just easier to troubleshoot later in my opinion.
Answer: I agree with Driftpeasant - makes life easier - one machine to look at if you get issues, and you can easily set up reservations with very specific options for unusual situtations/devices. pfSense 2.0 lets you set up DHCP options (e.g. option 66 which specifies a TFTP server) to your heart's content for all devices although I believe it is not quite as flexible when setting up reservations.
To answer mrdenny Both 1.2.3 and 2.0 let you specify your preferred DNS server for the clients. I agree with mrdenny that you want to use a Windows DNS server for this - as well as the clients registering themselves so they can be found by other clients/servers by a DNS lookup against your local windows DNS server, there will also be a heap of DNS SRV records relating to your AD envoironment that windows automatically maintains but are a PITA to set up in pfSense.
(If you do decide to use pfSense for DHCP, on the client pc's, open up properties for the NIC, check TCP/IPv4 properties, then click advanced, then go to the DNS tab, ensure the check box at the bottom that says Register this connection's addresses in DNS is ticked to ensure the clients actually do register)
Also in my experience, Windows boxes seem to take longer to get leases from some *nix DHCP servers including pfSense - I remember sometimes seeing the requests take so long windows would show the warning triangle by the NIC icon in the system tray then almost immediately afterwards sort itself out.


When selecting a bow, how can I find out what a good poundage for me would be?

Question: I currently have a 30 pound bow which is rather light for me, and I'd like to purchase a new one.  I'm guessing 45-50#, but I'm not sure.  I'm thinking 60# would probably be too heavy (trying to imagine pulling twice the weight of what I have now), but I don't know about that either.  Then again, it might be 40#.  I'm 16 years old, 5' 9", 140 lbs, and not quite in optimal physical condition (~25 pushups straight).
I'm not necessarily asking for you to give me a poundage off of those metrics, but I'd like to know what the right weight should feel like when I'm pulling a bow.  Also, does it matter if I go for a heavier bow, if I'm planning ahead for when (hopefully) I'm more physically fit?  Or should I plan to get a new bow after I "grow out" of the next one?
Answer: Guidance from huntingnet.com is:

As a rule of thumb, the shooter should be able to comfortably draw the
  bow back without straining or lifting the bow up over his head in
  order to draw it back, and hold it back for at least 60 seconds.

They also state that

Bows in the fifty to seventy pound draw weight will work just fine for
  most shooters

So if you have been used to a 30 pound bow I would suggest a 50 would be on the upper end of what you would want to move to.
Comment: +1 OK, that makes sense.  I recently talked with a rod-and-gun shop owner, and he asked me if I was using a 45# bow, so that info coupled with your post here gives me a pretty good idea of what I should be looking for.  Thanks!


Visualization of double integrals

Question: So, we just started learning double integrals in class.
$$\iint f(x,y) \mathrm{d}x \mathrm{d}y$$
Our teacher said that performing this operation within certain limits of x and y yields the volume under that function confined within these limits.
She also mentioned that when $$f(x,y)=1$$ we're finding the 2D area, again confined within limits. However, she mentioned that this is only valid when $f(x,y)=1$, and not for any other constant value the function may represent.
Now, I'm confused.
(i) Although dimensionally the integral will represent xy, why does finding the double integral not mean finding the volume of the cuboid within the limits?
(ii) If it infact means finding the area, why is it only true for $f(x,y)=1$ and not some other constant value?
Comment: A few similar questions: https://math.stackexchange.com/q/2987892/1242, https://math.stackexchange.com/q/2431781/1242, https://math.stackexchange.com/q/1311229/1242, https://math.stackexchange.com/q/3712272/1242.
Comment: Yes, that's correct.
Comment: @HansLundmark Thank you so much!!! So, according to this, if $f(x,y)=2$, I can interpret it to be the volume of a cuboid of height as $2$ units, or simply twice the area of a rectangle. Is this correct?
Answer: There are often several ways one can interpret integrals. The viewpoint in single-variable integrals as "(signed) area under the graph" is too limited, because we often have many many many other reasonable interpretations. It all depends on the actual purpose at hand.
Suppose $S\subset\Bbb{R}^2$ is some region in the plane, and $f:S\to \Bbb{R}$ is a given function; for now assume all the nice regularity that is needed, I just want to get some basic ideas across for how one can interpret the integral $\int_Sf\,dA$

Suppose $f\geq 0$ is a non-negative function. Then, we can imagine the graoh of $f$ as being a "surface lying over $S$". Then, the quantity $\int_Sf\,dA$ can be interpreted as the volume of the region bounded by the graph of $f$ and the region $S$. So, as a consequence, if we take $f=1$, we can interpret $\int_S\,dA$ as the volume of the solid with cross-section $S$, and height $1$. For example, if $S$ is the unit disk in the plane $S=\{(x,y)\in\Bbb{R}^2\,:x^2+y^2\leq 1\}$, then we can interpret $\int_S\,dA$ as the volume of the cylinder having $S$ as the cross section and having height $1$.

A more direct interpretation of $\int_S\,dA$ is as the area of the planar region $S$, because recall that the integral is approximated by the sums $\sum_{i=1}^n\text{area}(R_i)$, where $R_i\subset S$ are rectangles, so atleast in nice cases, this approximation had better yield the area of $S$ in the limit. This should be reasonable geometrically because area times a height of $1$ should be the same thing as the volume under the given region. If you really want to you can think of this as integrating a constant unit-less $1$ vs integrating $1$ meter to give the distinction of interpretation between area vs volume.

Another interpretation, again supposing $f\geq 0$, is to think of $f$ as describing the "surface mass density of $S$". So, imagine $S$ as a thin sheet of a material (like a very thin (not necessarily uniform) aluminum foil which you cut up into a certain shape), and suppose $a\in S$  is a point. Then, we can interpret $f(a)$ as the mass density at the point $a$. Recalling the relation "mass equals (surface)density times area", we thus interpret $\int_Sf\,dA$ as being the total mass of the thin sheet $S$.

Now, if we allow $f$ to take on both positive and negative values, then a physical interpretation is to think of $f$ as the electric charge density, rather than the mass density (which must be non-negative). Then, reasoning as above, we think of $\int_Sf\,dA$ as being the net charge contained in $S$.

If $f$ has some other special properties we can give it some other interpretation. For example, if $M$ is some two-dimensional surface, then often times we are able to parametrize the surface using a function $g:S\to M$ (for example, think of $M$ as the unit sphere, and $S=(0,\pi)\times (0,2\pi)$ as the domain for spherical coordinates parametrization). Then, the surgace area of $M$ can be calculated by the formula
\begin{align}
\text{area}(M)&=\int_S\underbrace{\left\lVert\frac{\partial g}{\partial u}\times \frac{\partial g}{\partial v}\right\rVert}_{:=f(u,v)}\,du\,dv
\end{align}
Don't worry about the exact formula for $f(u,v)$ here. My point is that sometimes, the thing you're integrating doesn't really have anything to do with the region $S$; rather you may be interested in the surface $M$, and $S$ and $f$ only comes up as an intermediate calculation. Concretely, we have (again don't worry about where exactly the formulas come from)
\begin{align}
\text{area of unit sphere}&=\int_{(0,\pi)\times (0,2\pi)}\sin\theta\,d\theta\,d\phi\\
&=\int_0^{\pi}\sin\theta\,d\theta\int_0^{2\pi}\,d\phi\\
&=4\pi
\end{align}
In this example, we have $f(\theta,\phi)=\sin\theta$ and $S=(0,\pi)\times (0,2\pi)$ is simply a rectangular region in the plane. Obviously, it is not very insightful to think of the integral $\int_Sf\,dA(\theta,\phi)$ as being the "mass of $S$" or as "the volume under the graph of $f$" or anything like that. The integral only comes in here as an intermediate calculation step to compute the surface area of the unit sphere

So you see, because there are so many possible interpretations of integrals, it is unwise to limit oneself to thinking only in terms of the "(signed) volume under the graph", or something like that. The integral is a very flexible tool, whose purpose is to "add up a lot of small things", and the things we're adding up then gives us the interpretation. I'm sure there are also many other possible ways of interpreting double integrals.
As a side remark: we can do the same thing with line integrals, triple integrals or really anything else. There are often many ways of viewing the same thing, and in some situations, one interpretation is more useful than another.
Comment: Interesting points about the flat alumnium sheet and net charge, both of which are rather...flat. I was going to say that volume is unitless hence that interpretation and these have units, but that isn't really true. Hooray for science!
Answer: $$\int\int f(x,y)dxdy$$
will yield the volume under the function if $f(x,y)\ge 0$ inside the region. If $f(x,y)\le0$ inside the region, it will yield the volume of the function inside the region, but with a minus sign.
So if $f(x,y)=1$, the integral will yield the volume of a base with a height of $1$, which is the same as the area (because $\text{surface area}=\text{volume}/1=\text{volume}$. If $f(x,y)=2$, then the height of the region will be $2$, and you can find the area by dividing by the integral by $2$. It can also be seen mathematically by
$$\begin{split}\text{Area}&=\frac 1 2\int\int 2dxdy\\
&=\int \int 1dxdy\end{split}$$

Visualization of double integrals


SSIS Deploying Expression variables

Question: I am planning to deploy a SSIS package on the production server using the command line prompt.
I am executing the following :
DTEXEC.exe /FILE "C:\SSISPackages\Rewards\ExcelMasterToRewardsExcel.dtsx"
           /DECRYPT ssis
           /CHECKPOINTING OFF
           /REPORTING EWCDI
           /SET "\PACKAGE.VARIABLES
[varExcelFilePath_Master]";"D:\SSIS\64bit\MIS_DownloadScheduler2012-11-29-07-00-03.xls"

The problem is that  I have another variable [varOutPutExcel] which is an expression variable which would take [varExcelFilePath_Master] and append datetime.
But How do I set this variable in the command prompt??
Comment: 1. You are not deploying... you are executing your package. 2. Expression are evaluated at the run time; you do not need to pass the value.
Answer: Pass parameters like this:
Dtexec /isserver "SSISDB\MyFolder\MyProject\MyPackage.dtsx" /server "." /parameter $Project::myparam;myvalue /parameter anotherparam(int32);12

More info here:

dtexec Utility - Parameters

For deployment , use deployment wizard by right clicking the solution if deploying to integration catalog. Dtexe.exe only executes the package, no more. If using a file store to store the solution or dtsx in a folder, supply that address to dtexec without ISServer option.
It is important to understand that expressions are computed when the package runs. But values can be passed for those expressions to use by employing parameters as shown above.

SSIS Deploying Expression variables


How to include a class by default in all nodes?

Question: How do I include this class all in all nodes by default?
snippet from my manifests/nodes.pp
class all {

  case $operatingsystem {
    debian, ubuntu: {
      include hosts
      include ssh
    }
    default: {
      err("OS NOT supported")
    }
  }
}

node default {
  include all
}

node 'dobby' {
  include all ## <<
  include apache
  include logrotate
}

Answer:  node 'dobby' inherits default  {.... }

will inherit all definitions from the node default.


Dificuldade em fazer RewriteEngine funcionar

Question: Preciso usar esse comando abaixo. No meu servidor funciona bem, mas quando fui instalar em outro essa mesma linha da erro em todo o site.
Preciso disso porque o comando ira vir de forma diferente e quero mascarar a url original do sistema. Tipo:
www.outrosite.com/aceita/12315544 ou www.outrosite.com/recusa/12315544
RewriteEngine On
RewriteRule ^([^/]*)/([^/]*)$ /transportadora/cotacoesEnviaPropostaAceitarRecusar.php?acao=$1&id=$2 [L]

Comment: Experimenta isto http://pastebin.com/BNhp6Ts5
Comment: Você verificou se o modo rewrite do apache está ativo? Qual é o erro? coloca o print do erro na pergunta para ajudar a responder.
Answer: Primeiro verifique se não é uma falha sua no uso do .htaccess, por exemplo, será que o seu servidor usa Apache mesmo ou usa outro como Ngnix.
Verifique também se esta na pasta correta ou se não existe alguma outra pasta.
Não acredito que você tenha esquecido de ligar o modulo, pois se fosse isto teria ocorrido 500 internal error server.
Tem uma coisa que parece errada no seu rewrite:
Você usou /transportadora... quando o correto seria transportadora..., ao menos este me parece o mais correto:
RewriteEngine On
RewriteRule ^([^/]*)/([^/]*)$ transportadora/cotacoesEnviaPropostaAceitarRecusar.php?acao=$1&id=$2 [L]

No entanto o seu rewrite esta aceitando qualquer ação e qualquer id, o que é estranho, talvez deve-se tentar isto:
RewriteEngine On
RewriteRule ^(recusa|aceita)/(\d+)$ transportadora/cotacoesEnviaPropostaAceitarRecusar.php?acao=$1&id=$2 [L]

O (recusa|aceita) só aceitará as ações pré-definidas.
O \d+ só aceitar numeros.


How can you process a CSV from Azure Blob Storage as a stream in Python

Question: It is simple to get a StorageStreamDownloader using the azure.storage.blob package:
from azure.storage.blob import BlobServiceClient

blob_service_client = BlobServiceClient.from_connection_string("my azure connection string")
container_client = blob_service_client.get_container_client("my azure container name")
blob_client = container_client.get_blob_client("my azure file name")
storage_stream_downloader = blob_client.download_blob()

and it is simple to process a file-like object, or more specifically, I think, a string-returning iterator (or the file path of the object) in the csv package:
import csv
from io import StringIO

csv_string = """col1, col2
a,b
c,d"""
with StringIO(csv_string) as csv_file:
  for row in csv.reader(csv_file):
    print(row) # or rather whatever I actually want to do on a row by row basis, e.g. ascertain that the file contains a row that meets a certain condition

What I'm struggling with is getting the streaming data from my StorageStreamDownloader into csv.reader() in such a way that I can process each line as it arrives rather than waiting for the whole file to download.
The Microsoft docs strike me as a little underwritten by their standards (the chunks() method has no annotation?) but I see there is a readinto() method for reading into a stream.  I have tried reading into a BytesIO stream but cannot work out how to get the data out into csv.reader() without just outputting the buffer to a new file and reading that file.  This all strikes me as a thing that should be doable but I'm probably missing something obvious conceptually, perhaps to do with itertools or asyncio, or perhaps I'm just using the wrong csv tool for my needs?
Comment: You can use pandas to read CSV file with BytesIO.
Comment: That's really helpful, thanks Jim.  I was trying to stick to the specialised csv library as I'm not doing any actual data point analysis but if pandas handles it then I'll give that a go
Answer: Based on a comment by Jim Xu:
stream = blob_client.download_blob()
with io.BytesIO() as buf:
  stream.readinto(buf)

  # needed to reset the buffer, otherwise, panda won't read from the start
  buf.seek(0)

  data = pd.read_csv(buf)

or
csv_content = blob_client.download_blob().readall()
data = pd.read_csv(io.BytesIO(csv_content ))

Answer: If you want to read csv file on row by one row, you can use the method pd.read_csv(filename, chunksize=1). For more details, please refer to here and here
For example (I use pandas1.2.1)
with pd.read_csv(content, chunksize=1) as reader:

    for chunk in reader:
        print(chunk)
        print('---------------')

Besides, if you want to use the method chunks(), we need to set max_chunk_get_size and max_single_get_size to the same value when we create BlobClient. For more details, please refer to here and here
For example
from azure.storage.blob import BlobClient

key = '<account_key>'

blob_client = BlobClient(account_url='https://andyprivate.blob.core.windows.net',
                         container_name='input',
                         blob_name='cities.csv',
                         credential=key,
                         max_chunk_get_size=1024,
                         max_single_get_size=1024)
stream = blob_client.download_blob()

for chunk in stream.chunks():
    print(len(chunk))

Comment: @ChristopherAlcock in the first sample, you can use the method `readinto()` to read into `BytesIO` stream. Then use pandas to process the stream.
Comment: @ChristopherAlcock please try to use the following code `stream = blob_client.download_blob()

with BytesIO() as buf :
   stream.readinto(buf)
   pandas.read_csv(buf)`
Comment: Thanks very much indeed. Will try and get it implemented today and accept answer
Comment: Thanks again for this but I still haven't managed to get this working together.  `content` in your first example seems to be effectively the same as `csv_file` in my question, and I still don't see how I stream azure files into it?  The chunk params in the second example seem very helpful tho, for optimizing once I have the stream processing actually working
Comment: Hi Jim,  I've finally worked out what was going wrong for me here.  The pandas read_csv unsurprisingly returns a pandas dataframe, which behaves very differently to the csv reader, so I had to change all my processing code too, which I hadn't foolishly hadn't expected. Thanks for your help.
Comment: I've worked on this further and whilst if I put my csv data into a BytesIO buffer csv_string like so `buffer = BytesIO(csv_string.encode('utf-8'))`, I can then process it with `pandas.read_csv()`.  However if I get the data from Azure in the way suggested and read that into a buffer, such that calling `.getvalue()` is identical to the buffer from string, pandas cannot process the data: `pandas.errors.EmptyDataError('No columns to parse from file')`.  I am tempted to believe that what I'm trying to do isn't possible
Comment: Hi Jim,  Thanks again for trying, but this is essentially what I was already trying, and despite reading in a very simple valid csv, it returns `EmptyDataError: No columns to parse from file`
Comment: If I do a `print(buf1.getvalue())` instead of `read_csv`, i get  `b'Col1,Col2,Col3\nval1,val2,val3\nval4,val5,val6\nval7,val8,val9'`, which as far as I can see is totally acceptable csv data


SSL_CLIENT_CERT_CHAIN not being passed to backend server

Question: I have client certificate configured and working in Apache. I want to pass the PEM-encoded X.509 certificates of the client to the backend server.
I tried with the SSLOptions +ExportCertData. This does nothing at all, while the documentation states it should add SSL_SERVER_CERT, SSL_CLIENT_CERT and SSL_CLIENT_CERT_CHAINn (with n = 0,1,2,..) as headers. Any ideas why this option is not working?
I then tried setting the headers myself using RequestHeader. This works fine for all variables except SSL_CLIENT_CERT_CHAIN. It shows null in the header. Any ideas why the certificate chain is not being filled?
This is my first Apache configuration:
<VirtualHost 192.168.56.100:443>
    ServerName www.test.org
    ServerAdmin webmaster@localhost

    DocumentRoot /var/www

    ErrorLog ${APACHE_LOG_DIR}/error.log
    LogLevel warn

    CustomLog ${APACHE_LOG_DIR}/ssl_access.log combined

    SSLEngine on
    SSLProxyEngine on

    SSLCertificateFile     /etc/apache2/ssl/certs/www.test.org.crt
    SSLCertificateKeyFile  /etc/apache2/ssl/private/www.test.org.key
    SSLCACertificateFile   /etc/apache2/ssl/ca/ca.crt

    <Proxy *>
        AddDefaultCharset Off
        Order deny,allow
        Allow from all
    </Proxy>

    <Location /carbon>
        ProxyPass          http://www.test.org:9763/carbon
        ProxyPassReverse   http://www.test.org:9763/carbon
    </Location>

    <Location /services/GbTestProxy>
        SSLVerifyClient require
        SSLVerifyDepth  5
        SSLOptions +ExportCertData

        ProxyPass          http://www.test.org:8888/services/GbTestProxy
        ProxyPassReverse   http://www.test.org:8888/services/GbTestProxy
    </Location>
</VirtualHost>

This is my second Apache configuration:
<VirtualHost 192.168.56.100:443>
    ServerName www.test.org
    ServerAdmin webmaster@localhost

    DocumentRoot /var/www

    ErrorLog ${APACHE_LOG_DIR}/error.log
    LogLevel warn

    CustomLog ${APACHE_LOG_DIR}/ssl_access.log combined

    SSLEngine on
    SSLProxyEngine on

    SSLCertificateFile     /etc/apache2/ssl/certs/www.test.org.crt
    SSLCertificateKeyFile  /etc/apache2/ssl/private/www.test.org.key
    SSLCACertificateFile   /etc/apache2/ssl/ca/ca.crt

    <Proxy *>
        AddDefaultCharset Off
        Order deny,allow
        Allow from all
    </Proxy>

    <Location /carbon>
        ProxyPass          http://www.test.org:9763/carbon
        ProxyPassReverse   http://www.test.org:9763/carbon
    </Location>

    <Location /services/GbTestProxy>
        SSLVerifyClient require
        SSLVerifyDepth  5
        SSLOptions +ExportCertData

        RequestHeader set SSL_CLIENT_S_DN "%{SSL_CLIENT_S_DN}s"
        RequestHeader set SSL_CLIENT_I_DN "%{SSL_CLIENT_I_DN}s"
        RequestHeader set SSL_CLIENT_S_DN_CN "%{SSL_SERVER_S_DN_CN}s"
        RequestHeader set SSL_SERVER_S_DN_OU "%{SSL_SERVER_S_DN_OU}s"
        RequestHeader set SSL_CLIENT_CERT "%{SSL_CLIENT_CERT}s"
        RequestHeader set SSL_CLIENT_CERT_CHAIN_0 "%{SSL_CLIENT_CERT_CHAIN_0}s"
        RequestHeader set SSL_CLIENT_CERT_CHAIN_1 "%{SSL_CLIENT_CERT_CHAIN_1}s"
        RequestHeader set SSL_CLIENT_VERIFY "%{SSL_CLIENT_VERIFY}s"

        ProxyPass          http://www.test.org:8888/services/GbTestProxy
        ProxyPassReverse   http://www.test.org:8888/services/GbTestProxy
    </Location>
</VirtualHost>

Hope someone can help.
Regards, nidkil
Answer: This is an old question, but I'll answer it in case someone else stumbles upon it like I did.
The issuer certificate is actually at position 0 in the chain from Apache, not 1.  To get the issuer certificate you want:
RequestHeader set SSL_CLIENT_CERT_CHAIN_0 "%{{SSL_CLIENT_CERT_CHAIN_0}}s"

Answer: SSLOptions +ExportCertData doesn't add headers to a proxied request, it adds environment variables -- the environment variables that you're trying to add to the headers in your second config (but they aren't in the environment then, since you dropped the SSLOptions config).
You'll need both the RequestHeader set config as well as SSLOptions +ExportCertData.
Comment: Hi shane, No there is no intermediate certificate ... Are you saying that only intermediate certificates are shown with the SSL_CLIENT_CERT_CHAIN_n? How do you get the root CA then?
Comment: Ahh, you're missing an underscore - change `%{SSL_CLIENT_CERT_CHAIN1}s` to `%{SSL_CLIENT_CERT_CHAIN_1}s`.
Comment: Shane, thx for your quick response. When I added the SSLOptions to the second example, the certificate chain is unfortunately still not added. Any other suggestions? I have updated the example in my question to reflect your suggestion. Quick question out of curiosity, why does the client certificate get populated without setting the SSLOptions?
Comment: Hi Shane, Sharp eye! The underscore was missing. Corrected it and it still doesn't work :-( This is driving me insane. Anymore ideas? Updated the the example to reflect the correction.
Comment: Huh.  Is there an intermediate cert for it to include as a part of the chain, or is it just the client cert straight back to the configured root?


Java File processing. Basic. Error in text output

Question: What I have to do is take a file which only has text in it and format it properly. Seems pretty easy in theory but I've run into a problem I'm not sure how to fix. Here is my code. TAB_SIZE is a final int set to 4.
    public static void justifyJava( String inputFileName,
                                    String outputFileName,
                                    int tabSize ) throws FileNotFoundException {

    Scanner input = new Scanner(new File(inputFileName));
    String str = "hi";
    int tabCount = 0;
    while (input.hasNext()){
        str = input.next();
        System.out.print(str + " ");
        if (str.equals("{")) {
           tabCount++;
           System.out.println();
           for (int i = 0; i < TAB_SIZE * tabCount; i++){
              System.out.print(" ");
           }
        } else if(str.equals(");")){
              tabCount--;
              System.out.println();
              for (int i = 0; i < TAB_SIZE * tabCount; i++){
                 System.out.print(" ");
              }
        } else if(str.equals("}")) {
              tabCount--;
              System.out.println();
              for (int i = 0; i < TAB_SIZE * tabCount; i++){
                 System.out.print(" ");
              }
        }
    }
}

So this code works great for a couple of the files I have to process but it gets stuck when there are 2 for loops in a row.
class Test3 {
    public static void main( String[ ] args ) {
        for( int i = 1; i < 10; i ++ ) {
            System.out.println( "Hello World!" );
        }
    for( int i = 1; i < 10; i ++ ) {
        for( int j = 1; j < 10; j ++ ) {
            for( int k = 1; k < 10; k ++ ) {
                System.out.println( "Hello World!" );
            }
        }
    }
if( 3 < 5 ) {
     System.out.println( "Hello World!" );
}
else if ( 4 < 5 ) {
System.out.println( "Hello World!" );
if( 5 > 3 ) {
System.out.println( "Hello World!" );
}
}
}
}

I understand that the problem is that after the "}" it is reducing the number of spaces but how can I get it to check if the next token is "for(" without the scanner actually moving to "for(" so it will still print when I run through again? Would I have to build a new scanner or reorganize code? Any help is appreciated.
Answer: Modified justifyJava() method to format properly and tried it with the Test3 class which is working properly, let me know if you find any difficulty:
public static void justifyJava(String inputFileName, String outputFileName,
        int tabSize) throws FileNotFoundException {

    Scanner input = new Scanner(new File(inputFileName));
    String str = "hi";
    int tabCount = 0;
    String prevToken = "";

    while (input.hasNext()) {
        str = input.next();
        if(str.equals("{") || str.equals(");")){
            System.out.print(str + " ");
            System.out.println();
        }
        if(prevToken.equals(");") && !str.equals("}")){
            for (int i = 0; i < TAB_SIZE * tabCount; i++) {
                System.out.print(" ");
            }
        }else if (str.equals("{")) {
            tabCount++;
            for (int i = 0; i < TAB_SIZE * tabCount; i++) {
                System.out.print(" ");
            }
        } else if (str.equals("}")) {
            tabCount--;
            if(!");".equals(prevToken)){
                System.out.println();
            }
            for (int i = 0; i < TAB_SIZE * tabCount; i++) {
                System.out.print(" ");
            }
            System.out.print(str + " ");
        }
        if(!(str.equals("{") || str.equals(");") || str.equals("}"))){
            System.out.print(str + " ");
        }
        if((str!= null && !"".equals(str.trim()))){
            prevToken = str;
        }
    }
}


Understanding the returned value of `decode-time` (elisp)

Question: After reading the documentation of encode-time and decode-time I'm not understanding how they work.
My trouble from comes from the fact that encode-time returns two values, whereas I'm expecting only one (the number of seconds since the UNIX epoch). What do these two values mean exactly?
ELISP> (encode-time 0 0 0 1 1 1970 t)
(0 0)
ELISP> (encode-time 0 0 0 1 1 1971 t)
(481 13184)

I get even more confused because these three calls work, but I don't understand how to interpret the argument in the first two cases:
;; Ok this is what I expect from the documentation
ELISP> (decode-time
        (encode-time 0 0 0 1 1 1971 t))
(0 0 0 1 1 1971 5 nil 0)

;; This is also what I expected, given it's the same than above, but I don't understand the meaning of the arguments
ELISP> (decode-time '(481 13184))
(0 0 0 1 1 1971 5 nil 0)

;; I kind of understand the following: here 481  is considered the seconds since UNIX epoch,
;; and 13184 is the difference in seconds from UTC.
;; The returned value, is the date (UNIX epoch + 481 seconds)
;; expressed in a timezone 13184 seconds ahead of UTC (45 47 3 1 1 1970 = 13665 seconds
;; and 13665−13184 = 481)
ELISP> (decode-time 481 13184)
(45 47 3 1 1 1970 4 nil 13184)

Note that for all the examples above I have set (set-time-zone-rule t) to avoid having to deal with timezones.
Answer: (481 131184) represents the number of seconds as (HIGH LOW) where HIGH is the upper bits and LOW is the lower 16 bits.  I.e. the real number of seconds is
(+ (* 481 65536) 13184) == 31536000

Answer: Looking at the documentation:

(decode-time &optional TIME ZONE)
Decode a time value as (SEC MINUTE HOUR DAY MONTH YEAR DOW DST UTCOFF).
  The optional TIME should be a list of (HIGH LOW . IGNORED),
  as from 'current-time' and 'file-attributes', or nil to use the
  current time.  It can also be a single integer number of seconds since
  the epoch.  The obsolete form (HIGH . LOW) is also still accepted.

So we can see that the expected format is a list with the values "HIGH" and "LOW" (and maybe some extra information).  Following that direction to current-time gives us further explanation:

(current-time)
Return the current time, as the number of seconds since 1970-01-01 00:00:00.
  The time is returned as a list of integers (HIGH LOW USEC PSEC).
  HIGH has the most significant bits of the seconds, while LOW has the
  least significant 16 bits.  USEC and PSEC are the microsecond and
  picosecond counts.

Why does Emacs use this seemingly-complicated format?  Undoubtedly the answer is simply that Emacs is old, and it needed to work with systems where only 16-bit integers were available.
Looking to the manual, M-x elisp-index-search for current-time takes us to (elisp)Time of Day:

Most of these functions represent time as a list of four integers
  '(SEC-HIGH SEC-LOW MICROSEC PICOSEC)'.  This represents the number of
  seconds from the "epoch" (January 1, 1970 at 00:00 UTC), using the
  formula: HIGH * 2**16 + LOW + MICRO * 10**−6 + PICO * 10**−12.  The
  return value of 'current-time' represents time using this form, as do
  the timestamps in the return values of other functions such as
  'file-attributes' (*note Definition of file-attributes::).  In some
  cases, functions may return two- or three-element lists, with omitted
  MICROSEC and PICOSEC components defaulting to zero.
Function arguments, e.g., the TIME argument to 'current-time-string',
  accept a more-general "time value" format, which can be a list of
  integers as above, or a single number for seconds since the epoch, or
  'nil' for the current time.  You can convert a time value into a
  human-readable string using 'current-time-string' and
  'format-time-string', into a list of integers using 'seconds-to-time',
  and into other forms using 'decode-time' and 'float-time'.  These
  functions are described in the following sections.

Hence you can, for example, pass a single 32-bit Unix timestamp integer to decode-time
(decode-time 1554670400)
=> (20 53 8 8 4 2019 1 nil 43200)

You can also use format-time-string to obtain a single integer value:
(string-to-number (format-time-string "%s" (current-time)))


Batch script to duplicate a file multiple times using filenames from a list

Question: I'm Using a batchscript to duplicate a couple of PDFs and output them with different filenames each.
So far, What I have done is
SET Template=C:\Temp\template.pdf
copy /y %Template% .\%Class%\Apples_fruits.pdf
copy /y %Template% .\%Class%\Oranges_fruits.pdf
copy /y %Template% .\%Class%\Grapes_fruits.pdf
copy /y %Template% .\%Class%\Bananas_fruits.pdf
copy /y %Template% .\%Class%\Strawberry_fruits.pdf

I want to do this without having to type the copy /y line each time. I'd like to have a list of 'fruits' in a .txt or .xlsx file and have batch use the items in the list as filenames.
For example:
Apples_fruits.pdf
Oranges_fruits.pdf
Grapes_fruits.pdf
Bananas_fruits.pdf
Strawberry_fruits.pdf

Comment: you need a [for /f](https://ss64.com/nt/for_f.html) loop to iterate over a textfile.What you want to do is basically a one-liner.
Comment: Other than not having the variable `class` defined, I don't see anything wrong with your code.  So what exactly is your question?
Comment: You mention .txt and .xlsx extensions. I hope you are not changing the file extension when you are copying.
Comment: I'm sorry I should have been more clear.

I want to do this without having to type the copy /y line each time.

I'd like to have a list of 'fruits' in a .txt or .xlsx file and have batch use the items in the list as filenames.
Answer: Windows 10 64-bit.
The batch file and fruit.txt have to be in the same directory.
SET Template=%temp%\template.pdf
SET Class=Class
IF /i not exist %Class% md %Class%
FOR /f "delims=" %%g in ('type fruit.txt') do COPY /y %Template% .\%Class%\%%g_fruits.pdf

fruit.txt:
Apples
Oranges
Grapes
Bananas
Strawberry


For which groups $G$, the group ring $\mathbb{Z}G$ is Artinian?

Question: By Showing the group ring $\mathbb ZG$ is not Artinian. , the group ring $\mathbb{Z}G$ is not Artinian when $G$ is finite.
My questions is that : For which groups $G$, the group ring $\mathbb{Z}G$ is Artinian?
Thank in advance.
Comment: To make the question more interesting, either replace $\mathbb{Z}$ with a field or some other Artinian ring or replace "Artinian" with "Noetherian".
Answer: You can argue as in the accepted answer of the question you have linked: $\mathbb{Z}$ is the image of the augmentation map, but not artinian. Hence, $\mathbb{Z}G$ is never artinian.


What is the probablity of January having 5 sundays. Similarly for the other months

Question: I'm trying to find out what is the probability that a randomly chosen January will have 5 Sundays. Of course the answer for 4 Sundays would be 1. I presume that 31 day months will have a higher probability of having 5 then 30 day months. Of course, February in a non-leap year has 0 probablity of having 5 sundays and in a leap year will have 5 only if 1st Feb is a Sunday. Therefore in a leap year P(Feb,5) = 1/7 and over a 400 year time period the P(Feb,5) will be 99/2800. I presume all 31 day months will have the same probablity which should be higher than 30 day months and in turn will be higher than 99/2800. I've worked out P(31d month,5) will be 223/343 and P(30d month,5) is 19/49. Is this right?
Comment: Is there a connection between what day the 1st of January is, and how many Sundays there are that January?
Comment: I think it is important to note that number $7$ has [GCD](http://en.wikipedia.org/wiki/Greatest_common_divisor) 1 both with 355 and 356, so that January the 1st has the same probability of being any of the weekdays.
Comment: Note also that the rules for leap years affect the distribution here - so it depends whether you are talking about a particular century or "the long term". And always assuming the calendar stays the same - it has changed before now.
Comment: @AndreasT In 400 years, there are $146,097 = 20,871\cdot 7$ days with current leap year rules, so some weekdays will be more common than others (I don't know exactly which ones, though, but I remember someone calculating that the 13th will fall on a friday once or twice more than on any other day during that period.
Comment: @Arthur sorry, my bad, Mark Bennet's answer made it clear. I'm still a bit puzzled though :)
Answer: You have to be a little careful calculating this. With the leap year rules the calendar repeats after 400 years (the number of days in 400 years is divisible by $7$). In any period of 400 years using the current calendar, 1 January will fall on:
Sunday 58 times
Monday 56 times
Tuesday 58 times
Wednesday 57 times
Thursday 57 times
Friday 58 times
Saturday 56 times
Answer: January will have 5 Sundays if January 1 falls on Friday,  Saturday or Sunday. Therefore the probability is 3/7. You can apply the same logic for other months.
Answer: now it is sure that the month of jan will have 4 sundays as you said. so 31-28=3 days remaining
the remaining 3 days can have different combination of days
sun-mon-tue
mon-tue-wed
tue-wed-thu
wed-thu-fri
thu-fri-sat
fri-sat-sun
sat-sun-mon
so there are total 7 combinations
and 3 of these combinations contains sunday
so probability of having 5 sundays in the month of january is P(E)= 3/7
Answer: 3 by 7 is the perfect answer.as there are seven days in a week and there are 3 possible outcomes
Possible outcomes ÷ total number of favourable outcomes.
Comment: Welcome to this site! The question you just answered is rather old and has perfectly good answers already, to which your post doesn't seem to add much.  More value can be added to the site by answering unanswered questions, or posting answers which significantly add to the existing ones.


Generate foreman-installer-answers.yaml

Question: Is there a way to generate a foreman-installer-answers.yaml file from a current setup?  After initially installing Foreman I changed a couple of things in the web interface and also used theforeman/puppet and puppetlabs/puppetdb to customize my setup (including puppet.conf).  I ask this for two reasons:

I am preping for upgrading to the next version of Foreman
I want to be able to reproduce this setup in Vagrant or on another server

Any help would be appreciated!
Answer: Not really if you changed things in the web UI - if you'd re-run the installer with updated arguments then the file would have been updated.
If you're using theforeman/puppet, theforeman/foreman, theforeman/foreman_proxy, then you could create the file just by copying the parameters you're passing to those modules.
Comment: Part of the problem is that since my mods were done via the web UI I am not certain what flags I need to pass. I'd love to define all this so that I could enforce it via modules provided by theforeman... just not figured out how yet.

Generate foreman-installer-answers.yaml


Capacitor Android pipeline building but no longer working

Question: I had a working React app released for Android and iOS via Capacitor. But now with a new version of my app, builds were not working with the Pixel 4 API 29 virtual device I used previously. Retrying with a Pixel 2 API 28 builds complete and the app opens, but now Mapbox is no longer loading and that is the core of my app. I updated to Android Studio 4.2.1 and have the following as dev dependencies in my package.json:
"@capacitor/android": "^3.0.2",
"@capacitor/cli": "^3.0.2",
"@capacitor/core": "^3.0.2",
"capacitor-resources": "^2.0.5",
"cordova-res": "^0.15.3"

Small elements of my app are accessing the web, so it doesn't seem to be an internet access issue. The main changes I've made in this version are upgrading to Mapbox 2.3.0 and making basic use of cookies for user settings, but not for ad tracking. But I've reverted both of these changes and the problem is persisting so it doesn't seem to be because of the new Mapbox version or because the introduction of cookies.
Getting errors like this where the last letter of the app name is missing for some reason:
E/o.ionic.ecorat: Invalid ID 0x00000000.
Invalid ID 0x00000000.
E/o.ionic.ecorat: Invalid ID 0x00000000.

Also errors like this:
E/cr_VariationsUtils: Failed reading seed file "/data/user/0/io.ionic.ecorate/app_webview/variations_seed": /data/user/0/io.ionic.ecorate/app_webview/variations_seed (No such file or directory)

Do errors like this mean that the app isn't detecting that it's meant for prod?
E/Capacitor/Console: File: http://localhost/static/js/2.9b5092bb.chunk.js - Line 2 - Msg: Error: Failed to initialize WebGL
E/Capacitor/Console: File: http://localhost/static/js/2.9b5092bb.chunk.js - Line 2 - Msg: Uncaught (in promise) Error: Failed to initialize WebGL.

I use ternary operators that start like this:
const url = process.env.NODE_ENV === 'production' ?

to decide whether to go to the real website or use localhost.
Should I go back to a more stable version of capacitor?
Answer: There are 3 things I can suggest which worked for me..

Check the devtool and inspect the emulator. if you see a error something like this

Failed to load resource: net::ERR_CONTENT_LENGTH_MISMATCH

Then you can use npx capacitor run which should solve the issue, this is a quick fix though.

Replace your dev-flow and start using npx instead of ionic XXXX commands.

If you wish to update the deps and dev-deps in that case, based on package.json you have shared in your question you are missing a few plugins.
if you were to create a new ionic app using ionic start then the package.json will look something like this [ignore the vue deps]

 "dependencies": {
    "@capacitor/android": "3.0.2",
    "@capacitor/app": "1.0.2",
    "@capacitor/core": "3.0.2",
    "@capacitor/haptics": "1.0.2",
    "@capacitor/keyboard": "1.0.2",
    "@capacitor/status-bar": "1.0.2",
    "@ionic/vue": "^5.4.0",
    "@ionic/vue-router": "^5.4.0",
    "core-js": "^3.6.5",
    "vue": "^3.0.0-0",
    "vue-router": "^4.0.0-0"
  }

So, you will need to manually install the package apart from @capacitor/android & @capacitor/core I believe these packages that are de-coupled packages that makes capacitor lighter than the prev version and need to be manually installed.
After that you need to build using ionic build then use ionic open to open the IDE and sync the project with Gradle for the android app. Once this is done you can use ionic capacitor run --livereload --external to open the emulator and the dev server with live-reload..


How to know the shape of trajectories of Prey Predator Model and existence of orbit

Question: Consider the Prey Predator Model,
$$
\begin{align}
\frac{du}{dt}&=(a_1-b_1 v)u,\\
\frac{dv}{dt}&=(-a_2+b_2 u)v\\
u(0)&=u_{10},v(0)=v_{20}
\end{align}\tag 1
$$
Although the model $(1)$ looks simple, a complete analytic solution of these equations are
not possible but for every $a_1, a_2, b_1, b_2, u_{10}, v_{20}$. By variable separation,
$$
\begin{align}
\frac{du}{dv}&=\frac{(a_1-b_1 v)u}{(-a_2+b_2 u)v}\\
\left(\frac{u}{u_{10}}\right)^{-a_2}e^{b_2(u-u_{10})}&=\left(\frac{v}{v_{20}}\right)^{a_1}e^{-b_1(v-v_{20})} \quad\textrm{ Integrating from 0 to t}\\
e^{b_2u+b_1v}&=\lambda v^{a_1}u^{a_2} \quad\text{ Where }\lambda=\frac{v_{20}^{-a_1}e^{b_1v_{20}}}{v_{10}^{a_2}e^{-b_2u_{10}}}\tag 2
\end{align}
$$

Both the $u$ and $v$ axes are orbits of $(1)$ and the orbits are the family of curves defined by $(2)$ and these curves are closed. This implies that each solution $u(t)$ and $v(t)$ of $(1)$ which starts in the first quadrant $u>0,v>0$ at time $t=t_0$ will remain there for all future time $t\geq t_0$.

I didn't understand this paragraph. How they said about orbits and closed without any justification. Especially, "each trajectory is bounded closed curve". This system has two equilibrium points. The zero equilibrium point $(0,0)$ and the positive equilibrium point $(a_2/b_2,a_1/b_1)$. In fact, I couldn't find any way to conclude this.

How could I get some idea of the shapes of the trajectories?
How could I know there exist a orbit?

We have recently introduced with population Dynamics and have only lecture notes to follow. That's why so many unclear paragraph need to resolve before exam :)
Any help will be appreciated. TIA
Comment: This is easier to treat in the logarithmic version, as it is simpler to explore the convexity of linear and convex terms in a sum than in a product.
Comment: Then $b_2u+b_1v=\log\lambda+a_1\log v+a_2\log u$, still I am able to drag something @LutzLehmann Actually, we haven't a clear explanation or a dummy example where these were clearly illustrate or written. It will be a great help if you redirect me something like that. Thanks for your response
Answer: The terms $b_1v-a_2\log v$ and $b_2u-a_2\log u$ in the "logarithmic" first integral are both convex functions with a minimum $m_v$ and $m_u$ and going to $+\infty$ moving towards $0$ and $\infty$. If the sum of both is equal to some constant $C$, then we know that the first term is bounded above by $C-m_u$ and the second by $C-m_v$. Both bounds give a finite interval where they are valid. This means that the level sets have to consist of closed curves.
A change of direction requires a stationary point, which do not exist outside the one equilibrium point at the center/minimum. So the level curves are followed in only one orientation.
As the first integral is also jointly convex as a function of both variables, all level sets are convex, so the level curves all have only one component.
Comment: very neat answer. Sorry but in the second line **"...in the "logarithmic" first integral are both convex functions with a minimum $m_v$ and $m_u$ and going to $+\infty$ moving towards $0$ and $\infty$"**, I didn't get the part **''going to $+\infty$ moving towards $0$ and $\infty$"**. Thanks again for your response @LutzLehman
Comment: $x$, with positive coefficient, goes from 0 to infinity on the positive half-axis. $-\log x$ goes from infinity to  minus infinity, but falls in the trend infinitely slower than $x$ raises. In the sum you get a fall from infinity to a minimum and then a raise to infinity again.


O que significa na prática o urlencoded do Expressjs?

Question: Analisando um código construído sobre a plataforma Nodejs, acabei me deparando com a instrução express.urlencoded({ extended: false }), para tentar compreender a mesma, acabei recorrendo à documentação do Expressjs, entretanto não consegui compreender o que está significa, faz e qual sua importância no código.
Ficarei grato caso alguém possa responder as dúvidas levantadas no texto acima. Bem como comentar a relevância do { extended: false }
Answer: Boa noite.
A opção "extended" diz para o express qual biblioteca ele deve utilizar para fazer o parsing do conteúdo das requisições que ele recebe.
Quando extended : true vai utilizar a biblioteca qs e quando for false ele vai utilizar a biblioteca querystring.
A diferença entre elas é que a biblioteca qs permite o aninhamento de objetos (nested objects), que é praticamente como o JSON trabalha:
// {"animal":{"tipo":"cachorro","raca":"vira-lata","idade":3}}

E a biblioteca querystring não suporta nested objects.
Fonte: https://github.com/expressjs/body-parser#bodyparserurlencodedoptions
Comment: na verdade o middleware é o body-parser, você instala ele como modulo do express para dar a habilidade ao express de analisar o conteúdo das solicitações antes de fazermos alguma manipulação. (em poucas palavras ele deixa o conteúdo do body das requisições tudo bonitinho pra gente trabalhar mais fácil esses dados)
e o urlencoded é um método desse middleware que pode receber parâmetros, como o extended que falamos, outros parâmetros que ele aceita vc encontra ali no link que deixei.
Comment: Compreendi, e qual o significado de `express.urlencoded`? É um middleware para lidar com parâmetros na URL?
Comment: @MuriloPortugal você explicou bastante sobre o parâmetro `extended` mas o que exatamente faz o `urlencoded` ? Eu sei que o `express.json()` é um parser das informações vindas de uma requisção post mas e o `urlencoded` ? Ele seria para fazer um parser de parâmetros passados na URL como por exemplo "http://site.com/name=lucas" ?
Comment: @JeanExtreme002 o `urlencoded` é um parser das informações vindas no body da request. Veja na [documentação](http://expressjs.com/pt-br/api.html#express.urlencoded)


Breed won't appear on interface - Netlogo

Question: working on a project for varsity here and we're working in Netlogo. Basically i have a function that spawns medkits every 15 ticks, yet they don't appear on the screen. The code is basically as follows:
breed[kits kit]
kits-own [qtEner]

to Go
spawn-kits
end

to spawn-kits
  if (remainder ticks intervalo) = 0
  [
    create-kits 1
    [
      set nrg qtEner
      set shape "medkit"
      set size 1.5
      set heading 0
      setxy random-xcor random-ycor
      output-type "Created"
    ]
  ]
end

Would appreciate some feedback. Thanks a million.
Answer: What is your setup procedure? Do you have a tick somewhere to increment your counter?
Also, I think you may want set qtEner nrg if you want the kits to have their kits-own variable independently set.
This works for me:
breed[kits kit]
kits-own [qtEner]

to setup
  ca
  reset-ticks
end

to Go
  spawn-kits
  tick
end

to spawn-kits
  if (remainder ticks 10) = 0
  [
    create-kits 1
    [
      set qtEner 5
      set shape "circle"
      set size 1.5
      set heading 0
      setxy random-xcor random-ycor
      print "Created"
    ]
  ]
end


Upload new item (node gallery) link not showing with a user of different permission - Drupal 7

Question: I created a new content type named "Home" which is connected to node gallery. I created a new role named "Home only" and gave permission. When I logged in as a user with role of Home only, I am not able to get the "Upload new item" link. Did I miss any permission. Please give me a solution.
I gave all "Home" Node level permission, File Entity permission, Filter permission,View the administration theme permission, Use the administration pages and help permission.
Please note: I am getting the "Upload new item" link when I logged as administrator. Also plupload is using for the bulk upload.

When I logged as "Home only" level user, I getting all the links as in the above image except "Upload new items"
Answer: Now it worked. Previously its was beta version of node gallery. Now I changed it into Node gallery-7.x-1.0. In the permission tab i had checked "Node Gallery API". In the case of beta version of node gallery these was not showing.


How can I set the energy settings for the Radioactivity module?

Question: I saw in this screencast (from 4m 20s) that a lot of cool features were available to set the energy settings in Drupal 6. One could for example give specific scores when nodes were viewed or evaluated with Fivestar.
Is this possible in Drupal 7 too? I can't find any documentation about it...
Comment: Aren't they applied by Rules in Drupal 7? Or maybe on the field settings (you attach a Radioactivity field to an entity if I remember rightly)
Comment: @Clive: One can indeed add some settings to a Radioactivity field, but these ones don't cover what I'm looking for. Should I really add a rule for every energy setting? Strange evolution from the module, regarding easy usability...
Answer: All those cool features are still there, you just need to set up a "Decay profile". You can do this at /admin/structure/radioactivity.
Once you've got the profile setup (with the "Advanced" method by the sounds of what you're looking for), you can edit the Radioactivity field on the entity, and choose that profile. When the entity is viewed, the tracking will kick in automatically.
To respond to events such as fivestar ratings, you need to use the Rules module as everything's been decoupled for flexbility.
Comment: @Jeroen I recorded a [screencast](http://youtu.be/vxXeJASe-QM) about a year ago over Radioactivity that covers the basics in the Drupal 7 version. Hope it helps!


How to install gpxe/etherboot to hard disk

Question: I have an old PC that I'd like to use as an LTSP client, but its BIOS cannot boot from the network... I tried booting from a CDROM containing a gxpe (Etherboot) image downloaded from ROM-o-matic and it works, so my question is: how do I install the image directly to the local hard disk?
Answer: Found a way:

Boot from a liveCD
Download USB image from ROM-o-matic
dd if=gpxe-1.0.1-gpxe.usb of=/dev/hda


Windows Server 2008 R2 - setting up a web server from scratch

Question: I just purchased a windows server 2008 R2 dedicated server from a local vendor. The server will also include SQL Server Web Edition Licence.
I have so little experience on servers and a little above basic info on IIS. I will be ruining asp.net applications on our server and there will be about 13 applications running on the server.
So where should I start here? should I firstly install IIS from control panel? or should I firstly install DNS server?
Comment: Honestly, call a consultant.
Comment: You should verify that the local vendor is selling you an authentic copy of windows.  AFAIK the web edition is a seperate server- not a license you add on to server 2008.  Web edition has some specific usage restrictions.
Comment: Windows web edition does not support the DNS role. Not quite sure why you would like DNS role on a pair of web and sql servers..
Comment: 3molo, that changed after it was released.  Web edition does support DNS role now.
Comment: thanks guys. the windows server is not web edition ! SQL server is. Windows Server 2008 R2 is Standard edition. I know I don't know much about this server issue but that would be great to know. I have purchased this server in order to learn about servers mostly.
Answer: I would definitely outsource DNS.  Get a vendor like dyndns.com and have them point to your IP addresses(s).  If you're going to handle this yourself then keep to just the IIS website/application part of it.
I've been working on a 52 week series for the web pro.  I walk through host headers, IIS in depth, DNS and various other tools and tricks for the web pro.  You may find this useful to answer a number of your 'getting started' (and then more advanced) questions.
http://weblogs.asp.net/owscott/archive/tags/Web+Pro+Series/default.aspx
Comment: thanks a lot. the blog posts looks great. I am checking them out now. on the other hand, I guess this server issue is too much for me to handle at the beginning level I guess. what do you think? is such a thing can be improved by practicing on the server?
Comment: Hi @tugberk.  Everyone has to start at some point, so don't worry about that.  You'll learn quickly.  However, if you don't have a real reason to do it yourself then this is something that does very well outsourced (web host, etc).  There is a LOT to consider for managing a secure and stable website, so it's not for the faint of heart, especially if you don't have someone that you work with that already knows this area.  That's your call.  You know your setup and reasons better than anyone else.
Comment: hi @scott. thanks a lot for your help. I'll start with your series and move forward from there.
Comment: @tugberk install plesk or some other related software. That's the easiest way. There are some opensource stuff like WebSitePanel as well


How do I use the #autocomplete_route_name property?

Question: I created a custom form and I want add a "users" reference field.
I see here I must use the property autocomplete_route_name, but what value must I set?
$form['project']['users'] = array(
  '#type' => 'textfield',
  '#title' => t('choose users'),
  '#autocomplete_route_name' => 'user.autocomplete',
);

With the previous code, I get the following error:

Uncaught PHP Exception Symfony\Component\Routing\Exception\RouteNotFoundException: "Route "user.autocomplete" does not exist." at /var/www/drupal8/core/lib/Drupal/Core/Routing/RouteProvider.php

What is the correct code I should use?
Answer: Users are entities so they're treated generically. The route is system.entity_autocomplete, with some parameters, but you don't need to get your hands that dirty. You can use the "entity autocomplete" form element type instead, which should be as simple as:
$form['project']['users'] = array(
  '#type' => 'entity_autocomplete',
  '#title' => t('choose users'),
  '#target_type' => 'user',
);

It's derived from a TextField, so you can use all the usual properties. Examples do seem to be a little hard to find other than in the core files (it's early days), but you can see all the available properties the entity_complete adds in EntityAutocomplete::getInfo(), and how they're used within other methods of the class.
Comment: This is correct and while it is not the exact answer to what you wanted to know (that would be: use a route that exists. user.autocompletee was removed a while ago), this is definitely want you want to use. This takes a way a lot of work that you'd have to otherwise do yourself. It will validate and load the user for you. This the underlying API used by entity reference field's autocomplete widget and supports all the things that does (like limit by user roles or use a view for the suggestions).
Comment: Thanks for your answer :) But i'm not sure this is the best way, use #autocomplete_route_name seems to be the simplest choice, but maybe i'm wrong. I wait a bit, if no body proposes another solution I accept yours :)
Comment: @user2137454 This answers your question, which was how to use the autocomplete. What you are asking in your comment is a different question; I am not sure we can answer about the best way, since that is subjective. We should need to see more of your code, and at the end it would still be a subjective choice.
Answer: From the entity reference element
$element['#autocomplete_route_name'] = 'system.entity_autocomplete';
$element['#autocomplete_route_parameters'] = array(
  'target_type' => $element['#target_type'],
  'selection_handler' => $element['#selection_handler'],
  'selection_settings_key' => $selection_settings_key,
);

See http://cgit.drupalcode.org/drupal/tree/core/lib/Drupal/Core/Entity/Element/EntityAutocomplete.php
Comment: I tried this method, you literally have to copy a part of code from core, that generates $selection_settings_key to make it work


Como exibir os elementos de um array sendo que eles são arrays?

Question: Criei um array em que cada índice armazena outro array - ambos globais para que os valores não sejam apagados. O problema está em exibir cada elemento, quando tento, o PHP me retorna "Notice: Array to string conversion"
Código:
function cadastrar($nome, $raca, $cor, $tipoPelo){

    $_SESSION['array1'][] = array($nome, $raca, $cor, $tipoPelo);

    $_SESSION['array2'][] = $_SESSION['array1'];

}

function listar(){

    for($i = 0; $i < sizeof($_SESSION['array2']); $i++){
        echo $_SESSION['array2'][$i];
    }

}

Com o var_dump($_SESSION['array2']); exibe:
  Arrayarray(3) { [0]=> array(1) { [0]=> array(4) { [0]=> string(0) "" [1]=> string(0) "" [2]=> string(0) "" [3]=> string(0) "" } } [1]=> array(2) { [0]=> array(4) { [0]=> string(0) "" [1]=> string(0) "" [2]=> string(0) "" [3]=> string(0) "" } [1]=> array(4) { [0]=> string(5) "nome1" [1]=> string(5) "raca1" [2]=> string(4) "cor1" [3]=> string(5) "tipo1" } } [2]=> array(3) { [0]=> array(4) { [0]=> string(0) "" [1]=> string(0) "" [2]=> string(0) "" [3]=> string(0) "" } [1]=> array(4) { [0]=> string(5) "nome1" [1]=> string(5) "raca1" [2]=> string(4) "cor1" [3]=> string(5) "tipo1" } [2]=> array(4) { [0]=> string(5) "nome2" [1]=> string(6) "raça2" [2]=> string(4) "cor2" [3]=> string(5) "tipo2" } } }

Comment: faz assim, no listar da um `var_dump($_SESSION['array2'])` e edita a questão com o resultado.
Answer: Pelo que entendi, você quer armazenar em uma sessão diversos cadastros feitos. Se for isso você pode fazer algo do tipo
function cadastrar($nome, $raca, $cor, $tipoPelo){
    // Verifica se a $_SESSION['dados_cadastro'] existe, caso nao exista, cria um array vazio, caso exista pega o valor e coloca na variabel $dados_cadastro
    $dados_cadastro = isset($_SESSION['dados_cadastro'])?$_SESSION['dados_cadastro']:[];

    // Adiciona no array $dados_cadastro os novos dados enviados
    array_push($dados_cadastro, [$nome, $raca, $cor, $tipoPelo]);

    // Atualiza a $_SESSION['dados_cadastro'] com os dados de todos os cadastros
    $_SESSION['dados_cadastro'] = $dados_cadastro;
}

function listar(){

    // Verifica se a $_SESSION['dados_cadastro'] existe, caso não, informa que nao tem dados
    if(!isset($_SESSION['dados_cadastro'])){
        echo 'Nenhum item cadastrado';
    }else{
        // Faz um loop em todos os dados em $_SESSION['dados_cadastro'] e imprime na tela
        foreach($_SESSION['dados_cadastro'] as $cadastro){
            var_dump('
');
            var_dump($cadastro);
            var_dump('
');
       }
    }
}

Adicionamos 3 cadastros em $_SESSION['dados_cadastro']
cadastrar('nome 1', 'raca 1', 'cor 1', 'tipo_pelo 1');
cadastrar('nome 2', 'raca 2', 'cor 2', 'tipo_pelo 2');
cadastrar('nome 3', 'raca 3', 'cor 3', 'tipo_pelo 3');

Ao chamar listar, veremos tudo que tem nessa variável de sessão
listar();

E a saída será
array(4) {
  [0]=>
  string(6) "nome 1"
  [1]=>
  string(6) "raca 1"
  [2]=>
  string(5) "cor 1"
  [3]=>
  string(11) "tipo_pelo 1"
}
array(4) {
  [0]=>
  string(6) "nome 2"
  [1]=>
  string(6) "raca 2"
  [2]=>
  string(5) "cor 2"
  [3]=>
  string(11) "tipo_pelo 2"
}
array(4) {
  [0]=>
  string(6) "nome 3"
  [1]=>
  string(6) "raca 3"
  [2]=>
  string(5) "cor 3"
  [3]=>
  string(11) "tipo_pelo 3"
}

Comment: Sim, quero exibir os elementos do vetor, mas de uma forma que eu possa manipulá-los e sem a exibição dos índices e demais informações que sejam desnecessárias ao usuário leigo que vai acessar a aplicação.
Comment: Então, ali dentro do loop, você pode manipular as informações da forma que quiser,  como em uma tabela, pro exemplo. Eu só dei o dump para mostrar o que foi armazenado.
Answer: Isso está acontecendo com você por que você criou um array dentro de um array.
Se você retirar o [] de $_SESSION['array1'] e $_SESSION['array2'] ira funcionar corretamente.
Exemplo:
function cadastrar($nome, $raca, $cor, $tipoPelo){
    $_SESSION['array1'] = array($nome, $raca, $cor, $tipoPelo);
    $_SESSION['array2'] = $_SESSION['array1'];
}

function listar(){
   cadastrar('teste','teste1','teste2','teste3');
   foreach ($_SESSION['array1'] as $value)
      echo $value . ' ';
}
listar();

Comment: Tentei aqui mas ao retirar os colchetes a variável só armazena o último valor inserido, eu preciso que tudo o que for entrado seja exibido. Por isso utilizei um array para guardar outros arrays, eles vão funcionar como um "banco de dados".
Comment: Infelizmente exibe apenas um grupo de valores. Se eu adicionar novos valores os anteriores desaparecem.
Comment: Conseguiu alterar?
Answer: Basta colocar outro loop dentro do primeiro:
foreach($_SESSION['array2'] as $item){
    foreach($item as $subitem){
        echo $subitem;
    }
}

Usei o foreach por ser mais simples, mas pode fazer com o for também
Comment: Testei aqui mas o mesmo erro aparece.
Answer: Há uma estrutura de repetição conhecida por iterar arrays ou objetos que é o foreach.
Exemplo de como é o seu uso:
$array = Array("maça","banana","uva");
foreach ($array as $elemento) {
    echo $elemento."
";
}

Saida:
maça
banana
uva

O primeiro parâmetro é o array que queremos percorrer o segundo é a variavel a qual vai ser atribuída o valor de um elemento do array

Para ajudar no seu problema você pode fazer dessa forma:
foreach($array as $elemento){
    if(!is_array($elemento)){
        echo $elemento;
    } else {
        foreach($elemento as $elemento) echo $elemento;
    }
}

Ele vai iterar dentro do foreach e verificar com o is_array se o elemento é um array, se não for ele vai executar o echo, se for ele vai iterar aquele array.
Fica a dica dar uma olha na documentação do PHP, tá ai o link para tirar suas duvidas sobre o
Foreach


Using Monotone Convergence Theorem to extend a result involving random variable

Question: We assume that for a non-negative, bounded, continuous random variable we have
$$
E[X]=\int_0^\infty P(X>x) dx
$$
Now the task is to extend this result to non-negative, continuous random variables by using the Monotone Convergence Theorem.
I am not sure how one achieves this. I assume one has to show that for a positive, continuous rv $X$, one can construct a series $\lbrace X_n \rbrace$ of bounded non-negative countinuous rv's such that $X_n \uparrow X$, but I am not sure how to that or what result can be used. I guess my problem is finding out when a random variable is the limit of a sequence of random variables.
Answer: Hint: consider the sequence of random variables $X_n = X\wedge n$ for $n\in\mathbf{N}$, where $a\wedge b = \min\{a,b\}$.


Botão com linha dupla no texto

Question: Gostaria de saber se tem como fazer um botão que tenha 2 linhas pré separadas para o texto.
Por exemplo:
<button>
   cima
   baixo
</button>

Ele me daria algo tipo:

Não precisa ser dessa forma o código, só foi um exemplo teórico.
Comment: Pq não usa div que eh um elemento bloco e já quebra a linha
Answer: Você pode utilizar a quebra de linha através da tag
. O código ficaria assim:
<button>
    cima

    baixo
</button>

Comment: Mesma resposta no SOen, basicamente essa é uma das soluções que mais usam
Mas também é possível utilizar o width pra limitar o tamanho e quebrar a linha e outras nº maneiras também :)
Resposta do SOen: https://stackoverflow.com/questions/7469088/html-can-i-display-button-text-in-multiple-lines
Comment: Iago, sempre poste as referências que buscou, caso tenha. Assim, enriquece o conteúdo da resposta e também dá crédito ao outro.

Botão com linha dupla no texto


Finding a specific dot product from a cross product

Question: I am doing the no bullsh*t guide to linear algebra.  On page 161 problem 2.9 is:
Find a vector that is orthogonal to both $u_1 = (1,0,1)$ and $u_2 = (1,3,0)$ and whose dot product with the vector $v = (1,1,0)$ is equal to $8$.
I took the cross product of $u_1$ and $u_2$ and got $(-3,1,3)$.  From there I can see we need to find values such that $-3x + 1y = 8$.  However, I think I need another equation to solve this system.
I was able to draw the vectors $u_1, u_2$, their cross product, and figure out the solution $(12, -4, -12)$ by following the slope of the line made by the cross product vector, but I am not sure how to systematically solve this kind of problem.
Can someone explain the right way to get the answer?
Comment: You need $\;(a,b,c)\;$ s.t. $\;(a,b,c)\cdot(1,0,1)=(a,b,c)\cdot(1,3,0)=0\;$ and also $\;(a,b,c)\cdot(1,1,0)=8\;$ . No need to do the cross product, but if you did it is fine, too. And you not necessarily get a unique solution: it could be there are infinite solutions...
Answer: Your final answer is correct. The mistake in the first calculation was that you wrote that you must have $-3x+1y=8$ but it should've been $-3x+1x=8$.
You found that the cross product is $w=(-3,1,3)$ which means that any vector which is orthogonal to both $u_1$ and $u_2$ must lie on the line spanned by $w$, that is, must be of the form $\lambda w=(-3\lambda, \lambda, 3\lambda)$ for some $\lambda\in\mathbb{R}$. The dot product constraint gives
$$(-3\lambda,\lambda,3\lambda)\cdot(1,1,0)=8$$
so that $\lambda=-4$ so substituting this we get $(12,-4,-12)$ which is your solution.
Comment: This makes a lot of sense.  Thank you for showing me the error and explaining that I am looking for the single scalar to the vector that is perpendicular, and not a list of variables x,y,z.
Answer: Option:
1)Vector perpendicular to $(1,0,1)$ is $(a, b, -a)$.
2)$(a, b, - a) \cdot (1,3,0)=a+3b=0;$
We get $(-3b,b,3b).$
3)$b(-3,1,3)\cdot (1,1,0)=8;$
$b(-3+1)=8; b=-4;$
Finally we have $(12,-4,-12).$
Answer: I went the same way like @Snaw above:
Any multiple of vector  $\begin{pmatrix}-3 \\ 1 \\ 3 \end{pmatrix}$ fulfills the requirement to be orthogonal to the given vectors $u_1$ and $u_2$.
Let $k$ be the factor of that orthogonal vector. This finally leads to the equation:
$-3k\cdot 1+1k\cdot 1+3k\cdot 0 = 8$
which finally gives you the factor $k=-4$ for your solution.
Comment: What is the difference between your post and the answer by Snaw?
Answer: Let $U = \begin{bmatrix}1 &0 &1\\1 & 3 &0\end{bmatrix}$ and $v = [1, 1, 0]$. Then you're being asked to find $x$ such that $Ux=0$ and $vx=8$. Note that $x$ is a three-dimensional column vector, while the $0$ in $Ux =0$ is a two-dimensional column vector. You can combine these two equations into one. Take $M$ to be a matrix with the first two rows being $U$ and the bottom row being $v$:
$M= \begin{bmatrix}1 &0 &1\\1 & 3 &0\\1&1&0\end{bmatrix}$
Then $Mx$ is a three-dimensional column vector where the first two entries are $0 $ (representing orthogonality) and the last entry is 8 (representing the dot product being $8$).
$\begin{bmatrix}1 &0 &1\\1 & 3 &0\\1&1&0\end{bmatrix} \begin{bmatrix}x_1\\x_2 \\x_3\end{bmatrix} =  \begin{bmatrix}0\\0\\8\end{bmatrix}$
The first two rows give a homogenous system. Remember that homogenous systems don't give unique solutions; any multiple of a homogenous system is also a solution. So once you've row-reduced the first two rows, you should have a solution expressed in terms of a free variable. You can then use the last row to solve for the value of that variable.


How do I show that formal logarithm is the inverse of the formal exponential?

Question: Let $A$ be a unital commutative and associative $\mathbb{Q}$-algebra.
Define $exp(f):=\sum_{n=0}^\infty \frac{f^n}{n!}$ for each $f\in XA[[X]]$.
Define $log(f):=\sum_{n=1}^\infty \frac{(-1)^{n+1}}{n} (f-1)^n$ for each $f\in 1+XA[[X]]$.
Hence, we have two maps $exp:XA[[X]]\rightarrow 1+XA[[X]]$ and $log:1+XA[[X]]\rightarrow XA[[X]]$.
I am trying to prove that $log$ map is the inverse of the $exp$ map.
The first thing I tried is to directly show $log\circ exp=id$ and $exp\circ log = id$ by checking if the identities hold for every element $f$, but this does not work well since this way involves too many calculations. For example, $$[X^n]exp(log(f))=[X^n]\sum_{k=0}^n log(f)^k/k! = \sum_{k=0}^n \frac{1}{k!} [X^n]log(f)^k= \sum_{k=0}^n \frac{1}{k!} [X^n](\sum_{l=1}^k \frac{(-1)^{l+1}}{l} (f-1)^l)^k$$.
Thus, we have to show that $$\sum_{k=0}^n \frac{1}{k!} [X^n](\sum_{l=1}^k \frac{(-1)^{l+1}}{l} (f-1)^l)^k=[X^n]f$$.
But this calculation is really a nightmare.. Is there a clever way to show this? If not, how do I wisely calculate to show the above identity?
Thank you in advance.
Comment: According to https://en.wikipedia.org/wiki/Formal_power_series#Composition_of_series , composition of formal power series is only defined if the inner power series has no constant term. Does that mean that this argument works for $\exp \circ \log$ but not $\log \circ \exp$?
Comment: This actually follows from the corresponding fact about actual functions over the reals. The point being that if $\log \circ \exp$ and $\exp \circ \log$ are equal to the identity as functions over the reals then the corresponding Taylor series must also be equal, and that implies the corresponding identity of formal power series. Said another way, analytic functions embed into formal power series, in a way compatible with addition, multiplication, and composition.
Comment: @QiaochuYuan How do we embed $A$ to $\mathbb{R}$? Say $A=\mathbb{Q}[X_1,X_2,...]$. And the above formal log definition is not well-defined over reals.. could you give me some more details?
Comment: It's unnecessary to embed $A$ anywhere. The desired identities are true universally in the sense that exp and log are inverses as formal power series over $\mathbb{Q}$.
Comment: Similarly, in order to prove that $\frac{1}{1 - f} = 1 + f + f^2 + \dots$ for all $f \in x A[[x]]$ I actually only have to prove it for a single $f$, namely $f = x \in x \mathbb{Z}[[x]]$, whereupon it's true universally.
Answer: Here is one possible argument. One way to define the exponential $\exp(x)$ as a formal power series is that it is the unique formal power series $f(x)$ (over any commutative $\mathbb{Q}$-algebra) satisfying $f(0) = 1$ and
$$f'(x) = f(x).$$
Repeatedly differentiating this identity easily gives $[x^n] \exp(x) = \frac{1}{n!}$ as expected. Similarly, one way to define the logarithm $\log (1 + x)$ as a formal power series is that it is the unique formal power series $g(x)$ satisfying $g(0) = 0$ and
$$g'(x) = \frac{1}{1 + x} = \sum_{n=0}^{\infty} (-1)^n x^n.$$
So what can we say about the composite $\exp \log (1 + x)$? Well, by the formal chain rule, we have
$$\frac{d}{dx} f(g(x)) = f'(g(x)) g'(x) = f(g(x)) \frac{1}{1 + x}.$$
So $f(g(x))$ is a solution $h(x)$ to the differential equation $h'(x) = h(x) \frac{1}{1 + x}$ with initial condition $h(0) = f(g(0)) = 1$. We clearly have $h(x) = 1 + x$ is a solution, and we can appeal to a formal version of the Picard-Lindelof theorem to assert that formal solutions to ODEs exist and are unique, so we conclude that
$$\exp \log (1 + x) = 1 + x.$$
Similarly, what can we say about $\log \exp x = \log ((\exp x - 1) + 1)$? Well, again by the formal chain rule, we have
$$\frac{d}{dx} g(f(x) - 1) = g'(f(x) - 1) f'(x) = \frac{f'(x)}{f(x)} = 1.$$
So $g(f(x) - 1)$ is a solution to the ODE $\frac{d}{dx} h(x) = 1$ with initial condition $h(0) = g(f(0) - 1) = 0$. Here it's a bit simpler to see that we must have $h(x) = x$, so
$$\log \exp(x) = x.$$
Answer: Another way might be
(feeling too lazy right now
to work out
all the details)
to use the functional equations:
For ln,
$f(xy) = f(x)+f(y),
f'(1) = 1$.
For exp,
$g(x+y) = g(x)g(y),
g'(0) = 1$.
From these,
can get
$f'(x)
=\dfrac1{x}
$
and
$g'(x) = g(x)$.


How many combinations can be made with these rules? (game of Dobble)

Question: The game called Dobble consists of a deck of cards; each card contains 8 symbols from a set of 50.
The deck is made so that any two cards have exactly one symbol in common. (The idea of the game is that on each turn, the first player to spot the symbol that's on both cards gets the card. The winner is the one who ends up with the most cards.)
My question is,

With the above numbers, what is the size of the largest possible deck?

(According to the rules there are actually 55 cards in a deck.)
My guess is that an explanation would involve an application of the multinomial theorem, but I can't see how to work it out.
Answer: It cannot be done with the numbers originally given. (In other words, with 10 symbols per card chosen from a set of 40, a deck of 50 cards is not possible.)
We will begin to deliberately construct cards so that they obey your constraints. We construct the first card using an arbitrary selection of 10 symbols from the 40 available. Then, for the second card, we select one symbol from the first card and the remaining 9 from the set of unused symbols (there are currently 30 of these).
For the third card, we may either use the symbol already on both of the existing cards (in which case we must use 9 more unused symbols, of which there are now 21, to fill the remaining spots) or we may choose one symbol from the first and a different symbol from the second (in which case we need only to use 8 of our 21 unused symbols). The second seems like the better option, since we use up our symbols less quickly.
We continue constructing these cards using the "better" method and find that we have 13 unused symbols left for the fourth card, 6 left for the fifth card, and... By the time we are trying to construct our sixth card, we have already used up all of our symbols. So that means our sixth card must use a combination of symbols on the existing cards. But we only have five cards; if we are to make a sixth card with 10 different symbols, we must pull more than one symbol from an existing card, which violates the constraint that no two cards share more than one symbol.
Comment: Thanks for the reply, but as I pointed out in my original question (which Andrew Kelley edited out), the numbers were made up, as I didn't have a set of Dobble cards in front of me. Whilst your reply is interesting, I was more interested in the answer to my actual question, which was how many cards can you make using the Dobble rules.


Single PHP File I need to Run as CGI

Question: I have a legacy program that I need to run with the extension of .cgi (search.cgi), but I have re-written this code using PHP.
How do I tell Apache to reference search.cgi but make it run search.php?
Answer: Use the url rewriting mod of apache.
Somthing like
RewriteEngine on
RewriteRule ^/search.cgi$ /search.php [QSA]

You can change search.cgi by ixsearch.cgi
Or more general
RewriteEngine on
RewriteRule ^/([a-z0-9_\-]+)\.cgi$ /$1.php [NC, QSA]

That will rewrite any url yourdomain.com/{some_scriptname}.cgi in yourdomain.com/{some_scriptname}.php (and rewriting the request GET parameter thanks to QSA clause)
the script name can contain any letter between a and z or numer or char like - or _ (ex tomato-juice). Plus it is case insensitive (thanks to NC clause)
Comment: Close but still not working, I am using http://taildb.com/ixsearch.php?F=B&TN=N911DE and need it to render the same thing via http://taildb.com/ixsearch.cgi?F=B&TN=N911DE
Answer: Use mod_rewrite to rewrite requests for search.cgi to search.php.
Answer: Just write it as a regular CGI like you've done but make it run using the command line version of PHP so that it runs like a regular CGI.
Comment: This will work, but generally it's better to run PHP scripts via mod_php if possible.
Comment: @IgnacioVazquez-Abrams no it's not. mod_php is horrible and a bad idea, popularity notwithstanding. Sane admins run PHP via FastCGI.
Comment: @hobbs: Sane admins don't run PHP at all unless they're forced to.
Comment: I work for an organisation that has a PHP based website and it's currently deployed as a FastCGI. I don't directly work on that project but I've been told by the ops people that they explicitly chose to run it in this fashion instead of using `mod_php`. Ignacio, why do you recommend `mod_php`?

Single PHP File I need to Run as CGI


Is it possible to query against the ldap server stored in drupal without reconnecting?

Question: I have a drupal install that uses LDAP to authenticate users.  I use that same LDAP to return user info such as roles, employee photo, email, role, and the center they work at.
<code>    $ds=ldap_connect("ldap-example.com");
            if ($ds) {
                $r=ldap_bind($ds);
                $sr=ldap_search($ds, "DC=tpcontact,DC=co,DC=uk",$search);
                $info = ldap_get_entries($ds, $sr)or die('get info fail');
}
</code>
I need to make it so that the server is pulled from drupal.  So, if it is possible to query ldap without reconnecting, I need to do that.  Otherwise I need to query the drupal DB's ldap_servers table, the only problem is that I dont have access to a MySql database that has LDAP enabled to see what the field is.
Comment: ok, i see you know the `ldap_query`, `ldap_feeds` and `ldap_views` are all designed to let you run queries like this at any time. you shouldn't have to write the query yourself (but more power to you if you can).
Comment: can you reword this question to be more clear. Your question doesn't make much sense. Any time you want to query mysql or ldap you have to connect first. A connection only last the duration of a single url page request from a site visitor.
Comment: I've updated my answer with the name of the field that contains the address...
Comment: If you need confidential info removed from a question, you need to flag the question for mod attention. Editing it will not make the info go away.
Answer: So I assume that you are using the LDAP module?
I've not looked into the code they use however I would expect that they will close the connection before your module runs, and even if they don't the connection won't be a global variable so your module will not have access to it.
If you are writing a custom module then you do have access to the DB - just use db_query and fetch the results, or look in your settings file for your connection details. Then you can connect directly to your DB using software like Navicat.
The table ldap_servers has a field called address. This is where you will find the address to your ldap server.


Configure intellitest to use just the one test project in Visual Studio 2015 RC

Question: So, I am playing with intellitest in Visual Studio 2015 RC, but something I see happening irks me and I would like to know how to disable this action. When I select to run intellitest and then go to either apply a fix or save a test result, intellitest auto-creates a second project where the changes should be applied. After having this happen so often, my solution file went from having just the two projects(Website and WebsiteTest) to having over 10 other duplicates of the WebssiteTest project in my solution file. Is there a way to disable this behaviour? I would like to know please.

A second issue I keep having is my intelliTest Projects continually include Android and Xamarin ability in the main Test and TestCopy projects, a behavior I am not really happy with. Is there a way to disable this please??
Thanks in advance
Comment: The first issue is being addressed in the next upcoming release.  Regarding the second issue please see workaround in VS 2015 RC release notes: http://go.microsoft.com/fwlink/?LinkId=524375 …. See "Known issues" in "Unit testing". This too will be addressed at the next upcoming release.
Answer: Just circling back to let you know that this has since been fixed at the Visual Studio RTM release. Thank you for the feedback.
Comment: [This still seems to be an issue](http://stackoverflow.com/q/36377316/234910). Is that right?


Text warp effect in Photoshop or Illustrator

Question: logo http://mlfuentes.webdesigndarwen.co.uk/austinsroofing.jpg
Hi there, I am unsure how to re-create the above text warp effect in either Photoshop or Illustrator?
I need the AUSTIN'S text to rise in the center, I have tried the text warp effects built into photoshop but they are too "rounded" and not as straight as this.
Can anybody please shed some light on his I can achieve this?
Thankyou!
Comment: Stackoverflow is really for programming questions. However, the best way to achieve this would be to convert the text to paths and move each of points of the upper half of the letters up so that are aligned with the roof. This would actually take a while. A quicker way would be to rasterise the type, duplicate it (treat the new layer as the right half and the previous one as the left half) and using warp, adjust the corners of the warp box so the text becomes angled like the roof, but remember to adjust the handles on the corners of the warp box to straighten out the text (so it's not curved)
Answer: It can be easy achieved both in Photoshop and Illustrator, but in Photoshop it's even easier :)
You can follow these simple steps:

Create the text you need.
Convert the text into a vector shape.
Duplicate this shape and broke it into 2 shapes with additional rectangle.
Distort both part of the word with Transform tool (Ctrl+T or Cmd+T) to achieve a perspective you need.
And finally merge these 2 vector shape together.

And if you need this logo in .ai format just copy and place the final vector shape into Illustrator.
That's it :) It can be done in minute.
Hope this helps you)


How to get firstname in autocomplete when adding new members in og group?

Question: I have created the group in og.
When adding the user for the group, In autocomplete its been displaying the user's email ID.
<code>function custom_form_alter($form,&$form_state){ if($form['#id']== 'og-ui-add-users'){
     $form['og_user']['name']['#autocomplete_path'] = 'user/autocomplete';
}
</code>
}
But I want to get the name instead of email ID.
I have tried to change the user/autocomplete in hook_form_alter,but its displaying email id only
Is there any way to get name instead of email ID ?
Tell me how to sort out this problem?
Comment: have you written query.
Comment: No, I didnt write query
Comment: Can you please update your question with coding.this might be useful.
Comment: added the code,just altered the form, But I dont know this method is right
Answer: I didn't get a clear idea, anyway please Check This.


How to get the revision of a paragraph

Question: I have a code which is running in hook_node_update. This code grab the revision of the saved node and compare the values of the fields between current node and its revision to generate some kind of historic log (what is deleted/updated/added).
This is working very well except for the paragraph field...
When my code is trying to get the revision of a paragraph (recursively), I got each time the same paragraph instead of the old revision (thus no differences to log)
Here is my code to get the revision of a the saved node (working well). This code is also used for the paragraphs (not working)
$updated_entity : the node/paragraph currently in the process to be saved
$old_entity : the revision to compare with
  $old_entity = $updated_entity->original;
  if (!$old_entity) {
    $storage = $this->getStorage($updated_entity);
    // no need to test if revisionable as we use only Node and Paragraphs
    if ($revision_id = $updated_entity->getLoadedRevisionId()) {
      $old_entity = $storage->loadRevision($revision_id);
     }
    else {
      //... handling new entity
      ]);
    }
  }

This code, when applied to the paragraphs, is producing an $old_entity == $updated_entity
The paragraphs are extracted from the currently saved node as follow:
$paragraphs = $updated_entity->get($paragraph_field)->referencedEntities();

after that, they become the $updated_entity variable in the upper function which is trying to get the revision...
Answer: The unnamed upper function works only for the one specific node you get via the hook as parameter. Load the old referenced paragraphs via the original entity:
$old_paragraphs = $node->original->get($paragraph_field)->referencedEntities();

For nested paragraphs you can then apply recursive loading, but each branch (old/new) separately and not with the upper function, use ->referencedEntities() for mulitple and ->entity for single field items, these functions load revisions.
In a multilingual site you have to get the translation of the paragraph using the node language:
$node_language = $node->language()->getId();
$value = $paragraph->getTranslation($node_language)->field_foo->value;

Comment: Comments are not for extended discussion; this conversation has been [moved to chat](https://chat.stackexchange.com/rooms/131668/discussion-on-answer-by-4k4-how-to-get-the-revision-of-a-paragraph).
Comment: But what if paragraphs get reordered? A given array key in the array returned by referencedEntities may not point to the same entity. I think instead we should load the older entity from the entity ID of the paragraph entry.
Comment: @gagarine, one could argue if the paragraphs are rearranged this is a change. If you want to ignore that you could sort both arrays by paragraph id before comparing.
Comment: @4uk4 yes, it's really depend of what you need to achieve. On my side, I need to detect changes at the paragraphe item level. But sorting is not enough,  as you may have deleted and add a new one. I end up doing a loop on the paragraphs array and compare until I found one with the same entity ID. Simple and effective :).
Answer: One way is to use hook_ENTITY_TYPE_update on the paragraph entity:
<?php
   // file mymodule.module

   /**
    * hook_ENTITY_TYPE_update
    *
    * @param \Drupal\paragraphs\Entity\Paragraph $paragraph
    *
    * @return void
    */
    function mymodule_paragraph_update(\Drupal\paragraphs\Entity\Paragraph $paragraph): void {

      // We are only interested by bundle_name paragraph
      if($paragraph->bundle() !== 'bundle_name'){
        return;
      }

      $field_value = $paragraph->get('field_name')->getValue();
      $original_field_value = $paragraph->original->get('field_name')->getValue();

      // You can get the parent node like that
      $node = $paragraph->getParentEntity();

    }

How to get the revision of a paragraph


Error with referencing to an array in ViewController from View

Question: i have an NSMutable array function in ExercisesViewController.m and want to call that array into ExercisesView.m.
ExerciseViewController.m
<code>- (NSMutableArray*)qBlock{

NSURL *url = [NSURL URLWithString:@"http://someaddress.php"];
NSError *error;
NSStringEncoding encoding;
NSString *response = [[NSString alloc] initWithContentsOfURL:url
                                                usedEncoding:&encoding
                                                       error:&error];
const char *convert = [response UTF8String];
NSString *responseString = [NSString stringWithUTF8String:convert];
NSMutableArray *sample = [responseString JSONValue];

return sample;}
</code>
ExercisesView.m:
<code> - (id) initWithParentViewController:(ExercisesViewController *)parent {
if ((self = [super init])) {
    // Update this to initialize the view with your own frame size
    [self setFrame:CGRectMake(0, 0, 320, 460)];
    refParentViewController = parent;
    NSMutableArray *qnBlock = [refParentViewController:qBlock];}
</code>
But there seems to be some error in linking the reference. I just have a gut feeling its syntax issue. Any pointers?
Answer: It's just a syntax error. Try this:
<code>NSMutableArray *qnBlock = [refParentViewController qBlock];
</code>
Comment: i did but the error returned:Instance method '-qBlock' not found (return type defaults to 'id')
Comment: Check that you also have a declaration of your method in your `ExerciseViewController.h` file.


Preload tableView cells and prevent reloading

Question: I already found entries with that topic on this page and also a website that provides a tutorial for that problem. But nothing worked very well.
The tutorial sad I should double the height of my tableView so cells loaded earlier, but with a higher tableView I never reached the last cells.
My problem is, I use a tableView to display my apps mainpage. This mainPage shows every time a topic and if its necessary for that topic it shows for example a cell with a map, one with pictures and sometimes not. Problem now, if I trying to scroll to my view its always lagging because it loads a map or this pictures. And scrolling back again because the loaded cells already deleted. I used a tableView because of the possibility to switch celltypes(mapCell, pictureCell, textCell) on and off.
I understand this feature, because of memory issues but in my case its not that much and it would be better if all my cells be preloaded and stay in memory until I change the topic.
Is there a swifty way to told my tableView to have this behavior?
Thanks a lot and nice greetings
Answer: I would suggest a different approach. Set up your table view controller to install placeholder images in your cells, trigger an async download that you cache to disk, and then update the cell with it's downloaded content if it's still visible when the download is finished.
There are various third party frameworks that do all this housekeeping for you.
Comment: yes, another method, but I think its okay! I have a memoryusage between 30-60 mb or is that to much?
Comment: On a newer device 30-60 mb should not be a problem. How many table view entries are we talking, and how big are the images?
Comment: iOS 9 runs on the 4s and above. That's your current lowest spec device. iOS 10 will drop the 4s and only run on the 5 and above.
Comment: It is a maximum of 6 cells. Some of the cells always there some are variable.
Comment: The 3 Cells that always there have 1. one image 550x1200 (not optimized jet) 2. one image 250x250(not optimized jet too) both loaded from a Database. The 3 variable cells are one with MapView, one with some text and one with a tableView that have 3 cells each with a image 320x180 also loaded from a Database. And there are some other little icons with just around 2-20kb
Comment: I testing on a iPhone 4s and a ipad mini 1th gen, both works fine. Only xcode shows on Energy Impact just High-Very High, but this was also before I changed to hold all cells. If I'm honest I wondering about that my app is not doing anything but showing content.
Answer: Declare a cell array.
Follow these steps whenever change in your topic.

Clear you array
Create and configure all cells add to your array.
Return these cells to datasource methods using row index. Don't use tableview dequeue method here.
Comment: Oh boy, I'm so embarrassed! How simple was that! I thank you so much!
Comment: This works but it's not memory-efficient. Better to pre-load the model data and still use the cell dequeue method.


Problem on partioning

Question: On reading the book 'Aha! Solutions' by Martin Erickson I came to know that the number of partitions of $n$ ($n \in \mathbb{N}$) into three parts is $\left\{ {\frac{{{n^2}}}{{12}}} \right\}$ where $\left\{ {} \right\}$ denotes the nearest-integer function. But I cannot understand how this result comes. Please show me how this can be derived and how this can be generalized.
Answer:
Let $P(n,k)$ be the number of partitions of $n$ into exactly $k$ parts. This function satisfies the recurrence
$$P(n,k)=P(n-1,k-1)+P(n-k,k)\;:$$
the first term on the right is the number of $k$-partitions of $n$ that have at least one part of size $1$, and the second is the number that have no parts of size $1$. (This is most easily seen by considering the Ferrers diagrams of the partitions.)
For $k=1$ we get
$$P(n,1)=P(n-1,0)+P(n-1,1)=P(n-1,1)\;,$$
so $P(n,1)=P(1,1)=1$ for all $n\ge 1$.
For $k=2$ we now get
$$\begin{align*}
P(n,2)&=P(n-1,1)+P(n-2,2)\\
&=P(n-2,2)+1\;,
\end{align*}$$
so $P(2m+1,2)=P(2m,2)=m$, since $P(3,2)=P(2,2)=1$. We can combine the cases as
$$P(n,2)=\left\lfloor\frac{n}2\right\rfloor\;.$$
Finally we can look at $k=3$:
$$\begin{align*}
P(n,3)&=P(n-1,2)+P(n-3,3)\\
&=\left\lfloor\frac{n-1}2\right\rfloor+P(n-3,3)\\
&=\left\lfloor\frac{n-1}2\right\rfloor+\left\lfloor\frac{n-4}2\right\rfloor+P(n-6,3)\\
&\;\;\vdots\\
&=\sum_{k=0}^{\lfloor n/3\rfloor-1}\left\lfloor\frac{n-1-3k}2\right\rfloor+1\;.
\end{align*}$$
If $n=6m$, this is
$$\begin{align*}
\sum_{k=0}^{2m-1}\left\lfloor\frac{6m-1-3k}2\right\rfloor&=\sum_{k=1}^{2m}\left\lfloor\frac{3k-1}2\right\rfloor\\
&=\sum_{k=1}^m\left\lfloor\frac{6k-1}2\right\rfloor+\sum_{k=1}^m\left\lfloor\frac{6k-4}2\right\rfloor\\
&=\sum_{k=1}^m(3k-1)+\sum_{k=1}^m(3k-2)\\
&=3\sum_{k=1}^m(2k-1)\\
&=3m^2\\
&=\frac{n^2}{12}\;.
\end{align*}$$
If $n=6m+1$, it's
$$\begin{align*}
\sum_{k=0}^{2m-1}\left\lfloor\frac{6m-3k}2\right\rfloor&=\sum_{k=1}^{2m}\left\lfloor\frac{3k}2\right\rfloor\\
&=\sum_{k=1}^m3k+\sum_{k=1}^m\left\lfloor\frac{6k-3}2\right\rfloor\\
&=\sum_{k=1}^m3k+\sum_{k=1}^m(3k-2)\\
&=2\sum_{k=1}^m(3k-1)\\
&=3m(m+1)-2m\\
&=3m^2+m\\
&=\frac{n^2-1}{12}\;.
\end{align*}$$
If $n=6m+5$, it's
$$\begin{align*}
\sum_{k=0}^{2m}\left\lfloor\frac{6m+4-3k}2\right\rfloor&=\sum_{k=0}^{2m}(3m+2)+\sum_{k=0}^{2m}\left\lfloor-\frac{3k}2\right\rfloor\\
&=(2m+1)(3m+2)-\sum_{k=0}^{2m}\left\lceil\frac{3k}2\right\rceil\\
&=(2m+1)(3m+2)-\sum_{k=0}^m3k-\sum_{k=1}^m\left\lceil\frac{6k-3}2\right\rceil\\
&=6m^2+7m+2-\sum_{k=1}^m3k-\sum_{k=1}^m(3k-1)\\
&=6m^2+7m+2-\sum_{k=1}^m(6k-1)\\
&=6m^2+7m+2-\big(3m(m+1)-m\big)\\
&=3m^2+5m+2\\
&=\frac{n^2-1}{12}\;.
\end{align*}$$
The other three cases are similar.

Problem on partioning


PouchDB 409 conflict when adding doc.

Question: I am getting a strange conflict with pouchDB when adding a new document. The conflict arises when creating a new doc shortly after another is made. However if I wait ~5 minutes or so the conflict no longer occurs. I am very stuck with solving this.
I am using a express with node.
Here is my method for adding an item. It is used in a router (see below)
<code>//require stuff
...
//require pouch
var PouchDB = require('pouchdb');
//db setup
var db = new PouchDB('http://127.0.0.1:5984/db');

module.exports = {
      addItem: (req, res, next) => {
        //check body fields with express validator
        req.checkBody('firstname', "Invalid, please enter firstname").notEmpty();
        req.checkBody('lastname', "Invalid, please enter lastname").notEmpty();
        req.checkBody('address', "Invalid, please enter address").notEmpty();
        var phonenumber = req.body.phonenumber; //phone number is optional dont use express validator
        var errors = req.validationErrors();
        if (errors) {
          res.render('add', {
            errors: errors
          });
        }
        var newDoc = {
          _id: date.toString() ,
          firstname: req.body.firstname,
          lastname: req.body.lastname,
          address: req.body.address,
          phonenumber: phonenumber,
          dateAdded: moment(date).format("dddd, MMMM Do YYYY, h:mm:ss a")
        }

        db.put(
          newDoc
        ).then(function (response) {
          res.redirect('/feed');
        }).catch(function (err) {
          if (err){
            return next(err);
          }
        });
      },
    ...
   //more methods
}
...
//export module
</code>
router for adding
<code>//require all the stuff
//post new item route
router.route('/feed/add').post(ActionController.addItem);
</code>
Answer: I used the pouchdb-upsert to fix this. https://github.com/pouchdb/upsert
and used the puIfNotExists method.
<code>...
    //save item to array and db
    db.putIfNotExists({
      _id: date.toString(),
      firstname: req.body.firstname,
      lastname: req.body.lastname,
      address: req.body.address,
      phonenumber: phonenumber,
      dateAdded: moment(date).format("dddd, MMMM Do YYYY, h:mm:ss a")
    }).then(function () {
      return res.redirect('/feed');
    }).catch(function (err) {
      if (err) {
        return next(err);
      }
    })
...
</code>

PouchDB 409 conflict when adding doc.