Criação de variável através da resposta do usuário em Python

Question: Gostaria de fazer que o usuário inserisse uma resposta de dessa resposta criaria uma "variável" ou não. Não sei se criação de uma nova variável seria a melhor forma, segue exemplo:
a = str(input('Existe mais produtos para serem adicionados?: '))

Nessa parte o usuário responderia sim ou não, se a resposta fosse sim, o programa criaria outra variável que receberia um determinado valor float (a2 a3 a4) e assim em seguida.
Comment: Infelizmente o que você está a procura no código não faz muito sentido. O que iria fazer com essas tais variáveis `a2 a3 a4` ?
Answer: O usuário criar não é possível assim. Mas aqui tenho uma solução
a= str (input ('Existe mais produtos para serem adicionados?: '))
a2 = 0
a3 = 0
a4 = 0
if a == 'sim':
    a2 = 1
else:
    a3 = 1

Mas, imagino que o melhor no seu código, seria uma lista.
Algo nesse gênero:
lista = []
a= str (input ('Existe mais produtos para serem adicionados?: '))
if a == 'sim':
   lista.append(1) #valor

Assim, o se você colocar dentro de um while, mudando o que você coloca dentro do append, e mudando o if, você consegue fazer uma lista infinita, que acho que é o que você deseja, dai você roda o while, enquanto a resposta for diferente de 'nao'. Se precisar de ajuda em como fazer, deixe o código, ou especifique o que você quer, ficarei feliz em ajudar.
Answer: Eu recomendária que você usasse dicionários. Assim você pode rastrear o valor pelo nome do item, por exemplo. Se você quisesse que rodasse um while até que não existisse mais produtos para serem adicionados, bastaria utilizar o seguinte código.
 #criamos nosso dicionario
d={}
a = "s"
#utilizei o lower pra sempre deixar a resposta em minusculo, pra nao ter problemas com input maiusculo
while a.lower() == "s":
    item = input("Digite o item que deseja adicionar")
    valor = float(input ("Digite o valor do item %s: "%item))
    d[item] = valor
    a = input ("Deseja adicionar mais algum item? s/n")
#para exibir em for, utilizamos a seguinte sintaxe
for x in d:
    #como o x vai rodar sempre com o valor da chave (nome), podemos chamar o valor do preço com a o dicionario[x] (d[x])
    print ("Item: %s \tPreço: %.2f"%(x, d[x]))


Open a desktop app by clicking on a link on the browser

Question:
I want to enable the user to open a certain software on his desktop when he clicks the link on the browser, as shown on the image above.
I am a ware of the security issue, and also I am assuming the user has this software installed on his machine. What is the best way to achieve this?
OS: windows.
Comment: Possible duplicate of [How to launch an application from a browser?](https://stackoverflow.com/questions/3057576/how-to-launch-an-application-from-a-browser)
Comment: It is possible in HTA (Win / IE - unrestricted "web" page) I am using this for AutoIt scripts for example var shell = new ActiveXObject("Wscript.Shell");
var basePath = ".\\";
shell.run(basePath + "AutoIt\\AutoIt3_x64.exe \"" + basePath
        + n + '"');

But of course does not work in common browser (security limitations). In short rename htm(l) to hta and you can do way more. Or also using frameworks like Cordova(?) you can do a bit more than in common pages.
Comment: Yeah those solutions from 10 year old threads are probably not going to work anymore. I remember the glory days of .hta viruses masked as .jpg on certain image boards years ago :)
Answer: If it's only on your own machine you could consider registering an URI scheme, so instead of having it link to http://something you use something like openMyApp://blabla
https://learn.microsoft.com/en-us/previous-versions/windows/internet-explorer/ie-developer/platform-apis/aa767914(v=vs.85)?redirectedfrom=MSDN


Must Follow rules of FxCOP

Question: I´m using FxCOP and I want to know which are the most important rules or the rules that anybody can´t miss when using this tool.
I´m looking for some article or page with a list of rules that must be used in fxCop, this tool has a lot of rules and it's difficult to select only a few of them.
Comment: Question is opion-based and asks for off-site resources. http://stackoverflow.com/help/on-topic
Comment: Generally: Enable all rules and when you get warned about a violation and the underlying root doesn't match your coding guideline or doesn't make sense in your project, than disable this specific rule.
Answer: That would depend very much on what sort of applications and/or APIs you are creating.  If you're interested in general-purpose "must" or "should" use lists, you might want to start with the rule sets packaged for Visual Studio Code Analysis (http://msdn.microsoft.com/en-us/library/dd264925.aspx).  (N. B.: These include a few extra rules that aren't available in the free version of FxCop.)  The following two rule sets might be of particular interest:

Managed Minimum Rules
Managed Recommended Rules

(Same answer as on the Microsoft forum.)

Must Follow rules of FxCOP


The meaning of certain C operators, delimiters and/or macros

Question: I have recently been granted access to a project that uses the C-language. In the file lexer.l, I have come across certain operators and delimiters unfamiliar to me, and was hoping for an explanation of these. What follows is a a list of said structures.

The delimiters %{...%}, ... being a bunch of #include statements and function definitions
%option followed by a string qualifying as a variable name
%x, followed by a bunch of identifiers qualifying as variable names, separated by whitespace:

wait
paraml
paraval
...

%% ... %%, with ... replaced by a bunch of blocks separated by newlines, such as

"~"               { macro_noarg("\\nbspc"); }
"\\%"             { chk_indent(); emitc('%'); }
[ \t\r]*"%"       { BEGIN(comment); }
[ \t\r]*"$$"      { emit_el();
                    indent(); emit(".. math::\n");
                    ilevel +=2;
                    if(user_lbl) {
                      ...
                    }
...

<wait>[...], <wait>"..." or <wait>s, where s is a symbol
<paraml>[...], <paraml>"..." or <paraml>s, where s is a symbol
<paraval>[...], <paraval>"..." or <paraval>s, where s is a symbol

What is the general meanings of these constructs?
Comment: Seems like [flex](https://github.com/westes/flex) input.
Comment: @lurker I have added information about these constructs being in a `.l` file.
Answer: The ones you mention are not default C operators nor macros.
It's Lex/Flex syntax.
For example:

The delimiters %{...%} are used to directly include C code
%option is used to specify some Flex option
%x defines "start conditions" for the lexer

Have a look:
http://dinosaur.compilertools.net/flex/manpage.html


How to start learning the piano again?

Question: When I was a kid (10 to 14 years old) I was taught how to play the piano. Or that's what I thought until today. I haven't been playing piano for about 10 years so I am of course rusty, but what I noticed is that when I learned I had developed bad practices (for example constantly looking at the keys instead of looking at the sheet). Moreover, I wasn't taught anything at all about chords, scales and so on.
So what I did back then was playing pieces (I remember playing a Ravel piece during my last year) by heart without particular knowledge of what was behind them. I'm trying to start playing again but now that I'm older (and my learning is less elastic) I find it really hard not to get discouraged. I think that I should go back to the basics, but I'm a bit confused on where to start again.
What theoretical concepts should I cover to fill my knowledge gaps? Is it a good idea to learn with a teacher?
Comment: Learning to play complicated pieces without being taught the theory required to understand how they work is not unusual; most traditional music teaching seems to work this way. (It is probably true that you can't start early enough with playing an instrument, even at an age when most of the theory would go over your head.) When I was a self-taught teenage bedroom musician, I was often surprised that friends who were taking piano or violin lessons didn't know the basics required to put together a simple chord sequence for a pop song.
Comment: @topomorto I really want to dive deep into the reasons why I'm playing certain notes, how harmony works, and I also want to develop the ability to sight read. I want to be able to anticipate the following bars in a sheet. I want (of course) to play mid-difficulty pieces again, but that's not my main aim right now. What I want, I guess, is to understand and "feel" more what I'm playing and why pieces are written in determinate ways.
Comment: What are your goals this time around? Just get back to playing pieces from score again? Why do you think it is that the gaps in your theory are now noticeable?
Comment: Do you have a particular style or period of music in mind? "reasons why I'm playing certain notes" is something that can be very genre-specific.
Comment: @topomorto I mainly play classical music, and that's what I want to play (other than videogames soundtracks). I don't have any specific periods in my mind, but I guess I enjoy classical music coming from the XIX and XX centuries.
Comment: @user105620 - I'll have to warn you that the music theory behind video game soundtrack themes can get downright unorthodox. I've heard quartal harmony, polytonality, Coltrane-like changes, modified blues and octatonic scales, and more from Nintendo music alone. You'll encounter similar theory difficulties the deeper you get into 20th-century classical music--for example, Impressionism is generally hellish to analyze.
Comment: @Dekkadeci Yes, I play videogame music mostly with no particular aims other than enjoying some pieces. I'd rather focus on the theoric basics of classical music and keep playing videogames music (easy pieces) as a side passion!
Answer: Lets start with the obvious:  you will do better with a teacher than without a teacher.  This is for many reasons but two of the main ones are that it will bring structure to your learning and development and you will get regular feedback on how you are progressing.
If you cannot get a teacher then you are going to have to be very disciplined.  If you were playing Ravel when you gave up previously then you must have made some progress back then (I can't think of any really easy pieces by Ravel) but that is no longer your starting point.
Start with the basics and move forward only at a pace that does not skip things.  Its obvious I know but its amazing how easy it is to move on from a piece when you can play most of it and you intend to "come back to that hard bit later".  Usually does not happen.
If you get it right then you will learn about different keys and chords as you progress.  If you end up without a teacher then try to get a look at the syllabus from one or more of the music schools (ABRSM for example).  Their grade 1 to Grade 8 pieces represent a reasonable line of increasing difficulty and complexity, as do their scale and arpeggio requirements which go alongside them.
You have already recognized that you have some flaws in your approach (you mentioned looking at the keys) so that's a positive.  You have recognized an issue which is halfway to fixing it.
Go for it.  Good luck.
Comment: "its amazing how easy it is to move on from a piece when you can play most of it and you intend to "come back to that hard bit later". Usually does not happen." : this is SO true!
Answer: First of all, I recommend not thinking about your age or the "elasticity" of learning now. I got interested in music when I was 14, and in the country where I lived at the time I would not be accepted into anything but percussion, because I was considered too old (and even that came with noticeable displeasure from my teacher).
I had played percussion (drums, kettle drums, xylophone) for 8 years in a folk orchestra (so no classical music or jazz). I was very careless with practising and rarely played outside of the 3 3-hour-long rehearsals per week with the rest of the orchestra. After a few years into university, I completely gave up on music (I didn't have the time to come to the orchestra anymore, and I didn't have much money to eat, let alone purchase a drum set).
I started to play saxophone (tenor), my favourite instrument, just around the age you are now. Most people in my place would've given up on the idea as soon as it arrived in their mind, but I had an almost lifelong passion for the instrument, and having worked for a number of years after finishing university allowed me to buy a professional instrument and enrol into a semester at the local conservatorium.
Because I was older, it was actually much easier for me to follow a practising routine than when I was a teenager who was mainly concerned with getting good grades and staying in touch with their friends. Investing a car's worth of money into a professional-grade instrument was a great incentive to keep on practising too.
As @JimM said, it is a good idea to invest into lessons. If you practise for 25 minutes 2 times a day and see a teacher every week for 3 months, it will pay off much more than you possibly expect now. Just make sure you do not overexert yourself in the beginning, as it can lead to long-term physical damage to your fingers, hands and posture.
When I came back to playing music, I could barely read note sheets. I started with simple pieces (like Mozart's minuets) and had to write note names over the staff to play at all. Now the saxophone is in many ways easier than the piano, so you might have to separately exercise with the treble and bass clefs in the beginning, but do not let it deter from your desire to learn to play the instrument again. You have most likely retained some physical memory from playing it as a child, which will come back to you eventually.
I know it is daunting at first, even financially speaking, but if you love the instrument and truly want to master it, you will succeed. It took me 1.5 years to go through 10 years of school-level saxophone, and I am hardly a genius at music, so I'm certain anyone can repeat my "success".
Please do not forget to research instruments and how to look after them prior to engaging. You will eventually have to get an instrument of your own. If you have a local conservatorium, it might be a good idea to enrol there, they usually offer instruments for hire, so you might be able to get yourself some time to find out whether you want to be bothered with the instrument at all before you fully invest yourself into it.
As for chords and music theory, those concepts come in time as well. If you get a good teacher, you might ask them to help you analyse the compositional techniques behind a particular piece. Most (good) piano teachers mention the concepts of tonality and harmony right off the bat anyway, but it's a good idea to ask for additional information and books. As you get deeper into playing piano and progress to more difficult pieces, you will start noticing patterns yourself. Just give yourself time and do not expect to grasp everything at once.
Comment: You mention that "Most (good) piano teachers mention the concepts of tonality and harmony right off the bat anyway" - does that really happen for adult learners? I noticed that none of my childhood piano teachers brought up tonality or harmony until I hit the Royal Conservatory of Music (RCM) grade range where I had to start taking music theory lessons.
Comment: Thank you for your reply. Luckily I own a piano so that is not a problem.
Comment: @Dekkadeci, I guess that depends on country, luck and the teacher in question... When I was learning percussion, my teacher wanted to teach me music theory, but I, in my teenage stupidity, objected as much as I could. I am currently under the tutelage of an American jazz multi-instrumentalist, and he made it apparent straightaway that I need to learn scales and harmony if I want to succeed (I am learning saxophone, however, not piano). He happily shared many exercise and theory books with me as well and dedicated a number of classes to music theory (including piano). That is my experience.
Comment: It's doubtful that a conservatoire would lend/hire out a piano. And without one available, it's a long, long journey.
Comment: @TIm, the one in my city hires out digital ones. Of course, they are old and shabby, but it's a start. They also allow one to use designated practice rooms for 1 hour every day. I am not sure how it is in other countries though.
Answer: Another way to re-start practicing might be one of the many learning apps out there (for Android, iOS etc).
Some of them are quite good at teaching theory and getting you into a nice daily/weekly routine.
Once you get a feel for your available time (and interest) after a few weeks/months, you could move to the next stage and, as @JimM suggests, invest into lessons or a more formal method.
And, most of all, ejoy the journey!
Comment: If you have experience using one or more of these apps, feel free to edit your answer and go into more detail about what they do, how you used them, what was good or bad about them, and how to select a good app.
Answer: Depending on whether your initial teacher used a particular method book to teach you from, I'd suggest obtaining that same method book and working through it again. Most of them are pretty focused on what you need to pay attention too, and you might find your training coming back to you as you work through it again. You can do this at your own pace and in addition start studying some basic music theory to help you understand scales, harmony and chords. Once you have a handle on the basics, you might wish to start playing with others. Ask others to come around and work on playing together. It's completely different from playing alone, and the learning curve usually turns dramatically more in the vertical direction. Learn how to develop your skills and try to have fun in the process. Once this is learned you'll probably be on the road to where you want to end up. That's been my experience.

How to start learning the piano again?


Buggy UV coordinates of sphere in OpenGL?

Question: I am having buggy texture map on my sphere. The issue is well known but solution is rare.
This is my code for generating UVs for a sphere.
T = triangles, Nv = vertex normals.
for (int i=0; i<nbF; i++)
{
    float tx1 = atan2(Nv[T[i].v1].x, Nv[T[i].v1].z) / (2.0f*M_PI) + 0.5f;
    float ty1 = asinf(Nv[T[i].v1].y) / M_PI + 0.5f;

    float tx2 = atan2(Nv[T[i].v2].x, Nv[T[i].v2].z) / (2.0f*M_PI) + 0.5f;
    float ty2 = asinf(Nv[T[i].v2].y) / M_PI + 0.5f;

    float tx3 = atan2(Nv[T[i].v3].x, Nv[T[i].v3].z) / (2.0f*M_PI) + 0.5f;
    float ty3 = asinf(Nv[T[i].v3].y) / M_PI + 0.5f;

    float n = 0.75f;

    if(tx2 < n && tx1 > n)
        tx2 += 1.0;
    else if(tx2 > n && tx1 < n)
        tx2 -= 1.0;

    if(tx3 < n && tx2 > n)
        tx3 += 1.0;
    else if(tx3 > n && tx2 < n)
        tx3 -= 1.0;

    out_UV[T[i].v1].u = tx1;
    out_UV[T[i].v1].v = ty1;

    out_UV[T[i].v2].u = tx2;
    out_UV[T[i].v2].v = ty2;

    out_UV[T[i].v3].u = tx3;
    out_UV[T[i].v3].v = ty3;
}

Output:
https://i.stack.imgur.com/luhgZ.jpg
![enter image description here][1]
As you can see in the figure, my code is generating long strip at one side of the sphere. The solution is here .. http://sol.gfxile.net/sphere/index.html but couldn't figure it out.. How can I solve this issue ? any suggestion?
# Update 1:#

This code also doesn't work for me.. I don't know what wrong in it. still the same ugly seam I am getting. ???
for (int i=0; i<nbV; i++)
{
    out_UV[i].u = (float) atan2(Nv[i].x, Nv[i].z) / (2.0f*M_PI) + 0.5f;
    out_UV[i].v =  (float) (asin(Nv[i].y) / M_PI) + 0.5f;
}

float nx = 0.9f;
float nv = 0.8f;
for (int i=0; i<nbV-2; i++)
{
    if (out_UV[i].u - out_UV[i+1].u > nx)
        out_UV[i+1].u += 1.0f;
    if (out_UV[i+1].u - out_UV[i].u > nx)
        out_UV[i].u += 1.0f;

    if (out_UV[i].u - out_UV[i+2].u > nx)
        out_UV[i+2].u += 1.0f;
    if (out_UV[i+2].u - out_UV[i].u > nx)
        out_UV[i].u += 1.0f;

    if (out_UV[i+1].u - out_UV[i+2].u > nx)
        out_UV[i+2].u += 1.0f;
    if (out_UV[i+2].u - out_UV[i+1].u > nx)
        out_UV[i+1].u += 1.0f;

    if (out_UV[i].v - out_UV[i+1].v > nv)
        out_UV[i+1].v += 1.0f;
    if (out_UV[i+1].v - out_UV[i].v > nv)
        out_UV[i].v += 1.0f;

    if (out_UV[i].v - out_UV[i+2].v > nv)
        out_UV[i+2].v += 1.0f;
    if (out_UV[i+2].v - out_UV[i].v > nv)
        out_UV[i].v += 1.0f;

    if (out_UV[i+1].v - out_UV[i+2].v > nv)
        out_UV[i+2].v += 1.0f;
    if (out_UV[i+2].v - out_UV[i+1].v > nv)
        out_UV[i+1].v += 1.0f;
}

Answer: The issue is because you're wrapping texcoords around the sphere.
If I take a horizontal slice of your globe and stretch it out flat, the x texcoords look something like this;
0.7    0.8    0.9     0     0.1    0.2    0.3    0.4
 |------|------|------|------|------|------|------|
                ^^^^^^
                      |-wrapping around here

The ugly seam comes from the area's I've marked with the carats (^). In between all your other vertices, the texture coordinates are nicely interpolated from n to n+0.1. However on the last pair of vertices, it's being interpolated all the way between 0.9 and 0, meaning that it flips and squishes the entire texture into that single seam (which is the ugly tear you are seeing.
To solve it, what you need to do is to create a duplicate pair of vertices around the seam, with texture coordinate 1.0. These should like directly on top of the original vertices, and they should probably not connect to them. The texcoord should look like this:
                     1.0
0.7    0.8    0.9     |0     0.1    0.2    0.3    0.4
 |------|------|------||------|------|------|------|

With the 1.0 and the 0 lying on top of each other. Then all areas between vertices will be interpolated evenly.
Comment: Thanks for the kind reply.
what I am not understanding is.. what are duplicate pair of vertices ? how to create them ?  You mean that I need to update the mesh vertices data ?  for example the sphere has 100 vertices and in order to apply texture map I need to update it with suppose 120 or 140 whatever vertices.. ?  like that ?
It should not be like that I think so? the mesh data should be same.. anyways.. could you please suggest me how can I create duplicate vertices... ?
Comment: I have updated the new code. still having the same ugly seam.
Comment: A classical problem, but the best way to describe it I've ever seen. Thanks!


Ordering Different Items among Different Groups

Question: Question 1) Seven different gifts are to be distributed among 10 children. How many distinct results are possible if no child is to receive more than one gift?
The first gift can go to any of the 10 children, the second to any of the remaining 9 children,
and so on. Hence, there are 10 ⋅ 9 ⋅ 8 ⋅ ⋅ ⋅ 5 ⋅ 4 = 604,800 possibilities.
Question 2) In how many ways can 5 different fruits be distributed among four children? (Some children may get more than one fruit and some may get no fruits.)
Total number of ways of distributing 5 different fruits among 4 children = 4*4*4*4*4 = 4^5 ways.
My Question:
Why is the approach different in both questions? I would have imagined for Question 1 that the answer would have been 10^7. But in the problem, we are considering the fact that once a child has been chosen for a gift he/she is not available for the next gift. What gives for the difference in approach?
Answer: The difference is the fact that in question 2 you're told that more than one fruit can be given to any child and also that a child can even end up without getting a fruit. In the first case it hasn't been mentioned that you can give more than 1 gift to the same child. For question 2, if we're not allowed to give more than 1 fruit to a kid, then the solution is $5\times4\times3\times2\times1$ and the $5$ comes in because we can select the fruit that won't be given to any kid in $5$ ways.
Comment: Sorry just made an edit to Question 1. It is assumed that you cannot give each kid more than 1 gift.
Comment: I don't think it is the "at most 1 item per person" that is causing the problem.


Two sites running same code and different config files?

Question: I have a Windows 2008R2 server with IIS, running one site (ASP.NET4.5). All the parameters are written in web.config file.
I have to add a new site, that will run on the same code (same root folder) as the first one, but will read parameters like sql connection strings etc. from its own config file, not from first site web.config.
How can I do that?
Is it possible to run the second site in different app pool?
Both sites will run the same .NET version of course.
Thank you!
Answer: Yes. I've served the exact same code/files from multiple AppPools for years; it works fine.
But all instances will read web.config identically since Microsoft's standard functionality wasn't written to do what you're trying to do. So you will have to implement your own custom solution for determining what instance the code is running under and choose the appropriate configuration variables based on that. You could either store your config data in a custom config section within web.config (defined in "configSections") or have a separate .config file somewhere else.
What I usually do is switch the code's behavior based on the path to the IIS Application it's running under (i.e. the path). E.g. if the site is being served up under "/example1", I pick one set of config data, and if it's served up under "/example2" it gets another set. (Note that you'll also want to handle the config for the Dev Server's URL when you're running your site through VisualStudio.)
Answer: Another solution is to maintain two separate root folders, each with their own web.config, but create links to the directories/files in the other root folder, so you only have to maintain the source in one location.
Powershell goes something like this to create the links the first time:
<code>function mklink { cmd /c mklink $args }

Get-ChildItem "root-source" | Where {($_.PSIsContainer) -band ($_.Name -ne "web.config")} | mklink /d ("root-links-are-here" + $_.Name) $_.FullName

Get-ChildItem "root-source" | Where {(!$_.PSIsContainer) -band ($_.Name -ne "web.config")} | mklink ("root-links-are-here" + $_.Name) $_.FullName
</code>


How to handle highly correlated observations (rows)

Question: What is the best practice to handle highly similar/ autocorrelated observations (rows) in a data set. These highly similar rows could come from recording (some of the) observations at too close timestamps.
This is for example a problem also found in pseudoreplication.
For highly correlated features (columns), one typically applied preprocessing step is dropping some of the columns which show high correlation or which have a high variance inflating factor (VIF).
How would one deal with very similar rows (which possibly have their origin in correlated observations) in the case of a classification task?
In the extreme case of duplicated rows some people drop the duplicated row.
One strategies for removing highly correlated observations could be to compute a n x n distance matrix between all n observations or do a clustering and drop observations which are too close
The question I have are:
a) is there literature related to this question?
b) would removing/subsampling rows with too high correlation improve generalization of the trained classifier? I would be happy if you could present an example or a counter example (or maybe both) in two dimensions for a binary classification.
c) how would an efficient implementation of dropping very similar rows look like in pandas?
PS: I found a related question here Subsampling to account for spatial autocorrelation of observations however it has no answers.
PPS: not randomly moving very similar samples from the training set into the test set is also important for a reliable validation (see pseudoreplication). As far as I know this is typically solved by some group base shuffling which requires however to define a feature based on which this grouping can happen.
Clarification about the type of date I am looking at:

Classification with repeated measurements $x_i$ at different times $i$ from one subject (e.g. measurements 1,2,3,4 come from subject 1, measurements 5,6,7,8,9 come from subject 2,...). Clearly, we have to avoid leakage and make a group split such that measurements from one subject only appear exclusively in the test or train split. However, having 4 strongly correlated measurements from subject 1 might not provide useful, one could aggregate some statistics about each subject, especially if the amount of measurements per subject is random. In this case, gathering the statistics would give equal weight to each subject. The situation becomes, however, more involved if, e.g., subject 1 and subject 2 themselves come from one region in sample space and they would have a small distance between them. Then they are correlated and gathering statistics over both could be beneficial. Is there any best practice which can be applied here? Any method, you would recommend?
Regression with autocorrelated time series. How would you go about it if the samples show high auto-correlation. Subsampling could be done, but is there more?

For both cases, could you please provide a verbose description of methods.
PPPS: this paper https://arxiv.org/abs/2206.14486v1 suggests pruning observations depending on clustering for improved neural net training
Comment: Please provide more details about the nature of your data and the "classification task" you are undertaking. If you have individuals sampled at different times/frequencies and you are using logistic regression or a variant, it might be something as simple as a mixed model. I can't quite figure that out from your description, however. Please provide that information by editing the question, as comments are easy to overlook and can be deleted.
Comment: I do understand that the the answer might depend on the use case. I will try to point out two different scenarios in which I am interested.
Answer: Markov processes, e.g., Markov logistic models, can handle even extremely high serial correlations all the way to absorbing states.  The cluster sandwich robust covariance matrix estimate can account for even complete redundancies in data such as truly duplicated observations (which are effectively ignored by the cluster sandwich approach).
Comment: Is [this](https://www.researchgate.net/publication/250073603_The_sandwich_robust_covariance_matrix_estimator) what you are referring to, or something else?
Answer: A bit of elaboration on Frank Harrell's answer (+1), in response to your addition to the question.
Throwing away data via subsampling is not generally a good idea. You want to use as much information as you have available. Chapter 7 of Frank Harrell's course notes is devoted to such issues in longitudinal measurements, but now goes beyond the original focus of that chapter of his book on generalized least squares for continuous outcomes.
For your second specific question, you can directly model autocorrelation where outcomes can change over a time series. You specify a function that combines time, prior outcome, and the time interval between measurements in a generalized linear model. Adapting an equation on page 7-39 of the current notes, where observation times $t$ are indexed by $i$, you can write a first-order Markov generalized linear model (GLM) as:
$$ g(Y(t_i)|X,Y(t_{i-1})) = \alpha + X\beta + f(Y(t_{i-1}), t_i, t_i - t_{i-1})$$
where $g()$ is the GLM link function, $Y$ is the outcome, $X$ is the set of covariates with coefficients $\beta$ to be estimated, $\alpha$ is an intercept, and the function $f()$

involves any number of regression coefficients for a main effect of $t$, the main effect of time gap $t_i − t_{i−1}$ if this is not collinear with absolute time, a main effect of the previous state, and interactions between these.

If you want higher-order correlations, include more prior outcome observations and intervening gap times.
The illustration in the course notes is for a proportional odds ordinal logistic model; the principles apply in general. This post shows how this can be done for binary outcomes at irregular observation times.
That also addresses part of the first specific question. Beyond that, the big problem with pseudoreplication is in estimating too narrow confidence intervals. One could argue that there's nothing wrong with giving a particular individual with more observations more weight, provided that you recognize those observations within the same individual aren't independent.
The "cluster sandwich robust covariance matrix estimate" starts with a model that assumes "working independence" and estimates the coefficients themselves as if all observations were independent. The covariance matrix is then adjusted for the clusters (subjects in your case). Random effects in mixed models, another standard way to handle multiple observations on subjects, also puts more weight on those with more observations.
Finally, unless you have tens of thousands of observations, your implied split into training and test sets is likely to lose precision in the training and lose power in the testing. Building the model on all the data and evaluating the modeling process by bootstrapping is superior. If you do have that many observations, simply splitting by subjects should be OK; you can check by doing repeated train/test splits.


Trouble trying to eliminate a node from a tree (struct)

Question: As the title says I'm trying to remove a node from a tree having 2 cases:

the node is a leaf that not connected to anything
the node is connected to another node

I was able to make a working function for the second case (the most difficult for me), but the first one (that seemed easy) causes a segmentation fault no matter what I try.
Here is the definition of struct:
struct node {
    int value;
    struct node *sx;
    struct node *dx;
};

typedef struct node *tree;

Here is the module that perform the operation of elimination:
void destroy_node(tree Y, int elem) {
    if (Y->value < elem)
        destroy_node(Y->dx, elem);
    if (Y->value > elem)
        destroy_node(Y->sx, elem);
    else { //
        if (Y->sx == NULL && Y->dx == NULL) {
            free(Y); <-- seg fault
            Y = NULL; <-- seg fault
        }
        if (Y->sx != NULL && Y->dx == NULL) {
            Y->value = (Y->sx)->value;
            free(Y->sx);
            Y->sx = NULL;
        }
        if (Y->sx == NULL && Y->dx != NULL) {
            Y->value = (Y->dx)->value;
            free(Y->dx);
            Y->dx = NULL;
        }
        if (Y->sx != NULL && Y->dx != NULL)
            printf("Can't eliminate that!\n");
    }
    print_everything(Y);
}

Here is the main call:
tree Y = T;
printf("Which one you want to destroy?  ");
scanf("%d", &elem);
destroy_node(Y, elem);

To compile the function I use the command
gcc -std=gnu99 -Wall -Wextra c.c

My environment is a virtual machine ubuntu 17.04 with stock gcc
EDIT 1
Module that build a tree
tree insert_node(tree T, int val) {
    if (T == NULL) {
        T = (tree)malloc(sizeof(struct node));
        T->value = val;
        T->sx = NULL;
        T->dx = NULL;
    } else {
        if ((T->value) < (val)) {
            T->dx = insert_node(T->dx, val);
        }
        if ((T->value) > (val)) {
            T->sx = insert_node(T->sx, val);
        }
    }
    return T;
}

Here there is the call in the main of this module
printf("How many nodes your tree will have?  ");
scanf("%d", &tot);
for (int i = 0; i < tot; i++) {
    printf("What is the %d° node?  ", (i + 1));
    scanf("%d", &val);
    T = insert_node(T, val);
}

P.S. If there are problem regarding the comprehensibility of the program I will copy paste the whole file
Comment: Hiding pointers behind typedefs? Ew.
Comment: Can you add the part where you build the tree?
Comment: @atru inserted the other function that you requested hope it helps
Comment: You forgot to check that `Y` is not null.
Answer: There are missing pieces in your function:

You do not check if Y != NULL.  You would have undefined behavior on an empty tree.
There is a missing else after the first if statement. You mistakenly delete the node if Y->value <= elem.
You do not update the parent pointer when you delete a node.

You should change the API to return the updated value for the pointer argument:
tree destroy_node(tree Y, int elem) {
    tree res = Y;
    if (Y != NULL) {
        if (Y->value < elem) {
            Y->dx = destroy_node(Y->dx, elem);
        } else
        if (Y->value > elem) {
            Y->sx = destroy_node(Y->sx, elem);
        } else {
        if (Y->dx == NULL) {
            res = Y->sx;
            free(Y);
        } else
        if (Y->sx == NULL) {
            res = Y->dx;
            free(Y);
        } else {
            printf("Can't eliminate that!\n");
        }
    }
    return res;
}

Call from main as:
tree T;
...
printf("Which one you want to destroy? ");
if (scanf("%d", &elem) == 1)
    T = destroy_node(T, elem);

Of course you must find a solution to delete nodes with 2 branches.
Comment: Using this instantly made my code works. Obviously i will found a solution to delete node with 2 branches but i usually try to start from a small code working and then adding new function to avoid too much confusion(and error). Btw thanks
Comment: @Allen: that's a good approach. Re-reading the code, I realized the `if (Y->sx == NULL && Y->dx == NULL)` test is redundant. Answer updated and simplified.


Errors Fatal Exception on Two activities

Question: enter code here

  05-31 00:26:46.295: ERROR/AndroidRuntime(4111):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2685)
  05-31 00:32:08.465: ERROR/AndroidRuntime(4301): FATAL EXCEPTION: main
  05-31 00:32:08.465: ERROR/AndroidRuntime(4301): java.lang.RuntimeException: Unable to start activity ComponentInfo{yaraby.y/yaraby.y.yarab}: java.lang.NullPointerException
  05-31 00:32:08.465: ERROR/AndroidRuntime(4301):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2669)
 05-31 00:32:08.465: ERROR/AndroidRuntime(4301):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2685)
 05-31 00:32:08.465: ERROR/AndroidRuntime(4301):     at a ndroid.app.ActivityThread.access$2300(ActivityThread.java:126)
 05-31 00:32:08.465: ERROR/AndroidRuntime(4301):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2038)
  05-31 00:32:08.465: ERROR/AndroidRuntime(4301):     at android.os.Handler.dispatchMessage(Handler.java:99)
  05-31 00:32:08.465: ERROR/AndroidRuntime(4301):     at android.os.Looper.loop(Looper.java:123)
 05-31 00:32:08.465: ERROR/AndroidRuntime(4301):     at android.app.ActivityThread.main(ActivityThread.java:4633)
 05-31 00:32:08.465: ERROR/AndroidRuntime(4301):     at java.lang.reflect.Method.invokeNative(Native Method)
 05-31 00:32:08.465: ERROR/AndroidRuntime(4301):     at java.lang.reflect.Method.invoke(Method.java:521)
 05-31 00:32:08.465: ERROR/AndroidRuntime(4301):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:858)
  05-31 00:32:08.465: ERROR/AndroidRuntime(4301):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
  05-31 00:32:08.465: ERROR/AndroidRuntime(4301):     at dalvik.system.NativeStart.main(Native Method)
 05-31 00:32:08.465: ERROR/AndroidRuntime(4301): Caused by: java.lang.NullPointerException
 05-31 00:32:08.465: ERROR/AndroidRuntime(4301):     at yaraby.y.yarab.onCreate(yarab.java:92)
 05-31 00:32:08.465: ERROR/AndroidRuntime(4301):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
  05-31 00:32:08.465: ERROR/AndroidRuntime(4301):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2633)
  05-31 00:32:08.465: ERROR/AndroidRuntime(4301):     ... 11 more

Yaraby Code
enter code here
 public class yaraby extends Activity {
/** Called when the activity is first created. */
String sentence,sentence1, modifiedSentence;;
EditText inputfld, txt;
TextView Text;
Button Enter, Connect, next;
Socket clientSocket;

DataOutputStream outToServer;
BufferedReader inFromServer ;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    inputfld=(EditText)findViewById(R.id.input);
    Text=(TextView)findViewById(R.id.view);
    Enter=(Button)findViewById(R.id.enter);
    Connect=(Button)findViewById(R.id.connect);

    Text.append( "\n about to create a socket");

    txt=(EditText)findViewById(R.id.txt);
    next = (Button) findViewById(R.id.Button01);

    next.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            try{
                Text.append("PPPPP");
            Intent i = new Intent(yaraby.this, yarab.class);

            startActivity(i);
            Text.append("OPS");
            }
            catch(Error e){
                Log.e("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", e.getMessage());
                Text.append("ofa7ay");
            }

        }});

                  }

public void appendText(View view){
    Text.append( "\n  In chat ");

    try{

    sentence=inputfld.getText().toString();
    sentence1="ingyyyy";
    Text.append( "\n  DataStream creating");
    outToServer.writeBytes(sentence);
    outToServer.writeBytes(sentence1);
    Thread.sleep(1000);
    modifiedSentence = inFromServer.readLine();
    Text.append(modifiedSentence);
    inputfld.setText(null);

    }
    catch(Exception modifiedsentence){
        Text.append("Exception");
    }

}

public void connect(View view){
    try{
        clientSocket= new Socket("192.168.1.6",54611);
        Text.append( "\n created a socket");
        outToServer = new DataOutputStream(clientSocket.getOutputStream());
        Text.append( "\n created a datastream");
        inFromServer = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
        Text.append( "\n created a bufferReader");
        outToServer = new DataOutputStream(clientSocket.getOutputStream());

    }catch(Exception e){
        System.out.println("Error");
    }
   }

yarab code
enter code here
package yaraby.y;

           public class yarab extends MapActivity

   {
Socket clientSocket;
TextView Text;
private MapView mapView;
private MapController mc;
DataOutputStream outToServer;
BufferedReader inFromServer ;
 Button start;
int error = 50;
GeoPoint p, p2;
List<Overlay> mapOverlays;
Drawable drawable, drawable2;
HelloItemizedOverlay itemizedOverlay, itemizedOverlay2;

LocationManager locationManager;

/** Called when the activity is first created. */

@Override
public void onCreate(Bundle savedInstanceState)

{

        super.onCreate(savedInstanceState);

        setContentView(R.layout.main);

        /* Use the LocationManager class to obtain GPS locations */

        LocationManager mlocManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);

        LocationListener mlocListener = new MyLocationListener();

        mlocManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0,
                0, mlocListener);
        mapView = (MapView) findViewById(R.id.mapView);

        // enable Street view by default
        mapView.setStreetView(true);

        // enable to show Satellite view
        mapView.setSatellite(true);

        // enable to show Traffic on map
        // mapView.setTraffic(true);
        mapView.setBuiltInZoomControls(true);

        mc = mapView.getController();

        mc.setZoom(12);
        addOverLays();
          start= (Button) findViewById(R.id.start);

                }

public void addOverLays() {
    String[] coordinates = { "31.216487288475037", "29.932637214660645",
            "30.084123015403748", "51.5002", "-0.1262",
            "31.337149143218994" };

    double lat = 29.98739718380868, lat2 = 29.987810254096985;
    double log = 31.442527770886084, log2 = 31.44258677959442;
    p = new GeoPoint((int) (lat * 1E6), (int) (log * 1E6));
    p2 = new GeoPoint((int) (lat2 * 1E6 ), (int) (log2 * 1E6 ));
    p3 = new GeoPoint((int) (lat3 * 1e6), (int) (log3 * 1e6));
    p4 = new GeoPoint((int) (lat4 * 1e6), (int) (log4 * 1e6));
    p5 = new GeoPoint((int) (lat14* 1e6), (int) (log14 * 1e6));
    p6 = new GeoPoint((int) (lat8 * 1e6), (int) (log8 * 1e6));
    p7 = new GeoPoint((int) (t1* 1e6), (int) (log15 * 1e6));
    p8 = new GeoPoint((int) (lat5 * 1e6), (int) (log5 * 1e6));
    p9 = new GeoPoint((int) (lat6 * 1e6), (int) (log6 * 1e6));
    p10=new GeoPoint( (int) (t4 * 1e6), (int) (log12 * 1e6));
    p11=new GeoPoint( (int) (t2* 1e6), (int) (log14 * 1e6));
    p12=new GeoPoint( (int) (t3* 1e6), (int) (log5 * 1e6));
    p13=new GeoPoint( (int) (t5* 1e6), (int) (log12 * 1e6));
    p14=new GeoPoint( (int) (t6* 1e6), (int) (log11 * 1e6));
    p15=new GeoPoint( (int) ((t6+t1)/2* 1e6), (int) (log3 * 1e6));
    p15=new GeoPoint( (int) (t3* 1e6), (int) (log11 * 1e6));
    p16=new GeoPoint( (int) (lat15* 1e6), (int) (log15 * 1e6));
    p17=new GeoPoint( (int) (lat13* 1e6), (int) (log13 * 1e6));
    p18=new GeoPoint( (int) (lat9* 1e6), (int) (log9 * 1e6));
    p19=new GeoPoint( (int) (lat10* 1e6), (int) (log10 * 1e6));
    p20=new GeoPoint( (int) (lat11* 1e6), (int) (log11 * 1e6));
    p21=new GeoPoint( (int) (lat12* 1e6), (int) (log12 * 1e6));
    mapOverlays = mapView.getOverlays();
    drawable = this.getResources().getDrawable(R.drawable.wit);
    drawable2 = this.getResources().getDrawable(R.drawable.ballon);

    itemizedOverlay = new HelloItemizedOverlay(drawable, this);
    itemizedOverlay2 = new HelloItemizedOverlay(drawable2, this);

    OverlayItem overlayitem = new OverlayItem(p, "Cairo", " over1");
    OverlayItem over2 = new OverlayItem(p2, "ulm", "over2");

    itemizedOverlay.addOverlay(overlayitem);

    mapOverlays.add(itemizedOverlay);

    itemizedOverlay2.addOverlay(over2);
    mapOverlays.add(itemizedOverlay2);

    mc.setZoom(17);

}

public void Location(){

    LocationManager myLocationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);

    LocationListener mlocListener1 = new MyLocationListener();

    LocationManager mlocManager1 = null;
    mlocManager1.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0,
            0, mlocListener1);
        //  Get the current location in start-up
          GeoPoint initGeoPoint = new GeoPoint((int)(myLocationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER)
       .getLatitude()*1000000),(int)(myLocationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER).getLongitude()*1000000));
       mc.animateTo(initGeoPoint);
    mc.setZoom(16);

    drawable21 = this.getResources().getDrawable(R.drawable.ggg);
    itemizedOverlay21 = new HelloItemizedOverlay(drawable21,this);
    OverlayItem over21 = new OverlayItem(initGeoPoint, "offff", "over21");

    itemizedOverlay21.addOverlay(over21);
    mapOverlays.add(itemizedOverlay21);
}

/* Class My Location Listener */

public class MyLocationListener implements LocationListener

{

    @Override
    public void onLocationChanged(Location loc)

    {

        GeoPoint point = new GeoPoint((int) (loc.getLatitude() * 1E6),
                (int) (loc.getLongitude() * 1E6));

        String Text = "My current location is: " +

        "Latitud =" + loc.getLatitude()+

        "Longitud =" +loc.getLongitude() ;

        Toast.makeText(getApplicationContext(),

        Text,

        Toast.LENGTH_SHORT).show();

    mc.animateTo(point);

    }

    private Resources getResources() {
        // TODO Auto-generated method stub
        return null;
    }

    public void onProviderDisabled(String provider)

    {

        Toast.makeText(getApplicationContext(),

        "Gps Disabled",

        Toast.LENGTH_SHORT).show();

    }

    public void onProviderEnabled(String provider)

    {

        Toast.makeText(getApplicationContext(),

        "Gps Enabled",

        Toast.LENGTH_SHORT).show();

    }

    public void onStatusChanged(String provider, int status, Bundle extras)

    {

    }

    protected boolean isRouteDisplayed() {
        return false;
    }

}/* End of Class MyLocationListener */

@Override
protected boolean isRouteDisplayed() {
    // TODO Auto-generated method stub
    return false;
}

           }

Comment: I see that `setContentView()` is called with the same resource identifier (R.layout.main) in both cases, did you really mean to do that? Other than that, it's kinda hard to know what the code in line 92 is specifically.
Comment: You must put this as an answer because it work wiz me :)
Answer: You have a NullPointerException on line 92 of yarab.java, in your onCreate() method. Based on the comment by @dmon, my guess is that you are loading the wrong layout and therefore your attempt to retrieve your MapView fails. However, that is just a guess, since you did not tell us what line 92 of yarab.java actually is.
Comment: could you belive this is line 92 !!


Como obter o último segmento do path?

Question: URLs de exemplo:
content/edit
content/edit/
content/edit?q=
content/edit/?q=

Eu tentei fazer o código mas sempre falha quando a url não possui "/" ou "?" e se tiver "/?" no final. O código que fiz foi:
.*\/([a-zA-Z0-9]*)[\/\?].*

Que pega o valor "edit".
Comment: Quais são os resultados esperados? Em todos a palavra `edit` deverá ser retornada ou no último a parte `?q=` também deverá estar presente no retorno?
Comment: É que a cada edição a pergunta fica mais confusa. Em uma URL `edit?q=teste`, a última palavra seria `teste`, mas o que você precisa é `edit`, correto? Se sim, use a expressão *último segmento do path*, para não gerar qualquer confusão.
Comment: na vdd somente o edit e ignorar as variaveis
Comment: Então não é necessariamente entre as últimas ocorrências de `/`, mas sim sempre o último segmento do *path*?
Comment: Isto ai! mas só preciso da ultima palavra, no caso edit, que podera ser qualquer outra.
Comment: Vc está certo, fiz as alterações
Comment: Posta exatamente como esta o seu .htaccess todo, pois multiplos rewrites podem conflitar.
Answer: Uma maneira bem simples, sem usar expressão regular:
//Obtenha a URL sem as variáveis
$url = $_SERVER['REDIRECT_URL'];

//exploda
$array_url = explode('/',$url);

//Caso a URL termine com /, a última posição do array estará em branco, então contorne isso
$array_url=array_filter($array_url);

//A última posição do array equivale à ultima palavra.
$palavra = array_pop($array_url);

Comment: Apesar da parte do array estar boa na resposta, no entanto `REDIRECT_URL` pode variar e depende muito da configuração do Apache, geralmente vai existir na maior parte dos servidores, mas em questões de fastgci e fpm isso pode ser algo que varia muito. Como disse, a resposta não é ruim, o problema é que o script esta confiando em uma variavel que realmente pode "variar" em diferentes servidores. O melhor seria usar algo como `PHP_SELF`+`parse_url(..., PHP_URL_PATH)`. Entenda como sugestão, pode efetuar seus testes para confirmar.
Answer: A solução mais simples é utilizando PHP, como apresentado em outras respostas, mas se desejar apenas a expressão regular para utilizar junto ao arquivo .htaccess, veja a solução abaixo.
Para responder isso, precisamos primeiro entender a estrutura da uma URI:
  foo://example.com:8042/over/there;param=value;p2;p3?name=ferret#nose
  \_/   \______________/\_________/ \_______________/ \_________/ \__/
   |           |            |              |              |         |
scheme     authority       path          params         query   fragment

Podemos perceber que após o path podem existir os valores de param, query e fragment. Começamos então analisando apenas o path:
Para obter o último segmento do path, utilizamos a expressão regular:
\/?([a-zA-Z0-9_\-+]+)\/?$

Isto é, o valor pode iniciar com uma barra, seguida de uma sequência não nula de letras, números ou _, - e + (pode alterar livremente essa parte), seguida ou não de uma barra, terminando o valor. Desta forma, as seguintes URLs abaixo serão devidamente analisadas:
edit
/edit
/edit/
/content/edit
/content/edit/

Veja funcionando no Regex101.

Agora, devemos adicionar à expressão a parte que analisará a possível existência do params na URL. Para simplificar, como não é de nosso interesse saber quais são os parâmetros do path, vamos considerar como parâmetro qualquer sequência de caracteres diferente de / que segue o caractere ;. Tanto o caractere quando a sequência serão opcionais, então a expressão regular passa a ser:
\/?([a-zA-Z0-9_\-+]+)\/?(?:\;[^\/]*)?$

Assim, tanto as URLs acima como as abaixo funcionarão:
edit
/edit
/edit/
/content/edit
/content/edit/
/content/edit;param=foo
/content;param=foo/edit/

Veja funcionando no Regex101.

A mesma lógica iremos aplicar para a query da URL, sendo definida como qualquer sequência de caracteres que segue o caractere ?. Assim, a expressão regular passa a ser:
\/?([a-zA-Z0-9_\-+]+)\/?(?:\;[^\/]*)?(?:\?.*)?$

Assim, as todas as URLs abaixo irão funcionar:
edit
/edit
/edit/
/content/edit
/content/edit/
/content/edit;param=foo
/content;param=foo/edit/
/content/edit?q=foo
/content/edit/?q=foo

Veja funcionando no Regex101.

Para completar, falta analisar a parte do fragment da URL, sendo definido como qualquer sequência de caracteres que segue o caractere #.
\/?([a-zA-Z0-9_\-+]+)\/?(?:\;[^\/]*)?(?:\?.*)?(?:\#.*)?$

Funcionando, assim, para todas as variações de URL possíveis:
edit
/edit
/edit/
/content/edit
/content/edit/
/content/edit;param=foo
/content;param=foo/edit/
/content/edit?q=foo
/content/edit/?q=foo
/content/edit#foo
/content/edit/#foo

Em todas, o único grupo capturado será edit.

Veja funcionando no Regex101.

A mesma expressão pode ser simplificada para:
\/?([\w+-]+)\/?(?|\;[^\/]*|[?#].*)?$

Colaboração de Guilherme Lautert.

Veja funcionando no Regex101.
Comment: Dava para reduzia a regex, fora isso muito bom e bem explicado +1.
Comment: Assim ja reduz um pouco https://regex101.com/r/g2hcQo/2
Comment: @GuilhermeLautert o que sugere?
Comment: @GuilhermeLautert realmente ficou bem mais simples. Obrigado.
Answer: Acredito que este regex resolve o seu problema:
(\/\w+\/\w+)((\/?$)|(\?.+$))

Criei um teste no link abaixo:
https://regex101.com/r/b48kWg/1
O conteúdo que você precisa está no grupo 1 (verde)
Comment: e se eu tiver somente "content/edit" ou "content/edit?q=123321&outroparametro=432" sem www e etc e queria pegar somente a palavra edit ?
Comment: Não tem problema, porque a regra é o "termina com". Eu adicionei o www... porque acreditei se tratar de uma URL completa, mas vai funcionar do mesmo jeito.
Answer: Pode usar preg_split() para capturar todos os valores entre as barras e chamar array_reverse() para inverter a ordem dos elementos, jogando o último como primeiro. preg_match() verifica se o elmento atual começa com alguma letra caso contrário passa para o próximo elemento isso trata o caso ?Q=abc
function ultimaParteURL($url){
    $segmentos = array_reverse(preg_split('#/#', $url , null, PREG_SPLIT_NO_EMPTY));
    foreach ($segmentos as $item){
        if(preg_match('#^[A-Z]#i', $item)) return $item;
    }
}

echo ultimaParteURL('content/edit/?Q=abc') .'
';
echo ultimaParteURL('content/edit/') .'
';
echo ultimaParteURL('content/edit&abc=12015') .'
';

Exemplo:
Array
(
    [0] => content
    [1] => edit?q=
)

Após a chamada de array_reverse() vira:
Array
(
    [0] => edit?q=
    [1] => content
)

Como obter o último segmento do path?


Trying to pass List of Ints as an argument in scala function when calling it

Question: I've written a function with the following signature
def countChange(money: Int, coins: List[Int]): Int =

When I try to call it and pass arguments I get a type mismatch error
I tried countChange(10, [1, 2]) and countChange(10, List[1, 2]) with no luck
Comment: `[1,2]` is not the syntax for List construction. Lists are not a built in linguistic structure, but just another library. Try `countChange(10, List(1,2))`
Comment: Make it the answer so I can upvote.
Answer: [1,2] is not the syntax for List construction. Lists are not a built in linguistic structure, but just another library. Try countChange(10, List(1,2))


Domain Change from .com to .org

Question: My company wants to change the domain from domain.com to domain.org, how would we do that according to moving the theme, all files, modules, etc. and keeping the Drupal integration intact?
Answer: Unlike Wordpress, Drupal doesn't care on the hostname. Unless you statically mentioned the domain in any custom modules/themes, this will be a straight forward change.

Change the domain name using a local host file.
Change the trusted hosts configuration (for D8, in settings.php)
Try accessing the site after the drupal clear cache, using drush.

If you are experiencing any issues, try searching for domain.com using grep and replace. Better to refactor the code without the domain hardcoded.
Edit: The links hard coded in WYSIWYG editors like ckeditor can create issues. You may have to update programatically or manually.
Edit2: You can use pathlogic module (not tested, d8 version is usable). to reformat the URLs in the content.
Comment: Indeed it can :) [Pathologic](https://www.drupal.org/project/pathologic) can help I believe
Comment: What about links in WYSIWYGs?
Comment: Ah! that can create issues.

Domain Change from .com to .org


Pattern searching in a file and replacing the found results

Question: I'm trying to write a simple program that will open text files in given directory search for all strings that match a given pattern and replace them with the desired string while removing all other info. I have two .txt files:
User_321.txt which contains:
321_AliceKelly001.jpg [size_info] [date_info] [geo_location_info] ... [other info]
321_AliceKelly002.jpg [size_info] [date_info] [geo_location_info] ... [other info]
321_AliceKelly003.jpg [size_info] [date_info] [geo_location_info] ... [other info]
 ...
321_AliceKelly125.jpg [size_info] [date_info] [geo_location_info] ... [other info]

and User_205.txt which contains:
 205_CarlCarlson001.jpg [size_info] [date_info] [geo_location_info] ... [other info]
 205_CarlCarlson002.jpg [size_info] [date_info] [geo_location_info] ... [other info]
 205_CarlCarlson_003.jpg [size_info] [date_info] [geo_location_info] ... [other info]
 205_CarlCarlson007.jpg [size_info] [date_info] [geo_location_info] ... [other info]

I want User_321.txt to contain:
321_AliceKelly_001.jpg
321_AliceKelly_002.jpg
321_AliceKelly_003.jpg
 ...
321_AliceKelly_125.jpg

and User_205.txt to contain:
 205_CarlCarlson_001.jpg
 205_CarlCarlson_002.jpg
 205_CarlCarlson_003.jpg
 205_CarlCarlson_007.jpg

So I simply want to add "_" between the name and last 3 digits. I'm able to handle the case where all the entries are uniform, that is only contain entries of the following form:
     \d\d\d_[a-zA-Z]\d\d\d.jpg [size_info] [date_info] [geo_location_info] ... [other info]

with the following code:
import os, re,

path = 'C:\\Users\\ME\\Desktop\\TEST'
text_files = [filename for filename in os.listdir(path)]

desired_text = re.compile(r'\w+.jpg')
#desired_ending = re.compile(r'$[a-zA-Z]\d\d\d.jpg')

for i in range(len(text_files)):
    working_file = path + '\\' + text_files[i]
    fin = open(working_file, 'r')
    match = ''

    for line in fin:
        mo1 = desired_text.search(line)
        if mo1 != '':
            match += mo1.group()[:-7] + '_' + mo1.group()[-7:]+'\n'

    fin.close()

    fout = open(working_file, 'w')
    fout.write(match)
    fout.close()

I'm having a difficult time with the second case, that is when I have an entry that is already in the desired form, like with:
 205_CarlCarlson_003.jpg [size_info] [date_info] [geo_location_info] ... [other info]
 205_CarlCarlson007.jpg [size_info] [date_info] [geo_location_info] ... [other info].

I would like for it to skip renaming the entry that is already in the desired form and continue with the rest.
I've had a look at How to search and replace text in a file using Python? and Cheap way to search a large text file for a string, and Search and replace a line in a file in Python. These cases seem to be concerned with searching for a specific string and replacing it with another using the fileinput module. I would like to do something similar but be a little more flexible in its search.
Comment: Replace the `desired_text` regex with `r'^\s*\d{3}_[^\W_]+\.jpg'`. If there is a match, add a `_`. If there is no match, the `_` must be there.
Answer: You can use parentheses for grouping and capturing
\b(\d{3}_[a-zA-Z]+)(\d{3}\.jpg)

and replace with \1_\2 to add an underscore in between.

\b matches a word boundary
Rest like your sample form, separated in two groups.

See demo at regex101 (Python code generator)
Answer: I have slightly modificated your code, handling the two different cases, and it seems to work:
import os, re

path = 'C:\\Users\\ME\\Desktop\\TEST'
text_files = [filename for filename in os.listdir(path)]

desired_text1 = re.compile(r'^\d{3}_[a-zA-Z]+\d{3}.jpg')
desired_text2 = re.compile(r'^\d{3}_[a-zA-Z]+_\d{3}.jpg')

for i in range(len(text_files)):
    working_file = path + '\\' + text_files[i]
    fin = open(working_file, 'r')
    match = ''

    for line in fin:
        mo1 = desired_text1.search(line)
        mo2 = desired_text2.search(line)
        if mo1:
            match += mo1.group()[:-7] + '_' + mo1.group()[-7:]+'\n'
        elif mo2:
            match += mo2.group() +'\n'

    fin.close()

    fout = open(working_file, 'w')
    fout.write(match)
    fout.close()

Answer: You can do that:
with open('source.txt') as f:
    with open('destination.txt', 'w') as g:
        for line in f:
            parts = line.split(None, 1)
            if parts[0][-8:-7] == '_':
                g.write(parts[0] + '\n')
            else:
                g.write(parts[0][:-7] + '_' + parts[0][-7:] + '\n')

Feel free to change \n to \r\n if you want a Windows newline sequence.


An admin-friendly approach to establishing a permissions relationship between a file group and a user

Question: The need is that when a new client project begins, that the client be given a username and password and have access to a specific piece of content that, in turn, gives access to download files, specific to that client, that were uploaded previously.
The ideal would be for the admin to have only these steps:

Create the project content
Create the project user
Bulk upload the files

This is a nontechnical admin, so the need is to avoid granular steps for creating accounts or setting up folders, permissions, etc.
The concern for 1. is restricting access to the 'project'. I'm thinking that hooking content access and simply comparing the project name to the username (both would be the same).
The approach for 2. concerns linking the files uploaded with FileZilla to the content. It would be great if all files could be uploaded to the same folder, and then admin then do one selection to link several to the content/user. The less-desired approach would be uploading each project's files to a new folder.
I don't know if filefield_sources would created multiple instances of a file field so that each file would be listed when viewing the content, or whether it would need to be using something like IMCE to let the user browse, then download, from a folder that is linked to the username like the content access was.
Another thought is OG, but that might be overkill, and it's not ported yet.
Answer: The concern for 1 : you can use Permissions by field

By adding fields of type Permissions by fields, you can manage access
  to the node hosting these field by referencing other entity and
  specifiy which access type you want to grant (none/standard
  permission, view, update, delete) for users which reference same
  entities (node, term, role or other users). You can also grant access
  to the node directly per user if needed.

The approach for 2 : (without using Fillezilla, but only backoffice) You can use Plupload to upload to upload files (pdf, jpeg...) massively through a content type

.After, you can link "file" content type to a project with a field entity reference in your content type "project". Add a "permission field" in your content type "file" to restrict access.

I dont know if I answer your question correctly


Linear regression model in distress inventory

Question: I am trying to analyze the problem of vacant seat in a multiplex and build a machine learning model which gives a forecast of how many seats will remain vacant on a given day.
Should linear regression model be perfect here ?
Comment: If you visually inspect scatterplots of all variables vs. vacant seats, and you see clear and obvious indication that there is a linear relationship in each plot, then linear regression should be a useful analysis tool - if - you have all necessary variables quantified for analysis.
Comment: I am using day of week, movie rating, price as the variables, is there anything else you think should be there
Comment: I would not go to the theater if it were raining, so maybe some indication of local weather conditions?
Comment: Is there any reference or document which you can share on where to start coding
Comment: I think you can use most spreadsheets for multiple linear regression, and you should easily find tutorials for multiple linear regression is your choice of programming languages, See the answer to this question posted below for more suggestions on modeling methods. I do not know if linear regression is good here - that is the reason for my scatterplot suggestion.
Answer: Generally you never know what algorithm will provide you the best result. Therefore, try to implement most of them and compare their performance.
Linear regression is usually the simplest algorithm. So try other algorithms as well. Ensemble methods often produce best results.
Choose an evaluation criteria such as MSE or RMSE and check which algorithm gives the least value of RMSE.
Also, try implementing cross validation to keep a check on your model's performance.


choose between ancova model and one-way anova

Question: Let's say that I want to know three training program effectiveness. Our independent variable is categorical variable (with three levels). Our response variable is after-train scores. Then I introduce a co-variate variable: before-training scores.  I introduce a new response variable the score difference between after train and before train.  (Y = after train score - before train scores)
Now I have two models in R
(1) one way anova, Y~training program (p-value 4.921e-11)
(2) ancova: after train ~ before train + train program (p-value  3.360e-11)
both output leads to same conclusion and very similar p-value.
Now, I'm confused which model to choose, what criteria should I look at to select a better model?
Answer: If there is correlation between treatment assignment and pretest score, the ANCOVA will be biased, and you should use the change-score ANOVA instead. Otherwise, the ANCOVA will have a bit more power. If you did a randomized experiment, asymptotically the estimates will be equal (assuming effective randomization). Otherwise, if people get to choose (or the researchers choose) which treatment to take based on some characteristic of the participant, then there may be a correlation between treatment assignment and pretest score.
I would recommend presenting the change score ANOVA, and perhaps mentioning that the same results were obtained from the ANCOVA.


DrupalDefaultEntityController invalid argument supplied for foreach

Question: Been trying for the last hour to work this one out.
$query = new EntityFieldQuery();
$query -> entityCondition('entity_type', 'node')
       -> entityCondition('bundle', 'subscription');

$results = $query->execute();

if(isset($results['node'])) {
    $subscription_nids = array_keys($results['node']);
    $nodes = node_load_multiple($subscription_nids, TRUE);
    return $nodes;
} else {
    return FALSE;
}

This is a very simple version of the entire query, but the error is exactly the same:
Warning: Invalid argument supplied for foreach() in DrupalDefaultEntityController->buildQuery() (line 290 of /var/www/ml/data/www/ml.mailapproved.com/includes/entity.inc).

I don't understand what's wrong here.
Answer: The 2nd argument for node_load_multiple() is an array of conditions; currently you're providing a boolean so when the buildQuery function tries to iterate over the variable you get a warning.
The 3rd argument is to reset the cache (I guess that's what you're trying to do), so the call should be:
$nodes = node_load_multiple($subscription_nids, array(), TRUE);


Herbert B. Enderton - Elements of set theory - Chapter 3 Relations and Function

Question: I'm currently reading Elements of set theory by Herbert B. Enderton, and at Chapter 3, Relations and Function, I am faced with this lemma and I am having a hard time understanding it.
If $\langle x,y\rangle \in A$, then $x$ and $y$ belongs to $\bigcup\bigcup A$.
Proof:
We assume that $\{\{x\},\{x,y\}\} \in A$. Consequently, $\{x,y\} \in \bigcup A$ since it belongs to a member of $A$. And from this we conclude that $x\in \bigcup\bigcup A$ and $y \in \bigcup\bigcup A$.
From what I understand $A$ is a set of ordered pairs of elements of $R$, that is, a subset of $R\times R$ and $\bigcup A $ should be the field($A$). I'm confused as to what $\bigcup\bigcup A$ is and how $x$ and $y$ would be a member of $\bigcup\bigcup A$. And shouldn't $x$ and $y$ both just be a member of $R\times R$?
Your explanation will be kindly appreciated. Thank you.
If you want to have a closer look at it : (Chapter 3.2, Lemma 3.16) http://p-adic.com/Set%20Theory.pdf
Comment: Where did $R$ come from? Neither the statement of the lemma nor its proof mention it.
Comment: I believe maxxxxx was referring to $A$ as a binary relation on some set $R$, but that is indeed confusing
Comment: It is not clear from this post what $UA$ and $UUA$ mean. Did you mean to write $\bigcup A$ and $\bigcup\bigcup A$?
Comment: Yes the R is mentioned as the set for the binary relation A. And so A would be the subset of the coordinate plane R x R. Very sorry for the confusion.
Comment: @John Douma Yes I meant ⋃A and ⋃⋃A. Sorry for the confusion, I am new to this.
Answer: Here are a few points that hopefully provide some clarification.
$A$ isn't necessarily a relation on a set, as you assume. It might just happen to have an ordered pair in it. This fact will apply to relations, which only have ordered sets in them, but it doesn't require that.
The $\bigcup$ means union of a collection of sets, so $\bigcup A=\{x:x\in y\mbox{ for some }y\in A\}$.
In developing basic set theory where everything is a set, ordered pairs $(x,y)$ are defined as $\{\{x\},\{x,y\}\}$. (You don't want to think of an ordered pair as a different type of object, you want to think of it as a particular set that depends on the $x,y$ in the pair.)
So if $(x,y)=\{\{x\},\{x,y\}\}\in A$, then the elements of that set are in $\bigcup A$. In particular, $\{x,y\}\in\bigcup A$.
Then if you look at $\bigcup\bigcup A$, this is repeating the definition above but instead of starting with $A$, you are starting with $\bigcup A$. And $x,y$ are elements of something (namely $\{x,y\}$) that is in $\bigcup A$.
Comment: Understood. Thank you for your explanation.


Xamarin Forms - Xamarin.Forms.Platform.UWP.ImageRenderer.UpdateAspect()

Question: I saw some post about it but, unlike them, me it only happens since the update of VS2015 to VS2017, any idea?
<code>at Xamarin.Forms.Platform.UWP.ImageRenderer.UpdateAspect()
at Xamarin.Forms.Platform.UWP.ImageRenderer.<OnElementChanged>d__3.MoveNext()
    End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.AsyncMethodBuilderCore.<>c.<ThrowAsync>b__6_0(Object state)
at System.Threading.WinRTSynchronizationContext.Invoker.InvokeCore()"
</code>
My project is a Forms Portable Project, tell me if you want any details, I'll edit the question ! Also, I use a renderer for Android, but not for UWP, it works on android, but it shouldn't be the problem since it worked before
Thank in advance
Comment: It's weird, but I created another project, and copied back my work, piece by piece, and I found which `Image` was creating the problem. It's on a "splash page" which is here only to redirect to the Login page or the Main page, and I feel like, the pages are switching before the image could appears, maybe it's the problem, I don't know
Answer: It's probably a bug in Xamarin Forms: https://bugzilla.xamarin.com/show_bug.cgi?id=37022
Updating Xamarin Forms should do the trick. I installed Xamarin.Forms version 126.96.36.199-pre3, which solved my problem.


Customizing Tank_Auth table field names for CodeIgniter

Question: I am a beginner learning codeigniter to build a website. For authentication feature, i use tank_auth library and it works fine if I dont alter the tank_auth table field names.
Then, to combine the tank_auth's 'users' table with my existing 'users_info' table, I modified the field names 'new_email_key' and 'username' as NewEmailKey and UserName respectively.
The above specified field name changes were done in libraries\Tank_auth.php, models\tank_auth\users.php and controllers\auth.php files.
In the database, the submitted data are stored right in the table. But in the activation email received, i am getting the following errors:

Message: Undefined variable: username
Filename: email/activate-html.php
Message: Undefined variable: new_email_key
Filename: email/activate-html.php

Is it safe to use the tank_auth table field names as it is in our CI projects?
Is there any clear documentation written on how to customize and use the tank_auth 'users' table field names?
I am stuck with these error messages as i dont figure out where else the field names need to be altered in tank_auth.
Any help appreciated.
Answer: These errors you are listing are simple "undefined variable" errors, like it says, I'm not sure what is confusing here.
Have you looked at the mailing function? Or googled the error meaning? Tank Auth's mail uses an array for sending mail.
$data['username'] = "Bob";
$data['new_email_key'] = "1249ufasiojlk215ifasdy243jhaslkjhasjkghasd";

mail_function_name($data)

that data is passed to the mail function which uses the /email/activate-html.php view/template.
I don't believe there is Tank_Auth modification documentation as the PHP is VERY straight forward, and well commented, if you are having trouble with it, it means you don't understand the code, and the fault lies in your ability to understand WHAT is being done in the code, not in the documentation of TankAuth.  Documentation won't really save you here.
Learn what the errors are (ie, undefined variable) and try to fix them one by one.
Comment: Hi jakob, Being a novice in php, i will take up your suggestions and will figure it out by self. Thanks..
Answer: Since Tank_auth's documentation does not seem to mention config setting for this,
sending such an error message is unexpected and may be taken as a bug.


"Sistema de variáveis" com expressões regulares

Question: Tenho um arquivo mais ou menos assim:
%usuario: 'Anônimo'
Olá %{usuario}

(Esse é só um exemplo e não é o caso real), mas creio que se fosse explicar o problema real daria bem mais trabalho para entender, então é o seguinte: eu sou péssimo em expressões regulares e tenho que exibir esse arquivo substituindo as variáveis que sempre estarão nesse modelo:
%var_name = valor;

E exibi-las quando forem requisitadas, dessa forma: %{var_name}
Comment: vc está montando um sistema de template?
Comment: Não é por nada, mas regex é a última coisa a se usar num caso desses.
Comment: Não compreendto qual é o resutado final a que quer chegar. Pode explicar mais na pergunta?
Comment: Se eu declarar uma variável idade com valor de 17, e no arquivo houver 'Eu tenho %{idade} anos de idade' a saída seria 'Eu tenho 17 anos de idade' entendeu? (Eu não posso editar o arquivo por que está fora do meu servidor)
Comment: O que exatamente pode ter em ´valor´? Me parece que vai ter que criar algum tipo de minilinguagem para lidar com strings/números. Um `eval` não seria legal já que o arquivo não está no seu servidor..
Comment: Sim é mais ou menos um sistema de template. @Bacco eu estava pensando em usar regex para devolver o nome da variável e o valor dela, e usar para substitui-los nos arquivos, mas se você tem um método melhor sinta-se a vontade para compartilha-lo.
Comment: @Júnior postei uma solução bem didática para que fique fácil você aproveitar e adaptar conforme o uso. Regex seria matar pombo com tiro de canhão.
Answer: Solução recomendada sem regex:
O exemplo a seguir faz a mesclagem de dois textos, um com as variáveis e outro com os templates. Creio que fica bem fácil adaptar para seu uso:
<?php

   $variaveis = <<<DELIMITADOR
      usuario: chico
      mensagens: 17
DELIMITADOR;

   $texto = <<<DELIMITADOR
      Ola %{usuario}, voce tem %{mensagens} mensagens!
DELIMITADOR;

   $linhas = explode(chr(10), $variaveis); // divite o texto em array, pela quebra de linha
   foreach ($linhas as $linha) {
      $partes = explode(':',$linha);       // divide cada linha em 2 partes, pelos ":"
      $variavel = trim($partes[0]);        // Remove os espaços em branco
      $valor= trim($partes[1]);            // Remove os espaços em branco
      // Agora, basta fazer a troca da %{variavel} pelo valor:
      $texto = str_replace('%{'.$variavel.'}',$valor, $texto);
   }

   echo htmlentities($texto);

?>

Resultado:
Ola chico, voce tem 17 mensagens!

Basta adaptar as declarações das variáveis e do texto pro seu caso, ou simplesmente ler ambos de arquivos externos.

Mesmo que esteja tudo num arquivo só, basta usar o mesmo princípio do foreach e do explode para separar o arquivo em várias linhas, e dividir a parte das variáveis da parte do template em si (por exemplo, verificando se a linha inicia com %).
Answer: Dependendo dos requisitos (já que foi mencionado que a pergunta é um exemplo simplificado), o objetivo de substituir variáveis e gerar conteúdo baseado em um modelo vindo de fora do programa pode ser alcançado com um mecanismo de templates.
Vantagens
Não reinventar a roda
É melhor reaproveitar o árduo trabalho de outros desenvolvedores do que implementar algo assim "do zero". Você evita gastar tempo próprio e evita muitos erros e percalços.
Mais recursos (formatação, listagem, variáveis)
A princípio pode ser que seja necessário apenas substituir um ou dois campos. Mas o que fazer quando a entrada contiver, digamos uma lista de itens? E a formatação de datas?
A vantagem de usar um template engine genérico é que ele já vem "de brinde" com esses recursos, e outros.

Desvantagens
Memória e armazenamento
Usar uma template engine provavelmente vai agregar mais arquivos e classes do que uma solução própria mais simples.
Desempenho
Dependendo dos recursos necessários, uma template engine pode ser menos eficiente, já que tem muitos recursos não usados. Entretanto, dependendo da quantidade de operações realizadas de substituição, isso o quadro pode mudar.

Exemplos de template engines
Blitz
Código de exemplo:
$View = new Blitz();
$View->load('hello {{ BEGIN block }} {{ $name }} {{ END block }}');
$View->block('/block', array('name' => 'Dude'));
$View->display();

Produz:

"hello Dude "

phpTenjin
Template:
Hello {==$name=}!

O template é convertido para PHP:
<?php echo 'Hello ', $name, '!'; ?>

A execução pode ser feita assim:
require_once 'Tenjin.php';
$engine = new Tenjin_Engine();
$context = array('name'=>'World');
$output = $engine->render('ex.phtml', $context);
echo($output);

Saída:

Hello World!

eZ Components - Template
Código para execução:
// Autoload classes ezcomponent
function __autoload( $className ) {
    ezcBase::autoload( $className );
}

//cria engine com configuração padrão
$t = new ezcTemplate();

//passar variável para o template
$t->send->a = 1;

// compila o template e imprime a saída
echo $t->process( "hello_world.ezt" );

Template:
{use $a, $b = 2}
{$a}, {$b}

Saída:

1, 2

Dwoo
Template:
Hello {$name}

Código para execução:
require 'lib/Dwoo/Autoloader.php';
\Dwoo\Autoloader::register();

$dwoo = new \Dwoo\Core();
$data = array('name'=>'World');
$dwoo->output('caminho/template.tpl', $data);


Finding a pair of vectors in $u$, $v$ in R that span the set of all x in R^4 that are mapped into the zero vector..

Question:
Find a pair of vectors in $u$, $v$ in $\mathbb R^4$ that span the set of all $x \in \mathbb R^4$ that are mapped into the zero vector by the transformation $x\rightarrow Ax$
Let $A = \begin{bmatrix}1&3&-3&-4\\0&1&4&-3\\-3&-10&5&15\end{bmatrix}$

$u = \begin{bmatrix}\end{bmatrix}$ , $v = \begin{bmatrix}\end{bmatrix}$
Any tips or advice would be great. I'm not sure how to obtain my two $4 \times 1$ vectors $u$ and $v$
I put the matrix in RREF Form and got
$\begin{bmatrix}1&0&0&237/9\\0&1&0&-59/9\\0&0&1&8/9\end{bmatrix}$
Comment: Try solving the associated set of simultaneous linear equations, or equivalently, row-reducing the matrix.
Comment: Should I put it in REF form or RREF?
Comment: RREF will make the solution set clearer.
Comment: Okay @DavidWheeler I got it in RREF form
Comment: Okay @DavidWheeler I got it in RREF form, see updated OP
Comment: Well, you did something wrong when computing the RREF, since what you have says that *no* vectors other than 0 get mapped to 0.
Answer: Note that the question is asking to show find the kernel of the matrix $A$. I am under the assumption that $A$ is not an augmented matrix.
As finding the rref is a straightforward execution, I have shown it below
$A'=\begin{pmatrix}
1&0&-15&5\\
0&1&4&-3\\
0&0&0&0
\end{pmatrix}$
Suppose $A'\vec{x}=0$ where $\vec{x}=\begin{bmatrix}
x_1\\
x_2\\
x_3\\
x_4
\end{bmatrix}$.
We have the free variables $x_3=s$ and $x_4=t$ and $x_2=-4s+3t$ and $x_1=15s-5t$.
Thus, any
$$\vec{u}=s\cdot\begin{bmatrix}
15\\
-4\\
1\\
0
\end{bmatrix}:s\in\mathbb{R} \quad\!\!\text{and} \quad\!\!\vec{v}=t\cdot\begin{bmatrix}
-5\\
3\\
0\\
1
\end{bmatrix}:t\in\mathbb{R}$$
span the set of all vectors $\vec{x}\in\mathbb{R^4}$ such that $A\vec{x}=0$. In other words, $A\vec{x}=0 \quad \forall \quad\!\!\vec{x}=\vec{u}+\vec{v}$
Note that row reduction does not change the solution to the system of linear equations.
Comment: The brackets [] and parentheses () are just personal preferences. I tend to use brackets for row or column vectors and () for all else.
Comment: The definition of reduced row echelon form is that
1. It is in row echelon form
2. Every leading coefficient is $1$ and all other entries in that *column* are zeros.
Comment: 1. add 3 times the 1st row to the 3rd row
--
2. add 1 times the 2nd row to the 3rd row
--
3. add -3 times the 2nd row to the 1st row
Comment: First of all, why does one of your matrices have ( ) and the other have [ ] . I never understood what the difference is? Second of all, How is your matrix in RREF when you don't have a 1 under the 4 ?
Comment: So the last row has no "leading coefficient" correct?
Comment: That is correct. Also, when I found the rref, I did not consider $A$ as an augmented matrix as it would not make much sense to the problem.
Comment: How did you get 0 in the last row last column? I'm getting 16.


use of substr in extracting the value

Question: I have the following value as shown ...
<xsl:variable name="abcbegid">
<xsl:value-of select="$atr/@lattier" />

which brings the value as  treId1, but I want to extract only the last digit that is 1 ,
please advise how to extract that through substr function
what I have tried is that..
<xsl:variable name="abcbegid">
    <xsl:value-of select=" substring ($atr/@lattier,5)" />
</xsl:variable>

Comment: there is also substring-after and substring-before. maybe those come in handy? Best regards, Peter
Comment: can you please convert my example into that as I want to extract the last digit, Thanks inadvance
Comment: @peter Please advise..!!
Comment: Can you give some examples of possible values? Will there always be a single digit at the end of them, for example? Or can there be two digits, like "treld12", in which case would you want "2" or "12"?
Comment: @peter there will be only two values that are  treId1 and  treId0 , and I want to extract the last one that is  is 0 or 1 , always
Comment: When you do `` what do you currently get returned?
Answer: substring("wewewe4",string-length("wewewe4"))

returns "4"
Answer: I think Kevin's solution is good. Use that one or do:
<xsl:value-of select="substring-after($atr/@lattier,'d')"/>

That would output the character after the "d".

use of substr in extracting the value


Raspberry PI 3 Python not writing correctly

Question: I am now playing around with my Raspberry PI using Telegram Bot.
What I want to do is simple: My Telegram Bot will have a few functions, at the moment he is only responding to me but I would like to make some kind of "registration" system. There is a text file with five Chat ID's and the passwords that look like this:
000000000
000000000
000000000
56*******
000000000
password

And the code is:
def usradd(chat_id)
    count = 0
    f = open("home/pi/...")
    e = f.readline()

    while count < 6
        if '000000000' in e:
           print >> f, str(chat_id)
           bot.sendMessage(chat_id, "You now have access")
           count = 5
           f.close()
        elif '000000000' not in e and count != 5:
           count += 1
           e = f.readline()
        elif count == 5
           count = 6
           bot.sendMessage(chat_id, "Sorry, no more space for users")
           f.close()

It almost works as it should. It does not overwrite the first 000000000 but the second one. And when it reaches the last one, it even overwrites the "password".
Any idea what I'm doing wrong here?
Comment: For one thing, one of `'000000000' in e` and `'000000000' not in e` will always be true, so your last `elif` will never execute.
Comment: `e = readline()` is going to throw a `NameError`.
Comment: You should probably change the last `elif` to `if`. And you should probably also break out from the while loop when you have written an entry (provided I understand what you are trying to do).
Comment: Sorry I forgot something, code is now the same as in the python file
Answer: When you have read the first line, the file pointer is on the start of the second line. Therefore the write to the file will happen there. You need to reposition the file pointer if you want to write on a particular location in the file.
For example, to start writing at the start of the file:
f.seek(0, 0)

Answer: Thanks to matli for the hint with f.seek(0,0)
This is the code now and it works:
def usradd(chat_id)
count = 0
f = open("home/pi/...")
e = f.readline()

while count < 6
    if '000000000' in e:
       r = 10 * count
       f.seek (r , 0)
       print >> f, str(chat_id)
       bot.sendMessage(chat_id, "You now have access")
       count = 5
       f.close()
    elif '000000000' not in e and count != 5:
       count += 1
       e = f.readline()
    elif count == 5
       count = 6
       bot.sendMessage(chat_id, "Sorry, no more space for users")
       f.close()


Saving values of a multistep form into custom entity fields

Question: I'm building a module that implement a multistep form based on a custom entity.
The entity contains fields which are created by the install file.
I was able to create the steps and if I print the $form_state[storage] array in the last step I can see all the values entered all along the form.
But when I submit the last step the entity is empty.
This is what I have in the last_step_submit:
$organisation = entity_ui_form_submit_build_entity('organisation',$organisation, $form, $form_state);
$organisation->save();
drupal_set_message(t('The organisation: @name has been saved.', array('@name' => $organisation->name)));
$form_state['redirect'] = 'admin/organisations';

I know that I'm missing something but really I can't figure out what.
I'm quite new in module developing and I'd appreciate any help.
Answer: After struggling for a couple of days I finally was able to store the values in the entity.
The first mistake was that I forgot to pass my entity ('organisation') as an argument in the primary hook_form:
  // Return the current form
  $function = $form_state['storage']['step'];
  $form = $function($form, $form_state, $organisation);
  return $form;

The second was that I had to build and save my entity each step with the code I attached in this question.
$organisation = entity_ui_form_submit_build_entity('organisation',$organisation, $form, $form_state);
$organisation->save();

Now I have my custom entity with custom fields and a multistep conditional adding form!
This is the code if someone else need the same functionality.
Primary form and submission functions:
function organisation_form($form, &$form_state, $organisation) {
  if ($form_state['rebuild']) {
      $form_state['input'] = array();
  }
  if (empty($form_state['storage'])) {
// No step has been set so start with the first.
   $form_state['storage'] = array(
      'step' => 'organisation_first_form',
   );
  }
// Return the current form
  $function = $form_state['storage']['step'];
  $form = $function($form, $form_state, $organisation);
  return $form;
}

function organisation_form_submit($form, &$form_state) {
 $values = $form_state['values'];
 if (isset($values['back']) && $values['op'] == $values['back']) {
   // Moving back in form.
   $step = $form_state['storage']['step'];
   // Call current step submit handler if it exists to unset step form data.
   if (function_exists($step . '_submit')) {
     $function = $step . '_submit';
     $function($form, $form_state);
   }
// Remove the last saved step so we use it next.
$last_step = array_pop($form_state['storage']['steps']);
$form_state['storage']['step'] = $last_step;
  }
  else {
   // Record step.
   $step = $form_state['storage']['step'];
   $form_state['storage']['steps'][] = $step;
   // Call step submit handler if it exists.
   if (function_exists($step . '_submit')) {
      $function = $step . '_submit';
      $function($form, $form_state);
   }
  }
return;
}

This is one of the steps and its submission function.
function organisation_second_form($form, $form_state, $organisation) {
  $form['#parents'] = array();
  // These variables are needed to build field forms.
  $entity_type = 'organisation'; // Substitute with any entity type.
  $bundle_name = 'organisation'; // Substitute with the entity's bundle.
  $entity = $organisation;
  $langcode = LANGUAGE_NONE; // Substitute as appropriate.

  $field_name = 'hub_position_activities';
  $items = field_get_items($entity_type, $entity, $field_name);
  $field = field_info_field($field_name);
  $instance = field_info_instance($entity_type, $field_name, $bundle_name);
  $field_form = field_default_form($entity_type, $entity, $field, $instance, $langcode, $items, $form, $form_state);
  $form += $field_form;

  $field_name = 'hub_market';
  $items = field_get_items($entity_type, $entity, $field_name);
  $field = field_info_field($field_name);
  $instance = field_info_instance($entity_type, $field_name, $bundle_name);
  $field_form = field_default_form($entity_type, $entity, $field, $instance, $langcode, $items, $form, $form_state);
  $form += $field_form;

  $form['back'] = array(
    '#type' => 'submit',
    '#value' => t('Back'),
    '#limit_validation_errors' => array(),
    '#submit' => array('organisation_second_form_submit'),
    '#weight' => 499,
  );
  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Next'),
    '#weight' => 500,
  );
  return $form;
}

function organisation_second_form_submit($form, &$form_state) {
  $values = $form_state['values'];
  $form_state['rebuild'] = TRUE;
  if (isset($values['back']) && $values['op'] == $values['back']) {
    $input = $form_state['input'];
    // The user clicked the back button, save values that were input
    if (isset($input['hub_position_activities'])) {
      $form_state['storage']['hub_position_activities'] = $input['hub_position_activities'];
    }
    if (isset($input['hub_market'])) {
      $form_state['storage']['hub_market'] = $input['hub_market'];
    }
    $form_state['storage']['step'] = 'organisation_first_form';
  }
  else {
    $form_state['storage']['hub_position_activities'] = $values['hub_position_activities'];
    $form_state['storage']['hub_market'] = $values['hub_market'];
    $organisation = entity_ui_form_submit_build_entity($form, $form_state);
    $organisation->save();
    $form_state['storage']['step'] = 'organisation_third_form';
  }
}

And the last submission function.
function organisation_last_form_submit($form, &$form_state) {
  $values = $form_state['values'];

  if (isset($values['back']) && $values['op'] == $values['back']) {
    $form_state['storage']['step'] = 'organisation_second_form';
    $form_state['rebuild'] = TRUE;
  }
  else {
    $form_state['storage']['hub_equipment_measurement'] = $values['hub_equipment_measurement'];
    $form_state['storage']['hub_equipment_software'] = $values['hub_equipment_software'];
    $organisation = entity_ui_form_submit_build_entity($form, $form_state);
    $organisation->save();
    drupal_set_message(t('The organisation: @name has been saved.', array('@name' => $organisation->name)));
    $form_state['redirect'] = 'admin/organisations';
  }
}

Perhaps there were easier way to achieve this goal but, so far, is the only one that worked for me. If anyone has better solutions I'm eager to know them.
Thanks to Alex Weber for his great tutorial on how to get the form for existent fields http://www.alexweber.com.br/en/articles/how-manually-add-entity-field-forms-custom-drupal-form and to Bryan Jones for his Multi-step form tutorial http://bryanjones.us/article/custom-multi-step-forms-drupal-7


Multi Level Marketing SQL Query to calculate turnover of the team

Question: I have a users table that looks someting like this :
ID NAME
1  Robin
2  Edward
3  Donald
4  Julie

The 2nd table user_tree
ID USER_ID TREE
1  1       ["2","3","4"]
2  2       ["3","4"]
3  3       ["4"]
4  4       []

The 3rd table orders
ID AMOUNT USER_ID
1  150    2
2  300    3
3  200    4
4  500    3

the expected result, get the following table (create table mlm_team as select..) with a SQL query
ID USER_ID TEAM_SUM
1  1       1150
2  2       1000
3  3       200

Is there an SQL expert who can help me?
Comment: What is the datatype of TREE? JSON?
Comment: How are you calculating the team sum in your expected result?
Comment: What kind of SQL have you tried, please?
Comment: TREE longtext
MySQL 5.7.9
Answer: Follow below step:
- Create table and insert record.
- Get JSON type for array value
- Use "JSON_CONTAINS" for find MLM chain

Explain here:
create table users(id int, name varchar(50));
create table user_tree(id int, user_id int, tree json );
create table orders(id int, amount int, user_id int);

insert into users values(1,  'Robin');
insert into users values(2,  'Edward');
insert into users values(3 , 'Donald');
insert into users values(4 , 'Julie');

select * from users;

insert into user_tree values(1,  1 ,      '["2","3","4"]');
insert into user_tree values(2 , 2  ,     '["3","4"]');
insert into user_tree values(3 , 3  ,     '["4"]');
insert into user_tree values(4 , 4  ,     '[]');

select * from user_tree;

 insert into orders values(1 , 150  ,  2);
    insert into orders values(2 , 300  ,  3);
    insert into orders values(3 , 200  ,  4);
    insert into orders values(4 , 500 ,   3);

 select * from orders;

- Final Query here:
SELECT u1.id, u1.user_id as user_id, sum(amount)
FROM user_tree u1
left outer join user_tree u2 on JSON_CONTAINS(u1.tree, concat('["', u2.user_id ,'"]'))
left outer join orders o1 on o1.user_id = u2.user_id
where u2.user_id
group by u1.id, u1.user_id
order by u1.id;

Find SQL Fiddle details from here LINK.


Cross Domain Authentication with ADFS (no domain trust)

Question: Yesterday I was asked whether it is possible to establish a cross domain authentication with ADFS.
Scenario:

Two different Windows Domains (A & B) without any trust configuration
Network access between Domains is established with IPSec Site2Site (all ports needs to be opened separately)
One specific Windows Service on a server in Domain A has to use an AD Account from Domain B for logon (Windows Service -> Logon -> This Account -> Account from Domain B)

Our partner doesn´t want to establish a domain trust due to security reasons and is therefore asking if we could realize this authentication process through ADFS?
ADFS is quite new to me and I'm not sure if this scenario is even possible with ADFS?
Comment: Can you do this with ADFS? Not likely. You don't specify what kind of service you need to access, but by the sound of it ADFS is not a solution.
Answer: This is not possible without a domain trust.

ADFS allows applications to authenticate against AD (or another Identity Provider) without direct access to it; but the applications must explicitly support this authentication method.
Windows logon doesn't.
In order to log on to a Windows system, you need to either:

Log in using a local user account
Log in using a user account in the domain the system is joined to
Log in using a user account in a trusted domain
Answer: To add to @Massimo answer, if you could change the Windows service to use OpenID Connect with the client credentials flow(i.e. a service not a user so no explicit logon), then this would work.
The other option is for the service to use the old-school WS-Trust i.e. WCF.
Both of these are supported by ADFS.