Forged FROM: header despite reject_authenticated_sender_login_mismatch

Question: structural description

Server A runs postfix and acts as smarthost for server B (also running postfix), reject_authenticated_sender_login_mismatch is set and works (almost) as expected, see below
Client C's MUA sends mails via Server A
B and C both connect via submission port and authentificate with STARTTLS

what happens when trying to forge sender

Setting an arbitrary FROM: header by changing the sender address in thunderbird or adding a new identity in roundcube leads to the expected result: the mail is declined
doing the same using mail -s "This is a Subject" -a "From: email@example.com" on Server B using A as Smarthost results in successfully sending the mail

observed differences
The following was observed by increasing the verbosity of postfix' smtpd

thunderbird and roundcube login and then directly set the FROM:to an accepted value
Server B starts in the same way but somehow manages to change the FROM: header afterwards. This cannot be seen in postfix smtpd logfile but in the mail which is finally sent:
Return-Path: <firstname.lastname@example.com>
Delivered-To: email@example.com
Received: from mail.example.com
by mail.example.com (Dovecot) with LMTP id UuV2IVaP3lvdKAAAEby5rg
for <email@example.com>; Sun, 04 Nov 2018 07:19:02 +0100
To: firstname.lastname@example.com
Subject: This is a Subject
From: firstname.lastname@example.com
MIME-Version: 1.0
Content-Type: text/plain; charset="UTF-8"
Content-Transfer-Encoding: 8bit
Message-Id: <firstname.lastname@example.com>
Date: Sun,  4 Nov 2018 07:19:02 +0100 (CET)
Authentication-Results: ORIGINATING;
    auth=pass email@example.com
email@example.com

body of your email

at least it is not (as opposed to valid mails) DKIM signed
This is not spam, I just do not want that "everybody" is able to forge sender addresses

questions

Why does this happen?
More important: What can I do to prevent it happening?
Answer: This is expected behavior, as the SMTP envelope sender and From: header are separate things. The reject_sender_login_mismatch (and the version limited to authenticated users only) prevents using an address in SMTP MAIL FROM command unless it matches an SASL authenticated owner. It doesn't care what's inside the message – that's including its headers. That's how email was designed, and there are also many legitimate reasons for this mismatch.
When using mail -a you modify the headers, alone. It's not changed afterwards, as you suggest. The only reason you can't do this with Thunderbird is that it uses the same address in both envelope and header.  It's not limited by your server.
Comment: Thunderbird does not *always* use the same address in both envelope and header. Afaik mismatches are always caused by bugs, but since those have not been resolved for years, one should not depend on Thunderbird behaving one way or another.
Comment: Aaah.That explains it a lot. Although it is not what I would have wanted to hear. Thank you very much! I would have thought this was somehow related.
Comment: This is not really a problem as the envelope sender is recorded to `Return-Path` and to the logs. If you suspect someone using this feature illegitimately (e.g. you receive abuse reports), you can always suspend their accounts.
Comment: Yes that is correct. And abuse is really improbable, as it is my private mail server. It's just sort of a cosmetic issue.
Comment: As a footnote: << As of Postfix 2.1, this is an alias for "reject_authenticated_sender_login_mismatch, reject_unauthenticated_sender_login_mismatch". >>  So Postfix admins now can handle unauthed users differently.


Scraping my index finger on frets

Question: When I shift from chord to chord I end up scraping the inside of the bottom joint of my left index finger as I move it up and down the neck. It's getting pretty raw.
A coworker says I should file down the lower corners on the frets; a friend says I should raise the action.
I have no idea what I'm doing wrong or what I should change. Can someone advise me on how to prevent this from happening?
Answer: The frets might start to rise at the ends, making it hard to avoid scraping against them. This can be made worse by dry weather. One can try to fix it by e.g. carefully work on the ends of the frets with a rubber mallet, and then file them down. While it is possible to do it yourself, I leave this kind of work to professionals. If you decide to make a go for it yourself, make sure you know what you're doing by finding some instructions.
I don't think the action on the guitar will mitigate the problem. I would get an opinion from a guitar repair professional, both what it would cost to fix, and if it's worth doing. If the guitar was cheap, buying a better one could be a better alternative.
Answer: I am in Afghanistan. This place is HORRIBLE for guitars. I have seen what happens to dry guitars. If you don't artificially humidify them they will wind up like yours, for sure. One wouldn't believe that the moisture in the guitar wood (or lack thereof) could and does make such a difference, but the prime indicator of this is the metal fret ends protruding past the fretboard as the wood shrinks. They didn't build your guitar like that, it BECAME like that from lack of moisture. I won't ask where you live or how you store your guitar but if you are in a dry environment, it's worse. If you hang your guitar up or leave it out on a stand in a dry environment, it will dry out (like a sponge).
You can revive it. Put your guitar in the case with a soaked sponge in a cup or ziplock bag with holes in it. You can buy guitar sound hole humidifiers to do the same thing. Or literally just put it in the bathroom with the shower on. As this thread is two years old, you either figured this out or your guitar is toast, literally. If you filed the fret ends and then humidified... well, just hope you didn't.
Answer: Well this could be an issue with your technique, an issue with the guitar, or both. Technique-wise, you may be pushing down a little too hard on your bar chords or putting too much pressure upwards and into the guitar. Those chords take a lot of muscle buildup, so that's understandable if that's the case. Also, you'll want to do your best to keep your fingers at a 90-degree angle to the fretboard. Obviously, this won't be perfect and it's not a strict rule, but it's good to help you keep in mind that your fingers should not be laying too flat (Except for the barring finger, of course).
Now, it sounds like you're getting small cuts from the edges of the fret wire. That will require a filing, but I'd recommend taking to a repair shop or a friend who has some repair experience if you're not sure how. See if that helps and if it doesn't, pay close attention to how your hands are moving and try to notice any unnecessary tension in how you're playing. Hope this helps and happy playing!
Answer: Since there were some wonderful technical answers already, I will provide you with a pragmatic answer: Do nothing.
Many beginning guitar players feel also sorts of discomfort when they are first learning. Common complaints are that the frets, and the strings are too sharp. Now don't get me wrong, I'm not saying that you guitar isn't misconfigured: it could very well be.
However, you may find that practicing a lot will relieve the discomfort. As you gain some dexterity and finger strength, you may find the frets no longer bother you. As an experienced guitar player, I can play even poorly set up guitars with little discomfort.
Comment: I agree there is discomfort in learning to play (I can remember playing until my un-calloused fingertips bled).  BUT - as an experienced guitar player, if I pick up a guitar with improperly dressed frets & cut my hand on the frets, I immediately stop playing that guitar.  There is normal pain associated with learning to play guitar.  But if the frets are not properly dressed and cutting a beginners finger, it is absolutely critical that the problem with the guitar be fixed.  Experienced player might be able to get away with altering technique to adapt to defects in guitar - but not beginner!
Comment: That's true, but without seeing a picture there is 0 way to tell one way or the other whether his guitar is broken.
Comment: So - since we can't rule out a broken (defective) guitar, we should not advise playing through the pain??
Comment: My answer is an alternative answer. If, it turns out his guitar is not broken, it is the correct answer. Like I said, without proof we can't know.
Comment: Yep- If it ain't broke - don't fix it.  But FIRST - be sure it ain't broke! ;)
Comment: Because I am such a novice I was really concerned that this was mostly my technique. But I didn't see anyone anywhere on the net complaining about this particular malady hitting novices, so I suspected that something strange was going on.
Comment: People express "it hurts" in various different ways.
Answer: Your guitar is dry, you need to humidify it. See my answer here for an explanation how to do this and more details. Don't file the frets, fix the problem properly and humidify your guitar. It will improve the life and the tone of your guitar.
If it is a good guitar(i.e. expensive, well made) then dressing the frets hides the problem, if it is a bad (i.e. Cheap, poorly made) guitar then it is not worth the expense.
I suspect the action (Distance between the strings and the frets) has nothing to do with your problem.
Comment: Either dry - or possibly a not so well made guitar (or both).  But I agree that if it is a really cheap guitar, might not be worth spending money on a fret dress.
Answer: If those fretwires are actually proud of the edge of the fingerboard, that guitar needs returning to the seller, assuming it was sold to you as a new guitar. No guitar should be a health hazard, as this sounds to be. Sharp fret ends shouldn't be there. Maybe it's a rogue guitar, maybe that model is how it is, but it needs returning.Leaving traces of blood may make your case more convincing...
Answer: First of all - I would like to congratulate you on beginning a journey which, if you stay the course, will lead to untold hours of pleasure, relaxation and enjoyment.  But it can be daunting and painful in the beginning. Sounds to me as if you are experiencing more than the normal and usual pain encountered by new guitar students.
Even though there are many good answers here already, I have decided to add my thoughts as another answer - rather than continue simply commenting on the other answers, - for the sake of yourself and any future visitors to this site who might have a similar problem.
And if any members of the community care to disagree or add to anything in my answer, I welcome your comments.  That's the beauty of this format.  All answers are "peer reviewed" so to speak.
First I agree with all others who have said that the action should not contribute in any way to the problem you are experiencing.  So let's rule that out as a potential solution right off the bat.
It is certainly possible that your technique could contribute to excess friction of finger against frets, but I feel it is more likely a problem with your guitar itself.
And if there is an issue with your guitar, modifying your technique to compensate for it, is not advisable in my opinion.  As a beginning student, I feel it is very important for you to be learning proper technique.  Having to adapt your technique because you are attempting to play a guitar that has a problem will not help you develop proper technique.
The only time I have personally experienced the particular problem you describe, or seen it happen to other beginning guitar students, is when the frets were protruding improperly, or not dressed (filed on the ends) properly.  I can't say for absolute certain without seeing your guitar, but from what you describe, I would be willing to bet that it is the frets causing the scraping and raw finger.
There are two reasons the ends of the frets might be sharper or protrude more than they should.  One reason could be that your guitar is mass produced by a company with less than perfect quality control and that one or more of the frets are not cut or dressed properly.
The other possibility is that the fretboard has dried (and shrunk) causing the frets to protrude.  The frets could have been fine when the guitar left the factory, but if the instrument was stored or kept in an environment with less than 45% relative humidity, the fingerboard (fretboard) could shrink as it loses moisture.  This will cause most or all of the frets (not just one or two) to protrude more than normal and scrape your fingers as you slide up and down the neck.
Or it could be a combination of both.
If you believe the protruding fret problem is solely due to lack of proper humidity, then re-hydrating your guitar may correct the problem.  Since you would need to re-hydrate the fret board, and you might be playing an electric guitar, a room humidifier will be the most effective way to re-hydrate your guitar's fretboard.  For re-hydrating, you will want to store your guitar in a room or case where you can achieve 50% humidity.  Too much is not good either.  Anything less than 40% and you will likely begin to see the problems associated with a dry guitar (such as sharp frets).
In addition to re-hydrating, a good fret board conditioning oil can be applied after your fret board is fully re-hydrated.  This will help slow down future drying.  But wait until you have completed the re-hydrating process which may take several days.  The oil can work in both directions preventing the absorption of moisture as well as the loss.  During re-hydration you WANT the fret board to absorb moisture.
If only one or two frets is sharp or protruding more than the others, your problem is more likely due to a fret or two that may need some attention. It's possible for a fret to become loose and stick up more than it should.  When that happens you will often get string buzz in addition to nicks in your index finger.  When a fret becomes loose, it will be necessary to re-set the fret.  Sometimes a guitar tech can tap the  loose fret with a hammer (with the neck properly supported), and re-seat it, but often the fret must be removed and replaced if the tang is damaged or the tech may put a bit of glue in the fret slot to hold it in place if the slot is larger than it should be. After replacing the fret, the tech should crown and polish the fret and dress the ends.  They will use a gauge or plane to insure that the height of the fret is even with the other frets.
On many of the lower priced guitars I have seen, some (or sometimes all) of the frets have not been properly cut or dressed on the ends.  You should be able to run your index (or any other) finger along the bottom edge of your fret board with your finger angled towards or even slightly touching the high e string, and feel only bumps where the fret ends are. They should be relatively smooth. If you run your finger along the edge of the fret board and it feels like one or more of the fret's are scraping or cutting your finger, you have a problem that needs attention!
Fret dressing is something that is ideally done with the correct type file and the fret end must be filed at the correct angle.  The wrong file may make the fret end feel rough and the wrong angle can either leave the ends in a finger scraping orientation or - too much of an angle can lead to the string slipping off the end of the fret.
I own over a dozen guitars presently and do most of my own set up work.  But when one of my guitars needs any type of fretwork, I take it to one of my friends who are luthiers (build and repair guitars) who have the proper tools and expertise to do it properly without damaging the guitar.
Depending on how many frets are a problem, and if it cannot be solved with re-hydrating your fret board, it could cost more to have a professional correct the problem than you want to spend - if your guitar did not cost very much to begin with.
Then you might try to sell your guitar and use the money to buy one that you can play without scraping your finger.  Or if your conscious will not allow you to sell a problem guitar, before you buy a new one, you could try filing the frets yourself - after doing a little research to learn what type file to use and what angle to shoot for.  Then if the problem is even worse or new problems arise from your attempts at DIY guitar repair, you will now have the perfect excuse to buy a new guitar.
Just be sure before you purchase another guitar, to use the index finger test described above, and if you discover sharp frets, don't buy that one!
Whatever you do, please try to get this problem solved before you do any further damage to your finger, or your technique (or worse - to your enthusiasm for learning to play).  Learning guitar has enough unavoidable pain factors without adding any that can and should be corrected.
I wish you much success as you continue your journey.

Scraping my index finger on frets


How can I move the files on unix with java?

Question: I write java in netbeans.I want to move files and create files.When I run the program on netbeans it works. Files creates and moved. But when I run program on the jar it doesnot copy or move. I give permisson jar and files for read , write. But it does not works.And I open jar with root user. how can i fix this?
this is my code to copy
package aaa;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

public class MoveFolder
{
    public   int copy(String from,String where  )
    {
        int onay=0;
        File srcFolder = new File(from);
        File destFolder = new File(where);

        //make sure source exists
        if(!srcFolder.exists()){

           System.out.println("Directory does not exist.");
            onay = -1;
          // JOptionPane.showMessageDialog(null, "Directory does not exist.");

        }else{

           try{
            copyFolder(srcFolder,destFolder);
           }catch(IOException e){
            e.printStackTrace();
                onay = -1;
           //    JOptionPane.showMessageDialog(null, "Was not Copied.");
           }
        }

        System.out.println("Done");
         return onay;
    }

    public   void copyFolder(File src, File dest)
        throws IOException{

        if(src.isDirectory()){

            //if directory not exists, create it
            if(!dest.exists()){
               dest.mkdir();
               System.out.println("Directory copied from "
                              + src + "  to " + dest);
          //          JOptionPane.showMessageDialog(null, "Directory copied from " + src + "  to " + dest);
            }

            //list all the directory contents
            String files[] = src.list();

            for (String file : files) {
               //construct the src and dest file structure
               File srcFile = new File(src, file);
               File destFile = new File(dest, file);
               //recursive copy
               copyFolder(srcFile,destFile);
            }

        }else{
            //if file, then copy it
            //Use bytes stream to support all file types

            InputStream in = new FileInputStream(src);
                OutputStream out = new FileOutputStream(dest);

                byte[] buffer = new byte[1024];

                int length;
                //copy the file content in bytes
                while ((length = in.read(buffer)) > 0){
                   out.write(buffer, 0, length);
                }

                in.close();
                out.close();
                System.out.println("File copied from " + src + " to " + dest);
         //       JOptionPane.showMessageDialog(null, "File copied from " + src + " to " + dest);
        }
    }

}

Comment: Your code does not contain a `main()` method. Please edit your question with code that recreates your exact problem so that we can help you. In particular, we need to know how you tell this class which files to copy. Also, where are those files located in your file system?
Comment: Please post the code, command you use to start your program and prints/exception you are getting.
Comment: i edited my question. it doesnt matter. I think the problem is about permissions
Comment: Add exception you are getting.
Comment: are you copying to a directory that doesn't exist?
Comment: then you need to tell us what exception did you get?
Comment: What exception ? it s work when I run it on netbeans but it not copy on jar?
Comment: the exception that is thrown when you run from jar file. if it doesn't work then it should be thown unless you consume the exception without doing anything, which is bad.
Comment: Providing [SSCCE](http://sscce.org/) could help to solve your problem!
Comment: Provide the *exception.* Not a paraphrase, or a translation, or what you think it says. The fact that you don't understand it makes you the last person who should be doing any of those things.
Comment: I edit my question and I use this class. It works on run it on netbeans butit doesnt work on jar. pls help
Comment: System.getProperty("user.dir") does not get the true path. /home/user/(missing desktop)/..
 why desktop is missing
Comment: Until you provide the actual exception this is not a real question.
Answer: Why are you copying files with IO streams? Why not just do
File f; // bla bla init
File otherFile;
f.renameTo(otherFile);

Also, you need read and write permissions on the files you're trying to move (to), not on the jars you're executing ...
Comment: Cause `renameTo` move file and not copy it.
Comment: I edit my question and I use this class. It works on run it on netbeans butit doesnt work on jar. pls help.


How to reload resources?

Question: In my 2d game i have 12 mb graphic resource.I have to reload them when my game resumes.But i have a lot of resources so reloading time is very much(around 5-6 seconds).In this time screen goes to black and i'm sure that some people think that game is broken.Also that's very bad user experience.How can solve this problem?
Answer: Simple, do a loading screen with progress bar. For good reference you can look at Where's my water after leaving the game and returning.
Comment: Okey but i can't do that.Bacause we can't load textures from different thread.So how can i create loading screen?
Comment: Don't understand the different thread comment. You can load the textures for the loading screen which are supposed to load very fast. Than load all the other textures while showing the loading for 5-6 secs. It can all happen on the same GLThread.
Comment: When i'm loading assets,screen doesn't show animations.It freezes when  it is loading assets.So a different thread is needed for that but it's not possible in that case i think.Is there a way to do that?

How to reload resources?


select count dentro do select

Question: Com a consulta abaixo esta retornando os valores total de cada mês, porém eu preciso contar a quantidades de vezes que cada item possui em cada mês.
SELECT instancia,
    (SELECT COUNT(instancia) FROM urt WHERE MONTH(ura_data) = 04) AS abril,
    (SELECT COUNT(instancia) FROM urt WHERE MONTH(ura_data) = 05) AS maio,
    (SELECT COUNT(instancia) FROM urt WHERE MONTH(ura_data) = 06) AS junho
from urt

Comment: "Cada mês" será sempre Abril, Maio e Junho ou serão todos os meses?
Answer: Você não precisa fazer múltiplas seleções para isso, basta fazer a seleção de todos os dados, agrupar por instância e somar os registros por mês:
SELECT
    instancia,
    SUM(CASE WHEN MONTH(ura_data) = 1 THEN 1 ELSE 0 END) as "Jan",
    SUM(CASE WHEN MONTH(ura_data) = 2 THEN 1 ELSE 0 END) as "Fev",
    SUM(CASE WHEN MONTH(ura_data) = 3 THEN 1 ELSE 0 END) as "Mar"
FROM urt
GROUP BY instancia;

Veja funcionando no DB-Fiddle
Como, no MySQL, o valor booleano é interpretado como 1 ou 0, podemos somar direto o resultado da comparação, sem o case when:
SELECT
    instancia,
    SUM(MONTH(ura_data) = 1) as "Jan",
    SUM(MONTH(ura_data) = 2) as "Fev",
    SUM(MONTH(ura_data) = 3) as "Mar"
FROM urt
GROUP BY instancia;

Simplificando um pouco a leitura da SQL.
Comment: Esta solução é mais eficiente do que utilizar subselects, para um volume maior de dados a diferença no tempo de execução se tornará perceptível.
Comment: Muito bom, menino Anderson
Comment: @Sorack Mestre em SQL desde que nasci xD
Comment: Show!!! muito bom
Answer: Referencia a instancia do SELECT mais externo nos subselects:
SELECT instancia,
    (SELECT COUNT(instancia) FROM urt WHERE MONTH(ura_data) = 04 AND a.instancia = instancia) AS abril,
    (SELECT COUNT(instancia) FROM urt WHERE MONTH(ura_data) = 05 AND a.instancia = instancia) AS maio,
    (SELECT COUNT(instancia) FROM urt WHERE MONTH(ura_data) = 06 AND a.instancia = instancia) AS junho
FROM urt a

Comment: Ficou show de bola!! muito obrigado, só mais uma coisa, tem como ordenar a coluna de junho de maior para menor???
Comment: Sim, use: ORDER BY 4 ASC.

select count dentro do select


Estimating potential moves in a time series relative to an other

Question: Say we have two time series which over time have a strong correlation, say above 0.8, say for example the price of oil and share price of an oil exploration and extraction company. Now say that we have a universe of oil companies exhibiting a strong correlation with oil, but we are interested in obtaining results for one of them say company A.
What we want is to have this: If the price of oil goes up by 5USD or down by 5USD how can I expect shares of company A to move? Our past data, may or may not have 5 dollar moves in oil prices.
What are some methods to look into for such a case based on your experience?
Thank you!
Answer: So we are given two time series, price of oil (O) and 'share price of an oil exploration and extraction company' that is not company A (let's call it F), whereas company A data is mixed within a group (G) of other oil companies. Do we have data for this group (that has A but not F)? Even though the given firm's data (F) is correlated to price of oil by 0.8 ($\rho_{F,O}=0.8)$, we do not know the exact value of the group (nor A)'s correlation with the commodity ($\rho_{G,O}=$'high' and so probably $\rho_{A,O}=$'high').
If you had information for A's price by itself, you could regress the price of company A's shares onto the price of oil and expect A to move $\beta_1$ dollars for every unit change in $P_{oil}$:
$$P_A = \beta_0 + \beta_{A,O} P_{O} + \epsilon$$
More directly, in terms of correlation $\rho$,
$$\beta_{A,O}= \frac{\rho_{A,O} \sigma_{A}}{\sigma_{O}}$$
just because the group has correlation $\rho_{G,O}$ with oil though, we can't expect that $\rho_{A,O} = \rho_{G,O}$. I feel that there might be a mix-up in the given data in the question, otherwise, if data for the group is available, it could be replaced as the independent variable in the regression and be used to proxy the relationship of A to oil assuming $\rho_{A,O} \approx \rho_{G,O}$. If unknown A is the firm of interest, there is not much use for the given firm F's data, unless it is also part of the group.
Comment: In my case, each company would have its own dataset. My question is essentially, Given a universe of companies correlated with oil all of which we have the time series for, I would like to see by how much company A would change when oil changes. I would like a non linear assumption, maybe if oil goes down by 1 buck then A would go down by 1.5 and if oil goes up by 1 buck then A would go up by 1. Maybe A's change would also be quadratic or exponential with respect to change in oil.


How does trigonometrical substituition work for integrating a function?

Question: I am recently learning integration and I came across trigonometrical substituition but I am confused that how is it working? For example:
For integrating
$\int \frac{1}{\sqrt{1-x^2}} dx$
We put
$x=\sin y$
as per my teacher told, we assume x and a (any constant and here in this case a=1) as sides of a right triangle and y an angle in it and then we substitute the values as per it but I am confused if we can do that then why don't we put
$x=\cos y $
I tried solving the integral substituting $x=\cos y $ but I got the answer negative.
Comment: Both $\arcsin(x)$ and $-\arccos(x)$ are antiderivatives of $\frac{1}{\sqrt{1-x^2}}$. In other words, the derivative of $\arcsin(x)$ is $\frac{1}{\sqrt{1-x^2}}$, and so is the derivative of $-\arccos(x)$. This means that $\arcsin(x)$ and $-\arccos(x)$ differ by a constant. Hence, $\arcsin(x)=-\arccos(x)+k$ for some constant $k$. As it turns out, $k=\frac{\pi}{2}$.
Comment: What answer did you get in both the cases?
Answer: If you do $x=\sin y$ and $\mathrm dx=\cos(y)\,\mathrm dy$, then $\int\frac1{\sqrt{1-x^2}}\,\mathrm dx$ becomes$$\int\frac{\cos(y)}{\sqrt{1-\sin^2(y)}}\,\mathrm dy=\int1\,\mathrm dy=y+C=\arcsin(x)+C.$$And if you do $x=\cos y$ and $\mathrm dx=-\sin(y)\,\mathrm dy$, then $\int\frac1{\sqrt{1-x^2}}\,\mathrm dx$ becomes$$-\int\frac{\sin(y)}{\sqrt{1-\cos^2(y)}}\,\mathrm dy=-\int1\,\mathrm dy=-y+C=-\arccos(x)+C.$$Since $\arcsin+\arccos$ is constant (it is equal to $\frac\pi2$), theses answers are the same.
Answer: With $x=\cos y$, you would get the answer as $-\cos^{-1}x+c$, which can be written as $-\cos^{-1}x+\frac{\pi}2+c_1$, where $c=\frac{\pi}2+c_1$. Now, $-\cos^{-1}x+\frac{\pi}2=\sin^{-1}x$, which is the same answer you would have got with $x=\sin y$ substitution.


What does this natural cancel?

Question: What does the natural in the last C in the second line cancel?

This is from Schumann's Album für die Jugend.
Since the natural is immediately followed by a sharp, which is in the key, it does not make sense to me unless it is cancelling the double sharp on the the second C in the same bar or something, but that double sharp should not affect one an octave below, afaik.
Comment: Interesting that in bar 3 there's an E#, but no courtesy natural on the E in bar 4.
Answer: It's a courtesy accidental to make extra clear that the double-sharp doesn't apply. There is sometimes confusion, especially with beginners, about whether an accidental in one octave applies to other octaves. You're correct that it's otherwise unnecessary.
The notation is included in Henle's Urtext edition, so we can suppose Schumann wrote it that way originally, particularly since there is no mention of it in the critical commentary (PDF page 6). A quick perusal of editions on IMSLP shows that the German second edition does not include the natural — just the sharp — but Clara Schumann's edition, which is considered authoritative, does.
Comment: If I were sight-reading something like this, I would really appreciate having the double sharp canceled.
Comment: It also clarifies that the notation is not an error in printing.
Answer: As Aaron states, it's a courtesy accidental. Completely unnecessary in theory, but put there to remind the reader that although the upper, earlier C is a double sharp, that one is not. However, since it's in a different octave, it would never have been affected by that x anyway - accidentals always only affect the notes in the same octave.
Given that the key signature already contains C♯ (all C notes should be C♯ unless changed), there should be no need to put anything before that lower C(♯). And, if it's a cautionary/courtesy accidental, it would help to be in parentheses - and maybe even not need the natural sign, only the sharp, telling it's reverted to 'normal' for that piece.
Comment: It should be noted that no matter what key signature, no matter what the context in the bar is, a single sharp in front of a C can never, ever mean anything else than a C sharp, so the tendency in music publishing is now to omit the natural sign. This one is probably there because Schumann wrote it that way in 1848.

What does this natural cancel?


Checking SSH failure in a script

Question: Hi what is the best way to check to see if SSH fails for whatever reason?
Can I use a IF statement ( if it fails then do something)
I'm using the ssh command in a loop and passing my hosts names form a flat file.
so I do something like:
for i in `cat /tmp/hosts` ; do ssh $i 'hostname;sudo ethtool eth1'; done

I get sometime this error or I just cannot connect
ssh: host1 Temporary failure in name resolution

I want to skip the hosts that I cannot connect to is SSH fails. What is the best way to do this? Is there a runtime error I can trap to bypass the hosts that I cannot ssh into for whatever reason, perhaps ssh is not allowed or I do not have the right password ?
Thanking you in advance
Cheers
Answer: To check if there was a problem connecting and/or running the remote command:
if ! ssh host command
then
  echo "SSH connection or remote command failed"
fi

To check if there was a problem connecting, regardless of success of the remote command (unless it happens to return status 255, which is rare):
if ssh host command; [ $? -eq 255 ]
then
  echo "SSH connection failed"
fi

Applied to your example, this would be:
for i in `cat /tmp/hosts` ;
do
  if ! ssh $i 'hostname;sudo ethtool eth1';
  then
    echo "Connection or remote command on $i failed";
  fi
done

Comment: Ok Thx "ThatOtherGuy" .. I know how to trap but in the context of the ssh command I have posted  how would I do it?  i need to use it within the same pass of this command for i in `cat /tmp/hosts` ; do ssh $i 'hostname;sudo ethtool eth1'; done
Comment: Thanks I got half way through. But I still get prompted 4 password hosts to which I do not have access to. How can I skip these hosts as well? Basically is there a way to escape the password challenged and jump to the next host?
Answer: You can check the return value that ssh gives you as originally shown here:
How to create a bash script to check the SSH connection?
$ ssh -q user@downhost exit
$ echo $?
255

$ ssh -q user@uphost exit
$ echo $?
0

EDIT - I cheated and used nc
Something like this:
#!/bin/bash
ssh_port_is_open() { nc -z ${1:?hostname} 22 > /dev/null; }

for host in `cat /tmp/hosts` ; do
    if  ssh_port_is_open $host; then
        ssh -o "BatchMode=yes" $i 'hostname; sudo ethtool eth1';
    else
        echo " $i Down"
    fi
done

Comment: Ok Thx wbt11a  .. I know how to trap but in the context of the ssh command I have posted  how would I do it?  i need to use it within the same pass of this command for i in `cat /tmp/hosts` ; do ssh $i 'hostname;sudo ethtool eth1'; done
Comment: Hi Thanks I got half way through. But I still get prompted 4 password hosts to which I do not have access to. How can I skip these hosts as well? Basically is there a way to escape the password challenged and jump to the next host?
Comment: Try the '-o "BatchMode=yes"' flag seen in example.
Comment: if [ ! ssh -o $1 ] ;
   then
     echo sshfailed
   else
     echo challenging me still
fi
Comment: hi tried that and it's failing somewhere ? Can u help ..  if [ ! ssh -o $1 ] ;
   then
     echo sshfailed
   else
     echo challenging me still
fi
Comment: if [ ! ssh -o $1 ] ;
       then
         echo sshfailed
       else
         echo challenging me still
    fi
Comment: ssh -o "BatchMode=yes"
Comment: I tried to put quote around the if statement inside the parantehsis . somehow the command is not bein interperted properly insde those brackets
Comment: It was the person beneath me who was using the ! to test functionality.
Comment: ok thx .. ur answers are  correct but not doing what I want  .. I may have to open another question to see if I get some response back

Checking SSH failure in a script


How is the many-to-one function $f(x) = \frac{1}{x-1} + \frac{2}{x-2} + \frac{3}{x-3}$ decreasing?

Question: The function $f(x) = \frac{1}{x-1} + \frac{2}{x-2} + \frac{3}{x-3}$ is many-to-one, despite it having a strictly negative derivative (the domain being $\mathbb{R} - \{1,2,3\}$).  Why is this so?  Is there any way of knowing this without actually graphing $f(x)$, which seems rather difficult?
Comment: Umm... "my book"?
Comment: @DavidG.Stork Resonance rank booster, it is a preparatory book for joint entrance advanced examination in India, I didn't think it would be well known so I didn't mention it.
Comment: You *DID* mention it... that's the problem!
Answer: When we approach $x=1$ very close from the negative direction, $x-1$ will be a very small negative value and so $\frac{1}{x-1}$ will be a very large negative value. Approaching from the other side we have $\frac{1}{x-1}$ becoming a very positive value. In fact, it can become as large or as small as you like, provided you get as close to $x=1$ as necessary.
By looking at the other terms, we see that the same thing happens at $x=2$ and $x=3$ and we see that, near each of these points, the function can attain any value we like. Therefore, there exist distinct $x$ values for which $f(x)$ is the same, and so the function is not one-to-one.

By the way, the reason we can have a function with a strictly negative derivative that isn't one-to-one is because it isn't continuous. Specifically, this function isn't continuous at the points $x=1, x=2, x=3$. Even if we remove these points from the domain as we have, we still find that our function can attain a particular value more than once without the derivative ever becoming zero or switching sign. This is because, at a certain point, the function 'blows up' to negative infinity and then magically returns again from positive infinity, so on the domain we have defined, the derivative is always negative.
Comment: The function is continuous where it's defined, see https://math.stackexchange.com/questions/1482787/can-we-talk-about-the-continuity-discontinuity-of-a-function-at-a-point-which-is/1482900#1482900
Comment: You are right—of course. But I don't think raising that issue here is going to do anyone any favours. My answer serves as a short, intuitive picture.
Answer: It's because it goes from plus infinity to minus infinity on both $(1,2)$ and $(2,3)$ (so by Intermediate value theorem it assumes every real value at least twice) which you can see by computing the appropriate limits.
Comment: Note that the function is continuous on the domain given and so the IVT applies.
Comment: The IVM demands also that the domain is an interval.
Answer: If a $C^1$-function's derivative is negative then it's decreasing on any interval where it's defined.
Answer: $f(x)=\displaystyle\sum_{k=1}^{n}f_{k}(x)$
$f_{n}(x)=\frac{n}{x-n}:n\in N^{*},x\in R-\{ n \}$
$\forall n\in N^{*},x\in R-\{ n \} :f_{n}'(x)=\frac{-n}{(x-n)^{2}}\lt 0$
$\Rightarrow \displaystyle\sum_{k=1}^{n}f_{k}(x)\lt 0$
$\forall n\in N^{*},x\in R-\{ n \} : f'(x)\lt 0$


How to adjust neural network weights for several inputs?

Question: Currently I'm working on solving the XOR problem with a homemade NN in C++. Several (worthy) people have recommended my weight adjustment formula to be:
$$
weight=weight + (error \cdot input)
.$$
That's all fine and dandy, but considering there are multiple inputs in XOR how does one decide the current input to be multiplied by the error for the new weight? Also, in the future I may need several outputs. In that case, which error do I use to find the new weight?
Comment: Did you read about how your weight update was derived?  Please show us what you understand.
Comment: The earlier formula I used was based on natureofcode.com, now I'm relatively sure it's only for perceptrons. Not adequate for MLP of course.
Answer: Remember that you can see this adjustment formula as operation of matrixes. Consider an example:
You have 2 inputs and 3 neurons on input layer. For each connection between input and neuron, we have a weight. So, in this case we could have a matrix of weights 3x2. We know that our input is 1x2, therefore our error matrix must be 3x1. This sounds a little bit strange because error for a single output (in XOR example) is scalar.
Then, in your formula this is not the absolute error, this could be called the gradient (if you're implementing a MLP), which is calculated by:
$\delta_i^L(n) = f'_k(x_i^L(n)) \cdot e_i^L(n)$ , L as the output layer
$\delta_i^k(n) = f'_k(x_i^k(n)) \cdot \sum_1^{k+1}weight_{ij}(n) \cdot \delta_i^{k+1}(n)$,  if k is not the output layer L.
Notations: Consider $f_k'$ as the derivate of activation function of the refered layer $k$. Consider $e_i^L$ as absolute error ($desired - observated$). Consider $x_i^k$ as each $i$ input of $k$ layer.
Obs: If you're not implementing MLP, please search for the "equivalent".
Finally, your weight adjustment could be realize with your formula using matrixes' point of view of the data to help NN to "decide" with whom each input and neurons is interacting. These approach is valid for multiple outputs as well.
Comment: Good Stuff. I'm a bit new to this so I wasn't sure I would get a reply, so thanks Adelson. This should clear up some of my code.


filter by taxonomy term = taxonomy term of referencing nodes

Question: I have a node type 'hotels'. These nodes have a reference to a vocabulary 'regions' and a field 'hotel_images'.
And I have a node type 'region_page' with also the reference to the vocabulary 'regions'. In these nodes I integrate a view with images of the field 'hotel_images'.
This view should be filtered by the 'regions'.
In case the node (type: region_page) is set to term 'xy' of the vocabulary 'regions' - only images of hotels for which the term 'xy' is also set should be displayed.
How can I do this?
Answer: If there is no specific requirement to use taxonomy terms to create the relationship between 'hotels' nodes and 'region_page' nodes, I recommend to use the Entity reference module instead.
In your use case, you likely want to attach an Entity reference field to the 'hotels' content type, that allows the content editor to point to a node of the content type 'region_page'.
If I understand it correctly, you already have a View attached to your 'region_page' content types' display. Assuming you're using the EVA: Entity Views Attachment module, you should add Content: Nid as your contextual filter in the particular View, create a relationship using Entity Reference: Referencing entity and then use this relationship for outputting the field 'hotel_images'.
In this way, when viewing a 'region_page' node, the View will show all images that are stored on 'hotels' nodes that have a reference to the particular 'region_page' node.
Comment: Thank you for your help.

But yes, there's a requirement to use taxonomy terms for the relationship. This is the only common thing. Both entity types (hotels and region_page) have this taxonomy reference.

I think you didn't understand it correctly.

Hotels have images. And a taxonomy reference (regions).

There's 1 region_page per taxonomy term (a region). The region_page has also the reference to the taxonomy 'regions'. The region_page should display the images of all the hotels in the region.
Comment: Personally, if there is only one 'region_page' node for each taxonomy term, I would still use the Entity reference module in order to create a relation from 'hotels' nodes to 'region_page' nodes. Please, if I do not understand your question correctly, do let me know! However, I've created a local test setup and used taxonomy terms to create the desired situation, in my second answer I've summed up the steps to create the View that displays all 'hotel_images' that are on 'hotels' nodes having the same taxonomy term as the 'region_page' node currently being displayed.
Answer: I assume you're using the EVA: Entity Views Attachment to attach a View to your 'region_page' content types' display, that you're required to use taxonomy terms to create a relationship between your 'hotels' and 'region_page' content, and that your vocabulary is named 'Regions'.
In the View, use Content: Nid as your contextual filter and add the Content: Taxonomy terms on node as a relationship. Then, add Taxonomy term: Content using Regions as an additional relationship and mark it required. In the remainder of this answer, I assume that the identifier of this second relationship is 'field_regions'.
The 'field_regions' relationship can be selected for outputting the field 'hotel_images'. You probably want to add a filter criteria using (field_regions) Content: Type (= Hotels), to prevent the output of row(s) from the content type 'region_page' that have the same taxonomy term selected (i.e., the 'region_page' node that is currently being displayed).


Object created in js.erb file not available to .js file on page load, but is with dev tools

Question: I create an array in a filename.js.erb file. I then try to iterate through that array in a difFile.js file, but I get an error that the array is not defined. However, when I open up devtools I have full access to the array.
I've precompiled my assets (and clobbered them first just to be sure). I'm guessing this has something to do with the manner/order Rails precompiles the assets but I can't find the answer in the docs.
Your help is greatly appreciated.
Comment: Once the `filename.js.erb` file has been delivered to the client (as a normal js file, of course), how does the `difFile.js` know to do something? Do you call a function in the `difFile.js` file? If you store the array in a namespace, that might work (something like `arraySpace.array = [1,2]`). Of course, `arraySpace` has to be defined beforehand (`arraySpace = {}`) in the `difFile.js`
Comment: @RyanK Thanks for the suggestions. I tried namespacing and still got the same error. Yes, I am calling a function in my difFile.js, and would receive an error that the variable in filename.js.erb was not defined, yet when I opened up devtools and either called the variable directly or the function it worked fine. Some sort of load-order issue that I still don't fully understand. If you know a better way to do this than the answer I provided below I'm happy to change the answer to one that you provide.
Answer: All I ended up doing was copying the code from my difFile.js to the filename.js.erb file. Not so good with the separation of concerns, but it's working.


Pop up com jquery antes de fechar o navegador

Question: Galera gostaria de fazer um pop up que apareça antes que a pessoa feche a aba do navegador igual a do shoptime:
http://www.shoptime.com.br/
Não tenho muito conhecimento em Javascript, muito menos em jquery. Alguém pode me ajudar?
Comment: Seja mais especifico, eu tenho adblock e não vi nenhum pop up
Comment: O único pop up que apareceu aqui foi o de carregamento da página, sendo assim você poderia usar o método `$(document).ready()` ou método `$(window).load()`. Se for outro pop-up especifique melhor como acha-lo por favor.
Answer: Você consegue fazer esse efeito com um plugin chamado OuiBounce.

Depois de instalar o plugin e chamá-lo na página, crie uma div oculta com um id para ela, por exemplo:

Modal de Exemplo

Exemplo

Fechar

E chame um javascript para atribuir o evento do OuiBounce para essa div
var _ouibounce = ouibounce(document.getElementById('ouibounce-modal'), {
        aggressive: true,
        timer: 0,
        callback: function() {
           _ouibounce.disable();
        }
      });

  $('body').on('click', function() {
    $('#ouibounce-modal').hide();
  });
# Essa função vai fechar o modal quando eu clicar fora dele #

  $('#ouibounce-modal .modal-footer').on('click', function() {
    $('#ouibounce-modal').hide();
  });
# Essa função vai fechar o modal quando eu clicar no botão 'Fechar' #

  $('#ouibounce-modal .modal').on('click', function(e) {
    e.stopPropagation();
  });
# Essa função vai impedir o modal de ser fechado se eu clicar dentro dele #

Answer: Você pode utilizar o fancybox, veja abaixo:
$(function() {

    var content = '
Sua propaganda aqui!
';
    $.fancybox.open([{
                   type: 'inline',
                   autoScale: true,
                   minHeight: 30,
                   content: content,
                   closeBtn:true
                  }], { padding: 0 });
});


Rust cannot represent Postgres numeric type as BigDecimal type

Question: I am writing simple rust web application using actix-web and sqlx.
I have struct Book with price field which should be mapped to postgres NUMERIC type. First I got error from sqlx that it was expecting bigdecimal type and suggested to enable this feature from cargo configuration, so I did. Then I imported BigDecimal from sqlx types and tried to use this type in my struct.
use sqlx::types::BigDecimal;

But I get this error:
12 |     pub price: BigDecimal,
   |     ^^^ the trait `configuration::_::_serde::Deserialize<'_>` is not implemented for `BigDecimal`

I tried to find solution to this problem, one possible solution was to use bigdecimal crate directly with serde enabled. So I tried to use bigdecimal type instead of sqlx one:
use bigdecimal::BigDecimal;

But now I got different error:
the trait `sqlx::Type<Postgres>` is not implemented for `bigdecimal::BigDecimal`

Here is code I am using:
Book struct:
use chrono::{DateTime, Utc,};
use chrono::serde::ts_seconds;
//use sqlx::types::BigDecimal;
use bigdecimal::BigDecimal;

#[derive(serde::Deserialize)]
pub struct Book {
    pub author: String,
    pub title: String,
    pub pages: i32,
    pub price: BigDecimal,
    #[serde(with = "ts_seconds")]
    pub published_at: DateTime<Utc>
}

function that tries to insert Book data into database:
pub async fn insert_book(data: &Book, pool: &PgPool) -> Result<(), sqlx::Error> {
    sqlx::query!(
        r#"
            INSERT INTO books
            (id, author, title, pages, price, published_at)
            VALUES ($1, $2, $3, $4, $5, $6)
        "#,
        Uuid::new_v4(),
        data.author,
        data.title,
        data.pages,
        data.price,
        data.published_at
    )
        .execute(pool)
        .await
        .map_err(|e| {
            e
        })?;

    Ok(())
}

Simple POST endpoint:
#[post("/book")]
pub async fn add_new_book(data: web::Form<Book>, pool: web::Data<PgPool>) -> impl Responder {
    match insert_book(&data, &pool).await {
        Ok(_) => HttpResponse::Ok(),
        Err(e) => HttpResponse::InternalServerError()
    }
}

Cargo.toml
[dependencies]
secrecy = { version = "0.8", features = ["serde"] }
actix-web = "4.3.1"
serde = { version = "1", features = ["derive"]}
tokio = { version = "1", features = ["macros", "rt-multi-thread"] }
uuid = { version = "1.3.4", features = ["v4"] }
config = "0.11"
chrono = { version = "0.4.26", features = ["serde"] }
bigdecimal = { version = "0.2.0", features = ["serde"] }

[dependencies.sqlx]
version = "0.6.3"
default-features = false
features = [
    "runtime-actix-rustls",
    "macros",
    "postgres",
    "uuid",
    "chrono",
    "migrate",
    "bigdecimal"
]

Not sure how to fix this problem, any help will be appreciated.
Comment: What version of the bigdecimal crate did you add to your dependencies? You need to match the version that sqlx uses (for the latest sqlx, that would be bigdecimal 0.3.0).
Comment: I was using bigdecimal 0.2.0. Let me switch to 0.3.0 and try again.
Comment: Yea you are right, it works now. I guess I did not pay attention to versions. Thanks for your reply
Answer: You need to match the version of bigdecimal that sqlx uses (for sqlx 0.6.3, that would be bigdecimal 0.3.0).
It's actually a dependency of sqlx_core
Comment: I know, just posted my comment as an answer. It is a Q& **A** site, after all.
Comment: Yea problem was that I was using wrong `bigdecimal` version


Estou tentando printar o x na tela mas dá erro no data table

Question: estou tentando fazer uma tabela coloca um x no local do arquivo.
O codigo da tabela deu certo, mas quero colocar em um datatable jquery
mas ele nao esta aceitando ele tira as confg do plugin
ou da erro
o codigo da tabela é este

<!DOCTYPE html>

 <title></title>

 <link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/v/dt/dt-1.10.16/datatables.min.css"/>
    <link rel="stylesheet" type="text/css" href="estilo.css">

                <select class="custom-select" id="inputGroupSelect01" style="width: 500px;">
                <option selected>Choose...</option>
            <option value="08:00">08:00</option>
            <option value="08:30">08:30</option>
            <option value="09:00">09:00</option>
            <option value="09:30">09:30</option>
            <option value="10:00">10:00</option>
            <option value="10:30">10:30</option>
            <option value="11:00">11:00</option>
            <option value="11:30">11:30</option>
            <option value="12:00">12:00</option>
            <option value="12:30">12:30</option>
            <option value="13:00">13:00</option>
            <option value="13:30">13:30</option>
            <option value="14:00">14:00</option>
            <option value="14:30">14:30</option>
            <option value="15:00">15:00</option>
            <option value="15:30">15:30</option>
            <option value="16:00">16:00</option>
            <option value="16:30">16:30</option>
            <option value="17:00">17:00</option>
            <option value="17:30">17:30</option>
            <option value="18:00">18:00</option>
            <option value="18:30">18:30</option>
            <option value="19:00">19:00</option>
            <option value="19:30">19:30</option>
            <option value="20:00">20:00</option>
            </select>

                        Dia
                        Cliente
                        Captador

                        08:30
                        09:00
                        09:30
                        10:00
                        10:30
                        11:00
                        11:30
                        12:00
                        12:30
                        13:00
                        13:30
                        14:00
                        14:30
                        15:00
                        15:30
                        16:00
                        16:30
                        17:00
                        17:30
                        18:00
                        18:30
                        19:00
                        19:30
                        20:00

                        23
                        Joao
                        CAptador01

                  s

                        x

Comment: Sua dúvida não ficou suficientemente clara.
Comment: Por que os scripts estão duplicados?
Comment: corrigidoda para entender?
Comment: Desculpe corrigi
Comment: nao vi acabei copiando sem querer
Comment: mas esta dando para entender minha duvida
Answer: Antes gostaria de dizer que está fazendo uma mistura de jQuery com JavaScript puro desnecessária. Use apenas o jQuery nesse caso, porque além de reduzir drasticamente o código, fica muito mais fácil e eficiente de escrever, além de apropriado já que está usando um plugin jQuery (Datatables).
Primeiro você deve carregar a lib do jQuery antes de todas as libs que a usam. No seu código você está chamando o Datatables bem antes.
Outra coisa é a ausência da classe .tabela-horario que você usa no script para fazer o laço for. Essa classe deve estar na primeira tr da tabela, que de onde você irá obter os valores das ths:

           ...

No script você poderá usar o método .each apenas nas ths que tiverem o atributo aria-label, isso porque o Datatables insere a mesma quantidade de ths existentes, duplicando a quantidade.

Outra coisa é que, adicionando linhas da forma que está fazendo com .append, as mesmas não herdarão a
  formatação da tabela, porque o Datatables possui renderização própria
  no momento em que o plugin é inciado.

O que você deve fazer é usar os métodos row.add e .draw da API:
tabela.row.add( array ).draw( false );

Onde em array, cada valor da array é o conteúdo da célula, e a array deve ter o mesmo número de itens igual ao número de colunas na tabela. No caso, a tabela tem 27 colunas, logo a array deve ter 27 itens.
Outra coisa é a ordem das linhas: o Datatables por padrão lista em ordem crescente, logo o valor da primeira coluna da linha deve ser sempre maior do que a da linha anterior. Para isso usei o código:
var linha = parseInt($("#filhos tr:last td").first().text())+1;

A variável linha irá incrementar o valor para que as novas linhas fiquem sempre por último.
Agora vamos ver o código em funcionamento:

$(document).ready(function() {
   $('#example').DataTable( {
      "scrollX": true
   } );
} );

$('#inputGroupSelect01').change(function () {
  var valor = $(this).val();
  var ths = $("th[aria-label]", '.tabela-horario');
  var linha = parseInt($("#filhos tr:last td").first().text())+1;
  var colunas = [linha]; // insere o primeiro índice na array

  ths.each(function(i){
     if(i != 0){ // ignorar o primeiro índice da array
        colunas.push($(this).attr('horario') == valor ? "x" : "");
     }
  });

   var t = $('#example').DataTable();
   t.row.add( colunas ).draw( false );

});

<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/v/dt/dt-1.10.16/datatables.min.css"/>

             <select class="custom-select" id="inputGroupSelect01" style="width: 500px;">
             <option selected>Choose...</option>
         <option value="08:00">08:00</option>
         <option value="08:30">08:30</option>
         <option value="09:00">09:00</option>
         <option value="09:30">09:30</option>
         <option value="10:00">10:00</option>
         <option value="10:30">10:30</option>
         <option value="11:00">11:00</option>
         <option value="11:30">11:30</option>
         <option value="12:00">12:00</option>
         <option value="12:30">12:30</option>
         <option value="13:00">13:00</option>
         <option value="13:30">13:30</option>
         <option value="14:00">14:00</option>
         <option value="14:30">14:30</option>
         <option value="15:00">15:00</option>
         <option value="15:30">15:30</option>
         <option value="16:00">16:00</option>
         <option value="16:30">16:30</option>
         <option value="17:00">17:00</option>
         <option value="17:30">17:30</option>
         <option value="18:00">18:00</option>
         <option value="18:30">18:30</option>
         <option value="19:00">19:00</option>
         <option value="19:30">19:30</option>
         <option value="20:00">20:00</option>
         </select>

                     Dia
                     Cliente
                     Captador

                     08:30
                     09:00
                     09:30
                     10:00
                     10:30
                     11:00
                     11:30
                     12:00
                     12:30
                     13:00
                     13:30
                     14:00
                     14:30
                     15:00
                     15:30
                     16:00
                     16:30
                     17:00
                     17:30
                     18:00
                     18:30
                     19:00
                     19:30
                     20:00

                     23
                     Joao
                     CAptador01

                     x

Obs.: a tabela não possui a coluna com o horário de 8:00 que possui no select.
Comment: Brunão, eu não consegui entender nada. Mas cada pergunta deve ser feita separada, a não ser alguns detalhes que a gente até ajuda. A minha resposta resolveu o problema? Então marque ✔ e poste outra pergunta para que a comunidade possa ajudar.
Comment: muito obrigado mesmo ajudou bastante só uma duvida eu tenho um modal para eu implementar as opçoes no modal é so copiar os options e colar dentro do modal
Comment: creio que sim... tenta aí
Comment: e se eu quiser so mostrar os horarios com o X como eu faço oq eu devo usar
Comment: Como assim? Dá um exemplo.
Comment: tipo ali ele mostra das 8 as 20 mostra todos os que nao tem e os que tem  mas se eu quiser so mostrar aqueles que tem X
Comment: e o usuario possa escolher isso
Comment: blz cara fechou farei isto mas novamente muito obrigado
Comment: Blz! Ajudarei com maior prazer. Mas tenta explicar melhor para que a pergunta não seja fechada.


Non existing pages does not return 404

Question: I have a strange problem when i visit some page like this

example.com/node/386 "onmouseover=prompt(9999) "

from Drupal perspective that page doesn't exists right ?
getting something like this
Comment: The second portion of the url is parsed as Javascript in your example. I could however not reproduce this on any other Drupal site. So I guess it is not Drupal related, but a browser or module setting somehow.
Comment: @Neograph734, yes it is not happening on my other sites as well, can you guess the reason?
Comment: Could be anything, browser, server, module... If you have the same browser and server, you could try by disabling modules one by one. But I don't know if you will find it then...
Answer: I was alterting the body class array for some reason with a non safe code.
$variables['classes_array'][] = 'mysite-'.arg(0);

Now, changed to
$variables['classes_array'][] = 'mysite-'.check_plain(arg(0));

As you can see javascript gets executed as added it to dom body
check_plain

Encodes special characters in a plain-text string for display as HTML.

PHP strip_tags will work too.

(PHP 4, PHP 5) strip_tags — Strip HTML and PHP tags from a string

Hope someone finds it helpful.

Non existing pages does not return 404


Automapper null collection becomes empty

Question: Why does automapper create empty instances of collections if they are null?
Here is my configuration
public class MapperProfile : Profile
{
    protected override void Configure()
    {
        AllowNullCollections = true;
        AllowNullDestinationValues = true;
        Mapper.CreateMap<User, DAL.Models.User>();
        Mapper.CreateMap<DAL.Models.User, User>();
        Mapper.CreateMap<Role, DAL.Models.Role>();
        Mapper.CreateMap<DAL.Models.Role, Role>();
        Mapper.CreateMap<Task, DAL.Models.Task>();
        Mapper.CreateMap<DAL.Models.Task, Task>();
        Mapper.CreateMap<TaskReport, DAL.Models.TaskReport>();
        Mapper.CreateMap<DAL.Models.TaskReport, TaskReport>();
        Mapper.CreateMap<Project, DAL.Models.Project>();
        Mapper.CreateMap<DAL.Models.Project, Project>();
    }
}

My models have the same properties:
public class User
{
    public virtual List<Task> Tasks { get; set; }

    public virtual List<Role> Roles { get; set; }

    public virtual List<TaskReport> TaskReports { get; set; }
}

In my MVC project in Global.asax I'm just add my profile like this:
Mapper.AddProfile(new BL.MapperProfile());

Thanks!
Comment: How are you creating the mapping in the code?
Comment: I've modified my question. Hope it clarify it a bit
Comment: I was able to re-create the issue after your edits and have updated my answer.
Answer: Sorry, my first answer was off the mark. I was able to re-create the issue and find out what's going on.
You are getting this error because of the static call to Mapper.CreateMap method. If you change your code to just call the non static CreateMap method you should be good.
public class MapperProfile : Profile
{
    protected override void Configure()
    {
        AllowNullCollections = true;
        AllowNullDestinationValues = true;

        // calling non-static CreateMap
        CreateMap<User, DAL.Models.User>();
        CreateMap<DAL.Models.User, User>();
        CreateMap<Role, DAL.Models.Role>();
        CreateMap<DAL.Models.Role, Role>();
        CreateMap<Task, DAL.Models.Task>();
        CreateMap<DAL.Models.Task, Task>();
        CreateMap<TaskReport, DAL.Models.TaskReport>();
        CreateMap<DAL.Models.TaskReport, TaskReport>();
        CreateMap<Project, DAL.Models.Project>();
        CreateMap<DAL.Models.Project, Project>();
    }
}


Black Crumb Nuisance

Question: Every Sunday I play five a side football at the local 3G pitches. Every Sunday I bring home hundreds if not thousands of the small black bits used to fill the pitch. This in itself is a nightmare, however recently I've also started developing blisters as a result of these little black bits ending up inside my boots.
I often stop during play now to empty my boots, however this is both time consuming and annoying.
Does anyone else experience this? If so any advice on how to avoid this?
Answer: Those black crumbs used in 3G pitches are rubber pellets. (These often come from used tyres and other scrap materials. There are unproven claims that these are cancer risks. So I'd advise you to ensure none of these enter your body during play.) These pellets are useful as they provide a good grip when running on the artificial pitch, which is made of plastics which can be slippery. However, if the quantity of them that makes it inside your shoe is so high, perhaps you should try and convince the ground staff to scrape off the excess amount.
To address your current problem, I had faced a similar problem earlier and I realized this is attributed to the fit and shape of the football shoes/studs you use. My previous shoes were a decent fit but the design of the shoe (which could be worsened by use) was such that the mouth of the shoe did not close firmly around the ankle. As a result, the open mouth of the shoe allowed pellets to slide into the space and slowly work their way inwards with each stride. When I purchased a new pair which had a closed mouth, the quantity of pellets in my shoe were reduced tenfold. I still find quite a few pellets in my shoes when I take them off after the game, but I hardly need to stop mid-game to get rid of them. Additionally, you should consider wearing a thicker pair of socks as this would reduce the sensitivity of your feet to these foreign objects inside your shoes.
PS: I am unable to provide links or pictures regarding the two contrasting shoe designs, but I hope I have been able to explain the design issue quite clearly.
Comment: It's about how the boots fit your feet. Perhaps you're wearing one size too big. In any case, there is no set rule about the shoe opening. But from personal experience, I found a solution to a similar problem and it lay in changing the boots to a pair that fit more snugly, allowing little place for the pellets to enter the shoe.
Comment: http://www.new-football-boots.com/images/1015Boots/Adidas-Leo-Messis-2014-F50-adiZero-TRX-TF-football-boots-serpentine-white_3.jpg
Comment: I have recently (around 3months ago) purchased the above boots. Coincidentally this is also when we changed pitch location so didn't even consider the boot could be the issue. To be totally honest I didn't even realise there were different kinds of opening. Will try my old boots on the new pitch for a while see how that goes.

Black Crumb Nuisance


How to capture time portion from date_time in pyspark pr sparksql?

Question: I have field visit_start_time_gmt in bigint format, I was able to convert it to date_time, but now I need to remove the time portion of the timestamp in another column, see data sample below
Answer: If you want to truncate time then use date_trunc() function.

If you want to convert to date then use to_date() function.

Example:
df.show()
#+--------------------+
#|visit_start_time_gmt|
#+--------------------+
#|          1522555602|
#|          1522622390|
#+--------------------+

from pyspark.sql.functions import *

df.withColumn("date_hour",date_trunc("HOUR",to_timestamp(col("visit_start_time_gmt")))).\
withColumn("date",to_date(to_timestamp(col("visit_start_time_gmt")))).\
show()
+--------------------+-------------------+----------+
|visit_start_time_gmt|          date_hour|      date|
+--------------------+-------------------+----------+
|          1522555602|2018-04-01 04:00:00|2018-04-01|
|          1522622390|2018-04-01 22:00:00|2018-04-01|
+--------------------+-------------------+----------+


Combine multiple generic types in hacklang

Question: I am trying to implement the reduce function from underscore in hack. In underscore, the reduce function has the following behavior:

If no memo is passed to the initial invocation of reduce, the iteratee is not invoked on the first element of the list. The first element is instead passed as the memo in the invocation of the iteratee on the next element in the list.

My attempt to implement the function:
function reduce<T, Tresult>(
  Iterable<T> $iterable,
  (function(?Tresult, T):Tresult) $fn,
  ?Tresult $memo=null):?Tresult {
    if (is_null($memo)) {
      $memo = $iterable->firstValue();
      $iterable = $iterable->skip(1);
    }

    foreach ($iterable as $value) {
      $memo = $fn($memo, $value);
    }

    return $memo;
}

This results in the error:
Invalid return type (Typing[4110])
  This is a value of generic type Tresult
  It is incompatible with a value of generic type T
    via this generic Tv

How do I tell the type checker that T == Tresult when is_null($memo)
Answer: I note that the line
$memo = $iterable->firstValue();

assigns a value of type T to $memo. This seems wrong; $memo is given to be of type ?Tresult in the declaration, and assigned a value of type Tresult here:
$memo = $fn($memo, $value);

Can you explain why $memo is assigned a value of type T in the first instance?  How do you know that T and Tresult are the same? I see no evidence whatsoever that these two types are ever constrained to be the same thing. The type checker is giving you an error here because this program isn't typesafe; if T is Animal and Tresult is Fruit, and someone passes in a null fruit, there's no way to get a fruit out of the sequence.
Also, I find it weird that reduce returns a nullable result; surely it should be returning a result of the given result type, no?
If you want this function to have two different behaviours depending on the nullity of the argument, then why not instead simply have two functions?
function reduce1<T, Tresult>(
  Iterable<T> $iterable,
  (function(Tresult, T):Tresult) $fn,
  Tresult $memo): Tresult {
    foreach ($iterable as $value) {
      $memo = $fn($memo, $value);
    }
    return $memo;
}

function reduce2<T>(
  Iterable<T> $iterable,
  (function(T, T):T) $fn): T {
    return reduce1($iterable->skip(1), $fn, $iterable->firstValue());
}

There, now we have two different forms of reduce, and both of them are typesafe.
Comment: When memo is omitted, the first value in the Iterable is used as the memo. In that case, T is the same as Tresult. This is the behavior of reduce() in underscore.js and is occasionally useful for commutative operations. For example: _.reduce([1,2,3], (x,y) => x+y)
Comment: @nwarp: You're not following me.  What **forces** the types to be the same in your Hack program?  What is stopping me from passing a null `?Fruit` as `$memo` and a sequence of `Giraffe` for the sequence?  The type system is telling you that you have not provided any proof that this *cannot* happen, and therefore it *can* happen.
Comment: @nwarp: Your question is "how do I tell the type checker that these two types are the same when this value is null?" when *they are not necessarily the same when the value is null*. You can't tell the type checker that because *that's a lie*.
Comment: My interpretation is that in order to do what I want, I'll need either: 1. function overloading 2. some kind of type assertion for generics like invariant(T == Tresult). Since both these features are not available in hacklang, the behavior I desire cannot be implemented in a type-safe way.
Comment: @nwarp: I don't see how function overloading helps. All function overloading gives you is the ability to have two different functions with the same name; why is it a hardship to have two different functions with different names?  The two behaviours you want are **different functions**; one requires a projection to arbitrary type and the other requires a projection to the element type; *those are different things* so you should have *two functions*.
Comment: Function overloading will allow me to call both reduce1 and reduce2 the same name, thus getting the desired behavior. I understand your reasoning behind why these **should be** two different functions. As mentioned, I am trying to reproduce the behavior of a widely used library and **what should be done is irrelevant** in this scenario.
Comment: @nwarp: I am kind of horrified by that last sentence.  Trying to mimic a library's syntax is a feature with costs and benefits.  Don't blindly reject the possibility that the costs are higher than the benefits.
Comment: @Brian I guess I should rephrase. This is not about finding the best/correct way to do something. It's about learning and testing the limits of Hack's type system.
Comment: @nwarp: Another consideration is: your design proposal conflates null with missing. Suppose you *wanted* the initial value of the accumulator to be null; in your proposed method, the initial value being null has a special meaning.


MAX on multiple offset arrays

Question: I have the following data in Excel. This is a simplified version of what I have, take note that the figures do not share a row or a column with the name.
Martin
        145 171 130
Dave
        157 190 201
Darren
        122 199 177
Mark
        197 183 202
Dan
        186 139 168
Martin
        185 204 156
Dave
        197 172 158
Darren
        231 228 217
Mark
        173 192 205
Dan
        214 166 172

What I would like is a list of distinct names, with the maximum figure next to it.
I've tried something like this: {=MAX(IF(B1:B50=I2,OFFSET(INDEX(B1:B50,MATCH(I2,B1:B50,0)),1,1,3,3)))} but doesn't work.
I am aware if the figures are on the same row as the name, I can use {=MAX(IF(B:B=I2,C:E))}, but I'm trying to prevent moving the figures.
Answer: Try this
=max(offset($B$1:$D$1,match(I2,$A1:$A1:$A50,0)))

Changes from yours

Doesn't need to be an array formula
The array size is set in the first part of the offset function
Index is not needed as you are not trying to return a certain cell you are just looking for an offset number which match provides

Note that offset is a volatile function which can slow down the sheet if its large (can force all cells to update every small change), but I can't think of a better solution off the top of my head.
With duplicate names this would should work, just build the offset into the array if function
={MAX(IF($A$1:$A$50=I2,$B$2:$D$51,""))}

Comment: Thank you. Will this only search the first instance of the name though? There will be multiple lines with Martin in, with values underneath.
Comment: Added another formula that should work with duplicate names

MAX on multiple offset arrays


Prove that integral of continuous function is continuously differentiable

Question:
Lots of things going on here. I immediately know that $F(x)$ does exist since $f$ is riemann integrable due to the fact that it is continuous. First I need to show that $F$ is continuous, then find $F'$ and show that it is continuous. What can I do?
Comment: Well I guess you know right away from the Fundamental Theorem of Calculus that $F'(x) = g'(x)f(g(x))$, right (assuming that's not a negative in front of the integral).
Comment: This sounds similar to this question: http://math.stackexchange.com/questions/751340/how-to-show-integral-is-continuous#comment1564189_751340 I still think the fact that $F(x)$ is the anti-derivative means that it must be differentiable (over the interval) and therefore continuous.
Answer: I can show you how to get the derivative, but I don't know about proving continuity, etc.  According to the fundamental theorem of calculus, there exists a function $G(x)$ such that:
$$
F(x) = \int\limits_a^{g(x)} f(x)dx = G\left(g(x)\right) - G(a)\text{, where } G'(x) = f(x) \\
F'(x) = g'(x)G'\left(g(x)\right) - 0 = g'(x)f\left(g(x)\right)
$$
I don't really like the following notation, but problems like these seem to warrant it...you could also write it like this:
$$
F'(x) = g'(x) \cdot \left(f\circ g\right)(x)
$$
Comment: Thanks! This would obviously be continuous due to composition of continuous functions though, wouldn't it? not much of a proof there required maybe.
Comment: also, how do we know $G'(x)$ exists? We're not given that $f$ is differentiable, just continuous.
Comment: You don't need $f$ to be differentiable since you don't take a derivative of $f$.  _However_, you _do_ need that $g$ is differentiable (and this _is_ given).  As for $G'$ existing, I would argue that's implied by the fundamental theorem of calculus (but I don't have anything better than that)...like I said, I'm not real sure how to prove the continuity part.
Comment: ah, you're right! i was thinking of this correctly. We proved in class that a continuous function on a compact interval is riemann integrable, so I know G' exists :)
Answer: Hint: $F = G\circ g$ where $G(x) = \int_0^x f(t)\,dt$ is a function that you can differentiate.
Comment: absolutely. you gain regularity with integration.
Comment: Is that $-$ supposed to be there?
Comment: probably not. I have read $:= -$ in OP's question.
Comment: Sorry! There's something wrong with the Latex in my teacher's assignments, the minus's and equals signs are reversed.
Comment: anyway, did you get the hint?
Comment: yeah I did: it's essentially the same thing Jared did below, right?
Comment: yes it is. {} {}
Comment: sounds great, thank you guys. the continuity of the derivative then comes immediately from composition of continuous functions, right? (f is given continuous so f(g(x)) is continuous, and g is cont. differentiable so g'(x)) is continuous so their product is continuous.)
Answer: Since $f$ is continuous in $[a,b]$ then $H(x):=\int_a^x f(t) dt, x\in[a,b]$ is differentiable,  by the FTC (see for instance M. Spivak, Calculus). Now, $F$ is nothing but the composition $H\circ g$, this composition being well defined since $Im g\subset Dom H$, is differentiable in $[a,b]$ since it is the composition of two differentiable functions ($H$ is so by construction, and $g$ by hypothesis). Hence, by the chain rule $F'(x)=(H\circ g)'(x)=(H(g(x))'=H'(g(x)) g'(x)=f(g(x)) g'(x)$, using the FTC ($H'(x)=f(x)$). $F'$ is a continuous function since it is the product of two continuous functions on $[a,b]$, $f(g)$ since it is the composition of continuous functions (and $Im g\subset Dom f$) and $g$. Therefore $F\in C^1([a,b])$. QED.


Find the components of a vector u which has initial point (-1,-2), terminal point (x,0)for some x∈ℝand which points in the same direction as (1,3)

Question: How can I find the components of this vector u?
I know how to find the components of a vector when all coordinates are given (taking the coordinates of the terminal points away from the initial), but how can I go about finding the x coordinate of the terminal point?
Comment: Welcome to Mathematics Stack Exchange.  Find the components of $u$ in terms of $x$; set them equal to a multiple of $(1,3)$, and solve for the unknowns
Comment: Please include your question in the body of the question, instead of putting it only in the title.
Answer: $u=(x,0)-(-1,-2)=(x+1,2)$.  Set this to be a multiple of $(1,3):\quad  (x+1,2)=\alpha(1,3).$
Can you solve this for $x$?  The answer to the question is then $x+1$.


Pegar cor dinamicamente

Question: Criei algumas cores no arquivo colors.xml
<color name="colorBackground1">#5c6bc0</color>
<color name="colorBackground2">#1e88e5  </color>
<color name="colorBackground3">#00838F</color>

No adapter quero setar a cor dinamicamente
val cor = "R.color." + cores.get(position)
val colorValue = getColor(context, cor)
vh.item.setBackgroundColor(colorValue)

A variável corescontém somente o nome da cor, exemplo colorBackground1.
Mas na linha
val colorValue = getColor(context, cor)
ele não aceita a variável cor, esperando um int mas tá passando uma string e não achei um jeito de converter. A string sai com o nome certo, R.color.colorBackground1. Como resolver?
Answer: Ou você pode transformar val cor = "R.color." + cores.get(position) em inteiro.
ou o ideal é utilizar o seguinte método:
getResources().getIdentifier("name", "resource", "package");

No seu caso ficaria então:
val cor = getResources().getIdentifier(cores.get(position), "color", getPackageName());

Espero ter ajudado.

Pegar cor dinamicamente


Changing items in DataGrid. Is this the right way?

Question: I have a DataGrid binded to an ObservableCollection, and i'm sure the way i use to update the items in that collection is not the right way.
I've been having problems to make the DataGrid refresh. If i modify an item directly, the DataGrid doesn't refresh until i click another cell. I can see the NotifyPropertyChanged is being hit in "Details" and "_Detail", but the UI just doesn't refresh. After trying a lot of things, i found a workaround: I remove the previous one, and add the new item.
Thing is i wan't to do it the right way. So...which one is?
C#
public class AsientoDetallesViewModel : ViewModelBase, IInteractionRequestAware, INotifyPropertyChanged
{
    private ObservableCollection details;
    public ObservableCollection Details
    {
        get => details;
        set
        {
            SetProperty(ref details, value, nameof(Details));
            NotifyPropertyChanged(nameof(Details));
        }
    }

    private Detail _detail;
    public Detail _Detail
    {
        get => _detail;
        set
        {
            SetProperty(ref _detail, value, nameof(_Detail));
            NotifyPropertyChanged(nameof(_Detail));
        }
    }

    private void UpdateRow()
    {
        var itemUpdated = _Detail;
        itemUpdated.Account.Name = "some name";
        itemUpdated.Account.Name2 = "another name";

        //the workaround
        Detalles.Remove(itemUpdated);
        Detalles.Add(itemUpdated);
    }
}

XAML
<DataGrid ItemsSource="{Binding Details, Mode=TwoWay}"
          SelectedItem="{Binding _Details, Mode=TwoWay}"
          AutoGenerateColumns="False">
<DataGrid.Columns>
            <DataGridTemplateColumn>
                <DataGridTemplateColumn.CellTemplate>
                    <DataTemplate>
                        <TextBlock Text="{Binding Path=Binding Path=Account.Name, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" HorizontalAlignment="Center" Margin="0, 3, 0, 0" ></TextBlock>
                    </DataTemplate>
                </DataGridTemplateColumn.CellTemplate>
            </DataGridTemplateColumn>
            <DataGridTemplateColumn>
                <DataGridTemplateColumn.CellTemplate>
                    <DataTemplate>
                        <TextBlock Text="{Binding Path=Account.Name2, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" Margin="0, 3, 0, 0"></TextBlock>
                    </DataTemplate>
                </DataGridTemplateColumn.CellTemplate>
            </DataGridTemplateColumn>
         </DataGrid.Columns>
    </DataGrid>

Comment: Does the `Account` class implement `INotifyPropertyChanged`? It should.
Comment: No. It doesn't. "Detail" it's a POCO. Does it matter? Or there is no problem with INotifyPropertyChanged in POCO classes?
Comment: It doesn't matter whether `AsientoDetallesViewModel` or `Detail` implement the interface since it's an `Account` that you bind to. See my answer.
Comment: Sorry. I meant to say "Account"
Comment: `Account` should implement `INotifyPropertyChanged`.
Comment: Ok then. I'll post the results.
Answer: It is the object returned from the Account property of the Detail class that must implement the INotifyPropertyChanged interface and raise change notifications for the TextBlocks bound to the Name and Name2 properties to get refreshed.
It doesn't matter whether AsientoDetallesViewModel implements INotifyPropertyChanged since you are not binding to a property of this class.


Add a new Taxonomy term page

Question:

I use drupal 8 and I want to add a new view page to taxonomy view.
I tried to dublicate default taxonomy page view and changed path
<code>from: taxonomy/term/%/
to : taxonomy/term/%/newpath
</code>
but this is not working. why would this not work?
Comment: You can alter routes using a route subscriber service.
Comment: I dont want to alter current paths, I just want to create a new view for taxonomies ex: taxonomy/term/2/feed taxonomy/term/2/newpath
Comment: I thought you wanted to replace the current routes.
Comment: Add your entire route definition in the question body.
Comment: I didnt write a custom route for that. Only changed the path of a current taxonomy view
Comment: What do you mean by "not working". What do you get when you visit that path?
Comment: page not foundd.
Answer: Did you tried to change the "Contextual filter" settings ?
WHEN THE FILTER VALUE IS NOT IN THE URL to -> Provide default value (taxonomy term from url)
or check the WHEN THE FILTER VALUE IS IN THE URL OR A DEFAULT IS PROVIDED validation

Add a new Taxonomy term page


Regex lookbehind with alterations and whitespace

Question: I'm trying to build a Regex in .NET which will match words from a list (using alteration) which does not come after words from another list with space after them.
For example, let's say I'm looking for AAA or BBB, and I want them to not come after WWW or XXX, so that the following should match:
DDD AAA
AAA

But the following shouldn't:
WWW AAA
XXX      BBB

I've tried to use the following pattern:
(?<!WWW|XXX)(AAA|BBB)

But I don't know how to define that there shouldn't be spaces after the first list.
Any ideas?
Answer: Fortunately, .NET regexes allow indefinite repetion inside lookbehind assertions, so it's uncomplicated to extend this regex:
(?<!(?:WWW|XXX)\s*)(AAA|BBB)

Explanation:

(?<!         # Assert it's impossible to match this before the current position:
 (?:WWW|XXX) # WWW or XXX
 \s*         # followed by any number of whitespace characters
)            # End of lookbehind
(AAA|BBB)    # Match AAA or BBB, capture the result in group 1

Comment: Wow, fastest answer ever... However, it doesn't seem to work, at least not on RegExr. It doesn't match anything. Could it be there is some problem in the pattern?
Comment: @ml123: This regex only works with a .NET engine. RegExr uses a PCRE engine (I think), and that engine doesn't support the feature I mentioned above.
Comment: Thanks, I would have never get it by myself, took me a long time to try to solve it.


How to RewriteRule without destroying relative path loading of source files?

Question: I have an ugly filesystem path on the server: example.com/a/b/c/d/e/f/main.html. For simplicity, I will use example.com/httpdocs/main.html in the body of this question.
I want that what the user sees is example.com/easy-to-remember. I will use example.com/abc in this question.
For reasons out of the question scope, I would like to do that with only the .htaccess file, not php-routing.
Let's start with the case that works:
RewriteEngine On

# Rewrite abc/ directory for loading of source material
    # Rewrite only if there is no actual file or directory that matches this request
    #   This can especially be useful for loading resources
    #   because then the full paths won't be redirected if they are correct.
    # Note that RewriteRule never sees leading slashes
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule ^abc/(.*)$ httpdocs/$1 [NC,L]

With that, the user can open example.com/abc/main.html (expressive path) and is shown the page that is internally stored at example.com/httpdocs/main.html (ugly path). The user never sees the internal path; the url remains /abc/main.html in their browser.
Up to this point, everything works as intended. The CSS source files, specified in a relative path in main.html are still loaded correctly.
But maybe main.html is a very useless name. I'd rather have example.com/abc as a link, instead of example.com/abc/main.html. That'd be more expressive and would allow internal changes of the file extension without changing the links.
# Rewrite abc without trailing slash to main.html
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule ^abc$ httpdocs/main.html
    # PROBLEM: This turns the current url into "example.com/abc", so "./libs"
    # is now looked for in "example.com/libs" instead of "example.com/httpdocs/libs"

This rule still works for loading main.html without displaying that name in the url to the user.
But the relative paths are now resolved wrongly.
/httpdocs/main.html relies on /httpdocs/libs/source.css. In the first case, where we access /abc/main.html, the sources are loaded from /abc/libs/source.css and these loads are redirected to /httpdocs/libs/source.css so everything worked fine. In this second case where we access /abc, the css is loaded from /libs/source.css instead, omitting the /httpdocs directory - and that results in a 404, so the page is now not rendered correctly anymore (when accessed in this way).
The obvious solution would be to keep the first case, and if I really don't want to show the name main.html to the user, I could in addition add a rule that redirects /abc/expressive-name to /abc/main.html (or directly to /httpdocs/main.html).
But I am curious whether there are ways to achieve what I was trying to do without adding a second depth level (another slash something) to the url.
I want to keep the loading of the sources relative, so that if I ever have to move the whole filesystem to another subdomain or so, I can just copy the whole thing over. Without that constraint, I could simply make all loads absolute.
Answer: As you found out,you must keep the URL of the main file at the same level for the relative links to work. A simple way is to use the URL /abc/ instead of /abc.
The difference is what the browser sees as the current directory or base URL. The base URL is the URL with everything removed after the last /. So with /abc the base URL is / while with /abc/ the base URL is /abc.
So you can write:
RewriteRule ^abc/$ httpdocs/main.html

or you can omit the filename in the URL if you supply it with
#RewriteCond %{REQUEST_FILENAME} !-f
#RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^abc(.*)$ httpdocs$1
DirectoryIndex main.html

The RewriteCond rules are just to make sure that the target is not an existing file or directory. As you know that the target doesn't exist, you can omit the rules.
If your main file is always named main.html, you can add DirectoryIndex just to the root directory (or a common ancestor). It would make the RewriteRules shorter, because you don't need separate RewriteRules for the directory and for the main file.
A get request to /abc needs an external redirect to /abc/, but apache will do that automatically if it detects that /abc is a directory.
A useful tool for external redirects is the program wget, it can display the redirects the server sends.
Comment: does that change answer your question?
Comment: Thanks so much! What is the difference between the two approaches?
Answer: Copied from Jon Lin's answer here

The extra slash in the URL changes the relative URL base. All your
  links that are relative URLs in your content will now use the
  incorrect base. You can fix this by either using absolute URL's
  (starts with a /) or add a base in your page's header:

<base href="/" />


Lettuce BDD from Mac OSX terminal

Question: I've been working through the Lettuce tutorial (Lettuce Tutorial) to get BDD and Pyton to work together, all is in place.
The problem is I cannot run lettuce through my Mac OSX terminal, the tutorial shows lettuce specifying the test path and passing in lettuce as an argument;
user@machine:~/projects/mymath/tests$ lettuce
But this doesn't work for me as it returns path not found but I can cd to the same path where my tests reside.
When using Mac OSX terminal, what is the command to run lettuce and specify the tests path? Thanks in advance
Answer: lettuce is the right command.
it'll be easy for everyone else understands your issue if you can post the error message.
you may need to install your project in 'development mode' so that lettuce can find necessary modules.
check out this example bdd-python project: https://github.com/guoliang-dev/bdd-python it may helps.

Lettuce BDD from Mac OSX terminal


What is the difference between if(b) and if(b==true) in java language?

Question: If b is a Boolean, what is the difference between if(b) and if(b==true)?
Comment: They evaluate to the same thing - effectively no difference
Comment: Former is correct (& short) way, later is 'a' way to do - developers in their learning phase use it - until they know the better thing.
Answer: There isn't any difference, unless one day you mistakenly replace the 2nd expression to this:
if (b = true)

and then you spend hours debugging what's the issue, you'll feel the need of using the first one.
Comment: Is there a any speed issue between them?
Comment: @BAEHARAM Well, there isn't. But here's a suggestion - don't think too much about efficiency while programming, specially in the beginning stage. First get the result. These are just pre-mature optimization, which shouldn't exist.
Comment: Thanks your comment :) but I have to know about the difference because of colleague homework. So is it related to only debugging problems?
Comment: @BAEHARAM Ok, just to finish this discussion, they are both the same. It's upto you what you choose to use. I've already given hint in my answer, about which one you should use.
Answer: if (b) evaluates the value of b, which means the conditions is met if b is true.
if (b==true) evaluates the value of the expressions b==true, and this expression evaluates to true if and only if b is true.
Therefore both expressions have the same outcome.
Comment: I know they have the same outcome, but are they compiled the same way? Could'nt it be possible that `if ( b==true )` gets compiled in more lines of machine code?
Answer: Simply if(b) will be executed if b is true.
if(!b) will be executed if b is false.
if(statement)...... the statement  should be true for the executing the if statement.


Choosing FQDN for Internal Use (avoiding split DNS)

Question: I've been looking everywhere for a definative answer to this. We are recreating our interal Windows domain and trying to come up with a FQDN for our TLD.
Currently we are using "company.co.uk" internally. We own this domain and also use it for our public website. This causes all sorts of DNS issues internally and by creating a new domain we were hoping to avoid all that micromanagment.
We want something like "company.local", however this would conflict with Bonjour.
Would using something like "local.company.co.uk" or "ad.company.co.uk" still present us with DNS issues? We want to avoid split DNS.
Thanks
Comment: Close this.  Duplicate x100.
Answer: Subdomains are the perfect use of registered domains for internal DNS, you won't be trampling on other people's valid domains, they will not conflict with your external domains, you can keep them private or expose them to the world (I prefer to keep them private). They also require just a small change on the part of employees, instead of www.company.uk, they can use www.ad.company.uk, and so forth.
Just remember to treat them like proper domains, set up valid RDNS and so forth.


Install package from conda for a specific version of python

Question: I'm relatively new on dealing with python libraries so it might be a stupid question but here is the detailed problem:
I'm working on Linux and trying to use a python program (ORF-rater) using python 3.7. Unfortunately, when I run the program, I get the following error:
ImportError: cannot import name 'maketrans' from 'string'

which I think is related to this issue. Therefore I want to use another version of Python (3.4 or 2.7 for instance) that will support this maketrans.
The program that I'm using also uses the Python package plastid, which I installed using Conda conda install -c bioconda plastid which I guess worked well.
However, it installed the package on python 3.7 only, and I can't find a way to install for python 3.4 (I tried others things as pip3.4 install plastid, but it did not work, most likely because I'm working on an university server and I don't have permission to do it).
In brief, how do I install a package using Conda for a specific version of Python (3.4)?
Comment: The python environment can be "confused", so to speak, regarding what packages to use. from where. I did it once and it took ages to get python working again (I removed conda, pip and reinstalled python)
Comment: Just a note; do *not* mix conda and pip. That only leads do disasters!
Comment: Can you be more exhaustive and explain why ?
Comment: Thx, then, maybe that's why I'm not permitted to use ```pip``` on the university server^^
Answer: The following code creates an environment with a specific python version (2.7 since 3.4 was not an option), then you activate it and install the package you need.
conda create -n test python=2.7
conda activate test
conda install -c bioconda plastid
python

Then in Python, I did the following and got no errors
from string import maketrans

Comment: It's always better to do it in one command: `conda create -n test -c conda-forge -c bioconda python=2.7 plastid` No reason to have the solver run twice.


Error generating images

Question: I was experiencing weird GD library issues with Drupal 8, when the site tries to generate thumbnails from image style. I am using Docker PHP.
The error is simply saying Error generating image. I checked the logs, but I didn't find anything helpful.
Answer: This is the fix for the issue.
The code taken from duplicated issue in https://stackoverflow.com/questions/36359917/docker-gd-module-for-php-7
Please take this with heaps of grain and salt, and modify the script accordingly.
<code># Install GD
RUN apt-get install -y libfreetype6-dev libjpeg62-turbo-dev libpng12-dev
RUN docker-php-ext-configure gd --with-freetype-dir=/usr/include/ --with-jpeg-dir=/usr/include/
RUN docker-php-ext-install gd
</code>
What is actually happens is your GD library is installed BUT without JPEG library configured. Your Drupal will be chill saying GD installed but there is hidden requirement that JPEG need to be exist too.
The line 179 in GDToolkit.php:
<code>$function = 'imagecreatefrom' . image_type_to_extension($this->getType(), FALSE);
</code>
Causes the function imagecreateformjpeg fails to be executed.
Hope it helps someone that confused, cant generate thumbnail with limited knowledge of the errors.
:)

Error generating images