How do I exclude/blacklist admin paths?

Question: Is there still a way to exclude administrative paths from using the CDN module in Drupal 8?
It appears you have to use advanced mappings, but I don't understand how.
Answer: No, not currently. As the UI suggests, the complex mappings can be set in the module's install/config/cdn.settings.yml config file, but it only allows for segmenting traffic to different CDNs based their extension.
The FileUrlGenerator service object handling the file URL rewriting doesn't consider a path context while deciding when/when not to serve file from the CDN.
You could replace this service class via the ServiceModifierInterface and its ::alter() method with a custom service class that does consider the path context.
Comment: Pretty much the conclusion we had come too :(

How do I exclude/blacklist admin paths?


What do dotted stave lines mean?

Question: I've seen a dotted stave lines in this piece: http://www.fullinuyasha.com/inuyasha-sheet-music-sango-theme.html
What do they mean? How is this supposed to be played?
Comment: They don't seem to be there on all of the versions of this song.
Comment: I'd go for "cues" -- if this were an orchestra score for some instrument I'd read the upper part as either an "ossia" line or the notes from some other instrument.
Answer: Typically dotted stave lines suggest a continuation of the stave without having the stave actually be present.  Quite often you'd just see the top and bottom lines of the stave extended to where the stave re-appears in full.  This technique is predominately used for cut-away scores to help line things up.
In this context of what you presented however, there seems to be little function in the use of these lines.  The only thing I can think of would be that the author is attempting to show that the dotted portion is not always part of the song, or that that portion is performed by electronic accompaniment only.  Otherwise, there is really no need.

What do dotted stave lines mean?


Why are macros based on abstract syntax trees better than macros based on string preprocessing?

Question: I am beginning my journey of learning Rust. I came across this line in Rust by Example:

However, unlike macros in C and other languages, Rust macros are expanded into abstract syntax trees, rather than string preprocessing, so you don't get unexpected precedence bugs.

Why is an abstract syntax tree better than string preprocessing?
Comment: *so you don't get unexpected precedence bugs*
Answer: If you have this in C:
#define X(A,B) A+B
int r = X(1,2) * 3;

The value of r will be 7, because the preprocessor expands it to 1+2 * 3, which is 1+(2*3).
In Rust, you would have:
macro_rules! X { ($a:expr,$b:expr) => { $a+$b } }
let r = X!(1,2) * 3;

This will evaluate to 9, because the compiler will interpret the expansion as (1+2)*3.  This is because the compiler knows that the result of the macro is supposed to be a complete, self-contained expression.
That said, the C macro could also be defined like so:
#define X(A,B) ((A)+(B))

This would avoid any non-obvious evaluation problems, including the arguments themselves being reinterpreted due to context.  However, when you're using a macro, you can never be sure whether or not the macro has correctly accounted for every possible way it could be used, so it's hard to tell what any given macro expansion will do.
By using AST nodes instead of text, Rust ensures this ambiguity can't happen.
Comment: Thank you for providing concrete examples of both types of macros.
Answer:
A classic example using the C preprocessor is
#define MUL(a, b) a * b

// ...

int res = MUL(x + y, 5);

The use of the macro will expand to
int res = x + y * 5;

which is very far from the expected
int res = (x + y) * 5;

This happens because the C preprocessor really just does simple text-based substitutions, it's not really an integral part of the language itself. Preprocessing and parsing are two separate steps.
If the preprocessor instead parsed the macro like the rest of the compiler, which happens for languages where macros are part of the actual language syntax, this is no longer a problem as things like precedence (as mentioned) and associativity are taken into account.


WARNING conda.gateways.disk:unlink_or_rename_to_trash(140)

Question: i have this error when i try to install pytorch in my environment, i have found the file that i need to delete but, which one of the four files do i delete?
Comment: Di you use both pip and conda for installing packages ?
Answer: I was stuck with the same problem. What I was doing wrong was I created one environment and installed packages using pip install while inside another environment I was trying conda install
The fix which worked form was to let conda itself remove unwanted files. This can be done using
conda clean --all

Comment: Your command works, but the original problem cannot resovle. *WARNING conda.gateways.disk.delete:unlink_or_rename_to_trash(140): Could not remove or rename C:\ProgramData\Anaconda3\envs\py36\vcruntime140.dll.  Please remove this file manually (you may need to reboot to free file handles)*
Answer: I had the same error when installing PyQtChart.  I received the following error:

Executing transaction: - WARNING
conda.gateways.disk.delete:unlink_or_rename_to_trash(139): Could not
remove or rename
C:\ProgramData\Anaconda3\envs\topss2\Library\resources\icudtl.dat.
Please remove this file manually (you may need to reboot to free file
handles) done ERROR conda.core.link:_execute(698): An error occurred
while installing package 'conda-forge::qt-5.12.9-hb2cf2c5_0'. Rolling
back transaction: done
[Errno 22] Invalid argument:
'C:\ProgramData\Anaconda3\envs\topss2\Library\resources\icudtl.dat'
()

I was able to delete the file in question without rebooting.  I got lucky this time.
There are some analytics packages I use which do not have conda packages, so occasionally I have to use pip.  As I am doing development work, I don't always know in advance when I will need a Python package that only has a pip-formatted package, so I occasionally use conda after using pip.  I am usually too lazy to rebuild a new environment every time I "dead-end" a conda environment.  There is a way to roll back a conda environment if a pip package corrupts it, but that is not recommended.  Interoperability between conda and pip is still an experimental feature, but it is improving.  See the following link for more information: conda-pip interoperability
Does anyone know of a package to simply convert a pip package to a conda package?  This would make my life much easier.
Answer: I got the same message when installing OpenCV

Executing transaction: \ WARNING conda.gateways.disk.delete:unlink_or_rename_to_trash(140): Could not remove or rename C:\Users\user\anaconda3\Library\resources\icudtl.dat. Please remove this file manually (you may need to reboot to free file handles)

I was able to resolve this issue by closing Spyder while installing.
Answer: I got the same error while cleaning up unused packages. It was more to do with Permission issue in my case. I resolved it by opening Anaconda Prompt in Run as Administrator mode and then it worked.
Answer: Inside conda environment, for example want removing environment named py36
run
conda remove py36

conda clean --all

see errors.

then delete

then
conda clean --all

Now it is ok.

Conclusion: Need also command conda remove also delete by hand in Windows Explorer.


How to define an image style where images are the exact same dimensions (e.g. grid of square images), without cropping or distorting the image?

Question: On my site, images of any shape can be uploaded, for example:

I want these to display in a grid where every image is the same size and shape (in my case, square) - due to the nature of the images, I don't want to use cropping and I don't want any distortion of the aspect ratio, but the backgrounds can be extended. This also needs to be applied to the image itself, not a CSS wrapper.
For example, I'd like the end result to look like this:

Everything I've tried using various combinations of "scale" and "resize" either doesn't give consistent final sizes depending on whether the original was tall or wide, or distort the image. Cropping isn't an option. How can I do this?
Answer: If you don't mind applying a block background colour, this seems to be possible with Imagecache Actions module.

Download and enable the Imagecache Actions module and its imagecache_canvasactions submodule.
Add a normal "scale" action to the desired size (300 x 300). This keeps the aspect ratio.
After, add a "Define canvas" action, then set to the same dimensions under "exact size".
Make sure "Resize canvas under image" is ticked, choose an appropriate background colour, and go. This fills in any gaps to the desired size with whatever colour you choose (or transparency if you choose no colour).


Prove that rational points are countable

Question: Prove that the set of points (p,q) on the plane - (where p,q are rational coordinates) is countable. I don't understand what I need to do to prove this
Answer: The problem asks you to show that the set $\{\langle p,q\rangle\in\Bbb R^2\mid p,q\in\Bbb Q\}=\Bbb{Q\times Q}$ is countable.
To prove this, recall that $\Bbb Q$ is countable, and use the basic theorems about countable sets.
Comment: Dear Asaf - Moments ago came the message that moderator elections are upon us. If it's something you would consider, I would be delighted to nominate you - as I am sure many others would as well. Regrads,
Comment: @Andrew: Thanks for the support. I am not personally cut for being a moderator on this website. I have declared that more than several times already that I will never, ever *ever* consider taking moderatorship on this website. But thanks for the vote of confidence.


Getting back to back error using "wait_on_rate_limit" parameter

Question: In order to avoid rate limit error I used the parameter:
wait_on_rate_limit

in function
api = tweepy.API(auth,wait_on_rate_limit=True,wait_on_rate_limit_notify=True)

At first my program worked fine. When I surpass the rate limit I got the message:
      "Rate limit reached. Sleeping for: 909". My program was sleeping for this amount of time and then my program continued to collect data. At some point I got some back to back errors.
...
ConnectionResetError: [WinError 10054] An existing connection was forcibly closed by the remote host

During handling of the above exception, another exception occurred:

...
urllib3.exceptions.ProtocolError: ('Connection aborted.',
ConnectionResetError(10054, 'An existing connection was forcibly closed by
the remote host', None, 10054, None))

During handling of the above exception, another exception occurred:

...
requests.exceptions.ConnectionError: ('Connection aborted.', ConnectionResetError(10054, 'An existing connection was forcibly closed by the remote host', None, 10054, None))

During handling of the above exception, another exception occurred:

...
tweepy.error.TweepError: Failed to send request: ('Connection aborted.', ConnectionResetError(10054, 'An existing connection was forcibly closed by the remote host', None, 10054, None))

My code:
for user in tweepy.Cursor(api.friends, id="twitter").items():
    friendsOfUser=user.screen_name
    ## Do something with friendsOfUser

Is there anything that I can do?
Answer: This worked for me:
    backoff_counter = 1
    while True:
        try:
            for user in tweepy.Cursor(api.friends, id="twitter").items():
                # do something with user
            break
        except tweepy.TweepError as e:
            print(e.reason)
            sleep(60*backoff_counter)
            backoff_counter += 1
            continue

Basically, when you get the error you sleep for a while, and then try again. I used an incremental backoff to make sure that the sleeping time was enough for reestablishing the connection.
Answer: You can't do anything with the fact that host closes the connection. If you are waiting for the rate limit, I bet you're a bit aggressive in API usage :) Try catching TweepError and explicitly waiting for some time and them try again.
You can try something like this:
import time

...
try:
    for user in tweepy.Cursor(api.friends, id="twitter").items():
        friendsOfUser=user.screen_name
        ...
except tweepy.TweepError:
    time.sleep(120) # sleep for 2 minutes. You may try different time

Comment: So should I write in my code:
     for user in tweepy.Cursor(api.friends, id="twitter").items():
       try:
           friendsOfUser=user.screen_name
       except tweepy.TweepError:
            time.sleep(60 * 15)
            continue
Comment: @MarkoPolo, no, exception is raised by `tweepy.Cursor(api.friends, id="twitter")`. Check the update
Answer: To avoid this you can add a timeout after every request. I am using a script that allows only 15 requests every 15 minutes, so I am making a single request every minute with maximizing the data.
for page in tweepy.Cursor(api.followers, screen_name=user_name, wait_on_rate_limit=True, count=200).pages():
try:
    followers.extend(page)
    print("-->", len(followers))
    if len(followers) % 100 == 0:
        save_followers_to_csv(user_name, followers)
    time.sleep(60)
except tweepy.TweepError as e:
    print("Going to sleep:", e)
    time.sleep(60)


Calculating expected number of failures using the CDF and SF

Question: Using a simple model, I have produced an output distribution as
<code>rv = scipy.stats.johnsonsu(1.874, 2.324, 52.633, 1.097)
</code>
If this is a manufacturing setting, and my lower spec limit is 45 and upper spec limit is 55, I want to know the expected failure rates (x < 45 or x > 55). I can check the cumulative density function and the survival function, respectively, to perform each of the single tailed tests:
<code>>>> rv.cdf(45)
1.035e-05
>>> rv.sf(55)
3.564e-08
</code>
Since this random variable represents an independent draw during manufacturing, if I assemble 1e6 units, should I expect none of them will be larger than 55 but 10 will be less than 45?
Comment: Why are you doing this? Where did you get those parameters?
Comment: I want to understand the expected failure rates for the given distribution and the upper/lower limits. Those parameters came from fitting that distribution to a histogram of data. That data was produced by doing a monte carlo simulation of a simple polynomial model with random variable inputs.
Comment: Well, I think you're doing it right.
Answer: If you believe your fitted distribution has negligible error, then you're right. You could be more precise about the phrasing: the number less than 45 is approximately Poisson with expectation about 10.
If you have no guarantee that your fitted distribution is correct, then you could be completely wrong, especially if your fitting procedure focuses on the bulk of the data at the expense of accuracy in the tails. An alternative would be to retain only extreme observations and fit some type of extreme value distribution to them. This would neglect potentially useful information from more typical samples, but it would be easier to understand the uncertainty in your estimates if you focus on how many examples you have of extreme behavior (or how few).


Returning a array from a void * argument in a function

Question: I have a variadic function that takes at least 3 arguments, and is of the form
foo(void* ret_val, int mode, int num_params, ...)

The general use of the variadic function foo() can involve returning different data types as well as an arbitrary number of input arguments that can have various data types, but I am unable to find a way of returning an array.
How can I return an array?
The function definition is that the first argument returns an arbitrary type depending on the function invoked by foo(), mode is the mode of operation, and num_params is the number of additional input parameters, which can be zero. There is a switch statement inside foo() which depending on mode, can invoke one or more functions, and can return a value of an arbitrary type.
As a simplified example, suppose I have the following 3 functions that are invoked by foo():
void bar1(int i, int, j) {
// Do some calculations but return nothing.
}

int bar2() {
// Do some calculations and return a value.
}

int* bar(3) {
// Do some calculations with an array and return it.
}

Then in foo() I can have the following code:
foo(void* ret_val, int mode, int num_params, ...) {
  va_list args;
  va_start(args, num_params);
  switch (mode) {
  case 1: {
          int a = va_arg(args, int);
          int b = va_arg(args, int);
          bar1(a, b);
          }
          break;
  case 2: {
          int val = bar1();
          *(int*)ret_val = val;
          }
          break;
  case 3: {
          int* p = new int[10];
          p = bar3();
          // Add a loop to test out that the array has been read from bar3(), which works.
          *(int*)ret_val = *p; // <== This is where the problem is.
          }
          break;
      }
      va_end(args);
}

Then in the main program I can invoke foo() in the following way:
int x;
foo(&x, 1, 2, 10, 20); // Call bar1()

foo(&x, 2, 0);         // Call bar2()
printf("%d\n", x);

int xd[10];            // Declare and initialize xd.
for (int i = 0; i < 10; i++) {
    xd[i] = 0;
}
foo(xd, 3, 0)          // Call bar3()
for (int i = 0; i < 10; i++) {
    printf("%d %d\n", i, xd[i]);
}

I put in the calls for bar1() and bar2() for context, and they work. For bar1() two ints are provided, but nothing is returned, and a dummy output argument has to be provided. For bar2() no input values are given, but an output int is returned, which is cast to star(int star) which works and is returned correctly.
However, for bar3() internally I generate a 10 element array as a test, which is correctly returned inside foo() from the print statement, but I am unable to return the array to main(). I have fiddled around with various statements involving pointers, but either a list of zeros is returned if the array is initialized, or garbage if it is not.
How can I return an array correctly?
Comment: This is not C; C does not have a `new` operator as in `new int[10];`. Are you writing in C or C++?
Comment: Change `int xd[10];` to `int *xd;` and call to be `foo(&xd, 3, 0)`. Also need `*(int*)ret_val = *p;` to be `*(int**)ret_val = p;` (assuming `bar3` returns an `int *`.
Comment: In `foo(xd, 3, 0)`, do you want `foo` to fill in an array that is passed to it by way of the first argument or do you want it to return a pointer to an array it has allocated by putting a pointer to the first element of that array in `xd`?
Comment: How is this function supposed to be invoked exactly? What is `ret_val` supposed to point to?
Comment: @kaylum: That is insufficient. Then they are passing an `int **` as a `void *` but accessing it in `foo` as an `int *`.
Comment: `int* p = new int[10]; p = bar3();` That doesn't make sense. The second statement throws away the memory allocated by the first. Did you mean to either pass `p` into `bar3` or have `bar3` return a newly allocated array?
Comment: Honestly and don't get me wrong, but it seems you've made a hash/hack trying things out in C++.  I know what your proposed "solution" is, but what was the original problem, where you had to resort to writing code this way?  Just having a glance at what you're trying to accomplish, C++ function objects and/or templates would have been the method I would have initially chosen to use.
Comment: I changed from C to C++. I don't know of any other language that would handle this code.
Comment: Even [this quick and dirty implementation](http://coliru.stacked-crooked.com/a/eba288c485ad84f2) is not the best, but at the very least, it works, the interface for the client is simple (no need to specify the number of arguments, just the mode), and there is no need for varargs.  I am going by the use-case you posted.
Answer: In this call
foo(xd, 3, 0)

the array designator xd is converted to pointer to its first element and the function deals with a copy of this value.
Within the function this statement
*(int*)ret_val = *p;

just changes the first element of the array xd with the value of the first element of the array pointed to by the pointer p.
Arrays do not have the copy assignment operator. You can not assign one array to another as for example
int a[10] = { /*...*/ };
int b[10] = { /*...*/ };

a = b;

So this code snippet
      int* p = new int[10];
      p = bar3();
      // Add a loop to test out that the array has been read from bar3(), which works.
      *(int*)ret_val = *p;

does not make a sense. Moreover it seems there is a memory leak because at first the pointer p was assigned with the address of the allocated memory
  int* p = new int[10];

and then reassigned with the value returned by the function bar3.
  p = bar3();

Answer: You can write foo as shown below (in C, as this question was originally tagged). Comments show how to think about ret_val. Note that the interface for bar3 has been changed.
/*  ret_val is a pointer to some type T, a "T *", that has been converted to
    "void *".  To use it, we convert it back to its original type "T *".
*/
foo(void *ret_val, int mode, int num_params, ...)
{
    va_list args;
    va_start(args, num_params);

    switch (mode)
    {
        case 1:
        {
            //  T is void.  Nothing is returned via ret_val.
            int a = va_arg(args, int);
            int b = va_arg(args, int);
            bar1(a, b);
        }
        break;

        case 2:
        {
            /*  We will return an int, so T is an int, and we convert ret_val
                back to "int *".
            */
            int val = bar1();

            //  Return val.
            * (int *) ret_val = val;
        }
        break;

        case 3:
        {
            /*  We will return a pointer to an int, so T is an "int *", and
                we convert ret_val back to "int **".
            int *p = malloc(10 * sizeof p);
            if (!p)
            {
                fprintf(stderr, "Error, memory allocation failed.\n");
                exit(EXIT_FAILURE);
            }

            bar3(p);

            //  Return p.
            * (int **) ret_val = p;
        }
        break;
    }

    va_end(args);
}

Then, for case 3, you can call foo with:
int *xd;
foo(&xd, 3, 0);

Comment: Sorry for messing about with the language tags. OP originally tagged it with both C and C++ and it's not C. Multilanguage tagging... :-/


Flex printjob crashes

Question: i'm trying to print data from a datagrid with the flex printjob. in the grid are about 40 lines filled with data.
However, when i try to print, the app crashes, but some pages were printed.
here is my code:
<code>protected function openPrintDialogMonth():void {
                doPrintingMonth();
        }
        protected function doPrintingMonth():void {
            var printjob2:FlexPrintJob;
            var printTemplate:printTemplate = new printTemplate();
            var printDataGrid:PrintDataGrid;

            printjob2 = new FlexPrintJob();
            if( printjob2.start() )
            {
                var currentYear:Date = new Date();

                var dataArray:Array = new Array();
                trace( "Width/Height:", printjob2.pageWidth, "/", printjob2.pageHeight );

                printDataGrid = new PrintDataGrid();
                printTemplate.width = 1368;
                printTemplate.height = 800;

                printTemplate.data = gridReport.dataProvider;
                printTemplate.editData();

                printTemplate.year = String(currentYear.getFullYear());

                printTemplate.printDataGrid.columns = gridReport.columns;
                printTemplate.printDataGrid.columnWidth = gridReport.columnWidth;
                printTemplate.printDataGrid.visible = true;
                printTemplate.printDataGrid.showHeaders = true;
                printTemplate.printDataGrid.sizeToPage = true;

                printTemplate.scaleX = 1.00;

                printTemplate.validateNow();

                this.addElement( printTemplate );

                if( !printTemplate.printDataGrid.validNextPage )
                {
                    printjob2.addObject( printTemplate,FlexPrintJobScaleType.MATCH_WIDTH);
                    this.removeElement( printTemplate );
                }
                else
                {
                    printjob2.addObject( printTemplate,FlexPrintJobScaleType.MATCH_WIDTH);
                    this.removeElement( printTemplate );

                    while( true )
                    {
                        printTemplate.printDataGrid.nextPage();
                        printjob2.addObject( printTemplate,FlexPrintJobScaleType.MATCH_WIDTH);

                        if( !printTemplate.printDataGrid.validNextPage )
                            break;
                    }
                }

                printjob2.send();
            }
        }
</code>
Comment: When the app "crashes" do any errors occur, have you verified you're using the flash player debug player in your browser.
Comment: i'm using the print function in adobe air. if the print file is longer, only some pages appear
Answer: Had the same problem today in Flash with Adobe Air. In my case I had to add the displayobject to the stage first before starting the print job. Adding it to the displaylist forces a redraw which is probably needed for the printjob.

Flex printjob crashes


Is there a term in MLB sounds like "down lacked command"?

Question: At about 1′47″ into the video linked below, it sounds like that the announcer says "Something to watch tonight is velocity, way down lacked command in his last start and he's a free agent at the end of the year." There are 3 parts in there, the part before "way down", the part after "and" and the part in between.
I understand "way" usually means "very much", so what does "down lacked command" mean? Does "his last start" refer to the first inning of his last game?
The link begins at 1′42″.
Answer: You're parsing the English incorrectly. It should be more like:

Something to watch tonight is velocity: way down, lacked command in his last start

i.e.

The velocity of his pitches was significantly lower in his last start than typically.
He had little control (ability to pitch strikes rather than balls) in his last start.
Comment: Correct. Even he is removed immediately after that pitch, he is still the starter, and any other pitches are coming into the game in relief. There aren't many (if any) rules that distinguish between a starter and a relief pitcher, though; the distinction is mostly relevant in determining how various statistics are calculated. For example, a starter can only earn a win if he pitches at least 5 innings.
Comment: Thank you. Btw, does "his last start" refer to the first inning of his last game?
Comment: Add that into the question and I'll add it into the answer :-)
Comment: Updated, thank you so much!
Comment: "Last start" just refers to the last game he started, without any particular reference to the inning or innings in that game.
Comment: @chepner Thank you. Does "started a game" mean the pitcher threw the first pitch of that game?


A limit of an integral of a quotient related to fractional Sobolev space

Question: Let $0<\alpha<1$ and $1\leq p<\infty$. Suppose $f\in L^p(\mathbb{R}^n)$ satisfies
\begin{align}
\int_{\mathbb{R}^n}\int_{\mathbb{R}^n}\frac{|f(x)-f(y)|^p}{|x-y|^{n+\alpha p}}dxdy<\infty
\end{align}
Is it true that
\begin{align}
\int_{B(0,r)}\frac{|f(x+h)-f(x)|^p}{|h|^{n+\alpha p}}dh\to 0\qquad\text{as}\qquad r\to 0
\end{align}
for a.e. $x\in\mathbb{R}^n$?
Since this is an integration over the ball $B(0,r)$ (of radius $r$), at first I tried to look at Lebesgue-Besicovitch differentiation theorem, but the theorem actually involves the average (i.e. we need to take care of $|B(0,r)|^{-1}$ too). Now I have no idea where to start.
Any hint, comment and answer are greatly appreciated.
Comment: Are you sure that shouldn't be $|f(x+h) - f(x)|^p$ instead of $|f(x+h)-f(h)|^p$ in your second integral?
Comment: ( The first condition is saying that a Gagliardo seminorm is finite, i.e. $f\in W^{\alpha,p}(\mathbb R^n)$, c.f. e.g. https://arxiv.org/pdf/1104.4345.pdf )
Comment: @RobertIsrael Sorry, my fault, you are right. The question is now edited.
Comment: @CalvinKhor Yeah I'm aware of that. In fact I encounter this problem when studying the $W^{\alpha,p}$ norm. But i'm still not sure how is that related to my question.
Answer: Writing $y = x+h$, this is
$$ \int_{\mathbb R^n} \int_{\mathbb R^n} \frac{|f(x+h) - f(x)|^p}{|h|^{n+\alpha p}}\; dx \; dh < \infty$$
Therefore for a.e. $x$ we have
$$ \int_{\mathbb R^n} \frac{|f(x+h) - f(x)|^p}{|h|^{n+\alpha p}}\; dh < \infty $$
Now use Dominated Convergence.


Serving static files on subpage causes 404 everywhere in nginx

Question: I have a Docker container with Nginx serving a static SPA website at /.
Here's the full configuration (/etc/nginx/conf.d/default.conf):
server {
    listen       80;
    server_name  localhost;

    location / {
        root   /usr/share/nginx/html;
        try_files $uri $uri/ /index.html;
    }

    error_page   500 502 503 504  /50x.html;
    location = /50x.html {
        root   /usr/share/nginx/html;
    }
}

Now, I need to change that the application is not served on / but on /app (no root at all for now). This seemed trivial so I've changed location / { to location /app/ {, but it doesn't work and now I get 404 for both / and /app/.
The new config file looks like below:
server {
    listen       80;
    server_name  localhost;

    location /app/ {
        root   /usr/share/nginx/html;
        try_files $uri $uri/ /index.html;
    }

    error_page   500 502 503 504  /50x.html;
    location = /50x.html {
        root   /usr/share/nginx/html;
    }
}

Only small change but nothing works now. What am I doing wrong?
Edit: Server logs:
2022/06/30 12:57:29 [error] 31#31: *1 open() "/etc/nginx/html/app" failed (2: No such file or directory), client: 172.17.0.1, server: localhost, request: "GET /app HTTP/1.1", host: "localhost:8000"
172.17.0.1 - - [30/Jun/2022:12:57:29 +0000] "GET /app HTTP/1.1" 404 555 "-" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/126.96.36.199 Safari/537.36" "-"
2022/06/30 12:57:29 [error] 31#31: *1 open() "/etc/nginx/html/favicon.ico" failed (2: No such file or directory), client: 172.17.0.1, server: localhost, request: "GET /favicon.ico HTTP/1.1", host: "localhost:8000", referrer: "http://localhost:8000/app"
172.17.0.1 - - [30/Jun/2022:12:57:29 +0000] "GET /favicon.ico HTTP/1.1" 404 555 "http://localhost:8000/app" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/18.104.22.168 Safari/537.36" "-"
2022/06/30 12:57:30 [error] 31#31: *1 open() "/etc/nginx/html/app" failed (2: No such file or directory), client: 172.17.0.1, server: localhost, request: "GET /app HTTP/1.1", host: "localhost:8000"
172.17.0.1 - - [30/Jun/2022:12:57:30 +0000] "GET /app HTTP/1.1" 404 555 "-" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/220.127.116.11 Safari/537.36" "-"
2022/06/30 12:57:30 [error] 31#31: *1 open() "/etc/nginx/html/favicon.ico" failed (2: No such file or directory), client: 172.17.0.1, server: localhost, request: "GET /favicon.ico HTTP/1.1", host: "localhost:8000", referrer: "http://localhost:8000/app"
172.17.0.1 - - [30/Jun/2022:12:57:30 +0000] "GET /favicon.ico HTTP/1.1" 404 555 "http://localhost:8000/app" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/126.96.36.199 Safari/537.36" "-"

In the logs I see that it tries to get the app from /etc/nginx/html instead of /usr/share/nginx/html. I have the root property set to /usr/share/nginx/html, why it tries to get these files from /etc? If I move my site to /etc/nginx/html it works.
Comment: The problem is that nginx also needs to redirect to `index.html` in case of 404, as the web application should handle 404 errors. This is the only configuration that works for me if you have better then post it as an answer. I've tried your solution and I must've doing something wrong as it didn't work.
Comment: what does the development Mode of the browser say, which path is used and furthermore, provide logs
Comment: @djdomi - updated with the server logs
Comment: What exactly your SPA is? What technology is it built upon? And no, serving something under an URI prefix isn't trivial in any way, and may require you to change your web app settings or rebuild it completely.
Comment: @IvanShatsky - I'm aware of the required changes. I meant that changing the webserver setting should be trivial in this case. For the app, you can assume that it is just a single HTML page with no CSS / JS - just a static page.
Comment: Ok, then at least 1) put your app at the `/usr/share/nginx/html/app` directory; 2) change your `try_files` directive to `try_files $uri $uri/ /app/index.html;` (most likely `try_files $uri /app/index.html;``$uri/` should be enough). You app assets should be referred using relative links (e.g. `assets/style.css` or `./assets/style.css` instead of `/assets/style.css`) or use an URI prefix (e.g. `/app/assets/style.css`).
Comment: @IvanShatsky - I've found the solution and answered the question. The solution was different from your suggestion, you may take a look if you're curious.
Comment: The most worse solution I ever seen. If you don't want to put your app under the `/usr/share/nginx/html/app` folder (and nginx will automatically redirect `/app` to `/app/`), you can add that redirect manually (`location = /app { return 301 /app/; }` Never use regexes when you can avoid them.
Answer: I solved the problem, had to slightly change the configuration:
server {
    listen       80;
    server_name  localhost;

    root   /usr/share/nginx/html;

    location /app/ {
        alias /usr/share/nginx/html;
                try_files $uri $uri/ /index.html =404;
    }

    location ~ ^/app(.*) {
                root /usr/share/nginx/html;
                try_files $1 $1/ /index.html =404;
        }

    error_page   500 502 503 504  /50x.html;
    location = /50x.html {
        root   /usr/share/nginx/html;
    }
}

First - I needed the root attribute on the top level, then the index.html was loaded fine, but everything else (like favicon.png) was also returned with the content of index.html, therefore the second location with ~ ^/app(.*). I suspect that there should be better solution for it, but this one works well for me.


Value not passing properly in javascript function while iterator using $.each() function

Question: I am returning array of object called "categories" from the Ajax call and then i am replacing its object(category) value in the string(categoriesList). Then i am replacing this string in the html div Area as  $("#divAreaName").html("StringName");
For proper understanding the code is shown below:
$.each(categories,function(index,category){
    categoriesList = categoriesList +
    "
"+
        ""+
    "
"+
    "
"+
        "
"+
            ""+category.name+""+
        "
"+
    "
";
});

Then i am replacing the string in the div area using the following line of code
$("#divName").html(categoriesList);

However the problem is when category.name is "Fruits and Vegetable". The HTML is formed as shown below:

Can someone let me know why the values are not getting passed properly and the possible solution?
Comment: Add the `categories` array in question
Comment: What will be the possible solution of it?
Comment: I think your `"<img onclick=dispProductCategoryWise(` is missing an opening quote for the value of the onclick attribute, also, whats the semicolon after the onclick attribute
Answer: Ive only used $('selector').each(fn) to do something for each matched jquery element
Perhaps try using categories.forEach(function(category, index){ ...
Comment: I had used $.each(categories,function(index,category){ }); and it is iterating to each object of the arraylist. The problem lies at the time of substituting the value of the object.
Comment: Even  though i will try your approach too and get back to you
Answer: Interesting problem, it seems the spaces are strangely converted when using .html(). As if the '/" itself are rendered. console.log gives correct string as well.
As an alternative, create an event on that specific image using a dynamically generated id.
Like so:
categories = {
        "category":{
            "name": "Fruits and Vegetables",
            "id": 1,
        }
    }

    $.each(categories,function(index,category){
        categoriesList =
        "
"+
            ""+
        "
"+
        "
"+
            "
"+
                ""+category.name+""+
            "
"+
        "
";
        $("#myDiv").html(categoriesList);
        //Added event.
        $('#specific_'+index).click(function() {
            return displayProductCategoryWise(category.name, category.id);
        });
    });

    function displayProductCategoryWise(name, id) {
        alert(name);
        alert(id);
    }

Answer: Are you turning the quote makes into special characters..... add a blackslash ()
Something like :
\"

Comment: Actually it's even worse


is it a security concern to run web and app containers in the same namespace in OpenShift?

Question: What will be the issue by running web containers and app containers in a same namespace in OpenShift? Is it a security no-no or to just keep and web and app layers separately?
IMO, OpenShift is pretty secure and running both web and app containers in the same namespace should not be a concern. But how others are viewing this?
What are the pros and cons? What is the best practice?
Comment: Namespaces are a way to have a logical group of applications...in any way. Maybe you are a software factory and you have multiple SaaS systems....then you can have you namespaces of projects, named after every one of you apps......or maybe you want to group for tennant, or by app type, like frontends apps and backend apps....there is no silver bullet, just the way that makes sense to you should be the right one
Answer: Namespaces don't really provide any significant security benefits. Most of the security rules and policies you can enforce, such as  NetworkPolicies, can just as easily be built with selectors as with namespaces. I'm sure there are some extreme edge advantages to having separate namespaces, but I don't see it as a common factor in making the decision.
As Hackerman mentions, namespaces are about logical grouping. (And, well, namespaces, so that you don't have name collisions.)
And this isn't because "OpenShift is pretty secure". If there is some security fault with the container, there is still a security fault with the container. And there are many tools available to you in OpenShift and OpenShift Advanced Container Security to help you mitigate those faults. But namespaces aren't really one of them.
Comment: Thanks David and Hackerman for your inputs. We are continuing with a hardened Nginx image and trying the container along with other app services.


Building for Windows under Linux using Qt Creator

Question: I need to compile my Qt application for Windows while I am using Fedora 14 which have binary packages for Qt Creator MinGW. I installed all the required cross compiling packages correctly and added the path for qmake as /usr/bin/mingw32-qmake-qt4. Qt Creator can't obtain enough environment variables to setup the required toolchain.
After little digging I discovered that Qt Creator calls the specified qmake path with the parameter -query to get these variables.
I found that calling /usr/bin/mingw32-qmake-qt4 -query directly gives the error ***Unknown option -query. So I guess Qt Creator is innocent.
Then I found that /usr/bin/mingw32-qmake-qt4 is not more than a symbolic link to the generic script /usr/libexec/mingw32-scripts that uses basename $0, rpm --eval, bla bla bla.
Now I got tired. Could any body come over this before?
These are the versions of my installed packages (they are the latest as of 2011/07/06):
mingw32-binutils.i686                2.20.1-2.fc14               @updates
mingw32-cpp.i686                     4.5.0-1.fc14                @fedora
mingw32-dbus.noarch                  1.4.1-0.1.20101008git.fc14  @updates
mingw32-expat.noarch                 2.0.1-6.fc13                @fedora
mingw32-filesystem.noarch            64-2.fc14                   @updates
mingw32-gcc.i686                     4.5.0-1.fc14                @fedora
mingw32-gcc-c++.i686                 4.5.0-1.fc14                @fedora
mingw32-libjpeg.noarch               7-2.fc12                    @fedora
mingw32-libpng.noarch                1.4.3-1.fc14                @fedora
mingw32-libtiff.noarch               3.9.5-1.fc14                @updates
mingw32-pthreads.noarch              2.8.0-10.fc13               @fedora
mingw32-qt.noarch                    4.7.1-3.fc14                @updates
mingw32-qt-qmake.i686                4.7.1-2.fc14                @updates
mingw32-runtime.noarch               3.15.2-5.fc13               @fedora
mingw32-sqlite.noarch                3.6.22-1.fc13               @fedora
mingw32-w32api.noarch                3.14-1.fc14                 @fedora
mingw32-zlib.noarch                  1.2.5-1.fc14                @fedora
qt.i686                              1:4.7.2-8.fc14              @updates
qt-assistant.i686                    1:4.7.2-8.fc14              @updates
qt-creator.i686                      2.1.0-4.rc1.fc14            @updates
qt-demos.i686                        1:4.7.2-8.fc14              @updates
qt-devel.i686                        1:4.7.2-8.fc14              @updates
qt-examples.i686                     1:4.7.2-8.fc14              @updates
qt-mysql.i686                        1:4.7.2-8.fc14              @updates
qt-webkit.i686                       1:4.7.2-8.fc14              @updates
qt-x11.i686                          1:4.7.2-8.fc14              @updates

I forgot to say that I prefer using the binary packages provided by Fedora repos over locally built libraries or tools
Answer: I took a quick look at what's happening on my Fedora 15 installation.
mingw32-qmake-qt4 is a shallow wrapper that basically just invokes qmake -spec win32-g++-cross $0. Now, if you call mingw32-qmake-qt4 -query, both the -spec and -query options get passed down to qmake. Qmake however is stupid enough to NOT accept these two options together and gives you the error message.
I suppose it might be possible to fix it by replacing the mingw32-qmake wrapper script with a proper executable that has the -spec option hardcoded. That way, it would become unnecessary to use the -spec option and you'd get a working -query option.
You might want to write to the Fedora MinGW mailing list, maybe someone over there has a better idea how to solve this.
Comment: Thanks for your answer. Actually I did it by using the normal  with qmake-qt4 -spec fedora-win32-cross but stackoverflow prevented me to add my answer that time.


Java proper parsing

Question: I m finding the best way to parse hand written data into objects.
Lets say I have an interface called IEvent.
Lets say I have two class EventNewPlayer and EventUpdateTime which both implements the interface IEvent
The class EventNewPlayer requires 2 integers and one string. Lets say position X and Y and the name of the player
The class EventUpdateTime only requires one argument: the time.
I would like to make as create as much events as I want, from a hand written file
The file would look like this:
NEWPLAYER, 4, 2, joe
NEWPLAYER, 8, 9, bob
UPDATETIME, 1
NEWPLAYER, 8, 9, carl
UPDATETIME, 3

I would like to generate a list of events from this file.
Also I would like in the future to add as much event as I want.
What is the best/proper/maintenable way to do this?
Sorry about any english mistakes, English is not my first langage.
Comment: SO is not the homework resolving resource. Come here with your code attempts which have some particular problem
Comment: @IvanPronin I m not asking for code. I don't need to write code to know its not the good way to do it (splitting on "," and conditions would be really easy but dirty)
Answer: An OOP-esque way of doing this:
1) Create a base interface called StringEventFactory, and a non-static function called parseFromArray, taking a string array as argument and returning an IEvent; also create a static function called className, which returns the in-file name for each event class.
2) For each event create a corresponding ...Factory class which inherits from StringEventFactory, and implement the parseFromArray function to create an event of that type from the string array data.
3) Create a hash table, whose:

Keys are the class names stored in the text file, e.g. "NEWPLAYER" etc.
Values are the corresponding class ..Factory objects

4) For each line split it into a string array, and use the first element to fetch the StringEventFactory object from the hashtable. Pass the rest of the array to its parseFromArray function to create the event object you want
This way it is very easy to add new class specifications, without using an ugly switch statement.

EDIT: Code + slight change in specification
 interface StringEventFactory {
    public static string className();
    public IEvent parseFromArray(string[]);
 };

 class EventNewPlayerFactory implements StringEventFactory
 {
    public static string className() { return "NEWPLAYER"; }

    public IEvent parseFromArray(string[] info)
    {
        if (info.length != 4) // includes the class name
            return null;

        // sanity check
        if (!info[0].equals(className()) || info[3].isEmpty())
            return null;

        int x, y;
        try {
            x = Integer.parseInt(info[1]);
            y = Integer.parseInt(info[2]);
        }
        catch (NumberFormatException ex) {
            // notify?
            return null;
        }

        return new EventNewPlayer(x, y, info[3]);
    }
 };

 // similarly for EventUpdateTime ...

 // main body
 public static void main(string[] args)
 {
    Hashtable<string, StringEventFactory> factories = new Hashtable<string, StringEventFactory>();

    factories.put(EventNewPlayerFactory.className(), new EventNewPlayerFactory());
    // similarly for other classes

    List<IEvent> eventList = new ArrayList();

    // file parsing
    FileReader input = new FileReader(fileName);
    BufferedReader read = new BufferedReader(input);
    String line = null;

    while ((line = read.readLine()) != null)
    {
        String[] array = line.split(",");
        for (int i = 0; i < array.length; i++)
            array[i] = array[i].trim();

        // fetch the factory class
        StringEventFactory fact = factories.get(array[0]);
        if (fact == null) {
            // class name does not exist
            continue;
        }

        StringEvent out = fact.parseFromArray(array);
        if (out == null) {
            // parameters were incorrect!
            continue;
        }

        // success! add to list
        eventList.add(out);
    }
 }

Sorry if it doesn't work straight out of the bag and has syntax errors, my Java is slightly rusty, but the gist is hopefully what you want.
Answer: Given a data array of
String[] data = { "ObjA,0,0,Bob", "ObjB,0" };

And an Enum defined as
public enum MyEnum {

    ObjA, ObjB;
}

I would use something like:
for ( String line : data ) {

    Object obj;

    String[] parts = line.split(",");

    switch(MyEnum.valueOf(parts[0])) {

        case ObjA:
            obj = new ObjectOfTypeA(parts);
            break;

        case ObjB:
            obj = new ObjectOfTypeB(parts);
            break;
    }

Each object could then handle their own arguments:
public ObjectOfTypeA(String[] params) {

    x = params[1];
    y = params[2];
    name = params[3];
}

And
public ObjectOfTypeB(String[] params) {

    ticks = params[1];
}

For every new object you create, you will be required to add it to the Enum list, the switch case, and then obviously the creation of the class itself.
Answer: I can suggest you to use Finite State Machine. It is simple and flexible for maintenance. You can add different handlers in future.
Here is my example for XML parsing - https://github.com/kurkov/XMLParser
But you can make something similar for text file parsing.

Java proper parsing


Identifying and understanding algorithm of random number generation

Question: Studying different ways to generate random numbers according to a distribution and the below algorithm describes the "box method". A search on Google led to the Box-Mueller method. Are they related? Also, what would be a simple implementation of this algorithm for $f(x)=\sin{(x)}$ on $[0,\pi]$? Is it correct that $y$ should be scaled to $[0,1]$?

We generate two random numbers $x$ and $y$. We scale $x$ so that it
  gives a random point in the restricted range we want to generate random numbers in. Now we scale
  $y$ so it matches the range from 0 to the maximum value of the function $f(x)$ we want to generate.
  Now we accept $x$ if $y < f(x)$ and reject $x$ otherwise.

Implementation example:
#include <math.h>

int main(){

double x = (double)rand();
double y = (double)rand();

double xs = fmod(x,pi);
double ys = fmod(y,1);

if(ys < sin(xs)) return sin(xs);

}

Answer: First of all $f(x)$ needs to be a density, so $\sin(x)$ doesn't do the job. Let's sample from standard normal distribution, i.e. $$f(x)=\frac{1}{\sqrt{2\pi}}e^{-x^2/2}$$ in the range $[-3,3]$, where most of the samples reside.
A note for your C code: You shouldn't return the number from main function. Either write to a file or print out for plotting (or directly plot if you have suitable libraries). Most random samplers give you uniform RVs in $[0,1]$, so let's assume we have such $X,Y$. You can achieve that in C by dividing the generated number with INT_MAX macro.
First we scale $X$ to our new range, i.e. $X\leftarrow6X-3$. Now, our $X$ is uniform in the range $[-3,3]$. Also, $\max f(x)=1/\sqrt{2\pi}$, and therefore let $Y\leftarrow \sqrt{2\pi}Y$. Then, we compare $Y$ and $f(X)$ and accept the scaled $X$ if $Y$ is smaller. Here is an example C code:
#include <stdio.h>
#include <math.h>
#include <stdlib.h>
#include <time.h>
#include <limits.h>

int main()
{
    srand(time(NULL));

    int N = 100000;
    for(int i = 0; i < N; i++){
        double x = ((double) rand()) / INT_MAX;
        double y = ((double) rand()) / INT_MAX;

        x = 6 * x - 3;
        y = y / sqrt(2*M_PI);

        if( y < 1/sqrt(2*M_PI) * exp(-x*x/2) )
            printf("%f\n", x);
    }

    return 0;
}

If you redirect the standard output to a file, via > opearator while running, you'll see a histogram as follows:

Now, why does it work?
By sampling $X$ within $[a,b]$ (i.e. the interested range) and $Y$ within $[0,f_{max}]$, you create a box in the x-y plane, and sample random points on it as follows, just like you're throwing darts to a rectangular window:

Then, you accept the points which are under the curve, i.e. $y<f(x)$, which actually makes up the histogram for you, i.e. the higher $f(x)$ in the region, the higher the probability of acceptance.


Route53 propagation time with ISPs not respecting TTL

Question: I have latency based DNS rules in AWS Route53 (with TTL set up to 60 seconds) pointing to AWS NLB located in various regions. I would like to have a possibility of redirecting traffic to other regions modifying Route53 rules and to be sure DNS failover policy will work for all clients.
I've heard that even though Route53 propagation time is fairly ok, it might not be respected by various Internet Service Providers doing their own caching and/or simply ignoring my TTL rules (even up to couple of days).
Is that statement true? Given the fact I need to make sure my routing changes should be propagated within 15m am I safe with using Route53, or should I implement mechanism allowing my client app to obtain my server address dynamically (rather than changing routing).
Answer: DNS propagation does not exist, it is incorrect terminology as DNS is not top down, but just governed by caches renewing their entries based on TTLs on records (and other more complicated rules, like DNSSEC RRSIG expirations, DNS Negative TTL, etc.)
In theory the TTL gives the maximum amount of time a cache can keep the entry.
So a cache is theoretically free to do things before it, hence kind of lowering it.
In theory again, a cache should honor it and not increase it.
In practice it is known that some caches override the value, especially if too small. Various nameservers software have configuration option to do so.
While I do not know a definitive study on the subject, my ballpark recommendation is to stay way from TTL lowers than 5 minutes because otherwise you have a risk of some caches not honoring it. Others sources are more optimistic than me and says anything above 30 (seconds) is fine. YMMV.
There is at least this study, using RIPE probes, from 2017:
https://labs.ripe.net/Members/giovane_moura/dns-ttl-violations-in-the-wild-with-ripe-atlas-2
It repeats the same sentiment: "It is publicly known that some cloud providers and CDNs override the original values provided by authoritative servers within their networks." based on this result in the study: "We have seen in Table 2 that 4.17% of the resolvers will actually increase the TTL value of our RRs in this measurement."
For further debug you will need to give more details on the specific caches where you see a behavior contradictory to your TTL configuration and you (and/or your clients) might want to try contacting their administrator to see if their rules can be changed (very low probability for that to succeed, but if you do not even try to contact them, absolute zero probability that things will change).
Comment: @Than I added a link to a study. Also you will probably need to monitor things closely (finding clients "clinching" to old IPs where they should have switched) and just architecture things as if TTLs will always work as is but take into account some sources may disregard them and make sure the resst of the system continue to work (routing to a less "favorable" IP). You may also want to look at anycast that can provide solutions for "local" routing without having to rely on the DNS.
Comment: "Clients will be mobile devices, so you can expect every possible ISP provider." Or maybe not.... browsers are more and more doing DoH at least on desktop and often hardcoded to 184.108.40.206 or things like that so you might wish to see how that one reacts to your DNS setup. As for mobile, I think I have read Android implements DoT, and there are "DNS VPNs" so to speak, like the app described on https://126.96.36.199/ (yes, again :-()
Comment: Clients will be mobile devices, so you can expect every possible ISP provider. Right now I don't see that behaviour so cannot say anything, for now it's just research before choosing solution. However it seems that your answer mean that indeed I cannot rely on Route53 routing in case I require fast propagation times.


Load balancing and HA with Nginx

Question: Preface: I'm trying to implement Blue-Green Deployment.
With the following nginx.conf:
http {

    upstream backend {
        keepalive_timeout               65;

        server django_blue:8000 fail_timeout=5s max_fails=1;
        server django_green:8000 fail_timeout=5s max_fails=1;
    }

    server {
        listen 80 default_server;

        location / {
            proxy_pass              http://backend;
            proxy_redirect          off;
            proxy_set_header        Host $http_host;
            proxy_set_header        X-Real-IP $remote_addr;
            proxy_set_header        X-Forwarded-For $proxy_add_x_forwarded_for;
            proxy_set_header        X-Forwarded-Host $host;
            proxy_set_header        X-Forwarded-Proto https;
            proxy_read_timeout      2s;
            client_max_body_size    20m;
        }
    }
}

If django_blue and django_green are both up & running all is working well: nginx does correctly LB in Roundrobin.

If I shutdown one of them - say django_green and then go on Chrome to do a web request, if the round robin gives the shutted down server, django_green, it waits for 1 minute (exactly 60 secs) and then reply to the browser with 504 Gateway Error.

So I've two questions:

why it waits 1 mins and not fail_timeout value?
why it don't simply reply with the another available server in upstream directive?
Answer: I just figured it out, that's a proxy_connect_timeout issue.
So I've just added:
proxy_connect_timeout   2s;
to location / {} block
Comment: Make sure to mark this as the accepted answer if it solves your issue.
Comment: Check out nginxconfig.io for all of your future config needs.

Load balancing and HA with Nginx


TypeError: morphSearch.querySelector(...) is null

Question: Can anyone resolve my problem with my code ( i just discovered it from debug mode )

This is not all of the code that I have, it's long so I just put the first lines of it.
In debug mode I get this error :

TypeError: morphSearch.querySelector(...) is null

Here is the generated markup: http://pastebin.com/P6tfvcZS
Is there a solution for this issue ?
Comment: Would probably help to provide the HTML and a bit more code. Would need to verify an element exists with the id = morphsearch.
Comment: `.querySelector()` returns `null` if the element does not exist (at least the `document.querySelector()` works so)
Comment: dear @WhiteHat
this is my php page
http://pastebin.com/P6tfvcZS
Comment: What does the actual HTML look like? Not the PHP but the output which is send to and interpreted by the browser.
Comment: @Andreas this is how it looks like on HTML !

http://pastebin.com/P6tfvcZS

thank you so much for yous assistance
Comment: The script should work and the HTML/Javascript in the pastebin link does not throw the mentioned error. Instead it fails on `morphSearch.querySelector('button[type="submit"]').addEventListener('click'` because there is no `button` in the markup. If this is fixed then there is still the missing `classie`. If this will also be fixed the script should work as intended. http://jsfiddle.net/bnjwjpsL/
Answer: found this...
var offsets = morphsearch.getBoundingClientRect();

morphSearch is the wrong case, I'm thinking it should be...
var offsets = morphSearch.getBoundingClientRect();

I also separated your var statements. The last one looked like this...
isOpen = isAnimating = false,

I don't think that's valid, try it like this.
  var morphSearch = document.getElementById( 'morphsearch' );
  var input = morphSearch.querySelector( 'input.morphsearch-input' );
  var ctrlClose = morphSearch.querySelector( 'span.morphsearch-close' );
  var isOpen = false;
  var isAnimating = false;

Those querySelector's appear to be working...
Actually, a side from the above, I think I found the only querySelector that wasn't working.
Try changing this...
morphSearch.querySelector( 'button[type="submit"]' ).addEventListener( 'click', function(ev) { ev.preventDefault(); } );

To...
morphSearch.querySelector( 'input.morphsearch-submit' ).addEventListener( 'click', function(ev) { ev.preventDefault(); } );

All that should do it.
Comment: i tried your advice but still same error ! ( i use this code on my wordpress theme )


Snake lemma for $R$-modules. Help with $\ker$ maps, not connecting hom.

Question: In Construction of the maps they say that the construction of the kernel/cokernel maps comes from the commutativity of the diagram:
$$
\require{AMScd}
\begin{CD}
& & A @>{f}>> B @>{g}>>C @>>> 0 \\
& @VV{a}V & @VV{b}V & @VV{c}V \\
0 @>>> A' @>{f'}>> B' @>{g'}>> C' \\
\end{CD}
$$
Define $\hat{f} = f\mid_{\ker a}$.  I want to show that $\hat{f}(A) \subset \ker b$.  So that $\ker a \xrightarrow{\hat{f}} \ker b$ exists.
Let $x \in \ker{a}$, then $b\hat{f}(x) = bf(x) = f'a(x) = 0$ so that $f(x) \in \ker b$.  Next, if $\hat{g}$ is defined similarly, then I want to show exactness or $\ker \hat{g} = \text{im} \hat{f}$. First, $\ker \hat{g} \supset \text{im} \hat{f}$ or $\hat{g}\hat{f} = 0$.
I don't see how to show this.
We know that $\ker g = \text{im} f$ so that $\ker g \cap \ker b = \text{im}f \cap \ker b \supset \text{im} \hat{f}$...
Answer: The inclusion of $\mathrm{ker} c$ into $C$ is a monomorphism, so $\hat g\hat f=0$ because $gf=0$.


How to import csv file into mysql using codeigniter

Question: I want to import csv into mysql using codeigniter.
This is my source code.
view
<?php $this->load->view("admin/v_header");?>
<?php $this->load->view("admin/v_top_menu");?>
<?php $this->load->view("admin/v_sidebar");?>

Import Data Dosen

    <?php $this->load->view("admin/v_alert_msg");?>

    <form class="form-horizontal" action="<?php echo base_url();?>admin/save_dosen" method="POST" enctype="multipart/form-data">
        <fieldset>
            <legend>Import Data Dosen</legend>

                Pilih File :

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

                    <button type="submit" class="btn btn-primary">
                        Save
                    </button>

        </fieldset>
    </form>

<?php $this->load->view("admin/v_footer");?>

library
<?php

error_reporting(0);

    class Csv_impot {

        var $csvfile, $delimitatore, $nometable;
        var $_FIELD;

        function csv_import($cf = "", $del = "", $nt = "") {
            $this->csvfile = $cf;
            $this->delimitatore = $del;
            $this->nometable = $nt;
        }

        function export() {
            $csvhandle = file($this->csvfile);
            $field = explode($this->delimitatore, $csvhandle[0]);
            $kolom = "";
            foreach ($field as $array_kolom) {
                $kolom.="`" . trim($array_kolom) . "`,";
            }
            $kolom = trim(substr($kolom, 0, -1));
            //echo $kolom;
            for ($i = 1; $i <= count($csvhandle); $i++) {
                $valori = explode($this->delimitatore, $csvhandle[$i]);
                $values = "";
                foreach ($valori as $val) {
                    $val = trim($val);
                    if (eregi("NULL", $val) == 0)
                        $values.="'" . addslashes($val) . "',";
                    else
                        $values.="NULL,";
                }
                $values = trim(substr($values, 0, -1));
                $query = "INSERT INTO " . $this->nometable . "(" . $kolom . ") values(" . trim($values) . ");";
                $QUERY[$i] = $query;
            }
            return $QUERY;
        }

    }

controller
function import_dosen()
    {
        $this->data['title']="Import Data Dosen";
        $this->load->view("admin/v_import_dosen",  $this->data);

    }
    function save_dosen()
    {

        if(isset($_FILES['csv_dosen']['name']))
        {
            $csv_dosen=$_FILES['csv_dosen']['name'];
            $handle = fopen($csv_dosen,"r");
            $this->load->library('csv_import');
            $csv=new csv_import(".$handle.",",","dosen");
            $query=$csv->export();
            $this->m_dosen->eksekusi($query);
//            $check_file=  explode(".", $csv_dosen);
//            if(strtolower($check_file[1])=="csv")
//            {
//                $csv_dosen=$_FILES['csv_dosen']['temp_name'];
//                $handle = fopen($csv_dosen,"r");
//                while (($data = fgetcsv($handle, 1000,",")) !== FALSE)
//                {
//                    echo "haha";
//                }
//            }
//            else{echo "bukan file csv";}
            //$handle = fopen($csv_dosen,"r");
            //$csv_dosen_type=$_FILES['csv_dosen']['type'];
            //$csv_dosen_size=$_FILES['csv_dosen']['size'];
        }
        //echo $handle;
    }

models
<?php
class M_dosen extends CI_model
{
    function __contruct()
    {
        parent::__construct();
    }

    function eksekusi($query)
    {
    //echo "
";
    //echo count($query);
        for($i=1;$i<count($query);$i++)
        {
            $this->db->query($query[$i]);
            //echo $query[$i];
            //echo "
"
        }
    }
}
?>

when I run this code, an erro display that  [function.fopen]: failed to open stream: No such file or directory.
How I solved this promblem?
I hope you can help to solve this problem.
Thanks.
Comment: what is this `".$handle."`?
Comment: $handle is a variable that to catch of location of the csv file in my directory.
Comment: what is the need for `. .` here?
Comment: oh, I'm sorry ".$handle." must be $handle :)
Comment: no, an erro display that [function.fopen]: failed to open stream: No such file or directory.
Comment: then print the path of your file. try to debug it yourself. Check path, permission etc..
Comment: when I print $csv_dosen, it is get the name file of csv. ex: dosen.csv
Comment: and the directory of the file doesn't include.
Comment: did you try my solution?
Comment: yes, but can't read data of csv file. I think, I must get the path/location of csv file. when I send with manual path/location, it is run.
Answer: As per your library, you have to pass file name to your Csv_impot  constructor. But you are passing file Handler.
so change your code as below.
//general oops method:
$csv=new csv_import($csv_dosen,",","dosen");

//In CI,
 $this->load->library('csv_import',array($csv_dosen,",","dosen")); // no need to create object again. Array of values will be parameter for constructor.

Comment: an error display that Non-existent class: Csv_import


Drupal 7 Calendar - How do you modify link from day number?

Question:
When I click on the day number, it currently goes through to day page.  I'd like to customise this to go to a specific event page for that day.
I can't find a hook for this.  Is there one?
Answer: The day page is generated by the day display of the view generated by the calendar module. You can customize this display as much as as you want - add header, footer, embed an attachment view, or otherwise enhance it:

You can disable the day display if you don't want the links at all.
Replacing it with another page would be much harder, but it might be possible using the panels module.
Answer: U need to customize it.
Firstly you need to put a alter in your template.php
<code>function themename_preprocess_calendar_datebox(&$vars) {
  $date = $vars['date'];
  $view = $vars['view'];
  $day_path = calendar_granularity_path($view, 'day');
  $vars['url'] = 'events-and-attractions/events/' . $date;
  $vars['link'] = !empty($day_path) ?l($vars['day'],$vars['url']):$vars['day'];
}
</code>
Create a view page that list the events , with a contextual filter of event start date. And provide that view path in  $vars['url'].


Problemas ao tentar salvar dados vindos do formulário

Question: Não estou conseguindo pela página HTML inserir o nome e salvar. Alguém poderia explicar o quê está acontecendo?
@Entity
public class Livro {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;

    private String nome;

    @ManyToMany
    private List<Autor> autor;

    @ManyToOne
    private Professor professor;

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getNome() {
        return nome;
    }

    public void setNome(String nome) {
        this.nome = nome;
    }
}

Meu controller:
@Controller
@RequestMapping("/livros")
public class LivroController {

    @Autowired
    private Livros livros;

    @RequestMapping("/novo")
    public ModelAndView novo(){

    return new ModelAndView("Livro");
    }

    @RequestMapping(method = RequestMethod.POST)
    public ModelAndView salvar(Livro livro){
    ModelAndView mv= new ModelAndView("Livro");
    livros.save(livro);

    return mv;
}

Página HTML:

<form action="from-horizontal" method="POST" th:action="@{/livros/novo}" th:object="${livros}">

Casastro de professor

      Matricula:

         <input type="text" class="from-control"   id="nome"  th:value="*{nome}"/>

         <button type="submit" class="btn btn-default">Sign in</button>

</form>

Erro:

Caused by: org.attoparser.ParseException: Exception evaluating
  SpringEL expression: "nome" (template: "Livro" - line 31, col 54)

não entendo esse erro.
Documentação do thymeleaf:
<input type="text" id="datePlanted" name="datePlanted" th:value="*{datePlanted}"

Answer: No seu HTML, tente inserir a tag name, segue exemplo:

     <input type="text" class="from-control" id="nome" name="nome" th:value="*{nome}"/>

Outro detalhe, tente debugar na linha:
livros.save(livro);

E verifique se o objeto livro está com o nome preenchido.
Answer: Você não adicionou a atributo name como mencionado pelo @Isaias, outra forma de preencher as informações de um input é utilizando o th:field
Faça assim:

<form action="from-horizontal" method="POST" th:action="@{/livros/novo}" th:object="${livros}">

Casastro de professor

      Matricula:

         <input type="text" class="from-control"  th:field="*{nome}"/>

         <button type="submit" class="btn btn-default">Sign in</button>

</form>

O Thymeleaf vai se encarregar de criar os atributos necessários com o campo informado, dessa forma não precisa se preocupar com os atributos id, name e value, serão criados automaticamente


Como enviar informaçoes por POST local para servidor externo?

Question: Estou desenvolvendo uma aplicação que necessita estar em um servidor local e preciso enviar algumas informações para um servidor externo, de que maneira devo fazer?
Comment: Pode dar mais detalhes ?
Comment: Então amigo, a minha aplicação usa o Arduino e devido a isso o Arduino deve ficar conectado ao servidor, a aplicação possui um sistema de login, se o usuário esquecer a senha eu devo enviar um email com a nova senha, tentei enviar o email localmente com o PHPMailer mas não funcionou então minha ideia foi para mandar por POST as informações para que o servidor externo consiga enviar o email
Comment: Pode criar um Webservice no servidor externo e utilizar ele no Arduino.
Comment: Hmm, muito obrigado.
Answer: Para fazer um post a um servidor externo, use o curl:
<code>$ch = curl_init();

curl_setopt($ch, CURLOPT_URL,            'http://www.exemplo.com.br');
curl_setopt($ch, CURLOPT_POSTFIELDS,     http_build_query(array('login' => 'abc', 'senha' => '1234')));
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST,           true);

$consulta = curl_exec($ch);
curl_close($ch);
</code>


Why Indian cricketers don't play in foreign leagues?

Question: In T20 leagues like BBL, BPL and like, many players from other countries participate whereas Indian players do not. So, what is the reasoning behind this?
Players like Murali Kartik have played in County cricket.
Speculating that the players earn enough and don't need to go anywhere else
but this might not be the sole reason.
Answer: This is a decision by the BCCI. For any player anywhere in the world to play in a foreign tournament, they need a No Objection Certificate (NOC) from their home board, and the BCCI have refused all NOC applications for Indian players to play in foreign T20 tournaments. Cricinfo wrote a good article on this in 2012 and I believe the gist of the details there remain the same today.
Answer: BCCI does not want players to play in other leagues, they do not have time for other leagues as well. Beside there is permission required from BCCI for all domestic and international players. They can even ban players who play conflicting leagues for BCCI. Remember ICL(Indian Cricket League)
Comment: There's a big difference between the ICL (a directly competing league deliberately outside the authority of the BCCI / ICC) and say the Big Bash League (an authorised T20 league being run by Cricket Australia, another ICC member). *Any* cricketer that played in the ICL was going to be banned from any ICC cricket, not just Indian ones.
Answer: Quoting First Post:

The BCCI imposes this restriction not just on its international
  players but also on domestic players, apparently in a bid to
  protecting their domestic tournaments, but their real intention is to
  safeguard the novelty and hence revenue of its cash cow, the IPL. BCCI
  thinks if Indian audience gets to see their cricketers play in other
  tournaments, the interest in IPL will diminish. Adopting such a
  protectionist model in the age of free markets is terribly myopic. If
  a cricket league prospers anywhere in the world, BCCI prospers from
  it.  As home to legions of fans, cricket's win will always be India's
  win. BCCI has in the past claimed that it's a nonprofit organization.
  As custodians of Indian cricket, it's incumbent on them to give their
  fans a chance to see their favorite cricketers play in leagues other
  than the IPL.

But for a change, the Board of Control for Cricket in India (BCCI) has finally thrown open the doors for India's women cricketers to participate in international leagues across the world.
The move was announced on the 1st of June during a meeting of the Women's Cricket Committee in Mumbai.
Answer: As Philip Kendall Said in his answer, BCCI have refused all NOC applications for Indian players to play in foreign T20 tournaments Source. But many articles speculate few other reasons for this like,

Board of Control for Cricket in India (BCCI) wants their players to feature in domestic competitions which take place at the same time in December and January.
BCCI is also keen to give their senior players a breather, as the cricketers play a number of international matches in a calendar year.
BCCI thinks if Indian audience gets to see their cricketers play in other tournaments, the interest in IPL will diminish.
Board officials say that they don't want a situation like West Indies to emerge in India where most of their top cricketers are busy playing T20 cricket by ignoring the national team.
BCCI thinks that if players are allowed to play in foreign leagues, it will dilute the IPL's brand (i.e; to protect IPL's revenue).

References:

Why Indians don't play in foreign T20 tournaments
Hope Indian players could play BBL in the future: Adam Gilchrist
Big Bash League: India skipper MS Dhoni open to playing in BBL
BCCI's refusal to allow Indian cricketers in foreign leagues depriving team of T20 specialists
Will BCCI allow Indians to play in away leagues?
Will BCCI allow Indian players to participate in global leagues?
Answer: I think Indian players do not play in other countries leagues like BBL, BigBash, NatWest T20 Blast, PSL etc. because of several reasons:

BCCI does not allow them.
Busy Schedule due to International matches.
Some players like Virat Kohli and MS Dhoni have a very high status. They prefer not to play in such a small league.

But in some conditions, Indian players prefer foreign league. For example, Kohli recently confirmed that he would play in a county match in England because he didn't play well in past India tour of England.


Foreign key entity framework asp.net mvc

Question: Tenho Minha Tabela Conserto e ConsertoDetalhes e estou recebendo a seguinte msg quando tento atualizar minha migration:
"A introdução da restrição FOREIGN KEY 'FK_dbo.ConsertoDetalhes_dbo.Pecas_PecasId'
na tabela 'ConsertoDetalhes' pode causar ciclos ou vários caminhos em cascata. Especifique ON DELETE NO ACTION ou ON UPDATE NO ACTION,
 ou modifique outras restrições FOREIGN KEY.
Não foi possível criar a restrição ou o índice. Consulte os erros anteriores."
<code>    public class Conserto
{
    [Key]
    public int Id { get; set; }

    public DateTime DataEntrada { get; set; }
    public string NomeCliente { get; set; }
    public string NomeFuncionario { get; set; }
    public string NomePeca {get;set;}
    public string DescricaoDefeito { get; set; }
    public string DescricaoSolucao { get; set; }
    public decimal ValorMaoObra { get; set; }
    public decimal ValorTotalConserto { get; set; }
    public int PecasId { get; set; }
    public int ClienteId { get; set; }
    public int FuncionarioId { get; set; }

    [ForeignKey("PecasId")]
    public virtual Pecas Pecas { get; set; }

    [ForeignKey("ClienteId")]
    public virtual Cliente Cliente { get; set; }

    [ForeignKey("FuncionarioId")]
    public virtual Funcionario Funcionario { get; set; }

}
</code>
ConserDetalhes
<code>    public class ConsertoDetalhes
{
    [Key]
    public int Id { get; set; }

    public int ConsertoId { get; set; }
    public int PecasId { get; set; }
    public decimal Total { get; set; }

    [ForeignKey("ConsertoId")]
    public virtual Conserto  Conserto { get; set; }

    [ForeignKey("PecasId")]
    public virtual Pecas Pecas { get; set; }
}
</code>
Comment: você mesmo que montou esse modelo ? você precisar mesmo dos ( public int PecasId { get; set; } ... public int ClienteId { get; set; } ...  public int FuncionarioId { get; set; } ... e criar  public virtual Pecas Pecas { get; set; } ?
Comment: sim porque quando estou criando, eu preciso ter acesso a lista de peças,funcionario e cliente.
Answer: Você está colocando ForeignKey "PecasId" nas duas classes (que já estão relacionadas)por isto o migration está reclamando de referência circular, remova de uma das classes preferencialmente da classe Conserto.
Comment: O problema que se eu remover do conserto eu não vou ter acesso a lista de peça.
Comment: Pelo detalhamento da classe Conserto você não consegue? Já que exite uma relação entre as duas.
Comment: Quando estou na View Criar ordem de servico eu preciso ter acesso a lista de peças,lista de cliente e lista de funcionarios. Em ConsertoDetalhes eu preciso ter acesso também a lista de Id das Peças e o id do Conserto, então eu preciso de FK em ambos para ter acesso ao que preciso


Firebase function not returning value

Question: I am trying to do some operations using oncall function where,
I am first checking if user exists in database, then if he exists then do some operations like updating the DB.
well the function is working as expected and updating the DB as well, but its returning response as null so I can't tell what exactly happening.
exports.populateCart = functions.https.onCall((data, context) => {
    const user = context.auth.uid;

    DB.collection('users').doc(user).get().then((usr_resp) => {
        if (usr_resp.exists) {
            DB.collection('products').doc(data.productKey).get().then((prod_res) => {
                DB.collection('carts').add({
                    //some data
                }).then(() => {
                    return {
                        response: 'CART UPDATED'
                    };
                }).catch((carts_err) => {
                    return {
                        response: 'ERROR WHILE POPULATING CART : ' + carts_err
                    }
                });
            }).catch((prod_err) => {
                return {
                    response: 'ERROR WHILE FETCHING PRODUCT : ' + prod_err
                };
            });
        }
        else {
            return {
                response: 'USER DOES NOT EXISTS OR USER NOT AUTHENTICATED'
            };
        }
    }).catch((usr_err) => {
        return {
            response: 'ERROR WHILE FETCHING USER : ' + usr_err
        };
    });
});

There is one more similar question on stack overflow, where the solution is proposed to use,
reject(err);
resolve(lists);

methods, Please if the solution is using above methods, then please explain the use cases of this method in detail and if there are more methods like this please explain them as well.
Firebase function not returning data
Answer: You are not returning your promise. (see line 3 below)
exports.populateCart = functions.https.onCall((data, context) => {
    const user = context.auth.uid;
    // add return here before Db.collection()
    return DB.collection('users').doc(user).get().then((usr_resp) => {
        if (usr_resp.exists) {
            return DB.collection('products').doc(data.productKey).get().then((prod_res) => {
              return  DB.collection('carts').add({
                    //some data
                }).then(() => {
                    return {
                        response: 'CART UPDATED'
                    };
                }).catch((carts_err) => {
                    return {
                        response: 'ERROR WHILE POPULATING CART : ' + carts_err
                    }
                });
            }).catch((prod_err) => {
                return {
                    response: 'ERROR WHILE FETCHING PRODUCT : ' + prod_err
                };
            });
        }
        else {
            return {
                response: 'USER DOES NOT EXISTS OR USER NOT AUTHENTICATED'
            };
        }
    }).catch((usr_err) => {
        return {
            response: 'ERROR WHILE FETCHING USER : ' + usr_err
        };
    });
});

Comment: can you elaborate ?
Comment: I commented line 3, you need to return the promise.
Comment: add return at `DB.collection('carts')`  as well as  DB.collection('collections')also, just make sure u return all the promises.
Comment: This is the problem of using chain promises. If it's complicated then you need to learn how to use async/await instead.
Comment: Yes I was aware of the issue, of using chain promise, and using await and async calls, but I forgot the syntaxes
Answer: You need to return every promise that you are running:
exports.populateCart = functions.https.onCall((data, context) => {
    const user = context.auth.uid;

    return DB.collection('users').doc(user).get().then((usr_resp) => {
        if (usr_resp.exists) {
            return DB.collection('products').doc(data.productKey).get().then((prod_res) => {
                return DB.collection('carts').add({
                    //some data
                }).then(() => {
                    return {
                        response: 'CART UPDATED'
                    };
                }).catch((carts_err) => {
                    return {
                        response: 'ERROR WHILE POPULATING CART : ' + carts_err
                    }
                });
            }).catch((prod_err) => {
                return {
                    response: 'ERROR WHILE FETCHING PRODUCT : ' + prod_err
                };
            });
        }
        else {
            return {
                response: 'USER DOES NOT EXISTS OR USER NOT AUTHENTICATED'
            };
        }
    }).catch((usr_err) => {
        return {
            response: 'ERROR WHILE FETCHING USER : ' + usr_err
        };
    });
});

Try copying the above code. Also using async functions will make it look better like this:
exports.populateCart = functions.https.onCall(async (data, context) => {
  try {
    const usr_resp = await DB.collection('users').doc(user).get()
    if (!usr_resp.exists) throw new Error("USER DOES NOT EXISTS OR USER NOT AUTHENTICATED")
    const prod_res = await DB.collection('products').doc(data.productKey).get()
    await DB.collection('carts').add({ . someData . })
    return { response: "Cart Updated" }
  } catch (e) {
    console.log(e)
    return { response: e }
  }
});

Firebase function not returning value


How does the bluetooth a2dp profile work?

Question: I want to create a bluetooth music player application which streams audio from one device to another. I have read everything on the android developers page about bluetooth and I found that a profile called a2dp has been specifically created for audio streaming. However not much has been provided on how to use it. I have also gone through the bluetooth chat example but i have been unable to figure out how to actually send audio and how to receive it. I have also read that a2dp sink functionality has been added as of android 5.0.
After spending hours on stackoverflow I see numerous questions asking the same thing but without any satisfactory answer.
My main questions are-

How does the bluetooth a2dp profile work?
Are there better methods to implement audio streaming between
android devices apart from a2dp?

Any help would be greatly appreciated.
Answer: You can read the AVDTP core specification to know what happens during an a2dp connection.
But if you want to know about the working of it in terms of coding, I suggest you go through this blog which I found useful.


Looping in Abletons session view without click (no global quantisation)

Question: I want to do make loops in Ableton live session view and use two tracks.
Because of creativity reasons, I don't want to be bound to the metronome, so I switched it off the global launch quantisation.
Now I record the first track,
and I can loop it perfectly.
Then, I record the second track, which wont have to same length like the first track because quantisation is off, and it's very unlikely that I hit the record button just in time.
It looks like this:

One note: the tempo is set to 120 bpm, but as metronome and quantisation is off, that does not effect the music. The 10+ and the 6+ and the bottom of the tracks just indicate the relative length of the tracks with 120 bpm as a reference.
When I press stop and play the following think happens:
The fist loop is perfectly aligned, and it sounds like it should sound.
But with the second loop, problems occur:
As the Track 2 is shorter than Track 1, it starts early.
Result: The Music is out of sync.
That can be seen here:

So what I am looking for:
A solution that starts Track 2 everytime, when I start track 1.
So that track 2 "waits" for track 1 to be finished before restarting.
I was thinking of the "follow actions", but coundn't figure it out.
Any ideas to keep me in sync are very welcome!
Edit:
My end-goal is to loop voices, and I love the session view, so my idea is to record e.g. 5 different voices without beat during recording.
Then, I would like to enable/disable voices with MidiPads.
And I would prefer a solution, where I dont have to use my computer keys for adjustment :)
Here is a photo of the setup:
Comment: Sounds like you want an actual looper pedal or something that mimics one. Try Ableton's Looper device. By the way, Ableton is spelled Ab Le Ton.
Comment: Yess, that is the idea! Thanks, I will try this out. And now I am able to spell it correct ;)
Answer: Thanks for asking this!
You don't need follow actions, that's not going to help you for this purpose. For your purpose, there are two things I want to point out.
First, how do I get both clips to start at the same time?

Instead of clicking the play buttons next to the clips, try the play button on the Master track at the far right end of your session view. That play button will simultaneously trigger all the clips for that "scene" (another word for rows in session view)

Second, how do I get the length of loop 2 to be the same as loop 1, so they don't de-synchronize?

You can do this simply by changing the loop length in the clip. Select the clip, then in the clip view (might have to toggle to this view using the tabs in the lower-right if it doesn't automatically show up when you click the clip) change the length and loop durations to be the same as loop 1. So if loop 1 has length/loop of 4.0.0 (4 bars) then loop 2 should also have length/loop of 4.0.0

Basically, the reason they're going out of sync is because the clips are not the same length. You would run into the same issue using a looper pedal, the issue is actually with your timing. To resolve this, you can try setting the loop/length of each clip as soon as they're created and sticking to that, or just improving your timing by counting out loud as you play, "one ee and uh, two ee and uh, three ee and uh, four ee and uh" etc -- and make sure your loops all start and end on the same beat, usually the "one."
Alternatively, you can loop as a fraction of the total loop length -- e.g. if loop 1 is 4 bars, you can record loop 2 as a 1 bar loop, then it will play four times through for each time through loop 1. But these must be an exact ratio for it to work -- if loop 1 is 4 bars and loop 2 is 2 bars 1 beat, they will go out of sync very quickly. :)
If you need further clarification, I can add some screenshots when I get home. Hopefully this helps you!
Comment: Thanks for taking so much time for writing an answer, I got your idea and you dont have to do the screenshots ;)
That brings me closer to what I want do to, but I am not there jet.
I am looking more for a hands-away-from-laptop-solution, so adjusting the track lengths manually is not an option. Also the counting is not feasable, as my loops will be quite short.
To specify my problem a little more, I add a photo of my setup in the end of my question. I keep your question unaccepted to see if other people have other ideas, but I really appreciate your sharing of ideas.
Comment: Of course! I'm glad my suggestions helped. If you truly want hands-off-laptop, a looper pedal might be your best option. I've heard you can simulate one using a sustain pedal and MIDI mapping in Ableton, but never done that myself. A decent entry looper like the TC Electronics Ditto isn't too expensive, so maybe demo one at your local music store and see if that fits your idea. As far as counting the rhythm, you should **always** be doing that, even if you're not looping. It's the best way to maintain a consistent tempo.
Comment: Cool! I already have a looper, but I want to use some abelton effects, so I use this.
Hmm, my next idea is to write a python script that remembers the length of the first loop in scene 1 and then triggers all other scenes to sync. Would be hacky, but interesting problem
Comment: I wish you the best of luck with your solution. Bear in mind that simply starting the loops at the same time is only half the battle. If loop 1 is 10 bars and loop 2 is 6 bars, your script will need to stop loop 2 after 6 bars, wait 4 bars, then start it again. Otherwise loop 2 would start again on bar 7, when loop 1 is only 70% done. This is why I encourage counting beats and simply leaving that space at the end of your loop. But, your solution might work too!
Comment: The second half of the battle can be solved with follow up actions and very long empty loops somewhere down the scene they lead to.
But I must say, I think I will just stay with the beat, I thought there would be a simple solution


Literally 'writing' on a page

Question: Has anyone got any ideas on how I could make literal writing on a page, like on PowerPoint the user can write over the presentation?
I understand that placing a div 1px square could do the job, but thought that this could lead to messy code (as well as a lot of it!)
Thanks in advance for any ideas.
EDIT: I can't use canvas as the rest of the project won't support it, unless somehow canvas can be made transparent and put with a higher zIndex than the rest of the document.
Comment: I believe that literal writing would involve a sharpie and a monitor.
Comment: re: Edit, canvas backgrounds, AFAIK, are transparent by default.
Comment: If, on the other hand, you are asking how to do virtual writing on top of a web page, look into Canvas.
Comment: SVG would be a better solution if you want the HTML behind it to be also interactable.
Comment: What do you mean by 'literal writing'?
Comment: The Canvas element is well suited for this, but I takes some code to accomplish this.  SVG could be another option.
Comment: Where the user can click and drag and it draws a line, curve etc. where they dragged the mouse across
Comment: @StorySystems - The background of `canvas` is always transparent by default.
Comment: Are you using HTML5? What about the `contenteditable` attribute? http://html5doctor.com/the-contenteditable-attribute/
Answer: You can take a look at canvas or svg. That will do the job.
Answer: If you want to write on a web page it's possible to use the property contenteditable="true"
Reference
Answer: This is what I would do:
http://jsfiddle.net/DerekL/DqZX8/
function drawingArea(ele) {
    var width = ele.scrollWidth,
        height = ele.scrollHeight,
        area = $("<svg>").attr({
            width: width,
            height: height,
            class: "draw"
        }).appendTo(ele),
        tracking = false;

    var mDown = false,
        id, line;

    $(window).mousedown(function (e) {
        if (tracking) {
            mDown = true;
            id = Date.now();
            line = $("<path>").appendTo(area).attr({
                d: [
                    "M",
                    e.clientX + ele.scrollLeft,
                    e.clientY + ele.scrollTop
                ].join(" "),
                id: id
            });
        }
    }).mousemove(function (e) {
        if (mDown) {
            line.attr({
                d: line.attr("d") + " " + [
                    "L",
                    e.clientX + ele.scrollLeft,
                    e.clientY + ele.scrollTop
                ].join(" ")
            });
            area[0].outerHTML = area[0].outerHTML;
            area = $("svg");
            line = area.find("#" + id);
            e.preventDefault();
            return false;
        }
    }).mouseup(function () {
        mDown = false;
    });

    return {
        area: area,
        startTrack: function () {
            tracking = true;
        },
        stopTrack: function () {
            tracking = false;
        },
        get isTracking() {
            return tracking;
        }
    };
}

var pad = new drawingArea(document.body);
pad.startTrack();

Literally 'writing' on a page


Como exibir imagem sem uma extensão pelo link direto no navegador?

Question: Exemplo - http://meusite/imagem/001
Resultado que não quero, desejo visualizar a imagem.
ÿØÿà�JFIF��H�H��ÿÛ�C�

ÿÛ�C

ÿÀ�p�"�ÿÄ������������
    ÿÄ�7����!1A"Q2a¡Bq'#3R$CbScðÿÄ�����������ÿÄ�)�������!1A"Q2a#BÿÚ���?�ù¶¨/d99ñI"s/•[0ò¹mömç_'ŒkY™å?e¬I~FŽfŒ™Nk³©àévÊ=¿"øÝãøÏÎ×GUÅüQÛ¯Ñþ  ~9ƧâÚ=/ƒÁ¦1ŽÒ93ÉÑŽs\Äÿ�Sðÿ�Œð?—†µ£³t×_Z0¹)AïG?zÙp'Ée×Ûèϳô™Uù6P–®–'65sµdÜž‰1p''%¨¶tœwÄÊš~
Ç   ð7œ c¸ëµÃqÿ�œâ·XÊø‹œè=Z

Meu servidor tem o Apache será possível usar algo parecido com AddType application/x-httpd- jpg
Comment: Acho que você devia usar `image/jpeg`.
Answer: Usando somente .htaccess talvez não seja possível, isso porque existem vários tipos de imagem e ficaria complicado adicionar o mime-type para cada uma, todavia você pode redirecionar para um php tratar isto, por exemplo:
Crie na pasta imagem um arquivo .htaccess: com este conteudo:
RewriteEngine On
RewriteRule ^ proxy_image.php?path=$0 [L]

Na mesma pasta crie um arquivo chamado proxy_image.php com o seguinte conteudo:
<?php

function mimeType($file)
{
    $mimetype = false;

    if (class_exists('finfo')) {//PHP5.4+
        $finfo     = finfo_open(FILEINFO_MIME_TYPE);
        $mimetype  = finfo_file($finfo, $file);
        finfo_close($finfo);
    } else if (function_exists('mime_content_type')) {//php5.3 ou inferiror
        $mimetype = mime_content_type($file);
    }

    return $mimetype;
}

if (empty($_GET['path'])) {
    echo 'Caminho invalido';
    exit;
}

$path = $_GET['path'];

$extensoes = array('jpeg', 'jpg', 'gif', 'png', 'ico', 'svg');

$fullPath = null;

//Busca pela primeiro arquivo que contiver a extensão (pode implementar glob também, é opicional)
foreach ($extensoes as $extensao) {
    if (is_file($path . '.' . $extensao)) {
        $fullPath = $path . '.' . $extensao;
        break;
    }
}

if ($fullPath) {
    //pega o mime-type do arquivo
    $mime = mimeType($fullPath);

    //Verifica se o mime-type é do tipo imagem
    if (strpos($mime, 'image/') === 0) {
        header('Content-Type: ' . $mime);

        readfile($path);
        exit;
    }
}

echo 'Isto não é uma imagem';
exit;

Depois basta navegar para algo como http://localhost/images/foobar, se existir uma imagem com este
Note que é possível implementar cache e usar Etag junto com este código acima, conforme usei neste exemplo da pergunta (não o da resposta):

É possível usar if-modified-since com "304 not modified" sem PHP
Answer:
Esta resposta se deve ao fato de estar com a tag [PHP] na pergunta.

Com PHP:
Você pode inserir o Header no PHP:
header('Content-type: image/png');

O tipo do documento vai variar, por isso deve definir o image/png somente para imagens são de mesmo formato, normalmente é possível identificar o formato através de sua extensão, como .png.
Portanto poderia fazer algo como:
$tipo = [
'gif' => 'image/gif',
'png' => 'image/png',
'jpeg' => 'image/jpeg',
'jpg' => 'image/jpeg'
];

$nome = 'image.png';
$extensao = strtolower(substr(strrchr($nome,"."),1));

if( isset( $tipo[$extensao] )) {
   header('Content-type: '.$tipo[$file_extension]);
}

//... { Exibe um "echo" da imagem }

Com Apache
Você pode usar o .htaccess (ou altere no httpd.conf se estiver desligado) para forçar todos os arquivos terem um mesmo content-type.
<Location /imagem>
  ForceType image/jpeg
</Location>

Isso irá fazer com que todas as requisições para /imagem saiam com o Content-type previamente definido. ;)
Mais informações sobre o ForceType pode ser vista aqui.


Save WordPress templates in theme's second subdirectory

Question: I have a WordPress page where i use a lot of different WordPress page-templates. First i saved the templates just inside the theme directory but now i want to bring some order into it.
I create the templates with:
<?php
     /*
    Template Name: Event - Overview
    */
?>

So when i save all these templates inside a subdirectory inside my theme i can select these templates for my pages. As axample i save theme inside /theme-directory/templates/template.php. But when i put them inside a second subdirectory like /theme-directory/templates/event-templates/template.php i cant select them anymore inside the WordPress Backend.
Is there a way that i can put my templates into more than just one subdirectory to bring some order into that?
Answer: Hi I have solution for you may try this, or see wordpress default themes, i have given example for twenty twenty theme.
get_template_part( 'templates/event-templates/template' );

for the file name dont use extension.
Please follow the link i given as screenshot https://prnt.sc/spe1qt
You can create as many directory as you want, that is not a problem at all